id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
11257967 | <filename>recipes/migrations/0014_tag_slug.py<gh_stars>0
# Generated by Django 3.1.1 on 2020-09-11 13:24
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('recipes', '0013_auto_20200911_1155'),
]
operations = [
migrations.AddField(
... | StarcoderdataPython |
324910 | #!/usr/bin/env python2.7
'''argparser.py: argparse example.'''
__author__ = '<NAME>'
import argparse
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='General description')
parser.add_argument('num', type=int,
help='required number')
parser.add_argument('-... | StarcoderdataPython |
3430977 | <reponame>kithsirij/NLP-based-Syllabus-Coverage-Exam-paper-checker-Tool<filename>database_insert_question_topic.py
import MySQLdb
import nltk
import string
import numpy as np
from nltk.corpus import stopwords
from nltk.stem.porter import *
from PyQt4 import QtGui
from PyQt4.QtGui import *
import math
import op... | StarcoderdataPython |
5059957 | from .edge import EdgeDao
from .point import PointDao
from .loc import LocDao
from .map import MapDao
from .redis_client import RedisDao | StarcoderdataPython |
1824243 | import socket
from centinel.experiment import Experiment
class TCPConnectExperiment(Experiment):
name = "tcp_connect"
def __init__(self, input_file):
self.input_file = input_file
self.results = []
self.host = None
self.port = None
def run(self):
for line in self.i... | StarcoderdataPython |
6703537 | <filename>Task2E.py
from datetime import datetime, timedelta
from floodsystem.datafetcher import fetch_measure_levels
import floodsystem.flood as flood
from floodsystem.stationdata import build_station_list, update_water_levels
from floodsystem.plot import plot_water_levels
def run():
stations = build_station_list... | StarcoderdataPython |
319273 | import os
import tempfile
import traceback
from threading import Thread
from easelenium.ui.file_utils import save_file
from easelenium.ui.parser.parsed_class import ParsedClass
from wx import ALL, EXPAND
FLAG_ALL_AND_EXPAND = ALL | EXPAND
def run_in_separate_thread(target, name=None, args=(), kwargs=None):
thre... | StarcoderdataPython |
136622 | <reponame>Alexhuszagh/fast_float
# text parts
processed_files = { }
# authors
for filename in ['AUTHORS', 'CONTRIBUTORS']:
with open(filename) as f:
text = ''
for line in f:
if filename == 'AUTHORS':
text += '// fast_float by ' + line
if filename == 'CONTRIBUTORS':
text += '// wit... | StarcoderdataPython |
4878217 | <filename>parsing/HeaderParser.py
import sys
import os
import io
import argparse
import pcpp
from pcpp import OutputDirective, Action
class Register:
width: int
name: str
addr: int
isIO: bool
def __repr__(self):
return "%s(0x%02x)" % (self.name, self.addr)
pcpp.CmdPreprocessor
# Processe... | StarcoderdataPython |
6550408 | # SPDX-License-Identifier: MIT
"""Todo handler
"""
import falcon
import todo
from middleware import login_required
from .base import RouteBase
class Todo(RouteBase):
"""Handles Todos
Args:
RouteBase (object): Baseclass
"""
@falcon.before(login_required)
def on_get(self, req, resp):
... | StarcoderdataPython |
6504692 | <gh_stars>10-100
import os
import h5py
from pyspark.sql import SparkSession
from pyspark.ml.linalg import Vectors
dataset_list = ['glove-25-angular', 'nytimes-16-angular', 'fashion-mnist-784-euclidean']
def convert(spark, outpath, data):
print('processing %s ... ' % outpath, end='')
vectors = map(lambda x: (... | StarcoderdataPython |
4962928 | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
## Converts h5 input to short format
## By: <NAME>
## Bring in system mod
import sys
# In[ ]:
## Set user defined variables
## Check we have three inputs!
assert (len(sys.argv) >= 4), "ERROR: This script must include:\n(1) The full path to a ginteractions (tsv) file... | StarcoderdataPython |
380413 | <gh_stars>0
CONFIGURATION_NAMESPACE = 'qmap'
# It is here and not inside the manager module to avoid circular imports
EXECUTION_ENV_FILE_NAME = 'execution'
EXECUTION_METADATA_FILE_NAME = 'execution'
class QMapError(Exception):
"""Base class for this package errors"""
pass
| StarcoderdataPython |
4937681 | <filename>races/project/controller.py<gh_stars>1-10
from project.core.car_factory import CarFactory
from project.driver import Driver
from project.race import Race
class Controller:
def __init__(self):
self.cars = []
self.drivers = []
self.races = []
self.car_factory = CarFactory(... | StarcoderdataPython |
388554 | ## TODO: define the convolutional neural network architecture
import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
# can use the below import should you choose to initialize the weights of your Net
import torch.nn.init as I
# helper conv() function to set up a convolu... | StarcoderdataPython |
177571 | # -*- coding: utf-8 -*-
import info
from Package.PerlPackageBase import *
class subinfo(info.infoclass):
def setDependencies( self ):
self.runtimeDependencies["dev-utils/perl"] = None
def setTargets(self):
for ver in ["0.016"]:
self.targets[ver] = f"https://search.cpan.org/CPAN/au... | StarcoderdataPython |
12826964 | import numpy as np
import pandas as pd
import sklearn.mixture as mix
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.dates import YearLocator, MonthLocator
import seaborn as sns
import missingno as msno
import quandl as qd
# reference:
# http://www.blackarbs.com/blog/introduction-hidden-marko... | StarcoderdataPython |
11386738 | <filename>pyblnet/__init__.py
from .blnet_web import BLNETWeb, test_blnet
from .blnet_conn import BLNETDirect
from .blnet import BLNET | StarcoderdataPython |
271247 | # Copyright 2017-present Open Networking Foundation
#
# 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 agr... | StarcoderdataPython |
1917651 | from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from .views import Login, logout_then_login
urlpatterns = [
path('login/', Login.as_view(), name='login'),
path('logout/', logout_then_login, name='logout'),
path('admin/', admin.site.urls),
path('... | StarcoderdataPython |
12838508 | import sys
from boto3.session import Session
from .models import Dataset
from .utils import get_headers
def get_instances_as_table(profile=None, region_name='us-east-1'):
session = Session(profile_name=profile)
ec2 = session.resource('ec2')
data = extract_data_from_objects(ec2.instances.all())
# enr... | StarcoderdataPython |
4800276 | import time
start = time.strftime('%H:%M:%S', time.localtime())
i =0
while True:
if (start != time.strftime('%H:%M:%S', time.localtime())):
print('Ops per second:',i/10**3, '\bk')
break
i+=1
| StarcoderdataPython |
116919 | '''
Finding minimum cost path in 2-D array "array[][]" to reach a position (left, right)
in array[][] from (0, 0).
Total cost of a path to reach (left, right) is sum of all the costs on that
path (including both source and destination).
'''
import sys
# Finding minimum cost path in 2-D array
def minimumCost(array,... | StarcoderdataPython |
3461518 | <filename>api/setup_evaluation.py<gh_stars>1-10
import os
import string
import subprocess
import logging
import json
from pathlib import Path
from collections import OrderedDict
from functools import reduce
import re
from math import floor
from multiprocessing import Pool, cpu_count
from random import seed
import rando... | StarcoderdataPython |
3398836 | <gh_stars>1000+
"""Define tests for the AEMET OpenData init."""
from unittest.mock import patch
import requests_mock
from homeassistant.components.aemet.const import DOMAIN
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import CONF_API_KEY, CONF_LATITUDE, CONF_LONGITUDE, CONF_NAME... | StarcoderdataPython |
8171147 | <reponame>mikiec84/ls.joyous<filename>ls/joyous/migrations/0004_auto_20180425_2355.py<gh_stars>10-100
# Generated by Django 2.0.3 on 2018-04-25 11:55
from django.db import migrations
import ls.joyous.models.events
import timezone_field.fields
class Migration(migrations.Migration):
dependencies = [
('joy... | StarcoderdataPython |
3492751 | from typing import List
class Solution:
def canJump(self, nums: List[int]) -> bool:
# the idea is to use DP and loop through "nums" reversely
# the base case is the "last position",
# this means if we are at the last position,
# we can win the jump game
g... | StarcoderdataPython |
3450703 | #!/usr/bin/env python
# pydle.py
# Copyright 2015 <NAME>.
#
# Licensed under the MIT License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://opensource.org/licenses/MIT
#
# Unless required by applicable law or agreed to in w... | StarcoderdataPython |
12824796 | <gh_stars>1-10
from ..utils import action, results_formatter
from functools import partial
import arep
import pytest
import os
results_formatter = partial(results_formatter, name=os.path.basename(__file__))
all_results = results_formatter({
(2, 4), (6, 8), (15, 12)
})
@pytest.fixture
def grepper():
engine =... | StarcoderdataPython |
4936438 | <filename>usaspending_api/search/v2/urls_search.py<gh_stars>0
from django.conf.urls import url
from usaspending_api.search.v2.views import search
from usaspending_api.search.v2.views import search_elasticsearch as es
from usaspending_api.search.v2.views.new_awards_over_time import NewAwardsOverTimeVisualizationViewSet
... | StarcoderdataPython |
152917 | from os import path, listdir, mkdir
from merge_db.save_merge import Database
from tqdm import tqdm
if __name__ == "__main__":
working_directory = "/Users/Mathieu/Desktop/"
db_folder = "{}/db2".format(working_directory)
# Be sure that the path of the folder containing the databases is correct.
asser... | StarcoderdataPython |
4868112 | import math
from multiprocessing import Pool
import numpy as np
import gym.spaces.prng as space_prng
from rl_teacher.utils import get_timesteps_per_episode
def _slice_path(path, segment_length, start_pos=0):
# TODO return var
return {
k: np.asarray(v[start_pos:(start_pos + segment_length)])
fo... | StarcoderdataPython |
6443656 | from django.test import TestCase
from events.models import Event
from events.models import Edition
# Create your tests here.
class EventModelTests(TestCase):
def setUp(self):
Event.objects.create(title='event title 1')
Event.objects.create(title='event title same title')
Event.objects.c... | StarcoderdataPython |
6656765 | from itertools import combinations, count
from typing import Callable, Iterable, List, Tuple
from projecteuler.util.timing import print_time
from util.primes import primes_until
DIGIT_STRINGS = list(map(str, range(10)))
def _get_primes_of_length(digits: int) -> Tuple[List[int], Callable[[int], bool]]:
"""
R... | StarcoderdataPython |
4987394 | from dataclasses import dataclass, field
from enum import Enum
from typing import List, Tuple, Set
from dataclasses_json import DataClassJsonMixin
from cloudrail.knowledge.utils.utils import hash_list
@dataclass
class PolicyEvaluation(DataClassJsonMixin):
resource_allowed_actions: Set[str] = field(default_facto... | StarcoderdataPython |
9778674 | import base64
import hashlib
from typing import List
import cbor2
from cryptography import x509
from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.backends import default_backend
from cryptography.x509.oid import NameOID
from webauthn.helpers.cose import COSEAlgorithmIdentifier
from webauth... | StarcoderdataPython |
9641620 | input = """
c num blocks = 1
c num vars = 100
c minblockids[0] = 1
c maxblockids[0] = 100
p cnf 100 465
-29 57 -100 0
-75 -16 66 0
72 73 93 0
63 -4 -61 0
-47 21 58 0
58 14 89 0
-26 81 50 0
-57 44 -56 0
31 93 -38 0
93 -57 99 0
-94 22 21 0
-45 71 75 0
-98 60 -34 0
-90 -37 87 0
73 1 -41 0
31 -90 89 0
-42 -39 82 0
-47 10 6... | StarcoderdataPython |
8160035 | <reponame>rudecs/jumpscale_core7
from JumpScale import j
def cb():
from .HashTool import HashTool
return HashTool()
j.base.loader.makeAvailable(j, 'tools')
j.tools._register('hash', cb)
| StarcoderdataPython |
8044750 | <reponame>albailey/config
#
# Copyright (c) 2021 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
from cgtsclient.common import base
class KubeCluster(base.Resource):
def __repr__(self):
return "<kube_cluster %s>" % self._info
class KubeClusterManager(base.Manager):
resource_class... | StarcoderdataPython |
275754 | '''Simple window with some custom values'''
import sys
from PyQt4 import QtGui
app = QtGui.QApplication(sys.argv)
w = QtGui.QWidget()
w.resize(300, 200)
w.move(100, 100)
w.setWindowTitle('Simple window')
w.show()
sys.exit(app.exec_())
| StarcoderdataPython |
11306471 | <reponame>afeinstein20/animal_colors
import numpy as np
import matplotlib.pyplot as plt
__all__ = ['Sensitivity']
class Sensitivity(object):
def __init__(self, animal):
"""
Sets the sensitivity scaling for different animals.
Sensitivity scalings are approximated as Gaussians.
Pa... | StarcoderdataPython |
9611952 | <reponame>JacobGrig/ML-volatility<filename>ml_volatility/ml_volatility/model/model.py
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
import statsmodels.api as sm
from sklearn.preprocessing import MinMaxScaler
from sklearn.ensemble import RandomForestRegressor
from scipy.optimize import fmin... | StarcoderdataPython |
1949690 | <filename>app.py<gh_stars>1-10
#!/usr/bin/env python3
"""
Copyright 2020 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at
http:... | StarcoderdataPython |
8084593 | import os, glob, gzip, sys
from subprocess import call
from requests_html import HTMLSession
def check_existing(save_loc, acc):
"""
Function to check for single- or paired-end reads
in a given `save_loc` for a particular `acc`ession.
Returns "paired" if paired reads found, "single" if
unpaired read... | StarcoderdataPython |
9656035 | # ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distrib... | StarcoderdataPython |
11394454 | from django.db import models
import datetime
# Create your models here.
YEAR_CHOICES = []
for r in range(1980, (datetime.datetime.now().year+1)):
YEAR_CHOICES.append((r,r))
class Publisher(models.Model):
name = models.CharField('Name', max_length=30, primary_key=True)
city = models.CharField('City', max... | StarcoderdataPython |
85725 | <reponame>avara1986/avara
from django.conf.urls import patterns, include, url
from django.contrib import admin
from avara import settings
from avara.routers import router
admin.autodiscover()
urlpatterns = patterns('',
url(r'^_ah/', include('djangae.urls')),
url(r'^admin/'... | StarcoderdataPython |
8154588 | <gh_stars>1-10
## ____ _ ____
## / ___|__ _ ___| |_ _ _ ___ / ___|__ _ _ __ _ _ ___ _ __
## | | / _` |/ __| __| | | / __| | | / _` | '_ \| | | |/ _ \| '_ \
## | |__| (_| | (__| |_| |_| \__ \ | |__| (_| | | | | |_| | (_) | | | |
## \____\__,_|\___|\__|\__,_|___/ \____\__,_|_| ... | StarcoderdataPython |
3485777 | <gh_stars>0
#!python
import string
# Hint: Use these string constants to ignore capitalization and/or punctuation
# string.ascii_lowercase is 'abcdefghijklmnopqrstuvwxyz'
# string.ascii_uppercase is 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
# string.ascii_letters is ascii_lowercase + ascii_uppercase
def is_palindrome(text):
... | StarcoderdataPython |
5097885 | <gh_stars>0
import chainer
import chainer.functions as F
import chainer.links as L
"""
Based on chainer official example
https://github.com/pfnet/chainer/tree/master/examples/ptb
Modified by shi3z March 28,2016
"""
class RNNLM(chainer.Chain):
"""Recurrent neural net languabe model for penn tree bank corpus.
... | StarcoderdataPython |
281450 | <filename>track17/exceptions.py
"""
Define custom exceptions
"""
__all__ = (
'Track17Exception',
'InvalidCarrierCode',
'DateProcessingError'
)
class Track17Exception(Exception):
def __init__(self, message: str, code: int = None):
self.message = message
self.code = code
super()... | StarcoderdataPython |
193852 | <reponame>belang/pymtl
#=======================================================================
# Bus.py
#=======================================================================
from pymtl import *
class Bus( Model ):
def __init__( s, nports, dtype ):
sel_nbits = clog2( nports )
s.in_ = [ InPort ( dtype... | StarcoderdataPython |
107045 | print("======================")
print("RADAR ELETRÔNICO!")
print("======================")
limite = 80.0
multa = 7
velocidade = float(input("Qual a sua velocidade: "))
if velocidade <= limite:
print("Boa Tarde, cuidado na estrada, siga viagem!")
else:
valor = (velocidade - limite) * 7
print(f"Você ultrap... | StarcoderdataPython |
5192629 | <reponame>Transkribus/TranskribusDU
'''
Created on 5 avr. 2019
@author: meunier
'''
import numpy as np
from graph.Graph import Graph
def test_one_edge():
o = Graph()
# 2 nodes linked by 1 edge
nf = np.array([
[0, 0]
, [1, 11]
])
e = np.array([
... | StarcoderdataPython |
3203782 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Python version: 3.6
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import copy
import numpy as np
from torchvision import datasets, transforms
import torch
import random
import csv
from utils.sampling import mnist_iid, mnist_noniid, cifar_iid
fr... | StarcoderdataPython |
11260631 | # django
from django.db import models
# graphql
from graphql.execution.base import ResolveInfo
# graphene
import graphene
# app
from ..registry import registry
def SnippetsQueryMixin():
class Mixin:
if registry.snippets:
class Snippet(graphene.types.union.Union):
class Meta:
... | StarcoderdataPython |
341700 | """
Author : <NAME>
Year : 2020
Model of the flask application, contains all the functions manipulating the database.
The database managed with TinyDB and stored in a file named **db.json**.
"""
from tinydb import TinyDB, Query, where
import networkx as nx
from networkx.algorithms import isomorphism as isoalg
# Bui... | StarcoderdataPython |
9656033 | import uuid
from app import db
from app.dao.dao_utils import transactional
from app.models import InboundNumber
def dao_get_inbound_numbers():
return InboundNumber.query.order_by(InboundNumber.updated_at).all()
def dao_get_available_inbound_numbers():
return InboundNumber.query.filter(InboundNumber.active, ... | StarcoderdataPython |
3500829 | # -*- coding: utf-8 -*-
import argparse
import logging
import os
import numpy as np
import scipy.io as sio
from matplotlib import pyplot as plt
import utils
from model import dsfa
net_shape = [128, 128, 6]
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
logging.basicConfig(format='%(asctime)-15s %(levelname)... | StarcoderdataPython |
4855885 | # Light LEDs at random and make them fade over time
#
# Usage:
#
# led_dance(delay)
#
# 'delay' is the time between each new LED being turned on.
#
# TODO The random number generator is not great. Perhaps the accelerometer
# or compass could be used to add entropy.
import microbit
import random
def led_dance(delay... | StarcoderdataPython |
319641 | <filename>slack/tests/conftest.py
import copy
import json
import time
import functools
from unittest.mock import Mock
import pytest
import requests
import asynctest
from slack.events import Event, EventRouter, MessageRouter
from slack.io.abc import SlackAPI
from slack.actions import Action
from slack.actions import Ro... | StarcoderdataPython |
8192536 | <reponame>shawnmullaney/python-isc-dhcp-leases
from distutils.core import setup, Command
def discover_and_run_tests():
import os
import sys
import unittest
# get setup.py directory
setup_file = sys.modules['__main__'].__file__
setup_dir = os.path.abspath(os.path.dirname(setup_file))
# us... | StarcoderdataPython |
289919 | from io import BytesIO
from os import makedirs, path
from configparser import ConfigParser, SectionProxy
from rich import print
from jinja2 import Environment
import click
from docker import APIClient, errors
from freshenv.console import console
from freshenv.provision import get_dockerfile_path
from requests import ex... | StarcoderdataPython |
1659967 | <reponame>harshlohia11/Text-Detection
from imutils.object_detection import non_max_suppression
import numpy as np
import cv2
import pytesseract
import argparse
import time
ap=argparse.ArgumentParser()
ap.add_argument("-i", "--image", type=str,
help="path to input image")
ap.add_argument("-east", "--east", t... | StarcoderdataPython |
3400623 | class Solution(object):
def findDisappearedNumbers(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
res = []
numset = set(nums)
N = len(nums)
for num in range(1, N + 1):
if num not in numset:
res.append(num)
... | StarcoderdataPython |
5035100 | from typing import List
from data_sets_reporter.classes.data_class.data_set_info_for_reporter import DataSetInfoForReporter
from data_sets_reporter.classes.data_set_string_reporter.data_set_validator.data_set_report_validator import DataSetValidator
from data_sets_reporter.exceptions.register_exeptions import WrongInp... | StarcoderdataPython |
12864929 | <reponame>AntonVasko/CodeClub-2021-SUMMER<filename>4. 01.07.2021/0. Secret Messages. New position.py
#Secret Messages. New position
alphabet = 'abcdefghijklmnopqrstuvwxyz'
key = 3
character = input('Please enter a character ')
position = alphabet.find(character)
print('Position of a character ', character, ' is ', pos... | StarcoderdataPython |
4871474 | <filename>SfmLearner-Pytorch/loss_functions.py
from __future__ import division
import torch
from torch import nn
import torch.nn.functional as F
from inverse_warp import inverse_warp
class SSIM(nn.Module):
"""Layer to compute the SSIM loss between a pair of images
"""
def __init__(self):
super(SSIM... | StarcoderdataPython |
1837621 | #!/usr/bin/env python
# Copyright 2014 Netflix
"""Append missing newlines to the end of source code files
"""
import os
import stat
SOURCE_CODE_EXTENSIONS = set(('py',)) # 'css','js','html',...
def walk(path):
"""Wraps os.walk"""
result = []
for root, _, filenames in os.walk(path):
for name ... | StarcoderdataPython |
1834596 | <gh_stars>1-10
# -*- coding: utf-8 -*-
import re
from os.path import dirname, join
from setuptools import find_packages, setup
with open(join(dirname(__file__), 'pipelines', '__init__.py')) as fp:
for line in fp:
m = re.search(r'^\s*__version__\s*=\s*([\'"])([^\'"]+)\1\s*$', line)
if m:
... | StarcoderdataPython |
6482770 | <gh_stars>0
class Solution:
def PredictTheWinner(self, nums: List[int]) -> bool:
dp = {}
def getMaxDiff(left, right):
if (left, right) not in dp:
if left == right:
return nums[left]
dp[left, right] = max(nums[left] - ge... | StarcoderdataPython |
1923410 | <reponame>thevahidal/hoopoe-python
from decouple import config
from hoopoe import Hoopoe
hoopoe = Hoopoe(
api_key=config("API_KEY"),
version=config("VERSION", default="1"),
base_url=config("BASE_URL", default="https://api.hoopoe.com"),
)
print(hoopoe.timestamp())
print(hoopoe.upupa("Hello World!"))
| StarcoderdataPython |
8168597 | <gh_stars>1-10
class Solution:
def calPoints(self, ops: List[str]) -> int:
stack = []
for op in ops:
if op == 'C':
stack.pop()
elif op == 'D':
v = stack.pop()
stack.append(v)
stack.append(v * 2)
... | StarcoderdataPython |
3254378 | <filename>src/background.py
# Copyright (C) 2022 viraelin
# License: MIT
from PyQt6.QtCore import *
from PyQt6.QtWidgets import *
from PyQt6.QtGui import *
class Background(QGraphicsRectItem):
def __init__(self) -> None:
super().__init__()
self.setZValue(-1000)
size = 800000
siz... | StarcoderdataPython |
9615131 | <reponame>JackieMa000/problems<filename>test_240.py<gh_stars>0
# https://leetcode-cn.com/problems/search-a-2d-matrix-ii/
import unittest
from typing import List
class Solution:
def binary_search(self, nums: List[int], target: int) -> int:
left, right = 0, len(nums) - 1
while left <= right:
... | StarcoderdataPython |
6504857 | import json
import logging
from pathlib import Path
from flow_py_sdk.cadence import Address
from flow_py_sdk.signer import InMemorySigner, HashAlgo, SignAlgo
log = logging.getLogger(__name__)
class Config(object):
def __init__(self) -> None:
super().__init__()
self.access_node_host: str = "loca... | StarcoderdataPython |
11279129 | <filename>publisher.py
import paho.mqtt.client as paho
import time
def on_publish(client, userdata, mid):
print("mid: "+str(mid))
client = paho.Client()
client.on_publish = on_publish
client.username_pw_set("ylfxubjy", "Bo3U7GcN5NAF")
client.connect("postman.cloudmqtt.com", 14843, 60)
client.loop_start()
while... | StarcoderdataPython |
5122355 | <filename>app.py
from flask import Flask
from flask import request, jsonify
app = Flask(__name__)
def change(amount):
# calculate the resultant change and store the result (res)
res = []
coins = [1, 5, 10, 25] # value of pennies, nickels, dimes, quarters
coin_lookup = {25: "quarters", 10: "dimes", ... | StarcoderdataPython |
1768938 | # Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
# Copyright 2019 The OSArchiver Authors. All rights reserved.
"""
Destination abstract base class file
"""
from abc import ABCMeta, abstractmethod
class Destination(metaclass=ABCMeta):
"""
The Destination a... | StarcoderdataPython |
11295733 | """
Some helper functions and classes used throughout the test suite
Constants:
TEST_DIR
COMMIT_DATAFILE
DEST_REPO_PREFIX
FEATURE_BRANCH
DEST_MASTER_COMMITS
DEST_FEATURE_COMMITS
ITEM_OPS_RETURN_VALUE
Helper functions:
load_iter_commits(repo, branch='master', mode='dict')
load_commi... | StarcoderdataPython |
4901777 | <gh_stars>1-10
import pathlib
import time
import subprocess
from cycler import cycler
import yaqc_bluesky
from yaqd_core import testing
from bluesky import RunEngine
from bluesky.plans import rel_spiral
__here__ = pathlib.Path(__file__).parent
@testing.run_daemon_entry_point(
"fake-triggered-sensor", config=__h... | StarcoderdataPython |
3495697 | from __future__ import print_function
import os
import shutil
import subprocess
import sys
from threading import Timer
import ustrings
if sys.version_info < (2, 7):
import unittest2 as unittest
else:
import unittest
from ..configuration import IrodsConfig
from .. import test
from .. import lib
from .resource... | StarcoderdataPython |
9610120 | import io
import os
import json
import logging
from copy import deepcopy
from collections import OrderedDict
from django.shortcuts import render
from django.core.exceptions import ValidationError
from django.http import Http404, HttpResponse
from django.db import transaction
from django.db.models import Subquery, Oute... | StarcoderdataPython |
8155503 | <gh_stars>0
import socket
hostname = socket.gethostname()
ROOT = '/scratch2/www/signbank/'
BASE_DIR = ROOT+'repo/'
WRITABLE_FOLDER = ROOT+'writable/'
# Added test database, to run unit tests using this copy of the database, use -k argument to keep test database
# python bin/develop.py test -k
DATABASES = {'def... | StarcoderdataPython |
4873350 | <gh_stars>0
from django.apps import AppConfig
class NpcConfig(AppConfig):
name = 'npc'
| StarcoderdataPython |
3450193 | # from .build_model import *
# from .feat_extr_model import *
#
# __all__ = ["Clustermodel", "FeatureExtractor"]
| StarcoderdataPython |
251304 | <gh_stars>0
"""
captcha-tensorflow
Copyright (c) 2017 <NAME>
https://github.com/JackonYang/captcha-tensorflow/blob/master/captcha-solver-model-restore.ipynb
"""
from os import path
# import matplotlib.pyplot as plt
import numpy as np # linear algebra
import tensorflow as tf
from keras.models import load_model
from P... | StarcoderdataPython |
72725 | <reponame>radiumweilei/chinahadoop-ml-2
#!/usr/bin/python
# -*- coding:utf-8 -*-
import numpy as np
from sklearn import svm
import matplotlib.colors
import matplotlib.pyplot as plt
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, fbeta_score
import warnings
def show_accuracy(a, b)... | StarcoderdataPython |
3376771 | #!/usr/bin/env python3
from taptaptap3 import TapDocumentValidator, parse_string
from taptaptap3.exc import TapMissingPlan, TapInvalidNumbering
from taptaptap3.exc import TapBailout, TapParseError
import io
import pickle
import unittest
def parse(source, strict=False):
return parse_string(source, lenient=not st... | StarcoderdataPython |
272216 | #!/usr/bin/env python
# Copyright 2016 University of Chicago
# Licensed under the APL 2.0 license
import argparse
import os
import re
import shutil
import subprocess
import sys
import time
import psycopg2
import fsurfer
import fsurfer.helpers
import fsurfer.log
PARAM_FILE_LOCATION = "/etc/fsurf/db_info"
VERSION = f... | StarcoderdataPython |
6583492 | """
ipwatch.py - version 0.0.1
Released under MIT license
https://github.com/packetflare/ipwatch/
OSX Menu widget that displays the user's current public IP address and
associated informaton as detected by the service https://ipinfo.io/.
A request to ipinfo.io is triggered if the application detects a change
in an... | StarcoderdataPython |
8063523 | <filename>pydocx/openxml/drawing/transform_2d.py
# coding: utf-8
from __future__ import (
absolute_import,
print_function,
unicode_literals,
)
from pydocx.models import XmlModel, XmlChild, XmlAttribute
from pydocx.openxml.drawing.extents import Extents
class Transform2D(XmlModel):
XML_TAG = 'xfrm'
... | StarcoderdataPython |
3207925 | # -*- coding: utf-8 -*-
from __future__ import (
division, absolute_import, print_function, unicode_literals,
)
from builtins import * # noqa
from future.builtins.disabled import * # noqa
from magic_constraints.exception import MagicSyntaxError, MagicTypeError
def transform_to_slots(constraints... | StarcoderdataPython |
3382952 | import codecs
import sys
def transformer(data_in, data_out, vocab):
id2tokens = {}
tokens2id = {}
with codecs.open(vocab, "r") as f1:
for line in f1.readlines():
token, id = line.strip().split("##")
id = int(id)
id2tokens[id] = token
tokens2id[token] ... | StarcoderdataPython |
11356324 | from crits.actors.actor import Actor
from crits.services.analysis_result import AnalysisResult
from crits.campaigns.campaign import Campaign
from crits.certificates.certificate import Certificate
from crits.comments.comment import Comment
from crits.domains.domain import Domain
from crits.emails.email import Email
from... | StarcoderdataPython |
3477394 | import re
from typing import List
from pygls.lsp.types.basic_structures import (
Diagnostic,
DiagnosticSeverity,
Position,
Range,
)
from pygls.workspace import Document
from server.ats.trees.common import BaseTree, YamlNode
class ValidationHandler:
def __init__(self, tree: BaseTree, document: Doc... | StarcoderdataPython |
1854384 | # 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 |
3429135 | <filename>hokonui/exchanges/mock.py
''' Module for Exchange base class '''
# pylint: disable=duplicate-code, line-too-long
import time
from hokonui.models.ticker import Ticker
from hokonui.utils.helpers import apply_format_level
class Mock():
''' Class Mock exchanges '''
TICKER_URL = None
ORDER_BOOK_URL... | StarcoderdataPython |
8000561 | import re
import sys
with open(sys.argv[1], 'r') as test_cases:
for test in test_cases:
stringe = test.strip()
multipliers = re.findall("\d+",stringe)
limitop = int(len(multipliers)/2)
total = []
for i in range(0,limitop):
total.append(str((int(multipli... | StarcoderdataPython |
3507712 | from manim import *
import networkx as nx
import json
import ast
class Geometry:
def __init__(self):
pass
def get_intersection(self, line1, line2):
xdiff = np.array([line1[0][0, 0] - line1[1][0, 0], line2[0][0, 0] - line2[1][0, 0]]).reshape((2, 1))
ydiff = np.array([line1[0][1, 0] - l... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.