id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
3533666 | # -*- encoding: utf-8 -*-
#
# HTTP Host Test
# **************
#
# :authors: <NAME>
# :licence: see LICENSE
import json
from twisted.python import usage
from ooni.utils import log
from ooni.templates import httpt
class UsageOptions(usage.Options):
optParameters = [['backend', 'b', 'http://127.0.0.1:57001',
... | StarcoderdataPython |
113202 | while True:
n = int(input())
if n == -1:
break
last_elapsed = 0
distance = 0
for _ in range(n):
s, t = map(int, input().split())
_t = t - last_elapsed
distance += s * _t
last_elapsed = t
print(distance, "miles")
| StarcoderdataPython |
4982471 | '''
<NAME>
<EMAIL>
Assignment11
Lab section: B56
CA name: <NAME>
Assignment #11 Part 1
Phone: 6079532749
'''
'''
This class represents a patron
A Patron has a name, a status and
zero or more books checked out
'''
#This one is just for my own use.
#I'm so confused as for what methods I have.
#I have this as an reminder... | StarcoderdataPython |
12849383 | from os.path import join as pjoin
# Format expected by setup.py and doc/source/conf.py: string of form "X.Y.Z"
_version_major = 0
_version_minor = 9
_version_micro = 8 # use '' for first of series, number for 1 and above
_version_extra = 'dev'
# _version_extra = '' # Uncomment this for full releases
# Construct ful... | StarcoderdataPython |
11387173 | <filename>skidl/libs/rfcom_sklib.py<gh_stars>100-1000
from skidl import SKIDL, TEMPLATE, Part, Pin, SchLib
SKIDL_lib_version = '0.0.1'
rfcom = SchLib(tool=SKIDL).add_parts(*[
Part(name='BL652',dest=TEMPLATE,tool=SKIDL,keywords='Bluetooth Nordic nRF52',description='Bluetooth module',ref_prefix='U',num_units=1,... | StarcoderdataPython |
11393420 | <filename>devilry/devilry_admin/views/assignment/download_files/download_archive.py
# -*- coding: utf-8 -*-
from django.contrib.contenttypes.models import ContentType
from django.http import Http404
from django.shortcuts import get_object_or_404
from django.views import generic
from django_cradmin import crapp
from... | StarcoderdataPython |
4940942 | # -*- coding:utf-8 -*-
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
#
# 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... | StarcoderdataPython |
9741973 | <filename>03-validador_e_gerador_CPF/validador_gerador_CPF.py
'''
Funções para validação e geração de CPF utilizando códigos simples
'''
def validacao_CPF(cpf):
cpf = str(cpf)
if len(cpf) != 11:
return False
cpf_9digitos = cpf[:9]
# variáveis para os loops dos laços e para somas
loop1 = 10
... | StarcoderdataPython |
86160 | from __future__ import absolute_import, division, print_function
from six.moves import range
def intify(a):
return tuple([int(round(val)) for val in a])
def reference_map(sg, mi):
from cctbx import sgtbx
asu = sgtbx.reciprocal_space_asu(sg.type())
isym_ = []
mi_ = []
for hkl in mi:
found = False
... | StarcoderdataPython |
5128781 | from . import webdrivery # noqa
from . import action # noqa
from . import settings # noqa
| StarcoderdataPython |
9722159 | <filename>apps/dot_ext/views/authorization.py
import json
import logging
import waffle
from oauth2_provider.views.introspect import IntrospectTokenView as DotIntrospectTokenView
from oauth2_provider.views.base import AuthorizationView as DotAuthorizationView
from oauth2_provider.views.base import TokenView as DotToken... | StarcoderdataPython |
99233 | n = int(input())
D = [list(map(int,input().split())) for i in range(n)]
D.sort(key = lambda t: t[0])
S = 0
for i in D:
S += i[1]
S = (S+1)//2
S2 = 0
for i in D:
S2 += i[1]
if S2 >= S:
print(i[0])
break | StarcoderdataPython |
1824875 | import os
import sys
sys.path.append("../") # go to parent dir
import glob
import time
import logging
import numpy as np
from scipy.sparse import linalg as spla
import matplotlib.pyplot as plt
import logging
from mpl_toolkits import mplot3d
from mayavi import mlab
from scipy.special import sph_harm
mlab.options.offscr... | StarcoderdataPython |
24503 | # node class for develping linked list
class Node:
def __init__(self, data=None, pointer=None):
self.data = data
self.pointer = pointer
def set_data(self, data):
self.data = data
def get_data(self):
return self.data
def set_pointer(self, pointer):
... | StarcoderdataPython |
3526725 | <reponame>jonathan-taylor/l0bnb
import numpy as np
import regreg.api as rr
from l0bnb.proximal import (perspective_bound_atom,
perspective_lagrange_atom,
perspective_bound_atom_conjugate,
perspective_lagrange_atom_conjugate)
def test_... | StarcoderdataPython |
3439926 | <gh_stars>1-10
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
from .logger import Logger, InternalLogger, DummyLogger, LogFormat
from .utils import convert_dottable, clone, set_seeds
__all__ = ["Logger", "InternalLogger", "DummyLogger", "LogFormat", "convert_dottable", "clone", "set_seeds"]... | StarcoderdataPython |
41134 | <reponame>happy-machine/ktrain<gh_stars>0
# Global version information
__version__ = "0.7.2"
| StarcoderdataPython |
302214 | from pymongo import MongoClient
class MongoDBConnectionManager:
def __init__(self, hostname, port):
self.hostname = hostname
self.port = port
self.connection = None
def __enter__(self):
self.connection = MongoClient(self.hostname, self.port)
return self
def __exit... | StarcoderdataPython |
1982338 | <reponame>MTC-ETH/Federated-Learning-source
# Copyright 2021, ETH Zurich, Media Technology Center
#
# 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/l... | StarcoderdataPython |
8006662 | import json
import random
import unittest
from model.firmware_error import FirmwareError, ErrorType
class FirmwareErrorTest(unittest.TestCase):
def test_given_a_firmware_error_then_it_is_serializable(self):
number = random.randint(400, 699)
task = 'test_task'
description = 'test_descripti... | StarcoderdataPython |
1749089 | # Copyright 2022 Novel, Emerging Computing System Technologies Laboratory
# (NECSTLab), Politecnico di Milano
# 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.... | StarcoderdataPython |
3284614 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-05-11 19:00
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('entrance', '0043_auto_20170510_2044'),
]
operations = [
migrations.AlterFie... | StarcoderdataPython |
8031704 | master_doc = "index"
extensions = ["sphinx.ext.autodoc", "uqbar.sphinx.book"]
html_static_path = ["_static"]
| StarcoderdataPython |
3382438 | #!/usr/bin/env python3
# pylint: skip-file
from quickeys.__main__ import *
main()
| StarcoderdataPython |
1793652 | # Two-layer, sigmoid feedforward network
# trained using the "Extreme Learning Machine" algorithm.
# Adapted from https://gist.github.com/larsmans/2493300
# TODO: make it possible to use alternative linear classifiers instead
# of pinv2, e.g. SGDRegressor
# TODO: implement partial_fit and incremental learning
# TODO: ... | StarcoderdataPython |
3583006 | # pylint: disable=relative-beyond-top-level,import-outside-toplevel
import os
import unittest
from traceback import print_exc
from optimade.validator import ImplementationValidator
from .utils import SetClient
class ServerTestWithValidator(SetClient, unittest.TestCase):
server = "regular"
def test_with_va... | StarcoderdataPython |
1730315 | from unittest import TestCase
from xrpl.models.exceptions import XRPLModelException
from xrpl.models.transactions import NFTokenCreateOffer, NFTokenCreateOfferFlag
_ACCOUNT = "<KEY>"
_ANOTHER_ACCOUNT = "<KEY>"
_FEE = "0.00001"
_SEQUENCE = 19048
_NFTOKEN_ID = "00090032B5F762798A53D543A014CAF8B297CFF8F2F937E844B17C9E00... | StarcoderdataPython |
3429700 | import numpy as np
import tensorflow as tf
import time
import os
import pickle
import argparse
from utils import *
from model import Model
import random
import matplotlib.pyplot as plt
import svgwrite
from IPython.display import SVG, display
# main code (not in a main function since I want to run this script in IPy... | StarcoderdataPython |
3419386 | <reponame>gpooja3/pyvcloud
# VMware vCloud Director Python SDK
# Copyright (c) 2018 VMware, Inc. All Rights Reserved.
#
# 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... | StarcoderdataPython |
5027956 | from . import _connector
Connections = _connector.Connections
Transaction = _connector.Transaction
| StarcoderdataPython |
368638 | class Defaults(object):
window_size = 7
filter_nums = [100, 100, 100]
filter_sizes = [3, 4, 5]
hidden_sizes = [1200]
hidden_activation = 'relu'
max_vocab_size = 1000000
optimizer = 'adam'
learning_rate = 1e-4
epochs = 20
iobes = True # Map tags to IOBES on input
max_tokens... | StarcoderdataPython |
283745 | <filename>Arquivo/2020-2/2020-2-uff-lrp/lista-2/ex-4.py
n = int(input())
if 0 <= n <= 100:
if n == 0:
print('E')
elif 1 <= n <= 35:
print('D')
elif 36 <= n <= 60:
print('C')
elif 61 <= n <= 85:
print('B')
elif 86 <= n <= 100:
print('A') | StarcoderdataPython |
1973321 | # Generated from Quil.g4 by ANTLR 4.7.1
from antlr4 import *
from io import StringIO
from typing.io import TextIO
import sys
def serializedATN():
with StringIO() as buf:
buf.write("\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\2J")
buf.write("\u0211\b\1\4\2\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6... | StarcoderdataPython |
5081693 | <gh_stars>0
# # looks outdated & python2
#
# trj, psg = min_jerk(pos, dur, vel, acc, psg)
#
# Compute minimum-jerk trajectory through specified points
#
# INPUTS:
# pos: NxD array with the D-dimensional coordinates of N points
# dur: number of time steps (integer)
# vel: 2xD array with endpoint velocities, [] sets vel ... | StarcoderdataPython |
328354 | import pytest
from brewtils import get_easy_client
from brewtils.schema_parser import SchemaParser
try:
from ..helper import RequestGenerator, setup_easy_client
except (ImportError, ValueError):
from helper import RequestGenerator, setup_easy_client
@pytest.fixture(scope="class")
def request_generator(reques... | StarcoderdataPython |
1692794 | ######### imports #########
from ast import arg
from datetime import timedelta
import sys
sys.path.insert(0, "TP_model")
sys.path.insert(0, "TP_model/fit_and_forecast")
from Reff_constants import *
from Reff_functions import *
import glob
import os
from sys import argv
import arviz as az
import seaborn as sns
import m... | StarcoderdataPython |
6422770 | import abc
import os
from multiprocessing import Process, Queue
class AbcDataPipeline(metaclass=abc.ABCMeta):
@abc.abstractmethod
def execute(self):
raise NotImplementedError
class TaskPipelineBase(AbcDataPipeline):
name = '单任务处理'
def __init__(self, in_data_path, out_data_path, process_num... | StarcoderdataPython |
1678716 | """Face Autoencoder used in:
IMPROVING CROSS-DATASET PERFORMANCE OF FACE PRESENTATION ATTACK DETECTION SYSTEMS USING FACE RECOGNITION DATASETS,
Mohammadi, <NAME> Bhattacharjee, Sushil and <NAME>, ICASSP 2020
"""
import tensorflow as tf
from bob.learn.tensorflow.models.densenet import densenet161
def _get_l2_kw(weig... | StarcoderdataPython |
12832124 | <reponame>gavinIRL/RHBotArray
import os
import cv2
import time
import math
import ctypes
import random
import win32ui
import win32gui
import warnings
import win32con
import threading
import subprocess
import pytesseract
import numpy as np
import pydirectinput
from fuzzywuzzy import process
from custom_input import Cust... | StarcoderdataPython |
6551826 | <gh_stars>1-10
""" A workbench. """
# Standard library imports.
import six.moves.cPickle
import logging
import os
# Enthought library imports.
from traits.etsconfig.api import ETSConfig
from pyface.api import NO
from traits.api import Bool, Callable, Event, HasTraits, provides
from traits.api import Instance, List, ... | StarcoderdataPython |
332292 | #Special Pythagorean triplet
def Euler9(sum):
for a in range(1,sum):
for b in range(1,sum):
c=sum-a-b
#print(str(a)+'\t\t'+str(b)+'\t\t'+str(c))
if (a*a+b*b)==(c*c):
return (a,b,c,a*b*c)
for i in range(1000,1001):
print(str(i)+'\t\t'+str(Euler9(i))) | StarcoderdataPython |
181311 | import logging
from typing import Dict
from threading import Lock
from prometheus_network_exporter.devices.basedevice import Device
__version__ = "1.1.2"
GLOBAL_GUARD: Lock = Lock()
CONNECTION_POOL: Dict[str, Device] = {}
COUNTER_DIR = ".tmp"
MAX_WAIT_SECONDS_BEFORE_SHUTDOWN = 60
MAX_WORKERS = 90
APP_LOGGER = loggin... | StarcoderdataPython |
3207773 | <gh_stars>0
flowers = ['Lily', 'Snapdragon', 'Rose', 'Tulip']
# large_flowers = ['a large ' + f for f in flowers]
# print(large_flowers)
large_flowers = list()
for f in flowers:
large_flowers.append('a large ' + f)
# print(large_flowers)
family = { 'mother': 'Margaret', 'father': 'Reginald', 'sister': 'Jenny'}
my_... | StarcoderdataPython |
5051933 | # Generated by Django 3.1.3 on 2020-11-17 15:20
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('equipments', '0007_auto_20201117_1457'),
]
operations = [
migrations.RemoveField(
model_name='c... | StarcoderdataPython |
9710797 | <reponame>strzelcu/vehicletyperecognizer<gh_stars>0
import argparse
import datetime
import os
import sys
from configparser import RawConfigParser
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
from imutils import paths
from sklearn.metrics import accuracy_score
from sklearn.metrics import ... | StarcoderdataPython |
1832210 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'graph.ui'
#
# Created by: PyQt5 UI code generator 5.15.1
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, QtGui, ... | StarcoderdataPython |
6481430 | <reponame>pgfeldman/RCSNN
from rcsnn.base.BaseController import BaseController
from rcsnn.base.DataDictionary import DataDictionary
from rcsnn.base.CommandObject import CommandObject
from rcsnn.base.Commands import Commands
from rcsnn.base.ResponseObject import ResponseObject
from rcsnn.base.Responses import Responses
... | StarcoderdataPython |
3542168 | <reponame>CodedLadiesInnovateTech/-python-challenge-solutions
# program to create a bytearray from a lis
print()
nums = [10, 20, 56, 35, 17, 99]
# Create bytearray from list of integers.
values = bytearray(nums)
for x in values: print(x)
print()
| StarcoderdataPython |
9712644 | <filename>nba/baseclient.py
import requests
from requests.adapters import HTTPAdapter
class BaseClient(object):
def __init__(self):
self.url = "http://stats.nba.com/stats/"
self.session = requests.Session()
self.session.mount("http://stats.nba.com", HTTPAdapter(max_retries=1))
self... | StarcoderdataPython |
6530834 | <gh_stars>1-10
from django import forms
from dicoms.models import Search, Session, Series
from os.path import basename, normpath
from django.utils.translation import ugettext_lazy as _
from bootstrap_datepicker_plus import DatePickerInput
from drf_braces.serializers.form_serializer import FormSerializer
import json
... | StarcoderdataPython |
5155537 | # *****************************************************************************
# © Copyright IBM Corp. 2018. All Rights Reserved.
#
# This program and the accompanying materials
# are made available under the terms of the Apache V2.0 license
# which accompanies this distribution, and is available at
# http://www.apac... | StarcoderdataPython |
1651433 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits:
1634 = 14 + 64 + 34 + 44
8208 = 84 + 24 + 04 + 84
9474 = 94 + 44 + 74 + 44
As 1 = 14 is not a sum it is not included.
The sum of these numb... | StarcoderdataPython |
3555311 | import warnings
warnings.simplefilter(action="ignore", category=FutureWarning)
import osmnx as ox
import pandas as pd
import numpy as np
import geopandas as gpd
import networkx as nx
import math
from math import sqrt
import ast
import functools
from shapely.geometry import Point, LineString
pd.set_option("display.pre... | StarcoderdataPython |
323297 | import pandas as pd
from pathlib import Path, PosixPath
import pickle
import dill
import os
from typing import Type, Any
import yaml
class DataInterfaceBase:
"""
Govern how a data type is saved and loaded. This class is a base class for all DataInterfaces.
"""
file_extension = None
@classmethod
... | StarcoderdataPython |
1722762 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... | StarcoderdataPython |
1837053 | <filename>start_up/start_up_uems.py<gh_stars>1-10
from copy import deepcopy
from modelling.devices import transmission_lines
from configuration.configuration_time_line import default_look_ahead_time_step
def start_up(microgrid, microgrid_middle, microgrid_long):
"""
Start up of universal energy management system, wh... | StarcoderdataPython |
26738 | <filename>setup.py<gh_stars>10-100
#!/usr/bin/python
from distutils.core import setup
setup(
name = 'payment_processor',
version = '0.2.0',
description = 'A simple payment gateway api wrapper',
author = '<NAME>',
author_email = '<EMAIL>',
url = 'https://launchpad.net/python-payment',... | StarcoderdataPython |
5091033 | expected_output = {
"route-information": {
"route-table": [
{
"active-route-count": "929",
"destination-count": "929",
"hidden-route-count": "0",
"holddown-route-count": "0",
"rt": [
{
... | StarcoderdataPython |
6433598 | """change category config options
Revision ID: 253ae54f5788
Revises: 36<PASSWORD>
Create Date: 2019-11-16 16:58:11.287152
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '<KEY>'
down_revision = '36c<PASSWORD>'
branch_labels = None
depends_on = None
def upgrad... | StarcoderdataPython |
1871878 | # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
#
# See COPYING file distributed along with the PyMVPA package for the
# copyright and license terms.
#
### ### ### ### ###... | StarcoderdataPython |
8016999 | <reponame>paramraghavan/beginners-py-learn
'''
When you assign 42 to the name myGlobal, therefore, Python creates a local variable that shadows the global variable of the same name.
That local goes out of scope and is garbage-collected when func1() returns; meanwhile, func2() can never see anything other than the
(u... | StarcoderdataPython |
3386455 | <reponame>itdependsnetworks/Network-Automation
from Database import DB_queries as DbQueries
from Software import NXOS, IOSXE, ASA
if __name__ == '__main__':
skip_login = input("Database populated? Press enter to skip. Enter any other key to populate new table. ")
print("\n")
if skip_login != "":
... | StarcoderdataPython |
6467206 | from setuptools import setup
import importlib
cmdclass = None
try:
import jinja2 # Available when installed in dev mode
except ImportError:
pass
else:
cmdclass = {
'generate_docs': getattr(importlib.import_module('aiotumblr.utils.docgen'), 'DocGenCommand')
}
setup(
name='AIOTumblr',
... | StarcoderdataPython |
1654461 | <reponame>dmulyalin/salt-nornir
import logging
import pprint
import pytest
import os
log = logging.getLogger(__name__)
try:
import salt.client
import salt.exceptions
HAS_SALT = True
except:
HAS_SALT = False
raise SystemExit("SALT Nonrir Tests - failed importing SALT libraries")
if HAS_SALT:
... | StarcoderdataPython |
1908345 | import os
from tqdm import tqdm
from IPython import embed
import numpy as np
import torch
from torch.autograd import Variable
from torch.utils.data import DataLoader
from utils import MemoryDataset, collate_fn, normal, normalize, ZFilter
from model import Model
from plotter import Plotter
class Trainer:
def __in... | StarcoderdataPython |
8157385 | <reponame>aniket15b/URL-Shortener
from django.db import models
# Create your models here.
class Route(models.Model):
original_url = models.URLField(help_text= "Add the original URL that you want to shorten.")
key = models.TextField(unique= True, help_text= "Add any random characters of your choice to shorten i... | StarcoderdataPython |
4890784 | """This component provides HA sensor support for Ring Door Bell/Chimes."""
from __future__ import annotations
from dataclasses import dataclass
from homeassistant.components.sensor import (
SensorDeviceClass,
SensorEntity,
SensorEntityDescription,
)
from homeassistant.const import PERCENTAGE, SIGNAL_STREN... | StarcoderdataPython |
11252871 | from django.apps import AppConfig
class InventarisConfig(AppConfig):
name = 'inventaris'
| StarcoderdataPython |
6473961 | <reponame>msc-acse/acse-9-independent-research-project-Wade003
#!/usr/bin/env python
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your opti... | StarcoderdataPython |
1867101 | <reponame>Rafiatu/ebay_predictions
from decouple import config
import pandas as pd
import psycopg2
import psycopg2.extras as extras
class DatabaseError(psycopg2.Error):
pass
class Database:
"""
Database class. Handles all connections to the database on heroku.
"""
connection = psycopg2.connect(
... | StarcoderdataPython |
8103012 | <reponame>acm-ucr/xhtml2pdf
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
# Copyright 2010 <NAME>, holtwick.it
#
# 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.ap... | StarcoderdataPython |
1772249 | import sys
s = sys.stdin.readline().rstrip()
def main():
ans = 'Good'
for i in range(3):
if s[i] == s[i+1]:
ans = 'Bad'
break
print(ans)
if __name__ == '__main__':
main()
| StarcoderdataPython |
11288626 | from .Auth.authentication import urlpatterns as auth_url_patters
from .Setup.roles import urlpatterns as routepatterns
urlpatterns = []
urlpatterns += auth_url_patters
urlpatterns += routepatterns
| StarcoderdataPython |
4889739 | """
POO - Abstração e Encapsulamento
O grande objetivo da POO é encapsular nosso código dentro de um grupo lógico e hierárquico utilizando classes.
Encapsular - A classe vai encapsular(englobar) os atributos e métodos.
classe
---------------------------------
/ /
/... | StarcoderdataPython |
1707383 | import datetime
from django.db import models
from django.dispatch import receiver
from django.utils import timezone
from django.conf import settings
# Create your models here.
from django.db.models.signals import pre_save, post_save
from django.urls import reverse
from model_utils import Choices
from util.util import ... | StarcoderdataPython |
5000008 | <gh_stars>1-10
from PyQt5.QtWidgets import QHBoxLayout, QLabel, QWidget
from PyQt5.QtCore import pyqtSignal
from widgets import ImageButton
class PlusIcon(QWidget):
"""
Plus icon widget with specified description text to its right
"""
add = pyqtSignal()
def __init__(self, text: str, size: int = 24... | StarcoderdataPython |
3256862 | <filename>build/lib/OpenSpecimenAPIconnector/os_core/participant.py<gh_stars>1-10
#! /bin/python3
# Import
import json
from datetime import datetime
from .req_util import OS_request_gen
from .. import config_manager
class participant:
"""Handles the API calls for the participant
Handles the OpenSpecimen API... | StarcoderdataPython |
1866764 | <reponame>MarchRaBBiT/pipelinex
from datetime import datetime, timedelta
import os
import tempfile
import torch
import logging
log = logging.getLogger(__name__)
__all__ = ["FlexibleModelCheckpoint"]
"""
Copied from https://github.com/pytorch/ignite/blob/v0.2.1/ignite/handlers/checkpoint.py
due to the change in ign... | StarcoderdataPython |
1896193 | <filename>augmented_reality/calibration_imgs/take_pictures.py
import cv2
def main():
video = cv2.VideoCapture(0)
num_pics = 15
input("place the checkerboard in front of the camera and press a key to start")
while num_pics > 0:
frame = video.read()[1]
cv2.imshow("shot", frame)
ke... | StarcoderdataPython |
8131126 | <gh_stars>0
import sys
from raspberrypi_py.utils import Led
def play(times=None, frequency=None):
led = Led()
print('Start session')
kwargs = {}
if times:
kwargs['times'] = times
if frequency:
kwargs['frequency'] = frequency
led.pulse(**kwargs)
if __name__ == '__main__':
... | StarcoderdataPython |
8174474 | # Generated by Django 3.0.5 on 2020-04-16 08:50
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("tests", "0018_auto_20200416_1049"),
]
operations = [
migrations.AlterField(
model_name="historicalrelatedmodeltest",
... | StarcoderdataPython |
3515998 | <gh_stars>0
from simglucose.simulation.user_interface import simulate
import unittest
from unittest.mock import patch
import shutil
import os, inspect
parentdir = os.path.join(os.path.expanduser("~"),'PycharmProjects','simglucose')
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
... | StarcoderdataPython |
1697630 | """def algo():
raise Exception("Exceção!!")
print("Depois da exceção!!")
def algo2():
try:
algo()
except:
print("Eu peguei uma exceção!!")
print("Executado após a exceção!!")
algo2()"""
"""def divisao(divisor):
try:
if divisor == 17:
raise ValueErro... | StarcoderdataPython |
3373104 | from typing import Optional, Union, List, Tuple
import numpy as np
import gurobipy as grb
from utils import Multidict, get_angles, get_angle, callback_rerouter, get_array_greater_zero, calculate_times, is_debug_env
from solver import Solver
from database import Graph, AngularGraphSolution
class AngularGraphScanMakes... | StarcoderdataPython |
1943559 | import ctypes
import mmap
MAX_PLAYERS = 10
MAX_NAME_LENGTH = 32
MAX_BOOSTS = 50
SHARED_MEMORY_TAG = 'Local\\RLBotOutput'
class Vector3(ctypes.Structure):
_fields_ = [("X", ctypes.c_float),
("Y", ctypes.c_float),
("Z", ctypes.c_float)]
class Rotator(ctypes.Structure):
_fields... | StarcoderdataPython |
6606095 | <gh_stars>1-10
import rospy
from eagerx import EngineState
import eagerx.core.register as register
class DummyReset(EngineState):
@staticmethod
@register.spec('DummyResetState', EngineState)
def spec(spec, sleep_time: float = 1., repeat: int = 1):
spec.config.sleep_time = sleep_time
spec.c... | StarcoderdataPython |
9686069 | <filename>api/v1_pf.py
#!/usr/bin/env python3
from flask import jsonify, request, make_response
from api import tools
@tools.require_auth
def pf_init():
tools.ip_init()
return ("", 204)
@tools.require_auth
def pf_get():
order = request.args.get("order")
if order and order.lower() != "ip":
... | StarcoderdataPython |
9636795 | <reponame>mitchute/SWHE
import unittest
from src.utilities import smoothing_function
class TestUtilities(unittest.TestCase):
def test_smoothing_function(self):
x_min = 0
x_max = 1
y_min = 0
y_max = 1
self.assertAlmostEqual(smoothing_function(-10, x_min, x_max, y_min, y_m... | StarcoderdataPython |
3537218 | <gh_stars>0
from flask import Flask
from app.errors.routes import error_404, error_403, error_401, error_500
def create_app():
app = Flask(__name__)
# Retrieve configuration information
app.config.from_object('app.config.Config')
# Initialization of blueprints
from app.main import main_bp
... | StarcoderdataPython |
1823663 | from pretix_eth.providers import BlockscoutTokenProvider
from eth_utils import (
is_boolean,
is_checksum_address,
is_bytes,
is_integer,
)
MAINNET_DAI_TXN_HASH = '0x4122bca6b9304170d02178c616185594b05ca1562e8893afa434f4df8d600dfa'
def test_blockscout_transaction_provider():
provider = Blockscout... | StarcoderdataPython |
3384142 | <gh_stars>0
## Contributors: <NAME>, <NAME>, and <NAME>
from math import log, ceil, floor
import numpy as np
# raw_resp = np.load('/cds/data/psdm/tmo/tmolw5618/results/raw_resp.npy')
raw_resp = np.load('/cds/home/m/mrware/Workspace/2021-02-tmolw56/2021-02-preproc-git/xtc/raw_resp.npy')
def FFTfind_fixed(hsd, nmax=100... | StarcoderdataPython |
6506210 | __author__ = 'julius'
class Post:
""" Facebook Post """
def __init__(self):
self.id = None
self.fb_id = None
self.content = None
self.author = None
self.nLikes = None
self.nComments = 0
self.timeOfPublication = None
self.original_features = None... | StarcoderdataPython |
201159 | <gh_stars>0
import unittest
import torch
from torch.utils.data import DataLoader
from few_shot.core import NShotTaskSampler
from few_shot.datasets import DummyDataset
from few_shot.matching import matching_net_predictions
from few_shot.utils import pairwise_distances
class TestMatchingNets(unittest.TestCase):
@... | StarcoderdataPython |
1708805 | <filename>thelma/repositories/rdb/schema/tables/experimentsourcerack.py
"""
This file is part of the TheLMA (THe Laboratory Management Application) project.
See LICENSE.txt for licensing, CONTRIBUTORS.txt for contributor information.
Experiment source rack association table.
"""
from sqlalchemy import Column
from sqla... | StarcoderdataPython |
199399 | import os
import json
import appdirs
class Settings:
def __init__(self, common):
self.common = common
self.settings_filename = os.path.join(self.common.appdata_path, "settings.json")
self.default_settings = {
"save": True,
"ocr": True,
"ocr_language": "E... | StarcoderdataPython |
4818915 | """
Request and Response model for position book request
"""
"""
Request and Response model for trade book request
"""
from typing import Optional
from pydantic import BaseModel
from datetime import datetime
from ....common.enums import ResponseStatus
from ....utils.decoders import build_loader, datetime_decoder
__a... | StarcoderdataPython |
6657311 | <gh_stars>0
import logging
import pajbot.models
from pajbot.modules import BaseModule
from pajbot.modules import ModuleSetting
from pajbot.modules import QuestModule
log = logging.getLogger(__name__)
class ShowEmoteTokenCommandModule(BaseModule):
ID = 'tokencommand-' + __name__.split('.')[-1]
NAME = 'Token... | StarcoderdataPython |
6429765 | <reponame>julian-r/tapiriik
import os
import math
from datetime import datetime, timedelta
import pytz
import requests
from django.core.urlresolvers import reverse
from tapiriik.settings import WEB_ROOT, RWGPS_APIKEY
from tapiriik.services.service_base import ServiceAuthenticationType, ServiceBase
from tapi... | StarcoderdataPython |
5003782 | import os
import fire
from tifffile import tifffile
import numpy as np
import matplotlib.pyplot as plt
def apply_possion(input_file, output_file, multiplier=.5, number=1):
rng = np.random.default_rng()
image = tifffile.imread(input_file)
image = image.astype("float64")
if np.isclose(np.mean(image[:50]... | StarcoderdataPython |
12836112 | <filename>miniworld/model/network/backends/InterfaceFilter.py
class InterfaceFilter:
def __init__(self, *args, **kwargs):
pass
def get_interfaces(self, emulation_node_x, emulation_node_y):
"""
Attributes
----------
emulation_node_x: EmulationNode
emulation_nod... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.