id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
50938 | import getpass
import telnetlib
HOST = "192.168.178.55"
user = input("Enter your telnet username: ")
password = <PASSWORD>()
tn = telnetlib.Telnet(HOST)
tn.read_until(b"Username: ")
tn.write(user.encode('ascii') + b"\n")
if password:
tn.read_until(b"Password: ")
tn.write(password.encode('ascii') + b"\n")
tn... | StarcoderdataPython |
4955387 | <filename>tests/http_client_test.py
import unittest
import responses
from braintreehttp import HttpClient, File
from braintreehttp.testutils import TestHarness
class GenericRequest:
def __init__(self):
self.path = ""
self.verb = ""
self.headers = {}
def __str__(self):
s = ""... | StarcoderdataPython |
5161723 | <gh_stars>0
import gc
import os
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
import tensorflow as tf
from rl_coach.base_parameters import TaskParameters, DistributedTaskParameters, Frameworks
from rl_coach.core_types import EnvironmentSteps
from rl_coach.utils import get_open_... | StarcoderdataPython |
5136741 | <reponame>TiddlySpace/tiddlyspace
"""
Enhance the default HTML serialization so that when we display
a single tiddler it includes a link to the tiddler in its space.
"""
from tiddlyweb.model.bag import Bag
from tiddlyweb.model.policy import PermissionsError
from tiddlyweb.model.recipe import Recipe
from tiddlyweb.seri... | StarcoderdataPython |
1814190 | <reponame>jvarho/python-oracle-serverless
import json
import cx_Oracle
def version(event, context):
conn = cx_Oracle.connect('user', 'pass', 'host')
cursor = conn.cursor()
res = cursor.execute('SELECT * from v$version')
response = {
"statusCode": 200,
"body": json.dumps([i for i in r... | StarcoderdataPython |
4849333 | import falcon
from broker.rabbitmq_consumer import Consumer
class MessageConsumerResource:
def __init__(self):
self._consumer = Consumer()
def on_get(self, req, res):
queue = req.get_param('queue', 'default')
print(f'Starting consumer for queue: {queue}...')
self._consumer.c... | StarcoderdataPython |
3478817 | import operator
import re
from typing import Iterable
from aio_pika import IncomingMessage
from gino import NoResultFound
from ninjin.decorator import (
actor,
lazy
)
from ninjin.exceptions import (
UnknownHandler,
ValidationError
)
from ninjin.filtering import (
ALL,
BasicFiltering
)
from nin... | StarcoderdataPython |
6552519 | from plasTeX import Command
# Dummy bm package - handled by mathjax
class bm(Command):
pass
| StarcoderdataPython |
1832921 | import numpy as np
import pandas as pd
import plotly.express as px
def update_liquidity_pool(quantity, liquidity_df , const_fee, token="Token 1"):
"""Finds and fills the order based on the token and liquidity provided, if it is not possible returns
the original liquidity data frame. To sell asset at the... | StarcoderdataPython |
5099763 | <filename>service_beacons_python/logic/IBeaconsController.py
# -*- coding: utf-8 -*-
"""
logic.IBeaconsController
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
IBeaconsController class
:copyright: Conceptual Vision Consulting LLC 2018-2021, see AUTHORS for more details.
:license: MIT, see LICENSE for more... | StarcoderdataPython |
4888775 | """
[summary]
[extended_summary]
"""
# region [Imports]
# * Standard Library Imports ---------------------------------------------------------------------------->
import os
# * Third Party Imports --------------------------------------------------------------------------------->
# * Gid Imports -------------------... | StarcoderdataPython |
3568473 | <filename>main.py
#!/usr/bin/env pybricks-micropython
from ev3dev2.motor import MediumMotor, OUTPUT_D, MoveTank, OUTPUT_A, OUTPUT_B
from pybricks import ev3brick as brick
from pybricks.ev3devices import (Motor, TouchSensor, ColorSensor,
InfraredSensor, UltrasonicSensor, GyroSensor)
from... | StarcoderdataPython |
9788667 | #!/usr/bin/env python3
#
# Copyright (c) 2018-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
#
import argparse
import binascii
import ssl
import tempfile
import unittest
import dns.messa... | StarcoderdataPython |
1895069 | import sys
from onnx_caffe import frontend
import argparse
import logging
#logging.basicConfig(level=logging.DEBUG)
parser = argparse.ArgumentParser(description='Convert a caffe model into an onnx file.')
#parser.add_argument('kfile', metavar='KerasFile', help='an input hdf5 file')
parser.add_argument('-n', metavar='p... | StarcoderdataPython |
6695497 | <reponame>koturn/kotemplate
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Description
"""
__author__ = '<+AUTHOR+> <+MAIL_ADDRESS+>'
__status__ = "production"
__version__ = '0.0.1'
__date__ = '<+DATE+>'
import optparse
import sys
if __name__ == '__main__':
N_REQUIRED_MEMAININGS = 1
parser = optparse.Op... | StarcoderdataPython |
1924619 | # retrieved from: https://gist.github.com/zyegfryed/918403, https://gist.github.com/grantmcconnaughey/ce90a689050c07c61c96
# used for creating pdf files to be served using django
# -*- coding: utf-8 -*-
import codecs
import subprocess
from fdfgen import forge_fdf
from django.core.exceptions import ImproperlyConfigured... | StarcoderdataPython |
1983309 | <filename>golem/core/test_data.py
"""Methods for dealing with test data files
Data files have csv or json extensions and are stored in the same
directory as the test.
"""
import ast
import csv
import json
import os
import traceback
from golem.core import test as test_module
from golem.core import utils
def csv_file... | StarcoderdataPython |
5011821 | import requests
from .exceptions import (
PyarrAccessRestricted,
PyarrBadGateway,
PyarrConnectionError,
PyarrMethodNotAllowed,
PyarrResourceNotFound,
PyarrUnauthorizedError,
)
class RequestHandler:
"""Base class for API Wrappers"""
def __init__(
self,
host_url: str,
... | StarcoderdataPython |
11220077 | <reponame>pennycxl/BearSki<filename>src/runtestt.py<gh_stars>1-10
import unittest
import BearSki.RunUnittest as rut
from BearSki.utils.logger import SkiLogger
from BearSki.report.LocalReportRunner import LocalReportRunner
import time
import sys
import logging
from BearSki.utils.arguments import runArg
def get_test_ca... | StarcoderdataPython |
1635868 | <reponame>Valaraucoo/raven
import datetime
import os
import uuid
from django.conf import settings
from django.contrib.auth import models as auth_models
from django.contrib.auth.signals import user_logged_in, user_logged_out
from django.db import models
from django.dispatch import receiver
from django.urls import rever... | StarcoderdataPython |
1624678 | #!/usr/bin/env python3
## In this example, we demonstrate how a Korali experiment can
## be resumed from any point (generation). This is a useful feature
## for continuing jobs after an error, or to fragment big jobs into
## smaller ones that can better fit a supercomputer queue.
## First, we run a simple Korali expe... | StarcoderdataPython |
9723121 | from types import MethodType
def deco_node_beta(self, node=None, level=0, indent=0):
return str(self.level) + node
class Obj:
pass
a = Obj()
a.level = 2
a.deco_node_beta = MethodType(deco_node_beta, a)
print(a.deco_node_beta('beta'))
| StarcoderdataPython |
3334620 | <gh_stars>1-10
# Created by <NAME>.
# GitHub: https://github.com/ikostan
# LinkedIn: https://www.linkedin.com/in/egor-kostan/
def check_for_factor(base, factor):
"""
This function should test if the
factor is a factor of base.
Factors are numbers you can multiply
together to get another number... | StarcoderdataPython |
3300240 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: huanglizhuo
# @Date: Sat Nov 18 16:57:23 CST 2017
'''
_____ __ __ ___ _ _ ___ _____
|_ _|\ \ / // __| | || | / \ |_ _|
| | \ \/\/ /| (__ | __ | | - | | |
_|_|_ \_/\_/ \___| |_||_| |_|_| _|_|_
_|"""""|_|"""... | StarcoderdataPython |
8098876 | import os
# use if needed to pass args to external modules
import sys
# used for directory handling
import glob
import time
import threading
from helpers.parameters import (
parse_args, load_config
)
# Load creds modules
from helpers.handle_creds import (
load_correct_creds, test_api_key,
load_telegram_cr... | StarcoderdataPython |
191040 | ### game.py is sort of the controller of the IronPython SGF Editor. The main
### class is Game, which provides calls for GUI event handling and makes calls
### to update the board and moves model.
import wpf
### Don't need this now due to new wpf module, but left as documentation of usage.
###
### Needed for... | StarcoderdataPython |
11376409 | # Complete the check_log_history function below.
def check_log_history(events):
stack = []
row = 0
for event in events:
row += 1
if event.startswith('A'):
lockNum = event.split(' ')[1]
# 重复输入
if lockNum in stack:
return row
stac... | StarcoderdataPython |
11291671 | #########################################################################
# 2020
# Author: <NAME>
#########################################################################
from typing import List
import cv2
import numpy as np
import csv
from pathlib import Path
from tqdm import tqdm
from torch.utils.data import Datas... | StarcoderdataPython |
6425717 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
Description : visualization library
Email : <EMAIL>
Date:2018/3/30
"""
from .vis_imports import *
from .line_plot import line
| StarcoderdataPython |
1777364 | # Generated by Django 3.1.8 on 2021-04-13 13:23
from django.db import migrations, models
import turtle_shell.utils
class Migration(migrations.Migration):
dependencies = [
("turtle_shell", "0005_auto_20210412_2320"),
]
operations = [
migrations.AddField(
model_name="execution... | StarcoderdataPython |
1624976 | from zipfile import ZipFile
from urllib.request import urlopen
from io import BytesIO
import pandas as pd
class WDIIndicators:
"""Retrieve WDI Indicators from the World Bank"""
def __init__(self, file_storage, s3_api):
""" Create a new instance of the WDIIndicators class
Parameters
-... | StarcoderdataPython |
3581949 | # util.py
""" Auxiliary functions """
""" some functions extracted from https://github.com/hyperledger/aries-cloudagent-python/blob/master/aries_cloudagent/messaging/connections/models/diddoc/util.py """
import datetime
def timestamp():
return datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc).i... | StarcoderdataPython |
12809745 | # Copyright 2018 the rules_m4 authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in... | StarcoderdataPython |
8028673 | import cv2
import numpy as np
from dataset.skeleton import *
from utils.converter import world_coords_to_image
if __name__ == '__main__': # Must run with main for multiprocessing
skeleton_dataset = SkeletonDatasetFlorence('D:/Illumine/Y4/METR4901/dataset/Florence', 0.8)
labels = skeleton_dataset.get_labels()... | StarcoderdataPython |
3383736 | <filename>src/decompress.py
from bitstring import Bits
from image_manipulation import show_image_from_numpy_array, load_image_to_numpy_array, save_image_from_numpy_array
from structure.Blob import Blob, TYPES
from structure.Blobs import Blobs
from structure.Image import Image
from structure.Vector import Vector2
def... | StarcoderdataPython |
8026928 | #!/usr/bin/env python3.6
import os
import tarfile
from six.moves import urllib
DOWNLOAD_ROOT = "https://raw.githubusercontent.com/ageron/handson-ml/master/"
HOUSING_PATH = os.path.join(*[os.path.pardir, "datasets", "housing"])
HOUSING_URL = DOWNLOAD_ROOT + "datasets/housing/housing.tgz"
def fetch_housing_data(hou... | StarcoderdataPython |
1971184 | <reponame>lgaravaglia999/plugin.streaming.cava
import sys
from resources.lib.views.TvshowView import TvShowView
from resources.lib.router_urls.websites_config import WebsitesConfig as cfg
#WEBSITE = "gs"
WEBSITE = cfg.get_path(cfg.GUARDASERIE)
class GuardaserieView(TvShowView):
def __init__(self):
if sys.... | StarcoderdataPython |
12835352 | <gh_stars>1-10
import datetime
def get_timestamp_min_in_past(min_ago: int) -> datetime.datetime:
dt = datetime.datetime.now() - datetime.timedelta(minutes=min_ago)
return dt.replace(tzinfo=datetime.timezone.utc)
| StarcoderdataPython |
9767019 | <gh_stars>1-10
from sklearn.naive_bayes import MultinomialNB
from sklearn.linear_model import SGDClassifier
from sklearn.preprocessing import LabelEncoder
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.svm import LinearSVC
from sklea... | StarcoderdataPython |
11220444 | <filename>tests/population_test.py
import unittest
import sys
sys.path.insert(1, '..')
import evogression
from test_data import categorical_data, surface_3d_data
from pprint import pprint as pp
import matplotlib
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d
import random
random.seed(10) # for... | StarcoderdataPython |
6550981 | <gh_stars>10-100
from Sakurajima.models.base_models import Anime, Episode, AniWatchEpisode
from Sakurajima.models.chronicle import ChronicleEntry
from Sakurajima.models.media import Media, UserMedia
from Sakurajima.models.notification import Notification
from Sakurajima.models.recommendation import RecommendationEntry
... | StarcoderdataPython |
3550571 | import time
from datetime import datetime
import json
from io import StringIO
import subprocess
import shlex
def run():
commands = shlex.split("python3 -c 'import main_app.runner; main_app.runner.run_real()'")
subprocess.Popen(commands)
def run_real():
import main_app.crawler as main
f = open('stati... | StarcoderdataPython |
3309091 | from django.conf.urls import patterns, include, url
from django.views.generic import ListView, DetailView
from django.views.generic.edit import UpdateView
from django.contrib.auth.decorators import login_required, permission_required
from models import *
from views import *
urlpatterns = patterns('',
url(... | StarcoderdataPython |
1866012 | <reponame>pordnajela/AlgoritmosCriptografiaClasica<gh_stars>0
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
from Plantilla import Template
from Transposicion.TransposicionSimple import TransposicionSimple
from Transposicion.TransposicionGrupo import TransposicionGrupo
from Transposicion.TransposicionSerie import Tran... | StarcoderdataPython |
12836134 | import numpy as np
import pandas as pd
import os
from PIL import Image
from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator
import matplotlib.pyplot as plt
import seaborn as sns
class GraphGenerator():
"""
A class that generates graphs to visualize data
"""
def create_wordcloud(self, freq_di... | StarcoderdataPython |
5042719 | n, k = map(int, input().split())
h = list(map(int, input().split()))
s = float("inf")
index = None
sm = 0
for i in range(k):
sm += h[i]
index = 0
j = 0
s = sm
for i in range(k, n):
# print(i, j)
# print(sm)
sm -= h[j]
sm += h[i]
# print(sm)
j += 1
if sm < s:
sm = s
in... | StarcoderdataPython |
178384 | import discord
import re
import db
def parse(message, quotes_file):
content = message.content
match = re.search('.+([A-Za-z0-9]:|\]:)+.+(\n[A-Za-z0-9].*)*', content)
if(match is not None):
if(match.group(0) == content):
db.insert('quotes', {'content': content})
return True
... | StarcoderdataPython |
8077002 | from flask import render_template,redirect,url_for,abort,request
from . import main
from app.requests import get_quote
from .forms import ReviewForm,UpdateProfile,ArticleForm
from .. models import Reviews,User,Articles
from flask import jsonify
from flask_login import login_required,UserMixin,current_user
from .. impor... | StarcoderdataPython |
6638475 | <filename>runner_service/controllers/jobs.py
import os
# from flask import request
from flask_restful import Resource
# import logging
from .utils import requires_auth, log_request
from ..services.jobs import get_events, get_event
from ..services.utils import build_pb_path
import logging
logger = logging.getLogger(__... | StarcoderdataPython |
6413956 | <filename>kfac/comm.py
import enum
import os
import torch
import torch.distributed as dist
try:
import horovod.torch as hvd
HVD_EXISTS = True
except:
HVD_EXISTS = False
# The global var containing the current initialized backend object
backend = None
def init_comm_backend():
global backend
if b... | StarcoderdataPython |
11334475 | from django.test import TestCase
class ReporterTestModel(TestCase):
def __init__(self, *args, **kwargs):
super().__init__(self, *args, **kwargs)
# TODO create EMBA-result with FWA and Result object
def test_download(self):
# TODO
pass
| StarcoderdataPython |
6589492 | <gh_stars>10-100
# Copyright (c) 2021 PaddlePaddle 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 ... | StarcoderdataPython |
12827070 | import ast
import bisect
import itertools
import tokenize
def iter_attribute_tokens(fname):
with open(fname, "rb") as file:
# The call to filter handles cases where an attribute access dot is at
# the end of a line and the attribute itself on the next one.
tokens = filter(lambda token: tok... | StarcoderdataPython |
6479120 | from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.parsers import JSONParser
from django.contrib.auth import get_user_model
# Create your views here.
class Register(APIView):
def get(self, request, format=None):
retur... | StarcoderdataPython |
8107949 | <reponame>fengggli/pegasus<gh_stars>0
#!/usr/bin/env python
import os
import sys
import subprocess
if len(sys.argv) != 2:
print "Usage: %s CLUSTER_PEGASUS_HOME" % (sys.argv[0])
sys.exit(1)
cluster_pegasus_home=sys.argv[1]
# to setup python lib dir for importing Pegasus PYTHON DAX API
#pegasus_confi... | StarcoderdataPython |
3202643 | #!/usr/bin/env python
# coding: utf-8
# info
__version__ = "0.1"
__author__ = "<NAME>"
__date__ = "04/10/19"
from gpiozero import Button
import time
BUCKET_SIZE = 0.2794
rain_count = 0
rain_interval = 5
def bucket_tipped():
global rain_count
rain_count += 1
def reset_rainfall():
global rain_count
... | StarcoderdataPython |
104901 | import traceback
import asyncio
# got the semaphore idea from https://asyncpyneng.readthedocs.io/ru/latest/book/using_asyncio/semaphore.html
class WithSemaphore(object):
def __init__(self, num_workers: int = 20) -> None:
self.num_workers = num_workers
def run(self, task, name=None, inven... | StarcoderdataPython |
1807895 | #!/usr/bin/env python3
import time
from datetime import datetime
from urllib.parse import urlparse
#from playsound import playsound
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from shops.Const import Const
from shops.ShopAlternateDE import ShopAlternateDE
from shops.ShopAlter... | StarcoderdataPython |
4946735 | <reponame>GennadyBarchenkov/python_training<gh_stars>0
from model.group import Group
import random
def test_full_edit_group(app, db, check_ui):
if len(db.get_group_list()) == 0:
app.group.create(Group(name="test", header="test", footer="test"))
old_groups = db.get_group_list()
group = Group(name="... | StarcoderdataPython |
3375464 | <filename>Download/DownloadSoccerNet.py
import SoccerNet
from SoccerNet.Downloader import SoccerNetDownloader
mySoccerNetDownloader = SoccerNetDownloader(
LocalDirectory="/path/to/SoccerNet")
mySoccerNetDownloader.password = input("Password for videos?:\n")
mySoccerNetDownloader.downloadGames(files=["Labels-v2.j... | StarcoderdataPython |
1682053 | <filename>Day 6/solution1.py<gh_stars>0
f = open("input.txt", "r")
puzzleInput = f.read()
totalOrbitCount = 0
def FindOrbiters(name, orbitCount):
global totalOrbitCount
totalOrbitCount += orbitCount
checkPos = 0
while True:
out = puzzleInput.find(name + ")", checkPos)
if(out == ... | StarcoderdataPython |
8124131 | <reponame>C4T-BuT-S4D/ad-boilerplate<filename>services/example/src/app.py
from flask import Flask, request, jsonify
app = Flask(__name__)
notes = set()
@app.route('/put_note', methods=['POST'])
def put_note():
note = request.json
if type(note) != dict or "name" not in note or "value" not in note:
ret... | StarcoderdataPython |
9675738 | '''
This script takes an image and splits it up into pieces as separate files.
drawn_quartered test.jpg --width 2 --height 2
drawn_quartered test.jpg outputname.jpg --width 3 --height 4
'''
import argparse
import math
import PIL.Image
import sys
from voussoirkit import pathclass
def drawquarter(image, width=2, heigh... | StarcoderdataPython |
1778855 | import unittest
import json
import json2txttree as j2t
class SimpleTest(unittest.TestCase):
def test_json2txttree(self):
with open('sample.json', 'r') as jsonfile:
data = json.load(jsonfile)
tree = j2t.json2txttree(data)
tree_exp = '└─ (object)\n' + \
' ... | StarcoderdataPython |
1973894 | import codecs
import string
import cryptopals.common as common
def decrypt_xor_encrypted_message(encrypted_message):
characters = [[ord(character)] for character in string.ascii_letters + string.digits]
encrypted_message = codecs.decode(encrypted_message, 'hex')
highest_score = 0
highest_scoring_mes... | StarcoderdataPython |
9702115 | from os import environ
from flask import Flask, render_template
import main as twitter
app = Flask(__name__)
@app.route("/bot")
def home():
twitter.main()
@app.route('/')
def root():
return render_template('index.html')
app.run(debug=True)
| StarcoderdataPython |
4810191 | import util
import libtcodpy as tcod
import towers
import items
registered_enemies = []
def enemy_classes ():
return [c for c in registered_enemies if c != Enemy]
class EnemyMeta (type):
def __init__ (class_, name, bases, attrs):
super(EnemyMeta, class_).__init__(name, bases, attrs)
registered_enemies.append(c... | StarcoderdataPython |
1833733 | #
# Copyright 2021 Red Hat Inc.
# SPDX-License-Identifier: Apache-2.0
#
"""AWS Report Serializers."""
from django.utils.translation import ugettext as _
from pint.errors import UndefinedUnitError
from rest_framework import serializers
from api.report.serializers import FilterSerializer as BaseFilterSerializer
from api... | StarcoderdataPython |
1965876 | # -*- coding: utf-8 -*-
import subprocess
from pupylib.PupyModule import *
import subprocess
import time
import datetime
import os
__class_name__="PExec"
@config(cat="admin")
class PExec(PupyModule):
""" Execute shell commands non-interactively on a remote system in background using popen"""
pool_time = 1... | StarcoderdataPython |
5003120 | <gh_stars>0
""" Converts coordinates in a Cartesian Reference System (CRS) into GPS coordinates (latitude + longitude)
Requires pyproj and utm libraries, install simply with: pip install pyproj utm"""
import pyproj
import utm
import math
# defining World Geodetic Format, should be set accordinly to the GPS device's WG... | StarcoderdataPython |
6441549 | #! /usr/bin/env python3
import build_utils, common, os, shutil, sys
def main():
os.chdir(common.basedir)
build_utils.rmdir("target")
build_utils.rmdir("shared/target")
build_utils.rmdir("platform/build")
build_utils.rmdir("platform/target")
build_utils.rmdir("tests/target")
build_utils.rmdir("examples/lw... | StarcoderdataPython |
1859538 | # -*- coding: utf-8 -*-
# Copyright (c) 2015, <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# Redistributions of source code must retain the above copyright notice, this
# list ... | StarcoderdataPython |
3201806 | <filename>poller/main.py
import traceback
from time import sleep
from modules.APICaller import APIHandler
from modules.DBConnector import DBConnector
def main():
#Setup, maybe read from config file to read intervall, servers etc.
api = APIHandler()
db = DBConnector()
while(True):
... | StarcoderdataPython |
5038053 | from dis import dis
from types import CodeType
from ..containers import Context
def debug(code: CodeType, context: Context) -> CodeType:
dis(code)
return code
EXTENSION = debug
| StarcoderdataPython |
8121397 | <reponame>purush34/a2oj-solutions
a,b=int(input()),input()
c=b.count('5')
d=a-c
print(int('5'*(9*(c//9))+'0'*d) if d else '-1') | StarcoderdataPython |
12851174 | import discord
from discord.ext import commands
import json
from utils import error, RARITY_DICT
from parse_profile import get_profile_data
from extract_ids import extract_internal_names
# Create the master list!
from text_files.accessory_list import talisman_upgrades
# Get a list of all accessories
ACCESSORIES = []... | StarcoderdataPython |
181093 | from __future__ import absolute_import
import logging
from kafka import KafkaProducer
from django.utils.functional import cached_property
from sentry import quotas
from sentry.models import Organization
from sentry.eventstream.base import EventStream
from sentry.utils import json
from sentry.utils.pubsub import Queu... | StarcoderdataPython |
9612351 | <reponame>MichaelRol/Threaded-Bristol-Stock-Exchange<filename>tbse_sys_consts.py
"""
constants uses across BSE
"""
TBSE_SYS_MIN_PRICE = 1 # minimum price in the system, in cents/pennies
TBSE_SYS_MAX_PRICE = 500 # maximum price in the system, in cents/pennies: Todo -- eliminate reliance on this
TICK_SIZE = 1 # minim... | StarcoderdataPython |
8174560 | <filename>sap/adt/annotations.py<gh_stars>0
"""Python decorators for conversions of Python objects to ADT XML fragments"""
from enum import Enum
import collections
def _make_attr_name_for_version(element_name, version):
"""Makes the given name unique for the given version parameter
which can be:
- ... | StarcoderdataPython |
8176108 | <filename>boston_demo.py<gh_stars>10-100
__doc__ = """Uncertainty-GBM applied to Boston real-estate data."""
import regressor
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.utils import shuffle
def main():
boston = datasets.load_boston()
X, y = shuffle(boston.... | StarcoderdataPython |
1802320 | <reponame>computerMoMo/FastMaskRCNN
#!/usr/bin/env python
# coding=utf-8
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import functools
import os, sys
import time
import numpy as np
import tensorflow as tf
import tensorflow.contrib.slim as slim
from time ... | StarcoderdataPython |
273358 | <reponame>hydrargyrum/UnityPy<filename>UnityPy/CommonString.py
COMMON_STRING = {
0 : "AABB",
5 : "AnimationClip",
19 : "AnimationCurve",
34 : "AnimationState",
49 : "Array",
55 : "Base",
60 : "BitField",
69 : "bitset",
76 : "bool",
81 : "char",
86 : "ColorRGBA",
96 : "Component",
... | StarcoderdataPython |
4914112 | <filename>setup.py
from distutils.core import setup
setup(name='Distutils',
version='0.1',
description='Python Shooting Game',
author='maTORIx',
author_email='<EMAIL>',
url='http://matorix.tk',
packages=['pygame'],
) | StarcoderdataPython |
141192 | <filename>HW2-6/HW4/Code/CSCI567_hw4_fall16.py
import hw_utils as ml_utils
from datetime import datetime
def main():
start = datetime.now()
print "Loading Data..."
X_tr, y_tr, X_te, y_te = ml_utils.loaddata('./MiniBooNE_PID.txt')
print X_tr.shape, y_tr.shape
"""
print "Normalizing Data..."
... | StarcoderdataPython |
11377506 | import serial
positions_file = open("positions_fpga.txt", "a")
with serial.Serial('/dev/ttyACM0', 250000, timeout=1) as ser:
previous = ""
ser.write(b'h')
for i in range(1024):
while
ser.write(b'h')
positions_file.write(repr(ser.read(1)))
positions_file.write("\n")
| StarcoderdataPython |
12818601 | <reponame>gordonmessmer/ansible-bender<filename>ansible_bender/builders/base.py
"""
Base class for builders
"""
from enum import Enum
class BuildState(Enum):
NEW = "new"
IN_PROGRESS = "in_progress"
DONE = "done"
FAILED = "failed"
class Builder:
ansible_connection = "default-value"
name = "de... | StarcoderdataPython |
47753 | #!/usr/local/python/bin/python
# script to check the previously unsolved files
#
# to do:
# Sanity check all the image_ids in the table actually have a png
# quick check shows 1349 in DB and 1353 pngs, 4 out, not bad
#
from create_movie import create_movie
import os,sys,getpass,time
import glob as g
from astropy.io... | StarcoderdataPython |
293151 | #!/usr/bin/python3
"Pymilter-based milter that adds Piwik / Matomo tracking parameters to links found in e-mails."
from time import strftime
import urllib
import tempfile
import email
import re
import io
import os
import sys
import Milter
# Configuration
# List of email addresses for which incoming mail should have... | StarcoderdataPython |
1933027 | # https://leetcode.com/problems/rotate-array/discuss/269948/4-solutions-in-python-(From-easy-to-hard)
# https://leetcode.com/problems/rotate-array/discuss/487529/py3-js-5-different-simple-solutions
# https://practice.geeksforgeeks.org/problems/rotate-array-by-n-elements-1587115621/1/?track=md-arrays&batchId=144
def ro... | StarcoderdataPython |
8004676 | <filename>7_kyu/Say_Me_Please_Operations.py<gh_stars>0
def sayMeOperations(stringNumbers: str) -> str:
numbers = [int(it) for it in stringNumbers.split()]
ERROR = "?"
if len(numbers) < 2:
return ERROR
a,b = numbers[0:2]
names = []
for c in numbers[2:]:
if a+b == c:
r ... | StarcoderdataPython |
1630963 | # -*- coding: utf-8 -*-
# file: __init__.py
# time: 2021/5/21 0021
# author: yangheng <<EMAIL>>
# github: https://github.com/yangheng95
# Copyright (C) 2021. All Rights Reserved.
from pyabsa.core.atepc.models import (lcfs_atepc,
lcfs_atepc_large,
... | StarcoderdataPython |
3463532 | <filename>patchmatch/python/patchmatch.py<gh_stars>0
# [mask,param] = CMFD_PM(img,param)
#This code is the version 1.0 of the CMFD (Copy-Move Forgery Detection)
# algorithm described in "Efficient dense-field copy-move forgery detection",
# written by <NAME>, <NAME> and <NAME>,
# IEEE Trans. on Information For... | StarcoderdataPython |
3554448 | class Solution:
# @param A : tuple of integers
# @param B : integer
# @return an integer
def search(self, A, B):
left, right = 0, len(A) - 1
while left <= right:
mid = (left + right) / 2
if B == A[mid]:
return mid
if A[left] == A[mid] a... | StarcoderdataPython |
1728597 | [1,4,5]
['a','b','c']
[x,y,z,t]
| StarcoderdataPython |
1873475 | # -*- coding: utf-8 -*-
# Copyright 2014 OpenMarket Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | StarcoderdataPython |
1986077 | <filename>ding/torch_utils/tests/test_metric.py
import random
import pytest
import torch
from ding.torch_utils.metric import levenshtein_distance, hamming_distance
@pytest.mark.unittest
class TestMetric():
def test_levenshtein_distance(self):
r'''
Overview:
Test the Levenshtein Dist... | StarcoderdataPython |
1632874 | <filename>azure-mgmt/tests/test_mgmt_sql.py
# coding: utf-8
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#-------------------------... | StarcoderdataPython |
6643572 | <reponame>alexandros44/UServer
from helpers.RegexHelpers import uregex as re
try:
import json
except:
import ujson as json
class RequestMethods:
'''
This class handles all of the predifined server HTTP Methods. It simply adds to the
UServer.__router_paths the paths the server wants to list... | StarcoderdataPython |
11322874 | # 导入必要的模块和要测试的类
import unittest
from employee import Employee
# 定义测试用例
class TestEmployee(unittest.TestCase):
"""针对Employee类的测试"""
def setUp(self):
"""创建新的雇员实例和属性,供使用的测试方法使用"""
self.my_employee = Employee('yahu', 'yang', 65000)
def test_give_default_raise(self):
"""测试默认加薪"""
... | StarcoderdataPython |
192671 | <reponame>kommurisaikumar/savings-manager-server<filename>backend/app/schemas/accounts.py
from pydantic import BaseModel
from typing import Optional
class AccountSingle (BaseModel):
id: int
user_id: int
class AccountList (BaseModel):
id: Optional[int]
user_id: int
class Account(BaseModel):
id: in... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.