content stringlengths 5 1.05M |
|---|
# -*- coding: utf-8 -*-
"""
sogou (Videos)
@website https://v.sogou.com
@provide-api no
@using-api no
@results HTML
@stable no
@parse url, title, content, thumbnail
"""
from lxml.html.soupparser import fromstring
from searx.url_utils import urlencode
categories = ['videos']
paging = Tru... |
from io import BytesIO
import random
import tempfile
import pytest
from pybloom2.pybloom import BloomFilter, ScalableBloomFilter
TEST_SIZE = 12345
@pytest.mark.parametrize("file_class", [
tempfile.TemporaryFile,
BytesIO,
])
@pytest.mark.parametrize("filter_class,args", [
(BloomFilter, (TEST_SIZE,)),
... |
import time
import pyaudio
import wave
import sys
import os
from google_speech import Speech
class Call_APP():
def __init__(self, package_name):
self.chunk = 1024
result = self.find_name(package_name)
print(package_name, result)
if result == None:
sys.exit(0)
sel... |
# Copyright 2015 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... |
# Integer silently converts to float then taken an action with another float
print(3 / 4)
print(9.87654000)
print(8 / 2)
print(6 * 7.0)
print(4 + 1.65)
|
#!/bin/env python
"""
Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License").
You may not use this file except in compliance with the License.
A copy of the License is located at
http://www.apache.org/licenses/LICENSE-2.... |
import cape_privacy as cape
from cape_privacy.spark import dtypes
from cape_privacy.spark.transformations import ColumnRedact
from cape_privacy.spark.transformations import DatePerturbation
from cape_privacy.spark.transformations import NumericPerturbation
from cape_privacy.spark.transformations import NumericRounding
... |
from ctypes import windll, c_void_p, POINTER, c_size_t, Structure, c_uint64, c_uint32, sizeof, c_wchar, c_wchar_p, byref
from ctypes.wintypes import DWORD
from pprint import pprint
from inc.errors import GWErrors
from inc.system_info import GWSystemInfo
class MEMORY_BASIC_INFORMATION(Structure):
"""https://msdn... |
"""Custom pyplot style and palette."""
import matplotlib.pyplot as plt
import seaborn as sns
plt.rcParams.update(
{
"figure.dpi": 120,
"savefig.dpi": 300,
"figure.figsize": (7, 4.33),
"lines.linewidth": 2,
"axes.spines.bottom": False,
"axes.spines.top": False,
... |
def vsota_diagonal_spirale_nxn(n):
najvecje = n * n
element = 1
vsota = 1
korak = 0
while element != najvecje:
korak += 2
for x in range(4):
element += korak
vsota += element
return vsota
|
antimony = '''
model myModel
S1 -> S2; k1*S1
S1 = 10; S2 = 0
k1 = 1
end
'''
phrasedml = '''
model1 = model "myModel"
sim1 = simulate uniform(0, 5, 100)
task1 = run sim1 on model1
plot "Figure 1" time vs S1, S2
'''
import tellurium as te
exp = te.experiment(antimony, phrasedml)
exp.execute()
exp.printp... |
from django.apps import AppConfig
class EventTypeConfig(AppConfig):
name = 'event_type'
|
from distutils.core import setup
import py2exe
import sys
# This is a standalone script, let it fill in the parameters.
if len(sys.argv) == 1:
sys.argv.append("py2exe")
setup(
name = "pop",
description = "The pop compiler.",
version = "0.1.1",
zipfile = None,
options = {
"py2exe": {
... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import unicode_literals
import os
from setuptools import setup, find_packages
try:
with open('Readme.md') as f:
readme = f.read()
except IOError:
readme = ''
def _requires_from_file(filename):
return open(filename).re... |
import open3d as o3d
import torch
import torch.nn as nn
import torch.nn.functional as F
from skimage.measure import marching_cubes_lewiner
import numpy as np
import trimesh
import proxy_models_im as proxy_models
import pc_encoder_im as pc_encoder
import tqdm
import os
import shutil
import matplotlib.pyplot as plt... |
from dagster_graphql import dauphin
from dagster import check
from dagster.core.snap import PipelineSnapshot
from dagster.core.types.dagster_type import DagsterTypeKind
from .config_types import DauphinConfigType, to_dauphin_config_type
def config_type_for_schema(pipeline_snapshot, schema_key):
return (
... |
import datetime
from .TwitterSearchException import TwitterSearchException
from .utils import py3k
try: from urllib.parse import parse_qs, quote_plus, unquote # python3
except ImportError: from urlparse import parse_qs; from urllib import quote_plus, unquote #python2
class TwitterSearchOrder(object):
"""
This... |
# /usr/bin/env python3.5
# -*- mode: python -*-
# =============================================================================
# @@-COPYRIGHT-START-@@
#
# Copyright (c) 2020, Qualcomm Innovation Center, Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification,... |
import datetime
from decimal import Decimal
from testil import eq
from dateutil.tz import tzoffset, tzlocal
from openpyxl.styles import numbers
from corehq.apps.export.const import MISSING_VALUE, EMPTY_VALUE
from couchexport.util import get_excel_format_value
def check(input, output, format, output_type):
exce... |
# -*- coding: utf-8 -*-
"""
Scrape Website Data | Cannlytics
Copyright © 2021 Cannlytics
Author: Keegan Skeate <keegan@cannlytics.com>
Created: 1/10/2021
License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANT... |
#!/usr/bin/env python3
import ffai.core.model as m
import ffai.core.table as t
import ffai.core.procedure as p
import ffai.ai.pathfinding as pf
import ffai.ai.proc_bot as pb
from typing import Optional, List, Dict
import ffai.core.game as g
from ffai.ai.registry import register_bot
import numpy as np
class ActionSequ... |
import os
from codenode.frontend._settings import *
HOME_PATH = os.path.join(PROJECT_PATH, '..', '..', 'devel', 'env')
DATABASE_ENGINE = 'sqlite3'
DATABASE_NAME = os.path.join(HOME_PATH, 'codenode.db') # Or path to database file if using sqlite3.
DATABASE_USER = '' # Not used with sqlite3.
DAT... |
from flask import Flask
import subprocess as sp
import os
app = Flask(__name__)
@app.route("/on-push", methods=['POST'])
def on_push():
command = os.environ.get('PUSH_COMMAND', False)
if command:
try:
sp.Popen(command, shell=True, executable='/bin/bash')
return ''
except... |
#!/usr/bin/env python
# -*- coding: utf8 -*-
import sys
import os
from xml.etree import ElementTree
from xml.etree.ElementTree import Element, SubElement
from lxml import etree
import codecs
from libs.constants import DEFAULT_ENCODING
TXT_EXT = '.txt'
ENCODE_METHOD = DEFAULT_ENCODING
class YOLOWriter:
def __init... |
import os
total_chars = 0
total_files = 0
for root, dirs, files in os.walk(os.path.abspath(""), topdown=False):
for name in files:
file_name = os.path.join(root, name)
if not (('.git' in file_name) or ('pycache' in file_name) or ('pyc' in file_name)):
try:
with open(fil... |
# Copyright 2013 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... |
#!/usr/bin/env python
# encoding: utf-8
"""
Drive the Robot
"""
import sched, time
import signal, sys
import time
import requests
from urllib.request import urlopen
from enum import Enum
import constants
from arduino import Arduino
from navigation import Navigation
class State(Enum):
COLLECT_spin_and_search_cone =... |
import torch
def onehot(y, num_classes):
y_onehot = torch.zeros(y.size(0), num_classes).to(y.device)
if len(y.size()) == 1:
y_onehot = y_onehot.scatter_(1, y.unsqueeze(-1), 1)
elif len(y.size()) == 2:
y_onehot = y_onehot.scatter_(1, y, 1)
else:
raise ValueError("[onehot]: y sho... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('donations', '0003_goal'),
]
operations = [
migrations.AddField(
model_name='goal',
name='source_type... |
# from .resnet import (
# ResNet,
# ResNet18,
# ResNet34,
# ResNet50,
# ResNet101,
# ResNet152,
# ResNet200,
# )
# __all__ = [
# "ResNet",
# "ResNet18",
# "ResNet34",
# "ResNet50",
# "ResNet101",
# "ResNet152",
# "ResNet200",
# ]
|
#!/usr/bin/env python
#@# vim: set filetype=python:
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), "./lib"))
import similar_image_search as SimilarImageSearch
# NOTE: This is a test query using a '4.png' in 'database_example.json'
test_query = {
"ahash": "82b00fef8410041f8006f43f80008... |
import os
from pathlib import Path
import gensim.downloader as api
from gensim.models import Word2Vec
import spacy
from yasmin.constants import SPACY_MODEL_NAME
from yasmin.core import WSD
from yasmin.helpers import custom_tokenizer, hash_types, make_type_matrix
model_path = str(Path(__file__).parents[1] /
... |
from visions.typesets.complete_set import CompleteSet
from visions.typesets.geometry_set import GeometrySet
from visions.typesets.standard_set import StandardSet
from visions.typesets.typeset import VisionsTypeset
__all__ = ["VisionsTypeset", "CompleteSet", "StandardSet", "GeometrySet"]
|
from django.apps import AppConfig
class GestionpedidosConfig(AppConfig):
name = 'gestionpedidos'
|
import pytest
import elaspic2_rest_api
@pytest.mark.parametrize("attribute", ["__version__"])
def test_attribute(attribute):
assert getattr(elaspic2_rest_api, attribute)
def test_main():
import elaspic2_rest_api
assert elaspic2_rest_api
|
# -*- coding: UTF-8 -*-
import requests
from bs4 import BeautifulSoup
from collections import defaultdict
occurrences = defaultdict(int)
__author__ = 'Webdeziner.se'
searchUrl = raw_input('Which url to scan: ');
def make_soup(url):
response = requests.get(url)
return BeautifulSoup(response.content, 'lxml')
... |
""" Get information related to instrument such as performance """
# Copyright (c) 2018-present, Taatu Ltd.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import sys
import os
import datetime
from datetime import timedelta
import pymysql.curs... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 8 21:45:27 2018
@author: pilla
"""
|
from flask import request
class HTTPError(Exception):
status_code = 400
code = NotImplemented
message = None
def __init__(self, code=None, status_code=None, payload=None):
Exception.__init__(self)
if code is not None:
if self.code is NotImplemented:
self.co... |
__version__ = "0.0.1"
from .block import Block
from .service import SVCObj, SVC
|
"""
James Park, laplacian.k@gmail.com
seoulai.com
2018
"""
import seoulai_gym as gym
import numpy as np
from seoulai_gym.envs.market.agents import Agent
from seoulai_gym.envs.market.base import Constants
from itertools import count
class RandomAgent(Agent):
def algo(
self,
state,
):
... |
#1) seqmut-1-1: Which of these is a correct reference diagram following the execution of the following code?
#A. I.
#2) seqmut-1-4: What will be the value of a after the following code has executed?
#a = ["holiday", "celebrate!"]
#quiet = a
#quiet.append("company")
#["holiday", "celebrate!", "company"]
#3) seqmut-1-5... |
#TODO
import numpy as np
import pywt
from pywt import wavedec
import matplotlib
from matplotlib import pyplot as plt
from skimage.restoration import (denoise_wavelet, estimate_sigma)
from skimage import data, img_as_float
from skimage.util import random_noise
from skimage.measure import compare_psnr
def decomp_vi... |
# third party lib
from flask import jsonify, make_response
import requests
import time, pdb
# internal lib
from lib.settings import ServerHTTP
from lib.client_registry import Registry
from client.routes.dispatcher import dispatcher
def create_response(code, msg=None):
"""
Convenience method for flask.make_re... |
from PIL import Image
import numpy
class PIC(object):
def __init__(self,fileN):
#initializes
self.fileN=fileN
self.pic=Image.open(fileN)
self.colors=numpy.array(self.pic)
self.ogColors=numpy.array(self.pic)
def ultra(self):
#makes the largest color the only colo... |
"""
TCKDB backend app tests models test_freq module
"""
from tckdb.backend.app.models.freq import Freq
def test_freq_model():
"""Test creating an instance of Freq"""
freq1 = Freq(factor=0.99 * 1.014,
source='J.A. Montgomery, M.J. Frisch, J. Chem. Phys. 1999, 110, 2822–2827, DOI: 10.1063/1.47... |
import os
from flask import Flask
# 实例化app,参数如下:
# import_name,
# static_url_path=None,
# static_folder="static",
# static_host=None,
# host_matching=False,
# subdomain_matching=False,
# template_folder="templates",
# instance_path=None,
# instance_relative_config=False,
# root_path=None,
BASE_DIR = os.getcwd()
root_f... |
from transformer.harvardnlp_transformer import *
def data_gen(V, batch, nbatches, max_words_in_sentence):
"""
Generate random data for a src-tgt copy task.
# 5: # of sentences per batch == batch(2nd arg)
# 4: # of words in each sentence
# 7: size of word dictionary
np.random.randint(low=1, hi... |
from pathlib import Path
import pybullet as p
ASSETS_PATH = Path(__file__).resolve().parent / 'assets'
class EndEffector:
"""
A base class for UR5 end effectors.
"""
def __init__(self, urdf_path, load_position, load_orientation, ur5_install_joints, ee_tip_idx):
"""
The initialization... |
import numpy as np
import tensorflow as tf
import roi_pooling_layer.roi_pooling_op as roi_pool_op
import roi_pooling_layer.roi_pooling_op_grad
from rpn_msr.proposal_layer_tf import proposal_layer as proposal_layer_py
from rpn_msr.anchor_target_layer_tf import anchor_target_layer as anchor_target_layer_py
from rpn_msr.p... |
import math
from cvat.apps.engine.ddln.geometry import Line, Point, PolarPoint, get_angle_between
from ..models import Runway
def iterate_runways(reader, reporter):
for row in reader._reader:
runway_id, *lines_data = row
if len(lines_data) != 12: # 6 lines, each line is represented by 2 values
... |
from ipywidgets import Box, Layout
class MenpoWidget(Box):
r"""
Base class for defining a Menpo widget.
The widget has a `selected_values` trait that can be used in order to
inspect any changes that occur to its children. It also has functionality
for adding, removing, replacing or calling the ha... |
r"""
Neighbor Lookups
================
"""
import numpy as np
from openpnm.utils import logging
logger = logging.getLogger(__name__)
__all__ = ['from_neighbor_throats', 'from_neighbor_pores']
def from_neighbor_throats(target, prop, mode='min', ignore_nans=True):
r"""
Adopt a value from the values found in ... |
class Solution:
def repeatedNTimes(self, nums: List[int]) -> int:
hash_map = set()
for num in nums:
if num not in hash_map:
hash_map.add(num)
else:
return num |
#!/usr/bin/env python
import sys
from setuptools import setup
import os
os.environ['COPY_EXTENDED_ATTRIBUTES_DISABLE'] = 'true'
os.environ['COPYFILE_DISABLE'] = 'true'
version = "1.0.8"
config = dict(
name = 'pydot3',
packages = ['pydot'],
version = version,
description = 'Python 3 interface to Gra... |
from pathlib import Path
from fhir.resources.valueset import ValueSet as _ValueSet
from oops_fhir.utils import ValueSet
from oops_fhir.r4.code_system.v3_processing_id import v3ProcessingID as v3ProcessingID_
__all__ = ["v3ProcessingID"]
_resource = _ValueSet.parse_file(Path(__file__).with_suffix(".json"))
clas... |
import numpy as np
import matplotlib.pyplot as plt
import os
from scipy.special import erf
###########################################
# load neutrino spectra
###########################################
PATH_abs = os.path.dirname(os.path.abspath(__file__))
flist_neuflux = [
PATH_abs + "/Background_inputs/NeutrinoF... |
'''
运行时的变量将暂存于此
'''
#告诉整个程序下载是否停止
Down_Satuation = False
#文件夹池
DirPool = {}
#文件池
FilePool = {}
#已经浏览过的文件夹的数量
seen_dir_count = 0
#正在浏览的文件夹数量
seeing_dir_count = 0
#已找到的文件夹数量
Dir_count = 0
#已找到的文件的数量
File_count = 0
#已处理的文件数量
seeing_file_count = 0
#RPC返回文本, 使用时需先转为str在把" ' "replace为" " "
RPC_satuation =... |
class TaskInstanceConfig(object):
def __init__(self, task_config):
self.cpu = task_config.cpu
self.memory = task_config.memory
self.disk = task_config.disk
self.gpu = task_config.gpu
self.gpu_memory = task_config.gpu_memory
self.duration = task_config.duration
... |
from flask_restful import Resource
from flask import jsonify
from injector import inject
from backend_application.service import ProjectService
class ProjectList(Resource):
@inject
def __init__(self, project_service: ProjectService):
self.project_service = project_service
""" returns list of pro... |
from openpyxl import load_workbook
filename = 'aalh_iit_buildings_011.xlsx'
wb = load_workbook(filename)
ws = wb['Metadata Template']
minimumcol = 2
maximumcol = 2
minimumrow = 7
maximumrow = 1343
iterationrow = 7
titlecol = 2
covcol = 10
for row in ws.iter_rows(min_row=minimumrow, min_col=minimumcol... |
#! /usr/bin/env python
from rakali import VideoPlayer, VideoStream
stream = VideoStream(src=5)
player = VideoPlayer(stream=stream)
with player:
player.autoplay()
|
print('''
::
:;J7, :, ::;7:
,ivYi, , ;LLLFS:
:iv7Yi :7ri;j5PL
,:ivYLvr ,ivrrirrY2X,
:;r@Wwz.7r: ... |
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
#replace can be mm and none. mm= mode for categoric features and median for numeric features
#n_r= null ratio , s_r=skewness ratio , c_r=correalation ratio , n_f=number of features ,t_s= test size, n= remove out... |
###################################################
# FILE: Weather.py #
# AUTHOR: NotPike #
# Function: OWM API caller, voice to read weather #
# https://openweathermap.org/ #
###################################################
import ... |
"""
"""
import attr
import pymunk
from pymunk.vec2d import Vec2d
#
from pyglet_pymunk.breakout_game.components.collision_types import CollisionType
@attr.s
class GroovJoint:
groove_a: Vec2d = attr.ib()
groove_b: Vec2d = attr.ib()
anchor: Vec2d = attr.ib(default=Vec2d())
class Paddle(pymunk.Body):
"... |
import os
from stackstrap.config import settings
from stackstrap.commands import Command
from stackstrap.template import Template, MASTER_TEMPLATE_URL
class Create(Command):
"Create a new template"
name = 'create'
def setup_parser(self, parser):
self.parser = parser
template_url = settin... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import time
import os
class ToolService:
def __init__(self):
pass
def prt_content(self, content):
flags = '*' * 30
print(f"{flags}{content}{flags}")
def gen_list(self, data):
return data.strip().split('\n')
def get_t... |
import numpy as np
def rot_matrix_align(final, origin=(0,0,1)):
origin = np.array(origin)/np.linalg.norm(np.array(origin))
final = np.array(final)/np.linalg.norm(np.array(final))
v = np.cross(origin, final)
mat_v = np.array([[0, -v[2], v[1]],
[v[2], 0, -v[0]],
... |
import tensorflow as tf
import tensorflow.contrib.layers as tfc_layers
def compute_q_att(context, keep_dropout, no_glimpse=2, glimpse_embedding_size=300, reuse=False):
with tf.variable_scope("glimpse"):
glimpses = []
with tf.variable_scope("glimpse"):
g_feature_maps = tf.nn.dropout(co... |
#!/usr/bin/env python
import argparse
import time
import os
import sys
# readline has a desired side effect on keyword input of enabling history
import readline
from lndmanage.lib.node import LndNode
from lndmanage.lib.listchannels import ListChannels
from lndmanage.lib.rebalance import Rebalancer
from lndmanage.lib.r... |
#Learning How to use GUI
#You're supposed to import tk
import tkinter as tk
#Creates a Window
window = tk.Tk()
#Sets The size of the Window
window.geometry("500x500")
#Sets the Icon of the window
window.wm_iconbitmap('favicon.ico')
#Sets the title of the window
#window.title("Scummy Hero Super Mario 64")
#Stores ... |
import torch
import torch.nn as nn
class Config:
"""
Configuration for MTCNN.
"""
def __init__(self):
self.kernel1 = 3
self.kernel2 = 4
self.kernel3 = 5
self.n_filters1 = 100
self.n_filters2 = 100
self.n_filters3 = 100
self.dropout1 = 0.5
... |
import io
import asyncio
from chickensmoothie import image
loop = asyncio.get_event_loop()
class TestClass:
def test_invalid_link(self):
data = loop.run_until_complete(image('https://www.chickensmoothie.com/viewpet.php'))
assert data is None
def test_valid_link(self):
data = loop.r... |
import requests
zhuanlanHost = "https://news-at.zhihu.com/api/4/news/latest"
githuburl = 'https://github.com/Peefy/WebMagicSharp/tree/master/WebMagicSharp'
r = requests.get(githuburl)
print(r.text)
r = requests.get(zhuanlanHost)
print(r.text)
|
"""Template jinja tests."""
def is_subset_of(value, subset):
"""Check if a variable is a subset."""
return set(value) >= set(subset)
def is_superset_of(value, superset):
"""Check if a variable is a superset."""
return set(value) <= set(superset)
def create_builtin_tests():
"""Tests standard for t... |
from .worker_manager import WorkerManager
worker_manager = WorkerManager()
|
from posixpath import split
from graphviz import Digraph
import glob, re
pattern = re.compile("Eth [0123]/[0123]")
device_cdp_neighbors = []
for file_name in glob.glob("/home/maciej/repo/networking/ansible/cdp_example_output/*"):
path_length = len(file_name.split("/"))
device = file_name.split("/")[path_leng... |
'''Faça um programa que calcule a soma entre todos os números ímpares que são múltiplos de três
e que se encontram no intervalo de 1 até 500.'''
soma = 0
for c in range(1, 501, 2):
if c % 3 == 0:
soma = soma + c
print(c, end=' ')
print('\nA soma dos números acima é {} '.format(soma))
|
conjunto1 = {1, 3, 7, 0, 5}
print(conjunto1, type(conjunto1))
conjunto2 = {1, 1, 2, 2, 2}
print(conjunto2)
conjunto1.add(4)
print(conjunto1)
conjunto1.discard(1)
print(conjunto1)
conjunto1 = {1, 3, 7, 0, 5}
conjunto2 = {1, 1, 2, 2, 2}
uniao = conjunto1.union(conjunto2)
print(1, uniao)
intercecao = conjunto1.intersectio... |
# Copyright 2022 Thomas Woodruff
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agr... |
#!/usr/local/bin/python
from __future__ import print_function
import sys
from st2common.runners.base_action import Action
def get_version_string(major=False, minor=False, micro=False):
"""
Return all or part of the Python version string.
If all parameters are False-y, returns the entire, unmangled Pyt... |
import unittest
from datetime import datetime
import ipywidgets as widgets
import numpy as np
from dateutil.tz import tzlocal
from ndx_grayscalevolume import GrayscaleVolume
from nwbwidgets.ophys import show_grayscale_volume, TwoPhotonSeriesWidget, show_df_over_f
from nwbwidgets.view import default_neurodata_vis_spec
... |
#!/usr/bin/env python
#
# -------------------------------------------------------------------------
# Copyright (c) 2018 Intel Corporation Intellectual Property
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain... |
"""add_collection_id_2
Revision ID: 413c84a833f5
Revises: bdfc23d8334c
Create Date: 2020-01-13 13:59:44.130399
"""
from alembic import op
# revision identifiers, used by Alembic.
revision = '413c84a833f5'
down_revision = 'bdfc23d8334c'
branch_labels = None
depends_on = None
def upgrade():
conn = op.get_bind()
... |
#! /usr/bin/env python
# coding:utf8
from .test import *
from .market import *
urls_bp = [
(TestView.as_view(), "test/"),
(MarketPriceView.as_view(), "api/market/price/"),
]
|
for a in range(1,10):
for b in range(1,10):
print '{}, {}'.format(a,b)
|
#!/usr/bin/env python3
import rospy
from std_msgs.msg import String
import requests
key = "トークン"
def callback(msg):
rospy.loginfo("Received a string")
print(msg)
message = msg.data
tweetdata = "_t=%s&msg=%s" % (key,message)
response = requests.post('http://stewgate-u.appspot.com/api/post/', da... |
import math
import config
def get_map_center():
"""Returns center of the map"""
lat = (config.MAP_END[0] + config.MAP_START[0]) / 2
lon = (config.MAP_END[1] + config.MAP_START[1]) / 2
return lat, lon
def get_start_coords(worker_no):
"""Returns center of square for given worker"""
grid = con... |
""" Prepare air quality and data for single city """
import os
import numpy as np
import pandas as pd
def assign_class(df, col, threshs):
df['class'] = np.zeros(len(df))
for i, thresh in enumerate(threshs):
high = (df[col] >= thresh)
df['class'].loc[high] = i + 1
return df
def lag(df, c... |
def show_description(path):
if 'Simulation_1' in path:
print('Simulation_1: Straight line drive on a wavey 2D surface')
if 'Simulation_2' in path:
print('Simulation_2: Left turn drive on a wavey 2D surface')
if 'Simulation_3' in path:
print('Simulation_3: Straight line drive on a... |
#!/usr/bin/python
import os, sys
from fps import py2cpp
def main() :
t1 = py2cpp .Type( 'uint64_t' )
t2 = py2cpp .Type( 'std::string' )
t3 = py2cpp .Type( 'std::map<std::string, std::vector<std::string>>' )
td1 = py2cpp .Typedef( t1, 'my_uint64_t' )
td2 = py2cpp .Typedef( t2, 'my_string_t' )
... |
import pybamm
import numpy as np
import pandas as pd
import os
import sys
import unittest
import uuid
class TestSimulation(unittest.TestCase):
def test_simple_model(self):
model = pybamm.BaseModel()
v = pybamm.Variable("v")
a = pybamm.Parameter("a")
model.rhs = {v: -a * v}
... |
import numpy as np
import cv2
import time
print("""
BE PREPARE YOU WILL BE INVISIBLE SOON............
""")
if __name__ == '__main__':
cap = cv2.VideoCapture(0)
#For capturing output video
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('invisibleYou.avi' , fourcc, 20.0, (6... |
from test_DBSCAN import *
|
name = input("Enter your name: ")
age = input("Enter your age: ")
print("Hello " + name + " ! Your are " + age + " Years old now.")
num1 = input("Enter a number: ")
num2 = input("Enter another number: ")
result = num1 + num2
print(result)
# We need int casting number num1 and num2
result = int(num1) + int(num2)
print(... |
from HABApp.openhab.items import StringItem, GroupItem
from HABAppTests import TestBaseRule, OpenhabTmpItem
class OpenhabItems(TestBaseRule):
def __init__(self):
super().__init__()
self.add_test('ApiDoc', self.test_api)
self.add_test('MemberTags', self.test_tags)
self.add_test('M... |
x=set('')
for i in range(int(input())):
x.add(input())
print(len(x)) |
from typing import Set, List
from rlbot.utils.structures.game_data_struct import GameTickPacket
from choreography.drone import Drone
class Choreography:
def __init__(self):
self.sequence = []
self.sequence_index = 0
self.finished = False
def step(self, packet: GameTickPacket, drone... |
# -*- coding: utf-8 -*-
from gitlint.tests.base import BaseTestCase
from gitlint.rules import RuleViolation
from gitlint.contrib.rules.signedoff_by import SignedOffBy
from gitlint.config import LintConfig
class ContribSignedOffByTests(BaseTestCase):
def test_enable(self):
# Test that rule can be enable... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.