id
stringlengths
1
7
text
stringlengths
6
1.03M
dataset_id
stringclasses
1 value
3388702
<reponame>mcarlen/libbiarc PkfName = 'void' KnotType = 'void' NCMP = 0 COMP = 0 coords = [] tangents = [] edges = [] def pkfread(file): global PkfName,KnotType,NCMP,COMP global coords,tangents,edges if file.readline().strip()!='PKF 0.2': print "Not PKF Version 0.2" exit(1) KnotType, PkfName = file.re...
StarcoderdataPython
4812211
<reponame>micahaza/contract-management-api from jcapi.extensions.mail import MailSender from unittest import mock from threading import Thread @mock.patch('smtplib.SMTP_SSL', autospec=True) def test_mail(mail_sender_mock, app): mail_sender_mock.return_value.login = mock.Mock(return_value={}) mail_sender_mock....
StarcoderdataPython
3394040
""" Input __init__. """ try: from spikey.snn.input.ratemap import RateMap from spikey.snn.input.staticmap import StaticMap from spikey.snn.input.rbf import RBF except ImportError as e: raise ImportError(f"input/__init__.py failed: {e}")
StarcoderdataPython
197395
<gh_stars>10-100 import pytest import pandas as pd import dariah @pytest.fixture def dtm(): return pd.DataFrame( [[1, 2, 3], [4, 5, 6], [7, 8, 9]], columns=["AAA", "BBB", "CCC"], index=["a", "b", "c"], ) @pytest.fixture def riddell_topics(): return pd.DataFrame( { ...
StarcoderdataPython
1620198
from modeltranslation.translator import translator, TranslationOptions from mezzanine.conf.models import Setting class TranslatedSetting(TranslationOptions): fields = ("value",) translator.register(Setting, TranslatedSetting)
StarcoderdataPython
118079
""" test_predictor.py Class created to run automated unit testings for the Pico & Placa predictor. The tests are made for the following use-cases: 1. Users are allowed to go outside 2. Users are not allowed to go outside 3. License plate is not valid 4. Date format is incor...
StarcoderdataPython
3207341
import os import random import traceback import discord from discord.ext import commands, tasks GUILD = 384811165949231104 IMG_DIR = './data/server-icons' PLAN_Z = 507429352720433152 def find_file(i): images = os.listdir(IMG_DIR) for img_name in images: if img_name.startswith(str(i)): r...
StarcoderdataPython
4828298
<reponame>EkaterinaLisovec/python_traning1 from model.contact import Contact import random import string import os.path import jsonpickle import getopt #для чтения опций командной строки import sys #чтобы получить доступ к этим опциям try: opts, args = getopt.getopt(sys.argv[1:], "n:f:", ["number of contacts", "fi...
StarcoderdataPython
174412
<filename>setup.py #!/usr/bin/env python """The setup script.""" import os from setuptools import find_packages, setup here = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(here, "requirements.txt"), encoding="utf-8") as requirements_file: requirements = requirements_file.read().splitlines() ...
StarcoderdataPython
1751822
<reponame>iliankostadinov/thinkpython<filename>Chapter14/Exercise_14_2.py<gh_stars>1-10 #!/usr/bin/env python3 """ Write a module that imports anagram_sets and provides two new functions: store_anagrams should store the anagram dictionary in a “shelf”; read_anagrams should look up a word and return a list ...
StarcoderdataPython
1625986
<gh_stars>1-10 #!/usr/bin/python import sdk_common import shutil import os import glob from functools import reduce import json import csv from collections import OrderedDict # Block in charge of licensing class LicenceSetter(sdk_common.BuildStepUsingGradle): def __init__(self, logger=None): super(Licence...
StarcoderdataPython
1670925
from typing import Dict, Any import torch from malib.algorithm.common.loss_func import LossFunc from malib.algorithm.common import misc from malib.utils.episode import EpisodeKey class DDPGLoss(LossFunc): def __init__(self): super(DDPGLoss, self).__init__() def reset(self, policy, configs): ...
StarcoderdataPython
135298
<filename>sickbeard/lib/hachoir_parser/file_system/ntfs.py """ New Technology File System (NTFS) file system parser. Sources: - The NTFS documentation http://www.linux-ntfs.org/ - NTFS-3G driver http://www.ntfs-3g.org/ Creation date: 3rd january 2007 Author: <NAME> """ SECTOR_SIZE = 512 from lib.hachoir_parser ...
StarcoderdataPython
1639407
<reponame>luxuantao/golden-retriever """ Query ES and merge results with original hotpot data. Input: - query file - hotpotqa data - output filename - whether this is for hop1 or hop2 Outputs: - json file containing a list of: {'context', 'question', '_id', 'query', 'json_context'} ...
StarcoderdataPython
198584
<filename>hddcoin/cmds/wallet_funcs.py<gh_stars>1-10 import asyncio import sys import time from datetime import datetime from decimal import Decimal from typing import Callable, List, Optional, Tuple, Dict import aiohttp from hddcoin.cmds.units import units from hddcoin.rpc.wallet_rpc_client import WalletRpcClient fr...
StarcoderdataPython
3393512
import numpy as np from scipy import linalg from ..processing import knee import warnings warnings.filterwarnings("ignore") def wgr_regress(y, X): n, ncolX = X.shape Q,R,perm = linalg.qr(X, mode='economic', pivoting=True) if R.ndim == 0: p = 0 elif R.ndim == 1: p = int(abs(R[0])...
StarcoderdataPython
156915
<gh_stars>0 # coding=utf-8 from collections import defaultdict import threading __author__ = 'nekmo' class Events(defaultdict): def __init__(self): super(Events, self).__init__(list) def propagate(self, event, *args, **kwargs): if not event in self: return for function in self[event]:...
StarcoderdataPython
3256994
<reponame>Mr-TelegramBot/python-tdlib from ..factory import Type class pushMessageContentChatChangePhoto(Type): pass
StarcoderdataPython
99562
# -*- coding: utf-8 -*- """Tests for backoff_utils._backoff""" from datetime import datetime import pytest import backoff_utils.strategies as strategies from backoff_utils._decorator import apply_backoff _attempts = 0 _was_successful = False def when_successful(value): """Update the global ``_was_successful`...
StarcoderdataPython
3273838
""" Utils for testing """ from django.db.models import fields def get_simplified_model(**kwargs): """ Generates a mocked model class Expected kwargs: - `fields`: dict field_name:field_instance that will populate the model fields :returns: InternalSimplifiedModel """ model_fields = { ...
StarcoderdataPython
140390
<reponame>erose1337/versionhelper VERSION = "1.0.0-beta.15" LANGUAGE = "python" PROJECT = "versionhelper" _p = "versionhelper.libvh." API = {_p + "version_helper" : {"arguments" : ("filename str", ), "keywords" : {"directory" : "directory str", ...
StarcoderdataPython
3313653
<reponame>jscpeterson/reminders # Generated by Django 2.2.4 on 2019-08-15 21:28 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('remind', '0001_initial'), ] operations = [ migrations.AlterField( model_name='deadline', ...
StarcoderdataPython
171555
#!/usr/bin/env python3 distro={ } library=[] distro["name"]="RedHat" distro["versions"]=["4.0","5.0","6.0","7.0","8.0"] library.append(distro.copy()) distro["name"]="Suse" distro["versions"]=["10.0","11.0","15.0","42.0"] library.append(distro.copy()) print(library)
StarcoderdataPython
1766374
#!/usr/bin/env python3 class Solution: def search(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ lo, hi = 0, len(nums) - 1 while lo <= hi: mid = (lo + hi) // 2 if nums[mid] == target: return mid ...
StarcoderdataPython
3383315
<filename>feeder/parsers/PT.py import requests, dateutil, arrow from bs4 import BeautifulSoup COUNTRY_CODE = 'PT' def GWh_per_day_to_MW(energy_day_gwh): hours_in_a_day = 24; power_mw = energy_day_gwh / 24 * 1000; return power_mw def fetch_PT(): r = requests.get('http://www.centrodeinformacao.ren.pt/EN/Informa...
StarcoderdataPython
1776918
WINDOW_WIDTH = 1024 WINDOW_HEIGHT = 720 BLACK = (0,0,0) WHITE = (225,225,225)
StarcoderdataPython
72407
from ..._common import block_to_format, str2format from ..._io.input.tough._helpers import write_record def block(keyword): """Decorate block writing functions.""" def decorator(func): from functools import wraps header = "----1----*----2----*----3----*----4----*----5----*----6----*----7----...
StarcoderdataPython
30224
<filename>scripts/supp_fig_C_calc.py import sys sys.path.append("../src") import numpy as np import matplotlib.pyplot as plt import seaborn as sns import C_calculation plt.style.use(['seaborn-deep', '../paper.mplstyle']) """ This script produces Figure S3, which displays a detailed summary of the calculations used ...
StarcoderdataPython
3276174
<reponame>phac-nml/irida-staramr-results import unittest from irida_staramr_results import util class TestUtil(unittest.TestCase): def setUp(self): print("\nStarting " + self.__module__ + ": " + self._testMethodName) def tearDown(self): pass def test_local_to_timestamp(self): "...
StarcoderdataPython
1685682
<reponame>ultimus11/Filed-Test from django.conf.urls import url,include from .views import GETAPIView from .views import CREATEAPIView from .views import UPDATEAPIView from .views import DELETEAPIView urlpatterns = [ url('GET/', GETAPIView.as_view()), url('CREATE/', CREATEAPIView.as_view()), url('UP...
StarcoderdataPython
1608799
# ****************************************************************************** # Copyright 2017-2018 Intel Corporation # # 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.apa...
StarcoderdataPython
1725231
import codecs import orcid_api from lxml import objectify import pprint import os.path import time from config import DATAPATH token='' def getToken(): global token if token=='': token = orcid_api.get_access_token(scope='/read-public', sandbox=False) return token def search_to_file(...
StarcoderdataPython
123554
# Generated by Django 3.0.5 on 2020-05-11 01:56 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] ope...
StarcoderdataPython
3218453
<filename>niceman/support/distributions/tests/test_debian.py # emacs: -*- mode: python; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*- # ex: set sts=4 ts=4 sw=4 noet: # ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## # # See COPYING file distributed along with the niceman p...
StarcoderdataPython
1792052
"""only allow unique keys in key-value store Revision ID: <KEY> Revises: c2aead9ff6d9 Create Date: 2019-03-09 12:12:25.914048 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '<KEY>' down_revision = 'c2aead9ff6d9' branch_labels = None depends_on = None def upg...
StarcoderdataPython
3327553
from __future__ import print_function import os, json, sys import requests from bs4 import BeautifulSoup class Bing: """Scrapper class for Bing""" def __init__(self): pass def get_page(self,query): """ Fetches search response from bing.com returns : result page in html ...
StarcoderdataPython
1749898
<reponame>chrisdunne/hibp import requests import urllib.parse def get(email, key): if isinstance(email, str): return requests.get( f"https://haveibeenpwned.com/api/v3/breachedaccount/{urllib.parse.quote(email)}", headers={"hibp-api-key": key} ).text if isinstance(...
StarcoderdataPython
3340316
<gh_stars>0 import os import sys import shutil import random from tqdm import tqdm from datasets.data_format.voc import VOCDataSet from datasets.data_format.yolo import builder class Project(object): """目录结构 project ├── data.yaml #数据集配置文件 ├── models #网络模型(可以使用下面的脚本自动生成) │ ...
StarcoderdataPython
3348980
from poop.hfdp.command.remote.ceiling_fan import CeilingFan class CeilingFanOnCommand: def __init__(self, ceiling_fan: CeilingFan) -> None: self.__ceiling_fan = ceiling_fan def execute(self) -> None: self.__ceiling_fan.high()
StarcoderdataPython
3362672
<reponame>python-demo-codes/basics # HEAD # DataType - Tuples as return Type with Multiple Returns # DESCRIPTION # Describes multiple returns from functions returned as tuple # Also referred to as destructuring # RESOURCES # def square(x,y): # return (x*x, y*y) # Following line is equivalent to above line ...
StarcoderdataPython
3347595
n, y = map(int, input().split()) l = set([int(input()) for i in range(y)]) for i in range(n): if i not in l: print(i) print(f"Mario got {len(l)} of the dangerous obstacles.")
StarcoderdataPython
1602033
import unittest from unittest_onerror import on_fail def my_fail_handler(testcase, exception=None): print('Hey, test {} failed:\n{}'.format(testcase.id(), exception)) class MyTestCase(unittest.TestCase): @on_fail(my_fail_handler) def test_which_fails(self): self.assertEqual(0, 1) # error wi...
StarcoderdataPython
1654372
<filename>parallel_esn/example/weather_recursive.py import numpy as np import argparse import matplotlib.pyplot as plt from ..esn import ESN from ..utils import to_forecast_form, standardize_traindata, scale_data, unscale_data from ..bo import BO """ Attempts to predict a window of humidities in a recursive manner, pr...
StarcoderdataPython
4823758
from flask import Blueprint workspace = Blueprint('workspace', __name__) @workspace.route('/', methods=['GET']) def get_workspaces(): return []
StarcoderdataPython
108065
<reponame>YangJae96/KMU_Visual-SLAM<gh_stars>0 from . import slam opensfm_commands = [ slam, ]
StarcoderdataPython
199142
<reponame>phlax/abstracts from typing import ( Any, Coroutine, Dict, Generator, List, Optional, Set, Tuple, TypedDict) import aiohttp from . import cve, dependency, typing # Scanner configuration class BaseCVEConfigDict(TypedDict): # non-optional attributes nist_url: str start_year: int clas...
StarcoderdataPython
1748305
<reponame>hydratk/hydratk-ext-datagen # -*- coding: utf-8 -*- """Module for sample XML generation from WSDL/XSD .. module:: datagen.xmlgen :platform: Unix :synopsis: Module for sample XML generation from WSDL/XSD .. moduleauthor:: <NAME> <<EMAIL>> """ """ Events: ------- xmlgen_before_import_spec xmlgen_after_...
StarcoderdataPython
161429
# -*- coding: utf-8 -*- #pylint: disable = missing-docstring, blacklisted-name, unused-argument, invalid-name, line-too-long, protected-access import unittest import re from nltk.tokenize.punkt import PunktSentenceTokenizer, PunktLanguageVars import context #pylint: disable=unused-import from qcrit import textual_fea...
StarcoderdataPython
198586
import numpy as np from preprocess.hierarchical import TreeNodes from preprocess import utils from evaluation.metrics import compute_level_loss from algorithms.MinT import recon_base_forecast from algorithms.ERM import unbiased_recon from algorithms import LSTNet, Optim import torch import torch.nn as nn import math im...
StarcoderdataPython
4811440
<filename>tests/sol/opt/opt_test.py # coding=utf-8 from itertools import product import pytest from hypothesis import given from hypothesis import strategies as st from numpy import array from sol import NetworkCaps from sol import NetworkConfig from sol.opt.app import App from sol.opt.funcs import CostFuncFactory fr...
StarcoderdataPython
139452
<reponame>ishtjot/susereumutep import gi; gi.require_version('Gtk', '3.0') from gi.repository import Gtk def ErrorDialog(self, message): d = Gtk.MessageDialog(self, 0, Gtk.MessageType.WARNING, Gtk.ButtonsType.OK, message) d.run() d.destroy()
StarcoderdataPython
67771
from argparse import Namespace from typing import List, Union from yawast.external.spinner import Spinner from yawast.reporting import reporter from yawast.reporting.enums import Vulnerabilities from yawast.reporting.issue import Issue from yawast.scanner.plugins.evidence import Evidence from yawast.scanner.plugins.ht...
StarcoderdataPython
1735270
import imageio import torch import time from tqdm import tqdm from animate import normalize_kp from demo import load_checkpoints import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation from skimage import img_as_ubyte from skimage.transform import resize import cv2 import os import a...
StarcoderdataPython
3236081
from typing import Callable, List from heuristic.classes import Solution from .handling_cost import handling_cost from .routes import routes from .objective import objective from .routing_cost import routing_cost STATISTICS: List[Callable[[Solution], float]] = [ routes, objective, routing_cost, handli...
StarcoderdataPython
3218762
import pytest import sklearn.decomposition import sklearn.linear_model from numpy.testing import assert_array_equal from sklearn import datasets from sklearn.model_selection import GridSearchCV, StratifiedKFold from sklearn.pipeline import Pipeline from baikal import Model, Input from baikal.sklearn import SKLearnWrap...
StarcoderdataPython
3202141
""" This script checks a scenario for v2.29.0 format and migrates the input tables it to the v2.31.1 format. NOTE: You'll still need to run the archetypes-mapper after this script has run. """ import os import cea import pandas as pd import collections import cea.config import cea.inputlocator from cea.utilities...
StarcoderdataPython
64738
<gh_stars>1-10 # Copyright 2020 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 ...
StarcoderdataPython
20447
<filename>WeIrD-StRiNg-CaSe.py def to_weird_case(string): arr=string.split() count=0 for i in arr: tmp=list(i) for j in range(len(tmp)): if j%2==0: tmp[j]=tmp[j].upper() arr[count] = ''.join(tmp) count+=1 return ' '.join(arr) ''' 一个比较不错的版本 d...
StarcoderdataPython
3216557
<reponame>jpmorgan98/MCDC-TNT<filename>mcdc_tnt/mako_kernels/gpu/advance.py """ Name: Advance breif: inputdeck for MCDC-TNT Author: <NAME> (OR State Univ - <EMAIL>) CEMeNT Date: Dec 2nd 2021 """ import math import numpy as np import numba as nb import pycuda.autoinit import pycuda.driver as drv from pycuda.compiler im...
StarcoderdataPython
1762377
# -*- coding: utf-8 -*- from elasticsearch import Elasticsearch es = Elasticsearch(hosts='192.168.3.11:9299') print(0) index = 'bi_da9ae629609135e55e4af697308f63b4' resp = es.indices.get_mapping(index=index, doc_type='doc') print(1) mappings = resp[index]['mappings']['doc']['properties'] print(2) field_list = mappin...
StarcoderdataPython
1674979
import igl import numpy as np import mpmath as mp import os import argparse import matplotlib.pyplot as plt from conformal_py import * from overload_math import * from render import * from collections import namedtuple from copy import deepcopy import meshplot as meshp import pickle RenderInfo = namedtuple('RenderInfo...
StarcoderdataPython
1726350
<reponame>arshadansari27/blockchain-experiment from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker import pytest from .. import mapper_registry @pytest.fixture(scope="session") def db_engine(): """yields a SQLAlchemy engine which is suppressed after the test session""" ...
StarcoderdataPython
1625522
<gh_stars>0 #!/usr/bin/env python """ Example script to register two volumes with VoxelMorph models. Please make sure to use trained models appropriately. Let's say we have a model trained to register a scan (moving) to an atlas (fixed). To register a scan to the atlas and save the warp field, run: register.py -...
StarcoderdataPython
3259200
<reponame>jernelv/SpecAnalysis import numpy as np import scipy def Der(x,y): """Function for finding first derivative of spectral data. Uses finite differences.""" n=len(x) x2=np.zeros(n-1) y2=np.zeros(n-1) for i in range(n-1): x2[i]=0.5*(x[i]+x[i+1]) y2[i]=(y[i+1]-y[i])/(x[i+1]-x[i]) return(x2,y2) def Der...
StarcoderdataPython
4834728
# -*- coding: utf-8 -*- """ plastiqpublicapi This file was automatically generated by APIMATIC v3.0 ( https://www.apimatic.io ). """ from plastiqpublicapi.models.address import Address class Card(object): """Implementation of the 'Card' model. Debit or Credit Card Attributes: ...
StarcoderdataPython
1747476
<gh_stars>0 # # Simple Python Extension # v 1.0.0 # def init(): global db global cmdMap cmdMap = {"getData": handleGetData} db = _server.getDatabaseManager() def destroy(): _server.trace( "Python extension dying" ) def handleRequest(cmd, params, who, roomId, protocol): if protocol == ...
StarcoderdataPython
4833824
<filename>faa_actuation/nodes/actuation_server.py #!/usr/bin/env python import roslib; roslib.load_manifest('faa_actuation') import rospy import copy import threading import time from faa_actuation import Actuation from faa_actuation.srv import UpdateLed, UpdateLedResponse from faa_actuation.srv import UpdateGate, Upd...
StarcoderdataPython
3287083
<gh_stars>100-1000 import unittest import win32com.client import win32com.test.util import win32com.server.util class Tester: _public_methods_ = ["TestValue"] def TestValue(self, v): pass def test_ob(): return win32com.client.Dispatch(win32com.server.util.wrap(Tester())) class TestException(...
StarcoderdataPython
1624820
# listener.py import asyncio from typing import List, Union class EventListener: def __init__(self, bot): self.bot = bot self.log = bot.log self.pool = bot.pool self.config = bot.config self.registered = False self.loop = asyncio.get_event_loop() def registere...
StarcoderdataPython
3392415
<gh_stars>1-10 import logging import os from pathlib import Path from time import sleep from dotenv import load_dotenv from twython import Twython, TwythonError logging.basicConfig(format="{asctime} : {levelname} : {message}", style="{") logger = logging.getLogger("tweet_followers") logger.setLevel(logging.DEBUG) IS...
StarcoderdataPython
3296542
<reponame>lifehackjim/tantrum # -*- coding: utf-8 -*- """Exceptions and warnings for :mod:`tantrum.api_clients`.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from .. import exceptions class ModuleError(exceptio...
StarcoderdataPython
1610085
<reponame>splunkenizer/splunk_as_a_service_app import os import sys bin_path = os.path.join(os.path.dirname(__file__)) if bin_path not in sys.path: sys.path.insert(0, bin_path) import json import fix_path from base_handler import BaseRestHandler import json from urllib.parse import parse_qs import splun...
StarcoderdataPython
3261815
<reponame>JonarsLi/sanic-ext<filename>tests/extensions/openapi/test_exclude.py from sanic import Blueprint, Request, Sanic, text from sanic_ext.extensions.openapi import openapi from utils import get_spec def test_exclude_decorator(app: Sanic): @app.route("/test0") @openapi.exclude() async def handler0(r...
StarcoderdataPython
1637642
from louqa import app app.run(debug=True, port=8089)
StarcoderdataPython
3369011
""" This file contain a class describing a memory efficient flat index """ import heapq from typing import List, Optional, Tuple from embedding_reader import EmbeddingReader import faiss import numpy as np from tqdm import trange from autofaiss.indices.faiss_index_wrapper import FaissIndexWrapper class MemEfficie...
StarcoderdataPython
157578
import logging from django.apps import AppConfig import large_image logger = logging.getLogger(__name__) class DjangoLargeImageConfig(AppConfig): name = 'django_large_image' verbose_name = 'Django Large Image' default_auto_field = 'django.db.models.BigAutoField' def ready(self): # Set up ca...
StarcoderdataPython
4833000
<reponame>lrahmani/agents-aea # -*- coding: utf-8 -*- # ------------------------------------------------------------------------------ # # Copyright 2018-2019 Fetch.AI Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # ...
StarcoderdataPython
1629220
<reponame>ufo2011/platformio-core # Copyright (c) 2014-present PlatformIO <<EMAIL>> # # 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 # # Unles...
StarcoderdataPython
3266966
import sys import json import uuid import datetime import logging class RedBanjoConfig: def __init__(self): self._logger = logging.getLogger("RedBanjoConfig") with open(sys.argv[1]) as jsonFile: self._config = json.load(jsonFile) self._logger.info("Parsed Config ...........
StarcoderdataPython
126221
import boto3 import botocore def download_data_from_s3(bucket_name, key, dst): try: s3 = boto3.resource('s3') s3.Bucket(bucket_name).download_file(key, dst) except botocore.exceptions.ClientError as e: if e.response['Error']['Code'] == "404": print("The object does not exis...
StarcoderdataPython
1632947
<reponame>sayRequil/qDev<filename>qdev_i.py from pyparsing import * data = open("code.q","r") LBRACE,RBRACE,LPAREN,RPAREN,SEMI,EQUAL = map(Suppress,"{}();=") GROUP = Keyword("$group") ENTRY = Keyword("$enter") PRINT = Keyword("$print") VAR = Keyword("$local") FROM = Keyword("$from") CALLVAR = Keyword("$call...
StarcoderdataPython
1663788
class A: pass (member := A)
StarcoderdataPython
191703
# !/usr/bin/env python # -- coding: utf-8 -- # @Author zengxiaohui # Datatime:4/30/2021 2:04 PM # @File:PIL_utils import cv2 import numpy as np import numpy import matplotlib.pyplot as plt from PIL import Image, ImageDraw, ImageFont from PIL import Image, ImageOps def PIL2cv2(image): """PIL转cv""" return cv2.cv...
StarcoderdataPython
198521
<reponame>Rig0ur/VKAnalysis<gh_stars>10-100 # -*- coding: utf-8 -*- """ @author: migalin @contact: https://migalin.ru @license Apache License, Version 2.0, see LICENSE file Copyright (C) 2018 """ import os from PyQt5 import QtWidgets, QtGui, QtCore from .config import * from .MenuItemWidget import VKMenuItemWidget ...
StarcoderdataPython
36272
from scipy import linalg from sklearn.decomposition import PCA from scipy.optimize import linear_sum_assignment as linear_assignment import numpy as np """ A function that takes a list of clusters, and a list of centroids for each cluster, and outputs the N max closest images in each cluster to its centroids """ def cl...
StarcoderdataPython
54099
class Node: def __init__(self,data): self.data = data self.next = None class LinkedList: def __init__(self): self.head=None def print_llist(self): temp = self.head while temp: print(temp.data) temp=temp.next lli...
StarcoderdataPython
140497
""" Copyright 2017-present, Airbnb Inc. 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, sof...
StarcoderdataPython
47183
import os from argparse import SUPPRESS import numpy as np from pysam import Samfile, Fastafile from scipy.stats import scoreatpercentile # Internal from rgt.Util import GenomeData, HmmData, ErrorHandler from rgt.GenomicRegionSet import GenomicRegionSet from rgt.HINT.biasTable import BiasTable from rgt.HINT.signalProc...
StarcoderdataPython
3265218
# -*- coding: utf-8 -*- """ # -------------------------------------------------------- # @Project: YNet # @Author : panjq # @E-mail : <EMAIL> # @Date : 2020-01-06 08:59:23 # -------------------------------------------------------- """ import numpy as np import tensorflow as tf import math def loss_fun(target, predi...
StarcoderdataPython
3310101
<reponame>chaptergy/clothing-color-changer import numpy as np import cv2 import os.path import warnings import myLogger as log def video_to_images(video_path, max_fps=20, max_size=None): """ Converts a video into a list of images and returns it. If necessary, it lowers the framerate and image size. :param...
StarcoderdataPython
1689991
<filename>setup.py<gh_stars>1-10 from setuptools import setup, find_packages # with open('README.md') as f: # readme = f.read() with open('LICENSE') as f: license = f.read() setup( name="bitmex_trader_bot", version="0.0.1", description="Trade with bitmex bot", # long_description=readme, ...
StarcoderdataPython
1661496
# encoding: utf-8 ''' 组合策略测试 ''' import sys sys.path.append('../../') from vnpy.app.cta_strategy.strategies.strategyMulti import MultiStrategy import argparse import pandas as pd import numpy as np from datetime import datetime from setup_logger import setup_logger setup_logger(filename='logsBackTest/vnpy_{0}.log'.fo...
StarcoderdataPython
3264136
<filename>gitlab_release/python-module/cz_nfc/setup.py<gh_stars>0 from setuptools import setup setup( name='NFC commitizen Custom Bump Map and changelog', version='0.1.0', py_modules=['cz_nfc'], license='MIT', long_description='this is a long description', install_requires=['commitizen', 'gitpy...
StarcoderdataPython
3363467
<reponame>URSec/Kage #!/usr/bin/env python3 import argparse import subprocess from os import path from pathlib import Path from time import sleep import serial from colorama import Fore, Style from elftools.elf.elffile import ELFFile PROJECTS = {'microbenchmark': {'baseline': 'freertos_microbenchmarks_clang', ...
StarcoderdataPython
1742109
# -*- coding: utf-8 -*- # Copyright 2020 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...
StarcoderdataPython
26904
from paraview.simple import * from paraview import coprocessing #-------------------------------------------------------------- # Code generated from cpstate.py to create the CoProcessor. # ParaView 5.4.1 64 bits #-------------------------------------------------------------- # Global screenshot output options imag...
StarcoderdataPython
1791824
<reponame>dek-odoo/python-samples<filename>python exercises/dek_program079.py #!/usr/bin/python # -*- coding: utf-8 -*- #- Author : (DEK) <NAME> # program079: # Please write a program to randomly generate a list with 5 even numbers # between 100 and 200 inclusive. # Hints: # Use random.sample() to generate a...
StarcoderdataPython
3208767
from model.group import Group import random def check_empty_group_list(app, db): if len(db.get_group_list()) == 0: app.group.create(Group(name="TEST GROUP NAME TO CHANGE", header="TEST GROUP HEADER TO CHANGE")) def test_modify_random_group(app, db, check_ui): check_empty_group_list(app, db) mod_...
StarcoderdataPython
4823280
import unittest import oauth class ConsumerTests(unittest.TestCase): def test_basic(self): self.assertRaises(ValueError, lambda: oauth.Consumer(None, None)) self.assertRaises(ValueError, lambda: oauth.Consumer('asf', None)) self.assertRaises(ValueError, lambda: oauth.Consumer(None, 'dasf...
StarcoderdataPython
3310763
<gh_stars>0 #!/usr/bin/env python # -*- coding: utf-8 -*- from pathlib import Path import unittest from shared.utils import get_input from . import solution1, solution2, common from .rescue import RescueMessage SOLUTION_DIR = Path(__file__).parent class TestSolution(unittest.TestCase): module = None input...
StarcoderdataPython