id
stringlengths
2
8
text
stringlengths
16
264k
dataset_id
stringclasses
1 value
9699454
<reponame>AdamShechter9/aws-cloudtrail-athena-script<gh_stars>1-10 #!/bin/python3 """ At1 <NAME> Python script to generate all resources needed to start CloudTrail logging on AWS Steps: 1. Creating S3 Bucket 2. Attaching S3 Bucket Policy 3. Creating new CloudWatch Log Grou 4. Creating new IAM Role for Cloudtrail 5. C...
StarcoderdataPython
1821253
<reponame>sleyzerzon/soar import itertools from PddlState import PddlState, iterator_is_empty from PddlStateSmlAdapter import PddlStateSmlAdapter class blocks_world: def __init__(self, agent): if agent: self.state = PddlStateSmlAdapter(self, agent) else: self.state = PddlSta...
StarcoderdataPython
1814452
<reponame>jerloo/pyidenticon import unittest import os from pyidenticon import make class MyTestCase(unittest.TestCase): def setUp(self): if not os.path.exists('data'): os.mkdir('data') def test_basic_make(self): img = make('basic') img.save('data/basic.png') img...
StarcoderdataPython
8103895
import json import os import pickle from sklearn.feature_extraction.text import CountVectorizer from sklearn.naive_bayes import MultinomialNB # from semantic.domain_models import sempryv_models as database class ThryvePulsoTrainer(object): def __init__(self): self.train_data_synthetic = [] self...
StarcoderdataPython
65388
<reponame>nishantkr18/PettingZoo<filename>pettingzoo/butterfly/pistonball/pistonball.py import os os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = 'hide' import pygame import pymunk import pymunk.pygame_util import math import numpy as np import gym from gym.utils import seeding from pettingzoo import AECEnv from pettingzoo....
StarcoderdataPython
1824961
import json import gzip import sys import os import socket from io import BytesIO from .utils import timestamp, base64_encode from .runtime import runtime_info if runtime_info.PYTHON_2: from urllib2 import urlopen from urllib2 import Request from urllib import urlencode else: from urllib.request imp...
StarcoderdataPython
8091298
<reponame>styam/coading_practice """ Write a Python program to create a lambda function that adds 15 to a given number passed in as an argument, also create a lambda function that multiplies argument x with argument y and print the result. """ add_number = lambda x:x+15 multiplies = lambda x, y:x*y print(add_number(5...
StarcoderdataPython
83713
""" Will run "shellfoundry install" on all shell subdirectories of current folder """ import os import subprocess def install_shell(dir_name): my_path = os.path.abspath(__file__) mydir = os.path.dirname(my_path) shell_dir_path = os.path.join(mydir, dir_name) subprocess.call(["shellfoundry", "install"...
StarcoderdataPython
12827303
<gh_stars>1-10 # -*- coding: utf-8 -*- # Licensed under a MIT style license - see LICENSE.rst """ Access spectroscopic data for a single BOSS target. """ from __future__ import division, print_function from six import binary_type import re import numpy as np import numpy.ma import fitsio import astropy.table im...
StarcoderdataPython
1718851
<gh_stars>0 VERSION='0.8.1'
StarcoderdataPython
1661206
import os import MaxwellConstruction as mx import numpy as np import matplotlib.pyplot as plt import argparse def run_pr_case( a_eos, b_eos, w_eos, sigma, beta, TrList ): """ Ejecucion de casos de construccion de Maxwell """ # Directorio del caso y limpieza main_dir = os.getcwd() ...
StarcoderdataPython
3275705
from rest_framework import serializers from presentation.models import Follower class FollowerSerializer(serializers.ModelSerializer): class Meta: model = Follower fields = ['type', 'owner', 'items']
StarcoderdataPython
6505449
#!/usr/bin/env python import time import asyncio import logging from typing import ( Any, AsyncIterable, List, Optional, ) from hummingbot.core.data_type.user_stream_tracker_data_source import UserStreamTrackerDataSource from hummingbot.logger import HummingbotLogger from .peatio_constants import Const...
StarcoderdataPython
3459121
<reponame>zhenglab/cxxnet<filename>example/MNIST/mnist.py<gh_stars>1-10 import sys sys.path.append('../../wrapper/') import cxxnet import numpy as np data = cxxnet.DataIter(""" iter = mnist path_img = "./data/train-images-idx3-ubyte.gz" path_label = "./data/train-labels-idx1-ubyte.gz" shuffle = 1 iter = en...
StarcoderdataPython
6540940
#!/usr/bin/env python # 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 # # Authors: # - <NAME>, <EMAIL>, 2017-2022 import logging import os import t...
StarcoderdataPython
3546422
from utils import * from Sprint import Sprint from stasis.Singleton import get as db from stasis.ActiveRecord import ActiveRecord, link class Group(ActiveRecord): sprint = link(Sprint, 'sprintid') def __init__(self, sprintid, name, seq = None, deletable = True, id = None): ActiveRecord.__init__(self) self.id =...
StarcoderdataPython
1778655
<gh_stars>0 """Args: param1 (int): byte as int value in binary Returns: True if input indicates a sys_ex event, False if otherwise. """ def is_sys_ex(n): # hex status bytes 0xF0 and 0xF7 # dec values between 240 and 247 dec_val = int(n, 2) if dec_val >= 240 or dec_val <= 247: ...
StarcoderdataPython
6636568
<filename>qiskit_metal/_gui/endcap_q3d_ui.py # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'endcap_q3d_ui.ui', # licensing of 'endcap_q3d_ui.ui' applies. # # Created: Thu Jan 7 16:03:08 2021 # by: pyside2-uic running on PySide2 5.13.2 # # WARNING! All changes made in this file wil...
StarcoderdataPython
1910911
import os import dj_database_url from .common import * # Production settings # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get("SECRET_KEY") # SECURITY WARNING: don't run with debug turned on in pr...
StarcoderdataPython
3488078
# imports required from django.shortcuts import render,redirect from django.contrib.auth import authenticate,login,logout from django.contrib.auth.models import User from django.contrib import messages from app.models import * from datetime import datetime, timedelta from django.contrib.auth.decorators import login_...
StarcoderdataPython
3226618
#!/usr/bin/env python from __future__ import print_function import cx_Oracle import datetime import calendar import sys import logging import CondCore.Utilities.conddb_serialization_metadata as sm import CondCore.Utilities.credentials as auth import CondCore.Utilities.conddb_time as conddb_time import os authPathEnvV...
StarcoderdataPython
9771350
import numpy as np import gym class POMDPWrapper(gym.ObservationWrapper): def __init__(self, env_name, pomdp_type='remove_velocity', flicker_prob=0.2, random_noise_sigma=0.1, random_sensor_missing_prob=0.1): """ :param env_name: :param pomdp_type: 1. remove_v...
StarcoderdataPython
326998
<gh_stars>0 # -*- coding: utf-8 -*- # # 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 wr...
StarcoderdataPython
6697399
<reponame>drhagen/nox-poetry """Unit tests for the poetry module.""" from pathlib import Path from nox_poetry import poetry def test_config_non_ascii(tmp_path: Path) -> None: """It decodes non-ASCII characters in pyproject.toml.""" text = """\ [tool.poetry] name = "África" """ path = tmp_path / "pyproje...
StarcoderdataPython
11372825
<filename>pymc/sandbox/test_twalk.py from pymc.sandbox.TWalk import * from pymc import * from numpy import random, inf import pdb """ Test model for T-walk algorithm: Suppose x_{i,j} ~ Be( theta_j ), i=0,1,2,...,n_j-1, ind. j=0,1,2 But it is known that 0 < theta_0 < theta_3 < theta_2 < 1 """ theta_true = array([ 0....
StarcoderdataPython
165270
<filename>bin/expr_parse.py #!/usr/bin/env python2 """ expr_parse.py -- Demo for translation. types/run.sh expr-parse """ from __future__ import print_function import sys from _devbuild.gen import grammar_nt from _devbuild.gen.syntax_asdl import source from asdl import format as fmt from core import alloc from core ...
StarcoderdataPython
3281882
<reponame>pingjuiliao/cb-multios #!/usr/bin/env python # # Copyright (C) 2014 Narf Industries <<EMAIL>> # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including withou...
StarcoderdataPython
1619166
""" Group all classes from macro/build""" from . import ( cavern_construction, evochamber_construction, expansion, extractor_construction, transformation_to_hive, hydraden_construction, transformation_to_lair, pit_construction, pool_construction, spine_construction, spire_con...
StarcoderdataPython
219122
<filename>boxvariable.py import pandas as pd import matplotlib.pyplot as plt import numpy as np data = pd.read_csv("IrisDataSet.csv") # box and whisker plots data.plot(kind='box', subplots=True, layout=(2,2), sharex=False, sharey=False) plt.show() #https://machinelearningmastery.com/machine-learning-in-py...
StarcoderdataPython
350485
<filename>src/villains/migrations/0001_initial.py # -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-02-27 18:35 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ('series', '0002_auto_20...
StarcoderdataPython
12861830
<filename>tests/test_qml.py """Tests for `prettyqt` package.""" import pathlib import pytest from prettyqt import core, qml from prettyqt.utils import InvalidParamError # def test_jsvalue(): # val = qml.JSValue(2) # val["test"] = 1 # assert val["test"].toInt() == 1 # assert "test" in val # asse...
StarcoderdataPython
3483005
import matplotlib matplotlib.use('agg') # now it works via ssh connection import os import mne import sys import glob import pickle sys.path.append('/home/dvmoors1/BB/ANALYSIS/DvM') import numpy as np import seaborn as sns import matplotlib.pyplot as plt from IPython import embed from beh_analyses.PreProcessing impo...
StarcoderdataPython
4984197
import cv2 import numpy as np def findSameAngle(points, errorRate = 0.2, minR = 10): 편차 = points - points.mean((0,1)).reshape(1, 1, 2) # N , 1, 2 제곱 = 편차 ** 2 # N , 1, 2, 반지름 = np.sqrt( 제곱.sum((1,2))) # N 반지름평균 = 반지름.mean() if(반지름평균 > minR): 반지름비율 = 반지름 / 반지름평균 # 다른언어에서 변환 타입 주의...
StarcoderdataPython
11393418
<filename>Source/Thttil/__init__.py # MIT License # Copyright (c) 2019 <NAME> # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # ...
StarcoderdataPython
325313
<filename>cloudentries/common/lifecycles/security_group.py # Copyright (c) 2021 Qianyun, Inc. All rights reserved. from abstract_plugin.platforms.common.base import CommonResource class CommonSecurityGroup(CommonResource): pass
StarcoderdataPython
9788065
<reponame>GarrickHe/sonic-mgmt """This module provides ptfadapter fixture to be used by tests to send/receive traffic via PTF ports""" import pytest from ptfadapter import PtfTestAdapter from ansible_host import AnsibleHost DEFAULT_PTF_NN_PORT = 10900 DEFAULT_DEVICE_NUM = 0 ETH_PFX = 'eth' def get_ifaces(netdev_ou...
StarcoderdataPython
11370107
# Generated by Django 3.0.8 on 2020-07-28 18:32 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] ope...
StarcoderdataPython
6641888
<filename>videoflow/utils/system.py import subprocess import os def get_number_of_gpus() -> int: ''' Returns the number of gpus in the system ''' try: n = str(subprocess.check_output(["nvidia-smi", "-L"])).count('UUID') return n except FileNotFoundError: return 0 def get_sy...
StarcoderdataPython
8072353
<filename>bazel/docker/bazel_dependencies.bzl def rules_docker_dependencies(): native.git_repository( name = "io_bazel_rules_docker", remote = "https://github.com/bazelbuild/rules_docker.git", tag = "v0.5.1" ) def rules_package_manager_dependencies(): native.git_repository( name = "distro...
StarcoderdataPython
222879
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2013 The Plaso Project Authors. # Please see the AUTHORS file for details on individual authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the L...
StarcoderdataPython
6579258
from abc import ABCMeta class ValueObject(object): __metaclass__ = ABCMeta def __init__(self, value): self.__value = value def get_value(self): return self.__value def __eq__(self, other): return self.get_value() == other.get_value() \ and isinstance(other, se...
StarcoderdataPython
1826305
<gh_stars>1-10 from django.shortcuts import render from django.contrib.auth.decorators import login_required from django.shortcuts import redirect, render from django.contrib import messages from apps.Accused.models import AccusedPerson from apps.Cells.forms import AddCellForm, EditCellForm from apps.Cells.models impor...
StarcoderdataPython
13473
<reponame>RuanBarretodosSantos/python cont = 3 t1 = 0 t2 = 1 print('-----' * 12) print('Sequência de Fibonacci') print('-----' * 12) valor = int(input('Quantos termos você quer mostrar ? ')) print('~~~~~' * 12) print(f'{t1} ➙ {t2} ' , end='➙ ') while cont <= valor: t3 = t1 + t2 print(f' {t3}', end=' ➙ ') ...
StarcoderdataPython
1829840
""" Maps: ComboMaps =============== We will use an example where we want a 1D layered earth as our model, but we want to map this to a 2D discretization to do our forward modeling. We will also assume that we are working in log conductivity still, so after the transformation we map to conductivity space. To do this we...
StarcoderdataPython
6622532
<filename>qa/tasks/util/rados.py import logging from teuthology import misc as teuthology log = logging.getLogger(__name__) def rados(ctx, remote, cmd, wait=True, check_status=False): testdir = teuthology.get_testdir(ctx) log.info("rados %s" % ' '.join(cmd)) pre = [ 'adjust-ulimits', 'cep...
StarcoderdataPython
4861215
import gym from agent.DQN import DeepQNetwork import numpy as np import argparse import matplotlib.pyplot as plt def train(RL, env): total_steps = 0 observation = env.reset() while True: # if total_steps - MEMORY_SIZE > 8000: env.render() action = RL.choose_action(observation) f...
StarcoderdataPython
5089002
from enum import IntFlag from typing import Optional, Union from .operation import Operation from .utils import check_ed25519_public_key from .. import xdr as stellar_xdr from ..keypair import Keypair from ..signer import Signer from ..strkey import StrKey __all__ = ["AuthorizationFlag", "SetOptions"] class Authori...
StarcoderdataPython
3313416
""" Basic Character Redaction """ import sys try: import pandas as pd except ImportError: pd = None from gretel_client.transformers import ( RedactWithCharConfig, DataPath, DataTransformPipeline, StringMask, ) xf = [RedactWithCharConfig()] xf2 = [RedactWithCharConfig(char="Y")] paths = [ ...
StarcoderdataPython
3304964
<gh_stars>1-10 import unittest from bltest import attr from lace.cache import sc from lace.serialization import wrl, obj @attr('missing_assets') class TestWRL(unittest.TestCase): def setUp(self): self.test_wrl_url = "s3://bodylabs-korper-assets/is/ps/shared/data/body/korper_testdata/test_wrl.wrl" s...
StarcoderdataPython
8005564
<gh_stars>1-10 from dodo_commands.framework.command_map import get_command_map as _get_command_map from dodo_commands.framework.command_path import get_command_dirs_from_config from dodo_commands.framework.container.facets import ( Commands, Config, Layers, i_, o_, register, ) from dodo_commands...
StarcoderdataPython
11397672
# Copyright 2013-2019 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 * class RDesolve(RPackage): """Functions that solve initial value problems of a system of first-or...
StarcoderdataPython
4919421
<filename>Greay_Atom_Courses/code.py # -------------- # Code starts here #Intruction # Create a 'class_1' list and pass the elements '<NAME>','<NAME>','<NAME>','<NAME>'. class_1 = ['<NAME>','<NAME>','<NAME>','<NAME>'] #Create a 'class_2' list and pass the elements '<NAME>','<NAME>','<NAME>'. class_2 = ['<NAME>','<NAME>...
StarcoderdataPython
9759979
<filename>3d/marin/marin.py from math import * import proteus.MeshTools from proteus import Domain from proteus.default_n import * from proteus.Profiling import logEvent # Discretization -- input options #Refinement=8#4-32 cores #Refinement=12 Refinement=24 genMesh=True useOldPETSc=False useSuperlu=False space...
StarcoderdataPython
170686
#compdef createmodule.py local arguments arguments=( '(- * :)'{-h,--help}'[show this help message and exit]' {-p,--prefix}'[specify path prefix]' '--noprefix[do not generate a prefix]' '*:filename:_files' ) _arguments -s $arguments
StarcoderdataPython
141725
import pytest @pytest.fixture def validator(): """Return validator fixture.""" from json_validator import JsonValidator return JsonValidator @pytest.fixture def dumps(): """Return json dumps fixture.""" from json import dumps return dumps
StarcoderdataPython
1662918
<filename>pyhalo/api.py<gh_stars>1-10 __author__ = '<NAME> (@DamonLPollard)' import requests class HaloFour(): def __init__(self, waypoint_token): self.waypoint_token = waypoint_token def get_api_version(self): url = "https://app.halowaypoint.com/en-US/home/version" return self._fetc...
StarcoderdataPython
1711241
<filename>cryptex/order.py class Order(object): ''' Basic order ''' order_type = 0 def __init__(self, order_id, base_currency, counter_currency, datetime, amount, price): self.order_id = order_id self.base_currency = base_currency self.counter_currency = count...
StarcoderdataPython
12835327
import logging import itertools import numpy as np from scipy.optimize import OptimizeResult, minimize_scalar import scipy.constants from .util import find_vertex_x_of_positive_parabola def scalar_discrete_gap_filling_minimizer( fun, bracket, args=(), tol=1.0, maxfev=None, maxiter=100, callback=None, verbos...
StarcoderdataPython
11251912
<gh_stars>100-1000 class Frame(BaseSheet): '''Maintains the data as records. ''' def __init__(self, frame=None, columns=None, nan=None): self._data = [] BaseSheet.__init__(self, frame, columns, nan) @property def info(self): new_m_v = map(str, self._missing) max_n =...
StarcoderdataPython
1807779
<reponame>MakeSenseCorp/nodes-v3<filename>2022/classes/StockMarketRemote.py #!/usr/bin/python import os import sys import signal import json import time import _thread import threading import base64 import datetime from datetime import date import queue import math from classes import StockMarketAPI from classes impor...
StarcoderdataPython
4895602
speakers={} f=open("speakers_class.csv",mode="r",encoding="utf-8") content=f.read() lines=content.split("\n") for line in lines[1:-1]: spk,id_class=line.split(";") speakers[spk]=id_class f.close() f=open("turns_all_info.csv",mode="r",encoding="utf-8") fo=open("turns_all_info_id_class.csv",mode="w",encoding="...
StarcoderdataPython
5080880
x1=int(input("Enter the Value: ")) x2=int(input("Enter the Value: ")) y1=int(input("Enter the Value: ")) y2=int(input("Enter the Value: ")) distance=((x2-x1)**2 + (y2-y1)**2)**0.5 print(round(distance,4))
StarcoderdataPython
1747828
import os import pathlib import pickle import json def subdirs(folder, join=True, prefix=None, suffix=None, sort=True): if join: l = os.path.join else: l = lambda x, y: y res = [l(folder, i) for i in os.listdir(folder) if os.path.isdir(os.path.join(folder, i)) and (prefix is No...
StarcoderdataPython
6437414
# Copyright 2020 Lorna Authors. 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-2.0 # # Unless required by appli...
StarcoderdataPython
6577695
<filename>collecting users/fake-user_collector.py # -*- coding: utf-8 -*- """ Created on Mar 15 2020 @author: GerH """ from selenium import webdriver import time from datetime import datetime import threading import sys from random import randint #this thread takes fake user data from...
StarcoderdataPython
5079552
<reponame>0xdc/wk<filename>wk/models.py from __future__ import unicode_literals from django.db import models class WellKnown(models.Model): key = models.CharField(max_length=255,unique=True) value = models.TextField() def __str__(self): return self.key
StarcoderdataPython
197839
# -*- coding: utf-8 -*- """cerberus_ac plugins module.""" try: from archan import Provider, Argument, DesignStructureMatrix class Privileges(Provider): """Cerberus AC provider for Archan.""" identifier = 'cerberus_ac.Privileges' name = 'Privileges' description = 'Provide matr...
StarcoderdataPython
8189226
from .data_structures import ASPECTDataset # noqa: F401; noqa: F401 from .data_structures import ASPECTUnstructuredIndex # noqa: F401 from .data_structures import ASPECTUnstructuredMesh # noqa: F401 from .fields import ASPECTFieldInfo # noqa: F401 from .io import IOHandlerASPECT # noqa: F401
StarcoderdataPython
9671157
<reponame>betaredex/pfmisc<gh_stars>0 #!/usr/bin/env python3.5 import sys import os import json import pudb try: from ._colors import Colors from .debug import debug from .C_snode import * from .error import * except: from _colors impo...
StarcoderdataPython
4858996
import doctest import todo doctest.testmod(todo)
StarcoderdataPython
3391391
import os import time from kombu import Connection from kombu import Exchange from kombu import Producer from utils import get_logger from utils import RABBITMQ_URI log = get_logger() class Scheduler: def run(self): """ Entry function for this service that runs a RabbitMQ worker through Kombu. ...
StarcoderdataPython
10569
#!/usr/bin/python import sys import re def iptohex(ip): octets = ip.split('.') hex_octets = [] for octet in octets: if int(octet) < 16: hex_octets.append('0' + hex(int(octet))[2:]) else: hex_octets.append(hex(int(oc...
StarcoderdataPython
1920614
<filename>nemoobot/bot/antispam.py import re from typing import Tuple CAPS_WARNING_MESSAGE = 'Calm down! БЕЗ КАПСА ТУТ!' URLS_WARNING_MESSAGE = 'Ссылки в чате запрещены.' BANNED_WORD_WARNING_MESSAGE = 'Аккуратнее с выражениями.' class AntiSpam: def __init__(self, is_active=False, caps=False, urls=False, banned_w...
StarcoderdataPython
9669458
<reponame>winnerineast/taichi import taichi as ti import matplotlib.pyplot as plt import math import sys x = ti.global_var(dt=ti.f32) v = ti.global_var(dt=ti.f32) a = ti.global_var(dt=ti.f32) loss = ti.global_var(dt=ti.f32) damping = ti.global_var(dt=ti.f32) max_timesteps = 1024 * 1024 dt = 0.001 @ti.layout def pla...
StarcoderdataPython
6492499
<reponame>GenBill/notebooks import random import numpy as np import torch import torch.nn as nn import torchvision from IPython import display from torch.utils import data from torchvision import transforms from matplotlib import pyplot as plt mnist_train = torchvision.datasets.FashionMNIST(root='./Datasets/Fashion...
StarcoderdataPython
8137986
# <NAME> # 2/25/2021 # selenium imports from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.by import By # scheduling tasks import schedule import time # import other scripts in directory import settings import functions userAgent = 'Mozilla/5.0 (X11; ...
StarcoderdataPython
3444278
<reponame>tdiprima/code # SomeSound.py audio=file('/dev/dsp', 'wb') def main(): for a in range(0,25,1): for b in range(15,112,1): for c in range(0,1,1): audio.write(chr(127+b)+chr(127+b)+chr(127+b)+chr(127+b)+chr(127-b)+chr(127-b)+chr(127-b)+chr(127-b)) for b in range(112,15,-1): for c in range(0,1,1): ...
StarcoderdataPython
1611797
# -*- coding: utf-8 -*- # Copyright (c) 2021 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 License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
StarcoderdataPython
8022169
from gpiozero import Buzzer from time import sleep buzzer = Buzzer(15) while True: """ buzzer.beep() sleep(1) """ buzzer.off
StarcoderdataPython
4923709
<reponame>golyshevskii/yamitoys import os from celery import Celery from django.conf import settings # DJANGO_SETTINGS_MODULE для программы командной строки Celery # DJANGO_SETTINGS_MODULE for Celery command line program os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'pupa.settings') # экземпляр класса Celer...
StarcoderdataPython
5090028
_bytes = b"x" * 3 def test_lrusized_acts_like_a_dict(): from guillotina.contrib.cache.lru import LRU m = LRU(1024) m.set("a", _bytes, 3) assert m["a"] == _bytes assert "a" in m assert m.get("a") == _bytes assert m.get_memory() == 3 del m["a"] assert len(m.keys()) == 0 assert m...
StarcoderdataPython
6444871
<gh_stars>1-10 # A sample application (based on a published sample for the CV2 library) for # determining the color range needed in order to isolate a specific target # in an image. The program will default to reading from a connected webcam, # but can also be used with a sample (still) image. # # This was used i...
StarcoderdataPython
6518897
<filename>layers/src/function1/index.py def lambda_handler(event, context): print("Hello data service function1") return "hello world"
StarcoderdataPython
9770425
from unittest import TestCase, main from dominio import Lance, Leilao, Usuario from excecoes import LanceInvalido class TestLeilao(TestCase): def setUp(self): self.gui = Usuario('Gui', 500) self.yuri = Usuario('Yuri', 500) self.lance_do_gui = Lance(self.gui, 150) self.lance_do_yu...
StarcoderdataPython
8130488
import os import pytest def test_been_called(expect, mocker): mock_called = mocker.patch('os.path.join') os.path.join('home', 'log.txt') expect(mock_called).to.have.been_called with pytest.raises(AssertionError): expect(mock_called).to.have_not.been_called mock_not_called = mocker.patch...
StarcoderdataPython
9632991
<gh_stars>1-10 import tensorflow as tf import numpy as np def remove_test_time_dropout(model_drop): config = model_drop.get_config() for layer in config['layers']: if 'Dropout' in layer['class_name']: layer['inbound_nodes'][0][0][3]['training'] = False model = tf.keras.Model().from_con...
StarcoderdataPython
9661254
# Esconde senha # Faça uma função que recebe uma senha (string) e devolve uma string do mesmo tamanho da senha formada somente por asteriscos ('*'). # O nome da sua função deve ser esconde_senha. def esconde_senha (password): length = len(password) hidden = "*" * length return hidden
StarcoderdataPython
3318998
import os, re import numpy as np import matplotlib.pyplot as plt def rename_files(path): for count, filename in enumerate(os.listdir(path)): name, number = filename.split('.') if (bool(re.search('^[-+]?[0-9]+$', number))): number = str('%03d' % int(number),) new_filename = ...
StarcoderdataPython
9651791
## Imports import os import sys import inspect import unittest # Include path to handybeam directory sys.path.append('../.') ## Class class TranslatorTests(unittest.TestCase): def setUp(self): self.translator = None def tearDown(self): del self.translator def test_import(self):...
StarcoderdataPython
4821450
class player: def __init__(self, health, attackpower, spec, armor, name, race): self.health = health self.attackpower = attackpower self.spec = spec self.armor = armor self.name = name self.race = race def take_damage(self, damage): relative_damage = dama...
StarcoderdataPython
165063
"""Solr Tests""" import os import pytest from hamcrest import contains_string, assert_that # pylint: disable=redefined-outer-name @pytest.fixture() def get_ansible_vars(host): """Define get_ansible_vars""" java_role = "file=../../../java/vars/main.yml name=java_role" common_vars = "file=../../../common/var...
StarcoderdataPython
1828551
<reponame>marykamau2/Blog<filename>tests/test_comment.py from app.models import Comment,User,Blog from app import db import unittest class CommentModelTest(unittest.TestCase): def setUp(self): self.user_Peris = User(username = 'Peris',password = '<PASSWORD>', email = '<EMAIL>') self.new_blog = Blog...
StarcoderdataPython
188054
n1 = str(input('digite uma frase: ')).strip().upper() print('A letra A aparece {} vezes na frase'.format(n1.count('A'))) print('A primeira letra A apareceu na posição {}'.format(n1.find('A')+1)) print('A ultima letra A aprece na posição {}'.format(n1.rfind('A')+1))
StarcoderdataPython
4969936
<reponame>IgorBwork/django-libreport<filename>reports/migrations/0003_auto_20171119_1232.py<gh_stars>1-10 # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import reports.models class Migration(migrations.Migration): dependencies = [ ('reports', '00...
StarcoderdataPython
1978936
<filename>06-Object_tracking/05_background_subtraction.py # import cv2 import numpy as np cap = cv2.VideoCapture(0) mog2 = cv2.createBackgroundSubtractorMOG2() # knn = cv2.createBackgroundSubtractorKNN() while True: ret, frame = cap.read() frame = cv2.flip(frame, 1) # apply background subtra...
StarcoderdataPython
5148173
<reponame>Attanon/classic-assist-attanon-lib<gh_stars>0 def Autoloot(obj): """ Sets the container for the Autoloot agent to put items into... :param obj: An entity serial in integer or hex format, or an alias string such as "self". """ pass def Counter(name: str): """ Returns the count of...
StarcoderdataPython
5186834
import explanes as el table = [['a', 'b', 1, 2], ['a', 'c', 2, 2], ['a', 'b', 2, 2]] print(el.util.constantColumn(table))
StarcoderdataPython
4940651
<reponame>hajime9652/observations # -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function import csv import numpy as np import os import sys from observations.util import maybe_download_and_extract def fertil3(path): """fertil3 Data l...
StarcoderdataPython
300179
import random from itertools import cycle import numpy as np import pygame import sys if not sys.warnoptions: import warnings warnings.simplefilter("default") import settings birds = [] bestbird = None def main(): settings.init() while True: # select random background sprites randBg...
StarcoderdataPython
3507330
import os, sys sys.path.append("../NetVLAD-pytorch") import torch import torch.nn as nn from torch.autograd import Variable from netvlad import NetVLAD, NetVLADPure from netvlad import EmbedNet from hard_triplet_loss import HardTripletLoss from torchvision.models import resnet18 # Discard layers at the end of base ...
StarcoderdataPython