id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
1785727 | <filename>shencoder/backend.py
import os
from torch.utils.cpp_extension import load
_src_path = os.path.dirname(os.path.abspath(__file__))
_backend = load(name='_sh_encoder',
extra_cflags=['-O3', '-std=c++14'],
extra_cuda_cflags=['-O3', '-std=c++14'],
sources=[os.path.j... | StarcoderdataPython |
11353 | from rest_framework import status
from rest_framework.exceptions import APIException
class BadSource(APIException):
"""
Exception for when a lazily-loaded data source can't
be accessed for some reason
"""
status_code = status.HTTP_417_EXPECTATION_FAILED
default_code = 'bad_source'
def __i... | StarcoderdataPython |
11062 | <reponame>GuiYuDaniel/CGC_of_Sn<filename>src/utils/utils.py
# -*- coding:utf8 -*-
"""
一些其他工具
当需要细化或者函数太多时,应该把其中一些独立出去
"""
import uuid
from enum import Enum, unique
from utils.log import get_logger
logger = get_logger(__name__)
@unique
class PipeTaskStatus(Enum): # 还不够需要写状态机,先用这个凑活一下
"""
name is Status
... | StarcoderdataPython |
1699560 | # Samba automatic dependency handling and project rules
import Build, os, sys, re, Environment, Logs, time
from samba_utils import *
from samba_autoconf import *
from samba_bundled import BUILTIN_LIBRARY
@conf
def ADD_GLOBAL_DEPENDENCY(ctx, dep):
'''add a dependency for all binaries and libraries'''
if not 'G... | StarcoderdataPython |
3376962 | from django.db import models
from django.utils import timezone
from datetime import timedelta
from django.utils.dateparse import parse_duration
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _
from network.models import Nonprofit
from accounts.models import Use... | StarcoderdataPython |
1648372 | <reponame>sravanrekandar/pyLearn<gh_stars>0
"""
04_identifier.py.
Declaring an identifier named 'name'
Assigning a value "Madhu" to the identifier 'name'
"""
name = "Madhu"
# Using the identifier in a print statement
print("Hello " + name + ".")
| StarcoderdataPython |
3284187 | <reponame>chidioguejiofor/airtech-api
# Generated by Django 2.2 on 2019-04-04 16:20
from django.db import migrations, models
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = []
operations = [
migrations.CreateModel(
name='Flight',
fields=... | StarcoderdataPython |
1690703 | <reponame>matthew-robertson/banned-word-tracker<gh_stars>10-100
import unittest
import datetime
from unittest.mock import Mock, patch
from types import MethodType
import bot
from commands import TimerCommand, ListRecordCommand, CooldownCommand, HelpCommand, SilenceCommand, AlertCommand, ChangeBanCommand, AddBanCommand... | StarcoderdataPython |
126132 | <reponame>maoyab/OWUS<filename>param_sm_pdf.py
import numpy as np
from scipy.interpolate import interp1d
from scipy.stats import ks_2samp, percentileofscore
from sswm import SM_C_H
class Inverse_bayesian_fitting(object):
def __init__(self, s_obs, unknown_params, save_params, p_ranges, epsi=None, stress... | StarcoderdataPython |
1688309 | <filename>wikidump/languages.py
supported = {'de', 'en', 'es', 'fr', 'it', 'nl', 'pl', 'ru', 'sv'}
bibliography = {
'en': {
'bibliography',
'references',
'reference',
'further reading',
'notes',
'sources',
'footnotes',
'citations',
'publicatio... | StarcoderdataPython |
181208 | <filename>tetris/window.py
from Tkinter import *
class StatusBar(Frame):
def __init__(self, master):
Frame.__init__(self, master)
self.label = Label(self, bd=1, relief=SUNKEN, anchor=W)
self.label.pack(fill=X)
def set(self, format, *args):
self.label.config(text=form... | StarcoderdataPython |
1783809 | import tensorflow as tf
grafo1 = tf.Graph()
with grafo1.as_default():
matrix1 = tf.constant([[3., 3.], [3., 3.]], name='Matriz1')
matrix2 = tf.constant([[2., 2.], [2., 2.]], name='Matriz2')
producto_grafo1 = tf.matmul(matrix1, matrix2, name='Producto')
with tf.Session(graph=grafo1) as sess:
... | StarcoderdataPython |
3238019 | import sys
import string
import logging
import logging.config
import logging.handlers
import collections
from punnsilm.core import Output
if sys.platform.startswith('linux'):
SYSLOG_SOCKET = '/dev/log'
elif sys.platform.startswith('freebsd'):
SYSLOG_SOCKET = "/var/run/log"
class ExtradataWrapper:
"""st... | StarcoderdataPython |
3297177 | from __future__ import absolute_import
from tesserocr import PyTessBaseAPI, PSM, get_languages
from ocrd.utils import getLogger, mets_file_id, xywh_from_points
from ocrd.model.ocrd_page import from_file, to_xml, TextEquivType
from ocrd import Processor, MIMETYPE_PAGE
from ocrd_tesserocr.config import TESSDATA_PREFIX
... | StarcoderdataPython |
1610529 | from flask import Flask, render_template
from flask_nav import Nav
from flask_nav.elements import *
nav = Nav()
# registers the "top" menubar
nav.register_element(
'top',
Navbar(
View('Widgits, Inc.', 'index'),
View('Our Mission', 'about'),
Subgroup('Products',
View('W... | StarcoderdataPython |
4826525 | <filename>features_scripts/mfcc/ravdess.py
'''
BME AI - Speech Emotion Analysis - RAVDESS Extraction script
------------------------------------------------------------
'''
import os.path
import zipfile
import shutil
import pandas as pd
from features_scripts.utils import save_dataframe, extract_mfcc_features
f... | StarcoderdataPython |
1615890 |
keyList = []
for char in "ABCDEFGHIJKLMNOPQRSTUVWXYZ 123456789,.'£$/\\":
keyList.append(char)
w = [1,0,0,0]
s = [0,1,0,0]
a = [0,0,1,0]
d = [0,0,0,1] | StarcoderdataPython |
3226448 | '''
File: uart_demo1.py
Project: uart
File Created: Wednesday, 23rd December 2020 3:33:56 pm
Author: chengzhu.zhou
-----
Last Modified: Wednesday, 23rd December 2020 3:34:15 pm
Modified By: chengzhu.zhou
-----
Copyright 2020 - 2020 quectel
'''
from machine import UART
import utime as time
"""
端口号
EC100... | StarcoderdataPython |
1634817 | from .classifier import DL85Classifier
from .boosting import DL85Booster
| StarcoderdataPython |
75148 | <filename>app/__init__.py<gh_stars>10-100
from __future__ import absolute_import
# This will make sure the app is always imported when
# Django starts so that shared_task will use this app.
# see http://chriskief.com/2013/11/15/celery-3-1-with-django-django-celery-rabbitmq-and-macports/
from .celery import app
| StarcoderdataPython |
63578 | <reponame>ad-free/lab-ml
import pandas as pd
import numpy as np
import sklearn
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.utils import shuffle
df = pd.read_csv("../download/student-mat.csv", sep=";")
data = df[["G... | StarcoderdataPython |
4831280 | import math
import numpy as np
import pytest
from albumentations import Flip, HorizontalFlip, VerticalFlip, IAAFliplr, IAAFlipud
from albumentations.augmentations.keypoints_utils import convert_keypoint_from_albumentations, \
convert_keypoints_from_albumentations, convert_keypoint_to_albumentations, convert_keypo... | StarcoderdataPython |
3251147 | import socket
import network
import machine, onewire, ds18x20, time
import settings
class DSInfo:
def __init__(self):
print("Setting up DS sensor")
self.ds_pin = machine.Pin(settings.DSPIN)
self.ds_sensor = ds18x20.DS18X20(onewire.OneWire(self.ds_pin))
self.roms = self.ds_sensor.s... | StarcoderdataPython |
67082 | <gh_stars>0
import numpy as np
from transformation import Transformation
class Data(object):
def __init__(self):
self.vicon_lists = []
self.vicon_ts = []
self.vicon_x = []
self.vicon_y = []
self.vicon_z = []
self.vicon_qw = []
self.vicon_qx ... | StarcoderdataPython |
1641940 | import os
here = os.path.dirname(__file__)
ini_path = os.environ.get('INI_FILE')
if not ini_path:
ini_path = os.path.join(here, '../../production.ini')
from paste.deploy import loadapp
application = loadapp('config:%s' % ini_path, relative_to='.')
import logging
import logging.config
logging.config.fileConfig(in... | StarcoderdataPython |
1772340 | <filename>open_seq2seq/parts/rnns/glstm.py
"""Module for constructing RNN Cells."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from six.moves import range
from tensorflow.contrib.rnn.python.ops import core_rnn_cel... | StarcoderdataPython |
22252 | <gh_stars>10-100
from random import random
TABLE_NAME = f"test-django-dynamodb-cache-{random()}"
| StarcoderdataPython |
3374061 | <reponame>ahameedx/intel-inb-manageability
from unittest import TestCase
from inbc.utility import search_keyword, is_vision_agent_installed
from mock import Mock, patch
from os import path
class TestUtility(TestCase):
def test_search_keyword_true(self):
payload = 'Status message FAILED'
output = ... | StarcoderdataPython |
3386513 | <gh_stars>1-10
import pyodbc
import pandas as pd
# main function to fetch the data and clean it
def fetch_data():
conn = create_connection()
result_hdc = query_data('queryTransplantsHDC.sql', conn)
result_npc = query_data('queryTransplantsNPC.sql', conn)
result_pdc = query_data('queryTransplantsPDC.sq... | StarcoderdataPython |
117995 | from django.db import models
from ..company_profile.models import CompanyProfile
from ...core.db.fields import PositiveTinyIntegerField
from ...core.db.models import TimeStampMixin
from ...share_resources.master_data.models import TypeAutoReplyMessage
from ...utils.storages import MediaRootS3Boto3Storage
class Messa... | StarcoderdataPython |
3208909 | #=============================================================================#
#
# File: prime_counting_function_plot.py
# Author: <NAME>
# Date: May 2021
# Description:
# A plot of the prime counting function,
#
#=============================================================================#
i... | StarcoderdataPython |
1720042 | <filename>stib_administraciones/core/models.py
# -*- coding: utf-8 -*-
from django.db import models
from model_utils import Choices
from easy_thumbnails.fields import ThumbnailerImageField
from taggit.managers import TaggableManager
class TimeStampedModel(models.Model):
modificado = models.DateTimeField(auto_now=... | StarcoderdataPython |
1602287 | # Subset file list based on the letters
#
# The sub file lists filtered by letters are useful to
# check the utterances with that letters
#
# Some conclusions are drawn by observing the sub file list
# - remove utterances with * (mispronunced words)
# - replace ('_', ''', and '-') with ' ' (space)
# - accented symbo... | StarcoderdataPython |
137707 | <reponame>EdiaEducationTechnology/edia-komensky-uploader
# Copyright 2021 EDIA B.V.
#
# 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
#
# Unle... | StarcoderdataPython |
3297253 | from psiturk.amt_services_wrapper import MTurkServicesWrapper
SESSION_SERVICES_MANAGER_MODE_KEY = 'services_manager_mode'
class PsiturkServicesManager():
_cached_amt_services_wrapper = None
@property
def amt_services_wrapper(self):
if not self._cached_amt_services_wrapper:
self._cache... | StarcoderdataPython |
180508 | <gh_stars>100-1000
from core.models.user import User
from core.utils.git import GitUtils
from core.utils.helpers import Helpers
from core.models.collector import Collector
from core.models.repository import Repository
from core.models.organization import Organization
class GithubCollector(Collector):
def __init_... | StarcoderdataPython |
164339 | <filename>app/.glp/glp.py
#!/bin/python3
def generate_prime_numbers(lim):
"""
Generates prime numbers above 100 10**100
"""
start = 10**100
l = []
for num in range(start, lim):
for n in range(2, num):
if num % n == 0:
print("Not found")
break
... | StarcoderdataPython |
1716571 | # flake8: noqa
# fmt: off
"""List of League of Legends API available regions and endpoints."""
REGION_URL = {
"BR1": "https://br1.api.riotgames.com",
"EUN1": "https://eun1.api.riotgames.com",
"JP1": "https://jp1.api.riotgames.com",
"KR": "https://kr.api.riotgames.com",
"LA1": "https://la1.api.riot... | StarcoderdataPython |
3313850 |
import json
import pytest
from faust import Record
from faust_bootstrap.core.streams.utils import create_deadletter
class DummyRecord(Record):
dummy_text: str
@pytest.fixture()
def dummy_record():
return DummyRecord(dummy_text="This is my dummy text")
def test_deadletter_creation_from_record(dummy_reco... | StarcoderdataPython |
3334832 |
import keras.backend as K
def sharpe_ratio_loss(y_true, y_pred):
epsilon = 1e-6
max_bound = 1 - epsilon
constraint_value = 3e-3
n_tickers = K.shape(y_true)[1]
y_pred_reshape = K.expand_dims(y_pred, axis=-1)
z = y_true * y_pred_reshape
z = K.sum(z, axis=1)
sum_w = K.clip(K.sum(y_pred_r... | StarcoderdataPython |
4811024 | """
Average daily user counts
"""
# Imports
from datetime import datetime
import os
import pandas as pd
# Verify file path to trax data is correct
trafx_data_file_path = os.path.abspath(os.path.join(os.getcwd(), "..", "..", "data", "raw", "TRAFx_raw.csv"))
# Load data
trafx_df = pd.read_csv(trafx_data_file_path)
# ... | StarcoderdataPython |
1637150 | <filename>tests/test_main.py
from unittest import TestCase
class Test(TestCase):
def test_main(self):
self.fail()
| StarcoderdataPython |
3278930 | #!/usr/bin/env python3
import gym
import torch
import os
from config.names import PROJECT_HOME
MODEL_SAVE_DIR = os.path.join(PROJECT_HOME, "out", "model_save_files")
print(torch.__version__)
from common.fast_rl import actions, value_based_model, rl_agent
import numpy as np
from config.parameters import PARAMETERS ... | StarcoderdataPython |
71920 | from tkinter import Tk, Text, ttk
from tkinter.constants import ANCHOR, BOTTOM, END, LEFT, NW, RIGHT, SW, W
class Fr_lbProduto(ttk.Frame):
def __init__(self, parent):
super().__init__(parent)
self.lbfr_produto = ttk.Labelframe(self, text='Info Produto')
self.fr = ttk.Frame(self.lbfr_produ... | StarcoderdataPython |
112453 | <reponame>robertogoes/exercicios-coursera-python
def fizzbuzz(n):
if n%3 == 0 and n%5 != 0:
resultado = "Fizz"
elif n%5 == 0 and n%3 != 0:
resultado = "Buzz"
elif n%3 == 0 and n%5 == 0:
resultado = "FizzBuzz"
else:
resultado = n
return resultado
| StarcoderdataPython |
3370057 | # Copyright 2019 Open End AB
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | StarcoderdataPython |
194495 | <gh_stars>100-1000
"""Control host OS desktop background spanning mode when needed."""
import os
import platform
import subprocess
if platform.system() == "Windows":
import winreg
def set_spanmode():
"""Sets host OS desktop background to span all displays."""
pltf = platform.system()
if pltf == "Windo... | StarcoderdataPython |
1635242 | <reponame>munisisazade/diplom_isi<filename>base_user/migrations/0012_myuser_share_time.py
# -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-09-29 01:28
from __future__ import unicode_literals
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
... | StarcoderdataPython |
139959 | <gh_stars>0
from django import forms
class LoginForm(forms.Form):
username = forms.CharField(label='Username', max_length=150)
password = forms.CharField(label='Password', max_length=250)
class RegisterForm(forms.Form):
email = forms.EmailField(label='Email', max_length=250)
username = forms.CharField... | StarcoderdataPython |
3344142 | <filename>BOJ_Python/12639.py
import math
class Vector:
def __init__(self, x, y, z):
self.x, self.y, self.z = x, y, z
def _add(self, other):
self.x += other.x
self.y += other.y
self.z += other.z
return self
def add(self, other):
return Vector(self.x + othe... | StarcoderdataPython |
1724892 | from os import path
import unittest
import sys
sys.path.append(path.join(".."))
from rocrate import *
ROCRATE_EXAMPLE_PATH = path.join("..", "examples", "rocrate", "GTM")
class TestROCrate(unittest.TestCase):
def test_load_rocrate(self):
"""Check that loading RO-Crate files works as expected."""
# Test using ... | StarcoderdataPython |
3330488 | """ACM PCA Certificate Generator.
Creates a new local key and csr, and has that signed by ACM-PCA.
Then, adds the key and signed cert to a local Keystore and Truststore.
Also adds configured remote S3 certs to the Truststore.
"""
| StarcoderdataPython |
3257633 | from torchvision import transforms
import torchvision
from torch.utils.data import DataLoader
import random
def _get_transforms():
"""
The AdaMatch paper uses CTAugment as its strong augmentations. I'm going to
create a pipeline of transforms similar to the ones used by CTAugment.
"""
train_transf... | StarcoderdataPython |
1709132 | # encoding:UTF-8
import numpy as np
import bsplines
# Knot Sequence Update Strategies need two method:
# 1) generateKnotList: which generates a new knotlist given the current spline and reprojection errors
# Returns a boolean flag if the updated knot sequence needs another step of optimization
# 2) getUpdatedSplin... | StarcoderdataPython |
3362298 | #!/usr/bin/env python
import sys
import tHome.weatherUnderground
tHome.weatherUnderground.cmdLine.run( sys.argv )
| StarcoderdataPython |
3233136 | # -*- coding: utf-8 -*-
# from builtins import *
import re
import os
from toolz.curried import curry, memoize
from toolz import curried as tz
import requests
import pandas as pd
import numpy as np
import pylab as plt
import scipy
import networkx as nx
from gensim.summarization import keywords, summarize
from wordclo... | StarcoderdataPython |
44342 | <gh_stars>0
def first_last(s1):
# [out of bound error] s2 = s1[0] + s1[1] + s1[4] + s1[5]
# [out of bound error] s2 = s1[0] + s1[1] + s1[-2] + s1[-1]
# [false result] s2 = s1[0:2] + s1[-2:-1]
s2 = s1[0:2] + s1[-2:]
# [out of bound error] s2 = s1[:2] + s1[-2]
return s2
print(first_last("... | StarcoderdataPython |
167062 | <gh_stars>1-10
from abc import ABC, abstractmethod
from teras.dataset.dataset import Dataset, BucketDataset
from teras.io.cache import Cache
from teras.preprocessing import text
class Loader(ABC):
def load(self, file):
raise NotImplementedError
class TextLoader(Loader):
def __init__(self, reader)... | StarcoderdataPython |
139897 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class SummaryInvoiceBillOpenDTO(object):
def __init__(self):
self._bill_no = None
self._buyer_user_id = None
self._pay_type = None
@property
def bill_no(self):
... | StarcoderdataPython |
95301 | <filename>admin/apps.py
from django.apps import AppConfig
class AdminConfig(AppConfig):
name = 'admin'
label = 'ai_admin'
| StarcoderdataPython |
1716495 | <filename>Competing_Algorithm/utils/sampleSigma.py<gh_stars>0
"""This module will update sigma_a and sigma_x using Gibbs sampler."""
import numpy as np
import numpy.random as nr
def sampleSigma_x(X, Z, A, sigma_xa, sigma_xb, N, D):
"""update sigma_x using Gibbs sampler."""
# Sample noise variance
# Let E ... | StarcoderdataPython |
3216773 | from django.urls import path
from .views import ProfileDetailView, UpdateProfileView
from django.conf.urls.static import static
from django.conf import settings
app_name = 'user_profile'
urlpatterns = [
path('user/<int:user_id>/', ProfileDetailView.as_view(), name='profile'),
path('user/<int:user_id>/edit', U... | StarcoderdataPython |
1640723 | <reponame>Passer-D/GameAISDK
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making GameAISDK available.
This source code file is licensed under the GNU General Public License Version 3.
For full details, please refer to the file "LICENSE.txt" which is provided as part of this so... | StarcoderdataPython |
3278974 | <reponame>luolongqiang/caffe-luolongqiang
# -*- coding: utf-8 -*-
import numpy as np
import os.path as osp
import google.protobuf as pb
import google.protobuf.text_format
import argparse, time, sys, os, copy
caffe_root = './'
os.chdir(caffe_root)
sys.path.insert(0, os.path.join(caffe_root, 'python'))
import caffe
GP... | StarcoderdataPython |
1637266 | # -*- coding: utf-8 -*-
"""
Created on Mon Dec 17 16:06:20 2018
@author: adam.rees
"""
import unittest
import DBEISCarbonFactors
class test_InstanceNames(unittest.TestCase):
def setUp(self):
pass
def test_new_flat_class_creation(self):
try:
# Create a class fo... | StarcoderdataPython |
134111 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
Date: 2022/2/24 14:50
Desc: 真气网-空气质量
https://www.zq12369.com/environment.php
空气质量在线监测分析平台的空气质量数据
https://www.aqistudy.cn/
"""
import json
import os
import re
import pandas as pd
import requests
from py_mini_racer import py_mini_racer
from akshare.utils import demjson
... | StarcoderdataPython |
1711871 | # Given an initial array arr, every day you produce a new array using the array of the previous day.
# On the i-th day,
# you do the following operations on the array of day i-1 to produce the array of day i:
# If an element is smaller than both its left neighbor and its right neighbor,
# then this element is increm... | StarcoderdataPython |
131583 | <filename>bmp280.py
from micropython import const
from ustruct import unpack as unp
# Author <NAME> (david at dafnet.se)
# Power Modes
BMP280_POWER_SLEEP = const(0)
BMP280_POWER_FORCED = const(1)
BMP280_POWER_NORMAL = const(3)
BMP280_SPI3W_ON = const(1)
BMP280_SPI3W_OFF = const(0)
BMP280_TEMP_OS_SKIP = const(0)
BMP... | StarcoderdataPython |
1755961 | # Copyright The IETF Trust 2019, All Rights Reserved
# -*- coding: utf-8 -*-
# Generated by Django 1.11.20 on 2019-05-27 05:56
from __future__ import absolute_import, print_function, unicode_literals
from django.db import migrations
import sys, time
from tqdm import tqdm
def forward(apps, schema_editor):
Co... | StarcoderdataPython |
3305501 | import colorsys
import json
import os
def hsvToRgb(h, s, v):
(r, g, b) = colorsys.hsv_to_rgb(h / 360, s / 100, v / 100)
return '#'+("%0.2X" % round(r * 255))+("%0.2X" % round(g * 255))+("%0.2X" % round(b * 255))
# svg
def generateFile(version, id, h, s, v):
c = hsvToRgb(h, s, v)
p = os.path.join('res... | StarcoderdataPython |
87508 | #!/usr/bin/env python
import subprocess
import sys
import os
if len(sys.argv) != 4:
print "Usage: ftprecon.py <ip address> <port> <directory>"
sys.exit(0)
ip_address = sys.argv[1].strip()
port = sys.argv[2].strip()
scan_results_location = sys.argv[3].strip()
print "INFO: Performing nmap FTP script scan for "... | StarcoderdataPython |
1657335 | <gh_stars>1-10
"""empty message
Revision ID: 293c8607996c
Revises:
Create Date: 2018-11-08 22:30:44.102498
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '293c8607996c'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### com... | StarcoderdataPython |
3241829 | <gh_stars>1-10
from ileg import ILeg
from typing import Tuple
import time
import numpy
def delay(t):
time.sleep(t)
class Spider:
def __init__(self, legs: Tuple[ILeg, ILeg, ILeg, ILeg], z_position=0):
self.legs = legs
self.z_position = z_position
self._current_side = 0
self._l... | StarcoderdataPython |
192559 | <reponame>thomwiggers/mk-cert
from encoder import oids, signs, camel_to_snake
for alg in signs:
alg = camel_to_snake(alg).upper()
print(rf"(SignatureScheme::{alg}, &signature::{alg}),")
| StarcoderdataPython |
3310545 | <reponame>EMbeDS-education/StatsAndComputing20212022
import re
# defines removePunctuations function
def removePunctuations(txt):
return re.sub(r'[^\w\s]','',txt)
def top_10words(fname):
# to complete ...
return top_words
top_words = top_10words('manzoni_1.txt')
print(top_words) | StarcoderdataPython |
4801390 | <filename>server/control.py
from __future__ import unicode_literals, absolute_import, print_function
from time import time
from txmsgpackrpc.server import MsgpackRPCServer
from txmsgpackrpc.factory import MsgpackServerFactory
from twisted.logger import Logger
from twisted.internet import defer
from cheesepi.excepti... | StarcoderdataPython |
3340292 | from collections import defaultdict
from django.contrib.auth.models import User
from django.db import models
from django.db.models import Prefetch
from django.utils import timezone
from workflows.models.option import Option
from workflows.models.output import Output
from workflows.models.input import Input
from workf... | StarcoderdataPython |
1751714 | """proxy spiders"""
# -*- coding:utf-8 -*-
import re
import traceback
import requests
from commonbaby.httpaccess import HttpAccess
from commonbaby.mslog import MsLogger, MsLogManager
from commonbaby.proxy import (EProxyAnonymity, EProxyType, ProxyItem, ProxySetting, ProxySpiderbase)
from commonbaby.countrycodes impor... | StarcoderdataPython |
4820750 | <reponame>ydp/serving
import tensorflow as tf
from tensorflow_serving.apis import classification_pb2
from tensorflow_serving.apis import inference_pb2
from tensorflow_serving.apis import model_pb2
from tensorflow_serving.apis import predict_pb2
from tensorflow_serving.apis import prediction_log_pb2
from tensorflow_serv... | StarcoderdataPython |
1722131 | import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from pathlib import Path
app = Flask(__name__)
# Create required directory(s)
Path(os.environ.get('APPDATA')).mkdir(parents=True, exist_ok=True)
Path(os.environ.get('FILE_METADATA_JSON')).mkdir(parents=True, exist_ok=True)
Path(os.environ.get('... | StarcoderdataPython |
1665862 | <reponame>yellowjaguar5/lnldb
# -*- coding: utf-8 -*-
# Generated by Django 1.11.16 on 2019-03-16 17:24
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
de... | StarcoderdataPython |
19904 | <filename>pybnn/svgd_.py
import random
import time
import numpy as np
import theano
import theano.tensor as T
from scipy.spatial.distance import pdist, squareform
from tqdm import tqdm
'''
Sample code to reproduce our results for the Bayesian neural network example.
Our settings are almost the same as Hernand... | StarcoderdataPython |
1649242 | <filename>Classifier/KNeighborsClassifier.py
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import f1_score, hamming_loss
from utils.utils import generate_stacking_csv
use_stacking = True
csv_file = r'D:\dataset\2021智慧農業數位分身... | StarcoderdataPython |
4801741 | # -*- coding: utf-8 -*-
# @Time: 2020/6/30 15:22
# @Author: GraceKoo
# @File: interview_50.py
# @Desc: https://www.nowcoder.com/practice/623a5ac0ea5b4e5f95552655361ae0a8?tpId=13&rp=1&ru=%2Fta%2Fcoding-interviews&
# qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking
from typing import List
class Solution:
def findRe... | StarcoderdataPython |
1661253 | <gh_stars>100-1000
# Copyright 2009-2017 <NAME>.
# This program is distributed under the MIT license.
'''
Defines the `TempWorkingDirectorySetter` class.
See its documentation for more details.
'''
import os
from .temp_value_setter import TempValueSetter
class TempWorkingDirectorySetter(TempValueSetter):
'''
... | StarcoderdataPython |
38825 | # Trinket IO demo
# Welcome to CircuitPython 3.1.1 :)
import board
import adafruit_dotstar as dotstar
import time
import busio
import struct
from adafruit_hid.keyboard import Keyboard
from adafruit_hid.mouse import Mouse
from qwertyMAC import *
overlay = webaccess
# One pixel connected internally!
dot = dotstar.DotS... | StarcoderdataPython |
3363835 | <gh_stars>1-10
# Forked from https://github.com/ServePeak/Blackjack-Python
try:
#!/usr/bin/python
#Import Library
import pygame
from pygame.locals import *
import random
import copy
#Load Images
icon = pygame.image.load('Assets/Gallery/icon.png')
cBack = pygame.image.load('Assets/G... | StarcoderdataPython |
1707371 | <reponame>tdans1/Use-Galaxy<filename>test/api/test_jobs.py<gh_stars>1-10
import datetime
import json
import os
import time
from operator import itemgetter
from base import api
from base.api_asserts import assert_status_code_is_ok
from base.populators import (
DatasetPopulator,
wait_on,
wait_on_state,
)
f... | StarcoderdataPython |
1614824 | import os
#----------------------------------------------------------------
# P r o j e c t
#----------------------------------------------------------------
ROOT_DIR = os.path.dirname(
os.path.dirname(os.path.dirname(os.path.abspath(__file__))
)) # This is your Project Root
CACHE_DIR = 'cache'
CACHE_MAP_DIR = '/... | StarcoderdataPython |
1710133 | ## generate cues from grad-cam++
import os
os.environ["CUDA_VISIBLE_DEVICES"]="1"
import torch
from tqdm import tqdm
import torch.nn.functional as F
from gradcam import GradCAMPlusPlus
import numpy as np
from TTT_loader import myImageFloder_img_path
from model import ClassificationModel
from scipy import ndimage
impor... | StarcoderdataPython |
3252654 | <gh_stars>0
"""
Created on Thu Dec 22 19:31:52 2016
@author: <NAME>
"""
#%%
import collections #High-performance container datatypes
import pandas as pd
#pandas is an open source, BSD-licensed library providing high-performance,
#easy-to-use data structures and data analysis tools for the Python programm... | StarcoderdataPython |
10644 | # coding: utf-8
"""
manage.py
~~~~~~~~~
"""
import os
import sys
import shutil
import platform
from app import app
from gen import Gen
from flask_script import Manager
"""编码设置"""
if (platform.python_version().split('.')[0] == '2'):
# reload(sys) is evil :)
reload(sys)
sys.setdefaultencoding('utf... | StarcoderdataPython |
53023 | <reponame>digitalsatori/odoo-demo-addons-tutorial
from odoo import models, fields, api
class DemoHierarchyTutorial(models.Model):
_name = 'demo.hierarchy'
_description = 'Demo Hierarchy Tutorial'
name = fields.Char(string='name', index=True)
parent_id = fields.Many2one('demo.hierarchy', string='Relate... | StarcoderdataPython |
1792397 | <filename>chamber_of_comm.py
import requests
from bs4 import BeautifulSoup
import numpy as np
import pymysql
import time
from random import randint
from time import sleep
import re
# defining user-agents
headers = {"User-Agent": "Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11"}
# Databas... | StarcoderdataPython |
82050 | <reponame>myron0330/caching-research<filename>core/basic.py
# -*- coding: UTF-8 -*-
# **********************************************************************************#
# File: Basic class file
# **********************************************************************************#
from utils.dict_utils import Defaul... | StarcoderdataPython |
1760498 | <reponame>AstroHuntsman/fast-zwo
import time
from asi import ASICamera
def frame_rate_test(camera, n=100):
start_time = time.monotonic()
camera.start_video_capture()
for i in range(n):
image = camera.get_video_data()
end_time = time.monotonic()
camera.stop_video_capture()
fps = n / (e... | StarcoderdataPython |
3350712 | import os
import asyncio
import discord
import requests, json
from discord.ext import commands
from discord.ext.commands import MissingRequiredArgument
from datetime import timedelta, datetime
from cogs.libs import brainfuck # BrainFu*k Interpreter
from cogs.libs import getch
from libs import httpsession
# from cogs... | StarcoderdataPython |
3315796 | <gh_stars>1-10
from argparse import ArgumentParser
from datetime import datetime, timedelta
import pytz
import time
import curses
from attrdict import AttrDict
from hydra.app import HydraApp
from hydra.rpc.base import BaseRPC
from hydra.test import Test
COLOR_GOOD = 2
COLOR_WARN = 8
COLOR_ERROR = 4
COLOR_ETC = 10
... | StarcoderdataPython |
21190 | <filename>dust/admin.py
from django.utils.html import format_html
def full_address(self):
return format_html('%s - <b>%s,%s</b>' % (self.address, self.city, self.state))
# null derek yazylmaly hat
admin.site.empty_value_display = '???'
admin.site.register(Item)
# str funksivany ady bilen gorkezyar
class ItemAd... | StarcoderdataPython |
1706203 | <reponame>cnlinxi/raspberrypi-demos
import socket
import time
import smtplib
from urllib.request import urlopen
from email.mime.text import MIMEText
from email.header import Header
from email.utils import parseaddr, formataddr
def _format_addr(s):
name, addr = parseaddr(s)
return formataddr((Header(name, 'utf... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.