id
stringlengths
1
265
text
stringlengths
6
5.19M
dataset_id
stringclasses
7 values
1763292
<reponame>the-house-of-black-and-white/pyWiderFace import logging import sys import unittest import os from morghulis.afw import AFW from morghulis.os_utils import ensure_dir logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) log = logging.getLogger(__name__) AFW_DIR = os.path.dirname(__file__) + '/AFW_sam...
StarcoderdataPython
1746614
<gh_stars>0 ''' Construa um algoritmo para calcular o volume de uma esfera de raio R, em que R é um dado fornecido pelo usuário. Forneça como saída o resultado do cálculo executado. ''' raio = int(input("Insira o raio do circulo.\n")) volume = (4*(3.14*(raio * raio * raio)))/3 print("O volume do circulo é:",...
StarcoderdataPython
3317116
from gevent import monkey; monkey.patch_all() # noqa from .worker import Worker, GeventWorker __all__ = [Worker, GeventWorker]
StarcoderdataPython
1715692
import os from pathlib import Path from colorama import Fore def square(s: str) -> str: return '+' + '-' * (len(s) + 2) + '+\n| ' + s + ' |\n+' + '-' * (len(s) + 2) + '+' def mp4ToMp3(path, name): try: base = path os.rename(path, f'{name}.mp3') print(f'{Fore.GREEN}{square(...
StarcoderdataPython
70145
<reponame>M-O-P-D/Police-Supply-Demand import neworder as no from crims.visualisation import density_map from crims.model import CrimeMicrosim if __name__ == "__main__": force = "City of London" month = 2 model = CrimeMicrosim(0, force, 3, (2020, month + 1)) no.run(model) crimes = model.crimes print(c...
StarcoderdataPython
3387654
#coding:utf-8 import os import flask import flask_login from login import app,users from flask import render_template,flash from extensions import login_manager from main.utils import log import sys reload(sys) sys.setdefaultencoding('utf8') class User(flask_login.UserMixin): pass @login_manager.user_loader def use...
StarcoderdataPython
1676326
<reponame>wgfi110/athena<filename>athena/data/datasets/speaker_recognition.py # coding=utf-8 # Copyright (C) 2020 ATHENA AUTHORS; <NAME> # # 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 # # ...
StarcoderdataPython
20641
<filename>isaactest/tests/recieve_verify_emails.py from ..utils.log import log, INFO, ERROR, PASS from ..utils.i_selenium import assert_tab, image_div from ..tests import TestWithDependency __all__ = ["recieve_verify_emails"] ##### # Test : Recieve Verification Emails ##### @TestWithDependency("RECIEVE_VERIFY_EMAILS...
StarcoderdataPython
1745227
<gh_stars>1-10 import tensorflow as tf def resnet(x, residual_depth, training): """Residual convolutional neural network with global average pooling""" x = tf.layers.conv3d(x, 16, [3, 3, 3], strides=1, padding='SAME', use_bias=False, kernel_initializer=tf.contrib.layers.variance_scal...
StarcoderdataPython
3225508
<gh_stars>0 # coding=utf-8 from flask import Flask from flask import request import json import infoGetter import config v2ex_session = {} header = {} app = Flask(__name__) # @app.route('/', methods=['GET', 'POST']) # def home(): # return '<h1>Home</h1>' @app.route('/newsTitle', methods=['GET']) def getNews():...
StarcoderdataPython
3217171
<reponame>iriberri/aiida_core<filename>aiida/cmdline/commands/cmd_data/cmd_remote.py # -*- coding: utf-8 -*- ########################################################################### # Copyright (c), The AiiDA team. All rights reserved. # # This file is part of the AiiDA code. ...
StarcoderdataPython
1765530
from app.tasks import monitor_ac_usage, monitor_temperatures from models.event import Event, EventType from sqlalchemy_utils import naturally_equivalent from models.temperature import Temperature from decimal import Decimal import pytest @pytest.mark.json_data('{ "Good data": "asdfa"}') def test_monitor_ac_usage_turn...
StarcoderdataPython
3285883
<gh_stars>0 from __future__ import ( absolute_import, unicode_literals, ) import abc import copy from typing import ( Callable, Iterable, Optional, SupportsInt, Type, Union, ) import attr import six from pysoa.client.client import Client from pysoa.common.constants import ( ERROR_...
StarcoderdataPython
3239318
<filename>migrations/versions/535ecccca644_removing_some_columns.py """removing some columns Revision ID: 535ecccca644 Revises: <PASSWORD> Create Date: 2018-06-25 15:01:54.482732 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '535ecccca644' down_revision = '<P...
StarcoderdataPython
1610370
<gh_stars>1-10 # Copyright 2013-2018 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * import os class Supernova(Package): """Supernova is a software package for de nov...
StarcoderdataPython
3320472
<gh_stars>0 from collections import Counter, deque import numpy as np import random class EpsilonGreedy: def __init__(self, n_outputs, epsilon_min = 0.05, epsilon_max = 1.0, epsilon_decay=0.999): self.n_outputs = n_outputs self.epsilon_min = epsilon_min self.epsilon_max ...
StarcoderdataPython
82492
from scapy.all import * import argparse def scan(ip): answered = srp(Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(pdst=ip),timeout=1, verbose=False)[0] clients_list = [] for element in answered: clients_dict = {"ip": element[1].psrc, "mac": element[1].hwsrc} clients_list.append(clien...
StarcoderdataPython
1647376
from pppr import aabb import numpy as np from pak.datasets.MOT import MOT16 from pak import utils from pppr import aabb from time import time from cselect import color as cs # =========================================== # Helper functions # =========================================== def remove_negative_pairs(Dt, W, ...
StarcoderdataPython
53713
from pathlib import Path from smarts.sstudio import gen_scenario from smarts.sstudio import types as t traffic_histories = [ t.TrafficHistoryDataset( name=f"us101_{hd}", source_type="NGSIM", input_path=f"../../xy-trajectories/us101/trajectories-{hd}.txt", speed_limit_mps=28, ...
StarcoderdataPython
3268774
import mypythontools if __name__ == "__main__": # All the parameters can be overwritten via CLI args mypythontools.utils.push_pipeline(deploy=True)
StarcoderdataPython
3226811
import RPi.GPIO as GPIO import picamera import time GPIO.setmode(GPIO.BCM) GPIO.setup(17, GPIO.IN) GPIO.setup(18, GPIO.OUT) camera = picamera.PiCamera() camera.resolution = (1024, 768) try: while True: input_state = GPIO.input(17) GPIO.output(18, False) if input_state == True: print('Motion Detected') ...
StarcoderdataPython
1747741
<gh_stars>0 # Generated by Django 4.0.4 on 2022-04-19 12:05 from django.contrib.postgres.operations import BtreeGinExtension, TrigramExtension from django.db import migrations class Migration(migrations.Migration): dependencies = [ ("boards", "0030_historicalboardpreferences"), ] operations = [...
StarcoderdataPython
1689300
# Time: O(n) # Space: O(n) # 834 # An undirected, connected tree with N nodes # labelled 0...N-1 and N-1 edges are given. # # The ith edge connects nodes edges[i][0] and edges[i][1] together. # # Return a list ans, where ans[i] is the sum of the distances # between node i and all other nodes. # # Example 1: # # Input...
StarcoderdataPython
1653111
################################################################################ # Copyright (C) 2013-2014 <NAME> # # This file is licensed under the MIT License. ################################################################################ import numpy as np import warnings import scipy from bayespy.utils import...
StarcoderdataPython
1782143
# Copyright 2021 UW-IT, University of Washington # SPDX-License-Identifier: Apache-2.0 from pathways.views.api import RESTDispatch from pathways.models.course import Course from django.core.exceptions import ObjectDoesNotExist from django.utils.decorators import method_decorator from django.contrib.auth.decorators imp...
StarcoderdataPython
1729396
from django.conf.urls import url from . import views # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover() urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^edit/(\d+)/$', views.edit, name='edit'), url(r'^view/(\d+)/$', views.details, na...
StarcoderdataPython
3273469
# -*- coding: utf-8 -*- """Module to create Flask and Dash applications.""" from flask import Flask from dash import Dash import dash_bootstrap_components as dbc from common.config import Config from common.mongo import Mongo def create_flask(): """Create the Flask instance for this application. Returns: ...
StarcoderdataPython
3299504
# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2017-08-17 02:43 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django.utils.timezone import model_utils.fields class Migration(migrations.Migration): ...
StarcoderdataPython
1771946
<reponame>Themimitoof/python-zipkin<filename>zipkin/binding/django/middleware.py """Middleware for django.""" import time import logging from django.conf import settings from zipkin import local from zipkin.api import get_current_trace, stack_trace from zipkin.models import Trace, Annotation, Endpoint from zipkin.uti...
StarcoderdataPython
3293427
''' -*- coding: utf-8 -*- @Time : 18-11-14 下午7:58 @Author : SamSa @Site : @File : loginApi.py @Software: PyCharm @Statement:登陆 ''' # from datetime import datetime # from re import sub from flask import session # from App.modles.orderModel import Orders '''登陆''' from flask_restful import Resource, reqparse f...
StarcoderdataPython
3376555
<reponame>moamenibrahim/nlp-project<gh_stars>0 from polyglot.text import Text def polyglotNER(inputText, lang='fi'): try: text = Text(inputText, hint_language_code=lang) # for sent in text.sentences: # for entity in sent.entities: ...
StarcoderdataPython
22397
<filename>tests/integration/test_k8s.py # -*- coding: utf-8 -*- # # Copyright Contributors to the Conu project. # SPDX-License-Identifier: MIT # """ Tests for Kubernetes backend """ import urllib3 import pytest from conu import DockerBackend, \ K8sBackend, K8sCleanupPolicy from conu.backend.k8s.pod ...
StarcoderdataPython
84832
# --------------------------------------------------------------------- # AlliedTelesis.AT8100.get_mac_address_table # --------------------------------------------------------------------- # Copyright (C) 2007-2018 The NOC Project # See LICENSE for details # -------------------------------------------------------------...
StarcoderdataPython
112253
from abc import ABC, abstractmethod from a2e.evaluation import EvaluationResult class AbstractModel(ABC): @abstractmethod def evaluate(self, x_train, y_train, x_valid, y_valid, budget=None, **kwargs) -> EvaluationResult: pass @abstractmethod def load_config(self, config: dict = None, **kwargs...
StarcoderdataPython
4823235
<filename>certbot_haproxy/tests/__init__.py """Certbot HAProxy Tests""" from __future__ import print_function import unittest def load_tests(loader, tests, pattern=None): """Find all python files in the tests folder""" if pattern is None: pattern = 'test_*.py' print("loader: ", loader) suite ...
StarcoderdataPython
1711459
from unicon.plugins.iosxe.statemachine import IosXESingleRpStateMachine from unicon.eal.dialogs import Dialog, Statement from ..patterns import IosXEPatterns patterns = IosXEPatterns() class SDWANSingleRpStateMachine(IosXESingleRpStateMachine): config_command = 'config-transaction' def create(self): ...
StarcoderdataPython
4810772
<filename>Client/App/Core/Engine/Entities/Goal.py from . import Entity from ...DataTypes.Standard import Vector from ....UI.CustomElements.Sprites import EmptySprite class Goal(Entity): def __init__(self,P1, P2,name, *args, horizontal = False, **kwargs): super().__init__(EmptySprite(), dynamic=False, ...
StarcoderdataPython
1677890
import argparse import json import pathlib import numpy as np from shutil import copyfile def main(): parser = argparse.ArgumentParser() parser.add_argument("prediction_file") parser.add_argument("--dataset_loc", default="./imagenet-vid-robust") args = parser.parse_args() results = {} with op...
StarcoderdataPython
1769227
<gh_stars>1-10 import unittest import nose class TestImageRecognition(unittest.TestCase): pass if __name__=='__main__': unittest.main()
StarcoderdataPython
77066
<reponame>cardin-higley-lab/CBASS<filename>python/Pipeline/Utilities/CBASS_U_MultiChannelTemplateMatching.py def MultiChannelTemplateMatching(db2Signal, db2Template, blCenter, blNormalize): ''' Synopsis: DB1SCORE = CBASS_U_MultiChannelTemplateMatching(DB2SIGNAL, DB2TEMPLATE, [BLNORM]) Returns a score DB1SCORE indicativ...
StarcoderdataPython
4825766
<reponame>alchem0x2A/vasp-interactive-test """Compare results for relaxation of H2 molecule using VaspInteractive vs Vasp internal vs Vasp SinglePoint + BFGS using the same force stop criteria the energy results should be almost identical Even if the WAVECAR is reload during the relaxation, VaspInteractive...
StarcoderdataPython
3385977
<gh_stars>100-1000 #!/usr/bin/env python3 import argparse from util.common import check_pid_exists from util.constants import CommandLineStr if __name__ == "__main__": aparser = argparse.ArgumentParser( description="Check if the given PIDs exist.") aparser.add_argument("pids", type=int, nargs="+", hel...
StarcoderdataPython
10488
<filename>sum.py #sum(iterable, start=0, /) #Return the sum of a 'start' value (default: 0) plus an iterable of numbers #When the iterable is empty, return the start value. '''This function is intended specifically for use with numeric values and may reject non-numeric types.''' a = [1,3,5,7,9,4,6,2,8] ...
StarcoderdataPython
1683237
# -*- coding: utf-8 -*- # Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and Contributors # See license.txt from __future__ import unicode_literals import frappe, erpnext import unittest from erpnext.hr.doctype.employee.test_employee import make_employee from erpnext.hr.utils import DuplicateDeclarationError class...
StarcoderdataPython
1619568
""" Questão 2 do laboratorio 7: Interpolação por MMQ pela seria de Fourier(exponencial) """ import numpy as np from math import pi, sin import matplotlib.pyplot as plt def sistemaAumentado(x, y, dim): m = len(x) A = np.empty((dim, dim)) b = np.empty((dim)) soma = [] for i in range(0, dim + 2): ...
StarcoderdataPython
112428
<reponame>SaintGimp/BeagleBoneHardware import datetime, numpy, scipy, pandas import matplotlib.pyplot as plt print "Loading data" df = pandas.read_json("/Users/elee/Downloads/geiger.json", orient='records', dtype={'cpm' : 'int64', 'device_time' : 'datetime64[ns]', 'timestamp' : 'datetime64[ns]', 'pressure': 'float64',...
StarcoderdataPython
40390
#!/usr/bin/env python import RTxxx_memcore import RTxxx_memdef import RTyyyy_memcore import RTyyyy_memdef import memcore import memdef __all__ = ["RTxxx_memcore", "RTxxx_memdef", "RTyyyy_memcore", "RTyyyy_memdef", "memcore", "memdef"]
StarcoderdataPython
1786616
import numpy as np import pytest import rasterio from rasterio import windows DATA_WINDOW = ((3, 5), (2, 6)) def test_index(): with rasterio.open('tests/data/RGB.byte.tif') as src: left, bottom, right, top = src.bounds assert src.index(left, top) == (0, 0) assert src.index(right, top) ==...
StarcoderdataPython
45106
<reponame>ClayAssis/HEALTH-INSURANCE-CROSS-SELL-PREDICTION import joblib import pandas as pd from crosssell.CrossSell import CrossSell from flask import Flask, request, Response ## Loading Model model = joblib.load('../models/linear_regression_cycle1.joblib') ## initialize API app = Flask(__name__) @app.route('/cros...
StarcoderdataPython
3219820
import unittest import tempfile import shutil import os import io from format_templates.format_templates import replace_iter, find_iters, render class TestFormatting(unittest.TestCase): def setUp(self): self.data = { "name": "World", "numbers": xrange(1,5), "nested": {...
StarcoderdataPython
3216320
""" Train a model on TACRED. """ import os from datetime import datetime import time import numpy as np import random import argparse from shutil import copyfile import torch import torch.nn as nn import torch.optim as optim from torch.autograd import Variable from data.loader import DataLoader from model.rnn import ...
StarcoderdataPython
131643
<filename>custom_components/foobar/__init__.py<gh_stars>0 """foobar2000 media player custom component init file"""
StarcoderdataPython
132053
#!/bin/python import sys; from Thesis.cluster.RiakCluster import RiakCluster; from Thesis.availability.availabilityBenchmark import runAvailabilityBenchmark NORMAL_BINDING = 'riak'; CONSISTENCY_BINDING = 'riak_consistency'; IPS_IN_CLUSTER = ['172.16.33.14', '172.16.33.15', '172.16.33.16', '172.16.33.17', '172.16.33....
StarcoderdataPython
4836521
import unittest def getStrings(): return ( "world", "how", "are", "you" ) class ListSliceTests( unittest.TestCase ): def test_ListSlice_01( self ): l = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ] assert l[ 3: 8 ] == [ 3, 4, 5, 6, 7 ] def test_ListSlice_02( self ): l = [ 0, 1, 2, 3, 4, 5, 6,...
StarcoderdataPython
1720503
<filename>van/static/tests/test_cdn.py import os import sys import shutil import tempfile from unittest import TestCase from mock import patch, Mock _PY3 = sys.version_info[0] == 3 if _PY3: def b(s): return s.encode("latin-1") else: def b(s): return s def _iter_to_dict(i): from van.static...
StarcoderdataPython
10934
import numpy as np from prml.dimreduction.pca import PCA class BayesianPCA(PCA): def fit(self, X, iter_max=100, initial="random"): """ empirical bayes estimation of pca parameters Parameters ---------- X : (sample_size, n_features) ndarray input data i...
StarcoderdataPython
3392547
import unittest from katas.kyu_8.leonardo_dicaprio_and_oscars import leo class LeonardoTestCase(unittest.TestCase): def test_equals(self): self.assertEqual(leo(88), 'Leo finally won the oscar! Leo is happy') def test_equals_2(self): self.assertEqual(leo(86), 'Not even for Wolf of wallstreet?...
StarcoderdataPython
1660442
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from typing import Optional, Tuple import torch from torch import Tensor from torch import nn as nn from torch import o...
StarcoderdataPython
3202012
#!/usr/bin/env python3 # ============================================================================== # Copyright 2018-2020 Intel Corporation # # 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 Licens...
StarcoderdataPython
3260182
import gi gi.require_version(namespace='Gtk', version='3.0') from gi.repository import Gtk class MainWindow(Gtk.ApplicationWindow): def __init__(self): super().__init__() self.set_title(title='GTK Entry') self.set_default_size(width=1366 / 2, height=768 / 2) self.set_position(posi...
StarcoderdataPython
1688651
<reponame>haeussma/PyEnzyme from pyenzyme.enzymeml.core.vessel import Vessel class TestVessel: def test_content(self): """Tests consistency of content""" vessel = Vessel( name="SomeVessel", volume=100.0, unit="ml", constant=True, id="v0", meta_id="undefined", uri="URI", c...
StarcoderdataPython
1600763
# Generated by Django 3.1.2 on 2020-10-10 15:38 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('CheeseQuery', '0001_initial'), ] operations = [ migrations.RenameField( model_name='cheese', old_name='origin', ...
StarcoderdataPython
52762
<gh_stars>1-10 ''' ================================================ ## VOICEBOOK REPOSITORY ## ================================================ repository name: voicebook repository version: 1.0 repository link: https://github.com/jim-schwoebel/voicebook author: <NAME> author contact:...
StarcoderdataPython
1735983
<reponame>RookieHong/python-objectness<gh_stars>10-100 import numpy as np import mat4py from easydict import EasyDict as edict import os def integrate_bayes(cues, score, params): likelihood = [] for i, cue in enumerate(cues): if cue == 'MS': struct = mat4py.loadmat(os.path.join(p...
StarcoderdataPython
3271818
<reponame>audurand/momab<gh_stars>1-10 import numpy def run_somab(setting, algorithm, nb_episodes=10000): cumul_regret = [0] options = numpy.random.rand(len(means)) for t in range(nb_episodes): # select a_t a_t = numpy.argmax(options) # play a_t and observe outcome z_...
StarcoderdataPython
1670731
<reponame>auwasu/scanobjectnn-1 import argparse import math from datetime import datetime import h5py import numpy as np import tensorflow as tf import socket import importlib import os import sys BASE_DIR = os.path.dirname(os.path.abspath(__file__)) ROOT_DIR = BASE_DIR sys.path.append(BASE_DIR) sys.path.append(os.path...
StarcoderdataPython
4837460
<gh_stars>0 #!/usr/bin/env python # -*- coding: utf-8 -*- import os import pkg_resources from configobj import ConfigObj from ruamel.yaml import YAML from ruamel.yaml.error import YAMLError from schema import Schema, Or, Optional from gmprocess.utils import constants CONF_SCHEMA = Schema( { "user": {"n...
StarcoderdataPython
3372672
<filename>appengine/monorail/api/v3/test/projects_servicer_test.py # Copyright 2020 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file or at # https://developers.google.com/open-source/licenses/bsd """Tests for the hotlists ser...
StarcoderdataPython
112102
<reponame>sharonkorir/picha from email.mime import image from unicodedata import name from django.test import TestCase from .models import location, category, Image # Create your tests here. class ImageTestClass(TestCase): ''' Test class that defines test cases for the image class behaviours. Args: ...
StarcoderdataPython
1668153
from typing import Optional, Tuple class FastqParser: """ A simple fastq parser that parses each read (four lines) of a fastq file """ def __init__(self, file: str): self.__fastq = open(file, 'r') def __enter__(self): return self def __exit__(self, exc_type, exc_...
StarcoderdataPython
1736401
# -*- encoding: utf-8 -*- from pygithub3.services.base import Service, MimeTypeMixin class Commits(Service, MimeTypeMixin): """ Consume `Commits API <http://developer.github.com/v3/repos/commits>`_ .. note:: This service support :ref:`mimetypes-section` configuration """ def list(self, ...
StarcoderdataPython
4842047
from pandac.PandaModules import * from toontown.toonbase import ToontownGlobals from direct.distributed import DistributedObject from direct.directnotify import DirectNotifyGlobal from toontown.toonbase import TTLocalizer class LobbyManager(DistributedObject.DistributedObject): notify = DirectNotifyGlobal.directNo...
StarcoderdataPython
107814
from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('core.urls', namespace='core')), path('accounts/', include('accounts.urls', namespace=...
StarcoderdataPython
1686882
<reponame>iridesc/ProxyPoolWithUI from operator import index import re import time import random import requests from pyquery import PyQuery as pq from fetchers.BaseFetcher import BaseFetcher class XiaoShuFetcher(BaseFetcher): """ http://www.xsdaili.cn/ 代码由 [Zealot666](https://github.com/Zealot666) 提供 ...
StarcoderdataPython
1731275
"""CSV file export.""" import os import sparv.util as util from sparv import Annotation, Config, Document, Export, ExportAnnotations, SourceAnnotations, exporter logger = util.get_logger(__name__) @exporter("CSV export", config=[ Config("csv_export.delimiter", default="\t", description="Delimiter separating fi...
StarcoderdataPython
1755146
from math import sqrt import torch.nn as nn import torch.nn.functional as F import torch.nn.init as init import torchvision.models as models __all__ = [ 'PixelShuffleCNN', 'GradualPixelShuffleCNN', ] class PixelShuffleCNN(nn.Module): def __init__(self, upscale_factor): super(PixelShuffleCNN, self...
StarcoderdataPython
4818953
#!/usr/bin/python3 import asyncio import bleak import bleak.utils import logging import random import struct import datetime from bleak import _logger as logger TARGET_ADDRESS = "F1:C8:1A:8D:37:8B" TARGET_LEAF_ADDRESS = "F1:C8:1A:8D:37:8B" #"E2:45:E5:25:22:F0" SERVICE_UUID = "21171523-4740-4AA5-B66B-5D2C6851CC5...
StarcoderdataPython
4836135
<gh_stars>1-10 """Tools for sending email.""" from email import Charset, Encoders from email.MIMEText import MIMEText from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email.Header import Header from email.Utils import formatdate, parseaddr, formataddr import mimetypes import os imp...
StarcoderdataPython
5781
<filename>ois_api_client/v3_0/dto/Lines.py from typing import List from dataclasses import dataclass from .Line import Line @dataclass class Lines: """Product / service items :param merged_item_indicator: Indicates whether the data exchange contains merged line data due to size reduction :param line: Pro...
StarcoderdataPython
3236441
<filename>ltr/models/loss/__init__.py from .target_classification import LBHinge, LBHingev2, IsTargetCellLoss, TrackingClassificationAccuracy
StarcoderdataPython
1791454
# coding = utf-8 # using namespace std """ """ class LocalTbs(object): """ """ ident_guide = " "*4 def get_schema_packs(self, data: list) -> str: """ :param data: :return: """ rs = "" for i in data: rs += str(i[1]) + " -> \n" ...
StarcoderdataPython
3337079
from django.shortcuts import render from django.http import HttpResponse,StreamingHttpResponse, HttpResponseServerError,HttpResponseRedirect from django.shortcuts import redirect from django.views.decorators import gzip from imutils.video import VideoStream from imutils.video import FPS import cv2 import time import im...
StarcoderdataPython
3369051
from django.db import models class Person(models.Model): last_name = models.CharField(max_length=255) first_name = models.CharField(max_length=255) profile = models.CharField(max_length=64) class Face(models.Model): person = models.ForeignKey('Person', on_delete=models.CASCADE) picture = models.Im...
StarcoderdataPython
87253
<filename>sutils/applications/cancel/cancel.py<gh_stars>0 import sys from . import core def run(options): if options['all']: run_all(force=options['force']) elif options['last'] is not None: run_last(options['last'], force=options['force']) elif options['first'] is not None: run_fir...
StarcoderdataPython
50129
<filename>lvmsurveysim/utils/plot.py #!/usr/bin/env python # -*- coding: utf-8 -*- # # @Author: <NAME> (<EMAIL>) # @Date: 2017-10-17 # @Filename: plot.py # @License: BSD 3-clause (http://www.opensource.org/licenses/BSD-3-Clause) # # @Last modified by: <NAME> (<EMAIL>) # @Last modified time: 2019-03-29 01:23:34 import ...
StarcoderdataPython
3388055
<filename>dlispy/VisibleRecord.py from .RCReader import * from .common import * logger = myLogger("VisibleRecord") from .LogicalRecordSegment import parseLRSegment class VisibleRecord(object): """ Visible Record consists of three parts in order: - Visible Record Length expressed in Representation Code ...
StarcoderdataPython
3387818
import time from argparse import ArgumentParser from django.contrib.auth.models import User from django.core.management.base import BaseCommand from django.db.models import Q class Command(BaseCommand): help = 'Create test users' def add_arguments(self, parser: ArgumentParser): parser.add_argument('...
StarcoderdataPython
1762560
from simple_pid import PID from mpu import mpu from dual_tb9051ftg_rpi import motors, MAX_SPEED class pid: def __init__(self, timer_tick): sample_time = timer_tick / 1000. self.Kp = 20 self.Ki = 5 self.Kd = -0.2 self.left_setpoint = 0 self.pid = PID(Kp=self.Kp, Ki=...
StarcoderdataPython
1678738
<filename>tick/base/learner/__init__.py from .learner_glm import LearnerGLM from .learner_optim import LearnerOptim
StarcoderdataPython
3257118
#Design a method to find the frequency of occurrences of any given word in a book. What if we were running this algorithm multiple times? #Hint 488: Think about what the best conceivable runtime is for this problem. If your solution matches the best # conceivable runtime, then you probablycan't do any better. #Hint 53...
StarcoderdataPython
124765
<gh_stars>0 # Generated by Django 3.0.3 on 2020-03-25 12:53 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Photos', fields=[ ('id', models...
StarcoderdataPython
38643
<filename>simulation/aws-robomaker-sample-application-deepracer/simulation_ws/src/sagemaker_rl_agent/markov/rollout_worker.py """ this rollout worker: - restores a model from disk - evaluates a predefined number of episodes - contributes them to a distributed memory - exits """ import argparse import json import math...
StarcoderdataPython
3282902
import cv2 import numpy as np # load image img = cv2.imread('image.jpg') rsz_img = cv2.resize(img, None, fx=0.25, fy=0.25) # resize since image is huge gray = cv2.cvtColor(rsz_img, cv2.COLOR_BGR2GRAY) # convert to grayscale # threshold to get just the signature retval, thresh_gray = cv2.threshold(gray, thre...
StarcoderdataPython
3309711
# Return: # podemos definir que devuelve la funcion. # luego de ejecutar devuelve ese valor de la funcion # por defecto devuelve: none # es decir, sino se define return, ejecutará y devolverá none. def cubo_de_numero(numero): return numero * numero * numero # si pongo algo luedo del return, ya no se ejecutara pr...
StarcoderdataPython
3397872
<filename>syspower.py<gh_stars>0 #!/usr/bin/env python3 '''syspower: A platform agnostic library for power state management. For any given operation, we first determine the platform type, and then try to use some extra stuff to narrow down what specific methods might work on this system for the requested oper...
StarcoderdataPython
176530
import sys import os import pprint import unittest __GALAXY_ROOT__ = os.getcwd() + '/../../../' sys.path.append( __GALAXY_ROOT__ + 'lib' ) from galaxy import eggs eggs.require( 'SQLAlchemy >= 0.4' ) import sqlalchemy from galaxy import model from galaxy import exceptions from galaxy.util.bunch import Bunch import m...
StarcoderdataPython
1642845
import os import pandas as pd import datetime from timeit import default_timer as timer import argparse #Start timer start = timer() time = datetime.datetime.now().strftime("%Y-%m-%d: %H:%M") print "Start running script at: {0}".format(time) ###Parse arguments parser = argparse.ArgumentParser(description = "This scri...
StarcoderdataPython
1638062
# [LICENSE] # Copyright (c) 2018, Alliance for Sustainable Energy. # All rights reserved. # # Redistribution and use in source and binary forms, # with or without modification, are permitted provided # that the following conditions are met: # # 1. Redistributions of source code must retain the above # cop...
StarcoderdataPython
1798268
<gh_stars>1-10 import numpy as np import scipy.io as sio class SVHN: def __init__(self, file_path, n_classes, use_extra=False, gray=False, normalize=False): self.n_classes = n_classes # Load Train Set train = sio.loadmat(file_path + "/train_32x32.mat") self.train_labels = self.__...
StarcoderdataPython
76114
<reponame>jpmarques19/tensorflwo-test class Fake(object): def __init__(self, shape): self.shape = shape
StarcoderdataPython