id
stringlengths
1
8
text
stringlengths
6
1.05M
dataset_id
stringclasses
1 value
5034274
<filename>tests/utils/test_is_connected.py<gh_stars>100-1000 import socket import pytest from janitor.utils import is_connected """ Tests the is_connected helper function, which is a function to check if the client is connected to the internet. Example: print(is_connected("www.google.com")) console ...
StarcoderdataPython
9758995
<reponame>cfginn/sap-simulation-package import unittest from pysapets.sloth import Sloth from pysapets.animal import Animal import pysapets.constants as constants from unittest.mock import patch from io import StringIO from copy import deepcopy class SlothTest(unittest.TestCase): def setUp(self): self.sloth = ...
StarcoderdataPython
1845993
<gh_stars>10-100 # # Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. # from .client import client # .Lambda imports greengrass_common, which only applies within Greengrass Core. # Try-except as below to make sure the SDK is able to be imported outside of Greengrass Core try: from .Lamb...
StarcoderdataPython
6630160
"""This demo shows how to use Traits TreeEditors with PyTables to walk the heirarchy of an HDF5 file. This only picks out arrays and groups, but could easily be extended to other structures, like tables. In the demo, the path to the selected item is printed whenever the selection changes. In order to run, a path to ...
StarcoderdataPython
5157037
<reponame>Cadair/ginga<filename>ginga/Mixins.py # # Mixins.py -- Mixin classes for FITS viewer. # # <NAME> (<EMAIL>) # # Copyright (c) <NAME>. All rights reserved. # This is open-source software licensed under a BSD license. # Please see the file LICENSE.txt for details. from ginga.misc.Callback import Callbacks cla...
StarcoderdataPython
1813548
<gh_stars>0 from keras.layers import * from keras.models import * #定义模型 def get_my_model(shape=(64, 64, 1)): nclass = 2 inp = Input(shape=shape) x = Convolution2D(16, (3,3), padding="same")(inp) x = BatchNormalization()(x) x = Activation("relu")(x) x = MaxPool2D(strides=(2, 2))(x) ...
StarcoderdataPython
1900598
<reponame>KeyoungLau/py4insect-specimen # -*- coding:utf-8 -*- # author:keyoung # email:<EMAIL> # date:2019-10-11 def draw_grid(amount_card, read_file, savefile_name): from readList import read_csv_to_list import xlsxwriter workbook = xlsxwriter.Workbook(savefile_name) # 新建excel表 worksheet = workbo...
StarcoderdataPython
8145334
<filename>python/tests/references/test_references.py # Copyright 2019 Regents of the University of Minnesota. # # 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/lic...
StarcoderdataPython
1782222
from abc import ABCMeta, abstractmethod from bisect import bisect_right from random import uniform import numpy as np from numpy.random import choice from pandas import Series from generative_models.data_synthesiser_utils.utils import normalize_given_distribution class AbstractAttribute(object): __metaclass__ =...
StarcoderdataPython
6523971
# Generated by Django 2.0.13 on 2019-05-24 09:51 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [("terra_layer", "0001_initial")] operations = [ migrations.AlterField( model_name="filterfield", ...
StarcoderdataPython
9610160
import arcade # pip install arcade # Setting size for main window Window_width = 700 Window_height = 700 # Creating and opening the window arcade.open_window(Window_width,Window_height,"Smiley") arcade.set_background_color(arcade.color.BLACK) arcade.start_render() # Always use thi...
StarcoderdataPython
81527
def _find_patterns(content, pos, patterns): max = len(content) for i in range(pos, max): for p in enumerate(patterns): if content.startswith(p[1], i): return struct( pos = i, pattern = p[0] ) return None _find_endi...
StarcoderdataPython
4929817
import sys, os, inspect if '/home/ubuntu/shared/GitHub' in sys.path: sys.path.remove('/home/ubuntu/shared/GitHub') try: import generative_playground except: import sys, os, inspect my_location = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) # sys.path.append('../../../....
StarcoderdataPython
319434
from .normal import Normal, HomoskedasticNormal from .laplace import Laplace from .lognormal import LogNormal, HomoskedasticLogNormal from .loglaplace import LogLaplace
StarcoderdataPython
1723711
from .abs_state import AbsState class Waiting(AbsState): def check(self): m = self._model m.logger.info('Checking for new round') if (m.napi.check_new_round() or m.test): m.logger.info('New round available') self._model.state = self._model.getting_data ...
StarcoderdataPython
4965852
<filename>deploy/slim/prune/sensitivity_anal.py # Copyright (c) 2020 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/l...
StarcoderdataPython
6665250
<filename>panoptes_aggregation/scripts/reduce_panoptes_csv.py from collections import OrderedDict from multiprocessing import Pool import io import os import progressbar import yaml import warnings warnings.filterwarnings("ignore", message="numpy.dtype size changed") warnings.filterwarnings("ignore", message="numpy.uf...
StarcoderdataPython
6433714
<reponame>ericchen12377/Leetcode-Algorithm-Python class Solution(object): def maxArea(self, height): """ :type height: List[int] :rtype: int """ left, right = 0, len(height) - 1 area = 0 while left < right: area = max(area, min(height[left], heigh...
StarcoderdataPython
1655810
from rest_framework.permissions import IsAuthenticated from django.shortcuts import get_object_or_404 from django.db.models import Count, Q from drinks.models import Recipe, Quantity, Ingredient, UserIngredient from drinks.serializers import RecipeSerializer, RecipeListSerializer from drinks.grammar import parse_searc...
StarcoderdataPython
8044234
<reponame>yalina2787/NovPython print ("This file tests variable definitions. ") a=5 b="abc" print(a) print(b)
StarcoderdataPython
246867
<reponame>akshayanadahalli/vpp_ietf97 __import__('pkg_resources').declare_namespace(__name__) from . vpp_papi import *
StarcoderdataPython
6440482
<reponame>brandonjbryant/regression-exercises<filename>evaluate.py import math import sklearn.metrics import pandas as pd import numpy as np import matplotlib.pyplot as plt def residuals(actual, predicted): return actual - predicted def sse(actual, predicted): return (residuals(actual, predicted) **2).sum() ...
StarcoderdataPython
9666305
<filename>plugin_bot/plugins/__init__.py<gh_stars>0 """Module for the BasePlugin class, as well as basic plugin recipies. """ import logging class BasePlugin: """A convenience class to inherit from when making plugins.""" def __init_subclass__(cls, **kwargs): """Automatically create the unique logge...
StarcoderdataPython
6513097
<filename>tcrdist/mixcr.py import sys import re import pandas as pd import numpy as np from tcrdist import repertoire_db import warnings def mixcr_to_tcrdist2(chain:str, organism:str, seqs_fn:str = None, clones_fn:str = None): """ Converts ...
StarcoderdataPython
3205424
#!/usr/bin/python3 # (C) <NAME> 2019 import os,sys,tty,termios from datetime import datetime from rpi.inputs import * from rpi.camerainfo import * ESC=27 ENTER=13 SPACE=32 exposure=1 framenumber=1 frame_default=1 digits=4 digits_default=4 quality_default=90 artist="" artistfile="artist.txt" # Uncomment to overide re...
StarcoderdataPython
77704
<reponame>garysnake/structural-probes<gh_stars>0 from run_experiment import setup_new_experiment_dir, execute_experiment import yaml import torch # CHANGE PATH CONFIG_FILE = '/home/garysnake/Desktop/structural-probes/experiments/config/bert_base_distance_cola.yaml' EXPERIMENT_NAME = '/home/garysnake/Desktop/structural...
StarcoderdataPython
6527459
<reponame>Harry73/Senpai from lib import Command from lib.Command import CommandType, register_command from lib.Message import Message def _get_help(request, author, channel, command_types, base_command): # Generate list of all available commands commands = {} for command_type in command_types: fo...
StarcoderdataPython
73114
<filename>scripts/angle_integrals.py #!/home/colm.talbot/virtualenvironents/py-2.7/bin/python from __future__ import division, print_function import numpy as np import pandas as pd import sys from gwmemory.angles import gamma """ Script to calculate the spherical harmonic decomposition of the output memory. <NAME> ""...
StarcoderdataPython
4852595
<gh_stars>10-100 __version__ = "1.1.0" from nvelope.nvelope import * from nvelope.conversions import *
StarcoderdataPython
132262
<filename>road_damage.py # -*- coding: utf-8 -*- import six.moves.urllib as urllib import os try: import urllib.request except ImportError: raise ImportError('You should use Python 3.x') if not os.path.exists('./RoadDamageDataset.tar.gz'): url_base = 'https://s3-ap-northeast-1.amazonaws.com/mycityreport/...
StarcoderdataPython
5196759
<filename>venv/lib/python3.9/site-packages/PyObjCTools/TestSupport.py """ Helper code for implementing unittests. This module is unsupported and is primairily used in the PyObjC testsuite. """ import contextlib import gc as _gc import os as _os import re as _re import struct as _struct import sys as _sys import typin...
StarcoderdataPython
220287
<reponame>Novel-Public-Health/Novel-Public-Health # Generated by Django 3.1.2 on 2021-03-26 08:16 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('catalog', '0052_auto_20210326_0248'), ] operations = [ mi...
StarcoderdataPython
6611464
import copy import logging import time import math import numpy as np import torch import torch.utils.data as td from sklearn.utils import shuffle from PIL import Image from torch.autograd import Variable import torchvision.transforms.functional as trnF from torch.nn import functional as F from utils impo...
StarcoderdataPython
177180
<reponame>sajjadt/competitive-programming import time from math import sqrt from sys import stdout num_tests = int(input()) cases = 0 start = time.time() for t in range(num_tests): a, b, c = list(map(int, input().split())) # C0: xyz = b (positive) -> x and y and z > 0 and x < 0 and y < 0 and z > 0 since they wi...
StarcoderdataPython
11297263
import tkinter as tk # create container window = tk.Tk() window.geometry("312x200") window.resizable(0, 0) # deactivate resizing # create label and entry for firstname and lastname FN = tk.Label(text="<NAME>", fg="black", bg="yellow", width=20, height=2) FNbox = tk.Entry() EM = tk.Label(text=" Emai...
StarcoderdataPython
11283629
individuals = {'Pluto': 'active', 'Goofy': 'inactive', 'Sofie': 'active'} for individual, status in individuals.copy().items(): if status == 'inactive': del individuals[individual] active_individuals = {} for individual, status in individuals.items(): if status == 'active': active_ind...
StarcoderdataPython
11286239
<filename>src/directories.py import numpy as np import os as os def return_dirs( ): dirs = directories('.','.','.','.','.') dirs.get_dirs() return dirs class directories( dict ): def __init__( self, data_dir, sex_files, psf_model_dir, code_dir, stilts_dir): self.__dict__['sex_files'] = sex_file...
StarcoderdataPython
9763888
<filename>algovenv/lib/python3.8/site-packages/algosdk/abi/bool_type.py from typing import Union from algosdk.abi.base_type import ABIType from algosdk import error class BoolType(ABIType): """ Represents a Bool ABI Type for encoding. """ def __init__(self) -> None: super().__init__() d...
StarcoderdataPython
9779883
<reponame>andreatomassetti/open-cas-linux<filename>test/functional/tests/incremental_load/test_core_pool.py # # Copyright(c) 2019-2021 Intel Corporation # SPDX-License-Identifier: BSD-3-Clause # import pytest from api.cas import casadm from api.cas.core import CoreStatus from core.test_run import TestRun from storage...
StarcoderdataPython
4842317
from __future__ import absolute_import from __future__ import print_function import numpy as np import os import nn_utils.network_utils as network_utils import gen_utils.seed_generator as seed_generator import gen_utils.sequence_generator as sequence_generator from data_utils.parse_files import * import config.nn_confi...
StarcoderdataPython
4892582
<filename>modules/info.py #!/usr/bin/env python """ info.py - Phenny Information Module Copyright 2008, <NAME>, inamidst.com Licensed under the Eiffel Forum License 2. http://inamidst.com/phenny/ """ def doc(phenny, input): """Shows a command's documentation, and possibly an example.""" name = input.group(1) ...
StarcoderdataPython
1683231
DATABRIDGE_START = "c_bridge_start" DATABRIDGE_RESTART = "c_bridge_restart" DATABRIDGE_RECONNECT = "c_bridge_reconnect" DATABRIDGE_GET_CREDENTIALS = "c_bridge_get_tender_credentials" DATABRIDGE_GOT_CREDENTIALS = "c_bridge_got_tender_credentials" DATABRIDGE_FOUND_MULTILOT_COMPLETE = "c_bridge_found_multilot" DATABRIDGE_...
StarcoderdataPython
339434
<gh_stars>0 from django import forms from django.contrib.auth.models import User from django.db.utils import OperationalError from django.utils.translation import gettext_lazy as _ from .helper import generate_email, validate_emails class DraftEmailForm(forms.Form): """ Field notes: other_recipients ...
StarcoderdataPython
1677752
#!/usr/bin/env python ############################################################################ # Copyright (C) by <NAME> # # # # You can redistribute and/or modify this program under the ...
StarcoderdataPython
5194760
<filename>dataObjectClass.py class dataObject: """ Each of the data points in the database should be represented as one of these objects. The actual data is put in the attributes vector. """ def __init__(self, numberOfAttributes): self.attributes = [0.0]*numberOfAttributes ...
StarcoderdataPython
9687957
<filename>LintCode/DataStructure/20200106_158_valid_anagram.py # -*-coding:utf-8 -*- #Reference:********************************************** # @Time    : 2020-01-07 00:33 # @Author  : <NAME> # @File    : 20200106_158_valid_anagram.py # @User    : liyihao # @Software : PyCharm # @Description: Write a method anagra...
StarcoderdataPython
3279361
# MIT License # # Copyright (c) 2018 <NAME>, <NAME>, <EMAIL>, <EMAIL> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, ...
StarcoderdataPython
174961
<reponame>rkislov/122callcenter from django.contrib import admin from import_export import resources from import_export.admin import ImportExportModelAdmin from .models import Subject, Sub_subject, Patient, Manipulation, City, Hospital, Call_result, Address, Call, Journal class CallResource(resources.ModelResource): ...
StarcoderdataPython
32943
from app import app from flask import render_template, flash, redirect, url_for from app.forms import LoginForm @app.route('/') @app.route('/index') def index(): return render_template('index.html') @app.route('/contato', methods=['GET','POST']) def contato(): form = LoginForm() if form.validate_on_submit...
StarcoderdataPython
3516538
import os import numpy as np import argparse def compare_tables(my_checkpoint_path, ta_checkpoint_path): my_checkpoint = np.load(my_checkpoint_path) ta_checkpoint = np.load(ta_checkpoint_path) differences = my_checkpoint == ta_checkpoint are_same = np.all(differences) count = 0 if not are...
StarcoderdataPython
1731380
import pickle import sys from abc import abstractmethod from threading import Lock import logging import zlib from PyQt5.QtCore import QByteArray, QDataStream, QIODevice, QObject, pyqtSignal from PyQt5.QtNetwork import QTcpSocket, QAbstractSocket from PyQt5.QtTest import QSignalSpy from PyQt5.QtWidgets import qApp CO...
StarcoderdataPython
240479
import os.path from collections import OrderedDict from functools import partial from typing import List, Union, Dict import ancpbids from ancpbids import CustomOpExpr, EntityExpr, AllExpr, ValidationPlugin from . import load_dataset, LOGGER from .plugins.plugin_query import FnMatchExpr, AnyExpr from .utils import dee...
StarcoderdataPython
1613405
""" Provides QtGui classes and functions. .. warning:: All PyQt4/PySide gui classes are exposed but when you use PyQt5, those classes are not available. Therefore, you should treat/use this package as if it was ``PyQt5.QtGui`` module. """ import os from pyqode.qt import QT_API from pyqode.qt import PYQT5_API f...
StarcoderdataPython
5134534
<filename>penn/news.py from .base import WrapperBase BASE_URL = "https://esb.isc-seo.upenn.edu/8091/open_data/" ENDPOINTS = { 'SEARCH': BASE_URL + 'news_events_maps' } class News(WrapperBase): """The client for the News Search API. :param bearer: The user code for the API :param token: The password...
StarcoderdataPython
11333847
#!/usr/bin/env python3 from __future__ import print_function # dsl1.py import sys import importlib # the source file is the 1st argument to the script if len(sys.argv) != 2: print('usage: %s <src.dsl>' % sys.argv[0]) sys.exit(1) sys.path.insert(0, '/Users/nathan/code/dsl/modules') with open(sys.argv[1], 'r...
StarcoderdataPython
3397298
from sense_hat import SenseHat sense = SenseHat() sense.set_rotation(0) sense.show_message("halo",text_colour=(0,0,255), back_colour=(4, 34, 180)) sense.set_pixel(3,3, (116,255,231))
StarcoderdataPython
8055835
<reponame>candyninja001/pypad from enum import Enum from .monster_type import MonsterType from .dev import Dev class LatentAwakening(Enum): UNKNOWN = (-1, 2, []) NONE = (0, 1, []) IMPROVED_HP = (1, 1, []) IMPROVED_ATTACK = (2, 1, []) IMPROVED_RECOVERY = (3, 1, []) EXTENDED_MOVE_TIME = (4, 1, []...
StarcoderdataPython
11310297
# -*- coding: utf-8 -*- # vim: set fileencoding=utf-8:noet:tabstop=4:softtabstop=4:shiftwidth=8:expandtab """ python3 method """ # Copyright (c) 2010 - 2020, © Badassops LLC / <NAME> # All rights reserved. # BSD 3-Clause License : http://www.freebsd.org/copyright/freebsd-license.html from logging import warning de...
StarcoderdataPython
4958765
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from collections import defaultdict from dataclasses import dataclass from itertools import chain, islice from typing import TYPE_CHECKING, Di...
StarcoderdataPython
1675956
import configparser from datetime import datetime from math import cos from skimage import filters from skimage import measure from math import radians from scipy.interpolate import splprep, splev import numpy as np import pandas as pd import scipy.ndimage as img """ Tools to manipulate and analyze data """ def can...
StarcoderdataPython
4821993
#!/usr/bin/env python3 # Usage: # $0 -o <output-zip> <toplevel-directory> # # zips all files under <toplevel-directory>. includes .log of process and .tsv of contents import zipfile from xdfile.metadatabase import xd_sources_row, xd_sources_header from xdfile.utils import find_files_with_time, get_log, get_args...
StarcoderdataPython
5053365
<gh_stars>10-100 from __future__ import absolute_import from base64 import b64encode, b64decode from irods.message.ordered import OrderedProperty import six if six.PY3: from html import escape else: from cgi import escape class MessageProperty(OrderedProperty): def __get__(self, obj, cls): return...
StarcoderdataPython
4906562
class DefaultConfig(object): data = {} def get(self, path, getter): self.data[path] = getter __all__ = ["entries", "getters"]
StarcoderdataPython
9655800
<gh_stars>10-100 import random import struct import sys from bxutils.logging.log_level import LogLevel from bxgateway.btc_constants import BTC_HDR_COMMON_OFF from bxgateway.messages.btc.btc_message import BtcMessage # FIXME dedup this against pongbtcmessage from bxgateway.messages.btc.btc_message_type import BtcMessa...
StarcoderdataPython
1719708
from utils import * from rtid_out_info import RtidOutInfo from rtid_config import RTIDConfig from content_manager import ContentManager from datetime import datetime from os import path, makedirs import json import praw import secret import sys class RTID(Logger): def __init__(self, rtid_config: RTIDConfig): super(...
StarcoderdataPython
5066356
import json import math import numpy from colorful.fields import RGBColorField from django.conf import settings from django.contrib.gis.db import models from django.contrib.gis.gdal import Envelope, OGRGeometry, SpatialReference from django.contrib.postgres.fields import ArrayField from django.db.models import Max, M...
StarcoderdataPython
3485095
<gh_stars>1000+ #!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import unittest import parlai.utils.testing as testing_utils class TestUnigram(unittest.TestCase): ...
StarcoderdataPython
75052
from .browser import * from .graphql import *
StarcoderdataPython
3238962
# Defination of Prime # If n is prime, 1 | n and n | n def isPrime(n): for k in range(2, n): # print('k =', k) if n % k == 0: # print(k, '|', n) # print(n, 'is not a prime') return False # print(n, 'is a prime') return True counter = 0 i = 2 while count...
StarcoderdataPython
5067248
#!/usr/bin/env python # Download and log the MTA's status updates. We only log changes. from __future__ import print_function import argparse import doctest import json import os import random import string import re import sys from datetime import datetime, timedelta from filewrapper import FileWrapper from parser im...
StarcoderdataPython
11271634
<reponame>fchapoton/sage r""" Subcrystals These are the crystals that are subsets of a larger ambient crystal. AUTHORS: - <NAME> (2013-10-16): Initial implementation """ #***************************************************************************** # Copyright (C) 2013 <NAME> <tscrim at ucdavis.edu> # # Dist...
StarcoderdataPython
4891594
def partition(arr: [], low: int, high: int): ''' Partition the selected part of the list in place. That means to select one of the elements, put all lower to the left, and all higher to the right, and the selected one (the pivot) in the middle. In this case we are selecting the rightmost item as ...
StarcoderdataPython
1636121
<filename>ros/src/tl_detector/light_classification/tl_classifier.py from styx_msgs.msg import TrafficLight import tensorflow as tf import numpy as np class TLClassifier(object): def __init__(self, is_sim): self.label_map = dict() self.label_text = dict() if is_sim: PATH_TO_GRAP...
StarcoderdataPython
5110871
# -*- coding: utf-8 -*- import gensim import os import sys import io class Word2VecModule(): def __init__(self): pass def run(self, line): model = gensim.models.Word2Vec.load('ko.bin') module = os.path.basename(sys.argv[0]) listB = line.split(",") resList = [] ...
StarcoderdataPython
5195501
import unittest import sshim from . import connect class TestFailure(unittest.TestCase): def test_unexpected(self): def echo(script): script.expect('moose') script.writeline('return') with sshim.Server(echo, address='127.0.0.1', port=0) as server: with connect(s...
StarcoderdataPython
5106996
#!/usr/bin/env python ############################################################################ # Copyright (c) 2015-2019 Saint Petersburg State University # Copyright (c) 2011-2014 Saint Petersburg Academic University # All Rights Reserved # See file LICENSE for details. ###########################################...
StarcoderdataPython
37994
<gh_stars>1-10 from collections import Counter from konlpy.tag import Hannanum import pytagcloud f = open('D:\\KYH\\02.PYTHON\\crawled_data\\cbs2.txt', 'r', encoding='UTF-8') data = f.read() nlp = Hannanum() nouns = nlp.nouns(data) count = Counter(nouns) tags2 = count.most_common(200) taglist = pytagcloud.make_tags(...
StarcoderdataPython
8155630
import json import sys from interface_lichess import lichess from train import Training def start_engine(): config = load_configuration() connection = lichess(config['token'], config['train']['training_file_name'], config['train']['training_file_path']) if config['mode_game'].lower() == 'ai':...
StarcoderdataPython
4985782
"""compressor.lib High-level functions exposed as a library, that can be imported. """ from compressor.char_node import CharNode # pylint: disable=unused-import from compressor.core import (create_tree_code, parse_tree_code, process_frequencies) from compressor.core import retrieve_compr...
StarcoderdataPython
4983215
<filename>utils.py<gh_stars>0 import torch import torch.distributed as dist import torch.multiprocessing as mp import random import numpy as np def move_to_device(maybe_tensor, device): """ Args: maybe_tensor: device: torch.device('cuda'/'cpu', OPTIONAL[index]) Returns:处理完后的数据 """ ...
StarcoderdataPython
1987204
<reponame>openredact/pii-identifier from .base import Backend from nerwhal.types import NamedEntity from nerwhal.nlp_utils import load_stanza_nlp # the stanza NER models have an F1 score between 74.3 and 94.8, https://stanfordnlp.github.io/stanza/performance.html # we choose a hardcoded score in this scale NER_SCORE =...
StarcoderdataPython
5140828
<reponame>ReinholdM/play_football_with_human<gh_stars>1-10 # -*- encoding: utf-8 -*- # ----- # Created Date: 2021/1/21 # Author: <NAME> # ----- # Last Modified: # Modified By: # ----- # Copyright (c) 2020 MARL @ SJTU # ----- import os import time import grpc import multiprocessing import traceback import numpy as np f...
StarcoderdataPython
8159809
# -*- coding: utf8 -*- import sys import os import pybossa_lc as plugin # Use the PYBOSSA test settings PB_PATH = os.environ.get('PYBOSSA_PATH', '..') sys.path.append(os.path.abspath(os.path.join(PB_PATH, 'test'))) PYBOSSA_TEST_SETTINGS = os.path.join(PB_PATH, 'settings_test.py') def setUpPackage(): """Setup t...
StarcoderdataPython
3535733
<gh_stars>1000+ import torch from colossalai.gemini.stateful_tensor import StatefulTensor from typing import Union, Tuple def colo_tensor_mem_usage(tensor: Union[torch.Tensor, StatefulTensor]) -> Tuple[int, int]: if isinstance(tensor, StatefulTensor): t = tensor.payload elif isinstance(tensor, torch.T...
StarcoderdataPython
1700706
from unittest import TestCase from unittest.mock import MagicMock, patch, call import tempfile import shutil import os import pytest from js9 import j from zerorobot import config, template_collection from zerorobot.template_uid import TemplateUID from zerorobot.template.state import StateCheckError def mockdecorat...
StarcoderdataPython
4957027
# -*- coding: utf-8 -*- """ A collection of generally useful mathematical (or numerical) functions. """ def is_power_of_two(value: int) -> bool: """ Determine if the given value is a power of 2. Negative numbers and 0 cannot be a power of 2 and will thus return `False`. :param value...
StarcoderdataPython
9687213
'''Tokens class. :copyright: 2021, <NAME> <<EMAIL>> ''' from .elements import NamedElement, c_export, go_export, java_export class Tokens(NamedElement): __slots__ = ('_tokens',) def __init__(self, tokens): self._tokens = tokens.split() self._tokens.sort(key=len, reverse=True) def __rep...
StarcoderdataPython
9664582
import os import click import logging import palettable import subprocess import pdb import math from jenks import jenks # pip install -e "git+https://github.com/perrygeo/jenks.git#egg=jenks" import sys from jenks import jenks import numpy as np import matplotlib as mpl from matplotlib import pyplot as plt import mat...
StarcoderdataPython
5061809
<reponame>drewrisinger/pyGSTi from ..testutils import BaseTestCase, compare_files, temp_files import unittest import pygsti import numpy as np import pygsti.extras.rpe as rpe import pygsti.extras.rpe.rpeconstruction as rc from pygsti.extras.rpe.rpeconfig_GxPi2_GyPi2_UpDn import rpeconfig_GxPi2_GyPi2_UpDn from pygsti.e...
StarcoderdataPython
9672404
from unittest import TestCase from mlcube.common.utils import StandardPaths from mlcube_ssh.ssh_metadata import (PythonInterpreter, SystemInterpreter, VirtualEnvInterpreter) class TestPythonInterpreters(TestCase): def test_all_interpreters_present(self) -> None: self.assertIsInstance(PythonInterpreter._in...
StarcoderdataPython
3545598
from __future__ import annotations from functools import partial from typing import Generic, Tuple import jax.numpy as jnp from jax.tree_util import tree_map, tree_reduce from ..annotations import BooleanNumeric, ComplexNumeric, RealNumeric from ..dataclasses import dataclass from ..leaky_integral import leaky_data_...
StarcoderdataPython
3373256
from app import app_search, settings from django.db import models from django.db.models import ObjectDoesNotExist from django.db.models.signals import m2m_changed, post_delete, post_init, post_save from django.dispatch import receiver class State(models.Model): name = models.CharField(primary_key=True, max_lengt...
StarcoderdataPython
5021590
from sqlalchemy import Column, ForeignKey, Integer, UniqueConstraint from sqlalchemy.orm import backref, relationship from sqlalchemy.types import PickleType from fonduer.candidates.models.temporarycontext import TemporaryContext from fonduer.parser.models.context import Context, construct_stable_id class TemporaryS...
StarcoderdataPython
311309
<filename>TranskribusDU/graph/FeatureDefinition_PageXml_FeatSelect.py # -*- coding: utf-8 -*- """ Standard PageXml features Copyright Xerox(C) 2016 <NAME> Developed for the EU project READ. The READ project has received funding from the European Union�s Horizon 2020 research and innovation progra...
StarcoderdataPython
11253329
from __future__ import annotations # To avoid circular import. from .ulist import read_csv as _read_csv from typing import List, TYPE_CHECKING if TYPE_CHECKING: # To avoid circular import. from . import UltraFastList def read_csv() -> List[UltraFastList]: from . import UltraFastList # To avoid circular im...
StarcoderdataPython
3376271
<reponame>sthysel/rakali import functools import time def cost(func): @functools.wraps(func) def wrapper_timer(*args, **kwargs): start_time = time.perf_counter() value = func(*args, **kwargs) end_time = time.perf_counter() wrapper_timer.cost = end_time - start_time wrap...
StarcoderdataPython
366972
import os import urllib.request from PIL import Image # This will create a page with the settings in default_site.py from bs4 import BeautifulSoup from django.contrib.auth.models import User from django.core.files import File from django.core.management.base import BaseCommand from filer.models import Image as FilerIm...
StarcoderdataPython
1700983
# https://oj.leetcode.com/problems/reverse-words-in-a-string/ class Solution: # @param s, a string # @return a string def reverseWords(self, s): result, word, s = [], "", s[::-1] for i in xrange(len(s)): if s[i] != " ": word += s[i] elif word != "": result.append(word[::-1]) ...
StarcoderdataPython
12822895
import numpy as np import pandas as pd from sklearn.preprocessing import StandardScaler class Data: '''Obtains hydro data and preprocesses it.''' def data(self, test_len): names = ['date', 'price', 'avg_p', 'bid', 'ask', 'o', 'h', 'l', 'c', 'avgp', 'vol', 'oms', 'num'] ...
StarcoderdataPython
11352895
<reponame>imranq2/SparkAutoMapper.FHIR from __future__ import annotations from spark_auto_mapper_fhir.fhir_types.uri import FhirUri from spark_auto_mapper_fhir.value_sets.generic_type import GenericTypeCode from spark_auto_mapper.type_definitions.defined_types import AutoMapperTextInputType # This file is auto-gene...
StarcoderdataPython