id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
39430 | import sys
from collections import deque
n = int(sys.stdin.readline())
deck = deque(list(range(1, n+1)))
for i in range(n-1):
deck.popleft()
deck.append(deck.popleft())
print(str(deck.pop()))
| StarcoderdataPython |
23783 | <reponame>cdgagne/django-dynamicform
from django import forms
from django.forms.utils import flatatt
from django.utils import formats
from django.utils.encoding import force_text
from django.utils.html import format_html
class AjaxValidatingTextInput(forms.TextInput):
def __init__(self, *args, **kwargs):
... | StarcoderdataPython |
157454 | <reponame>Kitware/kwimage<gh_stars>1-10
import torch
import numpy as np
import kwimage
import copy
import ubelt as ub
import itertools as it
# from kwimage.algo._nms_backend.torch_nms import torch_nms
def ensure_numpy_indices(keep):
import kwarray
keep = kwarray.ArrayAPI.numpy(keep)
# if torch.is_tensor(k... | StarcoderdataPython |
3361398 | <filename>TestTamanduaParam.py
import TamanduaParam
strfile = 'C:\\Users\\C\\Desktop\\ttt.csv'
tman=TamanduaParam.TamanduaParam(strfile)
#print tman.GetAllParam()
aa = tman.CalTaseCaseParam()
bb = tman.GetAllParam()
f=open('C:\\Users\\C\\Desktop\\11.txt','w')
print bb
print '--------------------'
print... | StarcoderdataPython |
169347 | # -*- coding: utf-8 -*-
"""
eve.io.mongo.flask_pymongo
~~~~~~~~~~~~~~~~~~~
Flask extension to create Mongo connection and database based on
configuration.
:copyright: (c) 2017 by <NAME>.
:license: BSD, see LICENSE for more details.
"""
from flask import current_app
from pymongo import MongoC... | StarcoderdataPython |
1771465 | <gh_stars>1-10
from django.contrib import admin
from django.contrib.auth.models import User
from nadine.admin import EmailAddressInline, UserProfileInline, EmergencyContactInline, XeroContactInline, UserWithProfileAdmin
from ldap_sync.models import LDAPAccountStatus
class LDAPAccountStatusInline(admin.TabularInline):... | StarcoderdataPython |
3398772 | import torch
from torch.nn import BCEWithLogitsLoss
import numpy as np
from itertools import product
DEFAULT_EPS = 1e-10
PADDED_Y_VALUE = -1
# From https://github.com/allegro/allRank/blob/master/allrank on June 7th 2021
def rankNet_weightByGTDiff(y_pred, y_true, padded_value_indicator=PADDED_Y_VALUE):
"""
... | StarcoderdataPython |
3230730 | '''
Created on 1.12.2016
@author: Darren
''''''
Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).
For example,
S = "ADOBECODEBANC"
T = "ABC"
Minimum window is "BANC".
Note:
If there is no such window ... | StarcoderdataPython |
3384460 | from imageprocessing.segmentation import segmentate_grayscale
| StarcoderdataPython |
133704 | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors.
#
# 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 ... | StarcoderdataPython |
3279998 | #!/usr/bin/env python3
import os
import re
import os.path
def add_post(path_to_blog, categories):
# Ввод названия поста
while True:
post_name = input('What is the title of your new post? <yyyy-mm-dd-my-new-post>\n')
post_name_pattern = re.compile("^[0-9]{4}-[0-9]{2}-[0-9]{2}-[a-zA-Z-... | StarcoderdataPython |
3389660 | <filename>Quiz.py
# Importing the necessary module(s)
import time
# A well-maintained Quiz built to unlock the power of your mind. This, being a class, acts as a blueprint for its objects(instances).
class Quiz:
levels = {}
def __init__(self):
self.username = " "
self.gameplay_num = 1
... | StarcoderdataPython |
1697584 | import subprocess
class DbException(Exception):
pass
def execute_cmd(db: subprocess.Popen, cmd: str):
if db.stdin:
print(cmd, file=db.stdin)
def run_cmds(cmds: list[str]) -> list[str]:
db = subprocess.Popen(
["./db", "mydb.db"],
stdin=subprocess.PIPE,
stdout=subprocess.... | StarcoderdataPython |
1755535 | <reponame>leweaver/orangine<gh_stars>0
from logging import log, info
from oe import managers, get_scene, Input, Vector3, Quat
import math
class FirstPersonCamera:
def __init__(self):
self.yaw = 0.0
self.pitch = 0.0
self.mouse_speed = 1.0 / 600.0
self.update_camera()
def tick(self):
mouse... | StarcoderdataPython |
4814793 | #!/usr/bin/python
"""
Copyright (c) 2018 <NAME>
The above copyright notice and the LICENSE file shall be included with
all distributions of this software
"""
import sys
import os.path
import time
import ConfigParser
import getopt
import paho.mqtt.client as mqtt
if __name__ == "__main__":
DEBUG = False
VERB... | StarcoderdataPython |
28395 | <filename>library/load_partial.py
# -*- coding: utf-8 -*-
## Developed by <NAME>
from PyQt5.QtWidgets import QMainWindow, QApplication, QFileDialog, QMessageBox, QSizePolicy, QDialog
from PyQt5.QtGui import QColor, QPalette
from PyQt5 import QtCore
from qt_iron_skillet_ui import Ui_Dialog as IRONSKILLET
from qt_config_... | StarcoderdataPython |
3399747 | # Generated by Django 3.2.10 on 2022-01-06 12:05
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Chat',
fields... | StarcoderdataPython |
116521 | import unittest
from io import StringIO
from book_parser import parse, Styles, ParagraphState, BulletedState, \
ParsingState, DiagramState, MetadataState
class BookParserTest(unittest.TestCase):
def test_paragraph(self):
source = """\
This is a one-line paragraph.
"""
expected_tree = [Paragra... | StarcoderdataPython |
3215903 | <gh_stars>0
# Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you ma... | StarcoderdataPython |
3326302 | <filename>train.py<gh_stars>0
import torch
import torch.nn as nn
import utils
import numpy as np
class Total_loss(nn.Module):
def __init__(self, lambdas):
super(Total_loss, self).__init__()
self.tau = 0.1
self.sampling_size = 3
self.lambdas = lambdas
self.ce_criterion = nn.... | StarcoderdataPython |
1677715 | <gh_stars>1-10
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Genera... | StarcoderdataPython |
165103 | <filename>test/gen_casadi_test.py
#!/usr/bin/env python
"""
Modelica parse Tree to AST tree.
"""
from __future__ import print_function, absolute_import, division, unicode_literals
import os
import glob
import unittest
import itertools
import casadi as ca
import numpy as np
import pymoca.backends.casadi.generator as ... | StarcoderdataPython |
3271766 | <filename>app.py<gh_stars>0
from datetime import datetime
from enum import Enum
from flask import Flask, request, redirect
from flask_sqlalchemy import SQLAlchemy
from config import cfg, secret, domain
from core import base10to62
app = Flask(__name__)
app.config.from_object(cfg)
db = SQLAlchemy(app)
class Short(db... | StarcoderdataPython |
3318142 | <filename>hardware_code/DormTemperature/temperature/views.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import glob
import time
import json
import requests
def read_temp_raw():
#os.system('modprobe w1-gpio')
#os.system('modprobe w1-therm')
base_dir = '/sys/bus/w1/devices/'
device_fol... | StarcoderdataPython |
39387 | from push_notifications import models
from rest_framework.serializers import HyperlinkedModelSerializer
class APNSDevice(HyperlinkedModelSerializer):
class Meta:
fields = ('url', 'registration_id', 'name', 'device_id', 'active')
model = models.APNSDevice
class APNSDeviceUpdate(APNSDevice):
c... | StarcoderdataPython |
1783490 | <gh_stars>0
import os
from setuptools import setup
from torch.utils.cpp_extension import BuildExtension, CUDAExtension
os.environ["TORCH_CUDA_ARCH_LIST"] = "3.7+PTX;5.0;6.0;6.1;6.2;7.0;7.5"
setup(
name='HAIS_OP',
ext_modules=[
CUDAExtension('HAIS_OP', [
'src/hais_ops_api.cpp',
... | StarcoderdataPython |
1620133 | from .state import State, View
from .crypto import LocalParams, PublicParams
| StarcoderdataPython |
4825019 | <filename>gym_pcgrl/envs/probs/zelda_orderless_prob.py
import os
import numpy as np
from PIL import Image
from gym_pcgrl.envs.probs.problem import Problem
from gym_pcgrl.envs.helper import get_range_reward, get_tile_locations, calc_num_regions, calc_certain_tile, run_dikjstra
import random
TILES_MAP = {"g": "door",
... | StarcoderdataPython |
1695452 | from ..route_handler import BaseModelRouter
from ..serializers.model_serializer import ModelSerializer
from .dragon_test_case import DragonTestCase
from swampdragon.tests.models import TwoFieldModel
class Serializer(ModelSerializer):
class Meta:
model = TwoFieldModel
class Router(BaseModelRouter):
m... | StarcoderdataPython |
3220370 | <reponame>lexicalunit/spellbot
from __future__ import annotations
from datetime import datetime
from os import getenv
from typing import Generic, Type, TypeVar
from .environment import running_in_pytest
T = TypeVar("T", bound="Singleton")
class Singleton(Generic[T], type):
_instances: dict[Type[T], T] = {}
... | StarcoderdataPython |
4811584 | """
ReLU Activation function
@author: <NAME>
"""
import numpy as np
from lib.activations.activation import Activation
class ReLU(Activation):
"""
Class implementing the Rectified Linear Unit activation function
"""
def __init__(self):
"""
Initializer of the relu object
"""
... | StarcoderdataPython |
191300 | from AnyQt.QtGui import QPalette
from AnyQt.QtCore import Qt
import pyqtgraph as pg
pg.setConfigOption("background", "w")
pg.setConfigOption("foreground", "k")
pg.setConfigOptions(antialias=True)
def create_palette(colors):
p = QPalette()
for role, color in colors.items():
p.setColor(role, color)
... | StarcoderdataPython |
1773586 | <reponame>hubaimaster/aws-interface
from cloud.permission import Permission, NeedPermission
from cloud.auth._constant import LOGIN_METHODS
from cloud.message import error
# Define the input output format of the function.
# This information is used when creating the *SDK*.
info = {
'input_format': {
'login... | StarcoderdataPython |
25265 |
'''
@brief this class reflect action decision regarding condition
'''
class EventAction():
'''
@brief build event action
@param cond the conditions to perform the action
@param to the target state if any
@param job the job to do if any
'''
def __init__(self, cond="", to=... | StarcoderdataPython |
3398477 | #!/usr/bin/env python
# Test remapping of topic name for incoming message
import socket
import inspect, os, sys
# From http://stackoverflow.com/questions/279237/python-import-a-module-from-a-folder
cmd_subfolder = os.path.realpath(os.path.abspath(os.path.join(os.path.split(inspect.getfile( inspect.currentframe() ))[... | StarcoderdataPython |
3343189 | from z3 import *
from . import *
from .enum import *
from .axioms import *
from .utils import *
class Table(object):
Type = Enum(["INT","STRING","REAL","BOOL"])
def __init__(self, name):
super(Table, self).__init__()
self.name = name
# key: attribute name
# value: z3 type
... | StarcoderdataPython |
78826 | # (c) 2018, NetApp, Inc
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
''' unit test template for ONTAP Ansible module '''
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import json
import pytest
from ansible.module_utils import ... | StarcoderdataPython |
1691721 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import datetime
import mock
import pytest
from pyramid import security
from pyramid.authorization import ACLAuthorizationPolicy
from zope.interface import implementer
from h.formatters.interfaces import IAnnotationFormatter
from h.presenters.annotatio... | StarcoderdataPython |
1739152 | <reponame>wx-b/imitation-learning
from logging import ERROR
import d4rl_pybullet
import gym
import numpy as np
import torch
from training import TransitionDataset
gym.logger.set_level(ERROR) # Ignore warnings from Gym logger
D4RL_ENV_NAMES = ['ant-bullet-medium-v0', 'halfcheetah-bullet-medium-v0', 'hopper-bullet-m... | StarcoderdataPython |
1739431 | <gh_stars>0
"""
This test is for testing the NanGuardMode.
"""
from __future__ import absolute_import, print_function, division
import logging
from nose.tools import assert_raises
import numpy as np
from theano.compile.nanguardmode import NanGuardMode
import theano
import theano.tensor as T
def test_NanGuardMode()... | StarcoderdataPython |
41074 | <gh_stars>0
#!/usr/bin/python3
def safe_print_list_integers(my_list=[], x=0):
i = 0
for index in range(x):
try:
print("{:d}".format(my_list[index]), end="")
i += 1
except (ValueError, TypeError):
pass
print()
return i
| StarcoderdataPython |
58431 | # -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition) available.
Copyright (C) 2017-2018 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in co... | StarcoderdataPython |
4817971 | # SPDX-License-Identifier: Apache-2.0
# Licensed to the Ed-Fi Alliance under one or more agreements.
# The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0.
# See the LICENSE and NOTICES files in the project root for more information.
from locust import task
from edfi_performance.api.cl... | StarcoderdataPython |
3392521 | """
Main experiment script
Author: <EMAIL>
"""
from chemist_opt.chemist import optimize_chemist
from mols.funcs import SAScore as mol_func
from chemist_opt.domains import MolDomain
from chemist_opt.function_caller import FunctionCaller
from chemist_opt.worker_manager import SyntheticWorkerManager
from chemist_opt.ut... | StarcoderdataPython |
108592 | <reponame>lvyufeng/keras_text_sum
from bs4 import BeautifulSoup
import jieba
def load_text(path):
f = open(path)
soup = BeautifulSoup(f,'lxml')
f.close()
summary = soup.select('doc > summary')
short_text = soup.select('doc > short_text')
summary = [i.text.strip('\n').strip() for i in summary]... | StarcoderdataPython |
78037 | <filename>src/detector/transforms.py<gh_stars>10-100
from __future__ import division
import numpy as np
import random
import six
from chainercv import utils
def random_distort(
img,
brightness_delta=32,
contrast_low=0.5, contrast_high=1.5,
saturation_low=0.5, saturation_high=1.5,
... | StarcoderdataPython |
140769 | #!/usr/bin/python
#coding: utf-8
class Subject(object):
def __init__(self):
self._observers = []
def attach(self, observer):
if not observer in self._observers:
self._observers.append(observer)
def detach(self, observer):
try:
self._observers.remove(observer)
except ValueError:
pass
def notify(sel... | StarcoderdataPython |
3388430 | """
Description:
Given the head of a singly linked list, return the middle node of the linked list.
If there are two middle nodes, return the second middle node.
Example 1:
----------
Input: head = [1,2,3,4,5]
Output: [3,4,5]
Explanation: The middle node of the list is node 3.
Example 2:
----------
Input: head ... | StarcoderdataPython |
76564 | import click
from ghutil.types import Repository
@click.command()
@Repository.argument('repo')
@click.pass_obj
def cli(gh, repo):
""" List releases for a repository """
for rel in repo.releases.get():
click.echo(str(gh.release(rel)))
| StarcoderdataPython |
3218220 | # -*- coding: utf-8 -*-
from __future__ import print_function
from utils import *
import os
import json
import shutil
import time
import uuid
import yaml
def build_image(path_sample, config):
global log
service_name = config["service_name"]
image_name = config["image_name"]
tag_name = config["tag_nam... | StarcoderdataPython |
85852 | from django.db import models
from core.models import NanoIdModel, TimeStampModel
from .managers import PublishedManager
class Tag(NanoIdModel):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
class Link(NanoIdModel, TimeStampModel):
title = models.CharField(max_leng... | StarcoderdataPython |
3377289 | <reponame>geoadmin/service-stac
# pylint: disable=too-many-lines
import logging
from collections import OrderedDict
from datetime import datetime
from datetime import timedelta
from pprint import pformat
from django.conf import settings
from rest_framework.exceptions import ValidationError
from rest_framework.render... | StarcoderdataPython |
4828488 | from django.utils.translation import ugettext_lazy as _
from event_log import registry
registry.register(
name='labour.signup.created',
message=_('{entry.person} signed up for volunteer work in {entry.event}'),
email_body_template='labour_signup_created.eml',
)
registry.register(
name='labour.signu... | StarcoderdataPython |
3216621 | <reponame>ckochenower/indy-node
import argparse
import json
import multiprocessing
import time
import asyncio
from multiprocessing import Process
import os
import functools
import sys
from indy import pool
count_of_connected = 0
count_of_not_connected = 0
def run_client(genesis_path, pipe_conn, client_number):
... | StarcoderdataPython |
3209310 | from __future__ import print_function
import numpy as np
def generate_mult_function_batch_compile(k_list, l_list, m_list, mult_table_vals, n_dims,
product_name, product_mask=None, cuda=False):
"""
Takes a given product and generates the code for a function that evaluate... | StarcoderdataPython |
106881 | <gh_stars>100-1000
"""
Fragments of user mutations
"""
AUTH_PAYLOAD_FRAGMENT = '''
id
token
user {
id
}
'''
USER_FRAGMENT = '''
id
'''
| StarcoderdataPython |
1664853 | from .flags import SoapyFlags, SoapyError
from .rx import Receiver
| StarcoderdataPython |
15947 | <gh_stars>0
import json
import os
import cv2
import imutils
import numpy as np
import torch
import torchvision.transforms.functional as tvf
from PIL import Image
from models.rapid import RAPiD
from tracker.deep_sort import DeepSort
from utils import utils
weights_path = "weights/pL1_HBCP608_Apr14_6000.ckpt"
model = ... | StarcoderdataPython |
3267437 | <filename>gnosis/xml/pickle/test/test_bools_ro.py
# read-only version of bool test.
# show that bools are converted to the "best" value, depending
# on Python version being used. --fpm
import gnosis.xml.pickle as xmp
from gnosis.xml.pickle.util import setVerbose, setParser, setParanoia
from funcs import set_parser, u... | StarcoderdataPython |
4808594 | <gh_stars>1-10
"""Deprecated code."""
import functools
import inspect
import os
from enum import Enum
from typing import Any, Dict, Set
from .namespace import Namespace
from .optionals import get_config_read_mode, set_config_read_mode
from .typehints import ActionTypeHint
from .typing import path_type, restricted_numb... | StarcoderdataPython |
138212 | # Copyright (c) Shopkick 2017
# See LICENSE for details.
"""
Seashore
=======
Seashore is a collection of shell abstractions.
"""
from seashore.executor import Executor, NO_VALUE, Eq
from seashore.shell import Shell, ProcessError
from seashore._version import __version__
__all__ = ['Executor', 'NO_VALUE', 'Eq', 'Shel... | StarcoderdataPython |
3359557 | <filename>WebParser.py<gh_stars>1-10
from bs4 import BeautifulSoup
from bs4.element import Comment
import requests
import urllib.request
from googlesearch import search
# tag_visible() and text_from_html() taken from:
# https://stackoverflow.com/questions/1936466/beautifulsoup-grab-visible-webpage-text
class WebScrap... | StarcoderdataPython |
4842281 | <reponame>carol-hsu/relay-bench
from validate_config import validate
from exp_templates import analysis_template
def generate_listing_settings(config):
passes = [';'.join([str(pass_spec[0]), '|'.join(pass_spec[1])])
for pass_spec in config['passes']]
return {pass_str: {'pass': pass_str} for pass_... | StarcoderdataPython |
194542 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Ported from:
# https://github.com/adafruit/Adafruit_Python_SSD1306/blob/master/examples/shapes.py
import sys
import time
from PIL import Image, ImageDraw
from demo_opts import device
import demo
class Timer:
def __enter__(self):
self.start = time.clock()
... | StarcoderdataPython |
3370064 | <reponame>samgdotson/pyrk
from nose.tools import assert_equal, assert_raises
from pyrk.inp import validation as v
from pyrk.utilities.ur import units
def test_ge_wrong_type():
val = "ten"
valname = "testval"
llim = 0
assert_raises(TypeError, v.validate_ge, valname, val, llim)
def test_ge_Quantity_t... | StarcoderdataPython |
1654520 | <filename>tests/run/test_make_tfrecord.py<gh_stars>1-10
import os
import tempfile
from speech_recognition.run.make_tfrecord import main, parser
from ..const import DEFAULT_LIBRI_CONFIG, SP_MODEL_LIBRI, WAV_DATASET_PATH
def test_make_tfrecord():
with tempfile.TemporaryDirectory() as tmpdir:
args = [
... | StarcoderdataPython |
87833 | from autokeras.nn.generator import *
from autokeras.nn.graph import TorchModel
def test_default_generator():
generator = CnnGenerator(3, (28, 28, 1))
graph = generator.generate()
model = graph.produce_model()
assert isinstance(model, TorchModel)
| StarcoderdataPython |
4825308 | <gh_stars>1-10
# [h] convert otfs to ufos
import hTools2.dialogs.folder.otf2ufo
import importlib
importlib.reload(hTools2.dialogs.folder.otf2ufo)
hTools2.dialogs.folder.otf2ufo.OTFsToUFOsDialog()
| StarcoderdataPython |
3345655 | from dagster_graphql.client.mutations import (
execute_execute_plan_mutation,
execute_execute_plan_mutation_raw,
)
from dagster import file_relative_path
from dagster.cli.workspace.cli_target import PythonFileTarget, workspace_from_load_target
from dagster.core.definitions.reconstructable import (
Reconstr... | StarcoderdataPython |
175412 | from webdnn.graph.operator import Operator
from webdnn.graph.order import OrderNHWC
from webdnn.graph.variable import Variable
def test_append_input():
op = Operator("op")
v1 = Variable((1, 2, 3, 4), OrderNHWC)
v2 = Variable((1, 2, 3, 4), OrderNHWC)
op.append_input("v1", v1)
op.append_input("v2",... | StarcoderdataPython |
1704895 | # encoding: utf-8
from __future__ import division, print_function, unicode_literals
###########################################################################################################
#
#
# Reporter Plugin
#
# Read the docs:
# https://github.com/schriftgestalt/GlyphsSDK/tree/master/Python%20Templates/Reporter
... | StarcoderdataPython |
149694 | <reponame>jitsuin-inc/archivist-samples
# Copyright 2019 Jitsuin, 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... | StarcoderdataPython |
3381254 | <reponame>firefly-cpp/simframe<gh_stars>0
# Tests for the Instruction class
import pytest
from simframe import Frame
from simframe import Instruction
from simframe import schemes
from simframe.frame import Field
def test_instruction_no_field():
with pytest.raises(TypeError):
i = Instruction(schemes.expl... | StarcoderdataPython |
1798933 | <reponame>josh95117/freetype-py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
#
# FreeType high-level python API - Copyright 2011-2015 <NAME>
# Distributed under the terms of the new BSD license.
#
# --------------------------------------... | StarcoderdataPython |
28390 | <filename>src/models/predict_model.py
import argparse
import sys
from pathlib import Path
import matplotlib.pyplot as plt
import torch
import torchvision.transforms as transforms
from model import ResNet
from PIL import Image
if __name__ == '__main__':
# Arguments
parser = argparse.ArgumentParser(description=... | StarcoderdataPython |
76840 | <reponame>RonnieGandhi/OLIVIA<filename>APIs/Speech-to-Text/test.py
import requests
from scipy.io.wavfile import read,write
import io
import json
import numpy as np
base="http://127.0.0.1:5000/"
payload={'file':open('test.wav','rb')}
r = requests.post(base, files=payload)
print(json.loads(r.text)['text'][0]) | StarcoderdataPython |
3385793 | <gh_stars>1-10
# from pypadre.core.model.code.code_file import CodeFile
#
#
# class PythonFile(CodeFile):
#
# def __init__(self, **kwargs):
# # TODO Add defaults
# defaults = {}
#
# # TODO overwrite with imports?
# # TODO Constants into ontology stuff
# # Merge defaults TODO ... | StarcoderdataPython |
3253075 | <filename>main.py
import csv
import os
import filecmp
import shutil
from pathlib import Path
def parse_csvs(path, dstPath):
collections = {}
collection_images = {}
adobe_images = {}
library_files = {}
library_folders = {}
library_roots = {}
with open(csvPath + 'AgLibraryCollection.csv', ne... | StarcoderdataPython |
3218327 | <filename>reptools/call_genes_utils.py
import os
import tempfile
import shutil
import reptools
def tiebreak(result1,result2,tiebreaker):
tiebreaker_values = [
getattr(result1[0].hsps[0],tiebreaker[0]),
getattr(result2[0].hsps[0],tiebreaker[0])
... | StarcoderdataPython |
1719892 | # get_driver scope='module'
def test_header_logo(get_driver):
assert get_driver.find_elements_by_xpath('//a[text()="Your Store"]')
def test_main_slider(get_driver):
assert get_driver.find_element_by_css_selector('.swiper-viewport #slideshow0')
def test_navbar(get_driver):
assert get_driver.find_element... | StarcoderdataPython |
20667 | <reponame>zhangdan0602/cogdl
from abc import abstractmethod
import argparse
import copy
import numpy as np
import torch
from tqdm import tqdm
from cogdl.data import Dataset
from cogdl.data.sampler import (
SAINTSampler,
NeighborSampler,
ClusteredLoader,
)
from cogdl.models.supervised_model import Supervis... | StarcoderdataPython |
4835870 | <gh_stars>0
#!/usr/bin/env python
import rospy
import std_msgs.msg
from geometry_msgs.msg import Twist, TwistStamped
#from std_msgs.msg import Header, TwistStamped
def simple_controller():
pub = rospy.Publisher('/command/twist', TwistStamped, queue_size=10)
rospy.init_node('simple_controller', anonymous=True)... | StarcoderdataPython |
4832106 | """The tests for the Xiaomi ble_parser."""
from ble_monitor.ble_parser import BleParser
class TestXiaomi:
def test_Xiaomi_LYWSDCGQ(self):
"""Test Xiaomi parser for LYWSDCGQ."""
data_string = "043e2502010000219335342d5819020106151695fe5020aa01da219335342d580d1004fe004802c4"
data = bytes(by... | StarcoderdataPython |
6115 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import random
import numpy as np
# Generic data augmentation
class Augmenter:
""" Generic data augmentation class with chained operations
"""
def __init__(self, ops=[]):
if not isinstance(ops, list):
print("Error: ops must be a list of fu... | StarcoderdataPython |
1616901 | import logging
from cle.backends import Backend, Symbol, Segment, SymbolType
from cle.backends.relocation import Relocation
from cle.utils import ALIGN_UP
from cle.errors import CLEOperationError, CLEError
from cle.address_translator import AT
l = logging.getLogger(name=__name__)
class ExternSegment(Segment):
de... | StarcoderdataPython |
4825637 | import re
data = []
with open('pinyin.txt') as f:
for index, i in enumerate(f):
if index < 2:
continue
unicode, character = re.match(r'U\+(.+):.*#\s+(.+)', i).groups()
data.append((unicode, character))
data_int = sorted((ord(j), j) for i, j in data)
pattern = ['[^'] + [data[0][1]... | StarcoderdataPython |
3307265 | <filename>package/tool-bazel-0.4.5-universal/custom.py
#
# Collective Knowledge workflow framework
#
# Developer: <NAME>, <EMAIL>, http://fursin.net
#
##############################################################################
# customize installation (via redirect)
def setup(i):
ck=i['ck_kernel']
# Find ... | StarcoderdataPython |
1718339 | <filename>featuretools_tsfresh_primitives/primitives/longest_strike_below_mean.py<gh_stars>1-10
from featuretools.primitives import AggregationPrimitive
from tsfresh.feature_extraction.feature_calculators import longest_strike_below_mean
from woodwork.column_schema import ColumnSchema
from woodwork.logical_types import... | StarcoderdataPython |
1797995 | <gh_stars>0
#Create Dependencies
import numpy as np
import datetime as dt
#Create Python SQL Toolkit and Object Relational Mapper
import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, func
from sqlalchemy import inspect
#Import F... | StarcoderdataPython |
4839255 |
import torch
from tqdm import tqdm
from transformers import AutoTokenizer, AutoModel
import logging
from torch.nn import ConstantPad3d, ConstantPad2d
from layers.utils import set_model_device, set_tensor_device
'''
tutorial4 tokenization
https://mccormickml.com/2019/07/22/BERT-fine-tuning/
how to use clinical ... | StarcoderdataPython |
1364 | <reponame>jmb/NightLightPi
# -*- coding: utf-8; -*-
"""Define error strings raised by the application."""
MISSING_CONFIG_VALUE = """
'{0}' is not specified or invalid in the config file!
""".strip()
| StarcoderdataPython |
103248 | import uuid
from sqlalchemy import Column, String, func, Index, ForeignKey
from sqlalchemy_utils import ArrowType, UUIDType
from registry.sql.database import Base
class Module(Base):
__tablename__ = 'modules'
id = Column(UUIDType, primary_key=True, default=uuid.uuid4)
organization_id = Column(UUIDType,... | StarcoderdataPython |
6369 | <reponame>vprnet/school-closings
#!/usr/local/bin/python2.7
from flask import Flask
import sys
from flask_frozen import Freezer
from upload_s3 import set_metadata
from config import AWS_DIRECTORY
app = Flask(__name__)
app.config.from_object('config')
from views import *
# Serving from s3 leads to some complications... | StarcoderdataPython |
1709527 | """Kea Control Channel - socket"""
# pylint: disable=invalid-name,line-too-long
import pytest
import misc
import srv_msg
import srv_control
from forge_cfg import world
def _send_cmd(cmd, extra_param=None, exp_result=0):
cmd = dict(command=cmd, arguments={})
if isinstance(extra_param, dict):
cmd["ar... | StarcoderdataPython |
1732550 | <filename>exec.py<gh_stars>1-10
"""
Training and testing routines.
<NAME>
Copyright 2021 <NAME> (<EMAIL>)
Please, email me if you have any question.
Disclaimer:
The software is provided "as is", without warranty of any kind, express or
implied, including but not limited to the warranties o... | StarcoderdataPython |
4830402 | <gh_stars>0
"""
Support for VOC.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/binary_sensor.volvooncall/
"""
import logging
from homeassistant.components.volvooncall import VolvoEntity
from homeassistant.components.binary_sensor import BinarySensorDe... | StarcoderdataPython |
1605681 | from dataclasses import dataclass
from typing import Any, List
@dataclass
class TaskUnit:
request: Any
def run(self, extractor):
yield extractor.run(self)
@dataclass
class MultiTaskUnit(TaskUnit):
request: Any
def run(self, extractor):
return extractor.run_multiple(self)
@dataclass... | StarcoderdataPython |
3223777 | <filename>sirepo/template/srw_common.py
# -*- coding: utf-8 -*-
u"""SRW simulation_db/template/sim_data independent routines
:copyright: Copyright (c) 2019 RadiaSoft LLC. All Rights Reserved.
:license: http://www.apache.org/licenses/LICENSE-2.0.html
"""
from __future__ import absolute_import, division, print_function... | StarcoderdataPython |
47610 | <reponame>quentin-xia/Maticv
#/usr/bin/env python
#-*- coding:utf-8 -*-
import math,os
import numpy as np
from adb import Adb
from screencap import MinicapStream
import tempfile
import hashlib
import gl
import platform
if platform.system() is "Windows":
try:
import maticv.common.opencv.x32.cv2 as cv2
ex... | StarcoderdataPython |
3276407 | import os # used to get the location of the testdata
import pytest
def test_helptext_direct(script_runner):
ret = script_runner.run('geoextent', '--help')
assert ret.success, "process should return success"
assert ret.stderr == '', "stderr should be empty"
assert "geoextent [-h]" in ret.stdo... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.