id
stringlengths
1
265
text
stringlengths
6
5.19M
dataset_id
stringclasses
7 values
1780225
<gh_stars>1000+ import os import sys from examples.iql import mujoco_finetune as iql from rlkit.core import logger from rlkit.testing import csv_util def test_iql(): logger.reset() # make tests small by mutating variant iql.variant["algo_kwargs"]["start_epoch"] = -2 iql.variant["algo_kwargs"]["num_e...
StarcoderdataPython
105405
<reponame>Ratgor/iLikeit-voting-platform from django.db import models # Create your models here. # RTG: example from http://v1k45.com/blog/modern-django-part-3-creating-an-api-and-integrating-with-react/ # RTG: example from http://v1k45.com/blog/modern-django-part-4-adding-authentication-to-react-spa-using-drf/ ...
StarcoderdataPython
1704244
import sys import os import tkinter as tk __dir__ = os.path.dirname(__file__) sys.path.insert(0, os.path.join(__dir__, '../..')) import suzu.tktool.filepathentry as filepathentry if __name__ == '__main__': app = tk.Tk() fpath = filepathentry.Saveas(app) # operation # set def set_action(): ...
StarcoderdataPython
3212742
import os from pyelliptic.openssl import OpenSSL def randomBytes(n): try: return os.urandom(n) except NotImplementedError: return OpenSSL.rand(n)
StarcoderdataPython
3278151
import os, sys, subprocess, shutil sys.path.append(os.path.dirname(__file__) + "/../lib") from test_helper import create_virtenv, run_test ENV_NAME = "pytest_test_env_" + os.path.basename(sys.executable) ENV_DIR = os.path.abspath(ENV_NAME) SRC_DIR = os.path.abspath(os.path.join(ENV_NAME, "src")) PYTHON_EXE = os.path....
StarcoderdataPython
3356489
# model model = Model() i1 = Input("op1", "TENSOR_FLOAT32", "{4}") # a vector of 4 float32s i2 = Output("op2", "TENSOR_FLOAT32", "{4}") # a vector of 4 float32s model = model.Operation("EXP", i1).To(i2) # Example 1. Input in operand 0, input0 = {i1: # input 0 [3.0, 4.0, 5.0, 6.0]} output0 = {i2: # output 0 ...
StarcoderdataPython
95037
alist = ['bob', 'alice', 'tom', 'jerry'] # for i in range(len(alist)): # print(i, alist[i]) print(list(enumerate(alist))) for data in enumerate(alist): print(data) for i, name in enumerate(alist): print(i, name)
StarcoderdataPython
56334
<filename>tests/integration/resources_permissions/test_webhooks_resources.py # -*- coding: utf-8 -*- # Copyright (C) 2014-2017 <NAME> <<EMAIL>> # Copyright (C) 2014-2017 <NAME> <<EMAIL>> # Copyright (C) 2014-2017 <NAME> <<EMAIL>> # Copyright (C) 2014-2017 <NAME> <<EMAIL>> # Copyright (C) 2014-2017 <NAME> <<EMAIL>> # Th...
StarcoderdataPython
1746845
<reponame>SciGaP/DEPRECATED-Cipres-Airavata-POC<gh_stars>0 import os import string import math import re import subprocess def getProperties(filename): propFile= file( filename, "rU" ) propDict= dict() for propLine in propFile: propDef= propLine.strip() if len(propDef) == 0: con...
StarcoderdataPython
1723744
<gh_stars>1-10 # modified from Kristen's code ## assumes k=2 class set-up ## p_in = [p_in_1, p_in_2] def create_affiliation_model_temp(average_node_degree, lambda_block_parameter, dispersion_parameter_vect, class_size_...
StarcoderdataPython
3354394
<reponame>parada3desu/foxy-key-broker import random from src.contexts.kms.cryptokeys.domain.entities.CryptoKeyId import CryptoKeyId from src.contexts.kms.cryptokeys.domain.entities.CryptoKeyPayload import CryptoKeyPayload from src.contexts.kms.cryptokeys.domain.repositories.CryptoKeyRepository import CryptoKeyReposito...
StarcoderdataPython
3294889
#!/usr/bin/env python # Copyright (c) 2011 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Selects the appropriate scraper for Chrome.""" def GetScraper(version): """Returns the scraper module for the given version....
StarcoderdataPython
3252380
<reponame>PaulGureghian1/Rainbow_HAT<gh_stars>1-10 #!/usr/bin/env python import time #import blinkt from rainbowhat import rainbow as blinkt blinkt.set_clear_on_exit() step = 0 while True: if step == 0: blinkt.set_all(128,0,0) if step == 1: blinkt.set_all(0,128,0) if step == 2: ...
StarcoderdataPython
170068
from bravado_core.spec import Spec from bravado_types.config import Config from bravado_types.data_model import (ModelInfo, OperationInfo, ParameterInfo, PropertyInfo, ResourceInfo, ResponseInfo, SpecInfo) from bravado_types.extract import get...
StarcoderdataPython
85114
# -*- coding: utf-8 -*- from numpy import array, pi from scipy.linalg import solve def solve_EEC(self): """Compute the parameters dict for the analytical equivalent electrical circuit cf "Influence of the Number of Pole Pairs on the Audible Noise of Inverter-Fed Induction Motors: Radial Force Waves a...
StarcoderdataPython
3305275
<filename>pydatatool/crowdhuman/crowdhuman_eval/demo.py from .common import * from tqdm import tqdm from multiprocessing import Process,Queue import numpy as np import math from .utils.infrastructure import compute_JC def commom_process(func, data, nr_procs, *args): total = len(data) stride = math.ceil(total/...
StarcoderdataPython
3361150
#! /usr/bin/env python import math import rospy import tf import tf2_ros from sensor_msgs.msg import LaserScan def callback2(laserData): #function for determining laser distance at determined angle # print len(msg.ranges) try: if lidar_angle == 500: return lidar_angle_new = int...
StarcoderdataPython
157076
import rospy from std_msgs.msg import Float64 from rospy import Subscriber from common.architectural.Singleton import Singleton class RAMSensor(metaclass=Singleton): __ram_sub: Subscriber __ram_percentage: float = 0.0 def __init__(self): self.__ram_sub = rospy.Subscriber('/ram_usage', Float64, sel...
StarcoderdataPython
1649319
<filename>omop_cdm/datalab_to_prepared_source.py import logging import json import os import argparse import csv import hashlib import sys try: from mapping_classes import InputClass except ImportError: sys.path.insert(0, os.path.abspath(os.path.join(os.path.split(__file__)[0], os.path.pardir, "src"))) from m...
StarcoderdataPython
59561
from __future__ import annotations from typing import Dict, Final, Literal, Set, Union import pylox.lox_types as lt import pylox.token_classes as tc from pylox.token_classes import TokenType as tt import pylox.lox_class as lc import pylox.functions as fn import pylox.lox_builtins as lb # TODO: Consider moving some of...
StarcoderdataPython
160225
<reponame>mikealgj/pulumi-digitalocean<gh_stars>10-100 # coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** 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, Mapp...
StarcoderdataPython
108479
# Copyright 2020 <NAME>, <NAME>, <NAME> # # 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 a...
StarcoderdataPython
1773426
from .BuiltTeam import BuiltTeam from .BuiltUnit import BuiltUnit from .BuiltClass import BuiltClass from .BuiltWeapon import BuiltWeapon from .BuiltItem import BuiltItem from .RankedSupport import RankedSupport
StarcoderdataPython
3215115
class Articles: ''' Articles class that determines the instance of new articles ''' def __init__(self,id,name,author,title,description,url,urlToImage,publishedAt,content): self.id = id self.name = name self.author = author self.title = title self.description = d...
StarcoderdataPython
84635
class Solution: def getSmallestString(self, n: int, k: int) -> str: def toChar(n): return chr(97 + n - 1) ans = [''] * n i = 0 while i < n: # how many spaces left to fill? left = n - i if k < left: # you got `left` spac...
StarcoderdataPython
23432
import os from flask_unchained import AppConfig class Config(AppConfig): WEBPACK_MANIFEST_PATH = os.path.join( AppConfig.STATIC_FOLDER, 'assets', 'manifest.json') class ProdConfig: # use relative paths by default, ie, the same host as the backend WEBPACK_ASSETS_HOST = '' class StagingConfig(P...
StarcoderdataPython
4828010
# ---------------------------------------------------------------------------- # Copyright (c) 2020, QIIME 2 development team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file LICENSE, distributed with this software. # -----------------------------------------------------...
StarcoderdataPython
4835255
<reponame>chrisseto/pyjwe class PyJWEException(Exception): pass class MalformedData(PyJWEException): pass class MalformedHeader(MalformedData): pass class UnsupportedOption(PyJWEException): pass class UnsupportedAlgorithm(UnsupportedOption): pass class UnsupportedEncryption(UnsupportedOpti...
StarcoderdataPython
3242851
class Tarea: def __init__(self, args = None, resultados = None): if args is None: args = {} if resultados is None: resultados = {} self.args = args self.resultados = resultados
StarcoderdataPython
1790881
import pytest from tape import Tape def test_get_content_of_non_empty_tape(): tape = Tape('B', ['a', 'b', 'X', 'B'], ['a', 'b']) assert tape.get_content() == 'a' def test_get_content_of_empty_tape(): tape = Tape('B', ['a', 'b', 'X', 'B'], []) assert tape.get_content() == 'B' def test_get_content_of_...
StarcoderdataPython
4834191
<gh_stars>0 try: from typing import ClassVar from tkinter import Toplevel, ttk from time import sleep except ImportError as err: exit(err) class SongMenu(Toplevel): def __init__(self: ClassVar, parent: ClassVar) -> None: super().__init__(parent) # expose variables to this class ...
StarcoderdataPython
30824
<filename>nerddiary/user/user.py """ User model """ from __future__ import annotations from datetime import tzinfo import pytz from pydantic import BaseModel, PrivateAttr, validator from pydantic.fields import Field from ..poll.poll import Poll from ..primitive.timezone import TimeZone from ..report.report import R...
StarcoderdataPython
3282473
__author__ = 'chris' """ Package for two way communication between nodes. Primarily used for buyer-vendor communication. """
StarcoderdataPython
3370526
<gh_stars>1-10 """Fetch official PATCO feed.""" import logging import requests from bs4 import BeautifulSoup from FeedSource import FeedSource DEVPAGE_URL = 'http://www.ridepatco.org/developers/' FILE_NAME = 'PortAuthorityTransitCorporation.zip' LOG = logging.getLogger(__name__) class Patco(FeedSource): """Fe...
StarcoderdataPython
3233630
<reponame>zjjott/html def ensure_utf8(s): """ unicode to ascii u'\u554a'->'\xe5\x95\x8a' """ if not isinstance(s, basestring): return str(s) if isinstance(s, unicode): return s.encode("u8") return s def ensure_unicode(s): """ ascii to unicode '\xe5\x95\x8a'->u'\...
StarcoderdataPython
157735
#!/usr/bin/env python import os import shutil import sys src, dst = sys.argv[1:] if os.path.exists(dst): if os.path.isdir(dst): shutil.rmtree(dst) else: os.remove(dst) if os.path.isdir(src): shutil.copytree(src, dst) else: shutil.copy2(src, dst)
StarcoderdataPython
3268983
import os from setuptools import setup, find_packages def read(file_name): return open(os.path.join(os.path.dirname(__file__), file_name)).read() setup( name="fate-of-dice", version_config=True, setup_requires=['setuptools-git-versioning'], author="<NAME>", author_email="<EMAIL>", descri...
StarcoderdataPython
179425
<reponame>zevaverbach/epcon """ This module takes care of a lot of user related things. It's a good place to put validators and user management functions/classes """ import os RANDOM_USERNAME_LENGTH = 10 def generate_random_username(): """Returns random username of length set by RANDOM_USERNAME_LENGTH""" ...
StarcoderdataPython
1680622
# Generated by Django 3.2.4 on 2021-07-27 13:44 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('property', '0001_initial'), ] operations = [ migrations.AlterModelOptions( name='property', options={'verbose_name': 'Proper...
StarcoderdataPython
65363
# 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, software # distributed under the...
StarcoderdataPython
1709915
<reponame>ktncktnc/SpaceNet_Off_Nadir_Solutions import argparse import os import numpy as np import pandas as pd from numpy.random.mtrand import RandomState from sklearn.model_selection import KFold def get_id(f): return "_".join(f.rstrip(".tif").split("_")[-2:]) def get_nadir(f): return int(f.split("_")[2...
StarcoderdataPython
3384591
# DO NOT ERASE from tethys_datasets.utilities import get_dataset_engine, get_spatial_dataset_engine from tethys_wps.utilities import get_wps_service_engine, list_wps_service_engines
StarcoderdataPython
1722282
"""Third party Python libraries. Third party libraries are placed here when they are not available on the platform by normal means. FlashAirMusic is a service and not a library. It is intended to be installed through the platform's packaging system (e.g. RPM files). Because of this some dependencies of FlashAirMusic ...
StarcoderdataPython
1605728
<reponame>trowa88/commstr from rest_framework import serializers from rest_framework.exceptions import PermissionDenied from rest_framework.relations import StringRelatedField from building.serializers import BuildingSerializer from building_post.models import BuildingPost, BuildingPostHistory class BuildingPostSeri...
StarcoderdataPython
3367224
<gh_stars>10-100 # -*- coding: utf-8 -*- """Handling datasets. For the moment, is initialized with a torch Tensor of size (n_cells, nb_genes)""" import copy import os import urllib.request from collections import defaultdict import numpy as np import scipy.sparse as sp_sparse import torch from sklearn.preprocessing i...
StarcoderdataPython
1736819
import django.forms as forms from .models import Subject, Comment, Answer class SubjectForm(forms.ModelForm): class Meta: model = Subject fields = [ 'title', 'subtitle', 'content' ] class CommentForm(forms.ModelForm): class Meta: model = Comm...
StarcoderdataPython
55949
from gstat_classroom.index import app app.run_server(debug=True)
StarcoderdataPython
3316472
<filename>calm/dsl/builtins/models/ref.py from .entity import EntityType, Entity from .validator import PropertyValidator from calm.dsl.store import Cache # Ref class RefType(EntityType): __schema_name__ = "Ref" __openapi_type__ = "app_ref" class RefValidator(PropertyValidator, openapi_type="app_ref"): ...
StarcoderdataPython
4838245
#!/usr/bin/env python3 """ Hydrogen molecule in Ground State (sto, 3g) Originally used by River Lane Research for testing Rigetti VQE. """ label_to_hamiltonian_coeff = { "ZZ": 0.011236585210827765, "II": -0.3399536172489041, "ZI": 0.39398367743432866, "IZ": 0.39398367743432866, ...
StarcoderdataPython
181525
# visualize.py - convert lattice to graphviz dot import os import glob import graphviz __all__ = ['lattice', 'render_all'] SORTKEYS = [lambda c: c.index] NAME_GETTERS = [lambda c: 'c%d' % c.index] def lattice(lattice, filename, directory, render, view): """Return graphviz source for visualizing the lattice g...
StarcoderdataPython
3397598
<reponame>GokulDas027/Chrome-dino-auto-run import cv2 import numpy as np from PIL import ImageGrab # windows and mac # import pyscreenshot as ImageGrab # linux import ctypes # import os # for linux key press # bbox = (450, 230, 500, 265) fix # bbox = (Left, Top, Right, Bottom) bbox = (865, 240, 960, 275) shape = (bbox[...
StarcoderdataPython
93659
<filename>gears/listentomysong.py from . import geffects from pbge import effects import pbge import random from . import aitargeters from . import enchantments SONG_REACH = 12 MENTAL_COST = 9 class _Info(object): def __init__(self, att_stat, att_skill, def_stat, def_skill): self.att_stat = att_stat ...
StarcoderdataPython
185571
<gh_stars>10-100 # @sp: newly created import os import sys sys.path.append(os.getcwd()) # puts all uploaded python modules into the python path sys.path.append('/input/src/') import params.polyaxon_parsing_iitnet_cnn_lstm as pp3 import random import shutil from data.process_data import process_data from params.Par...
StarcoderdataPython
1730551
<gh_stars>10-100 from builtins import str from django.test import TestCase from measure_mate.tests.factories import TemplateFactory class TemplateTestCases(TestCase): def test_has_up_to_five_in_running_set(self): template = TemplateFactory() template.clean() self.assertEqual(template.name...
StarcoderdataPython
173595
<reponame>lccasagrande/Hashtag-Monitor<filename>hashtag_monitor/apps/monitor/migrations/0020_auto_20191227_1803.py # Generated by Django 3.0 on 2019-12-27 18:03 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('monitor', '0019_auto_20191226_2112'), ] ...
StarcoderdataPython
12051
import datetime import logging import os import re from collections import OrderedDict from html import escape from html.parser import HTMLParser from io import StringIO import docutils import docutils.core import docutils.io from docutils.parsers.rst.languages import get_language as get_docutils_lang from docutils.wr...
StarcoderdataPython
3358905
<reponame>B-C-WANG/ReinforcementLearningInAutoPilot<filename>src/ReinforcementLearning/train/archive_bad/ddpg_train_waypoints_GAL_v1.py # coding:utf-8 # Type: Private Author: <NAME> ''' FIXME ddpg 需要全为负的reward,waypoints环境暂时没有提供! 描述: 和local模型相同,训练得不到较好的结果 ''' import numpy as np from ReinforcementLearning.Modules.A...
StarcoderdataPython
1618627
<gh_stars>1-10 # -*- coding: utf-8 -*- # # Copyright 2019 Ricequant, Inc # # * Commercial Usage: please contact <EMAIL> # * Non-Commercial Usage: # 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 th...
StarcoderdataPython
139236
<reponame>DCorredorM/MarkovDecisionProcess<gh_stars>0 from discrete_world.space import finiteTimeSpace from discrete_world.Reward import finiteTimeReward from discrete_world.mdp import finiteTime import networkx as nx class SSP_space(finiteTimeSpace): def __init__(self, actions, states, time_horizon, G): super(SSP...
StarcoderdataPython
3326095
# Simple NEC remote decode-and-print example # Prints out the 4-byte code transmitted by NEC remotes import pulseio import board import adafruit_dotstar import adafruit_irremote led = adafruit_dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1) pulsein = pulseio.PulseIn(board.REMOTEIN, maxlen=120, idle_state=True...
StarcoderdataPython
1618816
import axelrod as axl from rich import print from timeit import default_timer as timer from axelrod import tournament from axelrod import result_set TURNS = 200 REPETITIONS = 100 RUN_TYPE = "dev" player_set = { "dev_tour": [axl.Cooperator(), axl.Defector(), axl.TitForTat()], "first_tour": [s() for s in axl....
StarcoderdataPython
3315263
<reponame>bell-bot/audio_adversarial_examples<filename>datasets.py # -*- coding: future_fstrings -*- import os from re import L from typing import Dict, Tuple import sys import logging import numpy import regex as re # import torchaudio.datasets.tedlium as tedlium import librosa from Data import tedlium_local as ted...
StarcoderdataPython
3330423
<reponame>berdosi/Workflow-Analyzer """ Generate documentation for a UiPath project based on the annotations within the files. Create a folder deliverables/documentation, renders the contents in HTML. """ import logging import os from html import escape as e from itertools import tee from typing import Iterable, Opti...
StarcoderdataPython
151482
import os import torch import numpy as np import json import dgl import constants def read_partitions_file(part_file): """ Utility method to read metis partitions, which is the output of pm_dglpart2 Parameters: ----------- part_file : string file name which is the output of metis part...
StarcoderdataPython
4816873
n1 = int(input('Um valor:')) n2 = int(input('Outro valor:')) soma = n1 + n2 multiplicacao = n1 * n2 divisao = n1 / n2 divisaoint = n1 // n2 potencia = n1 ** n2 print('A soma é {} , \no produto é {} e a divisão é {:.3f}'.format(soma, multiplicacao, divisao), end=' ') print('Divisão inteira {} e potencia {}'.format(divis...
StarcoderdataPython
3383555
import contextlib import ctypes import sys import time import sdl2 import sdl2.ext import sdl2.examples.opengl import skia from OpenGL import GL WIDTH, HEIGHT = 1280, 720 fps_font = None def main_loop(state): global fps_font if sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO) != 0: print(sdl2.SDL_GetError()) ...
StarcoderdataPython
3297714
<reponame>BrianLusina/PyCharm from .enums import VehicleSize from .parking_spot import ParkingSpot from .vehicle import Vehicle class Car(Vehicle): def __init__(self, license_plate: str): super().__init__( vehicle_size=VehicleSize.COMPACT, license_plate=license_plate, spot_size=1 ) ...
StarcoderdataPython
115579
<reponame>rpmoseley/clubadmin ''' This module provides the support for the Options table, and enables the application to work with a simple mapping given the option text or number without having to access the underlying database information directly. ''' import apsw from ...config import configdb # Define the default...
StarcoderdataPython
1601414
#!/usr/bin/python3 import requests import math import os import json import threading import sys from mutagen.id3 import ID3, APIC, TIT2, TPE1, COMM from tenacity import retry, stop_after_attempt from requests import get, head import platform media_id = input('media_id:') ng_str = r'\/:*?"<>|' #win特供文件命名规则 translate...
StarcoderdataPython
3330627
# -*- coding: utf-8 -*- """ Created on Tue Mar 29 16:24:16 2016 @author: DanielleT """ import pandas as pd from sklearn.multiclass import OneVsRestClassifier from sklearn.svm import LinearSVC import matplotlib.pyplot as plt import PIL from PIL import Image import os import math from pandas import * import numpy as np...
StarcoderdataPython
28672
import json import time import requests import re from flask import Flask, render_template, jsonify from pyecharts.charts import Map, Timeline,Kline,Line,Bar,WordCloud from pyecharts import options as opts from pyecharts.globals import SymbolType app = Flask(__name__) #字典,受限于谷歌调用限制 cn_to_en = {'安哥拉': 'Angola', '阿富汗':...
StarcoderdataPython
74393
#!/usr/bin/env python ############################################################################ # # Copyright (C) 2004-2005 Trolltech AS. All rights reserved. # # This file is part of the example classes of the Qt Toolkit. # # This file may be used under the terms of the GNU General Public # License version 2.0...
StarcoderdataPython
1606013
<reponame>aws/aws-gamekit-unreal import time from base64 import b64decode, b64encode from unittest import TestCase, mock from layers.main.CommonLambdaLayer.python.gamekithelpers import pagination class TestPagination(TestCase): def setUp(self): self.player_id = "foo" self.start_key = {"bar": "ba...
StarcoderdataPython
3219387
# coding=utf-8 # Copyright 2019 The Tensor2Tensor Authors. # # 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...
StarcoderdataPython
3396478
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ## # Copyright 2020 Telefónica Investigación y Desarrollo, S.A.U. # # 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...
StarcoderdataPython
3343618
<reponame>piersharding/magnum # Copyright 2015 OpenStack Foundation # 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/...
StarcoderdataPython
47781
from setuptools import setup, Extension setup(ext_modules=[ Extension('_module', sources=["module_wrap.c"]) ])
StarcoderdataPython
25731
''' AAA lllllll lllllll iiii A:::A l:::::l l:::::l i::::i A:::::A l:::::l l:::::l iiii A:::::::A l:::::l l:::::l ...
StarcoderdataPython
3237466
import numpy as np import tensorflow as tf def transform_box_to_discrete(dims, act_space): n = dims^(np.sum(act_space.shape)) return n, tf.constant(act_space.high, dtype=tf.float32), tf.constant(act_space.low, dtype=tf.float32) def transform_discrete_to_box(act_space): n = tf.cast(tf.constant(act_space....
StarcoderdataPython
9257
from freezegun import freeze_time from rest_framework import test from waldur_mastermind.billing.tests.utils import get_financial_report_url from waldur_mastermind.invoices import models as invoice_models from waldur_mastermind.invoices.tests import factories as invoice_factories from waldur_mastermind.invoices.tests ...
StarcoderdataPython
60889
<filename>blog/models.py from django.db import models from django.contrib.auth.models import User from django.urls import reverse # Create your models here. class Category(models.Model): name = models.CharField(max_length=128,verbose_name='博客分类') def __str__(self): return self.name class Meta: ...
StarcoderdataPython
1787550
<filename>Project Euler (HackerRank)/063. Powerful digit counts.py n = int(input()) for i in range(1,20): j=1 while 1: power = i**j length = len(str(power)) if length == j : j+=1 if length == n: print(power) else: break
StarcoderdataPython
144325
import numpy as np def compute_fans(shape): if len(shape) == 2: fan_in, fan_out = shape[0], shape[1] else: fan_in, fan_out = np.prod(shape[1:]), shape[0] return fan_in, fan_out class initializer(object): def __call__(self, shape): return self.init(shape).astype(np.float32) ...
StarcoderdataPython
30457
<filename>regions/core/regions.py # Licensed under a 3-clause BSD style license - see LICENSE.rst """ This module provides a Regions class. """ from .core import Region from .registry import RegionsRegistry __all__ = ['Regions'] __doctest_skip__ = ['Regions.read', 'Regions.write', 'Regions.parse', ...
StarcoderdataPython
4804151
<filename>ProtVR.py #!/usr/bin/python3 # Author: <NAME> # Email: <EMAIL> # URL: https://github.com/sarisabban # # Created By: <NAME> # Created Date: 13 March 2017 import sys import re import urllib import Bio import os from Bio.PDB import * if sys.argv[1]=='-d': print('Downloading',sys.argv[2],'from http://...
StarcoderdataPython
107046
<gh_stars>1-10 import torch import networkx as nx from torchdiffeq import odeint # odeint_adjoint as odeint import numpy as np from collections import OrderedDict, defaultdict from scipy.spatial.transform import Rotation import copy from ..dynamics import ConstrainedHamiltonianDynamics, EuclideanT class BodyGraph(n...
StarcoderdataPython
78776
<filename>hc2002/plugin/symbolic_values.py import hc2002.plugin as plugin import hc2002.config as config plugin.register_for_resource(__name__, 'hc2002.resource.instance') _prefixes = ('availability-zone:', 'image:', 'kernel:', 'key:', 'load-balancers:', 'ramdisk:', 'security-groups:', 'spot-price:', ...
StarcoderdataPython
1640235
from jd.api.base import RestApi class KeplerSkuProductServiceRequest(RestApi): def __init__(self,domain='gw.api.360buy.com',port=80): RestApi.__init__(self,domain, port) self.skuIdSet = None self.extFieldSet = None def getapiname(self): return 'jd.kepler.sku.ProductService'
StarcoderdataPython
1742850
<reponame>takuron/Lesson from machine import Pin,Signal from micropython import const import time LED_RED_PIN = const(17) LED_GREEN_PIN = const(16) LED_BLUE_PIN = const(15) red_led = Pin(LED_RED_PIN,Pin.OUT,value=1) green_led = Pin(LED_GREEN_PIN,Pin.OUT,value=1) blue_led = Pin(LED_BLUE_PIN,Pin.OUT,value=1) while Tru...
StarcoderdataPython
1737642
<filename>geoutil.py import geopandas as gpd import tempfile def bounds_to_set(bounds): if not isinstance(bounds, list): print('Unknown boundary format, ignoring') return None if isinstance(bounds[0], str) and bounds[0].startswith('geo:'): btl = bounds[0].strip('geo:').split(',') bbr = bounds[1].st...
StarcoderdataPython
91968
""" solution Adventofcode 2019 day 4 part 1. https://adventofcode.com/2019/day/4 author: pca """ def valid_pw(pw_str: int) -> bool: has_double = False if len(pw_str) != 6: return False max_digit = 0 prev_digit = -1 for ch in pw_str: cur_digit = int(ch) # decreasing ...
StarcoderdataPython
71073
<filename>mainnotes/migrations/0001_initial.py<gh_stars>1-10 # Generated by Django 3.1.7 on 2021-03-30 08:22 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import encrypted_fields.fields class Migration(migrations.Migration): initial = True depend...
StarcoderdataPython
3287371
<reponame>ritlew/django-hls-video import os from django_hls_video.settings import * DEBUG = False
StarcoderdataPython
4803520
#! /usr/bin/env python import functions as fn def load_dictionary(filename, key_col, value_col): file = open(filename) dictionary = dict() for line in file: line=line.rstrip("\n") fields = line.split("\t") key = fields[key_col] value = fields[value_col] hpo_l = value.split(", ") if key not in dictio...
StarcoderdataPython
67408
# Generated by Django 2.0 on 2017-12-18 14:17 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('website', '0001_initial'), ] operations = [ migrations.CreateModel( name='Tutorial', fields=[ ('id', m...
StarcoderdataPython
3382497
<gh_stars>1-10 import random # 1 -> car # 0 -> goat choice = [1, 0, 0] win = 0.0 # as float, to have decimal places NUMBER_OF_SIMULATION = 10_000 for i in range(NUMBER_OF_SIMULATION): random.shuffle(choice) #print(choice) user_index = 0 # 0 is first user_index = random.randint(0, 2) # or ran...
StarcoderdataPython
140514
from flask import Flask, render_template app = Flask(__name__) @app.route('/') def inicio(): return render_template('inicio.html') app.run()
StarcoderdataPython
3342075
# optimizer optimizer = dict(type='Adadelta', lr=1.0) optimizer_config = dict(grad_clip=dict(max_norm=0.5)) # learning policy lr_config = dict(policy='step', step=[8, 10, 12]) total_epochs = 16
StarcoderdataPython
3209650
<gh_stars>0 """Collector base class.""" import logging import traceback from typing import cast, Optional, Set, Tuple, Type import cachetools import requests from .type import ErrorMessage, Measurement, Response, Units, URL, Value class Collector: """Base class for metric collectors.""" TIMEOUT = 10 # De...
StarcoderdataPython
1669868
#!/usr/bin/env python """ A wrapper script for deleting a history python ./print_history_command_lines.py --userkey <KEY> --url 'https://dev.globusgenomics.org' --history_id 939393933948 """ import glob, re, json, time, sys, optparse, os, random from bioblend import galaxy import requests requests.packages.urllib3.d...
StarcoderdataPython