id
stringlengths
1
7
text
stringlengths
6
1.03M
dataset_id
stringclasses
1 value
195421
#!/usr/bin/env python #The MIT License (MIT) #Copyright (c) 2016 <NAME> # #THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF #MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIG...
StarcoderdataPython
4842491
import logging from huobi.connection.impl.websocket_watchdog import WebSocketWatchDog from huobi.connection.impl.websocket_manage import WebsocketManage from huobi.connection.impl.websocket_request import WebsocketRequest from huobi.constant.system import WebSocketDefine, ApiVersion class SubscribeClient(object): ...
StarcoderdataPython
3324293
<gh_stars>0 # -*- encoding: utf-8 -*- """ Script para realizar a coleta dos tweets. """ import argparse from watching.tweetcollector import TweetCollector parser = argparse.ArgumentParser(description='Coletor de tweets.') parser.add_argument('--run-forever', action='store_true', help='O programa não é finalizado n...
StarcoderdataPython
1625644
from flask import render_template,redirect,url_for,flash,request from ..models import User, Subscriber, Post from .forms import LoginForm, RegistrationForm, SubscriberForm from .. import db from . import auth from ..email import mail_message from flask_login import login_user,logout_user,login_required, current_user ...
StarcoderdataPython
1716364
<filename>src/bq_test_kit/data_literal_transformers/__init__.py # Copyright (c) 2020 <NAME> # # This software is released under the MIT License. # https://opensource.org/licenses/MIT # C0114 disabled because this module contains only export # pylint: disable=C0114 from bq_test_kit.data_literal_transformers.base_data_...
StarcoderdataPython
1683747
import core import proto.framework_pb2 as framework_pb2 from framework import OpProtoHolder, Variable, Program, Operator from initializer import Constant, Normal, Xavier, Initializer from paddle.v2.fluid.layer_helper import LayerHelper, unique_name import re import cStringIO from param_attr import ParamAttr import cont...
StarcoderdataPython
3225470
""" Edge Examples """ __version__ = "$Revision: 1.13 $" import sys, os thisPath = os.path.dirname(os.path.abspath(__file__)) sys.path.append(os.path.abspath(os.path.join(thisPath,".."))) from ExampleBuilders.ExampleBuilder import ExampleBuilder from Core.IdSet import IdSet import Core.ExampleUtils as ExampleUtils from...
StarcoderdataPython
1678167
<filename>components/album-service/src/add_subscription_to_album_task_processor.py ''' add_subscription_to_album_task_processor.py Processes tasks to add subscriptions to albums Author: <NAME> eMail: <EMAIL> GPG-Key-ID: <KEY> GPG-Fingerprint: A757 5741 FD1E 63E8 357D  48E2 3C68 AE70 B2F8 AA17 License: MIT License '''...
StarcoderdataPython
9112
import logging from collections import namedtuple logger = logging.getLogger("pybinsim.Pose") class Orientation(namedtuple('Orientation', ['yaw', 'pitch', 'roll'])): pass class Position(namedtuple('Position', ['x', 'y', 'z'])): pass class Custom(namedtuple('CustomValues', ['a', 'b', 'c'])): pass cl...
StarcoderdataPython
1636636
import unittest from kubragen import KubraGen from kubragen.jsonpatch import FilterJSONPatches_Apply, ObjectFilter, FilterJSONPatch from kubragen.provider import Provider_Generic from kg_kubestatemetrics import KubeStateMetricsBuilder, KubeStateMetricsOptions class TestBuilder(unittest.TestCase): def setUp(self...
StarcoderdataPython
64279
<reponame>cmlohr/small-python-projects print("#######################################") print("## AVERAGE STUDENT HEIGHT CALCULATOR ##") print("#######################################") #test heights: 123 149 175 183 166 179 125 student_heights = input(" Input a list of student heights:\n>> ").split() for n in range(...
StarcoderdataPython
108445
<filename>demo/views.py from django.db.models import Q from rest_framework import decorators from rest_framework.generics import CreateAPIView, ListAPIView from rest_framework.mixins import DestroyModelMixin, ListModelMixin from rest_framework.permissions import IsAdminUser from devathon.viewsets import ActionModelVie...
StarcoderdataPython
4829098
import random from PIL import Image, ImageDraw import numpy as np import csv import math def ReadKeys(image: Image) -> list: """Input an image and its associated SIFT keypoints. The argument image is the image file name (without an extension). The image is read from the PGM format file image...
StarcoderdataPython
78025
# from zemailer.app.core import Settings, initialized_settings # from zemailer.app.core.mixins.patterns import PatternsMixin # from zemailer.app.core.sender import SendEmail, SendEmailWithAttachment # from zemailer.app.core.servers import Gmail, Outlook # from zemailer.app.patterns import schools # # from zemailer.app....
StarcoderdataPython
1690506
<gh_stars>1-10 from typing import List from vardautomation import FileInfo FILEINFO_ATTR: List[str] = [ 'path', 'path_without_ext', 'work_filename', 'idx', 'preset', 'name', 'workdir', 'a_src', 'a_src_cut', 'a_enc_cut', 'chapter', 'clip', '_trims_or_dfs', 'clip_...
StarcoderdataPython
3240839
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Jan 26 12:23:55 2019 @author: jxf """ import pandas as pd import numpy as np import matplotlib.pyplot as plt import datetime #has incomplete data. 999 points are NaN def read_file(fname): with open(fname, "r") as f: try: line1= ...
StarcoderdataPython
172929
<filename>ABC/abc001-abc050/abc025/b.py # -*- coding: utf-8 -*- # AtCoder Beginner Contest def main(): n, a, b = list(map(int, input().split())) position = 0 for i in range(n): s, d = list(map(str, input().split())) if int(d) < a: d = a elif int(d) > b: d ...
StarcoderdataPython
107320
import heapq import random class myHeapContainer(list): heap = None is_max_heap = None def _is_in_order(self, parent, child): comp_val = parent > child #print comp_val if self.is_max_heap: return comp_val else: return (not comp_val) def __init__(self, arr = None, is_max = False): self.is_max_heap...
StarcoderdataPython
3341451
<reponame>tansyab1/PhD-project import scipy import os import numpy as np def loadimage(filename): img = scipy.misc.imread(filename).astype(np.float) return img def loadimage_gray(filename): img = scipy.misc.imread(filename, mode='L').astype(np.float)[:,:,np.newaxis] return img def saveimages(outimage...
StarcoderdataPython
3306810
<reponame>thisdwhitley/ansible-role-add-repo import os import testinfra.utils.ansible_runner testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') def test_chrome_installed(host): assert host.package('google-chrome-stable').is_installed
StarcoderdataPython
16332
<gh_stars>0 #!/usr/bin/python from ansible.module_utils.basic import * from jdll import API ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'version': '1.0'} DOCUMENTATION = ''' --- module: book author: "<NAME> (@Spredzy)" version_added: "2.3" short_des...
StarcoderdataPython
166074
import pandas as pd from modules import tqdm import argparse import codecs import os def conll2003_preprocess( data_dir, train_name="eng.train", dev_name="eng.testa", test_name="eng.testb"): train_f = read_data(os.path.join(data_dir, train_name)) dev_f = read_data(os.path.join(data_dir, dev_name)) ...
StarcoderdataPython
15754
<filename>pytint/machine_io.py from pytint.interpreters import FiniteAutomaton from typing import List, Union, Dict, Iterable import collections import yaml class IncompleteMachine(Exception): def __init__(self, missing: str, machine_type: str): self.missing = missing self.machine_type = machine_t...
StarcoderdataPython
4807749
# -*- coding: utf-8 -*- from ws2812 import WS2812 ring = WS2812(spi_bus=1, led_count=16) data = [ (24, 0, 0), (0, 24, 0), (0, 0, 24), (12, 12, 0), (0, 12, 12), (12, 0, 12), (24, 0, 0), (21, 3, 0), (18, 6, 0), (15, 9, 0), (12, 12, 0), (9, 15, 0), (6, 18, 0), (3...
StarcoderdataPython
3210304
from __future__ import absolute_import try: from ._version \ import \ __version__ except ImportError as e: __version__ = "no-built" from .package \ import\ PackageInfo from .pool \ import\ Pool from .repository \ import\ Repository from .request \ im...
StarcoderdataPython
110094
"""Alarmageddon main module""" __version__ = "1.1.2" from alarmageddon.run import run_tests, construct_publishers, load_config
StarcoderdataPython
1705541
# -*- coding: utf-8 -*- # # @Author: <NAME> (<EMAIL>) # @Date: 2021-08-18 # @Filename: plot_skymakercam.py # @License: BSD 3-clause (http://www.opensource.org/licenses/BSD-3-Clause) # from lvmtan run: # poetry run container_start --name lvm.all # from lvmpwi run: # poetry run container_start --name=lvm.sci.pwi --simul...
StarcoderdataPython
4839575
from datetime import datetime, timedelta, timezone from typing import Any import pytest from queuery_client.cast import _cast_type, cast_row @pytest.mark.parametrize( "value, typename, desired", [ ("2", "smallint", 2), ("123", "integer", 123), ("12345", "bigint", 12345), ("3....
StarcoderdataPython
86293
from django.urls import path, include from django.conf.urls import url from django.conf import settings from django.conf.urls.static import static from . import views urlpatterns=[ path('register/', views.register, name='my_instagram-register'), ] if settings.DEBUG: urlpatterns+= static(settings.MEDIA_U...
StarcoderdataPython
49155
from price_picker.common.database import CRUDMixin from price_picker import db class Shop(CRUDMixin, db.Model): """ Shops """ __tablename__ = 'shops' name = db.Column(db.String(128), primary_key=True, unique=True, default="Zentrale") @classmethod def query_factory_all(cls): # insert defau...
StarcoderdataPython
1761444
<filename>aiommy/permissions/base.py from aiohttp import web class BasePermission(object): async def check_permission(self, request): return async def get_response(self): return web.HTTPForbidden()
StarcoderdataPython
3239942
from autotext import Autotext from sklearn.metrics import accuracy_score from sklearn.metrics import f1_score from sklearn.metrics import precision_score from sklearn.metrics import recall_score from sklearn.feature_extraction.text import TfidfVectorizer import csv root = '../datasets/' train_sets = ['20_newsgroups/']...
StarcoderdataPython
17400
import numpy as np import pandas as pd import os.path as path import abydos.distance as abd import abydos.phonetic as abp import pytest from scipy.sparse import csc_matrix from sklearn.feature_extraction.text import TfidfVectorizer import name_matching.name_matcher as nm @pytest.fixture def name_match(): package...
StarcoderdataPython
26447
from .base import ENDPOINT, process_response class ReviewsMixin: @process_response def get_review_details(self, review_id, **kwargs): """ GET /review/{review_id} """ url = f"{ENDPOINT}/3/review/{review_id}" return self.make_request("GET", url, kwargs)
StarcoderdataPython
1715264
class atl_IDE_webappserver(tornado.web.Application): class WSBlocksSubHandler(tornado.websocket.WebSocketHandler): def open(self): self.get_logger().info('[Server] WSBlocksSub client connected') self.application._blocks = self def on_close(self): self.get_logger().info('[Server] WSBlocksSub client disco...
StarcoderdataPython
3314081
# Copyright 2020 DeepMind Technologies Limited. # # 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 ag...
StarcoderdataPython
190162
"""Load notebook and cells""" import argparse import tarfile import os import chardet from reproducemegit.jupyter_reproducibility import config from reproducemegit.jupyter_reproducibility import consts from reproducemegit.jupyter_reproducibility.db import RequirementFile, Repository, connect from reproducemegit.jupyt...
StarcoderdataPython
109202
<reponame>yasserglez/pytiger2c<filename>packages/pytiger2c/ast/binaryoperatornode.py # -*- coding: utf-8 -*- """ Clase C{BinaryOperatorNode} del árbol de sintáxis abstracta. """ from pytiger2c.ast.operatornode import OperatorNode class BinaryOperatorNode(OperatorNode): """ Clase C{BinaryOperatorNode} del ár...
StarcoderdataPython
3266699
# DO NOT MODIFY THIS FILE!!! from unittest import TestCase from lab_questions import q3_which_number_is_larger as q3 class Q3Test(TestCase): def test_which_number_larger_same_numbers(self): msg = 'When called with %.1f and %.1f, which_number_is_larger() should return "same"' self.assertEqual('...
StarcoderdataPython
3255381
<gh_stars>1-10 ''' Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. The MIT License (MIT) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including w...
StarcoderdataPython
1604815
<gh_stars>0 from django.test import TestCase from django.contrib.auth.models import User from .models import Profile,Post,Comment,Location,Category,Neighborhood,Business # Tests class ProfileTestClass(TestCase): # Set up method def setUp(self): self.user = User.objects.create_user(username='testuser', ...
StarcoderdataPython
195639
<gh_stars>0 import tkinter as tk from PIL import ImageTk, Image import numpy as np import json import matplotlib.pyplot as plt from double_edges import choose_double_edges from euler_path import euler_path from path_variables import data_folder CIRCLE_SIZE = 10 DOUBLE_EDGE_WIDTH = 5 BACKGROUND_FILENAME = data_folder ...
StarcoderdataPython
112958
<filename>catfood.py import getpass import smtplib from email.mime.text import MIMEText from email.utils import formataddr import urllib.request, urllib.parse, urllib.error import ssl import json import time import re import os import sys # Email setting for notification def Email(sender, password, recipient, emailsub...
StarcoderdataPython
3396523
<reponame>salvatorecalo/nebula8<gh_stars>1-10 #!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright SquirrelNetwork from core import decorators from core.handlers.logs import sys_loggers, telegram_loggers from core.utilities.functions import ( ban_user_reply, ban_user_by_username, ban_user_by_id, bot_object, ...
StarcoderdataPython
92519
<gh_stars>0 #!/usr/bin/env python import pika from kafka import KafkaConsumer import json import utm import requests import os from xml.dom import minidom import datetime connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost')) channel = connection.channel() channel.exchange_declare(exchange='...
StarcoderdataPython
3300825
import snekspec.core as s import hypothesis.strategies as hst import hypothesis as h def _spec(): rating_spec = s.is_float() good_rating_spec = s.and_(rating_spec, s.PredSpec(lambda x: x > 0.6)) return s.keys({'first': s.is_any(), 'last': s.is_string(), ...
StarcoderdataPython
86187
"""DISTRO IGNITER CLI Usage: pycli start pycli -h|--help pycli -v|--version Options: start Starts the CLI -h --help Display the available commands -v --version Display CLI version """ from __future__ import print_function, unicode_literals from docopt import docopt import os import glob from PyInquirer ...
StarcoderdataPython
120523
<filename>flasky.py import os from app import create_app, db from app.models import User,Cult,Rating,Post from flask_migrate import Migrate app = create_app(os.getenv('FLASK_CONFIG') or 'default') migrate = Migrate(app, db) @app.shell_context_processor def make_shell_context(): return dict(db=db, User=User, Cult...
StarcoderdataPython
1601847
from abstract_factory import CommandHandler import random, string class User: """ To instantiate and store users. Cool things you can do: - Add a different neo4j url_location for each user - each user has their own command handler """ def __init__(self, name, ...
StarcoderdataPython
170709
<gh_stars>0 def test_client_can_get_avatars(client): resp = client.get('/api/avatars') assert resp.status_code == 200 def test_client_gets_correct_avatars_fields(client): resp = client.get('/api/avatars') assert 'offset' in resp.json assert resp.json['offset'] is None assert 'total' in resp.js...
StarcoderdataPython
195408
<filename>tests/test_arwn_collect.py #!/usr/bin/env python # -*- coding: utf-8 -*- """ test_arwn ---------------------------------- Tests for `arwn` module. """ import sys import mock import testtools import unittest from arwn.cmd import collect from . import arwn_fixtures class TestArwnCollect(testtools.TestCa...
StarcoderdataPython
3315428
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Measurement smoke test to make sure that no new action_name_to_run is defined.""" import os import optparse import logging import unittest from measureme...
StarcoderdataPython
1681486
<filename>bloodhound_search/bhsearch/tests/whoosh_backend.py # -*- coding: UTF-8 -*- # 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...
StarcoderdataPython
190459
<reponame>AartGoossens/goldencheetahlib import vcr # Set to True to enable 'once' mock recording MOCK_RECORDING_ENABLED = False vcr = vcr.VCR( cassette_library_dir='tests/mock/', record_mode='once' if MOCK_RECORDING_ENABLED else 'none', match_on=['uri'], )
StarcoderdataPython
3387321
with open('input') as f: binarr = [] for i in f.readlines()[0]: binarr.append(0) for line in f.readlines(): for i in range(line): binarr[i] += line[i] print(binarr)
StarcoderdataPython
1705572
<filename>agora_graphql/gql/__init__.py """ #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=# Copyright (C) 2018 <NAME>. #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file...
StarcoderdataPython
4827856
<gh_stars>0 #!/usr/bin/env python ''' Example script that generates FEFF input files from a cif file Remove comment # on write line to actually write files to disk ''' from __future__ import division __author__ = "<NAME>" __credits__= "<NAME>, <NAME>" __copyright__ = "Copyright 2012, The Materials Project" __version...
StarcoderdataPython
184517
from nflows.distributions.base import Distribution import torch class ProdDist(Distribution): """A Product Distribution with arbitrary marginals.""" def __init__(self, shape, marginals): super().__init__() self._shape = torch.Size(shape) self.d = self._shape[0] self.marginals =...
StarcoderdataPython
1621445
<reponame>CatsAreFluffy/generator-regex '''This is a generator based regex module.''' class RegexState: '''An internal state for the regex engine.''' def __init__(self,string,index=0,captured=None,capturing=None): '''Create a new internal state. Implicitly opens group 0.''' self.string=string ...
StarcoderdataPython
22601
import pytest from labelsync.github import Github from labelsync.helpers import HTTPError from tests.helpers import fl, FIXTURES_PATH, create_cfg_env, get_labels c = create_cfg_env('good.cfg') github = Github(c, name='github', api_url='https://api.github.com/repos') label = { 'name':'blabla', 'color':...
StarcoderdataPython
3209909
import argparse, textwrap parser = argparse.ArgumentParser( description=textwrap.dedent( """\ A python script to fetch submissions and comments using PRAW API """ ), usage='Use "python3 %(prog)s -h" for more information', formatter_class=argparse.RawTextHelpFormatter, ...
StarcoderdataPython
1730648
""" 2016 Day 5 https://adventofcode.com/2016/day/5 """ from functools import lru_cache from hashlib import md5 import aocd # type: ignore @lru_cache def md5hash(door: str, index: int) -> str: """ Calculate the md5 hash for the given Door ID and integer index. """ return md5((door + str(index)).encod...
StarcoderdataPython
4835099
import torch from torch import nn from mish_activation import Mish class Head(nn.Module): def __init__(self, nc, n, ps=0.5): super().__init__() layers = ( [AdaptiveConcatPool2d(), Mish(), Flatten()] + bn_drop_lin(nc * 2, 512, True, ps, Mish()) + bn_drop_lin(512,...
StarcoderdataPython
3296233
# ----------------------------------------------------- # Copyright (c) Shanghai Jiao Tong University. All rights reserved. # Written by <NAME> (<EMAIL>) # ----------------------------------------------------- """Custum training dataset.""" import copy import os import cv2 import pickle as pk from abc import abstractm...
StarcoderdataPython
3317595
import bs4 as bs import os import os.path import requests import base64 import json from datetime import datetime, timezone from requests.packages import urllib3 # rrdtool dump test.rrd > test.xml cfg_name = 'config.json' db_path = '/home/lcladmin/cmstats/data/' web_path = '/var/www/html/cmstats/' def main(): wi...
StarcoderdataPython
1757195
# -*- coding: utf-8 -*- from django import forms from .models import File class FileForm(forms.ModelForm): class Meta: model = File fields = '__all__' widgets = { 'link_type': forms.RadioSelect(attrs={'class': 'inline-block'}), }
StarcoderdataPython
1710314
from flask import render_template,request,Blueprint from flask_fp.models import Post main = Blueprint('main', __name__) @main.route("/") @main.route("/home") def home(): page = request.args.get('page', 1, type = int) posts = Post.query.order_by(Post.date_posted.desc()).paginate(page = page, per_page=5)...
StarcoderdataPython
4801970
import smartpy as sp class FA12(sp.Contract): def __init__(self, admin): self.init(paused = False, balances = sp.big_map(tvalue = sp.TRecord(approvals = sp.TMap(sp.TAddress, sp.TNat), balance = sp.TNat)), administrator = admin, totalSupply = 0) @sp.entry_point def transfer(self, params): ...
StarcoderdataPython
1616243
import os import sys import datetime import torch sys.path.append('../') from models.model import * from core.tune_labels import tune_labels from utils.utils import get_data_loader, get_data_loader_weight, init_model, init_random_seed, get_dataset_root, get_model_root, get_data from torch.utils.tensorboard import Summ...
StarcoderdataPython
1633404
# # Copyright 2016 Quantopian, 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 required by applicable law or agreed to in wr...
StarcoderdataPython
1601114
# coding=utf8 # # (C) 2015-2016, MIT License ''' Container for tests. '''
StarcoderdataPython
177212
<filename>python/day25.py import io EXAMPLE = """v...>>.vv> .vv>>.vv.. >>.>v>...v >>v>>.>.v. v>v.vv.v.. >.>>..v... .vv..>.>v. v.v..>>v.v ....v..v.>""" def step(map: list[list[str]]) -> bool: m = len(map) n = len(map[0]) move_east = set() for i in range(m): for j in range(n): if ma...
StarcoderdataPython
3252512
import io import re from setuptools import setup from collections import OrderedDict with io.open('README.md', 'rt', encoding='utf8') as f: readme = f.read() with io.open('TimePoints/__init__.py', 'rt', encoding='utf8') as f: version = re.search(r'__version__ = \'(.*?)\'', f.read()).group(1) setup( name...
StarcoderdataPython
3342389
<filename>cql_builder/assignment.py from cql_builder.base import Assignment, ValidationError # {key=value, key=value, ...} class Set(Assignment): def __init__(self, **kwargs): self.kwargs = kwargs @property def cql(self): return ', '.join('{}=%s'.format(k) for k in self.kwargs.keys()) @property def values(...
StarcoderdataPython
1783211
from urls import app
StarcoderdataPython
3352639
<filename>pacote-download/ex112/utilidadescev/teste.py from ex112.utilidadescev import dado from ex112.utilidadescev import moeda p = dado.leiaDinheiro('Digite o preco: R$') moeda.resumo(p,35,22)
StarcoderdataPython
136279
#!/usr/bin/env python ''' This script prints Hello World! ''' print('Hello, World!')
StarcoderdataPython
3251663
from fvh import MyTurtle import math def one(starth=270, startpos=(0,0), lm=None, cube=[60,60]): if not lm: lm=MyTurtle() lm.tracer(False) lm.pu() lm.goto(startpos) lm.seth(starth) lm.pd() lm.ht() lm.fd(5) lm.right(90) lm.fd(10) lm.left(90) lm.fd(40) lm.left(...
StarcoderdataPython
168494
<gh_stars>0 import networkx as nx from networkx.readwrite import json_graph import pickle from random import choice,uniform,randint import http_server import json import math from itertools import combinations class Optimize: G=None F=None def prune(self,G): tbd=[] for n in Optimize.G.nodes(): if sum(G.no...
StarcoderdataPython
1701172
''' author: <NAME> || @slothfulwave612 Python module for i/o operations on the dataset. ''' ## import necessary packages/modules import os import numpy as np import pandas as pd from pandas.io.json import json_normalize import json import math import multiprocessing from tqdm.auto import tqdm, trange import statsmode...
StarcoderdataPython
1797555
import ckit from ckit.ckit_const import * ## @addtogroup widget ## @{ #-------------------------------------------------------------------- ## タブバーウィジェット # class TabBarWidget(ckit.Widget): MAX_ITEM_WIDTH = 30 def __init__( self, window, x, y, width, height, selchange_handler ): ...
StarcoderdataPython
3278757
from os import environ import boto3 import configparser config = configparser.ConfigParser() config.read('config.ini') def get_new_boto3_session(): return boto3.session.Session( # Credentials have to be set in environment variables region_name = environ.get('AWS_REGION') or config['aws']['region_nam...
StarcoderdataPython
3298546
# Generated by Django 3.1.13 on 2021-10-07 15:28 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [("workstation_configs", "0009_auto_20211005_1329")] operations = [ migrations.AddField( model_name="workstationconfig", name="show...
StarcoderdataPython
4835307
from django.contrib import admin # RegisterView your models here. from openbook_auth.models import User, UserProfile class UserProfileInline(admin.TabularInline): model = UserProfile def has_delete_permission(self, request, obj=None): return False class UserAdmin(admin.ModelAdmin): inlines = [...
StarcoderdataPython
123464
<filename>examples/tables.py<gh_stars>0 import django_tables2 as tables from .models import equipment class equipmentTable(tables.Table): T_read =('<button type=\"button\" class=\"read-book btn btn-sm btn-primary\" data-id="{% url \'read_book\' record.pk %}\"><span class=\"fa fa-eye\"></span> </button>') rea...
StarcoderdataPython
179852
<gh_stars>10-100 import sys def hello(who): print('hello {}'.format(who)) hello(sys.argv[1])
StarcoderdataPython
135120
<filename>reconcile/test/test_quay_repos.py from unittest.mock import patch from reconcile.quay_repos import RepoInfo, act from reconcile.quay_base import OrgKey from .fixtures import Fixtures fxt = Fixtures("quay_repos") def build_state(fixture_state): return [ RepoInfo( org_key=OrgKey("i...
StarcoderdataPython
3298308
from app import app from flask import render_template, jsonify, request from loguru import logger @app.route("/") @app.route("/index") def index(): return render_template("index.html") @app.route("/dummy", methods=['POST']) def dummy(): string = request.form.get('string') return jsonify({"dummy":string})
StarcoderdataPython
44072
<filename>tests/aliyun_iot_test.py<gh_stars>1-10 # -*- coding: utf-8-*- import unittest import os os.sys.path.append(os.path.join(os.path.dirname(__file__), '../')) from app.components import logger from app.components.aliyun_iot import IotServer class TestComponentsAliyunIOT(unittest.TestCase): """ 表格计算 ...
StarcoderdataPython
1658957
# coding=utf-8 import datetime import StringIO import glob import os import traceback import urlparse from zipfile import ZipFile, ZIP_DEFLATED from subzero.language import Language from subzero.lib.io import FileIO from subzero.constants import PREFIX, PLUGIN_IDENTIFIER from menu_helpers import SubFolderObjectConta...
StarcoderdataPython
187277
#!/usr/bin/env python3 # coding:utf-8 import this s = "va gur snpr bs jung?" print('=' * 50) print(''.join([this.d.get(c, c) for c in s]))
StarcoderdataPython
3327253
from datetime import timedelta from dateutil.relativedelta import relativedelta class RatingDatesMixin: def get_date(self, rating_date): # two years ago return rating_date - timedelta(days=365 * 2) def tournament_age(self, end_date, rating_date): """ Check about page for deta...
StarcoderdataPython
1785906
# as defined in PyTorch, custom extension import pathlib from typing import BinaryIO, List, Optional, Text, Tuple, Union import torch from PIL import Image, ImageDraw, ImageFont from torchvision.utils import make_grid def save_image( tensor: Union[torch.Tensor, List[torch.Tensor]], fp: Union[Text, pathlib.Pa...
StarcoderdataPython
3253784
<reponame>Ashwin-op/Advent_of_Code<filename>2020/Day 13 - Shuttle Search/1.py with open("input.txt") as fp: startTime = int(fp.readline().strip()) busTimes = [int(i) for i in fp.readline().split(',') if i != 'x'] def closestMultiple(n, x): if x > n: return x z = int(x / 2) n = n + z n ...
StarcoderdataPython
1787092
<filename>inbm/dispatcher-agent/dispatcher/device_manager/constants.py<gh_stars>1-10 """ Constants for DeviceManager classes Copyright (C) 2017-2022 Intel Corporation SPDX-License-Identifier: Apache-2.0 """ # Linux specific constants LINUX_POWER = "/sbin/shutdown " LINUX_RESTART = "-r" LINUX_SHUTDOWN = "-...
StarcoderdataPython
3241481
<filename>gameinterface/minecraftinterface.py<gh_stars>0 import win32gui import keyboard import time import pyautogui import d3dshot from PIL import Image target_size = (640, 480) target_location = (0, 0) screen_grab_location_offset = (9, 34) screen_grab_size_offset = (-9, -7) default_region = (9, 34, 631, 473) def ...
StarcoderdataPython
168080
<reponame>notabela-org/project-1-photoshare-GarlandQ<gh_stars>1-10 # Generated by Django 3.1.6 on 2021-03-07 07:46 from django.conf import settings from django.db import migrations class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ...
StarcoderdataPython
1678174
<filename>tests/relay_integration/tests.py from __future__ import absolute_import, print_function import os from sentry import eventstore from django.core.urlresolvers import reverse from exam import fixture from sentry.testutils import TransactionTestCase, RelayStoreHelper from sentry.testutils.helpers.datetime imp...
StarcoderdataPython
69911
<filename>bridge/users/api.py # # Copyright (c) 2019 ISP RAS (http://www.ispras.ru) # Ivannikov Institute for System Programming of the Russian Academy of Sciences # # 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 co...
StarcoderdataPython
1613383
<reponame>terryyylim/feast<gh_stars>0 import os import random import string import tempfile from datetime import datetime, timedelta import click import pyarrow as pa from tqdm import tqdm from feast.data_source import FileSource from feast.entity import Entity from feast.feature import Feature from feast.feature_sto...
StarcoderdataPython