id
stringlengths
1
7
text
stringlengths
6
1.03M
dataset_id
stringclasses
1 value
1732048
import json from kazoo.client import KazooClient from .base import WatchableBase, WatcherBase class ZooKeeper(WatchableBase): '''A zookeeper client wrapper. Improves usability especially for watcher callbacks.''' def __init__(self, *hosts): self._client = KazooClient(','.join(hosts), read_only=True) ...
StarcoderdataPython
1625881
<reponame>return1/fabtools """ Git === This module provides high-level tools for managing `Git`_ repositories. .. _Git: http://git-scm.com/ """ from __future__ import with_statement from fabric.api import run from fabtools import git from fabtools.files import is_dir def command(): """ Require the git c...
StarcoderdataPython
1603532
""" The new xCaptcha implementation for Flask without Flask-WTF """ __NAME__ = "Flask-xCaptcha" __version__ = "0.5.2" __license__ = "MIT" __author__ = "<NAME>" __copyright__ = "(c) 2020 <NAME>" try: from flask import request from jinja2 import Markup import requests except ImportError as ex: print("Mi...
StarcoderdataPython
3330231
<reponame>tallninja/python_blockchain<gh_stars>1-10 import time from backend.blockchain.blockchain import Blockchain from backend.config import TIME_S blockchain = Blockchain() times = [] for i in range(1000): start_time = time.time_ns() / TIME_S blockchain.add_block(i) end_time = time.time_ns() / TIME_S...
StarcoderdataPython
1725451
<gh_stars>1-10 from dataclasses import dataclass from typing import List from lakey_finicity.models import Customer # https://community.finicity.com/s/article/201703219-Customers#get_customers @dataclass class CustomersListResponse(object): found: int # Total number of records matching search criteria displ...
StarcoderdataPython
3286777
from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from django.core.exceptions import ObjectDoesNotExist class Interest(models.Model): interest = models.CharField(max_length=150) def __str__(self): ...
StarcoderdataPython
1763338
<filename>src/spotify_party/auth.py __all__ = ["require_auth", "handle_auth", "update_auth", "call_api"] import time from functools import partial, wraps from typing import TYPE_CHECKING, Any, Awaitable, Callable, Optional, Tuple import aiohttp_session from aiohttp import web from aiohttp_spotify import SpotifyAuth, ...
StarcoderdataPython
29574
import unittest import io from unittest import mock from tests.lib.utils import INSPECT from custom_image_cli.validation_tool import validation_helper from custom_image_cli.validation_tool.validation_models.validation_models import \ ImageDetail, ImageManifest, EmrRelease class TestValidationHelper(unittest.TestC...
StarcoderdataPython
3251090
# -*- coding: utf-8 -*- import datetime from dateutil.relativedelta import relativedelta from unittest.mock import patch import time from odoo.addons.membership.tests.common import TestMembershipCommon from odoo.tests import tagged from odoo import fields @tagged('post_install', '-at_install') class TestMembership(...
StarcoderdataPython
3235706
<gh_stars>0 import math import pytest import autofit as af from autofit import exc class TestPriorLimits: def test_out_of_order_prior_limits(self): with pytest.raises(af.exc.PriorException): af.UniformPrior(1.0, 0) with pytest.raises(af.exc.PriorException): a...
StarcoderdataPython
1684795
<gh_stars>0 import unittest import random from Crypto.Cipher import AES from set1 import fromAscii, toAscii, fromB64 from set1 import fixedXor from set1 import isECBEncrypted def pkcs7Padding(data, blockSize=16): missingBytesNumber = (-len(data))%blockSize if missingBytesNumber == 0: missingBytesNumb...
StarcoderdataPython
1681879
# Copyright 2018 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.0 # # or in the "license...
StarcoderdataPython
46692
# coding: utf-8 # !/usr/bin/env python3 import csv import os, os.path import sys import argparse from WriteExcel import Excel from log import debug, info, error from baidu_traslate import * class Nessus(object): """处理Nessus扫描结果""" def __init__(self, csv_name): self.csv_name = csv_name self....
StarcoderdataPython
101896
<filename>torchrec/distributed/comm_ops.py #!/usr/bin/env python3 # Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. from dataclasses import dataclass, field from...
StarcoderdataPython
113320
''' For semester 1 Experiment to see if randomizing the queries will result in a new timetable Note that this is not a strict requirement ''' import unittest import sys from z3 import * sys.path.append('../nusmodsplanner') import queryParserBV import querySolverBV import mod_utils import random SEMESTER = 'AY1718S1' ...
StarcoderdataPython
3278624
<gh_stars>1-10 word = 'tin' print(word[0]) print(word[1]) print(word[2]) print(word[3])
StarcoderdataPython
1605170
# -*- coding: utf-8 -*- import io import uuid import os import requests from PIL import Image class DownloadImage: def makeFilename(self, imgUrl): ext = os.path.splitext(imgUrl) uniqueid = uuid.uuid1() filename = str(uniqueid) + ext[1] path = self.makePath() return {'re...
StarcoderdataPython
1638376
#!/usr/bin/python3 import os RPC_ETHEREUM_PORT = 8545 RPC_ETHEREUM_HOST = "ethereumgo" RPC_ENDPOINT = "http://{}:{}".format(RPC_ETHEREUM_HOST, RPC_ETHEREUM_PORT) if os.getenv("STAGE", "development") != "development": WS_ETHEREUM_PORT = 8546 else: WS_ETHEREUM_PORT = 8545 WS_ENDPOINT = "ws://{}:{}".format(RP...
StarcoderdataPython
42805
<reponame>plumdog/mainstay_kanban<filename>models.py from django.db import models from mainstay.models import UpdatedAndCreated class TaskUsersManager(models.Manager): def for_user(self, user): return self.get_queryset().filter(models.Q(user=user) | models.Q(user=None)) class Task(UpdatedAndCreated, mod...
StarcoderdataPython
1624
<gh_stars>1-10 import torch.nn as nn import torch.optim as optim import torch.utils.data from Training import functions from Training.imresize import imresize import matplotlib.pyplot as plt from Models.pix2pixHD_base import GANLoss, VGGLoss from Models.pix2pixHD2 import mask2onehot class Losses(): def __init__(se...
StarcoderdataPython
3397520
import unittest from netaddr import IPRange, IPAddress from netaddr_extensions import funcs from netaddr_extensions import classes class FuncsTestCase(unittest.TestCase): def test_bool_funcs(self): self.assertTrue(funcs.is_netmask('255.255.255.0')) self.assertFalse(funcs.is_netmask('127.0.0.1')) ...
StarcoderdataPython
1798849
<reponame>p3g4asus/orvpy import sys import traceback import threading import logging from util import init_logger, tohexs, s2b, uunq from dataparser import RoughParser import select import socket import time import abc import event import json from device.devicect10 import SendBufferTimer from action impor...
StarcoderdataPython
1657870
import basic_type from schema_dsl_common import * def _check_object_type(input_object, path): if not isinstance(input_object, dict): raise TypeError(get_message(path, 'Should be an object')) def _get_unrecognized_message(diff_set): diff = list(diff_set) if len(diff) == 1: return 'Unrecog...
StarcoderdataPython
152303
""" Defines upper bounds of in silico SD media used by Szappanos et al., 2011 """ from yeast.core.media.constants import reagents from yeast.core.media.sd.base import sd szappanos = { reagents["oxygen"]: 6.3, reagents["sulphite"]: 100.0, reagents["phosphate"]: 0.89, # Carbon reagents["D-glucose"]:...
StarcoderdataPython
1740568
<reponame>raghav-vish/cubescramble import random def scramble3(length=-1, number=1, gen2=False): ret=[] for loop in range(number): scr='' moves=['R', 'L', 'U', 'D', 'F', 'B'] if(gen2): moves=['R', 'U'] sides=["", "'", "2"] prevmov=-1 num=-1 if(length==-1): lent=random.randint(15, 25) else: l...
StarcoderdataPython
3326846
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright 2020 <NAME> <https://github.com/rzhw>. 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.apach...
StarcoderdataPython
1690539
<filename>django_spanner/client.py # Copyright 2020 Google LLC # # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file or at # https://developers.google.com/open-source/licenses/bsd from django.db.backends.base.client import BaseDatabaseClient from google.cloud.spanner_db...
StarcoderdataPython
160276
<gh_stars>0 # -*- coding: utf-8 -*- # Generated by Django 1.11.22 on 2019-07-09 23:09 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('js_locations', '0006_location_featured_image'), ] operations = [ ...
StarcoderdataPython
3310234
# Generated by Django 3.0.3 on 2020-03-24 18:37 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('study', '0004_remove_stu...
StarcoderdataPython
29804
<gh_stars>10-100 import csv import json def pair_entity_ratio(found_pair_set_len, entity_count): return found_pair_set_len / entity_count def precision_and_recall(found_pair_set, pos_pair_set, neg_pair_set=None): # if a neg_pair_set is provided, # consider the "universe" to be only the what's inside pos...
StarcoderdataPython
180070
from geventwebsocket.handler import WebSocketHandler class DjangoWebSocketHandler(WebSocketHandler): def run_websocket(self): """ Just run the websocket request on the application. Dont use client tracking because we are using unix domain sockets and the client addr is the same fo...
StarcoderdataPython
71834
# -*- coding: utf-8 -*- """Tests for the redirect.py script.""" # # (C) Pywikibot team, 2017 # # Distributed under the terms of the MIT license. # from __future__ import absolute_import, unicode_literals try: from unittest.mock import Mock, patch except ImportError: from mock import Mock, patch import pywikib...
StarcoderdataPython
1640086
<reponame>deniskolokol/anywhere #!/usr/bin/env python # -*- coding: utf-8 -*- from osgeo import ogr def filter_file(filter_func, infile, outfile): """ Saves all infile shapes which pass through filter_func to outfile. Example: filter_file(lambda x: x.GetField('ISO2') == 'CZ', 'TM_WORLD_BORDERS-0....
StarcoderdataPython
64685
import platform import os import logging.handlers from lbrynet import build_type, __version__ as lbrynet_version log = logging.getLogger(__name__) def get_platform() -> dict: p = { "processor": platform.processor(), "python_version": platform.python_version(), "platform": platform.platfo...
StarcoderdataPython
3376507
<filename>loops.py largest = None smallest = None val=None while True: num = raw_input('Enter a number :') try: val=int(num) except: print "Invalid input" if num == "done" : break if largest is None : largest=val if smallest is None : smallest=v...
StarcoderdataPython
1700577
<filename>day04/part1.py import re def test_num(num): str_num = str(num) if re.search("(1{2}|2{2}|3{2}|4{2}|5{2}|6{2}|7{2}|8{2}|9{2}|0{2})", str_num) == None: return False return list(str_num) == sorted(str_num) def process(start, end): count = 0 for num in range(start, end + 1): if test_num(num): ...
StarcoderdataPython
78656
#!/usr/bin/env python3.7 class Proposal: """ Sequence proposed by the player while trying to guess the secret The problem will add hint information, by setting the value of whites and reds """ """proposed secret sequence""" sequence = str """number of right colours in a wrong position"""...
StarcoderdataPython
1665931
""" ******************************** * Created by mohammed-alaa * ******************************** Here I'm training video level network based on recurrent networks(frames from CNN are concatenated into a 3d tensor and feed to RNN): 1. setting configs (considering concatenation will have feature of 4096 = 2048 *2) ...
StarcoderdataPython
153063
""" This module provides functions to get the dimensionality of a structure. A number of different algorithms are implemented. These are based on the following publications: get_dimensionality_larsen: - <NAME>, <NAME>, <NAME>, <NAME>. Definition of a scoring parameter to identify low-dimensional materials compo...
StarcoderdataPython
125805
<filename>codes/infer.py<gh_stars>10-100 import math import torch.nn.functional as F import matplotlib import sys from codes.evaluation.pyeval.calAOS import evaluateDetectionAPAOS from codes.evaluation.evaluate import evaluate from codes.utils import array_tool as at from torchvision.ops import boxes as box_ops import ...
StarcoderdataPython
38111
# -*- coding: utf-8 -*- # # Copyright (C) 2019 CERN. # Copyright (C) 2019 Northwestern University. # # Invenio-RDM-Records is free software; you can redistribute it and/or modify # it under the terms of the MIT License; see LICENSE file for more details. """DataCite-based data model for Invenio.""" from .utils import...
StarcoderdataPython
133611
"""Basic pipette data state and store.""" from dataclasses import dataclass from typing import Dict, List, Mapping, Optional, Tuple from typing_extensions import final from opentrons_shared_data.pipette.dev_types import PipetteName from opentrons.hardware_control.dev_types import PipetteDict from opentrons.types impor...
StarcoderdataPython
3219640
import pytoml as toml def get_cfg(path): # read config file with open(path, "r") as f: cfg = toml.load(f) return cfg def flit_metadata(cfg): return cfg.get("tool").get("flit").get("metadata") def snakeye_metadata(cfg): return cfg.get("tool").get("snakeye").get("metadata") def get_de...
StarcoderdataPython
4829689
<gh_stars>1-10 def test(): # Here we can either check objects created in the solution code, or the # string value of the solution, available as __solution__. A helper for # printing formatted messages is available as __msg__. See the testTemplate # in the meta.json for details. # If an assertion fa...
StarcoderdataPython
1685473
""" A Python library for the chorus.fightthe.pw site. This uses the website's API but transforms it into a Python-enviorment. """ from .pychorus import * __all__ = [ "Song", "search", "latest", "random", "count", "SongNotFoundError", "PageNotFoundError" ] __version__ = "0...
StarcoderdataPython
4806274
<gh_stars>1-10 #!/usr/bin/env python import fiona import time from rasterio.plot import show, show_hist from projections.rasterset import RasterSet, Raster import projections.predicts as predicts import projections.modelr as modelr # Open the mask shape file shp_file = '../../data/from-adriana/tropicalforests.shp' s...
StarcoderdataPython
1767024
<filename>projects/manipulathor_baselines/armpointnav_baselines/experiments/ithor/armpointnav_disjoint_depth.py import gym import torch.nn as nn from allenact_plugins.manipulathor_plugin.manipulathor_constants import ENV_ARGS from allenact_plugins.manipulathor_plugin.manipulathor_task_samplers import ( ArmPointNav...
StarcoderdataPython
148711
import embedded_media as emb from django.forms import Form, CharField, TextInput, Media from django.test import TestCase class EmbeddedMediaTest(TestCase): def test_css(self): ## CSS rendering css = emb.CSS('.mywidget { display: none; }') self.assertHTMLEqual(css.render('all'), ...
StarcoderdataPython
1695736
<reponame>shenhuaze/leetcode-python<filename>code/word_search.py """ @author <NAME> @date 2019-09-30 """ def exist(board, word): if board is None or len(board) == 0 or board[0] is None or len(board[0]) == 0: return False m = len(board) n = len(board[0]) for i in range(m): for j in rang...
StarcoderdataPython
59936
from interactiongrader import Answer from interactiongrader import ChangeType from fuzzywuzzy import fuzz def test_calculate_ranges(): ans = Answer() ranges = ans.calculate_ranges() assert ans.sentence == '' assert ranges[ChangeType.FLIP] == 0.75 def test_random_change_type(): ans = Answer() ...
StarcoderdataPython
3324820
#!/usr/bin/env python # coding: utf-8 # <img style="float: left;padding: 1.3em" src="https://indico.in2p3.fr/event/18313/logo-786578160.png"> # # # Gravitational Wave Open Data Workshop #3 # # # #### Tutorial 1.2: Introduction to GWpy # # This tutorial will briefly describe GWpy, a python package for gravitatio...
StarcoderdataPython
197478
<reponame>AdamCottrill/FishNetPortal from datetime import date from typing import Optional from pydantic import validator, constr from .utils import to_titlecase, yr_to_year from .FNBase import FNBase, prj_cd_regex class FN011(FNBase): """parser/validator for FN011 objects: + Valid project code. + Yea...
StarcoderdataPython
3270414
from django.urls import include, path from .views import DepartmentViewSet, PersonViewSet from .routers import CustomDefaultRouter router = CustomDefaultRouter() router.register(r'department', DepartmentViewSet, basename='department') router.register(r'people', PersonViewSet, basename='person') urlpatterns = ( pa...
StarcoderdataPython
3394130
import os from pathlib import Path import responses from wikidict import download from wikidict.constants import BASE_URL, DUMP_URL WIKTIONARY_INDEX = """<html> <head><title>Index of /frwiktionary/</title></head> <body bgcolor="white"> <h1>Index of /frwiktionary/</h1><hr><pre><a href="../">../</a> <a href="20191120/...
StarcoderdataPython
1770517
<filename>myo-sensor-data-analysis/Radar plots/real_time_refactored.py<gh_stars>0 import myo class Listener(myo.DeviceListener): def on_paired(self, event): print("Hello, {}!".format(event.device_name)) event.device.vibrate(myo.VibrationType.short) def on_unpaired(self, event): return F...
StarcoderdataPython
93139
import datetime import timeit import redgrease # Bind / register the function on some Redis instance. r = redgrease.RedisGears() # CommandReader Decorator # The `command` decorator tunrs the function to a CommandReader, # registerered on the Redis Gears sever if using the `on` argument @redgrease.command(on=r, requ...
StarcoderdataPython
32839
<reponame>fgmacedo/django-awards from celery.task import Task from ..notifications.contextmanagers import BatchNotifications class AsyncBadgeAward(Task): ignore_result = True def run(self, badge, state, **kwargs): # from celery.contrib import rdb; rdb.set_trace() with BatchNotifications(): ...
StarcoderdataPython
3268443
#Program to find non-repeated element arr=list(map(int, input().split(', '))) #Input various integers in arr list if 1< len(arr) <= 10**6: #Checking array length for i in arr: #Taking element from arr if 0 < i <= 10**9: #Checking element value if arr.count(i) ==1: #Che...
StarcoderdataPython
3399901
<reponame>rjczanik/xzceb-flask_eng_fr<filename>final_project/machinetranslation/tests/tests.py<gh_stars>0 import unittest from translator import * class TestEngToFrText(unittest.TestCase): def test_null_value(self): self.assertEqual( english_to_french(None), "Please enter some text to translat...
StarcoderdataPython
3373183
<reponame>minddistrict/authlib import os import base64 import unittest from flask import Flask, request from authlib.common.security import generate_token from authlib.common.encoding import to_bytes, to_unicode from authlib.common.urls import url_encode from authlib.integrations.sqla_oauth2 import ( create_query_c...
StarcoderdataPython
3230900
<reponame>kishorekolli/deep_racer_guru # # DeepRacer Guru # # Version 3.0 onwards # # Copyright (c) 2021 dmh23 # import math def get_pretty_small_float(number, max_value, decimal_places): assert 0 <= decimal_places <= 1 if max_value >= 10 and abs(round(number, decimal_places)) < 10: prepend = " " ...
StarcoderdataPython
1675680
<gh_stars>1-10 import os from setuptools import setup with open('requirements.txt') as f: required = f.read().splitlines() import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="cronio", version="1.2.0", author="<NAME>", author_email="<EMAIL...
StarcoderdataPython
3266391
<reponame>anyidea/drfexts<gh_stars>1-10 import functools import operator from decimal import Decimal import orjson from typing import Optional, Any import unicodecsv as csv from io import BytesIO import datetime from django.conf import settings from openpyxl import Workbook from openpyxl.styles import Font, PatternFi...
StarcoderdataPython
1716843
<filename>Lesson 02/Solutions/Solution02.py<gh_stars>0 # String Repeat # # Get two inputs from the user # 1. The number of times to repeat # 2. The string to repeat numRepeat = int(input("Enter the number of times to repeat: ")) stringRepeat = input("Enter the string to repeat: ") # Solution 1: for i in range(numRepe...
StarcoderdataPython
81884
<filename>043_face_landmark/lib/helper/init.py import tensorflow as tf def init(*args): if len(args)==1: use_pb=True pb_path=args[0] else: use_pb=False meta_path=args[0] restore_model_path=args[1] def ini_ckpt(): graph = tf.Graph() graph.as_default...
StarcoderdataPython
1684823
import requests import time import json import pdb import random import optparse import threading import sys import os def jsonPrint(r): """Pretty-print JSON""" return json.dumps(r.json(), indent=4, sort_keys=True) + "\n" def ordered(obj): """Order map for comparison https://stackoverflow.com/quest...
StarcoderdataPython
3226493
import numpy as np import pytest import pandas as pd import pandas._testing as tm @pytest.mark.parametrize("align_axis", [0, 1, "index", "columns"]) def test_compare_axis(align_axis): # GH#30429 df = pd.DataFrame( {"col1": ["a", "b", "c"], "col2": [1.0, 2.0, np.nan], "col3": [1.0, 2.0, 3.0]}, ...
StarcoderdataPython
3389642
<filename>docs/gallery/plot_spectra_pcolormesh.py """ Spectrum as pcolormesh ====================== Pcolor type plot of wave spectrum """ import matplotlib.pyplot as plt import cmocean from wavespectra import read_era5 dset = read_era5("../_static/era5file.nc") ds = dset.isel(lat=0, lon=0, time=0) p = ds.spec.plot(...
StarcoderdataPython
3393571
<filename>credsgrabber.py import requests, os, zipfile from zipfile import ZipFile # interesting directories """ ~/.ssh ~/.aws/ ~/.azure/ ~/Library/Application Support/Firefox/Profiles/<profilename>.default or Also other interesting files - osx/linux will have shell stuff like .bash* files, devs may have vim stuff...
StarcoderdataPython
3208642
"""Defines the factory object for all the initializers""" from torch.nn.init import kaiming_uniform_, kaiming_normal_, ones_, zeros_, \ normal_, constant_, xavier_uniform_, xavier_normal_ from coreml.factory import Factory init_factory = Factory() init_factory.register_builder('kaiming_uniform', kaiming_uniform_) ...
StarcoderdataPython
1685632
# -*- coding: utf-8 -*- """ (C) Rgc <<EMAIL>> All rights reserved create time '2020/7/22 14:31' Usage: """ __author__ = 'Rgc' __title__ = 'distributed_redis_sdk' __description__ = '使用一致性hash实现python flask版的分布式redis 客户端sdk包' __url__ = '<EMAIL>:Rgcsh/distributed_redis_sdk.git' __version__ = '0.0.1' __author_email__ = ...
StarcoderdataPython
3202475
<gh_stars>1-10 # -*- coding: utf-8 -*- from multiprocessing import Process from .message_handler import MessageHandler class ProcessHandler: process_list: list output_list: list has_web: bool = False message_handler: MessageHandler use_broker_process: bool = False broker_process: Process = No...
StarcoderdataPython
92246
<reponame>TangoMan75/pyhelper<gh_stars>0 #!/bin/python3 # -*- coding: utf-8 -*- """ This file is part of the TangoMan Type Validator package. (c) "<NAME>" <<EMAIL>> This source file is subject to the MIT license that is bundled with this source code in the file LICENSE. """ from setuptools import setup setup(...
StarcoderdataPython
1744215
<filename>ForgeEvo_griddly.py import copy from ray.rllib.models import ModelCatalog from evolution.evolver import init_evolver from griddly.util.rllib.torch import GAPAgent import os import pickle import sys # My favorite debugging macro from pdb import set_trace as T import gym import numpy as np import ray import r...
StarcoderdataPython
14791
"""common parser argument """ # pylint: disable=missing-docstring # pylint: disable=too-few-public-methods import argparse from enum import Enum import logging from sys import exit as sys_exit from . import archivist from .logger import set_logger from .proof_mechanism import ProofMechanism LOGGER = logging.getL...
StarcoderdataPython
173732
<filename>tests/api/test_generated_endpoints.py import pytest import json import re from share.disambiguation.matcher import Matcher from share.disambiguation.strategies import DatabaseStrategy from share.regulate import Regulator from share.util import IDObfuscator from tests import factories from tests.share.normal...
StarcoderdataPython
156048
from aoc2020 import * from aoc2020.utils import math_product from itertools import chain import numpy as np def tborder(tile): _, m = tile return "".join(m[0]) def bborder(tile): _, m = tile return "".join(m[-1]) def lborder(tile): _, m = tile return "".join(m[:,0]) def rborder(tile): ...
StarcoderdataPython
3367854
import time import numpy as np from multiprocessing.dummy import Pool as ThreadPool from mcts import MCTS from play import play_match from players.uninformed_mcts_player import UninformedMCTSPlayer from players.deep_mcts_player import DeepMCTSPlayer # Object that coordinates AlphaZero training. class Trainer: def...
StarcoderdataPython
83638
<reponame>parallelstream/kines<filename>tests/boto3_api_responses.py import datetime from dateutil.tz import tzutc, tzlocal LIST_SHARDS_8_RESPONSE = { "Shards": [ { "ShardId": "shardId-000000000007", "ParentShardId": "shardId-000000000003", "HashKeyRange": { ...
StarcoderdataPython
3395023
#!/usr/bin/env python3 # Implements https://developer.github.com/v3/repos/statuses/#create-a-status import argparse import os import requests import sys def SetCommitStatus(slug, hash, token, params): url = "https://api.github.com/repos/%s/statuses/%s" % (slug, hash) headers = { "Authorization": "t...
StarcoderdataPython
3299817
# proxy module from traits.util.resource import *
StarcoderdataPython
4826096
import sys # Django from django.apps import AppConfig # from django.core import checks from django.utils.translation import gettext_lazy as _ class ConfConfig(AppConfig): name = 'awx.conf' verbose_name = _('Configuration') def ready(self): self.module.autodiscover() if not set(sys.arg...
StarcoderdataPython
1739441
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ (C) 2013 by <NAME> Make sure that you paste some German and English text for the extraction of language models in text-de-1.txt and text-en-1.txt. The more text you put in these files, the better it should be for your model generation. """ # https://github.com/dcava...
StarcoderdataPython
56284
<gh_stars>0 #!/usr/bin/env python3 """ Tools to truncate functional images to remove all data recorded before the first stimulus. To use, call main(). Created on 7/6/2021 by <NAME>. """ # Standard Python modules. from os import PathLike import subprocess def main(onsets_path: PathLike, func_path: PathLike, out_prefi...
StarcoderdataPython
3224749
import os import sys import tkinter as tkinter import gobject from gi.repository import gst def on_sync_message(bus, message, window_id): if not message.structure is None: if message.structure.get_name() == 'prepare-xwindow-id': image_sink = message.src image_sink.s...
StarcoderdataPython
3364473
""" The different objects which can be declared. """ # pylint: disable=R0903 from .types import CType class CDeclaration: """ A single declaration """ def __init__(self, storage_class, typ: CType, name, location): assert isinstance(typ, CType) assert isinstance(name, str) or name is None ...
StarcoderdataPython
3297167
# Licensed under a 3-clause BSD style license - see LICENSE.rst import pytest import numpy as np from numpy.testing import assert_allclose from astropy import units as u from astropy.io import fits from astropy.utils.data import get_pkg_data_filename from gammapy.irf import EnergyDependentMultiGaussPSF from gammapy....
StarcoderdataPython
1708137
<reponame>rupakc/NeuralSearchSpace<gh_stars>1-10 LOCAL_MONGO_HOSTNAME = 'localhost' LOCAL_MONGO_PORT = 27017 EXPIRE_TIME = 1000 DB_NAME = 'Optimization' COLLECTION_NAME = 'NeuralSearchSpace'
StarcoderdataPython
3202242
from __future__ import annotations from dnnv.properties.expressions.base import Expression from ...expressions import BinaryExpression, Call from ..base import GenericExpressionTransformer from ._calls import FunctionSubstitutor from ...visitors import DetailsInference class SubstituteCalls(GenericExpressionTransfo...
StarcoderdataPython
3365822
<reponame>lucky-luk3/msticpy # ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # --------------------------------------------------------...
StarcoderdataPython
3277388
from django.contrib import admin from .models import Brouwersdag, Competition, Exhibitor, ShowCasedModel @admin.register(ShowCasedModel) class ShowCasedModelAdmin(admin.ModelAdmin): list_display = ( "name", "owner", "scale", "length", "width", "height", "is...
StarcoderdataPython
3291873
""" Push local state to AWS Cloudformation """ import collections import sys import click import halo from ..aws.cloudformation import Cloudformation from ..exceptions import StackNotFound from ..utils import (accounts_regions_and_names, class_filter, plural, set_stacks) @click.command() @accou...
StarcoderdataPython
1649345
# -*- coding: utf-8 -*- import argparse import pdb import traceback from hashlib import md5 from typing import List, Tuple def solve(door_id: str, verbose=False) -> Tuple[str, str]: pword_one: List[str] = [] pword_two: List[str] = [None] * 8 # type: ignore chars_left: int = 8 index: int = 0 whil...
StarcoderdataPython
4843213
import numpy as np class MaxPool: image_shape = [0, 0] num_filters = 0 def forward(self, input_image): """ function for performing forward propagation Parameters: input_image : numpy array Returns: output : numpy array """ ...
StarcoderdataPython
3328117
<reponame>ywkpl/DataStructuresAndAlgorithms<filename>Queue/LinkedQuequ.py from typing import TypeVar, Generic T=TypeVar('T') class Node(Generic[T]): def __init__(self, data:T, next=None): self.data=data self._next=next class LinkedQueue(Generic[T]): def __init__(self, capacity:int): se...
StarcoderdataPython
3233214
<reponame>Eloco/docker-action-send-skype #!/usr/bin/env python # coding=utf-8 import os import emoji from skpy import Skype, SkypeChats import skpy import time import sys import re """ Eloco """ def connect_skype(user=str, pwd=str): print(f"""[init]Skype connecting <{time.strftime("%Y-%m-%d %H:%M:%S", time.localt...
StarcoderdataPython
118641
<gh_stars>1-10 ############################################################################## # # Copyright (c) 2009 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribut...
StarcoderdataPython
176439
from __future__ import annotations from cmath import cos import sys from exo import proc, Procedure, DRAM, config, instr, QAST from matmap.base import * from matmap.qast_utils.loopReader import * from itertools import dropwhile class ReorderingTransform(Transform): #loop bounds are a ForLoop object #...
StarcoderdataPython
69274
import sys # Application for working with dictionaries # dictionaries: building, indexing, adding and removing keys, iterating through dictionaries # as well as their keys and values, checking key existence, keys(), items() and values() methods sample = {'home': '123 Main street', 'office': '22 Baker Street', 'bill':...
StarcoderdataPython
3389848
<reponame>shah-newaz/vaxrank<gh_stars>0 # Copyright (c) 2016-2018. Mount Sinai School of Medicine # # 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/LICENS...
StarcoderdataPython