id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
72599 | <filename>vega/algorithms/nas/modnas/backend/__init__.py
# -*- coding:utf-8 -*-
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the MIT License.
# This program is distributed in the hope that it will... | StarcoderdataPython |
175785 | # optimal performance
def copy_random_list(head):
if not head: return head
# copy each node and insert right after itself
curr = head
while curr:
node_new = RandomListNode(curr.label)
node_next = curr.next
curr.next = node_new
node_new.next = node_next
curr = no... | StarcoderdataPython |
53371 | #!/usr/bin/python3
import os
import subprocess
import sys
md5sums = {}
dirname = sys.argv[1]
for fn in os.listdir(dirname):
md5sum = subprocess.check_output(['md5sum', os.path.join(dirname, fn)]).decode('ascii').partition(" ")[0]
if md5sum in md5sums:
# This blob already exists. Symlink it
o... | StarcoderdataPython |
148977 | <reponame>tandy-1000/whatlastgenre<gh_stars>10-100
#!/usr/bin/env python
# whatlastgenre
# Improves genre metadata of audio files
# based on tags from various music sites.
#
# Copyright (c) 2012-2020 YetAnotherNerd
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and ... | StarcoderdataPython |
3368993 | <gh_stars>10-100
"""
t-SNE: Plots
We observe a tendency towards clearer shapes as the preplexity value increases.
The size, the distance and the shape of clusters may vary upon initialization,
perplexity values and does not always convey a meaning.
For further details, "How to Use t-SNE Effectively"
http://distill.p... | StarcoderdataPython |
192561 | <reponame>louisun/iSearch
#!/usr/bin/env python
# coding=utf-8
import json
from termcolor import colored
type_to_chinese = {
"basic":"【基本含义】",
"synonyms":"【同近义词】",
"discriminate":"【词语辨析】",
"word_group":"【词组】",
"collins":"【用例介绍】",
"bilingual":"【双语例句】",
"fanyiToggle":"【有道翻译】"
}
def is_title... | StarcoderdataPython |
28658 | <filename>pandatools/Client.py
'''
client methods
'''
import os
if os.environ.has_key('PANDA_DEBUG'):
print "DEBUG : importing %s" % __name__
import re
import sys
import time
import stat
import types
try:
import json
except:
import simplejson as json
import random
import urllib
import struct
import comm... | StarcoderdataPython |
1658662 | <gh_stars>1-10
import os
import pickle
def check_train_input(config):
print ('Checking training input...')
# Check that all necessary parameters have been defined
# [DATA]
try:
test = config['DATA']
except:
print('Header [\'DATA\'] not defined on config file')
print('Please check the config file available ... | StarcoderdataPython |
4806821 | from setuptools import setup
setup(
name='rulebook',
version='0.0.1',
packages=['rulebook'],
url='https://github.com/hmelberg/rulebook',
license='MIT',
author='<NAME>',
author_email='<EMAIL>',
description='Validate and revise Pandas dataframes',
install_requires=['pandas']
)
| StarcoderdataPython |
128369 | <filename>homeassistant/components/august/diagnostics.py
"""Diagnostics support for august."""
from __future__ import annotations
from typing import Any
from homeassistant.components.diagnostics import async_redact_data
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
... | StarcoderdataPython |
37156 | from typing import Callable, Mapping, TypedDict
import asyncio, aiohttp, discord
class Options(TypedDict):
interval: int
start: bool
class AutoPoster():
token: str
interval: int
bot: discord.Client
stopped: bool
_events: Mapping[str, Callable]
def __init__(self, token: str, bot: dis... | StarcoderdataPython |
1782410 | #!/usr/bin/env python3
import sys
import requests
import os
## Telegram
# "111111111:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" The token acquired from telegram @BotFather
BOT_TOKEN = os.environ['ESHOP_TG_BOT_TOKEN']
# "-111111111" Chat that is group/channel/pm that the bot has access to
CHAT_ID = os.environ['ESHOP_TG_CHAT_... | StarcoderdataPython |
4812889 | <reponame>KunalSin9h/Conway-Game-of-Life<filename>Code/Blocks/initial_condition.py
"""A pattern method for adding Glider"""
def addGlider(i, j, grid):
"""Adds a glider with top left cell at (i, j)"""
glider = np.array([
[0, 0, 255],
[255, 0, 255],
[0, 255, 255]
])
grid[i:i+3, j... | StarcoderdataPython |
18420 | <reponame>fraricci/MPContribs
# -*- coding: utf-8 -*-
from django.conf.urls import url
from django.views.generic.base import RedirectView
from mpcontribs.portal import views
app_name = "mpcontribs_portal"
urlpatterns = [
url(r"^$", views.index, name="index"),
url(r"^healthcheck/?$", views.healthcheck, name="he... | StarcoderdataPython |
3307290 | <filename>recipes/Python/576922_Delete_all_message_older_thgiven_date_pop/recipe-576922.py
import os, sys, getpass
import poplib # http://docs.python.org/library/poplib.html
from email.utils import parsedate_tz
import calendar
import datetime
# The main parameter
last_wanted = datetime.datetime(2009, 10, 5)
print last... | StarcoderdataPython |
1663446 | <reponame>shubhattin/mama_purAnyAni
from WConio2 import textcolor, clrscr, getch, setcursortype
import ctypes
ctypes.windll.kernel32.SetConsoleTitleW("n Numbers HCF")
def hcf(n):
a, b, r = n[0], n[1], 0
for x in range(0, len(n) - 1):
while a != 0:
r = b % a
b = a
a... | StarcoderdataPython |
75096 | <gh_stars>0
import json
from pymongo import MongoClient
from flask import jsonify, request, Flask
from flask_cors import CORS
import flask
from utils.utils import *
from bson import ObjectId
import copy
import requests
import datetime
app = Flask(__name__)
CORS(app)
@app.route("/login",methods=['POST'])
def loginUse... | StarcoderdataPython |
3326054 | <reponame>aviadr1/learn-python3<filename>content/_build/jupyter_execute/01_refresher/notebooks/reduce.py
#!/usr/bin/env python
# coding: utf-8
#
# <a href="https://colab.research.google.com/github/aviadr1/learn-advanced-python/blob/master/content/01_refresher/notebooks/reduce.ipynb" target="_blank">
# <img src="https... | StarcoderdataPython |
73552 | <filename>python/ovs/unixctl/__init__.py
# Copyright (c) 2011, 2012 Nicira, Inc.
#
# 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 |
1686391 | <gh_stars>100-1000
#!/usr/bin/env python
'''
/* Copyright 2016, <NAME>
All Rights Reserved
Permission to use, copy, modify, and distribute this software and
its documentation for any non-commercial purpose is hereby granted
without fee, provided that the above copyright notice appear in
all copies and that both t... | StarcoderdataPython |
1763669 | <filename>src/ghaudit/query/repo_collaborators.py
from typing import Any, Mapping
from ghaudit.query.sub_query import ValidValueType
from ghaudit.query.sub_query_common import SubQueryCommon
from ghaudit.query.utils import PageInfo
class RepoCollaboratorQuery(SubQueryCommon):
FRAGMENTS = ["frag_repo_user_edge.j... | StarcoderdataPython |
3258219 | <reponame>Kyubyong/cross_vc
# -*- coding: utf-8 -*-
#/usr/bin/python2
'''
By <NAME>. <EMAIL>.
https://www.github.com/kyubyong/cross_vc
'''
from __future__ import print_function
from hparams import Hyperparams as hp
import librosa
import numpy as np
from scipy import signal
import copy
import tensorflow as tf
def get... | StarcoderdataPython |
3310220 | <gh_stars>1-10
from collections import namedtuple
from ply import lex, yacc
from . import tokrules
import numpy as np
# LEXER
lexer = lex.lex(module=tokrules)
# FSS
FSS = namedtuple('FSS', 'nodes, actions, start, A, N')
# PARSER
class FSS_Parser:
tokens = tokrules.tokens
def __init__(self):
... | StarcoderdataPython |
112014 | <gh_stars>1-10
#!/usr/bin/python
import tornado.websocket
import tornado.httpserver
import tornado.ioloop
import tornado.web
import plivo
import ssl
import os
import re
import time
from tornado_http_auth import DigestAuthMixin, BasicAuthMixin, auth_required
#User Variable Section
#The script won't run if you don't... | StarcoderdataPython |
141751 | # -*- coding: utf-8 -*-
import setuptools
__version__ = "1.8.0+dd.2"
# read the contents of your readme file
from os import path
this_directory = path.abspath(path.dirname(__file__))
with open(path.join(this_directory, "README.md"), "rb") as f:
long_description = f.read().decode("utf-8")
setuptools.setup(
... | StarcoderdataPython |
3218911 | <filename>src/meltano/core/block/ioblock.py
"""The actual IOBlock interface is one of the lower level blocks for use with various BlockSet implementations."""
from abc import ABCMeta, abstractmethod
from asyncio import StreamWriter, Task
from typing import Optional, Tuple
from meltano.core.logging.utils import Subproc... | StarcoderdataPython |
4824492 | # -*- coding: utf-8 -*-
"""Testing :mod:`astropy.cosmology.units`."""
##############################################################################
# IMPORTS
import pytest
import astropy.cosmology.units as cu
import astropy.units as u
from astropy.cosmology import Planck13, default_cosmology
from astropy.tests.hel... | StarcoderdataPython |
93707 | ##
# ingestion service script to register multiple levels of an ivac patient
# (entity level, biological sample level, test sample level, NGS sample level)
##
def process(tr, parameters, tableBuilder):
"""Create different levels for ivac patient, entity level to NGS sequencing level
"""
level = parameters.get("... | StarcoderdataPython |
3376929 | def show_exceptions():
"""
Show exception handling patterns
:return:
"""
file =None
try:
# File is being opened
file = open('input-file', 'open mode')
except FileNotFoundError as fe:
# When File is Not Found
print("Caught the File Not Found error.")
ra... | StarcoderdataPython |
3299488 | import ocdskingfisherprocess.cli.commands.base
import ocdskingfisherprocess.database
from ocdskingfisherprocess.checks import Checks
class CheckCLICommand(ocdskingfisherprocess.cli.commands.base.CLICommand):
command = 'check-collection'
def configure_subparser(self, subparser):
self.configure_subpars... | StarcoderdataPython |
1731620 | from test_map_base import TestMapBase
from unittest.mock import patch
from werkzeug.datastructures import OrderedMultiDict
import os
import pytest
class TestMapDownload(TestMapBase):
def setup(self):
TestMapBase.setup(self)
self.downloads_dir = self.app.config["MAP_DOWNLOADS_DIR"]
self.clean_map_downlo... | StarcoderdataPython |
3385683 | <reponame>iAkogare/epg2xml
# -*- coding: utf-8 -*-
import argparse
import json
import logging
import os
import sys
import errno
from copy import copy
from epg2xml.utils import dump_json
from epg2xml import __version__, __title__, __description__, __url__
logger = logging.getLogger("CONFIG")
class Singleton(type):
... | StarcoderdataPython |
135605 | <gh_stars>0
from flask import Flask, render_template, request, jsonify
app = Flask(__name__)
@app.route("/", methods=['GET', 'POST'])
def index():
if request.method == 'POST':
form_data = request.get_json(force=True)
print(form_data)
data = {'valid': True}
return jsonify(data)
... | StarcoderdataPython |
189042 | from schedule import get_schedule
from playlog import get_play_logs, get_play_log_data
from datetime import datetime
import logging
log = logging.getLogger(__name__)
def generate_play_logs(teamid, year=2016):
sched = get_schedule(year)
games = sched[(sched.home_team == teamid) | (sched.away_team == teamid)]
for i ... | StarcoderdataPython |
1786121 | <filename>backend/clubs/management/commands/daily_notifications.py
import collections
import datetime
import traceback
from django.conf import settings
from django.contrib.auth.models import Group
from django.core.management.base import BaseCommand
from django.db.models import Q
from django.utils import timezone
from... | StarcoderdataPython |
1750014 | <filename>paymate/urls.py
from django.conf.urls import url
from django.contrib import admin
from rest_framework.documentation import include_docs_urls
from accounts.views import AccountViewSet, CurrencyViewSet, TransactionViewSet
urlpatterns = [
url(r'^accounts/', AccountViewSet.as_view(), name='accounts-list'),
... | StarcoderdataPython |
3264497 | <reponame>madoka-0w0/notice_rain
import time
import threading
class Schedule:
def __init__(self):
self.loop = True
def start(self, interval, func, wait=True):
base_time = time.time()
next_time = 0
while self.loop:
t = threading.Thread(target=func)
t.sta... | StarcoderdataPython |
4841779 | <gh_stars>1000+
"""
Timer test for the CC3200 based boards.
"""
from machine import Timer
import os
import time
mch = os.uname().machine
if "LaunchPad" in mch:
pwm_pin = "GP24"
elif "WiPy" in mch:
pwm_pin = "GP24"
else:
raise Exception("Board not supported!")
for i in range(4):
tim = Timer(i, mode=Ti... | StarcoderdataPython |
1793242 | <filename>dvbbox/api/models.py<gh_stars>0
#!/usr/bin/env python
# encoding: utf-8
from werkzeug.security import generate_password_hash, check_password_hash
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from flask import current_app
from flask_redis import FlaskRedis
db = FlaskRedis()
class ... | StarcoderdataPython |
1662674 | from models import Gene, Sample
# TODO method for creating samples faster
def test_gene_init():
gene = Gene('BAD')
assert gene.name == 'BAD'
same = Gene('BAD')
assert same == gene
assert same is gene
g = Gene('TP53', 'Tumour suppressor p53')
assert g.name == 'TP53'
assert g.descript... | StarcoderdataPython |
1762947 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import division
from builtins import dict
from Bio import SeqIO
import os
import sys
import gzip
import pickle
import random
import logging
import numpy as np
from shutil import copyfileobj
def phred_to_prob(q):
"""Convert a phred score (Sanger or ... | StarcoderdataPython |
3353957 | <gh_stars>1000+
from dagster import check
from dagster.config.snap import ConfigSchemaSnapshot, snap_from_config_type
from dagster.core.definitions.pipeline import PipelineDefinition
from dagster.utils import merge_dicts
def build_config_schema_snapshot(pipeline_def):
check.inst_param(pipeline_def, "pipeline_def"... | StarcoderdataPython |
1713060 | import pandas as pd
def call(interactions: pd.DataFrame()) -> pd.DataFrame():
interactions_filtered = interactions[interactions['is_cellphonedb_interactor']].copy()
def simple_complex_indicator(interaction: pd.Series, suffix: str) -> str:
if interaction['is_complex{}'.format(suffix)]:
ret... | StarcoderdataPython |
4825028 | <reponame>markify/ecohazard
#Name: Mark
#Description: database model
#Usage: storing data to database
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
# These are items for our database; Hazard Reports
class Category(models.Model):
id = models.IntegerField(prima... | StarcoderdataPython |
3311077 | a = 'ABABC'
b = 'BABCA'
c = []
| StarcoderdataPython |
3321596 | <reponame>odidev/mpld3
"""
Plot to test numeric tick labels
"""
import matplotlib.pyplot as plt
import matplotlib
import mpld3
def create_plot():
fig, ax = plt.subplots()
ax.plot([1000, 1050], [1, 2])
ax.set_title('Tick label test', size=14)
return fig
def test_date():
fig = create_plot()
_ ... | StarcoderdataPython |
3386708 | <reponame>ebeauce/PhaseNet<gh_stars>0
import matplotlib
#matplotlib.use("agg")
import matplotlib.pyplot as plt
import numpy as np
import os
def plot_residual(diff_p, diff_s, diff_ps, tol, dt):
box = dict(boxstyle='round', facecolor='white', alpha=1)
text_loc = [0.07, 0.95]
plt.figure(figsize=(8,3))
pl... | StarcoderdataPython |
1604540 | #!/usr/bin/env python
"""Simulation Utilities."""
# File to contain function necessary for the chi_square simulations
import copy
import logging
import numpy as np
def add_noise(flux, snr, use_mu=False):
"""Using the formulation 1/sigma (default) or mu/sigma from wikipedia.
https://en.wikipedia.org/wiki/S... | StarcoderdataPython |
20586 | <gh_stars>1-10
from sqlalchemy.dialects import registry
registry.register("greenplum", "sqlalchemy_greenplum.dialect", "GreenplumDialect")
from sqlalchemy.testing.plugin.pytestplugin import *
| StarcoderdataPython |
1673711 | t1 = (1, 2, 3, 'a', 'samu')
"""
A tupla funciona exatamente igual a uma lista, a unica diferença é
que eu não posso alterar os valores que ela contem após sua formação
""" | StarcoderdataPython |
3220087 | <gh_stars>0
class Node:
def __init__(self, value=None):
self.value = value
self.next = None
class Stack():
def __init__(self):
self.top = None
def push(self, item):
new_node = Node(item)
new_node.next = self.top
self.top = new_node
def pop(self):
c... | StarcoderdataPython |
3343396 | <reponame>yasinkaymaz/scRNAseq_Benchmark<gh_stars>0
import os
import sys
import numpy as np
import pandas as pd
import time as tm
import rpy2.robjects as robjects
def run_ACTINN(DataPath, LabelsPath, CV_RDataPath, OutputDir, GeneOrderPath = "", NumGenes = 0):
'''
run ACTINN
Wrapper script to run ... | StarcoderdataPython |
1740133 | import unittest
class Solution:
def rangeBitwiseAnd(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
while n > m:
n &= (n - 1)
return n
class Test(unittest.TestCase):
def test(self):
self._test(5, 7, 4)
self._test(... | StarcoderdataPython |
1627779 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License") you may not us... | StarcoderdataPython |
155143 | import setuptools
import re
with open("requirements.txt") as f:
requirements = f.read().splitlines()
with open("flat/__init__.py") as f:
m = re.search(r"__version__ \= \"(\d+\.\d+\.\d+)\"", f.read())
version = m.group(1)
setuptools.setup(
name="flat",
author="nguuuquaaa",
url="https://github.... | StarcoderdataPython |
1626851 | import os
from aioresponses import aioresponses
from aiounittest import AsyncTestCase, futurized
from asyncopenstackclient import AuthPassword
from unittest.mock import patch
class TestAuth(AsyncTestCase):
def setUp(self):
self.auth_args = ('http://url', 'm_user', 'm_pass', 'm_project',
... | StarcoderdataPython |
3265087 | <filename>src/sfcparse/error.py
# error - Contains base exception
class SfcparseError(Exception):
"""
sfcparse base exception
"""
__PARENT_EXCEPTION_NAME = 'sfcparse'
def __init__(self, msg: str, item: str='') -> None:
self.msg = str(msg)
self.item = str(item)
def __str__(self)... | StarcoderdataPython |
60362 | <reponame>moonieann/welib<filename>welib/weio/flex_doc_file.py
from __future__ import division,unicode_literals,print_function,absolute_import
from builtins import map, range, chr, str
from io import open
from future import standard_library
standard_library.install_aliases()
from .file import File, WrongFormatError, B... | StarcoderdataPython |
88392 | <filename>shot_detector/legacy_objects/base_video_unit.py
# -*- coding: utf8 -*-
"""
This is part of shot detector.
Produced by w495 at 2017.05.04 04:18:27
"""
from __future__ import absolute_import, division, print_function
import itertools
import logging
import six
from .second import Second
class BaseV... | StarcoderdataPython |
1705446 | <gh_stars>0
names = ["Ace", "Gene", "Paul", "Peter"]
for name in names :
print name | StarcoderdataPython |
1776782 | import api_utils.test as tu
from core_api import constants
# NZS1170p5 Tests
def test_get_nzs1170p5_ensemble_hazard(config):
""" Tests the successful get request of a NZS1170p5 ensemble hazard"""
response = tu.send_test_request(
constants.NZS1170p5_HAZARD_ENDPOINT,
config["general"],
)
... | StarcoderdataPython |
147398 | <filename>setup.py
#! /usr/bin/env python
import sys
try:
from setuptools import setup
HAVE_SETUPTOOLS = True
except ImportError:
from distutils.core import setup
HAVE_SETUPTOOLS = False
VERSION = '0.1.3'
setup_kwargs = {
"version": VERSION,
"description": ('A fast, drop-in replacement for py... | StarcoderdataPython |
3385341 | #!/usr/bin/env python3
from .kast import *
from .kast import _fatal, _warning, _notif
from .kastManip import readKastTerm
from graphviz import Digraph
def graphvizImports(definitionFile):
kDefn = readKastTerm(definitionFile + ".json")
if not isKDefinition(kDefn):
_fatal("Can only build impo... | StarcoderdataPython |
4836221 | <gh_stars>0
# -*- coding: utf-8 -*-
"""
[riddle.py]
Riddle Plugin
[Author]
<NAME>
[About]
Returns a riddle or whether guess at the answer was correct or not.
[Commands]
>>> .riddle
returns a random riddle
.riddle guess <<attempt>>
returns whether the guess was correct or wrong
"""
import random
class Plugin:
d... | StarcoderdataPython |
1658093 | from requests import get # Import the function to talk with the API
from time import mktime, strptime, strftime, sleep # Import the function for time conversion
from os import path, sep # Import the function to check for the existence of config files
from sys import exit, executable # Import the function for... | StarcoderdataPython |
3205138 | <filename>snake_seq.py
def isColSafe(col):
return 0 <= col < m
def isRowSafe(row):
return 0 <= row < n
def isDiffOne(next, cur):
return next - 1 == cur
def build_snake(row, col, amount):
nextAmount = amount + 1
cur = matrix[row][col]
colLeft = col - 1
colRight = col + 1
rowUp = row - 1
rowDown = ro... | StarcoderdataPython |
1726394 | #!/usr/bin/env python
"""
A dummy web server used to test the LendingClub API requests
"""
"""
The MIT License (MIT)
Copyright (c) 2013 <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 wi... | StarcoderdataPython |
1758433 | import subprocess
def run(source_file, result_file):
command = "powershell C:\\ffmpeg\\bin\\ffmpeg.exe -i {} {}".format(source_file, result_file)
completed = subprocess.run(command, capture_output=True, shell=True, text=True, input="y")
return completed.returncode
if __name__ == '__main__':
convert =... | StarcoderdataPython |
184394 | import serial
import time
ser = serial.Serial('COM6', 9800, timeout=1)
ser.write(b'L')
def blink(numBlinks):
accum = 0
while accum < numBlinks:
ser.write(b'L')
time.sleep(0.05)
ser.write(b'H')
time.sleep(0.05)
accum += 1
var = int(input("Number of blinks... | StarcoderdataPython |
1675708 | # Generated by Django 2.0.2 on 2018-03-02 10:20
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('raster_aggregation', '0018_aggregationlayer_extent'),
]
operations = [
migrations.AlterField(
model_name='aggregationlayer',
... | StarcoderdataPython |
3239127 | import gym
from pathlib import Path
import random
from datetime import datetime
from gym import logger
from msevolution_env.envs.microstructure_evolution import DiscreteMsEvolutionWrapper
from msevolution_env.fem_env import FEMCSVLogger
from msevolution_env.fem_wrapper import ODF
# run random agent on single-goal env... | StarcoderdataPython |
4814280 | <gh_stars>10-100
#!/usr/bin/python
from __future__ import print_function
import os
import json
import difflib
import subprocess
import string
import argparse
import sys
import re
parser = argparse.ArgumentParser()
parser.add_argument('--accept-all',
help='accept all new results',
... | StarcoderdataPython |
3201353 | from __future__ import annotations
from prettyqt.qt import QtCore
class SignalBlocker(QtCore.QSignalBlocker):
pass
| StarcoderdataPython |
1646732 | <reponame>martingaston/bangbangnapster<gh_stars>1-10
import ipaddress
from src.link_type import LinkType
from src.payload_parser import parse_payload
class User:
def __init__(self, nick, password, ip, port, client_info, link_type):
self.nick: str = nick
self.password: str = password
self.i... | StarcoderdataPython |
1795591 | class Subject:
def __init__(self):
self.__observers = []
def attach(self, observer):
self.__observers.append(observer)
print(f'New observer: {observer}, total observers: {len(self.__observers)}')
def detach(self, observer):
self.__observers.remove(observer)
... | StarcoderdataPython |
3301925 | <filename>nlp/textsum/train.py
# -*- coding:utf-8 -*-
import math
import os
import sys
import time
import numpy as np
from six.moves import xrange
import tensorflow as tf
from nlp.textsum import model as seq2seq_model
from nlp.textsum.dataset import data_utils, dataset
def read_data(buckets, source_path, target_pa... | StarcoderdataPython |
3294734 | """ Initiate the python module
"""
from bifrost_benchmarks.pipeline_benchmarker import PipelineBenchmarker
| StarcoderdataPython |
3252636 | def gen_command(command_dict, prefix_list):
command_list = prefix_list.copy()
for key, val in command_dict.items():
if isinstance(val, bool):
if val == True:
command_list.append(f"--{key}")
else:
command_list.append(f"--{key} {val}")
return " ".join(co... | StarcoderdataPython |
1708338 | <gh_stars>100-1000
import numpy as np
from skmultiflow.drift_detection.hddm_w import HDDM_W
def test_hddm_w():
"""
HDDM_W drift detection test.
The first half of the data contains a sequence corresponding to a normal distribution with mean 0 and sigma 0.1.
The second half corresponds to a normal distr... | StarcoderdataPython |
3283006 | <filename>torchglyph/hooks.py
import json
from logging import getLogger
from pathlib import Path
from typing import Any, Set
from typing import List, Tuple, Dict
import torch
from tabulate import tabulate
from torch import nn
logger = getLogger(__name__)
LOG_TXT = 'log.txt'
ARGS_JSON = 'args.json'
SOTA_JSON = 'sota.... | StarcoderdataPython |
1662349 | <reponame>dlzou/baby-interpreter<gh_stars>0
#----------------------------------------------------------------------------#
# Imports
#----------------------------------------------------------------------------#
from flask import Flask, render_template, request
# from flask.ext.sqlalchemy import SQLAlchemy
import logg... | StarcoderdataPython |
1771674 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.hr_expense.tests.common import TestExpenseCommon
from odoo.tests import tagged
@tagged('-at_install', 'post_install')
class TestExpensesMailImport(TestExpenseCommon):
@classmethod
def setUpClas... | StarcoderdataPython |
68572 | <reponame>miglesias91/dt
# Generated by Django 2.2.1 on 2019-05-07 20:27
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('noticias', '0002_remove_nota_comentario'),
]
operations = [
migrations.AddField(
model_name='nota',
... | StarcoderdataPython |
181200 | from tuiuiu.tuiuiusearch.views.frontend import search # noqa
| StarcoderdataPython |
68103 | <reponame>DonaldMcC/py4web
import io
import os
import unittest
from py4web import request, response, Field, Session
from py4web.utils.form import Form
class FormTest(unittest.TestCase):
def setUp(self):
request.environ['wsgi.input'] = io.BytesIO()
request.cookies.clear()
response._cookies ... | StarcoderdataPython |
1745267 | <filename>lib/python3.8/site-packages/ansible_collections/community/network/plugins/modules/network/fortimanager/fmgr_ha.py
#!/usr/bin/python
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the ... | StarcoderdataPython |
4839824 | from collections import OrderedDict, defaultdict
import xlrd
from django.conf import settings
from django.db import transaction
from django.utils.translation import ugettext as _
from django.utils.safestring import mark_safe
from django.core.exceptions import ValidationError
from evap.evaluation.models import Course,... | StarcoderdataPython |
3274988 | <gh_stars>0
import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
#from models import Resource, Task
app = Flask(__name__)
app.config['SECRET_KEY'] = '<KEY>'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///pmappdb.db'
db = SQLAlchemy(app)
from pmapp import routes
#need to import the routes... | StarcoderdataPython |
3323215 | string = "hello world"
print(string.center(16,"x"))
| StarcoderdataPython |
1717235 | <reponame>ifer21/TomBot<gh_stars>0
import numpy as np
from market_maker.utils import math, constants
import logging
def profit_loss_cal(pos_size, entry_price, exit_price, leverage, funrate=0, short=False):
logger = logging.getLogger('root')
margin_XBT_nofees = pos_size / leverage / entry_price
entry_valu... | StarcoderdataPython |
1621460 | import os
from setuptools import setup, Extension
from subprocess import check_output, CalledProcessError, STDOUT
extra_compile_args = ['-O0', '-g']
extra_compile_args.append('-Wno-write-strings') # fix "warning: deprecated conversion from string constant to 'char*'"
extra_link_args = []
# To use the ARCH flag simp... | StarcoderdataPython |
111090 | #!/usr/bin/python3
# gdacs.py
import os
import json
from subprocess import Popen
from datetime import datetime
from selenium import webdriver
from time import sleep
from selenium.webdriver.firefox.options import Options
def download_geojson():
options = Options()
options.headless = True
profile = webdriv... | StarcoderdataPython |
3370059 | <gh_stars>10-100
from django.db import models
from utils.django_utils.base_model import BaseModel
from testsuite.models import TestSuite
# Create your models here.
class TestCase(BaseModel):
testcase_name = models.CharField(max_length=128, verbose_name='测试用例名称', help_text='测试用例名称')
testcase_desc = models.Ch... | StarcoderdataPython |
82683 | <reponame>wubx/vitess<filename>test/queryservice_tests/test_env.py
#!/usr/bin/env python
# Copyright 2012, Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can
# be found in the LICENSE file.
import contextlib
import json
import MySQLdb as mysql
import os
import shuti... | StarcoderdataPython |
4828712 | <filename>branches/process-threads-test/source.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import threading
import sys
import re
import socket
from datetime import date
from pygtail import Pygtail
from databasemodel import DatabaseModel
class Source(threading.Thread):
def __init__(self, db_name=None, group... | StarcoderdataPython |
1730266 | from graph.graph_types import Edge, Vertex
from typing import List
class Graph:
def __init__(self) -> None:
self.edges: List[Edge] = []
self.vertices: List[Vertex] = []
self.outneighbors: List[List[int]] = []
self.inneighbors: List[List[int]] = []
def add_edge(self, edge: Edge... | StarcoderdataPython |
89361 | <filename>py/challenger.py
"""
All rights reserved
"""
from .hexen import *
from . import uart
from .apdu import Apdu
from .loader import Loader
"""
class Challenger():
Extend methods of Tester class by authentication methods.
"""
class Challenger(Loader):
def __init__(self, *args, **kwargs):
super().__... | StarcoderdataPython |
21572 | # Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.
# Example:
# Given nums = [-2, 0, 3, -5, 2, -1]
# sumRange(0, 2) -> 1
# sumRange(2, 5) -> -1
# sumRange(0, 5) -> -3
class NumArray:
def __init__(self, nums):
"""
:type nums: List[int]
... | StarcoderdataPython |
1612680 | <gh_stars>0
r"""Vision models run saved model for inference"""
from absl import app
from absl import flags
import tensorflow as tf
from official.vision.beta.serving import run_lib
from official.common import flags as tfm_flags
FLAGS = flags.FLAGS
flags.DEFINE_string('saved_model_dir', None, 'Saved model directory.'... | StarcoderdataPython |
1755274 | '''
Get caption stats : maxlen and length distribution of caption words.
'''
import json
from os import stat
from typing import List
from tqdm import tqdm
import argparse
from config import Config
# Indic library
import sys
from indicnlp import common
INDIC_NLP_LIB_HOME=r"indic_nlp_library"
INDIC_NLP_RESOURCES=r"ind... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.