id
stringlengths
1
7
text
stringlengths
6
1.03M
dataset_id
stringclasses
1 value
1664107
<filename>DonkiDirector/DirectorBgnThread.py import time import threading import os from DataAcqThread import DataAcqThread import zmq from DonkiOrchestraLib import CommunicationClass import traceback import socket import multiprocessing from InfoServer import infoServerThread from DataServer import DataServer THREAD...
StarcoderdataPython
3357416
<reponame>kvg/pydm<filename>tests/test_acceptance/example_sge.py from pathlib import Path from dmpy import DistributedMake, get_dm_arg_parser # Pass --dry-run to command line test_args = ['--scheduler', 'sge'] args = get_dm_arg_parser().parse_args(test_args) m = DistributedMake(args_object=args) target = Path(__file...
StarcoderdataPython
195070
<reponame>bytedance/raylink from unittest import TestCase from raylink.util.resource import Machine, ResourceManager class TestResource(TestCase): def setUp(self): cluster_nodes = { 'worker': { 'worker-0': {'cpu': 10}, 'worker-1': {'cpu': 10}, 'w...
StarcoderdataPython
1782174
<gh_stars>0 import sys import yaml from tqdm import tqdm import numpy as np import torch from sync_batchnorm import DataParallelWithCallback from modules.generator import OcclusionAwareGenerator from modules.keypoint_detector import KPDetector from animate import normalize_kp if sys.version_info[0] < 3: raise E...
StarcoderdataPython
1698096
<reponame>cptchloroplast/rosalind c = {'A':71.03711, 'C':103.00919, 'D':115.02694, 'E':129.04259, 'F':147.06841, 'G':57.02146, 'H':137.05891, 'I':113.08406, 'K':128.09496, 'L':113.08406, 'M':131.04049, 'N':114.04293, 'P':97.05276, 'Q':128.05858, 'R':156.10111, 'S':87.03203, 'T':101.04768, 'V':99.06841,...
StarcoderdataPython
77916
<gh_stars>0 from setuptools import setup, PEP420PackageFinder setup( name="cascade", version="0.0.1", packages=PEP420PackageFinder.find("src"), package_data={"cascade.executor": ["data/*.toml"]}, package_dir={"": "src"}, install_requires=["numpy", "pandas", "scipy", "toml", "sqlalchemy"], e...
StarcoderdataPython
4817442
# -*- coding: utf-8 -*- from __future__ import unicode_literals import json from django.contrib import admin from django.utils.safestring import mark_safe from pygments import highlight from pygments.lexers import JsonLexer from pygments.formatters import HtmlFormatter from . import models @admin.register(models.Oc...
StarcoderdataPython
86704
import unittest import plotly.graph_objs as go class TestPlotly(unittest.TestCase): def test_figure(self): trace = {'x': [1, 2], 'y': [1, 3]} data = [ trace ] go.Figure(data=data)
StarcoderdataPython
3392053
<gh_stars>1-10 import unittest from base_test_case import BaseTestCase from pyspark_proxy.ml.linalg import * class MLLinalgTestCase(BaseTestCase): def test_ml_linalg_dense_vector(self): dv = DenseVector([1.0, 2.0]) self.assertEqual(type(dv), DenseVector) def test_ml_linalg_dense_vector_data...
StarcoderdataPython
13582
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('convos', '0004_auto_20150511_0945'), ] operations = [ migrations.AddField( model_name='convothread', ...
StarcoderdataPython
92257
<filename>test_pyreds.py #!/usr/bin/env python import sys import unittest import redis import pyreds.reds as reds db = redis.StrictRedis(db=1) reds.set_client(db) def decode(byte): if sys.version > '3' and type(byte) == bytes: return byte.decode('utf-8') else: return byte class SearchTestCa...
StarcoderdataPython
119052
<gh_stars>10-100 import json import codecs __author__ = 'cmakler' js_directories = [ 'build/bundled/', 'docs/js/', 'docs/playground/code/', '../bh-textbook/code/', '../core-interactives/code/', '../econgraphs/static/js/' ] js_local_directories = [ 'build/bundled/', 'docs/js/', 'do...
StarcoderdataPython
106159
import itertools import traceback import pikepdf from pdf_preflight.issue import Issue class Profile: rules = [] @classmethod def get_preflight_check_text(cls, issues, exceptions): if issues or exceptions: exception_text = f"PDF failed Preflight checks with the following Issues & ex...
StarcoderdataPython
1668478
import os import time from copy import deepcopy from pathlib import Path from typing import List, Optional, cast import hydra import jax import numpy as np import ptvsd import pytorch_lightning as pl import wandb from hydra.utils import instantiate from omegaconf import OmegaConf from pytorch_lightning.loggers import ...
StarcoderdataPython
164520
<reponame>Holaplace/path_to_python name_list = ['Amy','Bob','Candy','Ellen'] print(len(name_list))
StarcoderdataPython
60586
<reponame>cclauss/redis-websocket-api<filename>redis_websocket_api/exceptions.py class APIError(Exception): """Base exception for errors raised by high-level websocket API.""" class MessageHandlerError(APIError): """Decoding or parsing a message failed.""" class RemoteMessageHandlerError(MessageHandlerError...
StarcoderdataPython
61937
<reponame>nachom12/my_portfolio<filename>python_little_things/entrada.py minombre = "NaCho" minombre = minombre.lower() print (minombre) for i in range(100): print(i) break
StarcoderdataPython
131119
# Copyright (c) The PyAMF Project. # See LICENSE.txt for details. """ Tests for the L{array} L{pyamf.adapters._array} module. @since: 0.5 """ try: import array except ImportError: array = None import unittest import pyamf class ArrayTestCase(unittest.TestCase): """ """ def setUp(self): ...
StarcoderdataPython
98710
from qfengine.risk.risk_model import RiskModel from abc import ABCMeta import numpy as np import pandas as pd class CovarianceMatrixRiskModel(RiskModel): __metaclass__ = ABCMeta def __init__(self, universe, data_handler, logarithmic_returns:bool = True, ...
StarcoderdataPython
1624193
''' http://pythontutor.ru/lessons/str/problems/swap_two_words/ Дана строка, состоящая ровно из двух слов, разделенных пробелом. Переставьте эти слова местами. Результат запишите в строку и выведите получившуюся строку. При решении этой задачи не стоит пользоваться циклами и инструкцией if. ''' s = input() space = s....
StarcoderdataPython
4832950
<reponame>dssg/mlpolicylab_fall20_schools3_public import nujson import pandas as pd from schools3.data.datasets.dataset import Dataset from schools3.ml.base.hyperparameters import Hyperparameters from schools3.config.ml.metrics import performance_metrics_config # base model class, which typically wraps around an sklea...
StarcoderdataPython
3311120
# Generated by Django 3.1 on 2020-10-24 07:15 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('experiments', '0011_auto_20201023_0924'), ] operations = [ migrations.AlterField( model_name='experiment', name='statu...
StarcoderdataPython
3326807
from adresseLib import getAdresse import pymysql from config import getMysqlConnection mysql = getMysqlConnection() requete = mysql.cursor() requete.execute('SELECT code, latitude, longitude FROM stations') stations = requete.fetchall() for station in stations: adresse = getAdresse(station[1], station[2]) requ...
StarcoderdataPython
3266515
<reponame>chawel/python-shoper # coding=utf-8 # shoperapi # Copyright 2018 <NAME> # See LICENSE for details. """ E-commerce platform Shoper REST API Wrapper """ __version__ = '1.0.0' __author__ = '<NAME>' __license__ = 'MIT' from .base import ShoperBaseApi from .shoperapi import ShoperWrapper class ShoperClient(S...
StarcoderdataPython
3344585
# coding: utf-8 import types import json import os import subprocess import sys import zipfile import marshal import imp import time import struct import shutil import sys import tempfile from datetime import datetime from xml.etree import ElementTree from xml.dom import minidom def call(*args): try: ret...
StarcoderdataPython
142976
import h5py import numpy as np import os import sys import time usage = ''' driver.py D F N outputfile where D = delay in microseconds between writes F = number of writes between flushes and chunksize N = total number of elements to write outputfile = name of output file ''' def run_...
StarcoderdataPython
1666651
class Template(object): """ a rudimentary replacement for Jinja2. currently in place due to a bug with the typing module. """ def __init__(self, template_string): self._template_string = template_string def render(self, **parameters): chunks = [] iterator = iter(self._...
StarcoderdataPython
1782869
from __future__ import print_function from unittest import TestCase from indexdigest.linters.linter_0164_empty_database import check_empty_database from indexdigest.test import DatabaseTestMixin class TestLinter(TestCase, DatabaseTestMixin): def test_empty_database(self): reports = list(check_empty_dat...
StarcoderdataPython
145308
# -*- coding: utf-8 -*- # Generated by Django 1.11.7 on 2018-10-01 12:05 from __future__ import unicode_literals from django.conf import settings import django.core.validators from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration):...
StarcoderdataPython
3261193
import os from faunadb import query as q from faunadb.objects import Ref from faunadb.client import FaunaClient from faunadb.errors import BadRequest class FaunaWrapper: def __init__(self): url = os.getenv("FAUNA_KEY") self.client = FaunaClient(secret=url) # initialize faunadb client ...
StarcoderdataPython
3230238
from marshmallow import INCLUDE, Schema, fields, post_load, pre_load class Dates: def __init__(self, on_sale=None, foc=None, unlimited=None, **kwargs): self.on_sale = on_sale self.foc = foc self.unlimited = unlimited self.unknown = kwargs class DatesSchema(Schema): onsaleDate...
StarcoderdataPython
58176
import unittest.mock import pytest import requests from lektor_twitter_embed import _init_params, _tweet def _mock_request_valid(url, params): return {"html": "<blockquote..."} def _mock_request_exception(url, params): raise requests.exceptions.HTTPError() _tweet_url = "https://twitter.com/thisstuartlaw...
StarcoderdataPython
164742
<filename>venv/lib/python3.6/site-packages/ansible_collections/cisco/mso/plugins/modules/mso_rest.py #!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2020, <NAME> (@anvitha-jain) <<EMAIL>> # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import abs...
StarcoderdataPython
1669501
<reponame>mia-jingyi/simglucose from simglucose.envs.simglucose_gym_env import DeepSACT1DEnv
StarcoderdataPython
1786475
# -*- coding: utf-8 -*- # Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe.utils.nestedset import NestedSet, get_root_of class SupplierGroup(NestedSet): nsm_parent_field = 'parent_sup...
StarcoderdataPython
64983
<filename>helloworld/cli.py """ command line interface """ from argparse import ONE_OR_MORE, ArgumentParser from colorama import Fore from . import __version__ from .model import User def run(): """ entry point """ parser = ArgumentParser(prog="helloworld", description="some documentation here") ...
StarcoderdataPython
1759862
<gh_stars>0 def read_matrix(is_tet=False): if is_tet: return [ [7, 1, 3, 3, 2, 1], [1, 3, 9, 8, 5, 6], [4, 6, 7, 9, 1, 0], ] else: (rows_count, columns_count) = map(int, input().split(', ')) matrix = [] for row_index in range(rows_count...
StarcoderdataPython
171779
class User(): def __init__(self , Name , userName , username_type , Game , data_dict): self.index = data_dict.getIndex()+1 self.name = Name self.username = userName self.username_type = username_type self.game = Game self.data = data_dict self.data.AddU...
StarcoderdataPython
3222875
<filename>scripts/save_images.py # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved """ Save some representative images from each dataset to disk. """ import random import torch import argparse import hparams_registry import datasets import imageio import torchvision.utils as vutils import os from ...
StarcoderdataPython
4815147
from twisted.web import http from twisted.web.http import HTTPChannel from twisted.internet import reactor, defer import threading from settings import LIMIT_FPS, PASSWORD class BotHandler(http.Request, object): BOUNDARY = "jpgboundary" def get_frame(self): return self.api.recorder.frame def wri...
StarcoderdataPython
1642061
import sys pyt_path = r'C:\Program Files (x86)\IronPython 2.7\Lib' sys.path.append(pyt_path) import clr clr.AddReference('ProtoGeometry') from Autodesk.DesignScript.Geometry import * from Autodesk.Revit.DB import * from Autodesk.Revit.DB.Architecture import * from Autodesk.Revit.DB.Analysis import * doc = __revit__.A...
StarcoderdataPython
1621066
import unittest from datasetio.datasetwriter import DatasetWriter import h5py import os import numpy as np import string import random class TestDatasetWriter(unittest.TestCase): def setUp(self): self.feat_length = 10 self.seq_length = 20 self.buffer_size = 5 self.num_rows = 100 ...
StarcoderdataPython
3381230
<reponame>chrgraham/tcex # -*- coding: utf-8 -*- """Test the TcEx Args Config Module.""" from ..tcex_init import tcex # pylint: disable=W0201 class TestArgsConfig: """Test TcEx Args Config.""" @staticmethod def test_address_get(): """Test args.""" assert tcex.args.tc_token assert...
StarcoderdataPython
3321342
import os scriptPath = os.path.dirname(os.path.abspath(__file__)) os.system('docker build -t urodoz/sailfish-runner-base:1.0 '+scriptPath+'/.')
StarcoderdataPython
4817076
import inspect def find_attributes(clazz): attrs = inspect.getmembers(clazz, lambda a: (not inspect.isroutine(a))) attrs = filter(lambda a: not (a[0].endswith('__')), attrs) attrs = filter(lambda a: a[0].startswith('_' + clazz.__name__), attrs) return attrs def getter(original_class): def add_property(clazz):...
StarcoderdataPython
1646156
<gh_stars>0 """ VERSION """ __version__ = '0.0.2'
StarcoderdataPython
1623078
import numpy as np from rllab.core.serializable import Serializable from rllab.exploration_strategies.base import ExplorationStrategy from sandbox.rocky.tf.spaces.box import Box from sandbox.gkahn.gcg.utils import schedules class GaussianStrategy(ExplorationStrategy, Serializable): """ Add gaussian noise ...
StarcoderdataPython
1793467
<filename>slides/slide_92_ejemplo_grafico.py import streamlit as st import pandas as pd import numpy as np import time import altair as alt from urllib.error import URLError from code.shared_functions import skip_echo def display(): c1, c2 = st.columns([9,1]) c1.title("Ejemplo - gráfico en altair") show_...
StarcoderdataPython
107928
import logging; module_logger = logging.getLogger(__name__) from pathlib import Path import sys, re, subprocess, datetime, collections, itertools, pprint, json from acmacs_base.json import read_json from . import latex from .map import sLabDisplayName # ================================================================...
StarcoderdataPython
3310407
<filename>module.py # -*- coding: utf-8 -*- """ Created on Fri Aug 3 15:07:43 2018 @author: KalcikR """ # from git import Repo import textwrap from reportlab.graphics import shapes from reportlab.lib.colors import PCMYKColor, PCMYKColorSep, Color, black, blue, red, transparent from reportlab.platypus import Paragraph...
StarcoderdataPython
1696359
<reponame>amureki/covidapp from django.contrib import admin from data.models import Summary class SummaryAdmin(admin.ModelAdmin): list_display = ( "id", "confirmed", "deaths", "recovered", "created", "is_latest_for_day", ) list_display_links = ("id", "creat...
StarcoderdataPython
1734190
<reponame>lajarre/euphrosyne<filename>lab/admin/__init__.py from .institution import InstitutionAdmin # noqa: F401 from .object import ObjectGroupAdmin # noqa: F401 from .project import ProjectAdmin # noqa: F401 from .run import RunAdmin # noqa: F401
StarcoderdataPython
1781535
import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = 'very-secret-key' INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'intercom' ] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3'...
StarcoderdataPython
1611612
#!/usr/bin/env python # encoding: utf-8 """ config.py Created by mmiyaji on 2016-07-17. Copyright (c) 2016 <EMAIL>. All rights reserved. """ from views import * def home(request): """ Case of GET REQUEST '/config/' Arguments: - `request`: """ page=1 span = 15 order = "-created_at" ...
StarcoderdataPython
4802932
import os import warnings warnings.filterwarnings('ignore') from pandas.core.series import Series #Data Source import yfinance as yf #Data viz import plotly.graph_objs as go #Interval required 5 minutes df = yf.download(tickers='RELIANCE.NS', period='7d', interval='5m') import numpy as np import p...
StarcoderdataPython
62281
import yaml document = """ "name": "example_app" "version": "1.0.0" "main": "example_app/main.py" "description": "A example structure for building projects cross-platform using kivy" "license": "MIT" "repository": "type": "git" "url": "<EMAIL>:VictorManhani/kivy_build.git" "engines": "python": "3.7.7" ...
StarcoderdataPython
4810873
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jan 26 17:53:42 2018 @author: vicen """ import sys sys.path.append("../../") from topopy import Flow, Grid import numpy as np from scipy.sparse import csc_matrix import matplotlib.pyplot as plt fd = Flow() fd.load_gtiff("../data/in/fd_tunez.tif") thre...
StarcoderdataPython
3209306
<gh_stars>1000+ import numpy as np import tensorflow as tf import lucid.optvis.render as render import itertools from lucid.misc.gradient_override import gradient_override_map def maxpool_override(): def MaxPoolGrad(op, grad): inp = op.inputs[0] op_args = [ op.get_attr("ksize"), ...
StarcoderdataPython
1757930
from pathlib import Path import numpy as np import pytest import aimsprop as ap @pytest.fixture(scope="module") def trajectory(): # 1. Parse a series of FMS90 trajectories that Hayley has run for ethylene trajs = [ ap.parse_fms90(Path(__file__).parent / "test_data" / f"000{x}") for x in [2, 3] ...
StarcoderdataPython
142566
<reponame>Yi-Zoey/adversarial-robustness-toolbox # MIT License # # Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021 # # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated # documentation files (the "Software"), to deal in the Software without ...
StarcoderdataPython
3391497
<filename>tests/unittest/test_package.py """ Test import and versioning of the package. """ def test_import(): """ Test import of the package. """ import nocaselist # noqa: F401 pylint: disable=import-outside-toplevel assert nocaselist def test_versioning(): """ Test import of the packa...
StarcoderdataPython
3364074
<gh_stars>0 import os from flask import Flask ''' To run the application: - under Windows set FLASK_APP=flaskr set FLASK_ENV=development flask run - under Linux: export FLASK_APP=flaskr export FLASK_ENV=development flask run ''' def create_app(test_config=None): # This is the application factory # Create a...
StarcoderdataPython
2277
from . import utils from . import display from . import save from . import FFTW from . import stackregistration __version__="0.2.1"
StarcoderdataPython
4815007
<filename>server/app/__init__.py import os from flask import Flask from flask_migrate import Migrate from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config.from_object(os.environ['APP_SETTINGS']) db = SQLAlchemy(app) migrate = Migrate(app, db) from app import routes, models # noqa: E401,E402,F401
StarcoderdataPython
185246
<reponame>AronYang/flask-base-admin # coding=utf-8 import logging import os from flask import Flask, current_app, jsonify, request from flask_cache import Cache from flask_migrate import Migrate from flask_sqlalchemy import SQLAlchemy from werkzeug.exceptions import (HTTPException, InternalServerError, ...
StarcoderdataPython
147407
from collections import namedtuple from enum import Enum constants = [ "STATES", "STATE_LABELS", "ACTIONS", "REWARDS", "QS", "NEXT_STATES", "NEXT_STATE_LABELS", "COMMAND", "NUM_EXP", "TIMESTAMP", "INPUT_SIZE", "NEURONS", "USE_BATCH_NORM", "USE_LAYER_NORM", "ACTIVATION_LAST", "NUM_COMPONENTS", "NUM_ACTIONS...
StarcoderdataPython
3239667
<gh_stars>0 """ This function is used to convert the passed video file into a audio file for further processing. """ def extract_audio(video_file_name, audio_output_file=audio.mp3, *args, **kwargs): """ #TODO - Fill this with the documentation of the code. i.e. the docstring. - Accomadate fo...
StarcoderdataPython
117943
# Reference : https://bigdatatinos.com/2016/02/08/using-spark-hdinsight-to-analyze-us-air-traffic/ import pyspark from pyspark import SparkConf from pyspark import SparkContext from pyspark.sql import SQLContext import atexit sc = SparkContext('local[*]') sqlc = SQLContext(sc) atexit.register(lambda: sc.stop()) imp...
StarcoderdataPython
1777884
# -*- coding: utf-8 -*- """@file isclose.py Provides an implementation of the @c isclose() function This function is found in the @c numpy library starting with version 1.7.0. The MSEAS @c numpy library version is 1.5.1. @author <NAME> (<EMAIL>) """ import numpy def isclose(a, b, rtol=1e-05, atol=1e-08): r"""...
StarcoderdataPython
1763477
import pytest from keras.utils.test_utils import layer_test from keras.utils.test_utils import keras_test from keras import layers @keras_test def test_sine_relu(): for epsilon in [0.0025, 0.0035, 0.0045]: layer_test(layers.SineReLU, kwargs={'epsilon': epsilon}, input_shape=(2, 3, 4)) ...
StarcoderdataPython
3302293
<gh_stars>0 from requests_html import HTMLSession session = HTMLSession() # TODO: # - https://oddspedia.com/ # - https://www.oddsportal.com/ def oddschecker(url): # Example: https://www.oddschecker.com/football/english/championship/brentford-v-fulham/winner response = session.get(url) container = respo...
StarcoderdataPython
1771829
# Generated by Django 2.2.13 on 2020-09-17 01:03 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('library', '0020_auto_20200904_1200'), ] operations = [ migrations.AddField( model_name='bookversio...
StarcoderdataPython
1643910
<reponame>rheinwerk-verlag/planning-poker from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from django.core.asgi import get_asgi_application import planning_poker.routing application = ProtocolTypeRouter({ 'http': get_asgi_application(), 'websocket': Aut...
StarcoderdataPython
1796794
#831162.py from graphics import * def makeWindow(size): return GraphWin("Collection of patches", size*100, size*100) def main(): size, myColours = getInputs() win = makeWindow(size) displayAndMovePatches(win, size, myColours) # triangle function for penultimate patch def triangle(win ,p1, p2, p3, co...
StarcoderdataPython
182350
# RT - NickName Panel from __future__ import annotations from discord.ext import commands import discord from rtlib.common.json import loads from rtutil.utils import is_json, replace_nl from rtutil.content_data import ContentData from rtutil.panel import extract_emojis from core import Cog, RT, t from data import...
StarcoderdataPython
1755339
#!/usr/bin/env python3 """Today Holiday? Uses third party library holidays. `pip install holidays` """ import holidays from datetime import date def main() -> str: """Determine if today is a US Holiday.""" today = date.today() us_holidays = holidays.UnitedStates(years=today.year) today_holiday = to...
StarcoderdataPython
192129
<gh_stars>0 # Generated by Django 2.2 on 2020-06-07 14:14 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('rate', '0005_project_account'), ] operations = [ migrations.CreateModel( name='Review...
StarcoderdataPython
3368172
<reponame>izzatnadzmi/ConcentricTubeRobot """ Simulate a CTR following a 3D trajectory Author: <NAME> Adapted from code by Python Robotics, <NAME> (daniel-s-ingram) """ from math import cos, sin import numpy as np import time import sys sys.path.append("../") sys.path.append("./ConcentricTubeRobot/") import matplotl...
StarcoderdataPython
3322133
<gh_stars>0 class NTI_Elev: def __init__(self, name, age, sex): self.name = name self.age = age self.sex = sex def __str__(self): return f"NTI eleven heter {self.name}, de är {self.age} år gammal och är en {self.sex}." def return_name(self): return self.name c...
StarcoderdataPython
1643743
<reponame>TUDelft-CITG/Hydraulic-Infrastructure-Realisation """Test package.""" import shapely.geometry import simpy import openclsim.core as core import openclsim.model as model import openclsim.plugins as plugins from .test_utils import assert_log def test_delay_plugin(): """Test the delay plugin.""" sim...
StarcoderdataPython
199941
<filename>u_base/u_file.py #!/usr/bin/python # -*- coding: utf-8 -* # file function import os import time import json import re import urllib.parse import requests from PIL import Image from concurrent.futures import ThreadPoolExecutor, wait, ALL_COMPLETED import u_base.u_log as log __all__ = [ 'convert_window...
StarcoderdataPython
3289257
<reponame>rszeto/click-here-cnn import lmdb import os import sys import math import numpy as np import argparse from PIL import Image from multiprocessing import Pool import datetime from google.protobuf import text_format import scipy.ndimage import skimage.transform BASE_DIR = os.path.dirname(os.path.abspath(__file...
StarcoderdataPython
1752338
import numpy as np #import scipy.stats import random import sys import tables from scipy import sparse def zscore(mat, return_unzvals=False): """Z-scores the rows of [mat] by subtracting off the mean and dividing by the standard deviation. If [return_unzvals] is True, a matrix will be returned that can b...
StarcoderdataPython
1683918
<filename>src/server/endpoints/quidel.py from flask import Blueprint from .._config import AUTH from .._query import execute_query, QueryBuilder from .._validate import check_auth_token, extract_integers, extract_strings, require_all # first argument is the endpoint name bp = Blueprint("quidel", __name__) alias = Non...
StarcoderdataPython
140072
<filename>ooobuild/lo/form/tabulator_cycle.py # coding: utf-8 # # Copyright 2022 :Barry-Thomas-Paul: Moss # # 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/licens...
StarcoderdataPython
1628206
<gh_stars>0 ######################################################################################### # Copyright (c) <2012> # # Author: <NAME> (<EMAIL>) # # International Institute of Information Technology, Hyderabad, India. ...
StarcoderdataPython
1602587
<filename>metr/tests/test_db.py<gh_stars>0 import os import uuid import pytest import sqlite3 from metr.db import migrate, get_points, set_point TEST_DB = '/tmp/test-db-' + str(uuid.uuid4()) + '.sqlite' @pytest.fixture() def conn(): conn = sqlite3.connect(TEST_DB) migrate(conn) yield conn print("tea...
StarcoderdataPython
165337
<filename>ondevice/core/exception.py """ Some exception classes for the ondevice client """ class _Exception(Exception): def __init__(self, *args, **kwargs): Exception.__init__(self, *args) self.msg = args[0] for k,v in kwargs.items(): setattr(self, k, v) class ConfigurationErr...
StarcoderdataPython
3289910
<reponame>joyfulflyer/billboard-reader import sys import billboard import sqlite3 import datetime import time def connect(): print('connecting to db') sys.stdout.flush() conn = sqlite3.connect('charts.db') return conn def getCursor(conn): sys.stdout.flush() c = conn.cursor(...
StarcoderdataPython
128819
<filename>23/aoc23-2-parallel.py<gh_stars>0 import pyximport pyximport.install() from aoc23 import do_it_parallel with open("data.sample2.txt", "r") as fh: board = fh.readlines() board = [i.rstrip() for i in board] do_it_parallel(board)
StarcoderdataPython
3327851
<gh_stars>1-10 import pytest import sys import logging from pypika_orm import Manager, Model, fields BACKEND_PARAMS = { 'aiomysql': ('aiomysql://root@127.0.0.1:3306/tests', {'maxsize': 2, 'autocommit': True}), 'aiopg': ('aiopg://test:test@localhost:5432/tests', {'maxsize': 2}), 'aiosqlite': ('aiosqlite:/...
StarcoderdataPython
1700349
<gh_stars>0 #!/usr/bin/python3 import re, sys from matplotlib import pyplot plotSlope = False def centeredMovingAverage(values, order): if (order % 2) != 1: raise ValueError('Order has to be an odd number!') result = [] for i in range(len(values)): s = values[i] n = 1 for j...
StarcoderdataPython
89020
from getratings.models.ratings import Ratings class NA_Quinn_Top_Aatrox(Ratings): pass class NA_Quinn_Top_Ahri(Ratings): pass class NA_Quinn_Top_Akali(Ratings): pass class NA_Quinn_Top_Alistar(Ratings): pass class NA_Quinn_Top_Amumu(Ratings): pass class NA_Quinn_Top_Anivia(Ratings): pass ...
StarcoderdataPython
1619130
<gh_stars>1-10 """ This module defines the class QueryPharos which connects to APIs at http://www.uniprot.org/uploadlists/, querying reactome pathways from uniprot id. """ __author__ = "" __copyright__ = "" __credits__ = [] __license__ = "" __version__ = "" __maintainer__ = "" __email__ = "" __status__ = "Prototype" ...
StarcoderdataPython
3342187
class Node: def __init__(self, val): self.val = val self.ln = None self.rn = None def __repr__(self): return "Node=({}, ln={}, rn={})".format( self.val, self.ln, self.rn) def get_bfs_alt(root, level, level_dict): if not root: return if level not in...
StarcoderdataPython
3357243
# Copyright 2016-2020 Blue Marble Analytics 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 ag...
StarcoderdataPython
19602
<reponame>Sanghyun-Hong/NLPProjects<filename>Project1/cl1_p1_wsd.py import numpy as np import operator # SHHONG: custom modules imported import json import random import itertools from math import pow, log from collections import Counter import os import sys sys.stdout = open(os.devnull, 'w') """ CMSC723 / INST725 / ...
StarcoderdataPython
86921
<reponame>tkrajina/gpxchart<filename>make_examples.py<gh_stars>1-10 import subprocess class Cmd: def __init__(self, output_file, description, params): self.output_file = output_file self.description = description self.params = params cmds = [ Cmd("simple.png", "Simple", ""), Cmd("smoothed.png", "With smoothe...
StarcoderdataPython
175750
from .choices import valid_extensions def validate_file_extension(value): import os from django.core.exceptions import ValidationError ext = os.path.splitext(value.name)[1] # [0] returns path+filename extensions = valid_extensions if not ext.lower() in extensions: raise ValidationError('U...
StarcoderdataPython
3253254
<reponame>Baduit/ScriptGUIfier import json import os import subprocess import tkinter as tk from tkinter import ttk class ListOption: def __init__(self, parent_widget, json_conf: json): self.literal = json_conf["literal"] if "literal" in json_conf else "" self.name = json_conf["name"] if "name" in json_conf else...
StarcoderdataPython