id
stringlengths
1
8
text
stringlengths
6
1.05M
dataset_id
stringclasses
1 value
4800359
<reponame>Dorothylyly/SAAT import cv2 import imageio import numpy as np import os from model import generate_model import torchvision.transforms as trn import torch import argparse from mean import get_mean, get_std from spatial_transforms import ( Compose, Normalize, Scale, CenterCrop, CornerCrop, ToTensor) def extr...
StarcoderdataPython
6627648
<reponame>y-akinobu/puppy B = Rectangle(500, 950, width=1000, height=100, isStatic=true) A = Ball(100,100,strokeStyle="yellow",lineWidth=30,width=100,height=100,fillStyle="green") print("Hello") def suzume_collision(): print("Bomb!") def suzume_clicked(): print("Chun") suzume = Circle(500,100,image='bird.png'...
StarcoderdataPython
333686
<reponame>josephsnyder/VistA-1 # # This file is part of WinPexpect. WinPexpect is free software that is made # available under the MIT license. Consult the file "LICENSE" that is # distributed together with this file for the exact licensing terms. # # WinPexpect is copyright (c) 2008-2010 by the WinPexpect authors. See...
StarcoderdataPython
3425593
<reponame>cavayangtao/rmtt_ros<gh_stars>0 #!/usr/bin/env python3 # coding=utf-8 import rospy import os import cv2 from geometry_msgs.msg import Twist from sensor_msgs.msg import Image import std_msgs.msg from cv_bridge import CvBridge from std_msgs.msg import Empty import math import sys import mediapipe as mp def ca...
StarcoderdataPython
8029223
<gh_stars>0 class AsyncOperationManager(object): """ Provides concurrency management for classes that support asynchronous method calls. This class cannot be inherited. """ def ZZZ(self): """hardcoded/mock instance of the class""" return AsyncOperationManager() instance=ZZZ() """hardcoded/returns an insta...
StarcoderdataPython
8148174
import re from typing import Callable, List, Tuple, Union from urllib.parse import parse_qsl, urlparse, urlsplit, urlunsplit, unquote_plus import requests from bs4 import BeautifulSoup from tld import get_fld from w3lib.url import url_query_cleaner __author__ = "<NAME>" __license__ = "MIT" __version__ = "0.0.8" __ma...
StarcoderdataPython
5150287
# Generated by Django 3.2.5 on 2021-07-27 13:03 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("connector_s3", "0016_alter_object_options"), ] operations = [ migrations.RemoveField( model_name="object", name="par...
StarcoderdataPython
230552
<filename>Widget testing/KivyMD Buttons/FlatButton.py from kivy.uix.screenmanager import Screen from kivymd.app import MDApp from kivymd.uix.button import MDRectangleFlatButton class MyApp(MDApp): def build(self): screen = Screen() screen.add_widget( #Rectangle Flat Button ...
StarcoderdataPython
139271
<filename>bldr/utils.py import os import pwd from pathlib import Path from pkg_resources import resource_filename class BLDRError(Exception): def __init__(self, msg: str, exitcode: int = 1) -> None: self.msg = msg self.exitcode = exitcode def __str__(self) -> str: return self.msg cl...
StarcoderdataPython
1791318
# -*- coding: utf-8 -*- ''' Created on 2015-8-21 @author: hustcc ''' from flask.globals import request, session # get / post data def get_parameter(key, default=None): ''' info:获得请求参数,包括get和post,其他类型的访问不管 ''' # post参数 if request.method == 'POST': param = request.form.get(key, default) ...
StarcoderdataPython
1878685
<reponame>oom-debugger/GraphZoo-1<gh_stars>1-10 """Base manifold""" from torch.nn import Parameter from typing import Tuple import torch class Manifold(object): """ Abstract class to define operations on a manifold """ def __init__(self): super().__init__() self.eps = 10e-8 def sq...
StarcoderdataPython
6641427
<gh_stars>0 #!/usr/bin/env python3 # -*- coding: utf-8 -*- import logging import os.path import pickle import random import re import traceback from spidery.utils.func import write_file, cap_sentence, num_to_alpha from .device_type import DeviceType UA_BIN = os.path.join(os.path.dirname(os.path.abspath(__...
StarcoderdataPython
240808
import torch import torch.nn as nn from torchvision import models def double_conv(in_channels, out_channels): return nn.Sequential( nn.Conv2d(in_channels, out_channels, 3, padding=1), nn.ReLU(inplace=True), nn.Conv2d(out_channels, out_channels, 3, padding=1), nn.ReLU(inplace=True) ...
StarcoderdataPython
9693226
<gh_stars>1-10 import os import sys from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait def resource_path(another_way):...
StarcoderdataPython
94724
<reponame>digitalinteraction/openmovement-python<filename>src/openmovement/load/base_data.py """ Base class for timeseries data loader """ from abc import ABC, abstractmethod class BaseData(ABC): def __init__(self, filename, verbose=False): """ Construct a data object from a file. :param...
StarcoderdataPython
5117362
from fastai.text.all import * import torch from transformers import GPT2TokenizerFast, GPT2LMHeadModel import pandas as pd import sys pretrained_weights = 'gpt2' tokenizer = GPT2TokenizerFast.from_pretrained(pretrained_weights) def tokenize(text): toks = tokenizer.tokenize(text) return tensor(tokenizer.conve...
StarcoderdataPython
10586
# # Copyright (C) 2018 The Android Open Source Project # # 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 la...
StarcoderdataPython
4810257
<filename>atividade2/util.py # -*- coding: utf-8 -*- ''' Metodos a serem usados em mais de uma questao serao colocados aqui ''' # Definicao de metodos def truncar(valor): if(valor < 0.0): return 0.0 elif(valor > 255.0): return 255.0 return valor
StarcoderdataPython
8169798
<reponame>harry-consulting/SAEF1 from django.contrib.contenttypes.models import ContentType from django.test import TestCase from model_bakery import baker from users.models import User, ObjectPermission from util.test_util import ClientLoginTestCase, ClientLoginDatalakeTestCase class UserManagerTests(TestCase): ...
StarcoderdataPython
3331156
<reponame>fyancy/Meta-Learning-in-Fault-Diagnosis """ Relation Networks programmed by <NAME>. (2021/8/30) """ import torch import numpy as np import learn2learn as l2l import visdom import os import time from Models.RelationNet.relation_model import encoder_net, relation_net from Datasets.cwru_data import MAML_Datase...
StarcoderdataPython
4937767
# -*- coding: utf-8 -*- # !/usr/bin/env python3 class ImportError(Exception): def __init__(self, fails): super(ImportError, self).__init__("You need to install the following packages:" + str(fails) + "\n" + " " * 24 + "$ pip3 install <package>") class UnsupportedHashingAlgorythm(Exception): def __in...
StarcoderdataPython
117065
<filename>cloud2/test.py from multiprocessing import Queue import cv2 if __name__ == '__main__': cap = cv2.VideoCapture(0) ret, frame = cap.read() frame = cv2.rotate(frame, cv2.ROTATE_180) cv2.imshow('image', frame) cv2.waitKey(0) # q = Queue(maxsize=1) # print('Add first message') # ...
StarcoderdataPython
1974941
# coding: utf-8 """Logging tools, built upon those from the logging standard library.""" import logging import functools import inspect import os from yaptools import check_type_validity LOGGING_LEVELS = { 'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARNING, 'warn': logging.WARN, '...
StarcoderdataPython
1616605
<reponame>MatteoRomiti/Lightning-Network-Deanonymization<filename>src/load_data.py # This script loads data to be imported from other scripts import pandas as pd import time from utils import read_json, level1_folder, level2_folder, results_folder from sort_mapping_entities import star_file, snake_file, collector_file...
StarcoderdataPython
6563763
from ... import microbuild # Uses @microbuild.task form instead of @microbuild.task() form. @microbuild.task def clean(): pass
StarcoderdataPython
3253747
#!packages/bin/python3 import sys import os import pickle sys.path.append('scripts/') from arduino_comms import Database, Monitor from comms_emulate import EmuSystem # EDIT ARDUINO PORT VALUE FOUND ON RPI PORT = '/dev/ttyACM0' # --------------------------- SETUP SYSTEM ----------------------------------- # if __name_...
StarcoderdataPython
3412563
<gh_stars>1-10 # this file is an adaptation from the work at mozilla deepspeech github.com/mozilla/DeepSpeech import itertools import kenlm from heapq import heapify from os.path import abspath, exists import numpy as np from pattern3.metrics import levenshtein from util.ctc_util import get_alphabet # the LER is jus...
StarcoderdataPython
1711884
<reponame>nailgun/seedbox<gh_stars>10-100 import itertools import json from flask import request from seedbox import models def render(node, indent=False): return IgnitionConfig(node).render(indent) class IgnitionConfig(object): def __init__(self, node): self.node = node self.cluster = nod...
StarcoderdataPython
1925021
#!/usr/bin/env python3 from flask import Flask, request, render_template import pickle import yaml import ruamel.yaml app = Flask(__name__) global_variable = ['global_user', '454CA7B2A26E50D8C51572C4D8A023693DDC404F4C563C98DD15818DF83D4F9R'] @app.route('/', methods=['GET']) def index(): local_variable = ['loca...
StarcoderdataPython
8024100
#!/usr/bin/env python3 # date: 2019.11.07 # from bs4 import BeautifulSoup as BS text = '<p class="A">text A</p> <p>text B</p> <p id="C">text C</p> <p data="D">text D</p>' soup = BS(text, 'html.parser') # --- without class and id # `class` is reserved keyword so BS uses `class_` all_items = soup.find_all('p', cla...
StarcoderdataPython
6670477
import os secrets_directory = "/run/secrets" def get(secret_name, default_value=None): """ Get a docker secret :param secret_name: :param default_value: :return: """ secret_file = os.path.join(secrets_directory, secret_name) try: with open(secret_file, 'r') as fpt: ...
StarcoderdataPython
1951949
### WEB SERVER IMPORTS ### from flask import Flask from flask import json from flask import request ### OTHER IMPORTS ### import json from libs import req import os import time from datetime import datetime, timedelta import hmac, hashlib ########################### ### LOADING SETTINGS from config import mist_conf fr...
StarcoderdataPython
9699829
<gh_stars>10-100 from grano.core import db, url_for from grano.model.common import UUIDBase from grano.model.property import Property, PropertyBase class Entity(db.Model, UUIDBase, PropertyBase): __tablename__ = 'grano_entity' same_as = db.Column(db.Unicode, db.ForeignKey('grano_entity.id'), ...
StarcoderdataPython
9633911
import os import csv from sklearn.datasets import make_spd_matrix import autograd.numpy as np from numpy import linalg as la, random as rnd import pymanopt from pymanopt.manifolds import Sphere from algorithms import ConjugateGradient, BetaTypes def create_cost(A): @pymanopt.function.Autograd def cost(x): ...
StarcoderdataPython
9794226
<gh_stars>1-10 # -*- coding: utf-8 -*- """Tests for reflinks script.""" # # (C) Pywikibot team, 2014-2015 # # Distributed under the terms of the MIT license. # from __future__ import absolute_import, unicode_literals from scripts.reflinks import XmlDumpPageGenerator, ReferencesRobot, main from tests import join_xml_d...
StarcoderdataPython
5029265
<filename>sitdown/views.py import datetime import matplotlib.pyplot as plt import numpy as np from collections import defaultdict, OrderedDict, UserDict from functools import total_ordering from typing import List from sitdown.core import Plottable, MutationSet class MonthSet(UserDict, Plottable): """An ordere...
StarcoderdataPython
3598722
# -*- coding: utf-8 -*- """ @date: 2022/5/9 下午3:48 @file: spoc.py @author: zj @description: """ import torch spatial_weight_cache = dict() def get_spatial_weight(h, w): """ Spatial weight with center prior. """ if (h, w) in spatial_weight_cache: spatial_weight = spatial_weight_cache[(h, w)...
StarcoderdataPython
6703218
import RPi.GPIO as GPIO # Named GPIO to physical pin mapping and mains plug with color of wire and default relay state (Normally Open, Normally Closed) PINS = { 'heat' : { "name" : "Heat Mat", "gpio" : 23, "color" : "grey", "plug" : 4, "pin" : 1, "default" : GPIO.LO...
StarcoderdataPython
12865703
""" Defines caching before for user preferences """ import jwt import time from cachetools import TTLCache from typing import Optional class CredentialCache(TTLCache): """ Subclass of TTLCache that temporarily stores and retreives user login credentials Arguments: TTLCache {TTLCache} -- A TTLCac...
StarcoderdataPython
11349661
#!/usr/bin/python # # Copyright 2020 <NAME> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed...
StarcoderdataPython
8175079
<reponame>xswz8015/infra<gh_stars>0 # -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: chromeperf/pinpoint/comparison.proto from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflecti...
StarcoderdataPython
11287244
import os import sys import numpy as np from random import shuffle assert len(sys.argv) == 3, "Usage: Python util.py [index authora] [index authorb]" ; def process(a,capa=None, capb=None): a = str(a) aout = open(a + '.out','w') bout = open('many.out','w') step = 15 start = int(step/2) stop = 1...
StarcoderdataPython
8000814
""" Unit tests for the ska_tmc_cdm.schemas.subarray_node.configure.sdp module. """ import pytest from ska_tmc_cdm.messages.subarray_node.configure import SDPConfiguration from ska_tmc_cdm.schemas.subarray_node.configure.sdp import SDPConfigurationSchema from ... import utils VALID_JSON = """ { "interface": "http...
StarcoderdataPython
1804934
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * from alipay.aop.api.domain.WorldTicketType import WorldTicketType class WorldOfflineDataInfo(object): def __init__(self): self._auth_mode = None self._available_ticket_types = None ...
StarcoderdataPython
11301387
<reponame>hrnoh/SpeechSplit<filename>conversion.py import torch import pickle import numpy as np from hparams import hparams from utils import pad_seq_to_2 from utils import quantize_f0_numpy from model import Generator_3 as Generator from model import Generator_6 as F0_Converter import matplotlib.pyplot as plt import ...
StarcoderdataPython
11293588
<filename>Lists/Sort_With_ Sorted.py animals = ['chicken', 'cow', 'snail', 'elephant'] print(animals) # ['chicken', 'cow', 'snail', 'elephant'] s = sorted(animals) print(s) # ['chicken', 'cow', 'elephant', 'snail'] print(animals) # ['chicken', 'cow', 'snail', 'elephant'] r = sorted(animals, reverse=True, key=len) pri...
StarcoderdataPython
5010044
<reponame>exogen/80sheep import logging __all__ = ['String', 'Base32', 'Set', 'Flag', 'Delimited', 'Integer', 'Boolean', 'BitField', 'Parameter', 'ParameterCollection'] log = logging.getLogger(__name__) class ParameterType(object): def encode(self, value): return value def decode(self...
StarcoderdataPython
6643021
import pandas as pd crime_csvs = [ ] def load_and_reshape_police(filename): df = pd.read_csv(filename, usecols=['REF_DATE', 'GEO', 'Statistics', 'VALUE']) index = (df["Statistics"] == "Police officers per 100,000 population") df = df[index] df = df.pivot(index='REF_DATE', columns='GEO', values='VALUE...
StarcoderdataPython
354163
<reponame>adamcharnock/factorio-status-ui<gh_stars>1-10 #!/usr/bin/python import asyncio import socket import struct import sys import logging from factorio_status_ui.state import application_config MESSAGE_TYPE_AUTH = 3 MESSAGE_TYPE_AUTH_RESP = 2 MESSAGE_TYPE_COMMAND = 2 MESSAGE_TYPE_RESP = 0 MESSAGE_ID = 0 logge...
StarcoderdataPython
5158991
import typing def main() -> typing.NoReturn: w, a, b = map(int, input().split()) if a > b: a, b = b, a print(max(0, b - (a + w))) main()
StarcoderdataPython
6648944
""" A simple CLI to deploy models to the spam detection API. It supports: - tagging models with human-readable names - deploying by tag - rollback """ import argparse from typing import List, Optional, Sequence, TextIO _DB_RESERVED_CHAR = "=" def db_set(*, db: TextIO, key: str, value: str) -> None: if _DB_RE...
StarcoderdataPython
9789640
<filename>tests/functional/context/validation/test_potential_types.py import pytest from vyper.context.types.indexable.sequence import ArrayDefinition from vyper.context.types.value.address import AddressDefinition from vyper.context.types.value.boolean import BoolDefinition from vyper.context.types.value.numeric impo...
StarcoderdataPython
8083393
<filename>pyEOM/datasets/predefined/MODIS/MYD13Q1.py __author__ = 'we32zac' from pyEOM.datasets import Dataset as DatasetAbs class Dataset(DatasetAbs): shortname = 'MYD13Q1' platform = 'Aqua' collection = '005' rastertype = 'Tile' timeInterval = 'P16D' host = 'http://e4ftl01.cr.u...
StarcoderdataPython
65210
<filename>modules/guidance.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Sep 1 22:24:28 2018 @author: jvdgoltz """ import numpy as np from cvxopt import matrix, solvers, sparse, spdiag, spmatrix def solve(x0,targetalt,targetvel,amax,dt=0.5,t_max=12*60): r = np.array([0,targetalt,targetvel,...
StarcoderdataPython
1774693
# AUTOGENERATED! DO NOT EDIT! File to edit: source_nbs/06_read_write_tfrecord.ipynb (unless otherwise specified). __all__ = ['serialize_fn', 'make_tfrecord_local', 'make_tfrecord_pyspark', 'make_tfrecord', 'chain_processed_data', 'write_tfrecord', 'make_feature_desc', 'reshape_tensors_in_dataset', 'add_loss...
StarcoderdataPython
1602466
# -*- coding: utf-8 -*- """ Created on Sat Oct 3 23:08:16 2020 @author: ninjaac """ #poision distribution import math def poision_D(k,lamp): return (lamp**k)*(math.exp(-lamp))/math.factorial(k) result=poision_D(5,2.5) print('%.3f'%result) #poision challeng 2 averageX, averageY = [float(num)...
StarcoderdataPython
4877270
<reponame>ferrumie/multi-pay<filename>api/extenal/ravepayment.py<gh_stars>0 import os from api.exceptions import FlutterException from api.payment import PaymentInterface from api.request import Request from transaction.models import Transaction class RavePayment(Request, PaymentInterface): ''' Extends the c...
StarcoderdataPython
12839355
<reponame>leo60228/everestbot<gh_stars>1-10 import time import config import discord from discord.ext import commands class EverestPins: def __init__(self, bot): self.bot = bot @commands.command() async def ahorn(self, ctx): embed = discord.Embed(title="Ahorn Downloads", ...
StarcoderdataPython
142492
from sqlobject import * from sqlobject.tests.dbtest import * ######################################## ## Expiring, syncing ######################################## class SyncTest(SQLObject): name = StringCol(length=50, alternateID=True, dbName='name_col') def test_expire(): setupClass(SyncTest) SyncTest(...
StarcoderdataPython
3539427
<reponame>DavidBitner/Aprendizado-Python n = int(input()) for i in range(0, n): resultado = 0 A, B = input().split(" ") x, y = int(A), int(B) if x % 2 == 0: x += 1 base = x + y * 2 for impar in range(x, base, 2): resultado += impar print(resultado)
StarcoderdataPython
5149589
from .gpu import set_gpu, run_and_release from .keras_tuner_hiplot.kt2hip import fetch_my_experiment from .debug import inspect_distances from .visualize import (visualize_distance_distribution, plot_history, visualize_pairs, visualize_distances)
StarcoderdataPython
1625069
<filename>corehq/apps/tzmigration/templatetags/tzmigration.py from __future__ import absolute_import from django import template from corehq.apps.domain_migration_flags.api import get_migration_status from corehq.apps.tzmigration.api import TZMIGRATION_SLUG register = template.Library() @register.filter def tzmigrat...
StarcoderdataPython
102338
<gh_stars>100-1000 # -*- coding: utf-8 -*- import numpy as np import pytest from npdl import activations def test_activation(): from npdl.activations import Activation act = Activation() with pytest.raises(NotImplementedError): act.forward((10, 10)) with pytest.raises(NotImplementedError)...
StarcoderdataPython
4827265
# -*- coding: utf-8 -*- """ Created on 06 Jan 2021 16:57:17 @author: jiahuei python -m unittest coco_caption/test_coco_caption.py """ import unittest import os from coca.coco_caption.eval import evaluate_caption_json from coca.data.mscoco import MscocoDataset from .paths import TEST_DATA_DIRPATH class TestCocoCaptio...
StarcoderdataPython
6434974
<filename>tests/unit/factory/test_table.py __author__ = "<NAME>, <NAME>" __credits__ = "<NAME>" import unittest from nose.plugins.attrib import attr import os from jnpr.junos import Device from jnpr.junos.factory.table import Table from mock import patch from lxml import etree from jnpr.junos.op.phyport import PhyPo...
StarcoderdataPython
3450029
from flask.testing import FlaskClient from tests import endpoint def test_widgets_return_models(client: FlaskClient, admin_login: dict): resp = client.get(endpoint('/widgets')) assert resp.status_code == 401 assert resp.json['error'] == 'Token is missing!' resp = client.get(endpoint('/widgets'), he...
StarcoderdataPython
224984
<reponame>Emily3403/Emily_password<filename>src/emily_password/share/config.py #!/usr/bin/env python3.10 import json import os import string import sys import base64 from emily_password.share.constants import * from emily_password.share.utils import * my_name = "emily_password" config_name_mapping = { "encrypte...
StarcoderdataPython
1711988
"""Unit test to test get list of data.""" from unittest import TestCase from adefa import cli from adefa.tests import runner import mock @mock.patch('adefa.cli.print_api_response') class TestList(TestCase): """Unit test class to test get list of data.""" def test_list(self, mocked_print): items = ...
StarcoderdataPython
1925729
<reponame>fadamsyah/final-project import numpy as np import pandas as pd import numba as nb from controller_2D import Controller_v1 import rospy from pkg_ta.msg import Control from nav_msgs.msg import Odometry freq = 10 # Hz waypoints_np = np.load('waypoints/waypoints_interpolated.npy') # In the Arduino, CW is positi...
StarcoderdataPython
3410759
""" Script to find and fix problematic jobs for Slurm. """ import sys import re import pymysql import argparse import subprocess DB_CONFIG_FILENAME = '/etc/slurm-llnl/slurmdbd.conf' KILL_SCRIPT_FILENAME = '/tmp/SlurmFixer-kill-orphans.sh' CLUSTER_NAME = 'linux' # list job IDS for currently running processes without p...
StarcoderdataPython
11329628
# coding=utf-8 # Copyright 2018 The HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable...
StarcoderdataPython
6656503
"""How we configure our Interact Client connection.""" import os import json class Configuration: """How our client is configured.""" def __init__( self, pod, api_version, api_folder, api_list, profile_extension_table_alias, ...
StarcoderdataPython
4862714
import os import sys import glob import sconstest.eval def usage(): print "graph_scaling.py <scons|make|both> results_idx <build|update>" prefixes = {'scons' : 'scons_cleanbuild', 'make' : 'make_cleanbuild'} ford = ['small', 'middle', 'large', 'vlarge', 'vvlarge'] files = {'small' : 5000, '...
StarcoderdataPython
196590
<reponame>p-p-m/nodeconductor from __future__ import unicode_literals import functools import datetime import logging import time import calendar from django.db import models as django_models from django.db import transaction, IntegrityError from django.db.models import Q from django.conf import settings as django_se...
StarcoderdataPython
11382234
<filename>douban/douban/itemdang.py<gh_stars>1-10 # -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # http://doc.scrapy.org/en/latest/topics/items.html import scrapy class DangdangItem(scrapy.Item): _id = scrapy.Field() title = scrapy.Field() comments = scr...
StarcoderdataPython
192967
# coding: utf-8 """ flask_oauthlib.provider.oauth2 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Implemnts OAuth2 provider support for Flask. :copyright: (c) 2013 - 2014 by <NAME>. """ import os import logging import datetime from functools import wraps from flask import request, url_for, jsonify, json from flask i...
StarcoderdataPython
161875
<reponame>ScottehMax/pyshowdown import asyncio import configparser import importlib import os import ssl import sys from http.cookies import SimpleCookie from typing import Optional, List, Dict, TYPE_CHECKING import aiohttp from pyshowdown import connection, message if TYPE_CHECKING: from pyshowdown.plugins.plu...
StarcoderdataPython
11329156
<filename>alab_management/__init__.py """ Managing everything in the autonomous lab. """ __version__ = "0.4.1" from .device_view.device import BaseDevice, add_device from .sample_view import Sample, SamplePosition from .task_view.task import BaseTask, add_task from .utils.module_ops import import_task_definitions, im...
StarcoderdataPython
208679
<filename>qtt/__init__.py """ Quantum Technology Toolbox The QTT package contains functionality for the tuning and calibration of spin-qubits. The package is divided into subpacakges: - Measurements: functionality to perform measurements on devices - Algorithms: functionality to analyse measurements - Si...
StarcoderdataPython
12185
if __name__ == "__main__": print("Nothing yet...")
StarcoderdataPython
364773
<reponame>ltowarek/budget-supervisor # coding: utf-8 """ Salt Edge Account Information API API Reference for services # noqa: E501 OpenAPI spec version: 5.0.0 Contact: <EMAIL> Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six ...
StarcoderdataPython
8189911
<filename>hic3defdr/analysis/alternatives.py<gh_stars>0 """ Experimental module exposing variants of the HiC3DeFDR model for benchmarking purposes. """ import numpy as np import scipy.stats as stats from hic3defdr.analysis import HiC3DeFDR from hic3defdr.util.printing import eprint from hic3defdr.util.dispersion impo...
StarcoderdataPython
228653
<filename>setup.py import setuptools with open('README.md', mode='r') as fh: long_description = fh.read() setuptools.setup( name='dicom-factory', version='0.0.4', author='<NAME>', author_email='<EMAIL>', description='DICOM data generator for (mainly) testing purposes', long_description=lon...
StarcoderdataPython
5163194
<reponame>pauliacomi/adsutils """Define and perform conversions between different units used.""" from pygaps.utilities.exceptions import ParameterError _MOLAR_UNITS = { "mmol": 0.001, "mol": 1, "kmol": 1000, "cm3(STP)": 4.461e-5, "ml(STP)": 4.461e-5, } _MASS_UNITS = { 'amu': 1.66054e-27, '...
StarcoderdataPython
4827278
#! /usr/bin/env python # -*- mode: python; coding: utf-8 -*- # Copyright 2021 the HERA Collaboration # Licensed under the 2-clause BSD license. """Add RTP task jobid entry to the M&C database with a start_time of "now". This script can be used for either single obsid tasks or multiple obsid tasks. For multiple obsid ...
StarcoderdataPython
149555
from enum import Enum """ AUTOR: <NAME> """ class EnvironmentMetric(Enum): """Enumeration of possible environment metrics in the cell matrix""" EUCLIDEAN = 'Euclidean' MANHATTAN = 'Manhattan'
StarcoderdataPython
11276327
<reponame>shrev/mydig-webservice-new # Memex cluster oozie url - http://10.1.94.54:11000/oozie import requests class OozieJobs(object): def __init__(self, oozie_url='https://oozie.memexproxy.com/'): self.oozie_url = oozie_url def submit_oozie_jobs(self, property_dict): oozie_url = self.oozie...
StarcoderdataPython
1858415
<filename>invest_natcap/sdr/sdr.py """InVEST Sediment Delivery Ratio (SDR) module""" import os import csv import logging from osgeo import gdal from osgeo import ogr import numpy import pygeoprocessing.geoprocessing import pygeoprocessing.routing import pygeoprocessing.routing.routing_core logging.basicConfig(forma...
StarcoderdataPython
6665591
from rest_framework import serializers from django.contrib.auth import authenticate from django.contrib.auth.password_validation import validate_password from .models import * from ..jobs.models import * from ..departments.models import * class EmployeeRegisterSerializer(serializers.ModelSerializer): employee...
StarcoderdataPython
11376073
''' Here we import the following libraries: 1 - requests: To get the information from the source; 2 - pandas: To have better organization of the openings and endings songs of the animes, as well as its authors; 3 - graphGenerator: Function that generates the graph. ''' import requests import pandas as pd from .graphG...
StarcoderdataPython
377374
from .resnet import res50 from .resnet_cifar import res32_cifar
StarcoderdataPython
196031
#!/usr/bin/env python3 ####### # Imports and functions ####### import json import pandas as pd import argparse def get_arguments(): parser = argparse.ArgumentParser(description='') parser.add_argument("-in", "--input", help ="name of input file", required=True, type=str) parser.add_argument("-out", "--o...
StarcoderdataPython
1867056
# Time: O(n) # Space: O(n) class Solution: def maxDistToClosest(self, seats: List[int]) -> int: left_arr = [float('inf')]*len(seats) right_arr = [float('inf')]*len(seats) for i in range(len(seats)): if seats[i]!=1 and i>0: left_arr[i] = left_arr[i-1]+1 ...
StarcoderdataPython
1741341
import flask import functools def login_required(method): @functools.wraps(method) def wrapper(*args, **kwargs): if 'username' in flask.session: return method(*args, **kwargs) else: flask.flash("A login is required to see the page!") return flask.redirect(fla...
StarcoderdataPython
3384039
<reponame>simonw/optfunc import unittest import optfunc from StringIO import StringIO class TestOptFunc(unittest.TestCase): def test_three_positional_args(self): has_run = [False] def func(one, two, three): has_run[0] = True # Should only have the -h help optio...
StarcoderdataPython
1987565
<filename>client-tests/testWorkspaceService.py import unittest from biokbase.auth.auth_token import get_token from biokbase.workspaceService.Client import workspaceService from datetime import datetime import os import subprocess class TestWorkspaces(unittest.TestCase): @classmethod def setUpClass(cls): ...
StarcoderdataPython
6541800
import numpy as np def norm_Frobenius(A): f = np.sqrt(np.sum(A ** 2)) return f def divergence_KullbackLeible(A, B): B[B == 0] = 1e-6 AdivB = A / B AdivB[AdivB == 0] = 1e-6 d = np.sum(A * np.log(AdivB) - A + B) return d
StarcoderdataPython
3380787
def handle_data(data_files): from sklearn.preprocessing import MinMaxScaler data = [] for file in data_files: df = pd.read_csv(file) data += list(df.values) data = np.asarray(data) demand = data[:-48, 4] normalizer = MinMaxScaler(feature_range=(0,1)) dat...
StarcoderdataPython
1652675
from rest_framework_mongoengine import serializers from .models import restaurants class restaurantsSerializer(serializers.DocumentSerializer): class Meta: model = restaurants fields = ('restaurant_id', 'name', 'cuisine', 'borough', 'address', 'image', 'city') class restaurantListSerializer(serializers.DocumentS...
StarcoderdataPython
6698347
from airflow.models import DAG from airflow_ext.gfw.models import DagFactory from airflow_ext.gfw.operators.python_operator import ExecutionDateBranchOperator from datetime import datetime, timedelta PIPELINE = 'pipe_vms_belize' # # PIPE_VMS_BELIZE # class PipelineDagFactory(DagFactory): """Concrete class to ...
StarcoderdataPython