id
stringlengths
1
7
text
stringlengths
6
1.03M
dataset_id
stringclasses
1 value
1616025
import numpy as np from sklearn.model_selection import train_test_split from utilities_test import get_data, \ get_feature_vector_from_mfcc _DATA_PATH = '../korean_dataset' _CLASS_LABELS = ("angry", "disappoint", "fear", "neutral", "sad", "surrender") def extract_data(flatten): data, labels = get_data(_DATA...
StarcoderdataPython
73868
<reponame>tupui/batman # coding: utf8 """ Refinement Class ================ This class defines all resampling strategies that can be used. It implements the following methods: - :func:`Refiner.func` - :func:`Refiner.func_sigma` - :func:`Refiner.pred_sigma` - :func:`Refiner.distance_min` - :func:`Refiner.hypercube` -...
StarcoderdataPython
101566
'''Container module that instantiate classes to accomplish IoC role''' from templatizator.domain.repository import ConfigurationRepository, \ VariableRepository, TemplateRepository, TemplateFileRepository, \ ConfigurableRepository, ConfigurableFileRepository from templatizator.domain.service import ProjectS...
StarcoderdataPython
1624779
<filename>src/sysinfo.py #!/usr/bin/env python3 """ sysinfo.py: Collection of classes to read Linux system information. """ __author__ = '<NAME>' __copyright__ = '(C) 2019 ' + __author__ __license__ = "MIT" __version__ = '1.0.0' from collections import namedtuple from datetime import timedelta import os import pwd ...
StarcoderdataPython
1772870
<filename>cla_public/libs/api_proxy.py<gh_stars>1-10 # coding: utf-8 """Decorator for API proxy views""" import functools import json import logging from requests.exceptions import ConnectTimeout, ReadTimeout TIMEOUT_RESPONSE = json.dumps({"error": "Request timeout."}) log = logging.getLogger(__name__) def on_ti...
StarcoderdataPython
1716202
<reponame>scpwiki/2stacks import json import config import helpers import requests from time import sleep from xmlrpc.client import ServerProxy import logging logger = logging.getLogger() logger.setLevel(logging.INFO) def lambda_handler(event, context): for record in event['Records']: callback_url = recor...
StarcoderdataPython
3212352
<gh_stars>0 import asyncio import PIL from PIL import ImageTk, Image import tkinter import traceback from common import ROOM_HEIGHT_IN_TILES, ROOM_WIDTH_IN_TILES, TILE_SIZE from .util import tile_to_text, ScrollableFrame # The DROD room size is 836x704, use half that for canvas to preserve aspect ratio _CANVAS_WIDTH...
StarcoderdataPython
3232078
#!/usr/bin/env python3 # 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, softwar...
StarcoderdataPython
1609137
# -*- coding: utf-8 -*- # PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN: # https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code from ccxt.base.exchange import Exchange import json from ccxt.base.errors import ExchangeError from ccxt.base.errors import AuthenticationE...
StarcoderdataPython
3217518
""" .. _tut-report: Getting started with ``mne.Report`` =================================== This tutorial covers making interactive HTML summaries with :class:`mne.Report`. As usual we'll start by importing the modules we need and loading some :ref:`example data <sample-dataset>`: """ import os import matplotlib.py...
StarcoderdataPython
159709
#!/usr/bin/env python import time, sys from Adafruit_LEDBackpack import LEDBackpack from LEDLetterValues import * from timeit import default_timer grids = [LEDBackpack(address=i) for i in range(0x70, 0x74)] wait_time = float(sys.argv[2] if len(sys.argv) > 2 else raw_input("Wait time: ")) text = sys.argv[1] if len(sys...
StarcoderdataPython
3352918
<gh_stars>1-10 # -*- coding: utf-8 -*- # Copyright (2018) Hewlett Packard Enterprise Development LP # # 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...
StarcoderdataPython
1661797
class Code: """Translates Hack assembly language mnemonics into binary codes.""" @staticmethod def dest(mnemonic): """Returns the binary code of the dest mnemonic.""" if 'A' not in mnemonic and 'M' not in mnemonic and 'D' not in mnemonic and mnemonic != "": raise KeyError ...
StarcoderdataPython
3371120
<filename>TOFD/dataloader.py import torch from torchvision import datasets,transforms import numpy as np from torch.utils.data.sampler import SubsetRandomSampler import os random_pad_size = 2 def get_train_valid_loader_cifars(batch_size, augment=True, ...
StarcoderdataPython
102359
import unittest import os import numpy as np from platform import python_implementation from sentinelhub import read_data, write_data, TestSentinelHub class TestIO(TestSentinelHub): class IOTestCase: def __init__(self, filename, mean, shape=(2048, 2048, 3)): self.filename = filename ...
StarcoderdataPython
38213
from bs4 import BeautifulSoup import time from kik_unofficial.datatypes.xmpp.base_elements import XMPPElement, XMPPResponse class Struct: def __init__(self, **entries): self.__dict__.update(entries) class OutgoingAcknowledgement(XMPPElement): """ Represents an outgoing acknowledgement ...
StarcoderdataPython
1714810
<reponame>foundation29org/F29.BioEntity from flask import current_app, request, make_response, jsonify from flask_restplus import Resource from ._api import * ''' Disease Successors/Predecessors ''' @API.route('/disease/successors/<string:ids>') @API.param('ids', 'Disease IDs') class disease_successors(Resource):...
StarcoderdataPython
1742480
<gh_stars>1-10 # -*- coding: utf-8 -*- import os import re import shutil import codecs import hashlib import chardet import json import stat import subprocess from .Config import g_conf from .Router import Router from enum import Enum class Color(Enum): BLACK = 30 RED = 31 GREEN = 32 YELLOW = 33 ...
StarcoderdataPython
1715906
<gh_stars>0 import sys import getopt class Options(object): def __init__(self, mandatory, optional=[], switches=[]): self.opts = {} self.__mand = mandatory self.__optn = optional self.__swtc = switches def __getattr__(self, attribute): if attribute in self.opts: return self.opts[attribu...
StarcoderdataPython
1613096
#Faça um Algoritmo que leia o preço de um produto e mostre seu novo preço, com 5% de desconto. preco = float(input('Qual o valor do seu produto? ')) desc = 0.05 precod = preco * (1-desc) print(f'Olá, seu produto de R${preco:.2f} estará saindo por R${precod:.2f}' )
StarcoderdataPython
4835277
""" https://www.freecodecamp.org/learn/scientific-computing-with-python/python-for-everybody/comparing-and-sorting-tuples Which does the same thing as the following code?: lst = [] for key, val in counts.items(): newtup = (val, key) lst.append(newtup) lst = sorted(lst, reverse=True) print(lst) Choices: pri...
StarcoderdataPython
4814290
<reponame>0201shj/Python-OpenCV<filename>Chapter02/0211.py # 0211.py import cv2 import matplotlib.pyplot as plt #1 def handle_key_press(event): if event.key == 'escape': cap.release() plt.colse() def handle_close(evt): print('Close figure!') cap.release() #2 프로그램 시작 cap = cv2...
StarcoderdataPython
1655242
<reponame>nachovazquez98/COVID-19_Paper<filename>covid_app.py<gh_stars>0 #https://blog.streamlit.io/uc-davis-tool-tracks-californias-covid-19-cases-by-region/ import streamlit as st import os import numpy as np import pandas as pd from PIL import Image import joblib import plotly.express as px from covid_graficas impor...
StarcoderdataPython
1681168
# Copyright 2022 Tiernan8r # # 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, so...
StarcoderdataPython
5733
<reponame>fabaff/spyse-python import requests from typing import List, Optional from .models import AS, Domain, IP, CVE, Account, Certificate, Email, DNSHistoricalRecord, WHOISHistoricalRecord from .response import Response from .search_query import SearchQuery from limiter import get_limiter, limit class DomainsSea...
StarcoderdataPython
35655
'''4. Write a Python program to check whether multiple variables have the same value.''' var1, var2, var3 = 20, 20, 20 if var1 == var2== var3: print("var1, var2, and var3 have the same value !")
StarcoderdataPython
1648022
<filename>paasta_tools/contrib/delete_old_marathon_deployments.py #!/usr/bin/env python # Copyright 2015-2016 Yelp Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apac...
StarcoderdataPython
1711303
<reponame>tefra/xsdata-w3c-tests from dataclasses import dataclass, field @dataclass class Iri3987: class Meta: name = "IRI-3987" value: str = field( default="", metadata={ "required": True, "pattern": r"", } ) @dataclass class IriReference3987: ...
StarcoderdataPython
4815432
import json import sys from pathlib import Path TYPE_ENUM_ENTRY_TEMPLATE = "\ %(enum_id)s(%(enum_type)s),\n" ID_ENUM_ENTRY_TEMPLATE = "\ %(enum_id)s = %(enum_value)#04x,\n" ID_TRY_FROM_MATCH_ENTRY_TEMPLATE = "\ x if x == SEOutputDataId::%(enum_id)s as u16 => Ok(SEOutputDataId::%(enum_id)s),\n" OUTPUT_TE...
StarcoderdataPython
86423
# Spider: A Spider in the game. The most basic unit. # DO NOT MODIFY THIS FILE # Never try to directly create an instance of this class, or modify its member variables. # Instead, you should only be reading its variables and calling its functions. from games.spiders.game_object import GameObject # <<-- Creer-Merge: ...
StarcoderdataPython
3273466
<reponame>simonmeoni/JRSTC-competition from transformers import AutoConfig, AutoModel def rm_dropout(model, remove_dropout): if remove_dropout: cfg = AutoConfig.from_pretrained(model) cfg.hidden_dropout_prob = 0 cfg.attention_probs_dropout_prob = 0 return AutoModel.from_pretrained(...
StarcoderdataPython
3383142
import pytest from autogoal.contrib import find_classes classes = find_classes() @pytest.mark.contrib @pytest.mark.parametrize("clss", classes) def test_create_grammar_for_generated_class(clss): from autogoal.grammar import generate_cfg generate_cfg(clss, registry=classes) @pytest.mark.slow @pytest.mark.c...
StarcoderdataPython
1789931
<reponame>mohammadbashiri/bashiri-et-al-2021<filename>neuraldistributions/trainers.py<gh_stars>1-10 from copy import deepcopy from abc import ABC, abstractmethod import numpy as np import torch from torch import optim, nn from tqdm import tqdm, trange from neuralpredictors.training import LongCycler from .utility imp...
StarcoderdataPython
3345964
import string import talk DEBUGGING = False masterSchedule = [] talkPRE = '<h3 class="talkTitle">' talkPOST = '</h3>' dayTimeTrackPRE = '<p class="abstract">' dayTimeTrackPOST = '</p>' speakerPRE = '<h4 class="speaker">' speakerPOST = '<span' descriptionPRE = '<p class="abstract">' descriptionPOST = '</p>' def P...
StarcoderdataPython
1703919
<filename>tensorflow_/2zhang/14_tf_keras_regression-wide&deep-multi-input.py # coding:utf-8 import matplotlib as mpl import matplotlib.pyplot as plt # %matplotlib inline import numpy as np import sklearn import pandas as pd import os import sys import time import tensorflow as tf from tensorflow import keras # 打印nam...
StarcoderdataPython
3326239
<filename>results-dissertation/cosine-sim/plot.py import matplotlib.pyplot as plt from scipy.spatial import distance from scipy import spatial a = [1, 2] b = [2, 1] c = distance.euclidean(a, b) a = [1, 2, 3] b = [3, 2, 1] c = [2, 3, 1] print(1 - spatial.distance.cosine(a, b)) print(1 - spatial.distance.cosine(a,...
StarcoderdataPython
1635680
<reponame>fbickfordsmith/attention-msc """ Define a set of 20 difficulty-based category sets. These are subsets of ImageNet categories that we choose to have varying difficulty (average error rate of VGG16) but equal size and approx equal visual similarity. Method: 1. Sort categories by the base accuracy of VGG16. 2. ...
StarcoderdataPython
3373648
<gh_stars>0 import numpy as np import pandas as pd import time as time import os def go_fish(fname): day_dir = os.path.realpath(__file__).split('/')[:-1] fname = os.path.join('/',*day_dir, fname) fish = np.array(pd.read_csv(fname).iloc[:,0].tolist()) # Initalize fish counts fish_counts = np.z...
StarcoderdataPython
4822147
<reponame>Monia234/NCI-GwasQc """Test parsing of Illumina BPM files.""" import pytest from cgr_gwas_qc.parsers.illumina import BeadPoolManifest from cgr_gwas_qc.testing.data import FakeData @pytest.fixture(scope="module") def bpm(): return BeadPoolManifest(FakeData._data_path / FakeData._illumina_manifest_file) ...
StarcoderdataPython
1733948
""" ``nn()`` is used to train an instance of ``globalemu`` on the preprocessed data in ``base_dir``. All of the parameters for ``nn()`` are kwargs and a number of them can be left at their default values however you will need to set the ``base_dir`` and possibly ``epochs`` and ``xHI`` (see below and the tutorial for d...
StarcoderdataPython
3333572
import numpy as np import cv2 def lambda_handler(event, context): print(cv2.__version__)
StarcoderdataPython
1698655
<gh_stars>10-100 ''' file bird_model.py @author <NAME>, <NAME> @copyright Copyright © UCLouvain 2020 multiflap is a Python tool for finding periodic orbits and assess their stability via the Floquet multipliers. Copyright <2020> <Université catholique de Louvain (UCLouvain), Belgique> List of the contributors to the...
StarcoderdataPython
1793142
#!/usr/bin/python import sys def fibonacci(n): if n == 0: return 0 elif n == 1: return 1 else: return fibonacci(n-1) + fibonacci(n-2) def main(): fibonacci(40) sys.exit(0) if __name__ == '__main__':main()
StarcoderdataPython
1626873
# from .models import BlogPost from django.db.models.signals import post_save, pre_save from django.dispatch import receiver @receiver(post_save, sender=BlogPost) def index_post(sender, instance, **kwargs): # import ipdb; ipdb.set_trace() instance.indexing() # @receiver(pre_save, sender=BlogPost) # def index_post(s...
StarcoderdataPython
45796
<reponame>SWuchterl/cmssw<gh_stars>1-10 import FWCore.ParameterSet.Config as cms process = cms.Process("TEST") process.load("FWCore.MessageLogger.MessageLogger_cfi") process.options = cms.untracked.PSet( wantSummary = cms.untracked.bool(True) ) process.source = cms.Source("EmptySource") process.maxEvents = cms.unt...
StarcoderdataPython
3327892
from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, BooleanField from wtforms.fields.html5 import EmailField from wtforms.validators import DataRequired, EqualTo, Email class RegisterForm(FlaskForm): email = EmailField("Email", validators=[DataRequired(), Email()]) password1 = Pass...
StarcoderdataPython
1621414
# Generated by Django 3.1.1 on 2020-10-03 15:19 from django.conf import settings from django.db import migrations class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('quiz', '0001_initial'), ] operations = [ migrati...
StarcoderdataPython
1691752
<filename>Census_Checker.py """ Geo-referencing GTFS with Census geographies methods by <NAME> """ import sys from osgeo import ogr from kdtree1 import * from kdtree2a import * from bst import * from point import * def getCensusTractsGDAL(long_lat_list, shapefile_name,MaxX,MaxY,MinX,MinY ...
StarcoderdataPython
1714267
<reponame>JacobHilbert/week_schedule from .schedule import schedule_figure
StarcoderdataPython
29847
#!/usr/bin/env python3 ''' ============================================================== Copyright © 2019 Intel Corporation SPDX-License-Identifier: MIT ============================================================== ''' import intel.tca as tca target = tca.get_target(id="whl_u_cnp_lp") components = [(c.component,...
StarcoderdataPython
88583
<reponame>Falldog/appengine-flask-template-light<gh_stars>0 from application import app @app.template_filter('reverse') def reverse_filter(s): return s[::-1] # app.jinja_env.filters['reverse'] = reverse_filte
StarcoderdataPython
3300991
# -*- coding: utf-8 -*- # Generated by Django 1.11.7 on 2018-01-31 06:55 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import lib.fields class Migration(migrations.Migration): dependencies = [ ('fleet_management', '0019_auto_20180124_14...
StarcoderdataPython
1659167
from .v0 import V0 from .v1 import V1 from .v2 import V2 from .v3 import V3
StarcoderdataPython
192790
from .variable import Variable from .basis_vector import BasisVector from .monomial_vector import MonomialVector from .chebyshev_vector import ChebyshevVector from .polynomial import Polynomial
StarcoderdataPython
82267
import scadnano as sc import modifications as mod import dataclasses def create_design(): stap_left_ss1 = sc.Domain(1, True, 0, 16) stap_left_ss0 = sc.Domain(0, False, 0, 16) stap_right_ss0 = sc.Domain(0, False, 16, 32) stap_right_ss1 = sc.Domain(1, True, 16, 32) scaf_ss1_left = sc.Domain(1, False,...
StarcoderdataPython
1633002
import numpy as np import torch from pgbar import progress_bar class RayS(object): def __init__(self, model, epsilon=0.031, order=np.inf): self.model = model self.ord = order self.epsilon = epsilon self.sgn_t = None self.d_t = None self.x_final = None self.q...
StarcoderdataPython
1711338
<reponame>shivamraval98/T5_AE<filename>src/eval_baseline.py import torch from models.bert_dataset_loader import * from models.bert_model import * from transformers import BertTokenizer, BertForSequenceClassification, Trainer, TrainingArguments from sklearn.metrics import classification_report ''' Function to te...
StarcoderdataPython
3303421
# ------------------------------------ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # ------------------------------------ from ._shared import parse_key_vault_id, KeyVaultResourceId def parse_key_vault_secret_id(source_id): # type: (str) -> KeyVaultResourceId """Parses a secret's...
StarcoderdataPython
1735310
from distutils.core import setup from Cython.Build import cythonize import numpy as np setup( name = "On-the-Fly Gridder", ext_modules = cythonize("src/*.pyx", include_path = [np.get_include()]), include_dirs = [np.get_include()] )
StarcoderdataPython
3320774
from sqlite3 import connect database_name = 'database.db' class DataBase: @staticmethod def createTable(query): try: con = connect(database_name) c = con.cursor() c.execute(query) except Exception as e: print("error:", e) @staticmethod...
StarcoderdataPython
1646527
import os def get_file_path(filename): if not os.path.exists('config'): os.makedirs('config') return 'config/' + filename
StarcoderdataPython
3217391
from pathlib import Path from time import time import tempfile import pytest from target_extraction.data_types import TargetTextCollection from target_extraction.dataset_parsers import CACHE_DIRECTORY from target_extraction.dataset_parsers import download_election_folder from target_extraction.dataset_parsers import ...
StarcoderdataPython
124871
<reponame>Nelestya/baseapp<gh_stars>0 from django.db import models #Abstract class class Recently(models.Model): created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def update_recent(self): """ return True if is updated recently """ ...
StarcoderdataPython
164043
<gh_stars>10-100 import torch as th from typing import Dict, Optional, Tuple from tpp.models.encoders.base.variable_history import VariableHistoryEncoder from tpp.utils.encoding import encoding_size from tpp.utils.events import Events class IdentityEncoder(VariableHistoryEncoder): """Variable encoder that passe...
StarcoderdataPython
98828
<reponame>Leonardo-Maciel/Truss_Maciel<filename>10truss/constrict.py def constrict(maxc,minc,dell): # Garante que as coordenadas de dell estão dentro dos limites # # next = constrict(maxc,minc,dell) # # next: vetor avaliado (com coordenadas dentro dos limites) # maxc: valor máximo das ...
StarcoderdataPython
1669950
from unittest import TestCase from yawast.scanner.plugins.dns import basic class TestGetMx(TestCase): def test_get_mx(self): recs = basic.get_mx("adamcaudill.com") self.assertTrue(len(recs) > 0) for rec in recs: if rec[0].startswith("aspmx4"): self.assertEqual...
StarcoderdataPython
1691350
import requests, datetime import json, os, os.path from .gqlclient import GqlClient from .constants import url, anime, manga from collections import namedtuple from .wrappers.media import Media, MediaTitle, AiringSchedule, MediaTrailer, MediaImage, MediaTag, MediaExternalLink, MediaStreamingEpisode from .wrappers.cha...
StarcoderdataPython
152310
<reponame>speer-kinjo/ro.py """ Grabs asset information. """ import asyncio from roblox import Client client = Client() async def main(): asset = await client.get_asset(8100249026) print("ID:", asset.id) print("Name:", asset.name) print(f"Description: {asset.description!r}") print("Type:", asse...
StarcoderdataPython
1645497
<gh_stars>0 # -*- coding: utf-8 -*- """ Django settings for server project. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their config, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ from django.utils.translation import u...
StarcoderdataPython
3267984
from share.transform.chain import * # noqa from share.transform.chain.utils import format_address def format_mendeley_address(ctx): return format_address( address1=ctx['name'], city=ctx['city'], state_or_province=ctx['state'], country=ctx['country'] ) RELATION_MAP = { 'r...
StarcoderdataPython
115509
<filename>benchmarks/sa.py #!/usr/bin/env python3 import time, argparse import numpy as np import arkouda as ak import random import string TYPES = ('int64', 'float64', 'bool', 'str') def time_ak_sa( vsize,strlen, trials, dtype): print(">>> arkouda suffix ...
StarcoderdataPython
3266952
<filename>Identification-of-Paintings-and-Style-Transfer/Identification/util.py import sys import os import numpy as np import cv2 import re def load_image(): filenames = list() for filename in os.listdir(sys.path[0]): filenames.append(filename) X1, X1names = list(), list() pat =...
StarcoderdataPython
1696778
<gh_stars>10-100 import shutil import sqlite3 import subprocess from os.path import dirname from pathlib import Path import regex # type: ignore import context from paroxython.cli_tag import main as tag_program from paroxython.preprocess_source import Cleanup import draw_flow PATH = f"{Path(dirname(__file__)).pare...
StarcoderdataPython
175370
<filename>build_dataset.py<gh_stars>0 import argparse from pathlib import Path import numpy as np import pandas as pd from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import train_test_split, KFold, StratifiedKFold import matplotlib.pyplot as plt OUTPUT = './data/' NC = 2 NAMES = ['benig...
StarcoderdataPython
3354857
import argparse import tempfile from flask import Flask from flask_cors import CORS from xplainer.backend.router import register_routes from xplainer.backend.utils.model import load_and_analyze def create_and_run_app(debug=False): parser = argparse.ArgumentParser(description="xxx") parser.add_argument("--mo...
StarcoderdataPython
1644526
<filename>tccli/services/billing/v20180709/help.py # -*- coding: utf-8 -*- DESC = "billing-2018-07-09" INFO = { "DescribeBillDetail": { "params": [ { "name": "Offset", "desc": "Offset" }, { "name": "Limit", "desc": "Quantity, maximum is 100" }, { ...
StarcoderdataPython
52648
<reponame>megatran/selflearning_openCV_ComputerVision import cv2 import numpy as np """ Corner matching in images is tolerant of: - Rotations - Translation - Slight photometric changes e.g brightness or affine intensity It is INTOLERANT OF: - large changes in intensity or photometric changes - scaling """ #import i...
StarcoderdataPython
3375218
# -*- coding: utf-8 -*- import importlib from . import operators from . import panels importlib.reload(operators) importlib.reload(panels) def register(): operators.register() panels.register() def unregister(): operators.unregister() panels.unregister()
StarcoderdataPython
27855
<filename>medicalseg/utils/utils.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/licenses/LICEN...
StarcoderdataPython
3305320
<filename>tests/test_util.py import unittest from falcon_crossorigin.util import _match_sub_domain class TestUtil(unittest.TestCase): def test_match_sub_domain(self): long_domain = "http://{}.com".format("a" * 254) # schemes are empty or do not match self.assertFalse(_match_sub_domain(""...
StarcoderdataPython
195814
<reponame>juhapekka/apitrace ########################################################################## # # Copyright 2011 <NAME> # Copyright 2008-2010 VMware, Inc. # All Rights Reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation fil...
StarcoderdataPython
1796032
<gh_stars>0 from requests import Session QUERY_URL = "https://reware-production.yerdle.io/v4/graphql" ITEM_URL_TEMPLATE = "https://wornwear.patagonia.com/shop/{slug}/{parentSKU}/{color}" def fetch_titles(session, offset, limit): query = """ { partner(uuid: "7d32ad83-330e-4ccc-ba03-3bb32ac113ac") { ...
StarcoderdataPython
1743868
<gh_stars>0 from __future__ import absolute_import from __future__ import division from __future__ import print_function import ray import numpy as np from runner import RunnerThread, process_rollout from LSTM import LSTMPolicy import tensorflow as tf import six.moves.queue as queue import gym import sys import os fro...
StarcoderdataPython
4830513
import torch from torch.utils.data import TensorDataset import pickle import numpy as np import pandas as pd from train_parameters import * from src.normalization import Normalization from src.voigt_rotation import * from src.model_utils import CPU_Unpickler def exportTensor(name,data,cols, header=True): df=pd.D...
StarcoderdataPython
1725389
<reponame>fernherrera/pylibrets """RETS search response parser classes.""" from xml.etree import ElementTree from .exceptions import RetsException class SearchResultSet(object): def GetReplyCode(self): pass def GetReplyText(self): pass def GetCount(self): pass def GetColum...
StarcoderdataPython
2776
<reponame>by-liu/SegLossBia import sys import logging from seglossbias.utils import mkdir, setup_logging from seglossbias.engine import default_argument_parser, load_config, DefaultTester logger = logging.getLogger(__name__) def setup(args): cfg = load_config(args) mkdir(cfg.OUTPUT_DIR) setup_logging(ou...
StarcoderdataPython
189198
from carberretta import Config from .bot import Bot
StarcoderdataPython
3274751
<filename>feedzero/feeds/tests/test_models.py from django.db.utils import IntegrityError from model_mommy import mommy import pytest from feedzero.feeds.models import Entry, EntryState, Feed, FeedManager @pytest.mark.django_db class TestFeedModel: def test_dunder_str(self, feed): """The model should rend...
StarcoderdataPython
1741806
# # For licensing see accompanying LICENSE file. # Copyright (C) 2020 Apple Inc. All Rights Reserved. # """Helper functions for calculating optimal binary quantization.""" from typing import Tuple import torch import torch.nn.utils.rnn as rnn_utils from quant.binary.ste import binary_sign def cost_function(matrix...
StarcoderdataPython
3305407
<gh_stars>0 import urllib from IPython import embed """This module should contain functions to parse specific formats""" def write_lsf_linetools_from_stscifile(stsci_file, output): """reads a stsci LSF file for COS, and writes the proper format that linetools expects. It currently works for the table versi...
StarcoderdataPython
3342455
# Generated by Django 2.2.9 on 2020-01-05 04:24 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('politicians', '0010_auto_20200105_0355'), ] operations = [ migrations.AddField( model_name='politicians', name='emai...
StarcoderdataPython
3387742
import yaml # 文字列でYAMLを定義 yaml_str = """ # 定義 color_def: - &color1 "#FF0000" - &color2 "#00FF00" - &color3 "#0000FF" # エイリアスのテスト color: title: *color1 body: *color2 link: *color3 """ # YAMLを解析 data = yaml.load(yaml_str) # エイリアスが展開されているかテスト print("title=", data["color"]["title"]) print("body=", data["col...
StarcoderdataPython
4838391
<filename>reagent/training/ranking/seq2slate_dr_trainer.py #!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. import logging import reagent.core.types as rlt import torch import torch.nn as nn import torch.nn.functional as F from reagent.core.dataclasses import field from re...
StarcoderdataPython
66530
<gh_stars>0 from dataactcore.models.stagingModels import ObjectClassProgramActivity from dataactcore.models.domainModels import SF133 from tests.unit.dataactvalidator.utils import number_of_errors, query_columns _FILE = 'b14_object_class_program_activity' _TAS = 'b14_object_class_program_activity_tas' def test_colu...
StarcoderdataPython
3246191
<reponame>davidbrownell/Common_Environment # ---------------------------------------------------------------------- # | # | SetupEnvironment.py # | # | <NAME> <<EMAIL>> # | 2018-02-11 12:59:02 # | # ---------------------------------------------------------------------- # | # | Copyright <NAME> ...
StarcoderdataPython
3362075
<reponame>Sinap/mazes # -*- coding: utf-8 -*- import random class BinaryTree(object): """ docstring for BinaryTree """ @staticmethod def on(grid): for cell in grid.each_cell(): neighbors = [] if cell.north: neighbors.append(cell.north) i...
StarcoderdataPython
3303118
<gh_stars>10-100 """ Harvester for the ASU Digital Repository for the SHARE project More information at https://github.com/CenterForOpenScience/SHARE/blob/master/providers/edu.asu.md Example API call: http://repository.asu.edu/oai-pmh?verb=ListRecords&metadataPrefix=oai_dc&from=2014-10-05T00:00:00Z """ from __futur...
StarcoderdataPython
1679341
<filename>alembic/versions/07d1fdb1f9e0_foreign_key_to_post_table.py<gh_stars>0 """foreign-key to post table Revision ID: 07d1fdb1f9e0 Revises: <PASSWORD> Create Date: 2022-01-08 23:55:39.058731 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '07d1fdb1f9e0' dow...
StarcoderdataPython
172629
import requests, sys from PIL import Image import time def calc_perc(u): tbpc = 0 img = Image.open(u) pic = img.load() total = img.height * img.width for h in range(img.height): for w in range(img.width): if isinstance(pic[w,h], int): if pic[w,h] == 0: tbpc += 1 else: try: if isinstanc...
StarcoderdataPython
1765862
import socket import os realpit = [] shadowpit = [] depth = [] def changeplayer(): if player == 1: player = 2 elif: player = 1 def choose(x, player, pit = []): if pit[x] or x==13 or x=6: pass else: hold = pit[x] now = x pit[x] = 0 while 1: now += 1 now = now%14 if player == 1 and now==13: ...
StarcoderdataPython