lang stringclasses 10
values | seed stringlengths 5 2.12k |
|---|---|
python | REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 10,
}
|
python | url="https://github.com/th-os/iotfs",
packages=setuptools.find_packages(),
platforms=['Linux'],
classifiers=[
"Programming Language :: Python :: 3", |
python | import jsonschema
import json
with open('court-schema.json', 'r') as schema_file:
schema = json.loads(schema_file.read())
with open('sample_court.json', 'r') as court_file:
court = json.loads(court_file.read())
print not jsonschema.validate(court, schema)
|
python |
def get_url(self, host, media_id):
return 'http://videomega.tv/cdn.php?ref=%s' % media_id
def get_host_and_id(self, url):
r = re.search(self.pattern, url)
if r: |
python | ('password', '0015_auto_20170312_1817'),
]
operations = [
migrations.AddField(
model_name='vault', |
python | d['subject'] = subjects
d['outcome'] = outcomes
d['preds'] = preds
for f_id in range(0, num_top_features):
feat = features_best[f_id]
curr_beta = betas[:, order[f_id]]
curr_shap = shap_values[:, order[f_id]]
... |
python | # cms geometry
# tracker geometry
# tracker numbering
# KFUpdatoerESProducer |
python | source_type="git",
source_url="https://foo.bar",
source_reference="master",
)
assert a1 == a1 |
python | return download_directory
def remove_remix(string_with_remix):
string_with_remix = string_with_remix.lower()
if 'remix' in string_with_remix:
string_with_remix = string_with_remix.replace('remix', '')
return string_with_remix
|
python |
def connection_info(self):
if self.srv:
return self.srv.client_info()
#
# simpleJSON Reader
#
def readConfig(self):
data = json.load(open('config.json')) |
python | self.cache = {}
def __call__(self, f):
def decorated_function(*args):
try:
return self.cache[self.tag]
except KeyError:
val = f(*args)
self.cache[self.tag] = val
return val
return decorated_function
|
python |
class DeviceTokenAdmin(admin.ModelAdmin):
list_display = ('id', 'device_token', 'uuid', 'user')
list_display_links = ('id', 'device_token', 'uuid', 'user')
admin.site.register(DeviceToken, DeviceTokenAdmin)
class CertFileAdmin(admin.ModelAdmin):
readonly_fields = ('filename', 'target_mode', 'is_use', '... |
python | """
eg. a picture, html doc, ...
"""
_SCHEMATEXT = """
@url = jumpscale.docs.docsite.1
name** = ""
path = ""
state** = "image,html,css" (E)
extension** = ""
|
python | MINER_FUND_RATIO = 8
MINER_FUND_ADDR = 'bchreg:pqnqv9lt7e5vjyp0w88zf2af0l92l8rxdgd35g0pkl'
class MinerFundTest(BitcoinTestFramework):
def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 1
self.extra_args = [[
'-enableminerfund',
'-allownonstdt... |
python | def _calculate_f1_acc(true_positive, false_positive, false_negative, true_negative):
if true_positive <= 0:
return 0.0, 0.0, 0.0, 0.0
precision = float(true_positive) / (true_positive + false_positive)
recall = float(true_positive) / (true_positive + false_negative)
f_1 ... |
python | if type(None) in get_args(fld.type):
# skip optional arguments
continue
elif isclass(fld.type) and issubclass(fld.type, Header):
attr_items[fld.name] = fld.type.empty()
elif get_origin(fld.type) is Union and issubclass(get_args(fld.type... |
python | pool.also_notifies = mock.MagicMock()
pool.also_notifies.__iter__.return_value = [
mock.Mock(host='192.168.1.1', port=53),
]
self.service.get_pool.return_value = pool
|
python | import uvloop
except ImportError:
pass
else:
uvloop.install() |
python | def __cmp__(self, other):
return cmp(self.foo, other.foo)
class AnotherComparable(object):
def __init__(self, baz='qux'):
self.baz = baz
def __hash__(self):
return hash(self.baz) |
python | from ..models import Post
register = template.Library()
@register.simple_tag(name='total_posts')
def total_posts():
return Post.published.count()
@register.inclusion_tag('blog/partials/latest_posts.html')
def show_latest_posts(count=3): |
python | fields = ('id', 'name', 'owner', 'opsim_run', 'maf_comment', 'created_at', 'plots', )
class MetricUploadSerializer(serializers.Serializer):
key = serializers.CharField()
data = MetricSerializer()
|
python |
from SCons.Options import PackageOption
opts = Options(args=ARGUMENTS)
opts.AddOptions(
PackageOption('x11',
'use X11 installed here (yes = search some places', |
python | text = event.get("text")
if text and text.lower() == "start":
return start_onboarding(user_id, channel_id, client)
|
python | if f.endswith('.conf'):
fpath = os.path.join(root, f)
try:
with open(fpath, 'r') as fh:
config = yaml.safe_load(fh)
if config.get('trubblestack', {}).get('returner', {}).get('splunk'):
... |
python | import os
username = os.environ.get('USERNAME', 'hoangan2030')
password = os.environ.get('PASSWORD', '<PASSWORD>')
|
python | "eu-west-2" : "894491911112",
"eu-west-3" : "807237891255",
"eu-south-1": "488287956546",
"eu-central-1" : "024640144536",
"ca-central-1" : "557239378090",
"af-south-1" : "143210264188",
"sa-east-1" : "424196993095",
"me-sou... |
python | from pywps import Service
from pywps.tests import assert_response_success
from .common import get_output, client_for, CFG_FILE
from emu.processes.wps_multiple_outputs import MultipleOutputs
@pytest.fixture
def resp():
client = client_for(Service(processes=[MultipleOutputs()], cfgfiles=CFG_FILE))
datainputs =... |
python | if n <= 1:
return 1
else:
return n * factorial(n - 1)
def main():
if len(sys.argv) != 2:
print('ERROR: One argument is required.')
print('Usage:')
print('\tpython factorial.py <n>') |
python | # print >> f, 'Portion wrong image: ', portion_wrong
# The image generator has some memory issues
gc.collect() |
python | sources.register(r'sources', views.FeedSourceViewset)
summary = SimpleRouter()
summary.register(r'summary', views.FeedViewset)
urlpatterns = [ |
python | import flwr as fl
import sys
# Start Flower server for three rounds of federated learning
if __name__ == "__main__":
fl.server.start_server("0.0.0.0:8080", config={"num_rounds": 10}) |
python | return ret
def convert_to_idx(self, labels, unk=None, bos=None, eos=None, _type=torch.LongTensor):
vec = []
|
python | roman = {1:'I', 2:'II', 3:'III'}
newRoman = roman.copy()
del roman[1]
print(roman)
print(newRoman) |
python | subsections = []
try:
subsections = list(tex_node.subsections)
subsections = [i.string for i in subsections]
except:
pass
return subsections
|
python | conn.send(data)
conn.close()
else:
if(os.path.isfile(request)): |
python | point statistics.
"""
def autocorrelate(X, basis, periodic_axes=[], n_jobs=1, confidence_index=None,
autocorrelations=None):
""" |
python | type='presence'
)
def returned_home_cb(self, entity, attribute, old, new, kwargs):
trigger_type = kwargs['type']
|
python | data_number = 0
cant = (min(max_number + 1, pieces_per_player) // 2)
hand = [(data_number, i) for i in sample(list(range(max_number + 1)), cant)]
if not (0, 0) in hand:
hand.pop()
hand.append((0, 0))
pieces = [(i, j) for i in range(max_number + 1) for j in range(max_number + 1)... |
python |
# check if gateway exsits
"""
gw_id = "38e998af01b5c8d8287a817211e5e52fb23a3e3bb031c0c1437746d9e148bd17"
if(not col.count_documents({"uuid": gw_id})):
print("# Invalid registration request!\n## Received gateway ID doest not exists in local database!")
# self.write("....")
#return
print("Gateway ID valid ... |
python |
Args:
other (Params): P2 part
Returns:
bool: Return true if NOT equal. Otherwise false
"""
len1 = len(self.data)
len2 = len(self.data)
if len1 != len2:
return True
else:
for item in self.data: |
python | def get_extras():
"""Extra pybm functionality, specified as a valid argument to
setuptools.setup's 'extras_require' keyword argument."""
extra_features = {
"gbm": ["google_benchmark @ git+https://github.com/google/benchmark"]
}
extra_features["all"] = sum(extra_features.values(), []) |
python | # get rl_state
self.p.rl_state[self.p.deta_x_index] = abs(self.a.state[0, -1] - self.w.goal[0, -1])
self.p.rl_state[self.p.deta_y_index] = abs(self.a.state[1, -1] - self.w.goal[1, -1])
self.p.rl_state[self.p.v_x_index] = self.a.state[4, -1] * np.cos(self.a.state[2, -1])
self.p.rl... |
python | <gh_stars>100-1000
"""Import snow and its metrics."""
from . import snow
metrics_functions = [snow.land_swe_top, ]
|
python | class Class:
def __init__(self, products, postal_code, house_number, country, city):
self.products = products
self.postal_code = postal_code
self.house_number = house_number |
python | from distutils.extension import Extension
from Cython.Distutils import build_ext
import numpy
import sys
if not sys.platform == 'win32':
include_dirs=['../include', numpy.get_include()]
library_dirs=['../lib'] |
python | from .model_helpers import make_tensorboard_callback, make_save_path
from ..utils import naming
class SimpleModel:
def __init__(self, directory_name: str, n_input: int, n_output: int):
self.directory_name = directory_name
self.model = keras.models.Sequential()
self.model.add(keras.layers.... |
python | defaultRoute='via 192.168.0.224' )
#############
sta5 = net.addStation( 'sta5', ip='10.0.0.2/24', defaultRoute='via 10.0.0.22' )
sta6 = net.addStation( 'sta6', ip='10.0.0.3/24', defaultRoute='via 10.0.0.22')
#############
h1 = net.addHost('h1', ip='192.168.0.5', defaultRou... |
python |
def set_sent_starts(doc):
# Mark each doc as a single sentence.
sent_start_char = 0
sent_end_char = len(doc.text) |
python | def payment_type(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "payment_type", value)
@property
@pulumi.getter
def period(self) -> Optional[pulumi.Input[int]]:
"""
The period. Unit: months. Valid values: `1`,`3`, `6`, `12`, `24`, `36`. |
python | if channel == BUTTONS[pattern[current_step_of_level]]:
current_step_of_level += 1
if current_step_of_level >= current_level:
current_level += 1
is_won_current_level = True
else:
is_game_over = True
|
python | model_name='grouping',
name='shopify_collection',
),
migrations.AddField(
model_name='grouping',
name='shopify_collections',
field=models.ManyToManyField(related_name='grouping', to='shopify.ShopifyCollection'),
), |
python | import functools
def _generate_key(*args, **kwargs):
return (args, frozenset(sorted(kwargs.items())))
def memoize(fun):
"""A simple memoize decorator for functions supporting (hashable)
positional arguments.
It also provides a cache_clear() function for clearing the cache: |
python | log.debug(f'Filename: {file}')
data['file'] = file
data['content_type'] = content_type(file)
self.cache[key] = file
def keys(self):
return self.cache.keys()
def remove(self, key):
if key in self.cache:
del self.cache[key]
|
python | return cmd
if __name__ == "__main__":
# configure logger
logging.basicConfig()
dateTimeTag = datetime.datetime.now().strftime( '%Y-%m-%d_%H%M%S' )
outDataDirPath = 'data/binary_' + dateTimeTag
|
python |
class Handler:
characters = []
# Constructor
def __init__(self, characters=[]):
self.characters = characters
self.load()
def add(self, character):
for character_temp in self.characters:
if character_temp.name == character.name:
return
self.c... |
python | def __repr__(self):
return '[Stack:%s]' % self.stack # print, repr(),..
def __eq__(self, other):
return self.stack == other.stack # '==', '!='?
def __len__(self):
return len(self.stack) # len(instance), not instance
def __add__(self, other)... |
python | from fundata.request import ApiClient
from fundata.client import init_api_client
from fundata.dota2.match import get_batch_basic_info
print(os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir))
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir))
def test(public_key,... |
python | Optional wait durating (in seconds) is specified
with keyword argument wait_t.
"""
responses = None |
python |
class CoinsE(Market):
def __init__(self):
super(CoinsE, self).__init__()
self.update_rate = 60
self.url = url_base + self.p_coin + '_' + self.s_coin + '/depth/'
def update_depth(self): |
python | from typing import Optional
from typer import Argument
from typer import Context as TyperContext
from typer import Option
from typer import echo
from spinta.cli.helpers.store import prepare_manifest
from spinta.components import Mode
from spinta.core.context import configure_context |
python | # 10^12 = 1,000,000,000,000 discs in total, determine
# the number of blue discs that the box would contain.
x = 1
y = 1 |
python | while True:
img = cam.read()[1]
img = cv2.flip(img, 1)
img = cv2.resize(img, (640, 480))
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
keypress = cv2.waitKey(1)
if keypress == ord('c'):
hsvCrop = cv2.cvtColor(imgCrop, cv2.COLOR_BGR2HSV)
flagPressedC = True |
python |
plt.plot(ph, vb)
plt.plot(ph, vb1)
plt.ylim(0, 20)
plt.show()
plt.plot(ph, a)
plt.ylim(0, 3)
plt.show()
|
python | def format_seconds(secs):
if secs < 1e-3:
t, u = secs * 1e6, 'microsec'
elif secs < 1e0:
t, u = secs * 1e3, 'millisec'
else:
t, u = secs, 'sec'
return '{:.03f} {}'.format(t, u)
|
python | src: /proc/mounts
register: mounts
- name: Print returned information
ansible.builtin.debug:
msg: "{{ mounts['content'] | b64decode }}"
# From the commandline, find the pid of the remote machine's sshd
# $ ansible host -m slurp -a 'src=/var/run/sshd.pid'
# host | SUCCESS => {
# "changed": false,
# ... |
python | inbox. The carousel then uses your factory function to create a new child
component. This way, a sequence of operations can be automatically chained
together.
If the argument source needs to receive a "NEXT" message before sending its
first set of arguments, then set the argument make1stRequest=True when creating
the ... |
python |
def f_principal(parametros):
if len(parametros) != 1:
raise SystemExit(f'Uso adecuado: {parametros[0]} ')
archivos_png(parametros)
return
if __name__ == '__main__':
import sys
f_principal(sys.argv) |
python | # uncompyle6 version 3.2.0
# Python bytecode 2.4 (62061)
# Decompiled from: Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:19:30) [MSC v.1500 32 bit (Intel)]
# Embedded file name: otp.ai.AIBaseGlobal
from AIBase import *
__builtins__['simbase'] = AIBase() |
python | # http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permi... |
python | while len(ms):
e = ms.pop()
print(e, end='')
print("")
lq.close()
lq.unlink() |
python |
class FacultyListView(generics.ListAPIView):
"""API view for faculty lists"""
queryset = Faculty.objects.all()
serializer_class = FacultySerializer
# authentication_classes = (authentication.TokenAuthentication,)
# permission_classes = (permissions.IsAuthenticated,)
filter_backends = [DjangoF... |
python |
from face_detector import detect_faces
def cut_and_save_face_imgs():
ORIGINAL_DATA_DIR_PATH = './data/original_images/face_dataset/' |
python | class Migration(migrations.Migration):
dependencies = [
('steambird', '0002_auto_20190328_2255'),
]
operations = [
migrations.AlterField(
model_name='teacher',
name='user',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletio... |
python | )
tb = row.column()
tb1 = tb.column(align=True)
tb1.operator('mmd_tools.display_item_frame_add', text='', icon=ICON_ADD)
tb1.operator('mmd_tools.display_item_frame_remove', text='', icon=ICON_REMOVE)
tb1.menu('OBJECT_MT_mmd_tools_display_item_frame_menu', text='', ico... |
python | while next_player is None:
next_player = input("Who should be the first player? 'X' or 'O': ")
if 'x' in next_player.lower():
game.next_player = "X"
elif 'o' in next_player.lower():
game.next_player = "O" |
python | def getch():
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
|
python | self.options.update(self.define_options(['pepfile', 'proteincol'],
prottable_options))
def parse_input(self, **kwargs):
super().parse_input(**kwargs)
self.headertypes = ['probability']
def initialize_input(self):
super().initializ... |
python | # copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# 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 applica... |
python | self.path += '?%s' % parsed.query
self._bufr = StringIO()
self._bufw = StringIO()
self._conn = None
self._timeout = None
self._headers = None
def open (self):
if self._conn is not None:
self.close() |
python | x_train = keras.preprocessing.sequence.pad_sequences(x_train, maxlen=maxlen)
x_val = keras.preprocessing.sequence.pad_sequences(x_val, maxlen=maxlen)
"""
## Train and evaluate the model
"""
model.compile(optimizer="adam", loss="binary_crossentropy", metrics=["accuracy"])
model.fit(x_train, y_train, batch_size=32, epo... |
python |
@pytest.mark.parametrize(
'activation_slot,exit_slot,slot,expected',
[
(0, 1, 0, True),
(1, 1, 1, False),
(0, 1, 1, False),
(0, 1, 2, False),
],
)
def test_is_active(sample_validator_record_params,
activation_slot, |
python | # 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, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See ... |
python | fig, ax = plt.subplots(1)
ax.plot(t, mu1, lw=2, label='mean population 1', color='blue')
ax.plot(t, mu2, lw=2, label='mean population 2', color='yellow')
ax.fill_between(t, mu1+sigma1, mu1-sigma1, facecolor='blue', alpha=0.5)
ax.fill_between(t, mu2+sigma2, mu2-sigma2, facecolor='yellow', alpha=0.5)
ax.set_title(r'rando... |
python | gif_lat_file = pd.read_excel(
excel_path,
header=0,
sheet_name='Full GIF Map for Review ', engine="openpyxl",
)
gifs_right = gif_lat_file.loc[gif_lat_file['R'].notnull(), 'R'].copy() |
python | if users[col].dtype == np.object:
users = users[users[col].map(len) > 0]
logging.info(" -> Without empty strings: %d records", len(users))
# # 8. Write results
logging.info("8. WRITING result")
logging.info(" ColDelimiter=%s | RowDelimiter=%s",
DST_COL_DELIMITER, DST_ROW_DELIMITER)
logging.... |
python | ZAL = '\u0630'
RE = '\u0631'
ZE = '\u0632'
ZHE = '\u0698'
SIN = '\u0633'
SHIN = '\u0634'
SAD = '\u0635'
ZAD = '\u0636'
TA = '\u0637'
ZA = '\u0638'
EYN = '\u0639'
GHEYN = '\u063a'
FE = '\u0641'
GHAF = '\u0642'
KAF = '\u06a9' |
python | has_receive = 0
while has_receive != filesize:
data = dir_socket.recv(1024) # 第二次获取请求,这次获取的就是传递的具体内容了,1024为文件发送的单位
f.write(data)
has_receive += len(data)
f.close()
def deal_dir():
# 待完善用于处理子文件夹,需要利用递归完成
|
python | socket_down = context.socket(zmq.SUB)
socket_up = context.socket(zmq.PUB)
socket_down.connect("tcp://127.0.0.1:5555")
# socket_down.bind("ipc:///@capnzero.ipc")
socket_down.setsockopt_string(zmq.SUBSCRIBE, rcv_topic) |
python |
print(Counter('aaaaaaaaaaaabbbbbbbbbcccccccccc'))
d = {'a': 10}
d = defaultdict(lambda: 0) |
python | if can_admin(user, world):
return True
if world.properties.get('features', {}).get('coordLink', False):
return True
return False
def is_superuser(user):
return user.is_authenticated() and user.is_superuser
def can_urllink(user, world): |
python | 'test.class1',
'test.class2',
{'model_alias1': ['test.class3']}]}
self.assertEqual(
lc_utils.get_test_steps(),
{'default_alias': ['test.class1', 'test.class2'],
'model_alias1': ['test.class3']})
|
python | print("Metadata misssing from database. Skipping experiment.")
db_id = exp_id
sample_dict = collections.OrderedDict()
if library == 'SINGLE':
sample_dict = collections.OrderedDict([('fastq_1',''), ('fastq_2',''), ('md5_1',''), ('md5_2',''), ('single_... |
python | fund_mapping = Mapping(fund_gsheet, Fund.constructor_parameters, field_casts=field_casts)
funds = extract_from_detailed_ledger(
'funds',
'A11',
('fund', 'type', 'parish fund', 'realised', 'bank account id')
) |
python | pipeline.raise_from_status()
# Since Kafka emission is asynchronous, we must wait a little bit so that
# the changes are actually processed.
time.sleep(kafka_post_ingestion_wait_sec)
@pytest.mark.dependency(
depends=[
"test_ingestion_via_rest",
"test_ingestion_via_kafka",
... |
python |
if src_lang not in self.supported_langs:
raise RuntimeError('Unsupported source language.')
if tgt_lang not in self.supported_langs:
raise RuntimeError('Unsupported target language.')
self.tokenizer.src_lang = src_lang
encoded_text = self.tokenizer(input_text, r... |
python |
def setUp(self):
'''
Set up method that will run before every Test
'''
self.new_headlines = Top_Headlines('<NAME>', '<NAME> delivers on Man United return with two goals and a show to delight Old Trafford - ESPN', 'Twelve years after he left Old Trafford, Ronaldo picked up where he left off in a Man U... |
python | 'author_email': '<EMAIL>',
'version': '1.0',
'install_requires': ['nose'],
'packages': ['parking'],
'scripts': [],
'name': 'parking-calculator'
} |
python | # -*- encoding: utf-8 -*-
__author__ = 'gotlium'
|
python | Created on Tue Dec 5 20:32:45 2017
@author: Flame
"""
from main import check
"""
from TuringMachine import Rule, Q, Move, TuringMachine, Tape |
python | """
def disambiguate(self, word):
"""Disambiguate Prefix Rule 1b
Rule 1b : berV -> be-rV
"""
matches = re.match(r'^ber([aiueo].*)$', word)
if matches:
return 'r' + matches.group(1)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.