id
stringlengths
1
265
text
stringlengths
6
5.19M
dataset_id
stringclasses
7 values
3235643
<filename>proxy.py # Copyright (c) 2016-2019, <NAME> # 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, this # ...
StarcoderdataPython
32088
import numpy as np import tensorflow as tf def split_reim(array): """Split a complex valued matrix into its real and imaginary parts. Args: array(complex): An array of shape (batch_size, N, N) or (batch_size, N, N, 1) Returns: split_array(float): An array of shape (batch_size, N, N, 2) conta...
StarcoderdataPython
1716506
from typing import List from base import version class Solution: @version("220, 15.4mb") def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int: depth = -1 h, w = len(grid) - 1, len(grid[0]) - 1 prev = [(-1, -1)] while prev: depth += 1 cur ...
StarcoderdataPython
47536
<reponame>tadodotcom/pyjoulescope<filename>joulescope/usb/api.py # Copyright 2018 Jetperch 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...
StarcoderdataPython
1745112
<filename>tests/TwoClasses_TwoDimensions.py # Copyright (C) 2021, <NAME> <<EMAIL>>= # # License: MIT (see COPYING file) import sys from os import path import numpy as np import pandas as pd import time from sklearn.preprocessing import MinMaxScaler from CytOpT import robbinsWass, CytOpT from CytOpT.labelPropSto import...
StarcoderdataPython
3397722
#!/usr/bin/python from k5test import * # We should have a comprehensive suite of KDC host referral tests # here, based on the tests in the kdc_realm subdir. For now, we just # have a regression test for #7483. # A KDC should not return a host referral to its own realm. krb5_conf = {'master': {'domain_realm': {'y': '...
StarcoderdataPython
1746592
import boto3 import os import requests from settings import DEFAULT_REGION, KEYNAME session = boto3.session.Session(region_name=DEFAULT_REGION, profile_name=KEYNAME) def get_public_ip(instance_ids): ec2_client = session.client("ec2") reservations = ec2_client.describe_instances(InstanceIds=instance_ids).get(...
StarcoderdataPython
1698896
import os import time import logging import unittest from unittest.mock import patch from configparser import ConfigParser import uuid import pandas as pd import numpy as np import itertools import shutil from OTUSampleMetadataCorrelation.OTUSampleMetadataCorrelationServer import MethodContext from OTUSampleMetadataCo...
StarcoderdataPython
3304938
"""Test for the EventThread.""" from unittest.mock import AsyncMock, patch import pytest from onyx_client.data.device_mode import DeviceMode from onyx_client.data.numeric_value import NumericValue from onyx_client.device.shutter import Shutter from onyx_client.enum.action import Action from onyx_client.enum.device_ty...
StarcoderdataPython
4801930
import pymysql def db_connect(): try: db = pymysql.connect("localhost", "TaipeiWaterServer", "tpewater123", "TaipeiWater") cursor = db.cursor() except pymysql.MySQLError: return None, None return db, cursor def sql_execute(db, cursor, sql, commit): try: cursor.execute...
StarcoderdataPython
1607988
""" Various density standards. """ from numpy import array # Visual density is typically used on grey patches. Take a reading and get # the density values of the Red, Green, and Blue filters. If the difference # between the highest and lowest value is less than or equal to the value # below, return the densi...
StarcoderdataPython
3296512
<reponame>whdalsrnt/cost-analysis<filename>src/spaceone/cost_analysis/service/cost_query_set_service.py<gh_stars>1-10 import logging from spaceone.core.service import * from spaceone.core import utils from spaceone.cost_analysis.error import * from spaceone.cost_analysis.manager.cost_query_set_manager import CostQuery...
StarcoderdataPython
141784
<reponame>REAM-lab/switch import pandas as pd from switch_model.wecc.get_inputs.register_post_process import post_process_step @post_process_step(msg="Replacing _ALL_ZONES plants with a plant in each zone") def post_process(_): """ This post-process step replaces all the generation projects that have a load ...
StarcoderdataPython
3236461
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright © 2018 <NAME> """ Container class for optical usage information .. Created on Thu Jan 25 11:01:04 2018 .. codeauthor: <NAME> """ import math import numpy as np from rayoptics.parax.firstorder import compute_first_order, list_parax_trace from rayoptics.raytr...
StarcoderdataPython
1652502
<gh_stars>1-10 from __future__ import (absolute_import, division, print_function, unicode_literals) from unittest.case import TestCase from fancontrol.sense import temperatures class NoneTests(TestCase): def test_get_temps_None_only(self): chips = [None] features = [None...
StarcoderdataPython
3206408
<gh_stars>1-10 import requests class Member: """A model representing a member of the club. Attributes: first: The member's first name. last: The member's last name. email: The member's email address. """ def __init__(self, row): """Creates a member model from a row in ...
StarcoderdataPython
1651664
from oscar.agent.commander.base_commander import BaseCommander class QueueCommander(BaseCommander): def __init__(self, subordinates): super().__init__(subordinates) self.__next_agent = 0 def choose_subordinate(self, obs): """ Round robin distribution :return: The chos...
StarcoderdataPython
3355974
<reponame>Honcharov12/appscale """ Handles operations related to instance registration. """ import json import logging import random from kazoo.exceptions import NodeExistsError, NoNodeError from tornado import gen from tornado.httpclient import AsyncHTTPClient from appscale.admin.instance_manager.constants import VE...
StarcoderdataPython
1719624
<filename>tests/test_scoring/test_scoring_functions.py<gh_stars>0 from scoring.scoring_functions import PreferenceScoring, RatioCharacteristicConfigurationPenalty, WeightedFeaturePenalty, ReduceScoring from scoring.value_functions import ValueToValueFunction from model.configuration_model import ConfigurationModel f...
StarcoderdataPython
4841587
# Sierpinski triangle. # Run the Module (or type F5). from turtle import * def sierpinski(length, level): speed(0) # Fastest speed. if level==0: return begin_fill() # Fill shape. color("red") for i in range(3): sierpinski(length/2,level-1) fd(length) lt(120) # L...
StarcoderdataPython
1738289
<reponame>Zeppelinen-DevOps/ansible-selvpc-modules<gh_stars>10-100 from ansible.module_utils.selvpc_utils import common, wrappers @wrappers.create_object('project') def create_project(module, client, project_name): result = client.projects.create(project_name) changed, msg = True, "Project '{}' has been creat...
StarcoderdataPython
1710051
#%% import numpy as np #%% from sklearn.datasets import fetch_openml mnist = fetch_openml('mnist_784', version=1) # %% X, y = mnist["data"], mnist["target"] # %% y = y.astype(np.uint8) # %% X_train, X_test, y_train, y_test = X[:60000], X[60000:], y[:60000], y[60000:] # %% from sklearn.neighbors import KNeighborsClassif...
StarcoderdataPython
3254843
<reponame>erleiuat/el-code<filename>src/test/langFiles/python.py<gh_stars>0 test = '123' def bla(text): if(text): print(text) else: print('no') bla(test)
StarcoderdataPython
1628323
<reponame>tcprescott/zabbix-jolokia-jmx<filename>scripts/jolokia_jmx_discovery.py #!/usr/bin/python import urllib2 import json import sys import time #from pprint import pprint #verify we have at least two arguments if len(sys.argv) < 3: print("at least two arguments required!") exit(1) #see if arg3 ...
StarcoderdataPython
3214590
<reponame>kuzaku-developers/disnake<gh_stars>0 from disnake.ui.item import * from disnake.ui.item import __dict__ as __original_dict__ locals().update(__original_dict__)
StarcoderdataPython
123977
import pandas as pd import matplotlib.pyplot as plt #import numpy as np #from scipy.interpolate import interp1d from matplotlib.pyplot import figure font = {'family' : 'Times New Roman', 'size' : 28} plt.rc('font', **font) figure(num=None, figsize=(17, 5)) data = pd.read_csv('C:\\Users\\<NAME>\\D...
StarcoderdataPython
3366198
"""File generated by TLObjects' generator. All changes will be ERASED""" from ...tl.tlobject import TLObject from ...tl.tlobject import TLRequest from typing import Optional, List, Union, TYPE_CHECKING import os import struct from datetime import datetime if TYPE_CHECKING: from ...tl.types import TypeInputChannel, ...
StarcoderdataPython
4837606
<gh_stars>1-10 from django.db import models from django.core.validators import ( RegexValidator, MinLengthValidator, MaxLengthValidator, ) from django.contrib.auth.models import User class Worker(User): PERMISSION_CHOICES = ( ('1', 'Worker'), ('2', 'Admin'), ) permission = mo...
StarcoderdataPython
37198
import unittest import mock import Tkinter from cursecreator import Application class TestNPCCreator(unittest.TestCase): def setUp(self): root = Tkinter.Tk() self.app = Application(root) def test_attribute_fixer(self): self.assertTrue(self.app.attribute_fixer("health", 0)) self.assertFalse(self.app.attribut...
StarcoderdataPython
1697349
"""Delete empty keywords Revision ID: dac430582787 Revises: <PASSWORD> Create Date: 2020-01-30 20:08:37.311976+00:00 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'dac<PASSWORD>' down_revision = '<PASSWORD>' branch_labels = None depends_on = None keywords = s...
StarcoderdataPython
3383037
import pandas as pd import unittest import ray from ray import tune from ray.tune import session def _check_json_val(fname, key, val): with open(fname, "r") as f: df = pd.read_json(f, typ="frame", lines=True) return key in df.columns and (df[key].tail(n=1) == val).all() class TrackApiTest(unitt...
StarcoderdataPython
174047
<filename>shadowhawk/plugins/shell.py import os import re import html import asyncio from time import sleep from io import BytesIO from pyrogram import Client, filters from .. import config, help_dict, log_errors, public_log_errors, self_destruct # All the processes we've started processes = {} def _dumb_wait(pid, ti...
StarcoderdataPython
1648052
<gh_stars>0 import os from django.conf import settings API_KEY_FILE_PATH = os.path.join(settings.BASE_DIR, 'google_api_key.txt') def get_google_api_key(): with open(API_KEY_FILE_PATH, 'r') as api_key_file: api_key = api_key_file.read() return api_key
StarcoderdataPython
1756753
import torch.utils.data as data import os import os.path #from plyfile import PlyData, PlyElement from Datasets.plyfile.plyfile import PlyData import numpy as np #import main import args as args def load_ply(dir,file_name, with_faces=False, with_color=False): path = os.path.join(dir,file_name) ply_data = PlyDa...
StarcoderdataPython
1721751
# -*- coding: utf-8 -*- # Copyright (c) 2021 Intel Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
StarcoderdataPython
1773572
import re import subprocess import os import opentamp from core.internal_repr.action import Action from core.internal_repr.plan import Plan CLEANUP = False PATCH = True class HLSolver(object): """ HLSolver provides an interface to the chosen task planner. """ def __init__(self, domain_config=None, ab...
StarcoderdataPython
3303516
from __future__ import absolute_import, division, print_function, unicode_literals import six from mpl_toolkits.axisartist.axislines import *
StarcoderdataPython
1770152
<gh_stars>0 import tensorflow as tf import numpy as np import matplotlib.pyplot as plt import os import cv2 from .utils import scale_images, calculate_fid def sample(gan, train_dataset): """Generate and visualize sample generated by the GAN Args: gan (GAN): Compiled GAN model train_dataset (...
StarcoderdataPython
4814216
<reponame>tabris2015/nayra_api import datetime import os from flask_restful import Resource, abort, fields, marshal_with, reqparse from werkzeug.datastructures import FileStorage from werkzeug.utils import secure_filename from app import app, db from app.models import Audio, AudioCategory ALLOWED_EXTENSIONS = ["wav...
StarcoderdataPython
26239
<gh_stars>0 #------------------------------------------------------------ # Dependencies #------------------------------------------------------------ import pathlib import os import argparse #------------------------------------------------------------ # #------------------------------------------------------------ ...
StarcoderdataPython
3310567
def pipeline(*filters): def inner(value): final_value = value for filter in reversed(filters): final_value = filter(final_value) return final_value return inner def limpa_texto(text): return text.replace('\n', '') def troca_eh_massa(text): return text.replace('ma...
StarcoderdataPython
1647932
# -*- coding: utf-8 -*- """ Created on Sat Dec 11 00:31:17 2021 @author: jaimel """ import pandas as pd df = pd.read_csv("/home/jolima/Documentos/multilabel-classification/multi-label-classification/dataset/kaggle_dataset.csv") df = df.sample(n=10) columns = ['Computer Science', 'Physics', 'Mathematics', 'Sta...
StarcoderdataPython
3311527
<reponame>diarts/aioyoutube from functools import wraps from aioyoutube.exeptions import ( VariableTypeError, VariableValueError ) def search_validation(coroutine): @wraps(coroutine) async def wrapper(*args, **kwargs): """Decorator validate passed parameters for api method getting search r...
StarcoderdataPython
1782032
# -*- coding: utf-8 -*- # # Validates if 2nd level domain from PTR record points to an IP address # that belongs to spam network. # import json import yaml import re from cachetools import TTLCache import socket import time import sys import argparse from goshawk.reporter import RabbitmqConsumer, WorkerPool from gos...
StarcoderdataPython
184027
from unittest import TestCase import torch from transformers import AutoTokenizer import nullprompt.templatizers as templatizers class TestEncodeLabel(TestCase): def setUp(self): self._tokenizer = AutoTokenizer.from_pretrained('bert-base-cased') def test_single_token(self): output = templat...
StarcoderdataPython
3223107
<reponame>anemesio/Pyyhon3-Exercicios n = int(input('Digite um valor: ')) a = n - 1 s = n + 1 print('Analisando o valor {}, seu antecessor é {} e seu sucessor é {}.'.format(n, a, s))
StarcoderdataPython
1781203
<filename>sdk/AsposeEmailCloudSdk/api/contact_api.py # coding: utf-8 # ---------------------------------------------------------------------------- # <copyright company="Aspose" file="contact_api.py"> # Copyright (c) 2018-2020 Aspose Pty Ltd. All rights reserved. # </copyright> # <summary> # Permission is he...
StarcoderdataPython
3376186
""" Shim for IPython before and after the big split """ try: import traitlets import traitlets.config as config except ImportError: from IPython.utils import traitlets from IPython import config try: import nbformat except ImportError: from IPython import nbformat try: import nbconvert excep...
StarcoderdataPython
4824278
# Copyright (c) 2015 Advanced Micro Devices, Inc. # All rights reserved # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: redistributions of source code must retain the above copyright # notice, this list of conditions ...
StarcoderdataPython
1773070
from __future__ import absolute_import import sqlalchemy, sqlalchemy.exc from sqlalchemy import Column, Integer, String from . import Base, get_default_session _dict_id = {} # maps dictionary text -> database ID _dict_obj = {} # maps session, dictionary text -> database object class DictionaryItem(Base): __tab...
StarcoderdataPython
138393
<gh_stars>0 import cmdInterface cmd = cmdInterface.cmdInterface() cmd.newProject()
StarcoderdataPython
136749
<reponame>ClementMaliet/playground-metrics<gh_stars>1-10 from playground_metrics.metrics_helper.mean_fbeta import MeanFBetaAtThresholds
StarcoderdataPython
3335320
import json def sanitize_json(json_dict, max_item_length=100): """Sanitizes json objects for safe storage in Postgres """ if json_dict is None: return None returned = json.dumps(json_dict) returned = returned.replace('\\u0000', '\\\\x00') returned = json.loads(returned) for key, v...
StarcoderdataPython
1658474
import json import ujson import time import pickle # Some performance tests to compare difference approches to seriallizing # dicts in apache beam # wrapper class for a dict. We need a unique class in dataflow to associate with # a specific coder class Message(dict): pass d = dict( field_1= 'twas brillig and ...
StarcoderdataPython
1658819
<filename>report_eb_autoscaling_alarms/asg_describe_scaling.py<gh_stars>0 # Writes an output CSV with summary of ASG Activity. # You could use Excel afterwards on the CSV to sort descending NumActivityStatusSuccessful. # Compare to the cloudwatch alarm history. import boto3.session from pathlib import Path from dateti...
StarcoderdataPython
3311975
############################################################################### # RingPotential.py: The gravitational potential of a thin, circular ring ############################################################################### import numpy from scipy import special from ..util import conversion from .Potential ...
StarcoderdataPython
1772862
# -*- coding: utf-8 -*- # filename : scraper.py # description : Grabs movie links # author : LikeToAccess # email : <EMAIL> # date : 07-15-2021 # version : v2.0 # usage : python scraper.py # notes : # license : MIT # py versi...
StarcoderdataPython
122523
"""This is a 'Hello, world' program.""" def hello(): """Say, hello.""" print("Hello, World!") if __name__ == "__main__": hello()
StarcoderdataPython
1701016
<gh_stars>0 from django.test import TestCase from unittest.mock import MagicMock, patch from handledapp.models import Invoice, Item, Carrot from handledapp.handlers import InvoiceSignalHandler from datetime import datetime from cached_fields.exceptions import UnauthorisedChange from cached_fields.handlers import Ca...
StarcoderdataPython
182079
from random import randint pc = randint(0,10) joga = int(input('Tente adivinhar o número que eu escolhi: ')) cont = 1 while joga != pc: if joga < pc: joga = int(input('Mais! Tente novamente: ')) if joga > pc: joga = int(input('Menos! Tentenovamente: ')) cont += 1 print(f'PARABÉNS! Você ten...
StarcoderdataPython
1741334
<gh_stars>0 """JetMET tools: CMS analysis-level jet corrections and uncertainties These classes provide computation of CMS jet energy scale and jet energy resolution corrections and uncertainties on columnar data. """ from .FactorizedJetCorrector import FactorizedJetCorrector from .JetResolution import JetResolution f...
StarcoderdataPython
1679199
n = eval(input('Enter Number To Check Collatz Conjecture: ')) count = 0 if (n == 1): count = 0 print("Sorry, this is an infinite loop of 1 - 2 - 4 - 2 - 1 - 4. And it's aldready 1.") print("Count =", count) elif(n == 2): count = 2 print("Sorry, this is an infinite loop of 1 - 2 - 4 - 2 - 1 -...
StarcoderdataPython
1663630
# Code was created by <NAME>, 2020/01/13 # https://github.com/ezygeo-ai/machine-learning-and-geophysical-inversion/blob/master/scripts/fwd_sp.py import numpy as np import matplotlib.pyplot as plt import pickle # SP forward function def SPfunc(x_inp, par): var_x0 = par[0] var_alpha = par[1] var_...
StarcoderdataPython
111434
<reponame>Sahmwell/G15_Capstone from env.SumoEnv import SumoEnv import time def main(): test = SumoEnv(1000, False) test.reset() if __name__ == '__main__': main()
StarcoderdataPython
1676874
<filename>architect/orms/peewee/features.py """ Defines features for the Peewee ORM. """ from peewee import CompositeKey from ..bases import BasePartitionFeature, BaseOperationFeature class OperationFeature(BaseOperationFeature): def execute(self, sql, autocommit=True): return self.model_cls._meta.datab...
StarcoderdataPython
3274472
import logging from . import BaseAuthenticatedApiView from rest_framework.response import Response logger = logging.getLogger(__name__) class StatusAuthenticatedApiView(BaseAuthenticatedApiView): """ View for authenticated status check API method. """ # noinspection PyMethodMayBeStatic,PyUnusedLocal...
StarcoderdataPython
26295
<reponame>heytrav/drs-project # -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-03-26 01:17 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dep...
StarcoderdataPython
3398755
"""Added columns to user_to_lesson Revision ID: 530c0d70d57d Revises: 2<PASSWORD> Create Date: 2013-11-01 14:15:16.414902 """ # revision identifiers, used by Alembic. revision = '530c0d70d57d' down_revision = '<PASSWORD>' from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generate...
StarcoderdataPython
3284508
""" Copyright (C) 2016, Blackboard Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following di...
StarcoderdataPython
3291796
<reponame>StuWares/Hacktoberfest2018 // Language: Python // Author: heckerman100 print("Hello World)
StarcoderdataPython
179126
# -*- coding:utf-8 -*- import requests import os import openpyxl from rrunner.common.handle_config import config from rrunner.common.handle_path import DATA_DIR, CASE_DIR def getByPath(path, obj): paths = path.split(".") for path in paths: obj = obj.get(path, None) if obj == None: ...
StarcoderdataPython
1678061
<gh_stars>0 # time: O(len(S) * T(in)) # space: O(1) class Solution: def numJewelsInStones(self, J, S): """ :type J: str :type S: str :rtype: int """ res = 0 for s in S: if s in J: res += 1 ...
StarcoderdataPython
4835989
from pytest_cases import parametrize from tests.conftest import get_expected_get_headers, get_expected_post_headers from tests.mms.conftest import ( get_inbound_mms_messages_query_parameters, get_inbound_mms_messages_response, get_mms_body_multipart, get_mms_body_request, get_mms_delivery_reports_q...
StarcoderdataPython
15832
from rest_framework.views import APIView from rest_framework.response import Response from django.shortcuts import render from django.http.response import JsonResponse from nitmis_admin.serializers.UserSerializer import UserSerializer def create_user(role="Guest"): """ """ def fun_wrapper(func): d...
StarcoderdataPython
3378562
<reponame>PDBe-KB/pdbe-kb-uniprot-variant-import import csv from uniprot_variant_import.constants import * class VariationImport(object): """ This object is responsible for parsing the data from a JSON file that is in the UniProt variant API format, and for extracting relevant information, saving it i...
StarcoderdataPython
3364610
<reponame>Ulises-Rosas/WoRMStools #!/usr/bin/env python3 # -*- coding: utf-8 -*- # import re import time from wormstools.utils import * from wormstools.worms_core import Worms def wid(file, win, wout): fo = wout + '_worms_aphiaID.tsv' if wout != 'input_based' else cname(win, 'aphiaID') pf = wformat(file, 'ge...
StarcoderdataPython
1708164
<gh_stars>0 import sqlite3 conn = sqlite3.connect('C:/Users/User/Desktop/test1.db') cursor = conn.cursor() def table_creation(): cursor.execute('''CREATE TABLE games( ID INT, name TEXT, genre TEXT, year INT, studio TEXT ) ''') table_creatio...
StarcoderdataPython
1634325
#!python3 from datetime import datetime from datetime import date datetime.today() #datetime.datetime(2018, 2, 19, 14, 38, 52, 133483) today = datetime.today() print (type(today)) #<class 'datetime.datetime'> todaydate = date.today() print ('today:',todaydate) #datetime.date(2018, 2, 19) type(todaydate) #<clas...
StarcoderdataPython
153548
<gh_stars>1-10 import json import numpy as np from sklearn import metrics def purity_score(y_true,y_pred): contingency_matrix = metrics.cluster.contingency_matrix(y_true,y_pred) return np.sum(np.amax(contingency_matrix,axis=0))/np.sum(contingency_matrix) result_path = 'work_dirs/res50_3mouse_512x512/result_ke...
StarcoderdataPython
4800247
<filename>winguhub/group/handlers.py from signals import grpmsg_added from models import GroupMessage from winguhub.notifications.models import UserNotification from seaserv import get_group_members def grpmsg_added_cb(sender, **kwargs): group_id = kwargs['group_id'] from_email = kwargs['from_email'] grou...
StarcoderdataPython
3367970
<reponame>CFD-UTSA/Turbulence-stars # Licensed under an MIT open source license - see LICENSE from __future__ import print_function, absolute_import, division ''' Test functions for Cramer ''' import numpy.testing as npt import os from ..statistics import Cramer_Distance from ._testing_data import \ dataset1, d...
StarcoderdataPython
93800
<gh_stars>0 """Package npcs.""" from codemaster.models.actors.npcs.bats import ( BatBlue, BatLilac, BatRed, BatBlack, ) from codemaster.models.actors.npcs.skulls import ( SkullGreen, SkullBlue, SkullYellow, SkullRed, ) from codemaster.models.actors.npcs.ghosts import ( GhostG...
StarcoderdataPython
1679402
<filename>examples/tutorial_parallel/atomic_out.py ### Model from pypdevs.DEVS import * class TrafficLightWithOutput(AtomicDEVS): def __init__(self): AtomicDEVS.__init__(self, "Light") self.state = "green" self.observe = self.addOutPort("observer") def intTransition(self): state = self.state return {"red"...
StarcoderdataPython
1729788
<reponame>petrpavlu/storepass # Copyright (C) 2019-2020 <NAME> <<EMAIL>> # SPDX-License-Identifier: MIT """Textual views suitable for the console.""" import storepass.model class ListView(storepass.model.ModelVisitor): """View that produces a tree with one-line about each visited entry.""" def visit_root(se...
StarcoderdataPython
1726116
import json import string import random from hashlib import sha256 import logging import requests from proxy.request import send_request, Request from proxy.response import Response from resources.base import Resource logger = logging.getLogger() class AAFResource(Resource): def __init__(self, service): su...
StarcoderdataPython
1629717
<reponame>PyGotham/rewards from __future__ import annotations from django.contrib.auth import get_user_model from django.test import Client import pytest TEST_EMAIL = "<EMAIL>" # pyre-ignore[16]: This is fixed by https://github.com/facebook/pyre-check/pull/256. User = get_user_model() @pytest.mark.django_db # pyre...
StarcoderdataPython
25035
<reponame>Alex92rus/ErrorDetectionProject def extract_to_m2(filename, annot_triples): """ Extracts error detection annotations in m2 file format Args: filename: the output m2 file annot_triples: the annotations of form (sentence, indexes, selections) """ with open(filename, 'w+') as ...
StarcoderdataPython
3254911
<reponame>Korred/advent_of_code_2016 def improve(a): return '{}0{}'.format(a, a[::-1].translate(str.maketrans('01', '10'))) def get_checksum(data): size = len(data) div = (size // 2) - 2 if (size // 2) % 2 == 0 else (size // 2) - 1 # find suitable eg. biggest even divisor (div) where quotient is odd ...
StarcoderdataPython
178194
<gh_stars>0 """ Auteur: <NAME> Date : Mars 2020 Projet : MOOC Python 3 - France Université Numérique Objectif: Écrire un programme qui, si temperature (entier lu sur input correspondant à la température maximale prévue pour aujourd’hui) est strictement supérieur à 0, teste si temperature est inférieur ou é...
StarcoderdataPython
3239679
<reponame>YuanshengZhao/adiabaticbinary import tensorflow as tf IMG_HEIGHT = IMG_WIDTH = 64 datagen = tf.keras.preprocessing.image.ImageDataGenerator(dtype=float, horizontal_flip=True, ...
StarcoderdataPython
1697975
from __future__ import absolute_import from __future__ import division from __future__ import print_function import csv import os import logging import argparse import random from tqdm import tqdm, trange import dill from collections import defaultdict import numpy as np import pandas as pd import torch from torch.ut...
StarcoderdataPython
3355177
<filename>.ci/ci_script.py #!/usr/bin/env python3 import importlib.util import os import subprocess import sys import git import github # Try to import, but its not critical libnames = ['bot_jokes'] for libname in libnames: try: lib = __import__(libname) except Exception: print(sys.exc_info()...
StarcoderdataPython
180824
<reponame>yilin-lu/bungo-bot-DEPRECATED- from nonebot import on_notice, NoticeSession from nonebot.log import logger from .utils import * @on_notice async def _(session: NoticeSession): logger.info('new notice: %s', session.event) @on_notice('group_decrease') async def _(session: NoticeSession): msg = await l...
StarcoderdataPython
1731837
# Copyright 2017 Sidewalk Labs | https://www.apache.org/licenses/LICENSE-2.0 from __future__ import ( absolute_import, division, print_function, unicode_literals ) from collections import defaultdict, namedtuple import numpy as np import pandas from doppelganger.listbalancer import ( balance_multi_cvx, discr...
StarcoderdataPython
3246520
from pathlib import Path import numpy as np import tensorflow as tf from src.helpers import paths from src.regnet import regnet PRETRIAN_MODEL_PATH = paths.checkpoints.regnet().parent.with_name( 'training.ckpt') WEITGHTS_PATH = paths.models.regnet_tf() config = paths.config.read(paths.config.regnet()) BETA1 = f...
StarcoderdataPython
4813750
<gh_stars>0 import urllib.request,json from .models import Articles, Source # Getting api key api_key = None # Getting the news base url base_url = None category_articles_url = None search_url = None categories_url = None source_url = None # Getting api key an source links def configure_request(app): global...
StarcoderdataPython
4811835
<gh_stars>1-10 # -*- coding: utf-8 -*- """ Created on Fri Jul 2 09:37:08 2021 @author: r.dewinter """ from testFunctions.BNH import BNH from testFunctions.CTP1 import CTP1 from testFunctions.OSY import OSY from testFunctions.CEXP import CEXP from testFunctions.C3DTLZ4 import C3DTLZ4 from testFunctions.TNK import TN...
StarcoderdataPython
143946
<filename>conf/apps.py from django.apps import AppConfig class ConfConfig(AppConfig): name = 'conf'
StarcoderdataPython
1685132
<reponame>artofimagination/stereo-calibration-and-vSLAM import os import numpy as np import glob import shutil from pathlib import Path from backend import Backend, States, Modes from pointCloudGLWidget import PointCloudGLWidget from linePlotWidget import LinePlotWidget from PyQt5 import QtCore from PyQt5.QtCore impo...
StarcoderdataPython
55803
import json import os from api_swgoh_help import api_swgoh_help, settings from env import get_env from initialise_data_structures import initialise_data_structures from texttable import Texttable from data_lookups import mod_set_stats, mod_slots, unit_stats, primary_stat_names_map saved_data = initialise_data_structur...
StarcoderdataPython