id
stringlengths
1
7
text
stringlengths
6
1.03M
dataset_id
stringclasses
1 value
1771801
import configparser import psycopg2 import boto3 from sql_queries import copy_table_queries, insert_table_queries, counting_queries def load_staging_tables(cur, conn): """ Copy data from S3 into staging tables. """ for query in copy_table_queries: try: print("Loading staging table.") ...
StarcoderdataPython
3343405
<filename>decode.py #!/usr/bin/env python3 def decode(data): # convert 36 bits to long integer value=int(data,2) # remove 12 least significant bits by shifting >> 12 value=value >> 12 # remove preambule - only 12 least significant bits are important value=value & 0xfff # lets check do we hav...
StarcoderdataPython
1715869
<reponame>ChristianSi/phoneng<filename>setup.py<gh_stars>1-10 import setuptools with open('README.md', 'r') as fh: long_description = fh.read() setuptools.setup( name='lytspel', version='2.0.7', author='<NAME>', author_email='<EMAIL>', description='A Simple Phonetic Respelling for the English ...
StarcoderdataPython
3289303
<gh_stars>0 import pytest import falcon from falcon import MEDIA_TEXT def test_response_set_content_type_set(): resp = falcon.Response() resp._set_media_type(MEDIA_TEXT) assert resp._headers['content-type'] == MEDIA_TEXT def test_response_set_content_type_not_set(): resp = falcon.Response() ass...
StarcoderdataPython
25588
<filename>models.py import ipdb import math import numpy as np import tensorflow as tf # N_DIM_STATE = 4 # N_DIM_ACTIONS = 2 N_DIM_STATE = 210*160 N_DIM_ACTIONS = 9 def batch_norm_init(inits, size, name): return tf.Variable(inits * tf.ones([size]), name=name) def weight_init(shape, name): return tf.Variable(...
StarcoderdataPython
1714373
# Generated by Django 3.2 on 2021-05-05 03:44 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('library_api', '0007_auto_20210505_0316'), ] operations = [ migrations.AlterField( model_name='meminjam', name='tanggal...
StarcoderdataPython
3261470
from flask_wtf import FlaskForm from wtforms import (BooleanField, StringField, HiddenField, PasswordField, validators, IntegerField, SubmitField) from wtforms.fields.html5 import DateTimeField from wtforms.widgets.html5 import DateTimeInput from ..common.constants import MAX_DESCRIPTION_LEN, STRI...
StarcoderdataPython
3385417
""" The ``display`` taxon groups applets implementing display interfaces, that is, interfaces for sending commands to a device that alters its transmittance and/or reflectance in response. Although some devices may receive periodic commands that embed 2d arrays of samples, they are still classified under the ``display...
StarcoderdataPython
143572
<reponame>bychkovav/gradient_descent import simpleGD as simple from mpl_toolkits import mplot3d import matplotlib.pyplot as plt import numpy as np from matplotlib import cm from matplotlib.ticker import LinearLocator, FormatStrFormatter # Gradient descent will be performed for Rosenbrock function: (a-x)**2+ b(y-x**2)*...
StarcoderdataPython
94743
<filename>scrapy-template/spider/{{class_prefix}}.py # -*- coding: utf-8 -*- import scrapy class {{class_prefix}}Spider(scrapy.Spider): name = '{{spider_name}}' allowed_domains = ['{{spider_name}}'] custom_settings = { 'CONCURRENT_REQUESTS': 2, 'DOWNLOAD_DELAY': 0.25 } defaultHeader...
StarcoderdataPython
3337261
<gh_stars>0 #! /usr/bin/env python3 if __name__=='__main__': a = 3 if a == 0: print("a==0") elif a > 0: print("a>0") else: print("a<0") b = 2 print("b >= 0") if b >= 0 else print("b < 0") if a > 0 and b > 0: print("a > 0 and b > 0")
StarcoderdataPython
1754525
class NewsPaper: def __init__(self, name): self.name = name class Book: BOOK_TYPES = ("PAPERBACK", "HARDCOVER", "EBOOK") def __init__(self, title, author, pages, price, booktype): self.title = title self.author = author self.pages = pages self.price = price...
StarcoderdataPython
1763297
from data import BayStars, Dragons, Eagles, Hawks, Carp, Tigers, Marines, Buffaloes, Swallows, Giants, Lions # Set alias of each team's name Buffaloes_name=["オリックス","おりっくす","バファローズ","ばふぁろーず","オリックスバファローズ","おりっくすばふぁろーず"] Swallows_name=["ヤクルト","やくると","スワローズ","すわろーず","ヤクルトスワローズ","やくるとすわろーず","東京ヤクルトスワローズ","とうきょうやくるとすわろーず"...
StarcoderdataPython
1650011
<gh_stars>1-10 import patent if __name__ == '__main__': google_patent = patent.get('CN1045110B', 'en') print(google_patent.title) print(google_patent.number) print(google_patent.inventors) print(google_patent.language) print(google_patent.claims)
StarcoderdataPython
123217
<filename>python/wiki.py class WikiPage: def __init__(self, title, uri=None, text=None, tags=None): self.title = title self.text = text or "" self.tags = tags or {} self.uri = uri or title self.parents = [] self.children = [] def add_child(self, pag...
StarcoderdataPython
3366295
<gh_stars>1000+ # Copyright DataStax, 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.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in...
StarcoderdataPython
45779
<reponame>Steven-Wilson/pyweek25 import model import pyxelen from view import * from sounds import * from utils import * def set_scene(state, **kwargs): return state.set(scene=state.scene.set(**kwargs)) def selection(state): return state.scene.selection def select_next(state): state = set_scene(state...
StarcoderdataPython
3202381
<reponame>EduardEdiJerkovic/Apr2 def hooke_jeeves(f, x0, dx=0.5, e=10 ** -6): iterations = 0 xp = x0.copy() xb = x0.copy() while True: iterations += 1 xn = find(f, xp, dx) if f.value_of(xn) < f.value_of(xb): xp = list(map(lambda n, b: 2 * n - b, xn, xb)) x...
StarcoderdataPython
3296536
#!/usr/bin/env python2 import urllib2, json, os, sys HEADER = ''' Redirect = { image: function(board, filename) { switch (board) { ''' POST = ''' } }, post: function(board, postID) { switch (board) { ''' TO = ''' } }, to: function(data) { var board, threadID, url; ...
StarcoderdataPython
1623820
import logging import re from django.apps import apps from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User from django.contrib.admin import AdminSite from django.contrib.admin.models import LogEntry from django.contrib.admin.views.main import Chan...
StarcoderdataPython
1696282
# fa19-516-160 # E.Cloudmesh.Common.2 # Task : Develop a program that demonstrates the use of dotdict. # Imports from cloudmesh.common.dotdict import dotdict # Sample data data = [ { "name": "Shreyans", "course": "e516", "address" : { "city": "Bloomington" , "state": "IN" } }, { "name"...
StarcoderdataPython
3234331
<filename>ml/ml_models/tumor_detection.py import os import sys import cv2 import matplotlib.pyplot as plt import numpy as np from keras import layers from keras.applications.vgg16 import VGG16 from keras.callbacks import EarlyStopping from keras.models import Model, Sequential, load_model from keras.optimizers import ...
StarcoderdataPython
3224016
<reponame>jfitz/code-stat import string import math from codestat_token import Token from codestat_tokenizer import Tokenizer from token_builders import ( InvalidTokenBuilder, WhitespaceTokenBuilder, NewlineTokenBuilder, EscapedStringTokenBuilder, PrefixedStringTokenBuilder, IntegerTokenBuilder, IntegerE...
StarcoderdataPython
12880
<reponame>DITGO/2021.1-PC-GO1-Archives from rest_framework import serializers from archives_app.documents_models import (FrequencyRelation, BoxArchiving, AdministrativeProcess, OriginBox, FrequencySheet, DocumentTypes) class Frequen...
StarcoderdataPython
174283
import numpy as np import segyio import pyvds VDS_FILE = 'test_data/small.vds' SGY_FILE = 'test_data/small.sgy' def compare_inline_ordinal(vds_filename, sgy_filename, lines_to_test, tolerance): with pyvds.open(vds_filename) as vdsfile: with segyio.open(sgy_filename) as segyfile: for line_ordi...
StarcoderdataPython
3231538
<gh_stars>0 # Copyright 2022 Google # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in w...
StarcoderdataPython
176009
import libsbml import importlib import amici import os import sys import pandas as pd import petab.sbml # SBML model we want to import sbml_file = 'CS_Signalling_ERBB_RAS_AKT_petab.xml' # Name of the model that will also be the name of the python module model_name = 'ERBB_RAS_AKT_Drugs' # Directory to which the genera...
StarcoderdataPython
35397
<reponame>nkmrohit/python # Generated by Django 2.1.4 on 2019-01-27 04:01 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('customerauth', '0001_initial'), ] operations = [ migrations.AlterField( model_name='customers', ...
StarcoderdataPython
1754932
import datetime from plt_pack.project_utils.save_opts import SaveOpts def test_freeze_time(freeze_time): assert datetime.datetime.now() == freeze_time def test_save_opts_time_format(freeze_time): date_fmt = '%d-%b-%H-%M-%S' save_opts = SaveOpts(datefmt=date_fmt) assert save_opts.time_str == freeze_t...
StarcoderdataPython
106941
<reponame>ChrisCrossCrash/SetOriginInEditMode import bpy import bmesh from mathutils import Vector # Meta Info # https://wiki.blender.org/wiki/Process/Addons/Guidelines/metainfo bl_info = { "name": "Set Origin in Edit Mode", "description": "Adds a `Set Origin to Selected` option to the right-click menu in Ed...
StarcoderdataPython
3333377
<filename>play.py import numpy as np from env import lumpy, reward, discount from agnt import rand, min, ffnn from plt import plotting_fools plot = True num_games = 10 max_iter = 40 #actor1 = rand.agent() #actor2 = min.agent() actor = ffnn.agent() rwrd = reward.score() dcount = discount.disc() for game in range(num...
StarcoderdataPython
1743769
import os import argparse from sklearn.feature_selection import ( SelectKBest, mutual_info_classif, ) from imblearn.over_sampling import RandomOverSampler from sklearn.metrics import roc_curve import matplotlib.pyplot as plt import classifiers as clfs import utils def main(args): print("Loading and prep...
StarcoderdataPython
3227094
"""Unit tests for Norm""" from tests.utils import NormTestCase class UnquotingTestCase(NormTestCase): def test_dynamic_projection(self): self.execute("test(a: String, b: Integer);") self.execute("test := ('test', 1)" " | ('here', 2)" " | ('there...
StarcoderdataPython
98439
#coding=utf-8 import json from app.util.messageque.http_request import RequestApi import logging from django.conf import settings class MessageSender: Host = settings.Message_Tornado_host @classmethod def send_bottle_message(cls, from_id, desc): body = {} body["from_id"] = from_id ...
StarcoderdataPython
3327418
from flask import Flask, jsonify, request, send_from_directory import requests from threading import Thread import os import shutil app = Flask(__name__) app.config['UPLOAD_FOLDER']='usersContent' def verifyJson(dadosNext): tempHTML = '' if (len(list(dadosNext)) > 0): for dado in dadosNext: ...
StarcoderdataPython
146477
from .constants import BTCMOVE from .controllers import ftx_move, ftx_trades __all__ = ["BTCMOVE", "ftx_trades", "ftx_move"]
StarcoderdataPython
56882
from flask_wtf import Form from wtforms import (TextField, StringField, BooleanField,PasswordField, validators) from .utils import Unique from .models import User from .constants import (USER_LEN_MSG, USER_REQ_MSG, USER_DUPL_MSG, EMAIL_FORMAT_MSG, EMAIL_REQ_MSG, EMAIL_DUPL_M...
StarcoderdataPython
3224707
#!/usr/bin/env python import rospy def helloworld(): #Initialize node with a default name rospy.init_node('default_node_name', anonymous=True) #Prints to INFO log rospy.loginfo("HELLOOO WOOORRLD") if __name__ =='__main__': try: helloworld() except rospy.ROSInterruptException: pass
StarcoderdataPython
101189
from django.utils.deprecation import MiddlewareMixin from django.conf import settings class Cors(MiddlewareMixin): def process_response(self, request, response): response['Access-Control-Allow-Origin'] = ','.join(settings.CORS_ORIGIN_LIST) if request.method == 'OPTIONS': respon...
StarcoderdataPython
1786689
# ai 서버, display 클라이언트 # server.py import flask from flask import request, make_response, jsonify from PIL import Image import time import cv2 import numpy as np import core.utils as utils import tensorflow as tf from PIL import Image from IPython.display import display import requests num_seats = input("좌석 수 :") n...
StarcoderdataPython
152725
from django.template import Library from evap.evaluation.models import Semester from evap.settings import DEBUG, LANGUAGES register = Library() @register.inclusion_tag("navbar.html") def include_navbar(user, language): return { "user": user, "current_language": language, "languages": LAN...
StarcoderdataPython
1653889
#!/usr/bin/python import time import cv2 import numpy as np from process import findColor from ftplib import FTP from bebop import * drone = Bebop() drone.videoDisable() # disable video stream drone.moveCamera( tilt=-100, pan=0 ) ftp = FTP('192.168.42.1') # connect to host, default port ftp.login() f...
StarcoderdataPython
171703
# -*- coding: utf-8 -*- # # SPDX-FileCopyrightText: © 2014 The glucometerutils Authors # SPDX-License-Identifier: MIT """Tests for the LifeScan OneTouch Ultra Easy driver.""" # pylint: disable=protected-access,missing-docstring from absl.testing import absltest from glucometerutils.drivers import otultraeasy class...
StarcoderdataPython
3340476
<reponame>nekoumei/dtreeplt import numpy as np import pandas as pd from sklearn import tree from sklearn.preprocessing import MinMaxScaler import matplotlib.patches as mpatch import matplotlib.pyplot as plt import matplotlib.cm as cm class dtreeplt(): ''' Parameters --------------- model: sklearn.tree...
StarcoderdataPython
1714639
import sys import cadquery as cq # obj = cq.Workplane("YZ").circle(1).extrude(10) # show_object(obj, "obj.1") # obj = obj.copyWorkplane(cq.Workplane("XZ")).circle(2).extrude(15) # show_object(obj, "obj.2") # obj = obj.copyWorkplane(cq.Workplane("XY")).box(10, 5, 1) # show_object(obj, "obj.3") obj = cq.Workplane("Y...
StarcoderdataPython
3233801
#!/usr/bin/python # -*- coding: utf-8 -*- import json import locale from decimal import Decimal from django import template register = template.Library() @register.filter def to_json(value): return json.dumps(value) @register.filter def to_abs(value): return abs(value) @register.filter def amount_split(...
StarcoderdataPython
3277895
# Find the sum of the only eleven primes that are both truncatable from left to right and right to left. import prime class Solve(object): def __init__(self): self.such_primes = [] self.nr_such_prime = 11 def solve(self): def contain_even(x): for i in str(x): ...
StarcoderdataPython
88892
<filename>monday/resources/items.py from monday.resources.base import BaseResource from monday.query_joins import mutate_item_query, get_item_query, update_item_query, get_item_by_id_query, \ update_multiple_column_values_query, mutate_subitem_query, add_file_to_column_query class ItemResource(BaseResource): ...
StarcoderdataPython
3322841
from wtforms import Form, TextField, TextAreaField, validators, StringField, SubmitField class MissionSearchForm(Form): ''' Form to perform the search functionality in the /search route where one needs to type in the first and last name ''' mission = TextField('Field', validators=[validators.DataRequired()])
StarcoderdataPython
1656644
import time import sips from sips.h import attach from sips.h import hot from sips.h import helpers as h from sips.h import serialize as s from sips.h import attach from sips.macros import macros as m from sips.macros import bov as bm def test_get_and_window(): columns = ["a_pts", "h_pts", "quarter", "secs"] ...
StarcoderdataPython
1735346
<reponame>wtsnjp/nlp100 # # usage: python k36.py {file name} # import sys import collections from k30 import load_mecab def frequency_ranking(data): cd = collections.Counter([m['base'] for s in data for m in s]) return [[k, v] for k,v in cd.most_common()] if __name__ == '__main__': fn = sys.argv[1] d...
StarcoderdataPython
4836996
<reponame>davbre/rotki from eth_utils import is_checksum_address from rotkehlchen.constants.ethereum import EthereumConstants def test_ethereum_contracts(): """Test that all ethereum contract entries have legal data""" for _, entry in EthereumConstants().contracts.items(): assert len(entry) == 3 ...
StarcoderdataPython
1763138
#coding=utf-8 ''' Created on 2016年1月12日 @author: hadoop ''' class UrlManager(object): def __init__(self):#构造函数 self.new_urls=set() self.old_urls=set() def add_new_url(self,url):#在管理器中添加一个新的url if url is None: return if url not i...
StarcoderdataPython
3227776
<reponame>foerstner-lab/GRADitude import pandas as pd def exclude_the_min_row_sum(feature_count_table, feature_count_start_column, feature_count_end_column, min_row, output_file): feature_count_table_df = pd.read_table(feature_count_table) matrix_value = _extract_value_matrix(featu...
StarcoderdataPython
83495
import pandas as pd from .. import config def process(filename, is_continuous=False, threshold=1.96): """ Parameters ---------- filename: :str tab separated file in which the first row contains gene name/entrez gene id combined and patient ids. The rest of the rows are the genes and their...
StarcoderdataPython
176365
# -*- coding: utf-8 -*- """jira_lex.py: Django datatableview_advanced_search""" from __future__ import unicode_literals from __future__ import print_function import sys import logging from datetime import date __author__ = '<NAME>' __date__ = '2/28/18 9:20 AM' __copyright__ = 'Copyright 2018 IC Manage. All rights r...
StarcoderdataPython
1672095
<filename>umpnet/unet_parts.py """ Parts of the U-Net model """ import torch import torch.nn as nn import torch.nn.functional as F class Conv(nn.Module): """convolution => [BN] => ReLU""" def __init__(self, in_channels, out_channels): super().__init__() self.conv = nn.Sequential( ...
StarcoderdataPython
141506
#!/usr/bin/env python # -*- coding: utf-8 -*- from pathlib import Path import reusables from box import __version__ as box_version from qtpy import API, QtCore, QtGui, QtWidgets from fastflix.language import t from fastflix.shared import base_path, link, pyinstaller from fastflix.version import __version__ __all__ =...
StarcoderdataPython
4836323
<filename>moneysocket/nexus/transact/provider.py # Copyright (c) 2020 <NAME> # Distributed under the MIT software license, see the accompanying # file LICENSE or http://www.opensource.org/licenses/mit-license.php import logging from moneysocket.nexus.nexus import Nexus from moneysocket.message.notification.invoice im...
StarcoderdataPython
1721470
"""Evented dictionary""" import sys from typing import ( Any, Dict, Iterator, Mapping, MutableMapping, Sequence, Type, TypeVar, Union, ) _K = TypeVar("_K") _T = TypeVar("_T") class TypedMutableMapping(MutableMapping[_K, _T]): """Dictionary mixin that enforces item type.""" ...
StarcoderdataPython
146234
import requests from .BITBOX import REST_URL class Transaction: def details(txid): if type(txid) is str: response = requests.get(REST_URL+"transaction/details/"+txid) return response.json() elif type(txid) is list: response = requests.post(REST_URL+"transaction/d...
StarcoderdataPython
164582
<reponame>Kwongrf/pytorch-retinanet from __future__ import print_function, division import sys import os import torch import numpy as np import random import math import csv import six from torch.utils.data import Dataset, DataLoader from torchvision import transforms, utils from torch.utils.data.sampler import Sampler...
StarcoderdataPython
3243233
<filename>6 kyu/Sequence classifier.py def sequence_classifier(arr): check=sorted(arr[i]-arr[i-1] for i in range(1, len(arr))) low=min(check) high=max(check) if low==high==0: return 5 elif low>=0: return 2 if low==0 else 1 elif high<=0: return 4 if high==0 else 3 retu...
StarcoderdataPython
1788323
<reponame>Azure/MachineLearning-MusicGeneration<filename>MusicGeneration/train.py # Spark configuration and packages specification. The dependencies defined in # this file will be automatically provisioned for each run that uses Spark. from __future__ import print_function import numpy as np from keras.models import S...
StarcoderdataPython
117041
<filename>src/lgr_advanced/lgr_editor/views/codepoints/list.py<gh_stars>1-10 #! /bin/env python # -*- coding: utf-8 -*- """ list.py - """ import logging from io import StringIO from django.contrib import messages from django.core.cache import cache from django.http import Http404, JsonResponse from django.shortcuts i...
StarcoderdataPython
13173
from .utils import (get_prescription, get_attributes, get_group) from .models import Disease, Result, Score, Question, SurveyResponse from .analysis import cardio_risk_group, diabetes_risk_group, stroke_risk_group from statistics import mean from celery import shared_task @shared_task def worker(session_id): df, ...
StarcoderdataPython
4803392
# automatically generated by the FlatBuffers compiler, do not modify # namespace: class Array(object): NONE = 0 ArrayInt = 1 ArrayLong = 2 ArrayDouble = 3 ArrayFloat = 4
StarcoderdataPython
3253086
<gh_stars>0 from django.views.generic import ListView, DetailView from django.views.generic.base import TemplateView from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.urls import reverse_lazy from django.contrib.auth.mixins import LoginRequiredMixin from .models import MainGenre, Sub...
StarcoderdataPython
102935
<gh_stars>1-10 #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ tkRAD - tkinter Rapid Application Development library (c) 2013+ <NAME> <<EMAIL>> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Sof...
StarcoderdataPython
46259
<reponame>liaohongdong/IPProxy import time import json import random if __name__ == '__main__': # a = 10 # while '172.16.17.32:1080': # a -= 1 # print(a) # if a <= 0: # break # a = ['a', 'b', 'c', 'd'] # a = [] # while a: # print(time.gmtime().tm_sec) ...
StarcoderdataPython
1660519
from django.conf import settings from django.contrib import auth, messages from django.contrib.auth.decorators import login_required, user_passes_test from django.db.models import Case, Value, When from django.http import HttpResponseRedirect from django.shortcuts import render, redirect from django.template.response i...
StarcoderdataPython
1713196
#%% from os import sep with open("data/data_4.txt") as file: data = [line for line in file] data[:5] #%% #Part 1 #? 1. Split the passport join_passport = [] join_passport = "".join(data) split_passport = join_passport.split(sep="\n\n") #%% #? 2. Split the components total_valid = 0 for fields in spli...
StarcoderdataPython
1695096
from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from .models import Question,Answers from django.template import loader from django.urls import reverse from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.shortc...
StarcoderdataPython
4842202
# Created by <NAME>. # GitHub: https://github.com/ikostan # LinkedIn: https://www.linkedin.com/in/egor-kostan/ def solution(number: int) -> int: """ If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Finish the solution so that it...
StarcoderdataPython
3339507
<gh_stars>1-10 #!/usr/bin/env python3 def say_hi(name, age): return f"Hi. My name is {name} and I'm {age} years old" if __name__ == '__main__': assert say_hi("Kitty", 28) == "Hi. My name is Kitty and I'm 28 years old" assert say_hi("Peter", 42) == "Hi. My name is Peter and I'm 42 years old"
StarcoderdataPython
4809700
<reponame>lixiaobo230665/ITMO_ICT_WebProgramming_2020-2021_d3310<filename>sutdents D33102 lixiaobo/sutdent's D33102 lixiaobo lr2/Stupid_monkey/Stupid_monkey/urls.py """Stupid_monkey URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.1...
StarcoderdataPython
173137
<gh_stars>1-10 """ strenum contains an enum that inherits from the plain enum and string. """ from enum import Enum # pylint: disable=too-few-public-methods class StrEnum(str, Enum): """ An enum that has string values. """ # see https://docs.python.org/3/library/enum.html?highlight=strenum#others
StarcoderdataPython
3303276
from django.contrib.auth import views as auth_views from django.urls import path from . import views urlpatterns = [ path('<int:R_id>', views.dds,name='dds') ]
StarcoderdataPython
3222730
import discord intents = discord.Intents.default() intents.members = True client = discord.Client( intents=intents ) ready = False @client.event async def on_ready(): ready = True while ready != True: pass bot = client bot.run('token')
StarcoderdataPython
140882
def FourierPower(db1Trace, inSampleRate, varargin): ''' STILL NOT IMPLEMENTED IN PYTHON!!! [DBWINLENSEC, INNSTEP, BLDOPLOT]) computes the spectral power of DB1TRACE over time. DB1TRACE is divided into segments whose length is specified by DBWINLENSEC and INSAMPLERATE. INNSTEP controls the overl...
StarcoderdataPython
3350568
<gh_stars>0 import time import numpy as np """ 代码流程: item_score = [] for item in 待推荐物品集合: for item_like in 用户喜欢的物品集合: score = get_score_from_similar_items() item_score.append([item,score]) """ def build_i2s_i2n(user_item_score_path, item_name_path): # 读取电影id-电影名字文件 item2name = {} with...
StarcoderdataPython
1754105
import os import cv2 import pickle import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.preprocessing import StandardScaler import tensorflow as tf from tensorflow.keras.applications import InceptionResNetV2, VGG16 from tensorflow.keras.models import Sequential, Model from tensorflow.ker...
StarcoderdataPython
4816910
<gh_stars>0 # Copyright 2021 MosaicML. All Rights Reserved. from composer.algorithms.scale_schedule.scale_schedule import ScaleSchedule as ScaleSchedule
StarcoderdataPython
95425
# coding: utf-8 import re import sre_constants from ..roles import Resolvable def validate_regex(regex): """ :param str regex: A regular expression to validate. :raises: ValueError """ try: re.compile(regex) except sre_constants.error as e: raise ValueError('Invalid regular ex...
StarcoderdataPython
1644521
import asyncio import aioredis from zdppy_redis import AsyncRedis r = AsyncRedis(host="localhost", port=6379, database=0) async def set(): """ 测试设置和获取 :return: """ await r.set("my-key", "value") value = await r.get("my-key") print(value) async def hset(): """ 测试设置和获取 :return...
StarcoderdataPython
3258321
# -*- coding: utf-8 -*- """ Description: Global fixtures for unittests Author: <NAME> Date: 12/14/20 """
StarcoderdataPython
1701118
#misc import sys #data processing import numpy as np import pandas as pd #homemade sys.path.append('../../utils') from helpers import load_tsv def clean_beehive(): filename = 'Beehive_Logger' df = load_tsv(filename) print("Now cleaning Beehive Geyser Data") print("Initial Shape of df: {0}".format(df.s...
StarcoderdataPython
3398390
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Time : 2019/1/29 11:20 AM # @Author : hysrc # @File : into_elastic.py from elasticsearch import Elasticsearch from elasticsearch_dsl import Search from config import ELASTICSEARCH_HOSTS from pipeline.elastic import Ips, Domains import json from datetime import da...
StarcoderdataPython
3329402
""" Trading-Technical-Indicators (tti) python library File name: _machine_learning_mlp.py Implements a Multilayer Perceptron classification model for the Machine Learning features of the tti library. """ import time import datetime import math from ._machine_learning_api import MachineLearningAPI from ._mach...
StarcoderdataPython
3329956
<reponame>zengaorong/yahaha # coding:utf8 import sys reload(sys) sys.setdefaultencoding('utf8') import xlwt import MySQLdb def export(host,user,password,dbname,table_name,outputpath): conn = MySQLdb.connect(host,user,password,dbname,charset='utf8') cursor = conn.cursor() count = cursor.execute('select *...
StarcoderdataPython
69649
<filename>2020/day15_test.py import day15 ITERS = 2020 def test_example1(): intro_seq = [0, 3, 6] final_move = day15.play_game(intro_seq, ITERS) assert final_move == 436, f"Error: {final_move}" def test_example2(): intro_seq = [1, 3, 2] final_move = day15.play_game(intro_seq, ITERS) assert...
StarcoderdataPython
3216929
<filename>audio_zen/model/module/causal_conv.py import torch import torch.nn as nn from torch.nn.utils import weight_norm from audio_zen.fvcore.nn import FlopCountAnalysis, flop_count_str class Chomp1d(nn.Module): def __init__(self, chomp_size): super(Chomp1d, self).__init__() self.chomp_size = c...
StarcoderdataPython
1674140
<filename>yardstick/benchmark/scenarios/networking/vnf_generic.py # Copyright (c) 2016-2017 Intel Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/li...
StarcoderdataPython
1753031
<filename>mi/instrument/seabird/sbe26plus/ooicore/driver.py from mi.instrument.seabird.sbe26plus.driver import SBE26PlusInstrumentDriver class InstrumentDriver(SBE26PlusInstrumentDriver): """ Specialization for this version of the 26 driver """
StarcoderdataPython
1692865
<reponame>tanglef/geomloss """ Optimization routines ============================================ """ import os import torch import matplotlib import matplotlib.pyplot as plt from math import isnan import numpy as np from scipy.optimize import minimize import warnings warnings.filterwarnings("ignore",".*GUI is implem...
StarcoderdataPython
4809857
<gh_stars>10-100 from django.core.management.base import BaseCommand from public_project.models import SearchTag from public_project.tag_cache_creator import rebuild_cache_for_tag class Command(BaseCommand): args = '' help = 'Rebuilding of all search tag cache entries for the project' def handle...
StarcoderdataPython
84300
<filename>nbs/dl2/selfmade/exp/nb_05.py ################################################# ### THIS FILE WAS AUTOGENERATED! DO NOT EDIT! ### ################################################# # file to edit: dev_nb/05_anneal.ipynb from exp.nb_04 import * def create_learner(model_func, loss_func, data): return Lear...
StarcoderdataPython
158087
from typing import Union import numpy as np def bspline_basis_manual( knot_vector_t: Union[list, tuple], knot_i: int = 0, p: int = 0, nti: int = 1, verbose: bool = False, ): """Computes the B-spline polynomial basis, currently limited to degree constant, linear, or quadratic. Arg...
StarcoderdataPython
178446
<reponame>DavidNemeskey/pytorch_lm<gh_stars>0 #!/usr/bin/env python3 # vim: set fileencoding=utf-8 : """Implements a very basic version of LSTM.""" import logging import torch import torch.nn as nn from torch.autograd import Variable from pytorch_lm.dropout import create_hidden_dropout from pytorch_lm.utils.lang im...
StarcoderdataPython
122195
# Python modules # 3rd party modules # Our modules import vespa.analysis.block_prep_fidsum as block_prep_fidsum from vespa.common.constants import Deflate class BlockPrepEditFidsum(block_prep_fidsum.BlockPrepFidsum): """ Building block to hold the state of a step in an MRS processing chain. Includes ...
StarcoderdataPython