id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
95329 | <reponame>Melimet/DAP2020
#!/usr/bin/python3
import unittest
from tmc import points
from tmc.utils import load, get_out
coefficient_of_determination = load('src.coefficient_of_determination', 'coefficient_of_determination')
class CoefficientOfDetermination(unittest.TestCase):
@points('p05-12.1')
def test... | StarcoderdataPython |
3265141 | <reponame>ASMlover/study
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
#
# Copyright (c) 2020 ASMlover. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must r... | StarcoderdataPython |
124429 | from sports.nba.nba_team import NBA_Team
class PhoenixSuns(NBA_Team):
"""
NBA Golden State Warriors Static Information
"""
full_name = "<NAME>"
name = "Suns"
team_id = 1610612756
def __init__(self):
"""
"""
super().__init__()
| StarcoderdataPython |
3255579 | class OperatorUtils():
@classmethod
def apply_assignment_op(cls, left, op, right):
if op == "=":
return right
elif op == "*=":
return left * right
elif op == "/=":
return left / right
elif op == "%=":
return left % right
eli... | StarcoderdataPython |
1610338 | """Rational quadratic kernel."""
from typing import Optional
import numpy as np
import probnum.utils as _utils
from probnum.typing import IntArgType, ScalarArgType
from ._kernel import IsotropicMixin, Kernel
class RatQuad(Kernel, IsotropicMixin):
r"""Rational quadratic kernel.
Covariance function defined... | StarcoderdataPython |
75341 | <filename>conekt/flask_blast/__init__.py
from .blast import BlastThread | StarcoderdataPython |
3354636 | # Generated by Django 3.0.4 on 2021-03-07 01:30
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('api', '0013_auto_20210307_0125'),
]
operations = [
migrations.AddField(
... | StarcoderdataPython |
23190 | <filename>src/python_module_setup.py
from distutils.core import setup, Extension
import os
#os.environ['USE_CUDA'] = '1'
#os.environ['USE_BLAS'] = '1'
#os.environ['USE_OPENMP'] = '1'
cuda_obj = []
cuda_extra = []
cuda_include = []
cuda_macro = [(None, None)]
blas_obj = []
blas_extra = []
blas_include = []
blas_macr... | StarcoderdataPython |
1725759 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
将Omicron中与性能相关比较密切的函数抽取到这个模块。以便将来进行加速。
TODO: 部分函数之前已使用numba加速,但因numba与OS的兼容性问题取消。需要随时保持跟踪。
"""
import logging
import numpy as np
from deprecated import deprecated
logger = logging.getLogger(__name__)
@deprecated(version="1.1")
def index(arr, item): # pragma: no co... | StarcoderdataPython |
123905 | <gh_stars>10-100
"""Algorithms for STRIPS learning that start from the most general operators,
then specialize them based on the data."""
import itertools
from typing import Dict, List, Set
from predicators.src import utils
from predicators.src.nsrt_learning.strips_learning import BaseSTRIPSLearner
from predicators.s... | StarcoderdataPython |
3320448 | from PIL import Image
from PIL import ImageFilter
import utils.logger as logger
#from utils.rotate import rotate
from config import *
from typing import Tuple, List
import sys
i = 0
def crop_image(image, area:Tuple) -> object:
''' Uses PIL to crop an image, given its area.
Input:
image - PIL opened image
Area - C... | StarcoderdataPython |
3263143 | #Exercício Python 012: Faça um algoritmo que leia o preço de um produto e mostre seu novo preço, com 5% de desconto.
price = float(input('Enter product price: '))
discount = price * 0.05
new_price = price - discount
print('New product price is: %.2f' %new_price)
| StarcoderdataPython |
3265156 | <filename>src/fnc/sequences.py<gh_stars>100-1000
"""
Functions that operate on sequences.
Most of these functions return generators so that they will be more efficient at processing large
datasets. All generator functions will have a ``Yields`` section in their docstring to easily
identify them as generators. Otherwis... | StarcoderdataPython |
1695285 | from ttracker.model.items.match import MatchResult
class Player:
def __init__(self, content):
self.user_id = content['userId']
self.player_name = content['playerName']
self.system_seat_id = content['systemSeatId']
self.team_id = content['teamId']
def __repr__(self):
r... | StarcoderdataPython |
3265142 | from tracker.app import app as application
| StarcoderdataPython |
1720739 | <gh_stars>0
import vk_api
import datetime
import colorama
from colorama import Fore
colorama.init()
editnumber = [('0', '0⃣'), ('1', '1⃣'), ('2', '2⃣'), ('3', '3⃣'), ('4', '4⃣'), ('5', '5⃣'), ('6', '6⃣'), ('7', '7⃣'), ('8', '8⃣'), ('9', '9⃣')]
ballnumber = [('0', ''), ('1', '❶'), ('2', '❷'), ('3', '❸'), ('4', '❹'), ('... | StarcoderdataPython |
76335 | <filename>LiveFeedback/CentralLinePhantom1.py
import os
import keras
import sys
import time
import numpy as np
from keras.models import Sequential
from keras.layers import Activation, GlobalAveragePooling2D
from keras.layers.core import Dense, Dropout, Flatten
from keras.optimizers import Adam, SGD
from keras.metrics ... | StarcoderdataPython |
3328103 | <reponame>shiburizu/concerto-direct
#core
from winpty import PtyProcess #pywinpty
import os, sys, time, re, threading, logging
from functools import partial
from datetime import datetime
logging.basicConfig(filename='concerto.log', encoding='utf-8', level=logging.DEBUG)
# Pyinstaller path helper
def resource_pat... | StarcoderdataPython |
3222602 | import datetime
import typing
from typing_extensions import TypeGuard
from .. import spec
from .. import exceptions
from . import timelength_units
def detect_timelength_representation(
timelength: spec.Timelength,
) -> spec.TimelengthRepresentation:
"""return str name of Timelength representation"""
if ... | StarcoderdataPython |
3270854 | <filename>openprescribing/pipeline/management/commands/org_codes.py
from io import BytesIO
import requests
from zipfile import ZipFile
import datetime
import os
from django.conf import settings
from django.core.management import BaseCommand
"""Practice and CCG metadata, keyed by code.
Similar data, pertaining to spe... | StarcoderdataPython |
141861 | <reponame>tonnkie/USC-Second-hand-Group
# coding:utf-8
import re
def emoji_print(rawstring):
flag = True
while flag:
start = rawstring.find('<span')
end = rawstring.find('></span>')
if start < 0 or end < 0:
flag = False
break
emojistr = rawstring[start :... | StarcoderdataPython |
3257332 | <filename>run.py
import itertools
import json
import random
import sys
import time
import networkx as nx
import eon
if hasattr(time, 'process_time_ns'):
process_time = time.process_time_ns
else:
process_time = time.process_time
def run(algorithm, seed, weight='distance', log=1):
if algorithm == 'filtere... | StarcoderdataPython |
1695264 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# This example demonstrates the use of Convolution1D for text classification.
# 利用1D-CNN模型对IMDB影评倾向分类
# Output after 5 epochs on CPU(i5-7500)/GPU(1050Ti): ~0.8773
from keras.preprocessing import sequence
from keras.models import Sequential
from keras.layers import Dense, Drop... | StarcoderdataPython |
1660041 | from sko.GA import GA
def demo_func(x):
x1, x2, x3 = x
return x1 ** 2 + (x2 - 0.05) ** 2 + x3 ** 2
ga = GA(func=demo_func, lb=[-1, -10, -5], ub=[2, 10, 2], max_iter=500)
best_x, best_y = ga.fit()
| StarcoderdataPython |
3206616 | from datetime import time
import time as t
from heatmiserV3.devices import Master, Device
from heatmiserV3.config import Config
import logging
import logging.config
from heatmiserV3.protocol_manager import ProtocolManager
def main():
log_config = Config.LOG_CONFIG
logging.config.dictConfig(log_... | StarcoderdataPython |
1703437 | <reponame>cyphermaster/beholder
#!/usr/bin/python2.7
# -*- coding: utf8 -*-
"""
Copyright [2014,2015] [beholder developers]
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.or... | StarcoderdataPython |
1605870 | <gh_stars>0
a,b = map(int, input().split())
if (b % a == 0) or (a % b == 0):
print("Sao Multiplos")
else:
print("Nao sao Multiplos") | StarcoderdataPython |
4815472 | <reponame>Elec5616/prophessor<filename>phabricator/api.py
import subprocess
import json
from local_settings import PHAB_API_ADDRESS, PHAB_API_TOKEN
phab_api_templates = {
"remove_user_from_project": {
"method": "project.edit",
"data": "api.token=" + PHAB_API_TOKEN + "&transactions[0][type]=members.... | StarcoderdataPython |
3248685 | <filename>tests/conftest.py
from asyncio import get_event_loop
import pytest
@pytest.fixture
def event_loop():
return get_event_loop()
| StarcoderdataPython |
1605738 | <reponame>agaldemas/ngsi-timeseries-api
"""
Data structures and operations to manage work queues.
Notice these data structures and operations abstract away the underlying
RQ implementation so clients don't have to depend on the RQ API.
"""
from enum import Enum
from typing import Callable, Iterable, List, Optional
fro... | StarcoderdataPython |
117289 | #!/usr/bin/env python3
import os
import pathlib
import re
import subprocess
import sys
from typing import List
def main():
os.chdir(str(get_toplevel_dir()))
check_unstaged_changes()
files = get_tracked_files()
check_go_source(files)
make('build')
make('test')
make('test-large')
def che... | StarcoderdataPython |
163764 | <filename>dynn/activations.py
#!/usr/bin/env python3
"""
Activation functions
====================
Common activation functions for neural networks.
Most of those are wrappers around standard dynet operations
(eg. ``rectify`` -> ``relu``)
"""
import dynet as dy
def identity(x):
"""The identity function
:ma... | StarcoderdataPython |
1773770 | <gh_stars>0
# Promote all symbols from submodules to the top-level package (TODO is this bad practice?)
from .api import *
from .core import *
from .kubernetes import *
from .settings import *
from .slo import *
| StarcoderdataPython |
1782253 | # -*- coding: utf-8 -*-
from scipy import sparse as spspa
from scipy.sparse import linalg as spspalinalg
from time import time
from root.config.main import cOmm, rAnk, mAster_rank
from tools.linear_algebra.data_structures.global_matrix.main import LocallyFullVector
def ___scipy_sparse_linalg_v0___(A, b, COD=None):
... | StarcoderdataPython |
186654 | # Generated with Iteration
#
from enum import Enum
from enum import auto
class Iteration(Enum):
""""""
COLUMN = auto()
GRID = auto()
def label(self):
if self == Iteration.COLUMN:
return "Column"
if self == Iteration.GRID:
return "Grid" | StarcoderdataPython |
3324372 | from rdflib import XSD, Literal
class TestTokenDatatype:
def test1(self):
lit2 = Literal("\two\nw", datatype=XSD.normalizedString)
lit = Literal("\two\nw", datatype=XSD.string)
assert str(lit) != str(lit2)
def test2(self):
lit = Literal("\tBeing a Doctor Is\n\ta Full-Time J... | StarcoderdataPython |
3282507 | # coding: utf-8
__author__ = 'cleardusk'
import sys
sys.path.append('..')
import cv2
import numpy as np
import os.path as osp
from Sim3DR import rasterize, rasterize_adv
from _3DDFA_V2.utils.functions import plot_image
from _3DDFA_V2.utils.io import _load, _dump
from _3DDFA_V2.utils.tddfa_util import _to_ctype
ma... | StarcoderdataPython |
3203640 | # This algorithm search the way to move disk from one tower to another with just one rule.
# You can't put a big disk over a small one. #
# Input: height, initTower, middleTower, finalTower
# Output: initTower, middleTower, finalTower
# we put this to prove we sent from the initTower to the finalTower every disk
def... | StarcoderdataPython |
182336 | <filename>src/local_run.py
__author__ = 'david'
from davesite.app.factory import create_app
app = create_app()
app.run("", 8080) | StarcoderdataPython |
1745900 | <reponame>kingformatty/E2E-NLG-Project
import os
import logging
import numpy as np
import torch
import torch.nn as nn
from components.utils.visualize import plot_train_progress, plot_lcurve
from components.data.common import cuda_if_gpu
from torch.autograd import Variable
from components.trainer import BaseTrainer
lo... | StarcoderdataPython |
190889 | <gh_stars>0
from urllib import request
class Request:
def __init__(self, url):
self.url = url
class Client:
def __init__(self, req):
self.req = req
def get(self):
source = request.urlopen(self.req.url)
data = source.read()
return data | StarcoderdataPython |
138988 | <gh_stars>0
import os
from setuptools import setup
import crudbuilder
# Allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='django-crudbuilder',... | StarcoderdataPython |
99266 | import sys, configparser
from math import floor
from fractions import Fraction
from .matrixOp import frange
from collections import OrderedDict
# NOTE File path starts where main.py executes
config = configparser.ConfigParser()
filePath = 'config.ini'
# Reads config file and returns variables
# TODO enforce input ty... | StarcoderdataPython |
3391494 | import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from context import bbfsa
#read csv file
spectra = pd.read_csv('./tests/workflow/input/700cow.csv', delimiter=',', names= ['wn', 'ab'])
# cristallinity index
s = bbfsa.slice(spectra,700,400) #slice for baseline
b = bbfsa.baseline(s) #baseline
... | StarcoderdataPython |
1747627 | from machine import Pin
import utime
button = Pin(16, Pin.IN, Pin.PULL_UP)
while True:
b1 = button.value()
if not b1:
print('Button pressed!')
utime.sleep(0.5)
| StarcoderdataPython |
5689 | <gh_stars>0
from __future__ import absolute_import
import six
from sentry.utils.safe import get_path, trim
from sentry.utils.strings import truncatechars
from .base import BaseEvent
def get_crash_location(exception, platform=None):
default = None
for frame in reversed(get_path(exception, 'stacktrace', 'fra... | StarcoderdataPython |
194791 | <reponame>cgarciae/tf-interface
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# __coconut_hash__ = 0xaa0f5a8b
# Compiled with Coconut version 1.2.3-post_dev1 [Colonel]
# Coconut Header: --------------------------------------------------------
from __future__ import print_function, absolute_import, unicode_literals, ... | StarcoderdataPython |
3227639 | # Licensed Materials - Property of IBM
# Copyright IBM Corp. 2017
import unittest
import sys
import itertools
import time
import os
from streamsx.topology.topology import *
from streamsx.topology.tester import Tester
from streamsx.topology import schema
import streamsx.topology.context
import streamsx.spl.op as op
c... | StarcoderdataPython |
152418 | <filename>server/athenian/api/models/web/pull_request_event.py
from athenian.api.models.web.base_model_ import Enum, Model
class PullRequestEvent(Model, metaclass=Enum):
"""PR's modelled lifecycle events."""
CREATED = "created"
COMMITTED = "committed"
REVIEW_REQUESTED = "review_requested"
REVIEWE... | StarcoderdataPython |
4818088 | <reponame>tao-shen/FedGraph
import torch.nn as nn
from dgl.nn.pytorch import GraphConv
import torch.nn.functional as F
import dgl.function as f
class MLP(nn.Module):
def __init__(self, in_feats, n_hidden, num_classes, n_layers, dropout):
super(MLP, self).__init__()
self.activation = F.relu
... | StarcoderdataPython |
1786691 | <reponame>fengjixuchui/androguard
import hashlib
import os
import sys
import collections
from androguard.core.analysis.analysis import Analysis
from androguard.core.bytecodes.dvm import DalvikVMFormat, DalvikOdexVMFormat
from androguard.core.bytecodes.apk import APK
from androguard.decompiler.decompiler import Decompil... | StarcoderdataPython |
1607661 | <gh_stars>100-1000
from __future__ import absolute_import
import logging
import numpy as np
from .import utils
from .import sampling
from sklearn.preprocessing import MultiLabelBinarizer, LabelBinarizer
from sklearn.model_selection import StratifiedShuffleSplit
logger = logging.getLogger(__name__)
class Dataset(... | StarcoderdataPython |
3209885 | # -*- coding: utf-8 -*-
from six import text_type
from typing import Union
from zerver.lib.test_classes import WebhookTestCase
class BitbucketHookTests(WebhookTestCase):
STREAM_NAME = 'bitbucket'
URL_TEMPLATE = "/api/v1/external/bitbucket?payload={payload}&stream={stream}"
FIXTURE_DIR_NAME = 'bitbucket'
... | StarcoderdataPython |
1612278 | <gh_stars>1-10
import logging
logging.basicConfig(filename='test_deleteme.log', filemode='w', level=logging.DEBUG)
"""
Acquire data for training a Machine-Learning algorithm
"""
import pandas as pd
from .ArXivTrainingData import ArXivTrainingData
from .CrossRefTrainingData import CrossRefTrainingData
from .... | StarcoderdataPython |
4809123 | # Generated by Django 3.2.4 on 2021-08-12 23:50
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('museum_site', '0066_rename_patron_level_profile_patronage'),
]
operations = [
migrations.AlterField(
model_name='profile',
... | StarcoderdataPython |
1692767 | # Generated by Django 3.1.2 on 2020-11-04 08:54
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('bills', '0007_auto_20201104_0251'),
]
operations = [
migrations.AddField(
model_name='storeunion',
name='is_credit_u... | StarcoderdataPython |
1672920 | <filename>src/sage/rings/padics/padic_extension_leaves.py
"""
p-Adic Extension Leaves
The final classes for extensions of Zp and Qp (ie classes that are not
just designed to be inherited from).
AUTHORS:
- <NAME>
"""
#*****************************************************************************
# Copyright (C)... | StarcoderdataPython |
1618228 | <filename>test/integration/ggrc/converters/test_import_assessment_templates.py
# Copyright (C) 2019 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# pylint: disable=maybe-no-member
"""Test Assessment Template import."""
from collections import OrderedDict
from ggrc import ... | StarcoderdataPython |
3219319 | <reponame>Minkov/python-oop-2021-02<filename>interators_generators/iterators.py
ll = [1, 2, 3, 4, 5]
for x in ll:
print(x)
print([[x + 1] for x in ll])
ll_iter_1 = iter(ll)
ll_iter_2 = iter(ll)
print(ll_iter_1)
# print(f'Iter1: {next(ll_iter_1)}')
# print(f'Iter1: {next(ll_iter_1)}')
# print(f'Iter1:... | StarcoderdataPython |
1799010 | <reponame>SilvaneiMartins/api_user_python_flask
from flask.json import JSONEncoder
class USERS(object):
new_id = 1
def __init__(self, name, email, password):
self.name = name
self.email = email
self.password = password
self.id = USERS.new_id
USERS.new_id += 1
class U... | StarcoderdataPython |
3350010 | #!/usr/bin/env python3
import argparse as arp
import os
import sys
##### PARSING COMMAND LINE ARGUMENTS #####
prs = arp.ArgumentParser()
prs.add_argument('sp_data_path', type = str, help = 'path of spatial data')
prs.add_argument('cuda_device', type = str, help = "index of cuda device ID or cpu")
prs.add_argument('... | StarcoderdataPython |
3289045 | from auto_yolo import envs
readme = "Testing air variational autoencoder with math."
distributions = None
durations = dict()
n_digits = 2
largest_digit = n_digits * 9
n_classes = largest_digit + 1
config = dict(
n_train=16000, min_digits=n_digits, max_digits=n_digits,
max_time_steps=n_digits, run_all_time_... | StarcoderdataPython |
3212936 | """Handles for Broden-like datasets.
The original Broad and Densely Labeled Dataset (Broden_) was introduced in
[Bau2017]_ as a combination of several existing semantic segmentation and
classification datasets on overlapping image sets.
For more details on Broden and its encoding see :py:class:`BrodenHandle`.
.. note:... | StarcoderdataPython |
19460 | <reponame>ceshine/pytorch-helper-bot
""" Finetuning BERT using DeepSpeed's ZeRO-Offload
"""
import json
import dataclasses
from pathlib import Path
from functools import partial
import nlp
import torch
import typer
import deepspeed
import numpy as np
from transformers import BertTokenizerFast
from transformers import ... | StarcoderdataPython |
1778542 | #!/usr/bin/env python
# Author: <NAME>
# License: Open Source based, so open source distribution.
import sys
import pdfkit
from barcode import Code128
from barcode.writer import ImageWriter
BARCODE_OPTIONS = {
'font_size': 12,
'text_distance': 2.0
}
PDF_OPTIONS = {
'page-size': 'A4',
'margin-top': '0.... | StarcoderdataPython |
93330 | <reponame>mindsolve/pySymProxy
import logging
import logging.config
import logging.handlers
import json
import os
def findConfigFile(candidates):
for location in candidates:
if os.path.isfile(location):
return location
return candidates[-1]
def findConfigValue(rootDict, name, required = Fa... | StarcoderdataPython |
102430 | from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('', include('frontend.urls')), # home page react
path('', include('leads.urls')), # leads page api
path('', include('accounts.urls')), # accounts page api
]
| StarcoderdataPython |
1683761 | import os
import nbformat
from textwrap import dedent
from .preprocessor import Preprocessor
from ..utils import (
is_grade, is_solution, is_description,
get_task_info, get_valid_name, get_points)
class AddTaskHeader(Preprocessor):
def get_header(self, idx, points):
header = nbformat.v4.new_ma... | StarcoderdataPython |
1614329 | <gh_stars>0
from numba.core import dispatcher, compiler
from numba.core.registry import cpu_target, dispatcher_registry
import numba_dppy.config as dppy_config
class DpplOffloadDispatcher(dispatcher.Dispatcher):
targetdescr = cpu_target
def __init__(self, py_func, locals={}, targetoptions={}, impl_kind='dire... | StarcoderdataPython |
3299489 | <reponame>jerinka/Redis_OpenCV
import redis
import cv2
import numpy as np
import time
import io
import uuid
r = redis.StrictRedis.from_url('redis://')
img_path ="redis.png"
uid = str(uuid.uuid1())
img1 = cv2.imread(img_path, 1)
retval, buffer = cv2.imencode('.png', img1,[cv2.IMWRITE_PNG_COMPRESSION, 0])
img1_bytes =... | StarcoderdataPython |
149830 | <gh_stars>1-10
import os
import numpy as np
from taskinit import tb
def cpxx2yy(tb_in=[]):
if not tb_in:
print('tb_in not provided. Abort...')
if type(tb_in) is str:
tb_in = [tb_in]
tb.open(tb_in[0] + '/SPECTRAL_WINDOW', nomodify=False)
nspw = tb.nrows()
tb.close()
for ctb in tb... | StarcoderdataPython |
4839786 | <reponame>mrTavas/owasp-fstm-auto
import sys
import logging
import os
import json
import binascii
from pwn import *
import random
# Unicorn imports
# require unicorn moudle
from unicorn import *
from unicorn.arm_const import *
from unicorn.arm64_const import *
from unicorn.x86_const import *
from unicorn.mips_const... | StarcoderdataPython |
3242012 | from django import forms
class PlaceholderForm(forms.Form):
"""
A base form for automatically adding placeholder text.
Forms that extend this form will by default have all text, password, and
date input widgets display placeholder text equal to their label. This can
be overridden per form field b... | StarcoderdataPython |
119933 |
## bisenetv2
cfg = dict(
model_type='bisenetv2',
num_aux_heads=4,
lr_start = 5e-2,
weight_decay=5e-4,
warmup_iters = 1000,
max_iter = 150000,
im_root='./datasets/coco',
train_im_anns='./datasets/coco/train.txt',
val_im_anns='./datasets/coco/val.txt',
scales=[0.5, 1.5],
crops... | StarcoderdataPython |
1661238 | from django.conf.urls import url
from project import views
urlpatterns = [
url(r'^urlinfo/', views.urlinfo),
url(r'^urlinfoselect/', views.urlinfoselect),
url(r'^baseinfo/', views.baseinfo),
url(r'^getproname/', views.getproname),
url(r'^getmodelname/', views.getmodelname),
]
| StarcoderdataPython |
106245 | import argparse
import asyncio
import logging
from pathlib import Path
from dvdp.ha_433 import HA433Light
from dvdp.recorder_433 import RECORDINGS_DIR, get_recordings
from dvdp.ha_mqtt.client import MQTTClient
def main():
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',... | StarcoderdataPython |
75043 | <filename>deprecated/db_functions.py
# This script stores common database operations
import sys
import MySQLdb
global DEBUG
DEBUG = 1
global c, conn
conn = MySQLdb.connect(host="localhost", \
user="root", \
passwd="<PASSWORD>", \
db='twins') # use c... | StarcoderdataPython |
115856 | import gym
import tensorflow as tf
from rl.agent import util
class A3CModel(tf.keras.Model):
def __init__(self, env):
super().__init__()
self.action_is_continuous, self.action_size, self.action_low, self.action_high = util.parse_env(
env
)
# Policy (actor) layer
... | StarcoderdataPython |
1629935 | <filename>src/umassstembot/coronavirus.py
from bs4 import BeautifulSoup
import overlay as over
import dateutil.parser
import dateutil.utils
import discord
import requests
import os
import tempfile
FINNHUB_CORONA_TOKEN = os.environ.get('FINNHUB_API_TOKEN_5')
us_areas = {'AL': ['Alabama', '4903185'],
'AK': ... | StarcoderdataPython |
3217494 | <reponame>bogdanvuk/pygears
from pygears import alternative, TypeMatchError, gear
from pygears.typing import Union
from pygears.lib import fmap as common_fmap
from pygears.lib.mux import mux
from pygears.lib.demux import demux_ctrl
from pygears.lib.ccat import ccat
from pygears.lib.shred import shred
def unionmap_che... | StarcoderdataPython |
31013 | # from django.db.models.signals import post_save
# from django.dispatch import receiver
# from onadata.apps.logger.models import XForm
#
# from onadata.apps.fsforms.models import FieldSightXF
#
#
# @receiver(post_save, sender=XForm)
# def save_to_fieldsight_form(sender, instance, **kwargs):
# FieldSightXF.objects.c... | StarcoderdataPython |
1752026 | from django.conf.urls.defaults import *
urlpatterns = patterns('',
url(r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/(?P<day>\w{1,2})/(?P<object_id>\d+)/$',
view = 'basic.bookmarks.views.bookmark_detail',
name = 'bookmark_detail',
),
url(r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/(?P<day>\w{1,2})/$',
vie... | StarcoderdataPython |
167459 | <reponame>ufkapano/planegeometry
#!/usr/bin/python
import unittest
from fractions import Fraction
from planegeometry.structures.points import Point
from planegeometry.structures.segments import Segment
from planegeometry.algorithms.bentleyottmann2 import BentleyOttmann
class TestBentleyOttmann(unittest.TestCase):
... | StarcoderdataPython |
1602556 | import os
from contextlib import contextmanager
@contextmanager
def cwd(path):
old_path = os.getcwd()
os.chdir(path() if callable(path) else path)
try:
yield
finally:
os.chdir(old_path)
def in_dir(path):
def decorator(fn):
def wrapper(*args, **kwargs):
with cw... | StarcoderdataPython |
3236717 | import random # because we'll need this ha, ha, ha
# the vocabulary could just be a single list but I've organized more-or-less
# in case I want to try a few grammaticaly rules later:
people = [
'<NAME>',
'<NAME>',
'<NAME>',
'<NAME>',
'<NAME>',
'<NAME>',
'<NAME>',
'Jaybez',
'... | StarcoderdataPython |
1604131 | <gh_stars>0
import numpy.testing as npt
from numpy import (absolute, all, arange, array, cos, linspace, log, sin)
from ..nearshockapproximator import (NearShockApproximator,
NearShockFifthOrderApproximator)
class TestNearShockApproximator:
def test__two_points_away_from_shoc... | StarcoderdataPython |
3342864 | # This file is Copyright 2009, 2010 <NAME>.
#
# This file is part of the Python-on-a-Chip program.
# Python-on-a-Chip is free software: you can redistribute it and/or modify
# it under the terms of the GNU LESSER GENERAL PUBLIC LICENSE Version 2.1.
#
# Python-on-a-Chip is distributed in the hope that it will be useful... | StarcoderdataPython |
1700750 | from mldp.steps.transformers.base_transformer import BaseTransformer
from mldp.utils.helpers.validation import validate_field_names
from mldp.utils.helpers.nlp.sequences import compute_windows
from mldp.steps.transformers.nlp.helpers import create_new_field_name
from mlutils.helpers.general import listify
import numpy ... | StarcoderdataPython |
99496 | # -*- coding: utf-8 -*-
"""
Created on Thu Mar 31 12:44:45 2022
@author: Danie
DEPRICATED FILE DO NOT USE
Old biolerplate work for when stage 3 classification was just going to be selecting a set of representative
points create by ModelsA B and C. Has terrible accuracy and should absolutley not be used.
"""
import... | StarcoderdataPython |
1767807 | <gh_stars>1-10
from . import node
import json
import copy
class Edge :
"""
Edge
======
A simple edge, embedding a `id_a`, a `id_b` and a `modality`.
"""
def __init__(self, id_edge: str, a: node.Node, b: node.Node, modality: str = "1", directed: bool = False):
"""
Nodes are given instead of just t... | StarcoderdataPython |
3334621 | <reponame>objectnf/training-code<filename>Lead-to-New-Language/Python/tool - pyinstaller/basic - syntaxSugar01.py
a = 10; b = 5 # 单行定义多个变量
c = [a, b][a < b] # 将a、b中的小值赋值给c
# 若 a < b 为 True, 取 [a, b][1]; 若 a < b 为 False, 取 [a, b][0]
print("c = " + str(c))
# 也可以写成如下形式:
c = a if a < b else b
del c # 清除变量
s... | StarcoderdataPython |
3363240 | from basetestcase import FormTestCase
from _test_app.forms import MyForm, MyBaseFormSet, MyFormSet
from _test_app.models import MyModel
class FormTestCaseTest(FormTestCase):
def form(self, *args, **kwargs):
form = MyForm(*args, **kwargs)
return form
def test_field_rendered(self... | StarcoderdataPython |
4816670 | <filename>run.py<gh_stars>1-10
from kernel_matrix_benchmarks.main import main
from multiprocessing import freeze_support
if __name__ == "__main__":
# Freeze_support is a Windows-only function that ensures compatibility
# with a ".py -> .exe" packaging method. On Linux, this has zero consequences.
freeze_su... | StarcoderdataPython |
110693 | <reponame>etianen/py.sh<gh_stars>1-10
class StyleMapping:
def __init__(self, opts):
self._opts = opts
def __getitem__(self, key):
return getattr(self._opts, "style_{}".format(key), "").encode().decode("unicode_escape")
def apply_styles(opts, command):
return command.format_map(StyleMappi... | StarcoderdataPython |
143920 | <reponame>archerckk/PyTest<gh_stars>0
'''
1.能使用随机数
2.用户猜对了提示信息
3.用户猜错能显示用户猜大了还是猜小了
4.机会一共只有3次
5.用户用完三次机会或者猜对了游戏结束
'''
import random
target=random.randint(1,10)
times=3
while times!=0:
tmp=input('请输入你要猜的数字:')
while not tmp.isdigit():
tmp=input('你的输入有误,请重新输入:')
guess=int(tmp)
times-=1
if targ... | StarcoderdataPython |
1744766 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
from queue import Queue
def coroutine(func):
def start(*args, **kwargs):
rc = func(*args, **kwargs)
rc.next()
return rc
return start
@coroutine
def threaded(target):
messages = Queue() # message queue
def run_target():
w... | StarcoderdataPython |
1744234 | <filename>flask_cognito.py
from collections import OrderedDict
from functools import wraps
from flask import _request_ctx_stack, current_app, jsonify, request
from werkzeug.local import LocalProxy
from cognitojwt import CognitoJWTException, decode as cognito_jwt_decode
from jose.exceptions import JWTError
import loggin... | StarcoderdataPython |
3367463 | from __future__ import print_function
from __future__ import division
from future import standard_library
standard_library.install_aliases()
#from builtins import str
from builtins import range
from quantities.quantity import Quantity
from quantities import mV, nA
import sciunit
from sciunit import Test,Score
try:
... | StarcoderdataPython |
3284042 | <filename>tests/multi_process/zeromq_queue.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Tests for the the zeromq queue."""
import unittest
from plaso.lib import errors
from plaso.multi_process import zeromq_queue
from tests import test_lib as shared_test_lib
class ZeroMQPullBindQueue(zeromq_queue.ZeroMQPul... | StarcoderdataPython |
4838102 | <reponame>bencarlisle15/AlexaControlledSamsungTV<filename>tvconfig.py<gh_stars>1-10
device_name = "Pi" #What shows up under devices in alexasmarttv.tk. not that important unless you have multiple devices (not tvs) on your account
volume_step_size = 5 #how much your tv volume should go up by when you say 'Alexa, turn u... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.