id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
1794620 | from __future__ import print_function
from classes import What
def hello():
return('hello what')
def whattest():
what = What()
return what.nameit()
| StarcoderdataPython |
1650925 | import numpy as np
from scipy.misc import imresize
import gym
from gym.core import ObservationWrapper, Wrapper
from gym.spaces.box import Box
from gym.wrappers import SkipWrapper, TimeLimit
from copy import copy
import collections
try:
import ppaquette_gym_doom
from ppaquette_gym_doom.wrappers.action_space imp... | StarcoderdataPython |
1747463 | # -*- coding: utf-8 -*-
"""
Project Index -- prepares an index of WikiProjects and their in-scope pages for use by scripts
Copyright (C) 2015 <NAME>, 2016 <NAME>
Licensed under MIT License: http://mitlicense.org
"""
from collections import namedtuple
import re
from BTrees.IIBTree import IIBTree
from oursql import Pr... | StarcoderdataPython |
98801 | <gh_stars>0
from collections import namedtuple
TaskMeta = namedtuple("TaskMeta", ["task_token", "run_id", "workflow_id", "domain", "tasklist"])
| StarcoderdataPython |
3329640 | import random
from .Bot import Bot
class BogoBot(Bot):
title = "Random Bot"
"""
This bot moves at random
"""
def __init__(self, player):
Bot.__init__(self, player, "BogoBot")
self.player_type = 'rng bot'
random.seed()
def compute_next_move(self, board, valid_moves):
... | StarcoderdataPython |
16278 | <reponame>saransh09/openfl-1<filename>openfl/component/ca/ca.py<gh_stars>0
# Copyright (C) 2020-2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
"""Aggregator module."""
import base64
import json
import os
import platform
import shutil
import signal
import subprocess
import time
import urllib.request
from... | StarcoderdataPython |
1785373 | <filename>scripts/quest/q20837s.py
# Created by MechAviv
# Quest ID :: 20837
# Lesson 5 - Skills
sm.setSpeakerID(1102102)
sm.removeEscapeButton()
sm.sendNext("Try attacking a monster using your skills! Drag them to a hotkey to make them more convenient!")
sm.setSpeakerID(1102102)
sm.removeEscapeButton()
sm.sendSay("... | StarcoderdataPython |
3388265 | <filename>friendly-telegram/configurator.py
# -*- coding: future_fstrings -*-
import locale, time, os, inspect, ast
from dialog import Dialog, ExecutableNotFound
from . import loader, utils, main
class TDialog():
OK=0
NOT_OK=1
# Similar interface to pythondialog
def menu(self, title, choices):
... | StarcoderdataPython |
1697756 | <reponame>GuoSuiming/mindspore
# Copyright 2020 Huawei Technologies Co., Ltd
#
# 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 |
3297981 | <filename>test/test_add_axis.py<gh_stars>1-10
import pytest
import numpy as np
from Animate.Movie import Movie
def test_axis():
with pytest.raises(ValueError) as ex:
m = Movie()
m.add_axis(x_label='x', y_label='y', tight_x='1')
assert 'tight_x should be a boolean' in str(ex.value)
m = Mov... | StarcoderdataPython |
3318716 | <filename>src/constants.py
round_1_matchups = [
("Gonzaga", "Georgia St"),
("Boise St", "Memphis"),
("Connecticut", "New Mexico St"),
("Arkansas", "Vermont"),
("Alabama", "<NAME>"),
("Texas Tech", "Montana St"),
("Michigan St", "Davidson"),
("Duke", "<NAME>"),
("Baylor", "Norfolk St"... | StarcoderdataPython |
3257127 | <gh_stars>10-100
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.test import TestCase
import pytz
import datetime
from app.tests.mixins import Pep8ModelTests, ModelCrudTests
from app.models import Analytics
class AnalyticsModelTests(TestCase, Pep8ModelTests, ModelCrudTests):
def setU... | StarcoderdataPython |
49877 | import re
import platform
import os
import time
import json
import datetime
from .website import websiteText
from .UpdateJson import UpdateJsonLanguage
def EnglishFunction(Balthazar, text, languages):
websiteText(Balthazar, text, languages)
if "hello" in text:
Balthazar.speak("hello, how are you?", la... | StarcoderdataPython |
3274370 | """Varous helper functions that do not require a route."""
import random
import string
import json
import re
from flask import make_response
from sqlalchemy.orm.exc import NoResultFound
from .pmoi_db_session import db_session
from .database_setup import User, Category
FORBIDDEN_USER = ['static', 'user', 'admin', 'ad... | StarcoderdataPython |
3220088 | <gh_stars>0
from datetime import timedelta
from django.utils.translation import ugettext_lazy as _
from mayan.apps.common.queues import queue_tools
from mayan.apps.task_manager.classes import CeleryQueue
from mayan.apps.task_manager.workers import worker_fast, worker_medium
from celery.schedules import crontab
from... | StarcoderdataPython |
154230 | from moduls import *
from oredictnames import *
from Inventorys import *
import Item
import crafting as cb
import config
from Inventorys import *
from Inventorys.Inventory import Slot, handler as invhandler, InventoryHandler
import EventHandler
import entity
class player:
def __init__(self, window):
... | StarcoderdataPython |
4817336 | <gh_stars>0
# Generated by Django 3.1.4 on 2020-12-14 03:17
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('movies', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='movie',
name='metascore',
... | StarcoderdataPython |
1721320 | <reponame>blackAllSun/JeuxDeCourseAutomobile<gh_stars>0
# coding=UTF-8
from Statut import *
from Voiture import *
class Pilote(object):
"""
:version:1.0
:author:BlackAllSun
"""
""" ATTRIBUTES
idPilote (private)
nom (private)
prenom (private)
age (private)
statut (private)
voiture (private)
""... | StarcoderdataPython |
105935 | import numpy as np
def trans():
print("Transpose of matrix:")
#Enter rows and columns
row=int(input("Enter number of rows:"))
column=int(input("Enter number of columns:"))
print("Enter the elements of Matrix:")
matrix_a= [[int(input()) for i in range(column)] for i in range(row)]
print("Matrix is: ")
f... | StarcoderdataPython |
3210575 | <filename>src/dbvd.py<gh_stars>0
import xlwt
import re
from structure import TABLE, COLUMN, DRIVER
class ReTableDriver(DRIVER):
def parse(self, s):
comment, table_name, columns, engine, charset = "", "None", [], "Default", "Default"
primary_keys, foreign_keys, index_keys, unique_keys = [], [], [],... | StarcoderdataPython |
3378111 | <reponame>mouton5000/DiscreteEventApplicationEditor
__author__ = 'mouton'
import pygame
from database import Event
import game.Registeries.SoundRegistery as soundReg
import game.Registeries.SpriteRegistery as spriteReg
import game.Registeries.TextRegistery as textReg
import game.Registeries.LineRegistery as lineReg
i... | StarcoderdataPython |
182517 | <reponame>bricksflow/datalake-bundle<filename>src/datalakebundle/table/parameters/ValueResolverFactory.py
from injecta.module import attribute_loader
from injecta.service.parser.DTypeResolver import DTypeResolver
from datalakebundle.table.identifier.ValueResolverInterface import ValueResolverInterface
class ValueReso... | StarcoderdataPython |
96950 | import numpy as np
from sklearn.svm import SVC
import matplotlib.pyplot as plt
from sklearnclassifiers.ClassifierBase import ClassifierBase
import logging
logger = logging.getLogger(__name__)
class SupportVectorMachine(ClassifierBase):
def __init__(self, datasetloader,save_image=False):
super(self.__clas... | StarcoderdataPython |
1782928 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Base class to create prop rigs
"""
from __future__ import print_function, division, absolute_import
__author__ = "<NAME>"
__license__ = "MIT"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
import os
import sys
import json
import math
from . import control
from . ... | StarcoderdataPython |
1788158 | import re
from tweepy import Status
from updatesproducer.updateapi.update import Update
from twitterproducer.updateapi.media_factory import MediaFactory
TWITTER_BASE_URL = 'https://www.twitter.com'
class UpdateFactory:
@staticmethod
def to_update(tweet: Status):
user_id = tweet.user.screen_name
... | StarcoderdataPython |
187585 | #!/usr/bin/env python3
# Requirements:
# pip3 install pillow
"""
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-com... | StarcoderdataPython |
141112 | import json
import sys
import fileinput
data = dict()
def read_out_experiment(experiment):
global data
with open(experiment) as json_file:
data = json.load(json_file)
# print(data)
def node_id_to_hostname(hostname=None):
if hostname is None:
raise Exception('Given hostname is None... | StarcoderdataPython |
3267822 | <reponame>StopPointTeam/APF-RRT
import socket
import sys
import time
from zss_cmd_pb2 import Robots_Command, Robot_Command
class Action(object):
def __init__(self):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.command_address = ('localhost', 50001)
def sendCommand(self, ... | StarcoderdataPython |
107821 | <gh_stars>0
# Message Sender
import os
from socket import *
import socketserver
# import terminalv2 as tml
import logging
import json
from threading import local
from art import *
from tqdm import tqdm, trange
from time import sleep
from colorama import Fore, Back, Style,init
from termcolor import colored
import os
# ... | StarcoderdataPython |
1605743 | import importlib
import sys
def lazy_import(name):
"""
Allows you to lazily import a module.
Usage:
>>> asb = lazy_import("aerosandbox") # Runs instantly
>>> asb.Airplane() # When this is called, ASB will be loaded.
Args:
name: The package name
Returns: The module itself, to be... | StarcoderdataPython |
1730734 | <reponame>TanZng/mysite<filename>hello/urls.py
from django.urls import path
from . import views
from django.views.generic import TemplateView
app_name='hello'
urlpatterns = [
path('', views.sessfun),
] | StarcoderdataPython |
188889 | from typing import Dict, List
class Solution:
# s1: DFS TLE
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
if len(set(s)) > len(set(''.join(wordDict))):
return False
set_words = set(wordDict)
r = self.helper(s, set_words)
return r
def helper(self, s, ... | StarcoderdataPython |
150025 | <filename>misc/arg_handler.py
import argparse
from pipeline import backtest
from pipeline.backtest import TestStrategy
from pipeline.strategies.ff_strat import FeedforwardStrategy
from scripts import feedforward_nn, recurrent_lstm, ConvNet
from scripts import data_process as dp
from misc.graph import graph
def arg_pa... | StarcoderdataPython |
193477 | import zlib
from hazelcast.serialization import (
BYTE_SIZE_IN_BYTES,
CHAR_SIZE_IN_BYTES,
BE_UINT16,
DOUBLE_SIZE_IN_BYTES,
BE_DOUBLE,
INT_SIZE_IN_BYTES,
BE_INT,
LONG_SIZE_IN_BYTES,
BE_LONG,
BE_UINT8,
)
_MASK_PREFIX = 1
_MASK_METRIC = 1 << 1
_MASK_DISCRIMINATOR = 1 << 2
_MASK_DI... | StarcoderdataPython |
4830989 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# see http://stackoverflow.com/questions/4931376/generating-matplotlib-graphs-without-a-running-x-server
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
def plot_recall_precision_curve(recall_precision_pairs,
title = 'Precision-Recall curve (1... | StarcoderdataPython |
3386935 | from typing import Any, Optional
from fastapi import HTTPException, status
bad_credentials = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
invalid_credentials = HTTPException(
status_code=status.HTTP_401_UNAU... | StarcoderdataPython |
99006 | <filename>ezusbfifo/__init__.py
from ezusbfifo.actor import USBActor
from ezusbfifo.async import AsyncUSBActor
from ezusbfifo.sim import SimUSBActor
| StarcoderdataPython |
3313430 | <reponame>Durburz/eMonitor
def getFrontendContent(self, params={}):
return ""
def getFrontendData(self):
return "" | StarcoderdataPython |
1783653 | <reponame>praekeltfoundation/ge-messaging-consent
from .base import * # noqa
from .base import env
DEBUG = False
# Raises ImproperlyConfigured exception if SECRET_KEY not in os.environ
SECRET_KEY = env.str("SECRET_KEY")
ALLOWED_HOSTS = env.str("ALLOWED_HOSTS").split(",")
# Configure Sentry Logging
INSTALLED_APPS +... | StarcoderdataPython |
1714559 | """Abstract definition of database connections"""
import functools
import pathlib
@functools.lru_cache(maxsize=None)
def db(alias):
"""Returns a database configuration by alias"""
from . import config
databases = config.databases()
if alias not in databases:
raise KeyError(f'database alias "{... | StarcoderdataPython |
1639808 | from imports import *
from tools import bot_utils
class Tracker:
def __init__(self, bot):
self.bot = bot
self.antispam = []
async def antiSpam(self, user):
await asyncio.sleep(30)
self.antispam.remove(user)
async def on_message(self, message):
if message.author.bot... | StarcoderdataPython |
3245931 | #!/usr/bin/env python3
import unicornhat as uh
import time
from random import randrange
uh.brightness(0.1)
uh.rotation(270)
while True:
r = randrange(200, 255, 1)
b = randrange(0, 200, 1)
x = (r, 0, b)
o = (0, 0, 0)
heart = [
[o,o,o,o,o,o,o,o],
[o,x,x,o,o,x,x,o],
[x,x,x,... | StarcoderdataPython |
8983 | <reponame>chen88358323/HanLP
# -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-12-28 21:12
from hanlp_common.constant import HANLP_URL
SIGHAN2005_PKU_CONVSEG = HANLP_URL + 'tok/sighan2005-pku-convseg_20200110_153722.zip'
'Conv model (:cite:`wang-xu-2017-convolutional`) trained on sighan2005 pku dataset.'
SIGHAN2005... | StarcoderdataPython |
1652088 | import aws.entity.MetricAlarm
import aws.api.SNS
import aws.api.CloudWatch
import re
import itertools
class LogMetricFilter:
def __init__(self, logMetricFilterDict):
self.name = logMetricFilterDict['filterName']
self.filterPattern = logMetricFilterDict['filterPattern']
self.metricTransforma... | StarcoderdataPython |
189009 | """update evas alipay batchrefund record.
Revision ID: 499dbfdd807d
Revises: 2<PASSWORD>
Create Date: 2015-12-07 16:52:36.066491
"""
# revision identifiers, used by Alembic.
revision = '<KEY>'
down_revision = '2<PASSWORD>6748030'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column('eva... | StarcoderdataPython |
1706642 | <gh_stars>1-10
import uuid
import json
import yaml
import flask
import sqlite3
import os.path
import importlib
import AsModels
import IrModels
import VibModels
import IrAgent
import VibManager
import AsAuthAgent
'''
CLASS: OperationAgent
AUTHOR: <NAME>
CREATION: 05 Nov. 2020
L. UPDATE: 28 Jul. 20... | StarcoderdataPython |
1637754 | """This module is just functions to deal with different common pathname manipulations.
As Exarata is going to be cross platform, this is a nice abstraction."""
import os
import opihiexarata.library as library
import opihiexarata.library.error as error
import opihiexarata.library.hint as hint
def get_directory(pathn... | StarcoderdataPython |
3331401 | #!/usr/bin/env python3
class Solution(object):
def firstMissingPositive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums.append(0)
n = len(nums)
for i in range(len(nums)):
if nums[i] < 0 or nums[i] >= n:
nums[i] = 0
... | StarcoderdataPython |
35407 | from ..fuzzable import Fuzzable
class Simple(Fuzzable):
"""Simple bytes value with manually specified fuzz values only.
:type name: str, optional
:param name: Name, for referencing later. Names should always be provided, but if not, a default name will be given,
defaults to None
:type default... | StarcoderdataPython |
3316084 | import os
import sys
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
import pandas as pd
main_path = "" # write the path where the data from TrackMate is stored (.csv)
files = os.listdir(main_path)
track_id = 0
for f in files:
if f.__contains__(".csv"):
print(f)
file_data... | StarcoderdataPython |
3279882 | <gh_stars>0
import datetime
import pytest
from dynamo.entities import Session, itemToSession # pylint: disable=wrong-import-position
def test_default_init():
session = Session( '2020-01-01T00:00:00.000Z', '0.0.0.0', 0.1, 0.1 )
assert session.sessionStart == datetime.datetime( 2020, 1, 1, 0, 0 )
assert session.ip... | StarcoderdataPython |
193194 | <filename>adminmgr/media/code/python/map3/BD_830_1094_1439_2391_mapper.py
#!/usr/bin/python3
import sys
infile = sys.stdin
for line in infile:
line = line.strip()
my_list = line.split(',')
if my_list[0] != "info" and my_list[0] != "version":
bowl = my_list[6]
bat = my_list[4]
runs = my_list[7]
extras = my_l... | StarcoderdataPython |
1798663 | <reponame>kala51773/py
import json
import os
from pymongo import MongoClient
class tool:
def __init__(self):
self.file_list = os.listdir()
self.json_list = []
def merge(self):
db=self.connect()
for file in self.file_list:
if file.rfind("json")!=-1:
pr... | StarcoderdataPython |
3361447 | <reponame>saicharanabhishek/machinelearning_examples
"""
Functions to load the dataset.
"""
import numpy as np
def read_data(file_name):
"""This function is adapted from:
https://github.com/benhamner/BioResponse/blob/master/Benchmarks/csv_io.py
"""
f = open(file_name)
# skip header
f.readline... | StarcoderdataPython |
3284471 | from django.http import HttpRequest
from uuid import uuid4
class Middleware:
def __init__(self, get_response) -> None:
self.get_response = get_response
def __call__(self, request: HttpRequest):
if "player_id" not in request.session:
request.session["player_id"] = str(uui... | StarcoderdataPython |
3393041 | <reponame>alextongue/vaessl-doa<filename>vaessl_core.py
"""
Code implementing inference and generative models for semi-supervised
variational autoencoder (VAE-SSL) approach to source localization in reverberant
environments
The method implemented here is described in:
1. <NAME>, <NAME>, <NAME>, <NAME>, "Semi-supervis... | StarcoderdataPython |
3375707 | <reponame>Minipeps/openpose_train<filename>pig/fixScale.py
import json, math
datasetFolder = "../dataset/PigData/"
source = "annotations_final_v2.4.json"
output = "annotations_final_v2.5.json"
def getScale(keypoints):
''' return scale with respect to 200px '''
nose = keypoints[-2]
tail = keypoints[-1]
... | StarcoderdataPython |
150792 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 19 16:00:21 2019
@author: lucas
"""
import pandas as pd
import numpy as np
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes impor... | StarcoderdataPython |
183618 | <gh_stars>0
import random
def choose_pivot(nos):
i = random.randrange(0, len(nos))
pivo = nos[i]
return pivo
def get_min_weight_in_not_processed_adjacent_arrows(adjacencias):
menor_peso = None
for aresta, peso in adjacencias.items():
if menor_peso == None:
menor_peso = peso
... | StarcoderdataPython |
1681948 | from typing import Any, Dict
class MessageUtils:
@staticmethod
def deserialize_value(message: Any) -> Dict[str, Any]:
pass
@staticmethod
def __from_proto(message: Any) -> Any:
kafka_pb2 = KafkaMess | StarcoderdataPython |
1768275 | from os import getenv
class Config:
DEBUG = False
TESTING = False
USER = getenv('USER')
SECRET_KEY = getenv('SECRET_KEY')
DATABASE_NAME = getenv('DATABASE_NAME')
SQLALCHEMY_TRACK_MODIFICATIONS = False
SQLALCHEMY_DATABASE_URI = f'postgresql://{USER}:{SECRET_KEY}@localhost... | StarcoderdataPython |
161944 | '''
Notes on wordpress hero theme:
'''
BORDERSTYLE = "border:12px solid transparent;"
import argparse
import re
def parseHTML(html):
'''
Parse the smugmug link for the things we need. The return is
link, src, alt
'''
regex = '<a href="(\S+)"><img src="(\S+)".*alt="(.*)"></a>'
match = re.mat... | StarcoderdataPython |
3307034 | <gh_stars>0
from app.views.handlers.list_action import ListAction
class ListAddQuestion(ListAction):
def is_location_valid(self):
if not super().is_location_valid() or self._current_location.list_item_id:
return False
return True
def handle_post(self):
self.questionnaire_s... | StarcoderdataPython |
13873 | # Copyright 2020-2021 Canonical Ltd.
#
# 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 writi... | StarcoderdataPython |
192973 | <filename>tests/shared/test_event_stream.py<gh_stars>1-10
import pytest
from dataclasses import FrozenInstanceError
from bank_ddd_es_cqrs.shared.model import EventStream
def test_default_version_on_new_event_stream_is_minus_one():
event_stream = EventStream([])
assert event_stream.version == -1
def test_eve... | StarcoderdataPython |
3271861 | <filename>CompetitiveProgramming128/41SweepLine.py<gh_stars>0
# %%
# Sweep line technique
# Example -- Intersection of Intervals
# Given n intervals [i,ri) for i = 0, . . . ,n − 1, we wish to find a value x included
# in a maximum number of intervals. Here is a solution in time O(n log n).
import os
def max_interval... | StarcoderdataPython |
169303 | <filename>benchmark.py<gh_stars>10-100
import argparse
import configs
import os
from glob import glob
import data
from visualize import viz_files, viz_png_file
from skimage.io import imsave
import xgboost as xgb
from utils import get_model_feature_type
from utils import hr_name_to_models, hr_predict_single
files_to_... | StarcoderdataPython |
98399 | Version = "3.53.0"
| StarcoderdataPython |
104162 | import panel as pn
import param
import pandas as pd
import numpy as np
import holoviews as hv
from holoviews import streams
from holoviews import opts, dim
hv.extension('bokeh')
pn.extension()
class FlagChecker(param.Parameterized):
flag = param.ObjectSelector(default="UNCHECKED", objects=[
... | StarcoderdataPython |
127325 | <filename>sitecontent/migrations/0003_auto_20210520_1058.py
# Generated by Django 2.2.13 on 2021-05-20 07:58
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('sitecontent', '0002_ListViewAttributeColumn'),
]
operations = [
migrations.Crea... | StarcoderdataPython |
1721714 | import pytest
import tempfile
import subprocess
try:
import pymongo
from blitzdb.backends.mongo import Backend as MongoBackend
test_mongo = True
@pytest.fixture(scope="function")
def mongodb_backend(request):
return mongo_backend(request, {})
@pytest.fixture(scope="function")
def ... | StarcoderdataPython |
4308 | import pathlib
import yaml
documentations = {"Our Platform": "QuantConnect-Platform-2.0.0.yaml",
"Alpha Streams": "QuantConnect-Alpha-0.8.yaml"}
def RequestTable(api_call, params):
writeUp = '<table class="table qc-table">\n<thead>\n<tr>\n'
writeUp += f'<th colspan="2"><code>{api_call}</code... | StarcoderdataPython |
91972 | <filename>src/test/provision/app/test_cloudwatch_logs_alarms.py<gh_stars>1-10
from spacel.provision.app.cloudwatch_logs_alarm import \
CloudWatchLogsTriggerFactory
from test import BaseSpaceAppTest, ORBIT_NAME, APP_NAME
NAMESPACE = 'LogMetrics/%s/%s' % (APP_NAME, ORBIT_NAME)
ENDPOINT = 'test'
class TestCloudWat... | StarcoderdataPython |
190586 | import pytest
import numpy as np
import scipy.stats
import focal_stats
def test_focal_stats_values():
a = np.random.rand(5, 5)
# Values when not reducing
assert np.allclose(focal_stats.focal_mean(a)[2, 2], a.mean())
assert np.allclose(focal_stats.focal_sum(a)[2, 2], a.sum())
assert np.allclose(fo... | StarcoderdataPython |
82992 | from django.conf import settings
from rest_framework import serializers, viewsets
from .models import Menu, Page, Plugin
# lolworthily high, also the max :)
MENU_DEPTH = getattr(settings, 'COW_API_MENU_DEPTH', 10)
class PageSerializer(serializers.ModelSerializer):
class Meta:
model = Page
fields... | StarcoderdataPython |
166500 | from model.project import Project
from selenium.webdriver.support.select import Select
import string
import random
import re
class ProjectHelper:
def __init__(self, app):
self.app = app
project_cache = None
def random_string(self, prefix, maxlen):
symbols = string.ascii_letters + string... | StarcoderdataPython |
3236000 | """WidgetApp models"""
from django.db import models
from django.contrib.postgres.fields import JSONField
class WidgetList(models.Model):
"""
WidgetList handles authentication and is linked to a set of WidgetInstances
"""
class Meta:
app_label = "widgets"
class WidgetInstance(models.Model):
... | StarcoderdataPython |
3296144 | class Solution:
def busyStudent(self, startTime: List[int], endTime: List[int], queryTime: int) -> int:
return sum(1 for i in range(len(startTime)) if startTime[i] <= queryTime <= endTime[i])
| StarcoderdataPython |
139541 | import os
import shutil
import sys
import tarfile
import tempfile
import genomicsdb
import pandas as pd
def run_test():
genomicsdb.version()
gdb = genomicsdb.connect("ws", "callset_t0_1_2.json", "vid.json", "chr1_10MB.fasta.gz", ["DP"], 40)
try:
gdb.query_variant_calls()
... | StarcoderdataPython |
132063 | <filename>deps/mozjs/js/xpconnect/src/dombindingsgen.py
#!/usr/bin/env/python
# ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
#
# The contents of this file are subject to the Mozilla Public License Version
# 1.1 (the "License"); you may not use this file except in compliance with
# the License. Yo... | StarcoderdataPython |
3375063 | #!/usr/bin/python3
import os
import os.path
import json
import shutil
import subprocess
import boto3
import logging
import time
from logging.handlers import TimedRotatingFileHandler
f = open('config.json', 'r+')
configObj = json.loads(f.read())
f.close()
ddanToolsFolder = configObj["ddanToolsFolder"]
if ddanToolsFold... | StarcoderdataPython |
3394166 | <reponame>tanyafish/micropython-envirobit
# bargraph code modified from <NAME> code
# in Microbit for Mad Scientists
# Go buy his book, it's great
import tcs3472
import microbit
tcs3472 = tcs3472.tcs3472()
def light_level():
max_level = 0
for i in range(0, 10):
light_level = tcs3472.brightness() / 10... | StarcoderdataPython |
1636651 | # AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"GaussianBandit": "01_thompson_sampler.ipynb",
"BayesLinReg": "01_thompson_sampler.ipynb",
"BatchBayesLinReg": "01_thompson_sampler.ipynb",
"AbstractContextualSolver": "01_thompson_... | StarcoderdataPython |
136863 | <reponame>kirill-kundik/verify-test-task
import pathlib
from unittest.mock import mock_open, patch
import requests
import app.utils
def test_download_file(timeout, true_url, not_found_url, timeout_url, incorrect_url):
url = incorrect_url # url is not exists
resp = app.utils.download_file(url, timeout)
... | StarcoderdataPython |
142223 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 3 19:30:35 2019
@author: yangyutu123
"""
import torch
# We need to set requires_grad=True in order to get gradient with respect to x
x = torch.ones(2,2, requires_grad=True)
# construct function y as function of tensor x
y = torch.sum(torch.mm(x.t... | StarcoderdataPython |
1633274 | <gh_stars>0
trip_price = float ( input () )
puzzles = int ( input () )
dolls = int ( input () )
bears = int ( input () )
minions = int ( input () )
trucks = int ( input () )
money = (puzzles * 2.60) + (dolls * 3) + (bears * 4.10) + (minions * 8.20) + (trucks * 2)
num_toys = puzzles + dolls + bears + minions + trucks
mo... | StarcoderdataPython |
12840 | <filename>converter.py
import sys
import os
if sys.version_info[0] != 3 :
print("Running in python "+sys.version_info[0]+", should be python 3.")
print("Please install python 3.7 from the official site python.org")
print("Exiting now.")
exit()
import shutil
import argparse
import fbx2tree
import builder_fromfbx
... | StarcoderdataPython |
166031 | #!/usr/bin/env python
from setuptools import setup, find_packages
try:
README = open('README.rst').read()
except:
README = None
try:
REQUIREMENTS = open('requirements.txt').read()
except:
REQUIREMENTS = None
setup(
name='django-vspace-utils',
version="0.1",
description='Miscelleneous Dja... | StarcoderdataPython |
3386156 | import argparse
import base64
import io
from pathlib import Path
from typing import List, Iterator
import time
import numpy as np
import pandas as pd
from PIL import Image
import requests
def image_to_base64(image: Image) -> bytes:
fp = io.BytesIO()
image.save(fp, format="PNG")
fp.seek(0)
return base... | StarcoderdataPython |
152401 | import json
import os
from yunionclient.common import base
from yunionclient.common import exceptions
from yunionclient.common import utils
from yunionclient.common.utils import url_unquote, url_quote
class Image(base.ResourceBase):
def _normalize_attribute_dict(self, attr_dict):
props = attr_dict.get('... | StarcoderdataPython |
1674375 | <reponame>Doigyfu/Glass
# coding=utf-8
from os.path import abspath
from plugin import PluginSystem
from server import Mineserver, MineFactory
__all__ = ["main", "PureFactory", "Pureserver"]
server_config = '''
#Puremine server properties
#File format is same with Bukkit/Spigot servers
#However, not all values are su... | StarcoderdataPython |
77579 | import sqlite3
from pathlib import Path
from typing import List, NamedTuple, Union
from dtsdb import sqlite_util
class ScannedFile(NamedTuple):
path: Path
sdid: str
class ScannerState(object):
def __init__(self, conn: sqlite3.Connection, inbox_path: Union[str, Path]) -> None:
# TODO(fyhuang): w... | StarcoderdataPython |
1706409 | <reponame>JorgeGarciaIrazabal/baby_tracker_be<filename>src/controllers/pee.py
from typing import List, Optional
from fastapi import Depends
from fastapi_jwt_auth import AuthJWT
from sqlalchemy import desc
from sqlalchemy.orm import Session
from src.app import app, get_db
from src.models import Pee, PPee
from src.serv... | StarcoderdataPython |
3229742 | import csv
from get_icon import *
import graph
"""
This function reads a CSV history file and loads each URL as a node in the graph
"""
def load_graph(filename=str()):
# open File
file = open(filename, 'r')
# define graph object
g = graph.Graph()
# metadata stores URL : (Page Title, Icon path, Ic... | StarcoderdataPython |
1745290 | # coding: utf-8
"""
Galaxy 3.2 API (wip)
Galaxy 3.2 API (wip) # noqa: E501
The version of the OpenAPI document: 1.2.0
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import unittest
import openapi_client
from openapi_client.api.client_mazer_api import Clie... | StarcoderdataPython |
1646555 | <reponame>radekska/django-network-controller<filename>config_app/views.py
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.views.generic import ListView, View
from .models import ConfigParameters, SNMPConfigParameters
... | StarcoderdataPython |
3351650 | <filename>mongordkit/Search/tests/test_substructure.py
from mongordkit.Database import write
from mongordkit.Search import substructure, similarity
from mongordkit.Search.tests import utils
from rdkit import Chem
def test_addPatternFingerprints():
db = utils.setupMockDB()
write.WriteFromSDF(db.molecules, 'dat... | StarcoderdataPython |
100169 | <gh_stars>0
# -*- coding: utf-8 -*001-
from resources.Help import init_parabrisa
import time
try:
while True:
init_parabrisa()
print("\n----------------------------------\n")
time.sleep(86400000)
except KeyboardInterrupt:
print('Stoping observer')
| StarcoderdataPython |
3216459 | <filename>speech/microphone/transcribe_streaming_infinite.py
#!/usr/bin/env python
# Copyright 2019 Google LLC
#
# 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/... | StarcoderdataPython |
1751817 | <reponame>gLhookniano/AlgTradeTest
# coding: utf-8
import numpy as np
import talib as ta
from settings import evaluete
MAKER_COST = evaluete["maker_cost"]
TAKER_COST = evaluete["taker_cost"]
IMPACT = evaluete["impact"]
SLIDE = evaluete["slide"]
LEVER = evaluete["lever"]
MAX_POSITION = evaluete["max_position"]
STOP_EAR... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.