id
stringlengths
1
7
text
stringlengths
6
1.03M
dataset_id
stringclasses
1 value
28290
# -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2016-02-17 13:59 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.Creat...
StarcoderdataPython
143998
from typing import List, Set, Dict import json import pytumblr from api_tumblr.pytumblr_wrapper import RateLimitClient API_KEYS_TYPE = List[str] class BotSpecificConstants: """Values specific to my development environment and/or the social context of my bot, e.g. specific posts IDs where I need apply some overr...
StarcoderdataPython
1788201
pip install plotly_express #pip install category_encoders import calendar import pandas as pd import numpy as np from sklearn.model_selection import train_test_split import matplotlib.pyplot as plt pd.options.display.max_columns = None april20 = pd.read_csv('assets/2020_04.csv') march20 = pd.read_csv('assets/2...
StarcoderdataPython
199704
import functools import tensorflow as tf from gpflow import default_float from gpflow.utilities import to_default_float from gpflow.utilities.ops import square_distance, difference_matrix def cached(variable): def cache(func): func = tf.function(func, experimental_compile=True, experimental_relax_shapes=T...
StarcoderdataPython
3258198
# coding: utf-8 ''' This script reads data from Scopus xlsx files to process and laod in MongoDB. ''' import logging import pyexcel import models import keycorrection from accent_remover import * logging.basicConfig(filename='logs/scopus_loader.info.txt', level=logging.INFO) logger = logging.getLogger(__name__) def...
StarcoderdataPython
3321712
<reponame>claudiocassiano/ClaudioParticular print("Bem vindos ao nosso exercício!!!!\n") n1 = float (input("Digite a primeira nota: ")) n2 = float (input("digite a segunda nota: ")) soma = n1 + n2 if (soma <10) : print(f"O valor da soma que é {soma} é menor que 10.") elif (soma ==10) : print(f"O valor da soma...
StarcoderdataPython
1795271
from PyQt5.QtCore import QObject import socket import time import struct import base64 import subprocess import logging from Module.Packages import ClassBroadcastFlag class ClassBroadcast(QObject): parent = None current_ip = None socket_ip = None socket_port = None socket_buffer_size = None so...
StarcoderdataPython
3283351
# Добавить один билет на утилизацию по игре бинго 75 с помощью экранной клавиатуры def test_add_one_barcode_bingo_75_current_draw_keyboard(app, fixture_barcode_bingo75): app.utiliz.open_page_utilization() app.utiliz.click_bingo_75() get_value = app.utiliz.get_input_value() app.utiliz.modal_draw_ok() ...
StarcoderdataPython
186020
# The following templates are markdowns overview = """ ## Context Manufacturing process feature selection and categorization ## Content Abstract: Data from a semi-conductor manufacturing process Data Set Characteristics: Multivariate Number of Instances: 1567 Area: Computer Attribute Characteristic...
StarcoderdataPython
1638744
from redis import Redis, RedisError # Don't know what much to do here redis = Redis(host='redis', db=0)
StarcoderdataPython
133790
<filename>equilibrium_points/statistics_brief.py import os import warnings import numpy as np import random as rand import matplotlib.pyplot as plt import dynalysis.basics as bcs import dynalysis.classes as clss from itertools import combinations from scipy.stats import pearsonr from sklearn.cluster import KMeans from ...
StarcoderdataPython
1600980
from django.conf import settings from django.contrib.contenttypes.fields import GenericRelation from django.db import models from replies.models import Reply class PublicManager(models.Manager): def get_queryset(self): return super(PublicManager, self).get_queryset().filter(hidden=False).order_by('-creat...
StarcoderdataPython
3310957
<gh_stars>0 def metade(p = 0, form=False): p /= 2 return p if form is False else moeda(p) def dobro(p = 0, form=False): p *= 2 return p if form is False else moeda(p) def aumentar(p = 0, quant = 0, form=False): percent = p + (p*quant / 100) return percent if form is False else moeda(percen...
StarcoderdataPython
52559
import requests lis = [ {'http': '172.16.17.32:8888'}, {'http': '192.168.3.11:3129'}, {'http': '172.16.58.3:8181'}, {'http': '172.16.31.10:8010'}, {'http': '172.16.31.10:80'}, {'http': '192.168.3.11:31773'}, ] headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) Ap...
StarcoderdataPython
1725917
<reponame>DrZlo77/Python_Lesson3<gh_stars>0 # Получаем текст истории из файла 'Text_story' file = open('Text_story','r', encoding= 'utf-8') text_story = file.read() #================================================================================== # 1) методами строк очистить текст от знаков препинания; #Удаляем к...
StarcoderdataPython
3357148
<filename>rest_server.py #!/usr/bin/env python # -*- coding: utf-8 -*- # @Author : <NAME> (<EMAIL>) import os import uvicorn import argparse if __name__ == '__main__': parser = argparse.ArgumentParser(description="args of rest service") parser.add_argument("--host", default='0.0.0.0') parser.add_argumen...
StarcoderdataPython
1677640
"""Utils to make train/test splits""" import random flatten = lambda l: [item for sublist in l for item in sublist] def _train_test_keys_split( grouped_keys, n_train, if_insufficient_data='only_train' ): groups = list(grouped_keys) if n_train > len(groups): if if_insufficient_data == 'only_train...
StarcoderdataPython
1789858
<filename>GPflow/testing/test_config.py<gh_stars>10-100 import unittest import os import tensorflow as tf import gpflow from testing.gpflow_testcase import GPflowTestCase class TestConfigParsing(GPflowTestCase): def setUp(self): directory = os.path.dirname(os.path.realpath(__file__)) f = os.path.j...
StarcoderdataPython
1665074
from unittest import TestCase import datetime from hamcrest import assert_that, is_, contains from backdrop.core.timeseries import timeseries, HOUR, DAY, WEEK, MONTH, QUARTER, YEAR from tests.support.test_helpers import d, d_tz class TestTimeseries(TestCase): def test_returns_a_full_timeseries(self): ts =...
StarcoderdataPython
48
<filename>garaged/src/garage/tf/regressors/gaussian_mlp_regressor_model.py """GaussianMLPRegressorModel.""" import numpy as np import tensorflow as tf import tensorflow_probability as tfp from garage.experiment import deterministic from garage.tf.models import GaussianMLPModel class GaussianMLPRegressorModel(Gaussia...
StarcoderdataPython
1736217
""" I/O for FLAC3D format. """ import logging import struct import time import numpy from ..__about__ import __version__ as version from .._common import _pick_first_int_data from .._exceptions import ReadError, WriteError from .._files import open_file from .._helpers import register from .._mesh import Mesh meshio...
StarcoderdataPython
4813394
# Generated by Django 2.0.8 on 2018-10-14 15:45 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('feedbacks', '0012_auto_20181013_1230'), ] operations = [ migrations.CreateModel( name='SurveyCover', fields=[ ...
StarcoderdataPython
4810980
<reponame>chenzhengda/tensorflow import tensorflow as tf from tensorflow.python import ipu # Configure the IPU device. config = ipu.config.IPUConfig() config.auto_select_ipus = 2 config.configure_ipu_system() # Create a dataset for the model. def create_dataset(): mnist = tf.keras.datasets.mnist (x_train, y_tra...
StarcoderdataPython
1735478
<gh_stars>0 """ Copyright 2016 University of Auckland 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
3276765
#!/usr/bin/env python ''' Author: <NAME> @ RIKEN Copyright (c) 2020 RIKEN All Rights Reserved See file LICENSE for details. ''' import os,sys,glob def init(args, version): # pythonpath global base base=os.path.abspath(os.path.dirname(os.path.realpath(__file__))) sys.path.insert(0, os.path.join(base...
StarcoderdataPython
76161
""" n = 4 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 count: i + 1 f(i, j) = i (i + 1) / 2 + 1 + j 1 + 2 + 3 + 4 + ... + n = n (n + 1) / 2 """ n = int(input()) # k = 1 # for i in range(n): # for _ in range(i + 1): # print(k, end=' ') # k += 1 # print() """ Time Complexity: O(n^2) Space Complexity: ...
StarcoderdataPython
116069
import time import multiprocessing class SubprocessFunctionCaller(object): class CliFunction(object): def __init__(self, s2c, c2s, lock): self.s2c = s2c self.c2s = c2s self.lock = lock def __call__(self, *args, **kwargs): self.lock.acquire() ...
StarcoderdataPython
112514
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' This script just show the basic workflow to compute TF-IDF similarity matrix with Gensim OUTPUT : clemsos@miner $ python gensim_workflow.py How to use Gensim to compute TF-IDF similarity step by step ---------- Let's start with a raw corpus :<type 'list'> STEP 1 : Inde...
StarcoderdataPython
3356520
import numpy as np import random def supervised_model_cv_fit_predict(X_train_df, y_train, X_test_df, model, runs=5): y_preds = [] for i in range(runs): random.seed(i) model.fit(X_train_df, y_train) y_pred = model.predict(X_test_df) y_preds.append(y_pred) return y_preds d...
StarcoderdataPython
4813757
"""Application base, containing global templates.""" default_app_config = 'pontoon.base.apps.BaseConfig'
StarcoderdataPython
1713528
import numpy as np class SistemaLinear: def __init__(self, matriz = None , vetor_constante = None, dimensao = None, tipo = 'C'): self.matriz = matriz #Recebe a matriz dos coeficientes self.vetor_constante = vetor_constante # Recebe o vetor de constantates, tambem conhecido como vetor b ...
StarcoderdataPython
175777
import os from java.awt import Color, GridLayout from javax.swing import JPanel, JComboBox, JLabel, JFrame, JScrollPane, JColorChooser, JButton, JSeparator, SwingConstants, SpinnerNumberModel, JSpinner, BorderFactory, JCheckBox from net.miginfocom.swing import MigLayout from ij import IJ, WindowManager, ImagePlus, Ima...
StarcoderdataPython
3231302
# TestSwiftRegex.py # # This source file is part of the Swift.org open source project # # Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors # Licensed under Apache License v2.0 with Runtime Library Exception # # See https://swift.org/LICENSE.txt for license information # See https://swift.org/CONTRIBUT...
StarcoderdataPython
137967
<reponame>arthurtibame/cvat<filename>serverless/openvino/omz/public/faster_rcnn_inception_v2_coco/nuclio/model_handler.py # Copyright (C) 2020 Intel Corporation # # SPDX-License-Identifier: MIT import os from model_loader import ModelLoader class ModelHandler: def __init__(self, labels): base_dir = os.env...
StarcoderdataPython
3387563
<reponame>defianceblack/PyPattyrn<gh_stars>1000+ from abc import ABCMeta, abstractmethod from unittest import TestCase from pypattyrn.structural.composite import Composite class CompositeTestCase(TestCase): """ Unit testing class for the Composite class. """ def setUp(self): """ Initia...
StarcoderdataPython
21836
<gh_stars>0 from django.conf import settings from django.urls.conf import include, path from rest_framework.routers import DefaultRouter, SimpleRouter if settings.DEBUG: router = DefaultRouter() else: router = SimpleRouter() app_name = "api" urlpatterns = [ path("", include("summers_api.users.api.urls")),...
StarcoderdataPython
3348188
<reponame>mmmmlz/VQA_tencent """Test Demo for Quality Assessment of In-the-Wild Videos, ACM MM 2019""" # # Author: <NAME> # Email: <EMAIL> AT <EMAIL> DOT edu DOT cn # Date: 2018/3/27 # import torch from torchvision import transforms import skvideo #skvideo.setFFmpegPath(r'D:\apps\ffmpeg-N-102166-g1ab74bc193-win64-gpl\...
StarcoderdataPython
1787855
<filename>qcelemental/models/common_models.py from enum import Enum from typing import Any import numpy as np from pydantic import BaseModel, Extra ndarray_encoder = {np.ndarray: lambda v: v.flatten().tolist()} class Provenance(BaseModel): creator: str version: str = None routine: str = None class ...
StarcoderdataPython
3306135
import socket import select import struct from threading import Thread import time import rsparse import doctest import base64 def make_sensor_list(lis): """ >>> make_sensor_list(['a', 1, 'b', 2]) [('a', 1), ('b', 2)] """ list = [] for i in range(len(lis)/2): list.append((lis[i*2], lis[...
StarcoderdataPython
92084
<reponame>grantps/superhelp from textwrap import dedent from tests import check_as_expected ROOT = 'superhelp.helpers.packing_help.' def test_misc(): test_conf = [ ( dedent("""\ pet = 'cat' """), { ROOT + 'unpacking': 0, ROOT...
StarcoderdataPython
1751533
import os, re def tex_escape(text): """Return text with problematic escape sequences parsed for Latex use. Note: This function was copied from the following StackOverflow answer, <https://stackoverflow.com/a/25875504/10134974> Parameters ---------- text : str a plain text message...
StarcoderdataPython
1793855
# Apply STG on XOR dataset from stg import STG import numpy as np import scipy.stats # for creating a simple dataset import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score def generate_XOR_labels(X): y = np.exp(X[:,0]*X[:,1]) prob_1 = ...
StarcoderdataPython
3214215
a = 'Hello Python' print(a) #length print(len(a)) #index - slice string print(a[0]) print(a[1]) print(a[2:5]) #repeat print((a+'\n')*2)
StarcoderdataPython
3385731
from flask import Flask,request,Response,jsonify, make_response from flask_cors import CORS, cross_origin from recognizer import Recognizer; import cv2 import base64 import numpy as np app = Flask(__name__) @app.route('/') def application(): return "<center><h1>You are Hacked!!</h1></center>" @app.route('/reco...
StarcoderdataPython
1668253
# # General-purpose Photovoltaic Device Model - a drift diffusion base/Shockley-Read-Hall # model for 1st, 2nd and 3rd generation solar cells. # Copyright (C) 2008-2022 <NAME> r.c.i.mackenzie at googlemail.com # # https://www.gpvdm.com # # This program is free software; you can redistribute it and/or m...
StarcoderdataPython
1685835
import argparse import os import re class ShowUsageException(Exception): pass def dir_path(s): if os.path.isdir(s): return s else: raise ShowUsageException(f'"{s}" is not a directory') def origin_directory_pair(s): try: origin, path = s.split(':') except ValueError: ...
StarcoderdataPython
11772
# pylint: disable=missing-module-docstring # # Copyright (C) 2020 by UsergeTeam@Github, < https://github.com/UsergeTeam >. # # This file is part of < https://github.com/UsergeTeam/Userge > project, # and is released under the "GNU v3.0 License Agreement". # Please see < https://github.com/uaudith/Userge/blob/master/LIC...
StarcoderdataPython
3314659
""" @Author : Ailitonia @Date : 2021/08/15 1:19 @FileName : __init__.py.py @Project : nonebot2_miya @Description : @GitHub : https://github.com/Ailitonia @Software : PyCharm """ from datetime import datetime from nonebot import on_command, logger from nonebot.plugin.e...
StarcoderdataPython
124719
import math try: from ulab import scipy, numpy as np except ImportError: import scipy import numpy as np A = np.array([[3, 0, 2, 6], [2, 1, 0, 1], [1, 0, 1, 4], [1, 2, 1, 8]]) b = np.array([4, 2, 4, 2]) # forward substitution result = scipy.linalg.solve_triangular(A, b, lower=True) ref_result = np.array(...
StarcoderdataPython
4837301
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'symmGui.ui' # # Created by: PyQt5 UI code generator 5.6 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow....
StarcoderdataPython
1696392
<reponame>ryosuke0825/atcoder_python switch, light = map(int, input().split()) K = [] for _ in range(light): k = list(map(int, input().split())) K.append(k) P = list(map(int, input().split())) ans = 0 # bit全探索で全パターンをチェックする for i in range(2**switch): # 各電球につながっているスイッチが何個ONか switch_on_list = [0]*light ...
StarcoderdataPython
3331474
# converts yaml configuration file to json file # usage: python <yaml_input_filename> <json_output_filename> # called by build_resources.sh script import json import sys import yaml from yaml_tools import Loader yaml_file = sys.argv[1] json_file = sys.argv[2] Loader.add_constructor('!include', Loader.include) with...
StarcoderdataPython
3253084
from .controller import Controller from .view import View from .module import Module from abc import ABC class Options(ABC): Controller = Controller View = View Module = Module
StarcoderdataPython
1617796
<reponame>collaborative-robotics/ABT #!/usr/bin/python # # # Revised to match fig BT-01164_Huge.png # from BT-Hmm proposal May 18 import os as os # b3 class modified by BH, local version in current dir import b3 as b3 # behavior trees import random as random import math as m import numpy as np #impo...
StarcoderdataPython
125291
import random import re import math import numpy as np from src import constants from src.multi_agent.elements.camera import Camera, CameraRepresentation from src.my_utils import constant_class from src.my_utils.my_math.bound import bound_angle_btw_minus_pi_plus_pi, bound from src.my_utils.my_math.line import distance...
StarcoderdataPython
1671687
from keras.layers import Dense, LeakyReLU, Reshape, Conv2DTranspose, Conv2D, Dropout, Flatten from keras.models import Sequential from mido import MidiFile, MidiTrack, Message from keras.optimizers import Adam from tensorflow.python.ops.init_ops import RandomNormal from scripts.DataLoader import DataLoader from script...
StarcoderdataPython
4803039
<reponame>hotpxl/minpy-jit<filename>minpy/segment.py #!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function import ast import types import inspect from collections import OrderedDict from functools import wraps, reduce from mxnet import nd from . import core _segment_cnt = 0 _ndarray_fun...
StarcoderdataPython
149239
<reponame>ma-compbio/MATCHA<gh_stars>10-100 import os import time import numpy as np import networkx as nx import random from tqdm import tqdm import torch from concurrent.futures import as_completed, ProcessPoolExecutor device = torch.device("cuda" if torch.cuda.is_available() else "cpu") device_ids = [0, 1] class ...
StarcoderdataPython
54388
<gh_stars>0 # -*- coding: utf-8 -*- """ Created on Wed Feb 19 08:43:36 2020 @author: HP """ #dataFrameName[column_name].dtype import statistics import pandas as pd import numpy as np import random #dataset=pd.read_csv(r"C:\Users\HP\Desktop\pp.csv") def missing(input_file): dataset=pd.read_cs...
StarcoderdataPython
1798456
<gh_stars>0 from yql import YQL from yql import Filter f1 = Filter('symbol', 'in', ['YHOO', 'GOOG', 'AAPL']) f2 = Filter('symbol', 'eq', 'YHOO') f3 = Filter('startDate', 'eq', '2014-02-11') f4 = Filter('endDate', 'eq', '2014-02-18') f1_expected = 'symbol IN ("YHOO", "GOOG", "AAPL")' f2_expected = 'symbol = "YHOO"' f3...
StarcoderdataPython
145886
# SdsViewProperty.py # # Copyright (C) 2018 OSIsoft, LLC. All rights reserved. # # THIS SOFTWARE CONTAINS CONFIDENTIAL INFORMATION AND TRADE SECRETS OF # OSIsoft, LLC. USE, DISCLOSURE, OR REPRODUCTION IS PROHIBITED WITHOUT # THE PRIOR EXPRESS WRITTEN PERMISSION OF OSIsoft, LLC. # # RESTRICTED RIGHTS LEGEND # Use, dupl...
StarcoderdataPython
18833
<filename>src/fireo/utils/utils.py<gh_stars>0 import re from google.cloud import firestore def collection_name(model): return re.sub('(?!^)([A-Z]+)', r'_\1', model).lower() def ref_path(key): return key.split('/') def collection_path(key): return '/'.join(key.split('/')[:-1]) def get_parent(key): ...
StarcoderdataPython
1793255
# Script written by <NAME> # Last Update: November 23, 2020 # License: MIT from pathlib import Path import logging import os import subprocess from requests.adapters import HTTPAdapter from requests.packages.urllib3.util.retry import Retry import requests log = logging.getLogger() esp32 = "http://board_ip" # Ori...
StarcoderdataPython
1683620
""" 3D plotting ============ Demo 3D plotting with matplotlib and style the figure. """ import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import axes3d ax = plt.gca(projection='3d') X, Y, Z = axes3d.get_test_data(0.05) cset = ax.contourf(X, Y, Z) ax.clabel(cset, fontsize=9, inline=1) plt.xticks(()) plt.ytic...
StarcoderdataPython
1628646
import pymysql from threading import Thread from sys import exit class Database(object): def __init__(self, user, password, database): try: self.db = pymysql.connect ( host="127.0.0.1", port=3306, user=user, ...
StarcoderdataPython
59714
<gh_stars>0 import xadmin from .models import Course, UserAsk, UserCourse, UserFavorite, UserMessage class CourseAdmin(object): pass class UserAskAdmin(object): pass class UserCourseAdmin(object): pass class UserFavoriteAdmin(object): pass class UserMessageAdmin(object): pass xadmin.site...
StarcoderdataPython
1729905
<reponame>imasnyper/ltd-priority-list import random from list.models import Job def create_jobs(num_jobs, machine, customers): for x, i in enumerate(range(num_jobs)): rand_job_number = random.randrange(1000, 9999) rand_customer = random.choice(customers) rand_tools = random.choice([True, ...
StarcoderdataPython
1603240
<gh_stars>0 import sys sys.path.append("..") from preprocesspack import Attribute,DataSet,graphics,utils def test_all(): ##ATTRIBUTE ##Numeric Attribute attr=Attribute.Attribute(name="age",vector=[34,16,78,90,12]) attrContinuous=Attribute.Attribute(name="age",vector=[1.2,3.4,6.7,8.9,4.7]) ##Ca...
StarcoderdataPython
1642558
from django.apps import AppConfig class ReversionDynamoDBBackend(AppConfig): name = 'reversion.backends.dynamodb' label = 'reversion_backends_dynamodb'
StarcoderdataPython
86248
import os import xml.etree.ElementTree as et import argparse import pkgutil import shutil from subprocess import call import time from common import get_host_ip, get_unoccupied_port, is_port_in_use, get_pid_by_name from client import Client import re from colorama import init, Fore, Back, Style from logger import setup...
StarcoderdataPython
1638180
<reponame>mcjczapiewski/work<filename>check_photo_dpi.py # -*- coding: utf-8 -*- from __future__ import unicode_literals # import bibliotek from PIL import Image import os import datetime import codecs from natsort import natsort_keygen nkey = natsort_keygen() # root jesli chcemy wrzucac plik pythona do # foleru, w ...
StarcoderdataPython
1702057
<reponame>knp19i/story-prompt import sys import lib from collections import defaultdict # Get number of invalid prompts def get_num_errors(): try: errors_file = open(lib.ERRORS_FILE, 'r') error_lines = errors_file.readlines() errors_file.close() return len(error_lines) except F...
StarcoderdataPython
3298092
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data import matplotlib.pyplot as plt import os import numpy as np # mnist = input_data.read_data_sets("MNIST_data", one_hot=True) # print "basic information of mnist dataset" # print "mnist training data size: ", mnist.train.num_examples # ...
StarcoderdataPython
3315754
data = input("STDIN: ") print("STDOUT: " + data) raise ValueError("This is an error")
StarcoderdataPython
3288031
# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. # # 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 applica...
StarcoderdataPython
4807180
import sys import math # Auto-generated code below aims at helping you parse # the standard input according to the problem statement. experiments = [] result = 0 last_expr = 0 for i in range(int(input())): j, d = [int(j) for j in input().split()] # We will create a matrix of all the experiments experiment...
StarcoderdataPython
1631546
<filename>tests/testutils.py # -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2015-2019 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Files download/upload REST API similar to S3 for Inve...
StarcoderdataPython
3345965
from datetime import datetime from decimal import Decimal from unittest import mock import pytest from django.conf import settings from django_countries.fields import Country from django_scopes import scopes_disabled from pytz import UTC from pretix.base.models import ( Event, InvoiceAddress, Order, OrderPosition...
StarcoderdataPython
117203
<filename>my_code.py from py_extras import change_stmt def make_change(cost, amount_given): twenties = 0 tens = 0 fives = 0 ones = 0 quarters = 0 dimes = 0 nickels = 0 pennies = 0 # Making change in pennies (to avoid float math) change = round(((amount_given - cost) *...
StarcoderdataPython
4823145
# -*- coding: utf-8 -*- """ Created on 19-4-24 下午9:22 IDE PyCharm @author: <NAME> """ from torch.utils.data import Dataset import os import h5py as hf import torch from config import config import numpy as np class macaque_h5(Dataset): def __init__(self, data_path, list_path, mode): self.data_path = dat...
StarcoderdataPython
3262354
<filename>deploy/python/downloader/SAP_Scenarios.py #!/usr/bin/env python3 # # SMP Downloader # # License: GNU General Public License (GPL) # (c) 2019 Microsoft Corp. # class Package(object): selector_newest = 'max(range(len(results)), key=lambda index: results[index]["ReleaseDate"...
StarcoderdataPython
3306692
from . import _ST from . import pyFunctions as __pf from . import __plotPatterns__ as __pp _ST.SpikingTempotron.getVoltageTrace = __pf.__SpikingTempotron_getVoltageTrace _ST.SpikingTempotron.getVoltageTraceFromInputLayer = __pf.__SpikingTempotron_getVoltageTrace_1 _ST.Tempotron.w = __pf.__tempotron__w _ST.SpikeTrain.p...
StarcoderdataPython
1781448
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('stages', '0014_added_supervisionbill_model'), ] operations = [ migrations.AddField( model_name='student', name='supervision_attest_received', field=model...
StarcoderdataPython
3277241
""" Pre-train classifiers Author: <NAME> Date: 04/19/2016 """ import os import re import Porter_stemming as ps import math from sklearn.svm import SVC from sklearn.neighbors import KNeighborsClassifier from sklearn.tree import DecisionTreeClassifier from sklearn.externals import joblib # Helper function def tokenize_...
StarcoderdataPython
1768288
<gh_stars>100-1000 ''' Helper functions for writing out basis set references in various formats ''' from .. import api _lib_refs = ["pritchard2019a", "feller1996a", "schuchardt2007a"] _lib_refs_desc = 'If you downloaded data from the basis set\nexchange or used the basis set exchange python library, please cite:\n' ...
StarcoderdataPython
158262
from flask import request, jsonify from . import api from app.models import Comment, MessageBoard, PostView, History, Post import datetime from sqlalchemy import func from collections import OrderedDict def get_certain_day_sum_visit_count(visit_date): certain_day_visit_res = PostView.query.filter_by( visi...
StarcoderdataPython
1738457
#!/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 os import time import joblib import tqdm import glob import imageio import copy import numpy as np from typing im...
StarcoderdataPython
3313411
<gh_stars>0 """A show queue which can will be played sequentially.""" from collections import deque from typing import Tuple from mpf.assets.show import Show, RunningShow, ShowConfig from mpf.core.system_wide_device import SystemWideDevice class ShowQueue(SystemWideDevice): """Represents a show queue.""" c...
StarcoderdataPython
1626052
<reponame>overflowin-st-hackers/YouGotAppoint from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import status from .models import Doctor from .serializers import DoctorSerializer, UserSerializer, CurrentUserSerializer, AppointmentSerializer from django.short...
StarcoderdataPython
82152
<filename>verticapy/learn/pipeline.py # (c) Copyright [2018-2022] Micro Focus or one of its affiliates. # 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/LICENS...
StarcoderdataPython
3365877
'''OpenGL extension OES.fbo_render_mipmap This module customises the behaviour of the OpenGL.raw.GLES1.OES.fbo_render_mipmap to provide a more Python-friendly API Overview (from the spec) OES_framebuffer_object allows rendering to the base level of a texture only. This extension removes this limitation by a...
StarcoderdataPython
3328243
import json class ActorInfo: def __init__(self, name, id, html): self.name = name self.id = id self.titles = None self.html = html def set_titles(self, titles): self.titles = {title.id: title for title in titles} def add_titles(self, titles): if self.titles...
StarcoderdataPython
3397874
# Generated by Django 2.2.19 on 2021-06-07 20:16 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("archive", "0013_revise_protected_field"), ] operations = [ migrations.AlterField( model_name="digitizedwork", name=...
StarcoderdataPython
1763582
from datetime import datetime import tweepy import logging import requests from api import create_api logging.basicConfig(level=logging.INFO) logger = logging.getLogger() def get_random_quote(quotes_api_url, quotes_api_key): """ Get a random quote from quotes api. """ headers = {"Authorization": "Bearer {}"...
StarcoderdataPython
1711970
<reponame>uva-slpl/embedalign import numpy as np import sys from collections import defaultdict data = defaultdict(list) metric = None for line in sys.stdin: if line: parts = line.split(' ') for part in parts: k, v = part.split('=') if k == 'metric': metric ...
StarcoderdataPython
3367700
<gh_stars>0 from flask import Flask from config import Config import os from flask_mail import Mail, Message app = Flask(__name__, template_folder = '../template', static_folder = '../static') mail = Mail(app) app.config.from_object(Config) app.config['MAIL_SERVER'] = 'smtp.gmail.com' app.config['MAIL_POR...
StarcoderdataPython
1690122
<reponame>zipated/src #!/usr/bin/python # Copyright 2016 The ANGLE Project Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # # gen_format_map.py: # Code generation for GL format map. The format map matches between # {format,type} and ...
StarcoderdataPython
3362254
from .linear import Linear from .rnn import LSTM, GRU, LSTMCell, RNNCell, GRUCell __all__ = [ 'Linear', 'LSTM', 'GRU', 'LSTMCell', 'RNNCell', 'GRUCell', ]
StarcoderdataPython
120336
import csv import requests from collections import Counter from pprint import pprint as pp CSV_URL = 'https://bit.ly/2HiD2i8' def get_csv(): """Use requests to download the csv and return the decoded content""" resp = requests.get(CSV_URL) resp.raise_for_status() return resp.tex...
StarcoderdataPython
1795306
<filename>Backup/backup_190324/utils.py<gh_stars>1-10 import torch import torch.nn as nn import torch.nn.functional as F import random import os import wave as we import numpy as np import mir_eval import csv import re def melody_eval(ref, est): ref_time = ref[:,0] ref_freq = ref[:,1] est_time = est[:,0] ...
StarcoderdataPython