id
stringlengths
1
8
text
stringlengths
6
1.05M
dataset_id
stringclasses
1 value
1737965
from confluent_kafka import Consumer conf = {'bootstrap.servers': 'kafka-1:9092', 'group.id': 'ch3_consumer_group'} consumer = Consumer(conf) consumer.subscribe(['ch3_topic_1']) try: while True: msg = consumer.poll(timeout=1.0) if msg is None: continue elif msg.error(): ...
StarcoderdataPython
5132213
<reponame>skearnes/color-features<filename>oe_utils/shape/overlap.py """ OEShape overlap utilities. """ __author__ = "<NAME>" __copyright__ = "Copyright 2014, Stanford University" __license__ = "3-clause BSD" import collections import numpy as np from openeye.oechem import * from openeye.oeshape import * from oe_ut...
StarcoderdataPython
4923310
<gh_stars>1-10 # -*- coding: utf-8 -*- import sys import logging.handlers import os import re # noinspection PyUnresolvedReferences import apiclient import httplib2 from oauth2client.service_account import ServiceAccountCredentials from flask import Flask, request from flask_restful import Resource, Api, abort from fl...
StarcoderdataPython
8056872
<gh_stars>0 """main code for tree searching using - using minimax search - MCTS? 22.11.2020 - @yashbonde"""
StarcoderdataPython
156851
<reponame>tlambert03/anyfft<filename>anyfft/reikna/_version.py # file generated by setuptools_scm # don't change, don't track in version control version = "0.1.dev1+ga7b326d.d20210618" version_tuple = (0, 1, "dev1+ga7b326d", "d20210618")
StarcoderdataPython
6514900
########################################################################### # Imports ########################################################################### # Standard library imports import argparse import time as time import numpy as np import matplotlib.pyplot as plt from matplotlib import path # L...
StarcoderdataPython
11232068
<reponame>sakost/kutana<filename>kutana/backends/vkontakte/__init__.py from .extensions import VkontaktePluginExtension from .backend import Vkontakte __all__ = ["VkontaktePluginExtension", "Vkontakte"]
StarcoderdataPython
9651999
from .token import Token class Scanner: def __init__(self, text): self.text = text self.start = 0 self.current = 0 self.tokens = [] def at_end(self): return self.current >= len(self.text) def advance(self): self.current += 1 return self.text[self.c...
StarcoderdataPython
367236
# Uploads the following to Storage: # - (A version of) CBS catalog (TODO: Decide if/what/how) # - Kerncijfers wijken and buurten # - Nabijheidsstatistieken # - Bevolkingsstatistieken per pc4 # - Mapping pc6huisnummer tot buurten and wijken # TODO: Creates a `CBS helper` dataset in BQ, with 4 (/5?) tables ??? (Concat?)...
StarcoderdataPython
9721001
<reponame>JohnnyHowe/Slow-Engine-Python """ Sample program for the SlowEngine. Shows off basic 2D player movement. No bells or whistles. """ import slowEngine import pygame class Game: player = None def __init__(self): self.player = Player() def run(self): while True: self.r...
StarcoderdataPython
6541062
from flask.ext.restful import fields, marshal from flask import Blueprint as FlaskBlueprint import logging from pouta_blueprints.models import User from pouta_blueprints.forms import SessionCreateForm from pouta_blueprints.server import app, restful sessions = FlaskBlueprint('sessions', __name__) token_fields = { ...
StarcoderdataPython
3237611
<reponame>Jumper78/pyIndego<gh_stars>0 """Classes for states of pyIndego.""" import logging from dataclasses import dataclass, field, is_dataclass from datetime import date, datetime, time, timedelta from typing import List from .const import ( ALERT_ERROR_CODE, DAY_MAPPING, DEFAULT_LOOKUP_VALUE, MOWER...
StarcoderdataPython
1948136
<gh_stars>10-100 from abc import (ABC, abstractmethod) from queue import Queue from ..lib import ( object_name, look_up, deep_map, inverse_deep_map) import noodles try: import ujson as json except ImportError: import json def _chain_fn(a, b): def f(obj): first = a(obj) if first: ...
StarcoderdataPython
8074076
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities from...
StarcoderdataPython
3363119
<reponame>marzy-bn/Leetcode_2022<filename>1929-concatenation-of-array/1929-concatenation-of-array.py class Solution: def getConcatenation(self, nums: List[int]) -> List[int]: p1 = 0 p2 = len(nums) - 1 end = len(nums) while p1 < end: nums.append(nums[p1]) p1 +=...
StarcoderdataPython
5011078
<reponame>enriquecoronadozu/NEP_samples<filename>nanomsg/python/publish-subscribe/publisher.py import nep import time import sys msg_type = "json" # Message type to listen. "string" or "json" node = nep.node("publisher_sample", "nanomsg") # Create a new node conf = node.broker(mode = "one2many") ...
StarcoderdataPython
8066203
<reponame>curtiszki/CYK-character-scrape # csv_read_write.py # Use the CSV module to read and write dictionary files. import re import os.path class CsvReadWrite(object): ''' Class with methods designed around reading from cc_cedict and a designated CSV output file. ''' def __init__(self, inputF...
StarcoderdataPython
8106064
<reponame>pnsaevik/ladim # Testing the nested_gridforce import numpy as np from nested_gridforce import Grid config = dict(grid_args=[]) g = Grid(config) # Two first in fine grid, land, sea # Two next outside, land, sea X = np.array([60, 80, 50, 30]) Y = np.array([40, 30, 50, 20]) print("X, Y = ", X, Y) X1, Y1 = ...
StarcoderdataPython
4868874
from czsc.extend.utils import push_text from datetime import datetime from czsc.extend.analyzeExtend import JKCzscTraderExtend as CzscTrader import traceback import time import datetime import shutil import os from czsc.objects import Signal, Factor, Event, Operate from czsc.data.jq import get_kline import pandas as p...
StarcoderdataPython
4955300
<reponame>z-btc/z-btc-main<filename>test/functional/bsv-pbv-submitblock.py<gh_stars>1-10 #!/usr/bin/env python3 # Copyright (c) 2019 Bitcoin Association # Distributed under the Open BSV software license, see the accompanying file LICENSE. """ We will test the following situation where block 1 is the tip and three block...
StarcoderdataPython
3599934
<reponame>kaka-lin/pycon.tw # -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2016-04-09 03:49 from __future__ import unicode_literals from django.db import migrations, models import sponsors.models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ ...
StarcoderdataPython
5127006
<gh_stars>0 import logging from os import getenv from os.path import dirname, join from typing import Optional from dotenv import load_dotenv def get_logging_level(level: Optional[str]) -> int: if level == 'CRITICAL': return logging.CRITICAL elif level == 'FATAL': return logging.FATAL eli...
StarcoderdataPython
11356834
from datetime import datetime import numpy as np from utils import read_instances, get_cost from best_improvement import grasp, best_improvment from dynamic_cut_stock import bottom_up from greedy import greddy def pipeline(algoritmo, *params): algoritmos = { 'greddy': greddy, 'grasp': grasp, ...
StarcoderdataPython
11238505
<filename>hard-gists/11526013/snippet.py #!/usr/bin/env python import subprocess import itertools import sys from south.migration import all_migrations from south.models import MigrationHistory def get_migrations(): from multiprocessing import Process, Queue queue = Queue() p = Process(target=get_migrations_task...
StarcoderdataPython
1690428
<filename>casino/deck.py<gh_stars>0 import random from collections import deque from itertools import product, chain class Deck: """Creates a Deck of playing cards.""" suites = (":clubs:", ":diamonds:", ":hearts:", ":spades:") face_cards = ('King', 'Queen', 'Jack', 'Ace') bj_vals = {'Jack': 10, 'Queen...
StarcoderdataPython
4939455
<filename>tests/apps/hello/__init__.py #!/usr/bin/env python import time import webify app = webify.defaults.app() # Controllers @app.subapp(path='/') @webify.urlable() def index(req, p): p(u'Hello, world!') @app.subapp() @webify.urlable() def hello(req, p): p(u'<form method="POST">') name = req.params....
StarcoderdataPython
3247575
<gh_stars>1-10 from mDateTime import cDate, cDateDuration; # The rest of the imports are at the end to prevent import loops. def fxConvertFromJSONData(xStructureDetails, xJSONData, sDataNameInError, s0BasePath, dxInheritingValues): if xStructureDetails is None: if xJSONData is not None: raise cJSONDataTyp...
StarcoderdataPython
11327089
from tensorflow.keras.layers import BatchNormalization from tensorflow.keras.layers import Conv2DTranspose from tensorflow.keras.layers import Concatenate from tensorflow.keras.layers import Activation from tensorflow.keras.layers import MaxPool2D from tensorflow.keras.layers import Conv2D from tensorflow.keras.layers ...
StarcoderdataPython
5193004
<filename>transformers/abstract/mixin.py import logging from abc import ABC, abstractmethod # Scientific import pandas as pd # Machine Learning from sklearn.base import TransformerMixin # Local from utilities.container import Spans # ################################################################## # ABSTRACT FEA...
StarcoderdataPython
1721189
<gh_stars>1-10 import numpy as np import pandas as pd class InferredParameter(object): """ """ # Public def __init__(self): self.estimate = None self.bounds = [None, None] self.inclusive = [True, True] self.label = None def __repr__(self): return "Inferr...
StarcoderdataPython
1874193
"""Module to test and flatten a list into a flat list""" def isflat(untyped): """tests if object is a flat set or list. Returns True for other types""" onlyelements = True if isinstance(untyped, (set, list)): for e_temp in list(untyped): if isinstance(e_temp, (set, list)): ...
StarcoderdataPython
8076232
<reponame>Slawomir-Kwiatkowski/fuel_page_parser import requests from lxml import html import matplotlib.pyplot as plt import unicodedata import tkinter as tk from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg from datetime import datetime import os from PIL import Image, ImageTk class MainWindow(tk.Fram...
StarcoderdataPython
6413544
""" Custom exceptions. """ class RecordUnknown(Exception): pass class APIException(Exception): pass
StarcoderdataPython
365699
#!/usr/bin/env python3 """ This is a NodeServer for Wi-Fi enabled Roomba vacuums by fahrer16 (<NAME>) Based on template for Polyglot v2 written in Python2/3 by Einstein.42 (<NAME>) <EMAIL> """ import udi_interface import sys import json from threading import Timer from roomba import Roomba LOGGER = udi_...
StarcoderdataPython
1951982
# -*- coding: utf-8 -*- # Copyright (c) 2014 Docker. # # 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
4969313
<reponame>regisb/richie<filename>tests/apps/courses/test_templates_program_detail.py<gh_stars>0 """ End-to-end tests for the program detail view """ import re from cms.test_utils.testcases import CMSTestCase from richie.apps.core.factories import UserFactory from richie.apps.courses.factories import CourseFactory, Pr...
StarcoderdataPython
3269628
#!/usr/bin/env python3 import argparse import sys from . import loader parser = argparse.ArgumentParser( prog="csgomenumaker", description="Generate a console menu for CSGO." ) parser.add_argument( "file" ) args = parser.parse_args(sys.argv[1:]) loader.Loader(args.file)
StarcoderdataPython
9676262
#!/usr/bin/env python import os import sys try: from setuptools import setup, find_packages except ImportError: from distutils.core import setup, find_packages readme = open('README.rst').read() doclink = """ Documentation ------------- The full documentation is at http://centreonapi.rtfd.org.""" history = ...
StarcoderdataPython
9719479
<reponame>yaelmi3/backslash<gh_stars>10-100 """SCM Info Revision ID: 37bc6a190f Revises: <PASSWORD> Create Date: 2015-10-03 23:08:48.308287 """ # revision identifiers, used by Alembic. revision = '37bc6a1<PASSWORD>' down_revision = '3<PASSWORD>' from alembic import op import sqlalchemy as sa def upgrade(): ##...
StarcoderdataPython
1654522
<reponame>DadeCoderh/starlingx-stagingm<filename>dcmanager/db/api.py # Copyright (c) 2015 Ericsson AB. # 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 # # ...
StarcoderdataPython
12809174
<gh_stars>1-10 # UCF Senior Design 2017-18 # Group 38 import cv2 import unittest import utils.image_man as im GOOD_EXIF = 'tests/images/test_good_exif.JPG' EMPTY_EXIF = 'tests/images/test_empty_exif.JPG' NONEXIF = 'tests/images/test_nonexif_image_format.png' class ImageManipulationTestCase(unittest.TestCase): "...
StarcoderdataPython
88977
<reponame>TJCSec/rcds<gh_stars>0 from textwrap import dedent from typing import Any, Dict, List, Optional import yaml from jinja2 import Environment, PackageLoader, filters jinja_env = Environment( loader=PackageLoader("rcds.backends.k8s", "templates"), autoescape=False, trim_blocks=True, lstrip_block...
StarcoderdataPython
9665825
<reponame>fossabot/autofocus from pathlib import Path import requests BASE_URL = "http://localhost:8000" def test_sample_predict_request(): filepath = Path(__file__).resolve().parents[1] / "gallery" / "raccoons.jpeg" response = requests.post( f"{BASE_URL}/predict", files={"file": open(filepath, "rb"...
StarcoderdataPython
1863186
#!/usr/bin/python # encoding: utf-8 from workflow import web import json import os.path import urllib search_url_tem = 'http://www.wowhead.com/search' list_json = 'data/list.json' faction_icon = 'icon/' image_url_tem = 'http://wow.zamimg.com/images/wow/icons/large/%s.jpg' image_suffix = ".jpg" class WowheadGateway(ob...
StarcoderdataPython
11379666
from .wrapper import Wrapper try: from .gym_wrapper import GymWrapper except: print("Warning: make sure gym is installed if you want to use the GymWrapper.")
StarcoderdataPython
5107005
<gh_stars>1-10 import logging import random import string import pytest import salt.config import salt.loader import salt.states.boto_iot as boto_iot from tests.support.mock import MagicMock, patch boto = pytest.importorskip("boto") boto3 = pytest.importorskip("boto3", "1.2.1") botocore = pytest.importorskip("botocor...
StarcoderdataPython
1825140
<reponame>jawaidss/halalar-web<gh_stars>1-10 from django.conf.urls import url from . import views urlpatterns = [ url(r'^privacy-policy/$', views.PrivacyPolicyView.as_view(), name='legal-privacy_policy'), url(r'^terms-of-service/$', views.TermsOfServiceView.as_view(), name='legal-terms_of_service'), ]
StarcoderdataPython
11224920
a = int(input('Digite a 1° reta: ')) b = int(input('Digite a 2° reta: ')) c = int(input('Digite a 3° reta: ')) if ((b-c) < a < b + c) and ((a - c) < b < a + c) and ((a - b) < c < a + b): if a == b == c: print('E um triangulo equelátero.') elif a == b or b == c or a == c: print('E um triangulo is...
StarcoderdataPython
6636708
# coding: utf-8 """ Cloudbreak API Cloudbreak is a powerful left surf that breaks over a coral reef, a mile off southwest the island of Tavarua, Fiji. Cloudbreak is a cloud agnostic Hadoop as a Service API. Abstracts the provisioning and ease management and monitoring of on-demand clusters. SequenceIQ's Cloud...
StarcoderdataPython
5136755
<gh_stars>100-1000 import imp import marshal import importlib code = ''' print('hello,worldddddddd') ''' def t(): name = 'hello' co = compile(code, name, 'exec') r = marshal.dumps(co) i = 0 for c in r: i+=1 print('0x%02x,'%(c,), end='') if i%16==0: print() p...
StarcoderdataPython
1932848
<gh_stars>0 # encoding: utf-8 ''' @author: allen-jia @file: auth.py @time: 2019/2/20 0020 11:54 @desc: ''' from rest_framework.authentication import BaseAuthentication from rest_framework import exceptions token_list = [ '<KEY>', '<KEY>', ] class TestAuthentication(BaseAuthentication): def authenticate(...
StarcoderdataPython
1817931
<reponame>Manny27nyc/BitcoinArmory ################################################################################ # # # Copyright (C) 2011-2015, Armory Technologies, Inc. # # Distributed under the GNU Affero General...
StarcoderdataPython
5186042
<gh_stars>1-10 from typing import Union from getnet.services.customers import Address from getnet.services.payments.credit import Credit as BaseCredit class Credit(BaseCredit): billing_address: Address def __init__(self, billing_address: Union[Address, dict] = None, **kwargs): self.billing_address =...
StarcoderdataPython
3521865
<reponame>amikey/audio_scripts #!/Users/tkirke/anaconda/bin/python # -*- coding: utf-8 -*- import re,sys,os,codecs from time import sleep from math import sqrt,log from scipy import signal,fft import numpy, matplotlib from lame import * matplotlib.use('qt4agg') import matplotlib.pyplot as plt import warnings def fxn(...
StarcoderdataPython
6481459
from typing import Sequence, Optional import numpy as np from matplotlib.pyplot import Axes import datasets def plot_predictions(data: datasets.BaseDataGenerator, ax_arr: Sequence[Axes], name: str, t_seq: np.ndarray, paths: np.ndarr...
StarcoderdataPython
311318
<gh_stars>10-100 from typing import List, Dict import math import numpy as np from banditpylib.data_pb2 import Feedback, Actions, Context from banditpylib import argmax_or_min_tuple from banditpylib.arms import PseudoArm from banditpylib.learners.mab_fcbai_learner import MABFixedConfidenceBAILearner class Centrali...
StarcoderdataPython
3493759
<gh_stars>1-10 import autocomplete_light from cities_light.models import Country, City from django.contrib.auth.models import User, Group class AutocompleteTaggableItems(autocomplete_light.AutocompleteGenericBase): choices = ( User.objects.all(), Group.objects.all(), City.objects.all(), ...
StarcoderdataPython
292708
<gh_stars>0 import unittest import tempfile import shutil from os import path from pbcore.io import AlignmentSet, ReferenceSet from pbalign.pbalignrunner import PBAlignRunner from test_setpath import ROOT_DIR class Test_PBAlignRunner(unittest.TestCase): def setUp(self): self.rootDir = ROOT_DIR ...
StarcoderdataPython
11241781
<reponame>Trafalcon/Parsr import argparse import os import numpy as np import pandas as pd from sklearn import metrics from sklearn.feature_selection import RFECV from sklearn.svm import SVC from sklearn.tree import DecisionTreeClassifier from sklearn_porter import Porter from imblearn.over_sampling import SMOTE pa...
StarcoderdataPython
8151987
<gh_stars>0 d = {'x':1,'y':2,'z':3} for keys in d: print keys, 'corresponds to',d[keys] print '='*20 names=['anne','beth','george','damon'] ages=[12,45,32,102] for i in range(len(names)): print names[i], 'is', ages[i], 'years old' print '='*20 for name,age in zip(names,ages): print name, 'is', age, 'years old' pr...
StarcoderdataPython
318971
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import unittest from os.path import join as joinpath import ffmpymedia from tests import TEST_FILE_PATH class TestMediaUse(unittest.TestCase): def test_compare_two_files(self): # User1 wants to compare two media files to see if their stream layouts are t...
StarcoderdataPython
179400
<filename>django_react/json_encoder.py # -*- coding: utf-8 -*- # deprecated for now... import json from django.utils.encoding import force_unicode from django.db.models.base import ModelBase class LazyJSONEncoder(json.JSONEncoder): """ a JSONEncoder subclass that handle querysets and models objects. Add y...
StarcoderdataPython
12858058
<reponame>brunosmmm/scoff """Auto-generate custom TextX AST classes.""" import re try: import black except ImportError: black = None GRAMMAR_RULE_REGEX = re.compile( r"([a-zA-Z_]\w*)\s*:(((['\"];['\"])|[^;])+);", re.S ) RULE_MEMBER_REGEX = re.compile( r"([a-zA-Z_]\w*)\s*([?\+\*]?)=\s*([^\s]+)", re.S ...
StarcoderdataPython
3398514
# Placeholder. # Use prepare_contest.py to get an up-to-date version.
StarcoderdataPython
79411
<filename>pplbench/models/utils.py # Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from typing import Tuple import numpy as np import xarray as xr def log1pexp(x: np.ndarray) -> np.ndar...
StarcoderdataPython
1882850
<filename>foiamachine/apps/government/api.py<gh_stars>1-10 from tastypie.resources import ModelResource, Resource, ALL, ALL_WITH_RELATIONS from tastypie import fields from tastypie.authentication import Authentication from tastypie.authorization import Authorization#need?, DjangoAuthorization from apps.government.model...
StarcoderdataPython
3467843
from __future__ import division import sys from time import sleep, time from threading import Event from math import atan2, degrees, hypot try: from inspect import getfullargspec except ImportError: from inspect import getargspec as getfullargspec from .btcomm import BluetoothServer from .threads import Wrap...
StarcoderdataPython
3213833
<reponame>owen198/kslab-atrisk-prediction # coding: utf-8 import matplotlib.pyplot as plt def generate_boxplot(data, title, datasets_small_name): fig = plt.figure(figsize=(8, 6)) bplot = plt.boxplot(data, notch=False, # box instead of notch shape # sym='rs', ...
StarcoderdataPython
5122067
<reponame>MickaelRigault/pysedm #! /usr/bin/env python # -*- coding: utf-8 -*- from glob import glob ################################# # # MAIN # ################################# if __name__ == "__main__": import argparse from pysedm.script.ccd_to_cube import * # ================= # # Optio...
StarcoderdataPython
3461332
<filename>micromagneticmodel/energy/zeeman.py import ubermagutil as uu import discretisedfield as df import ubermagutil.typesystem as ts from .energyterm import EnergyTerm @uu.inherit_docs @ts.typesystem(H=ts.Parameter(descriptor=ts.Vector(size=3), otherwise=df.Field), wav...
StarcoderdataPython
6662037
#! /usr/bin/ python # -*- encoding: utf-8 -*- from utils import config_loop, start_loop, set_ams, display_message config_loop(gui=True) from agent import Agent from messages import ACLMessage from aid import AID class Teste(Agent): def __init__(self, aid): Agent.__init__(self, aid) def on_...
StarcoderdataPython
243756
# -*- coding: utf-8 -*- """ biothings_explorer.dispatcher ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This module contains code that biothings_explorer use to communicate to and \ receive from APIs. It serves as a glue between "apicall" module and "api_output_parser" module. """ from .json_transformer import Transformer clas...
StarcoderdataPython
3451444
""" For a new client: 1) send FULL_DATASET (to erase remaining data) 2) send DIFFERENTIAL for each new live update """ from gtfs_realtime_pb2 import FeedMessage import iso8601 import sys import time import zmq from utils import getVehiclePosition KV6_ZMQ = "tcp://127.0.0.1:6006" sequence = 0 context = zmq.Contex...
StarcoderdataPython
3557998
#This script is intended to find the top and the mid pedestal of the H mod plasma profile for the pre and post processing of the simulation #Developed by <NAME> on 02/03/2020 import numpy as np import matplotlib.pyplot as plt import scipy.optimize as opt import re from max_stat_tool import * # some_file.py import sys...
StarcoderdataPython
9644252
<reponame>BoyanZhou/starstr #!/usr/bin/python # -*- coding: utf-8 -*- import numpy as np def calculate_d_stat(distance_data, individual_index): """ calculate D_stat for each individual """ d_ij = 1.0/(distance_data[:, 3] + 1.0) # record D_stat for each individual individual_d_stat = [0.0]*len(...
StarcoderdataPython
8168044
<gh_stars>10-100 """ Support for Sense Hat LEDs. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/light.sensehat/ """ import logging import voluptuous as vol import homeassistant.helpers.config_validation as cv from homeassistant.components.light import ...
StarcoderdataPython
9639437
<filename>manim_sandbox/utils/import.py from manim_sandbox.utils.functions.calculation import * from manim_sandbox.utils.functions.debugTeX import * from manim_sandbox.utils.functions.ratefunc import * from manim_sandbox.utils.functions.MyClass import * from manim_sandbox.utils.functions.MathTools import * from manim_...
StarcoderdataPython
8028209
# Generated by Django 3.1.7 on 2021-05-03 02:15 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='TargetDomain', fields=[ ('id', models.AutoF...
StarcoderdataPython
6562787
#!/usr/bin/env python from __future__ import print_function, unicode_literals import argparse import ast from datetime import datetime import glob import io import json import os from pkg_resources import Requirement import re import sys import textwrap # Todo: This should use a common omit logic once ci scripts are r...
StarcoderdataPython
287999
# pluto.py # My brother Steven and father Jim collaborated buiding this program # I modified the output - to print the vector and return the string "Done" # === import random.py and statistics.py import random import statistics # === initialize temperatures in a vector that represents n layers of pluto's surface # =...
StarcoderdataPython
1727215
import scipy.stats as spst import scipy.special as spsp import numpy as np from . import opt_abc as opt from . import opt_smile_abc as smile class Cev(opt.OptAnalyticABC, smile.OptSmileABC, smile.MassZeroABC): """ Constant Elasticity of Variance (CEV) model. Underlying price is assumed to follow CEV proc...
StarcoderdataPython
329479
<filename>python/runner.py import argparse import re from sandbox import iterative_placement from sandbox.core import CoreScene from sandbox.explainer import Explainer from sandbox.hunter import Hunter from sandbox.propertyset import PropertySet def run_sample(scene, *props): parser = argparse.ArgumentParser() ...
StarcoderdataPython
5040525
#!env/bin/python3 from termcolor import colored import json import os import sys import zmq import fclient import ffile # client data client = json.dumps({'ip': '', 'port': '', 'serverIP': '', 'serverPort': ''}) client = json.loads(client) context = zmq.Context() socket = context.socket(zmq.REP) socket_send = conte...
StarcoderdataPython
11227631
<gh_stars>1-10 class RewardPerformanceScore(): rewardName = "PerformanceScore" def getReward(self, thisPlayerPosition, performanceScore, matchFinished): reward = - 0.001 if matchFinished: finalPoints = (3 - thisPlayerPosition)/3 reward = finalPoints + performanceScore ...
StarcoderdataPython
9645899
from datetime import datetime import logging import sys import traceback import click import colorama from colorama import Fore, Style from dateutil import tz as dutz import rasterio from . import horizon, KM, sunrise_sunset, sunrise_sunset_details, sunrise_sunset_year colorama.init() logger = logging.getLogger(__p...
StarcoderdataPython
6581091
<reponame>srujanpanuganti/elsa #! /usr/bin/env python from __future__ import division import rospy from math import pi, asin # from geometry_msgs.msg import Twist, Pose # from nav_msgs.msg import Odometry from std_msgs.msg import Int32 import numpy as np import RPi.GPIO as gpio class TickPublisher: def __init__...
StarcoderdataPython
274449
import csv from typing import List def write_dict_to_csv(data, file): csv_columns = list(data[0].keys()) with open(file, "w") as csvfile: writer = csv.DictWriter(csvfile, fieldnames=csv_columns) writer.writeheader() for row in data: writer.writerow(row) def read_csv_to_di...
StarcoderdataPython
9772792
from uzuwiki.settings_static_file_engine import * from commons.file.backends.file_engine_s3 import _put_s3 from logging import getLogger import os import hashlib import mimetypes import tempfile from datetime import datetime logger = getLogger(__name__) def initialize_dirs(wiki_id): _put_s3(STATIC_FILE_S3_PATH["...
StarcoderdataPython
5091881
import sys import re filename = sys.argv[1] # print(filename) with open(filename) as f: lines = f.readlines() no_header = [line for line in lines[1:] if line != '\n'] data = "".join(no_header) # print(data) re_matcher = re.compile('[0-9]+\.[0-9]+\n') rest = data while True: temp = rest.split...
StarcoderdataPython
1726756
"""Script defined to test the paystack class.""" import unittest import httpretty from paystackapi.paystack import Paystack paystack_secret_key = "sk_test_0a246ef179dc841f42d20959bebdd790f69605d8" paystack = Paystack(secret_key=paystack_secret_key) class TestPaystackClass(unittest.TestCase): """Method defined ...
StarcoderdataPython
8011487
<filename>model.py #!/usr/bin/env python # -*- coding: UTF-8 -*- """================================================= @Author :蒋虎成 @Date :2021/9/24 19:12 @Desc :模型训练 ==================================================""" import csv import os from settings import DATACENTER_ID,WORKER_ID,SEQUENCE,color_distance from c...
StarcoderdataPython
3526646
import pathlib import geopandas as gpd THIS_DIR = pathlib.Path(__file__).parent.absolute() PARENT_DIR = THIS_DIR.parent.absolute() DATA_DIR = PARENT_DIR / "data" def main(): zips_df = gpd.read_file(DATA_DIR / 'zips.geojson') hoods_df = gpd.read_file(DATA_DIR / 'hoods.geojson') joined_df = gpd.sjoin(hoods...
StarcoderdataPython
3455955
# https://leetcode.com/problems/maximum-subarray/ # 방법 1 # O(N^2) def maxSubArray(nums): ans = -10 ** 4 for i in range(len(nums)): for j in range(i + 1, len(nums) + 1): ans = max(ans, sum(nums[i:j])) return ans # 방법 2 # O(N) def maxSubArray(nums): total, ans = 0, -10 ** 4 for...
StarcoderdataPython
3499936
import logging from osconfeed import load from frozenjson import * from frozenattr import * logging.basicConfig(level=logging.DEBUG) raw_feed = load() feed = FrozenJSON(raw_feed) print(len(feed.Schedule.keys())) for key, value in sorted(feed.Schedule.items()): print('{:3} {}'.format(len(value), key)) sudeepFroz...
StarcoderdataPython
5190856
<gh_stars>10-100 #!/usr/bin/python # after runing this file you MUST modify nsIdentityinfo.cpp to change the # fingerprint of the evroot import tempfile, os, sys import random import pexpect import subprocess import shutil libpath = os.path.abspath('../psm_common_py') sys.path.append(libpath) import CertUtils dest...
StarcoderdataPython
4898814
from rest_framework import serializers from accounts.models import User from pwuDB.models import Categories, Coupon, Orders, Products class CategoriesSerializer(serializers.ModelSerializer): class Meta: model = Categories fields = '__all__' class CategorySerializerForProduct(serializers.ModelSe...
StarcoderdataPython
4849710
# Python Version: 3.x """ the module for yosupo's Library Checker (https://judge.yosupo.jp) """ import glob import os import pathlib import re import subprocess import sys import urllib.parse from typing import * import requests import onlinejudge._implementation.logging as log import onlinejudge._implementation.tes...
StarcoderdataPython
9702604
<gh_stars>0 # -*- coding: utf-8 -*- import cv2 import os import re #指定する画像フォルダ files = os.listdir('/home/ringo/Prog/StarField/python3/OpenCV/test/') for file in files: jpg = re.compile("jpg") print(file) if jpg.search(file): img = cv2.imread(file) cv2.imshow("img", img) resized = cv...
StarcoderdataPython
1711725
import abc from sparclur._metaclass import Meta from sparclur._renderer import Renderer from sparclur._text_extractor import TextExtractor class Hybrid(TextExtractor, Renderer, metaclass=Meta): """ Abstract class to handle parsers that both render and have text extraction. """ @abc.abstractmetho...
StarcoderdataPython
3410686
<reponame>thinkAmi-sandbox/wsgi_webtest-sample<filename>e.g._get_post_app/get_post_app.py import datetime import cgi import io from jinja2 import Environment, FileSystemLoader # WSGIアプリとして、以下より移植 # https://github.com/thinkAmi-sandbox/wsgi_application-sample class Message(object): def __init__(self, title, handle,...
StarcoderdataPython