id
stringlengths
1
8
text
stringlengths
6
1.05M
dataset_id
stringclasses
1 value
259151
import sys sys.path.append('./codes/fine-tuning') from codes.bias_rv.BiasRV import biasRV import pandas as pd from codes.sentiment_analysis import SentimentAnalysis model_checkpoint='./models/fine-tuning/pytorch_imdb_fine_tuned/epoch5.pt' bert_config_file='./models/uncased_L-12_H-768_A-12/bert_config.json' vocab_fi...
StarcoderdataPython
4968923
<gh_stars>0 #! /user/bin/env python from load_samples import * from NeuralNet import * import numpy as np import random import os, struct from array import array as pyarray from numpy import append, array, int8, uint8, zeros if __name__ == '__main__': INPUT = 28*28 OUTPUT = 10 net = NeuralNet([INPUT, 40, OUTPUT...
StarcoderdataPython
203765
<gh_stars>0 from sqlalchemy import Column, String, Boolean from database import Base class Shortcode(Base): __tablename__ = "shortcodes" shortcode = Column(String(20), primary_key=True, unique=True) target_url = Column(String(1024)) is_random = Column(Boolean()) def __init__(self, shortco...
StarcoderdataPython
9735991
class Solution(object): def evalRPN(self, tokens): """ :type tokens: List[str] :rtype: int """ num_stack = [] for i in range(len(tokens)): if '+' == tokens[i] or '-' == tokens[i] or '*' == tokens[i] or '/' == tokens[i]: num0 = num_stack.po...
StarcoderdataPython
332571
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available. Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. BK-BASE 蓝鲸基础平台 is licensed under the MIT License. License for BK-BASE 蓝鲸基础平台: ---------------------------------------------...
StarcoderdataPython
6525472
<reponame>proudzhu/algorithms import unittest from algorithms.dynamic_programming.lcs import lcs class TestLCS(unittest.TestCase): """ Tests the Longest Common Subsequence of several strings """ def test_lcs(self): str1 = "BANANA" str2 = "ABA" str3 = "BCAD" str4 = "NN...
StarcoderdataPython
3375340
<filename>pandas/prepare/extract_tle.py #DAV: satellite visible area: https://stackoverflow.com/a/54990129 import skyfield from skyfield import api from skyfield.positionlib import ICRF, Geocentric from skyfield.constants import (AU_M, ERAD, DEG2RAD, IERS_2010_INVERSE_EARTH_FLATTENING...
StarcoderdataPython
5153171
# Copyright 2019 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 to in writing, ...
StarcoderdataPython
6660199
<reponame>LihaoLixue/face_classification<gh_stars>0 # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'EmotionRecongnition_UI.ui' # Created by: PyQt5 UI code generator 5.11.3 # @Time : 2019/5/25 18:29 # @Author : WuXian # @Email : <EMAIL> # @blog : wuxian.blog.csdn.net # @Soft...
StarcoderdataPython
5078731
<gh_stars>10-100 from . import metrics from .utils import pad_or_truncate import numpy as np def evaluate( references, estimates, win=1*44100, hop=1*44100, mode='v4', padding=True ): """BSS_EVAL images evaluation using metrics module Parameters ---------- references : np.ndar...
StarcoderdataPython
195796
<filename>pybaseball/analysis/projections/marcels/age_adjustment.py from typing import Optional from pandas import isnull def age_adjustment(age: Optional[float]) -> float: """ Marcel age adjustment :param age: numeric :return: float """ if isnull(age): return float("nan") a...
StarcoderdataPython
6561682
from contextlib import contextmanager from ctypes import cdll from ctypes.util import find_library import datetime import functools import hashlib import hmac import os import socket import sqlite3 import tempfile import threading import unittest import urllib.parse import uuid import httpx from sqlite_s3_query impor...
StarcoderdataPython
1674081
from django.db import models class ClanModel(models.Model): order = models.IntegerField(primary_key=True) name = models.CharField(max_length=64) cell_count = models.IntegerField(default=0) is_in_council = models.BooleanField(default=False)
StarcoderdataPython
3277489
<filename>Series/Cubes.py<gh_stars>10-100 # Cubes.py """ Cubes takes the number of elements Num, and returns a list containing "Num" numbers in the Cube series. Pre-Conditions - Num should be an integer >=1. Cubes(Num = 5) --> Standard function call Output --> Num numbers are returned in series starting from 1^3 u...
StarcoderdataPython
6585103
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import os import time import io import yaml from maro.simulator import Env from maro.rl import ActorProxy, SimpleLearner, AgentMode from examples.ecr.rl_formulations.common.state_shaper import ECRStateShaper from maro.utils import Logger, conver...
StarcoderdataPython
12839484
<reponame>mouradmourafiq/data-analysis __author__ = 'mourad'
StarcoderdataPython
6524986
#!/usr/bin/env python3 # # Copyright (c) 2020, The OTNS Authors. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright # notice, th...
StarcoderdataPython
8127052
<gh_stars>1-10 # Generated by Django 2.2.11 on 2020-03-12 10:40 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("applications", "0013_auto_20200311_1124"), ] operations = [ migrations.AddField( model_name="baseapplication", ...
StarcoderdataPython
11346930
# -*- coding: utf-8 -*- class Config: ''' default config ''' DEBUG=False, TESTING=False, BCRYPT_LEVEL=13, APP_NAME='Flask-Mongo', SECRET_KEY="__SECRET_KEY__", WTF_CSRF_ENABLED=True, TEMPLATE_FOLDER="%(PROJECT_PATH)s/template", STATIC_FOLDER="%(PROJECT_PATH)s/static", STA...
StarcoderdataPython
379377
<reponame>SeitaBV/ts-forecasting-pipeline<gh_stars>1-10 import logging from datetime import datetime, timedelta import pandas as pd import pytest import pytz from statsmodels.tools.sm_exceptions import MissingDataError from timetomodel import forecasting from timetomodel.tests import utils as test_utils """ Test the...
StarcoderdataPython
1692623
from setuptools import find_packages, setup if __name__ == "__main__": setup( name="docs_snippets", author="Elementl", author_email="<EMAIL>", license="Apache-2.0", url="https://github.com/dagster-io/dagster/tree/master/examples/docs_snippets", classifiers=[ ...
StarcoderdataPython
4952851
from flask_jwt_oidc.exceptions import AuthError from flask import current_app from flask_restplus import Resource from app.extensions import api from app.config import Config def register_routes(app): # Set URL rules for resources app.add_url_rule('/', endpoint='index') # Healthcheck endpoint @api.r...
StarcoderdataPython
5045227
<reponame>CaioHRombaldo/PythonClasses from playsound import playsound playsound('rsc/ACruelAngelThesis.mp3')
StarcoderdataPython
4895219
<gh_stars>1-10 # import libraries and functions required for the code run import acitoolkit.acitoolkit as aci import sys import acitoolkit from acitoolkit import Session, Credentials, Node, ExternalSwitch from Credential import apic_dc_ip1, apic_dc_ip2, apic_dc_ip3,apic_username, apic_password from Legend impor...
StarcoderdataPython
12841703
<reponame>codepointtku/viuhka-flask from flask import Blueprint, render_template, request, redirect, Response, url_for from flask_login import login_required, current_user from flask_wtf.csrf import validate_csrf from app.services.models.service ...
StarcoderdataPython
6688030
<reponame>Harmon758/Harmonbot from discord.ext import commands import collections import csv import sys from utilities import checks sys.path.insert(0, "..") from units.runescape import get_ge_data, get_item_id, get_monster_data, UnitOutputError sys.path.pop(0) def setup(bot): bot.add_cog(RuneScape(bot)) class R...
StarcoderdataPython
1753362
import cv2 import mediapipe as mp import time import tkinter from KeyboardControl import keyboardControl from PositionDetect import positionDetector class handDetector(): def __init__(self, mode = False, maxHands = 1, detectionConf = 0.6, trackConf = 0.7): self.mpHands = mp.solutions.hands self.han...
StarcoderdataPython
1839523
import pytest from django.test import TestCase from django.test import override_settings import ozpcenter.api.custom_field_type.model_access as model_access from ozpcenter.models import CustomFieldType from tests.ozpcenter_api import fixtures @pytest.mark.integration @pytest.mark.fast @override_settings(ES_ENABLED=F...
StarcoderdataPython
205275
<gh_stars>1-10 # NOT_RPYTHON """ The 'sys' module. """ from _structseq import structseqtype, structseqfield import sys def excepthook(exctype, value, traceback): """Handle an exception by displaying it with a traceback on sys.stderr.""" # Flush stdout as well, both files may refer to the same file try: ...
StarcoderdataPython
11255343
# Copyright (c) 2015 Hewlett-Packard Development Company, L.P. # # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LIC...
StarcoderdataPython
5087427
<reponame>carderne/descarteslabs-python<filename>descarteslabs/common/workflows/outputs/__init__.py from .mimetype_to_proto import mimetype_to_proto, mimetype_to_field_name from .format_to_mimetype import user_format_to_mimetype, field_name_to_mimetype from .user_destination_options import user_destination_to_proto fr...
StarcoderdataPython
6438285
<reponame>eatyofood/Phyme import pandas as pd from Phyme import Phyme import pretty_errors pd.set_option('display.max_colwidth',None) ph = Phyme() def rhyme(word='',only_perfect=False,r_frame=False,return_output=True): ''' TAKES: word : (str) enter a word you want to find rhymes. if left blank it w...
StarcoderdataPython
6459270
import copy import json from datetime import datetime, timedelta from animal_case import animalify from grant.email.subscription_settings import get_default_email_subscriptions from grant.user.models import User, user_schema, db from mock import patch from ..config import BaseUserConfig from ..test_data import test_u...
StarcoderdataPython
5099156
<filename>main.py import logging import os import sys from logging import DEBUG from os import curdir, getenv, path from sys import exit import requests as re from flask import (Flask, abort, flash, jsonify, redirect, render_template, request, session) from flask_cors import CORS from kiteconnect im...
StarcoderdataPython
6445719
#! coding:utf-8 """ trackmasterapp.py Created by 0160929 on 2016/09/29 16:36 """ import os __version__ = '0.1' import sys from PySide.QtGui import * from PySide.QtCore import * from track_controller import TrackController class TrackMasterApp(QWidget): def __init__(self, parent=None): ...
StarcoderdataPython
4967836
import pathlib from typing import NamedTuple, NewType, Tuple, List, Union from enum import Enum from collections.abc import Sequence, Mapping USV = int Marker = int VirtualKey = int class Context(Sequence): Item = Union[USV, Marker] def __init__(initial: str): pass def __del__(self): pa...
StarcoderdataPython
9680232
# Escreva um programa que pergunte a quantidade de KM percorridos por um carro alugado e a # quantidade de dias pelos quais ele foi alugado. Calcule o preço a pagar, # sabendo que o carro custa R$ 60 por dia e R$ 0,15 por KM rodado dias = int(input('Quantos dias alugados? ')) km = int(input('Quantos KM rodados? ')) ac...
StarcoderdataPython
124967
<reponame>drh4kor/webformhax from selenium import webdriver from selenium.webdriver.firefox.firefox_binary import FirefoxBinary loginURL='http://10.10.1.20/cgi-bin/login.cgi' binaryPath='/usr/bin/firefox' binary = FirefoxBinary(binaryPath) driver = webdriver.Firefox(firefox_binary=binary) driver.implicitly_wait(60) ...
StarcoderdataPython
5069050
import curses from curses import panel import os import textwrap # Can you believe how lame curses.textpad is? It has emacs bindings so the user needs to know ^G to use it. # Re-engineering the wheel it is. class InputWindow(object): def __init__(self, stdscr, prompt="Enter text:"): self.stdscr = stdscr ...
StarcoderdataPython
1954203
<reponame>andersgs/pyjstat<gh_stars>0 # -*- coding: utf-8 -*- """pyjstat is a python module for JSON-stat formatted data manipulation. This module allows reading and writing JSON-stat [1]_ format with python, using data frame structures provided by the widely accepted pandas library [2]_. The JSON-stat format is a sim...
StarcoderdataPython
9625040
<reponame>zooliet/tensorflow_exercises<gh_stars>0 #!/usr/bin/env python # pip install sklearn import sys sys.path.append('./') sys.path.append('../../') from lab_utils import ( tf, os, np, plt, logger, ap, BooleanAction, debug, toc, auto_increment ) ap.add_argument('--epochs', type=int, default=10, help='nu...
StarcoderdataPython
5131123
<reponame>zhiyiYo/SSD from .ssd import SSD from .loss import SSDLoss from .dataset import VOCDataset, CustomDataset from .train_pipeline import TrainPipeline from .eval_pipeline import EvalPipeline
StarcoderdataPython
12860659
<reponame>fossabot/bagua from enum import Enum class Compressor(Enum): NoneCompressor = None Uint8Compressor = "MinMaxUInt8"
StarcoderdataPython
9700524
__author__ = 'dimd' from zope.interface import Interface, Attribute class IBaseProtocolActionsInterface(Interface): """ This interface defines all needed actions to works with our DynamicSession """ def save(): """ Save current object into session storage, this method is a proxy to ...
StarcoderdataPython
1676907
from collections import defaultdict from random import choice pages = [] index = defaultdict(list) # word -> [(page, i), (page, i) ...] with open('sherlock-holmes.txt') as fp: # ~300 words per page, ~10 words per sentence page, lnum, wnum = [], 1, 1 for line in fp: if not line.strip(): ...
StarcoderdataPython
6609658
""" Code for Bayes by Backprop, modified from https://github.com/nitarshan/bayes-by-backprop """ import math import numpy as np import random import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import torch.autograd as autograd class Gaussian(object): def __init__(sel...
StarcoderdataPython
13043
<reponame>pepetox/gae-angular-materialize # Copyright 2013 Google, 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 re...
StarcoderdataPython
162437
<reponame>vikneswaran20/rn import click def validate_range(ctx, param, value): if value[0] >= value[1]: raise click.BadParameter('The given lower range should be lesser than upper range') return value def validate_precision(ctx, param, value): if value is not None and value > 10: raise ...
StarcoderdataPython
3550212
#!/usr/bin/env python3 import asyncio import unittest import logging import stormaudio @asyncio.coroutine def test(): log = logging.getLogger(__name__) def log_callback(message): log.info('Callback invoked: %s' % message) host = '127.0.0.1' port = 14999 log.info('Connecting to Anthem A...
StarcoderdataPython
11380322
# coding=utf-8 import asyncio import functools def set_event(event): print('在回调中设置事件') event.set() async def test(name, event): print('\t{} waiting for event'.format(name)) await event.wait() print('\t{} triggered'.format(name)) async def main(loop): event = asyncio.Event() print('事件开始...
StarcoderdataPython
8161121
# Copyright 2018 Rackspace # 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, softw...
StarcoderdataPython
6402623
<reponame>m-deck/lookml-tools ''' Authors: <NAME> (<EMAIL>) ''' class SimpleBqWriter(): ''' Class that writes dataframe to BigQuery directly (i.e. not via GCS). This is simple to configure, but it is slower than via GCS and it probably mean that you don't have any backups ...
StarcoderdataPython
3204545
from .GAvP import GAvP from .MPNCOV import MPNCOV from .BCNN import BCNN
StarcoderdataPython
3528530
def insertionSort(myList): for i in range(1,len(myList)): key=myList[i] for j in range(0,i): comparator = myList[i-1-j] if key >= comparator: myList[i-j] = key break else: myList[i-j] = comparator if ...
StarcoderdataPython
1769545
<filename>aib/rep/__init__.py """ The "rep" package is responsible for generating reports. """
StarcoderdataPython
11290147
<reponame>NeonJarbas/OVOS-local-backend<filename>ovos_local_backend/database/utterances.py from json_database import JsonDatabaseXDG class UtteranceRecording: def __init__(self, utterance_id, transcription, path): self.utterance_id = utterance_id self.transcription = transcription self.pat...
StarcoderdataPython
9718754
# !/usr/bin/python3 # -*- coding: utf-8 -*- # @Time : 2021/7/19 下午6:06 # @Author : Latent # @Email : <EMAIL> # @File : sequence_label.py # @Software: PyCharm # @class : 类别 """ 字段说明: 1.nick_id ---->数据库自增 2.nick_name 3.nick 4.brand 5.company_name 6.platform """ class Sequence_Label(object): # 产品分类标签 @classmet...
StarcoderdataPython
11343703
<gh_stars>0 #%% import keras2onnx from tensorflow import keras import tensorflow as tf import onnx model = keras.models.load_model('fcn.h5') print(model.name) onnx_model = keras2onnx.convert_keras(model, model.name) temp_model_file = 'fcn.onnx' onnx.save_model(onnx_model, temp_model_file) # %% from tensorflow import...
StarcoderdataPython
3225762
<filename>IMU/VTK-6.2.0/Examples/Annotation/Python/cubeAxes.py<gh_stars>1-10 #!/usr/bin/env python # This example demonstrates the use of vtkCubeAxesActor2D to indicate # the position in space that the camera is currently viewing. The # vtkCubeAxesActor2D draws axes on the bounding box of the data set # and labe...
StarcoderdataPython
1793061
<filename>src/datareader.py import csv SEPARAT0R = '\t' class DataReader(): """Reads the text from input file. """ def __init__(self, input_file): super(DataReader, self).__init__() self._input_file = input_file def read_data(self): texts = [] scores = [] wi...
StarcoderdataPython
211278
<gh_stars>0 from fastapi import APIRouter, Depends from app import schemas from app.models import Demo from app.utils.paginator import Pagination, PaginationResult router = APIRouter() @router.get("/demo", response_model=PaginationResult[schemas.DemoDetail], tags=["Animal"]) async def list_demos(p: Pagination = Dep...
StarcoderdataPython
9723689
<filename>server/auvsi_suas/views/teams.py """Teams view.""" import json import logging from auvsi_suas.models.takeoff_or_landing_event import TakeoffOrLandingEvent from auvsi_suas.models.uas_telemetry import UasTelemetry from auvsi_suas.proto import interop_api_pb2 from auvsi_suas.views.decorators import require_logi...
StarcoderdataPython
6535298
import os import argparse import tensorflow as tf from random import shuffle parser = argparse.ArgumentParser() parser.add_argument('--file_dir', type=str, required=True, help='Base folder containing the data') parser.add_argument('--list_file', type=str, required=True, help='F...
StarcoderdataPython
5018754
from django import forms from django.db.models import fields from .models import * from django.contrib.auth.forms import UserCreationForm class Registration(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username','email','<PASSWORD>','<PASSWORD>'] class PatientForm(for...
StarcoderdataPython
4994534
<filename>lifecycle_test_library/src/lifecycle_test_library/lifecycle_test_library.py<gh_stars>0 from __future__ import print_function #ROS Imports import rospy import actionlib from rosgraph import Master, MasterError from rospy.msproxy import MasterProxy from rosservice import get_service_list #Python Imports from...
StarcoderdataPython
3492109
<gh_stars>0 import numpy as np import matplotlib import matplotlib.pyplot as plt from danpy.sb import dsb from danpy.useful_functions import save_figures,is_number from scipy import signal import numdifftools as nd import scipy as sp from params import * # from animate import * def LP_filt(filter_length, x): """ Fin...
StarcoderdataPython
6476877
<reponame>riyazudheen/py-fqn-decorators<gh_stars>0 import warnings warnings.warn( 'This module was renamed to `asynchronous` due to adding `async`' ' keyword in python 3.7', PendingDeprecationWarning ) from .asynchronous import * # isort:skip
StarcoderdataPython
12828102
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
StarcoderdataPython
3436195
<reponame>MareSeestern/VineLeafDisease # -*- coding: utf-8 -*- import numpy as np import cv2 cascade = cv2.CascadeClassifier('cascade.xml') # lesen des Classifiers img = cv2.imread('example.jpg') # lesen des Bildes gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # konvertieren in Schwarz-Weiß leaf = cascade.detectM...
StarcoderdataPython
8105804
<reponame>Eiphodos/SwinSemanticSegmentation _base_ = [ '../_base_/models/upernet_vit_mae.py', '../_base_/datasets/ade20k.py', '../_base_/default_runtime.py', '../_base_/schedules/schedule_160k.py' ] model = dict( backbone=dict( image_size=224, dim=1024, depth=12, heads=12, ...
StarcoderdataPython
3319864
""" test the slip correction factor calculation """ import pytest from particula import u from particula.util.knudsen_number import knu from particula.util.slip_correction import scf def test_slip_correction(): """ test the slip correction factor calculation the slip correction factor is approximately ...
StarcoderdataPython
6620888
<reponame>dgerod/behavior_tree_learning import time import py_trees as pt from behavior_tree_learning.core.sbt.world import World from behavior_tree_learning.core.sbt.behavior_tree import BehaviorTreeStringRepresentation from behavior_tree_learning.core.sbt.node_factory import BehaviorNodeFactory class ExecutionParam...
StarcoderdataPython
6531337
from zoneinfo import ZoneInfo # Note: must pip install tzdata from datetime import datetime, timedelta, timezone def current_time_zone(): "Returns the current time zone of the computer as a timezone object." return datetime.now().astimezone().tzinfo def now_utc(): "Returns the current time as a time zone-aware ...
StarcoderdataPython
9711329
<filename>Validation/RecoTrack/python/MultiTrackValidator_cff.py import FWCore.ParameterSet.Config as cms from DQMServices.Core.DQM_cfg import * DQMStore.collateHistograms =cms.untracked.bool(True) from Validation.RecoTrack.MultiTrackValidator_cfi import * from SimTracker.TrackAssociation.LhcParametersDefinerForTP_cfi...
StarcoderdataPython
258045
<filename>DGFit/DustGrains.py #!/usr/bin/env python # Started: Jan 2015 (KDG) # Updated to include better diagnoistic plots when run (Mar 2016 KDG) """ DustGrains class dust grain properties stored by dust size/composition """ from __future__ import print_function import glob import re import math import numpy as np...
StarcoderdataPython
11209992
""" Database router for event logging """ from . import app_settings class EventLogRouter: privacy_model = "privacyanonymised" def _route_model(self, model): """ Route to log table for all gdpr actions. Except for the PrivacyAnonymised, which needs to be in main db. """ ...
StarcoderdataPython
1620680
<filename>conans/client/generators/virtualenv.py import os import platform import textwrap from jinja2 import Template from conans.client.tools.oss import OSInfo from conans.model import Generator sh_activate_tpl = Template(textwrap.dedent(""" #!/usr/bin/env sh {%- for it in modified_vars %} export CON...
StarcoderdataPython
1659484
import xml.etree.ElementTree as xmlet from pathlib import Path import numpy as np import craamvert.utils.iso_time as time from astropy.io import fits from craamvert.instruments.sst import SST_FITS_FILE_NAME from craamvert.utils import SST_INSTRUMENT, OBJECTS_NOT_FROM_SAME_INSTRUMENT, CONCATENATED_DATA, INVALID_FILE_N...
StarcoderdataPython
5051137
from enum import Enum import random class Moves(Enum): """Enum of the set of possible moves the agent is allowed to perform""" Idle = 0 Right = 1 DownRight = 2 Down = 3 DownLeft = 4 Left = 5 UpLeft = 6 Up = 7 UpRight = 8 LightPunch = 9 MediumPunch = 10 HeavyPunch = 1...
StarcoderdataPython
1757308
""" Tests for all async use cases. Currently we're not supporting completion of them, but they should at least not raise errors or return extremely strange results. """ async def x(): argh = await x() #? argh return 2 #? int() x() a = await x() #? a async def x2(): async with open('asdf') as ...
StarcoderdataPython
3312971
import json import subprocess import sys class Api: def getAllKinds(self): apiKindList = [] command = "kubectl api-resources" commandOutput = subprocess.run(command.split(), stdout=subprocess.PIPE) isNamespaced = None for result in commandOutput.stdout.decode('...
StarcoderdataPython
1783563
import click import requests import pandas from io import StringIO import re import os class CurrencyCode(click.ParamType): name = 'symbol' def convert(self, value, param, ctx): if value.isalpha(): return value.upper() self.fail('%s is not a valid symbol' % value, param, ctx) cl...
StarcoderdataPython
3205362
from utils import * from sklearn.linear_model import Perceptron from sklearn.datasets import make_classification def test_mnist(): trX, trY, teX, teY = load_mnist() # get 2 class data and label train_datas = [] train_labels = [] test_datas = [] test_labels = [] for x in range(trX.shape[0]...
StarcoderdataPython
9684516
from setuptools import setup requirements = [ 'opencv-python', 'Pillow', 'scipy', 'pygame', 'numpy', 'tqdm' ] setup( name='text_renderer', version='0.0.6', description="Generate Mjsynth text data", packages=['text_renderer'], package_data={'text_renderer': [ 'data/...
StarcoderdataPython
1635391
<gh_stars>0 import numpy as np import random def generate_binary(n): bin_arr = range(0, int(np.power(2,n))) bin_arr = [bin(i)[2:] for i in bin_arr] max_len = len(max(bin_arr, key=len)) bin_arr = [i.zfill(max_len) for i in bin_arr] return bin_arr def local_space(initial,agents): pos = [random.choice(i...
StarcoderdataPython
11258652
<gh_stars>0 def build_kde_parameters_matrix(jsons_list): """Contructs the list of good QAOA input parameters from jsons provided.""" good_params_matrix = [] for json in jsons_list: good_params = json["good_params"] good_params_matrix = good_params_matrix + good_params return good_params_...
StarcoderdataPython
11336817
import epicbox epicbox.configure( profiles=[ epicbox.Profile('python', 'czentye/matplotlib-minimal') ] ) files = [{'name': 'main.py', 'content': b'x = input(); print(x); y = input(); print("Hi " + y)'}] limits = {'cputime': 10, 'memory': 64} result = epicbox.run('python', 'python3 -u main.py', stdin=b'...
StarcoderdataPython
6638454
<reponame>Yu-Group/adaptive-wavelets<gh_stars>10-100 import torch from torch import nn, optim from torch.nn import functional as F import numpy as np from tqdm import tqdm import torch.utils.data as data_utils from features import downsample import pickle as pkl import models class neural_net_sklearn(): ""...
StarcoderdataPython
3469479
<gh_stars>1-10 import uuid from decimal import Decimal import pytest from django.urls import reverse_lazy from getpaid.exceptions import ( LockFailure, ChargeFailure ) from pytest import raises from getpaid_przelewy24.types import Currency, BuyerData pytestmark = pytest.mark.django_db url_api_operate = reve...
StarcoderdataPython
9766426
import math import numpy as np import torch def bitreversal_permutation(n): """Return the bit reversal permutation used in FFT. Parameter: n: integer, must be a power of 2. Return: perm: bit reversal permutation, numpy array of size n """ m = int(math.log2(n)) assert n == 1 <...
StarcoderdataPython
5135926
<reponame>hscspring/TheAlgorithms-Python import re import locale import pnlp pcomp = re.compile(r'[⿰⿱⿲⿳⿴⿵⿶⿷⿸⿹⿺⿻]') NEED_PRON = ["kMandarin", "kCantonese", "kKorean", "kJapaneseOn", "kVietnamese"] ########## Pronunciation ########## def get_pron_rawdict(fp: str): lines = pnlp.read_lines(fp) dct ...
StarcoderdataPython
11382547
#!/usr/bin/python3 # -*- coding: UTF-8 -*- from functools import wraps from common import Logging from common.Logging import get_generic_logger from common.YamlConfig import AppConfig from lib.bottle import Bottle, request, response from ..AppRunner import AppRunner from ..RemoteServerApi import get_server_config, ge...
StarcoderdataPython
8172608
from distutils.core import setup setup( name = 'gcs-inspector', packages = ['gcs-inspector'], version = '0.1', license='MIT', description = 'A small library used for monitoring public instances of Google Cloud Storage using Google Service Account', author = '<NAME>', author_email = '<EMAIL>', url = 'htt...
StarcoderdataPython
1787090
<gh_stars>0 import factory from democracy.factories.hearing import SectionFactory from democracy.models import SectionPoll, SectionPollOption class SectionPollFactory(factory.django.DjangoModelFactory): class Meta: model = SectionPoll exclude = ('option_count',) option_count = 3 section...
StarcoderdataPython
4967649
from file.CSVConverter import CSVConverter from file.FileWriter import FileWriter
StarcoderdataPython
11376225
<reponame>markahix/pydrachem from .Equilibration import Run_Equilibration from .Production import Run_Production
StarcoderdataPython
1980415
import boto3 import itertools import json from . import awslambda, utils from .combine_dict import combine_dict def get_stack_ids(): CloudFormation = boto3.client("cloudformation") def stack_filter(stack_id): resources = CloudFormation.list_stack_resources(StackName=stack_id) for resource in...
StarcoderdataPython
9780783
<reponame>xuezhong/Paddle # Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 ...
StarcoderdataPython
3548570
import csv import xlrd import xlsxwriter import re import datetime import common import os INPUT_FILE = "finance_old.xls" OUTPUT_FILE = os.path.join(common.OUTPUT_FOLDER, 'financial_plans') VARIABLES_FILE = 'sheet1.csv' DATE_FILE = "finance_date.txt" DIGITS_ROW_NUMBER = 6 STARTING_ROW = 7 SHEET_NUMBER = 1 DATE_RE = re...
StarcoderdataPython
6439929
from .async_monitor import Monitor from .events import RiderStateEventArgs, RiderEnteredWorldEventArgs, RiderTimeSyncEventArgs, IncomingMeetupEventArgs, \ RiderChatEventArgs, RiderRideOnEventArgs, ZwiftEvent, ZwiftEventArgs from .zwift_messages_pb2 import ServerToClient, ClientToServer, Chat, RideOn, PlayerState, M...
StarcoderdataPython