id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
1624141 | # static box
import engine
WIDTH = 640
HEIGHT = 480
class Box(engine.GameObject):
def __init__(self):
super().__init__(0, 0, +1, 0, 'square', 'red')
def isstatic(self):
return True
if __name__ == '__main__':
engine.init_screen(WIDTH, HEIGHT)
engine.init_engine()
box = Box()
engine.add_obj(box)
engine.eng... | StarcoderdataPython |
168671 | <reponame>szabolcstoth/robotframework-robocop
"""
Spacing checkers
"""
from robot.parsing.model.blocks import TestCase, Keyword
from robot.parsing.model.statements import EmptyLine, Comment
from robocop.checkers import RawFileChecker, VisitorChecker
from robocop.rules import RuleSeverity
class InvalidSpacingChecker(R... | StarcoderdataPython |
4808203 | #!/usr/bin/env python3
"""
Android decompiler
"""
from argparse import ArgumentParser
import logging
from pathlib import Path
import sys
import subprocess
from tempfile import TemporaryDirectory
__author__ = 'Grievejia'
__version__ = '0.1'
def sanity_check(args):
for filepath in args.files:
if not filepath.exists(... | StarcoderdataPython |
1627654 | <filename>src/htsql/ctl/default.py
#
# Copyright (c) 2006-2013, Prometheus Research, LLC
#
"""
:mod:`htsql.ctl.default`
========================
This module implements the default routine.
"""
from .routine import Routine
from .option import HelpOption, VersionOption
from .help import HelpRoutine
from .version imp... | StarcoderdataPython |
3254564 | <filename>students_final_projects/group-f/utilities/basic/coordinate.py
'''
Utility functions for positions and velocities.
@author: <NAME> <<EMAIL>>
'''
# system ----
from __future__ import absolute_import, division, print_function # python 2 compatability
import numpy as np
from scipy import spatial
# local ----
f... | StarcoderdataPython |
1579 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for `ged4py.date` module."""
import unittest
from ged4py.calendar import (
CalendarType, CalendarDate, FrenchDate, GregorianDate, HebrewDate, JulianDate,
CalendarDateVisitor
)
from ged4py.date import (
DateValue, DateValueAbout, DateValueAfter, DateV... | StarcoderdataPython |
1715277 | import argparse
import datetime
import functools
import re
import sys
import traceback
import typing
import holidays
import github
class PennHolidays(holidays.UnitedStates):
def _populate(self, year):
super()._populate(year)
# See https://github.com/greenelab/scrum/issues/114
for day in... | StarcoderdataPython |
42685 | from __future__ import annotations
import json
import os
import shutil
import subprocess
import tempfile
import uuid
from abc import ABC, abstractmethod
from typing import Any, Union
from urllib.error import HTTPError
from urllib.request import urlopen, urlretrieve
import warnings
import meerkat as mk
import pandas a... | StarcoderdataPython |
3261905 | import pytest
import numpy as np
import pandas as pd
from ..linkages import sortLinkages
from ..linkages import calcDeltas
### Create test data set
linkage_ids = ["a", "b", "c"]
linkage_lengths = [4, 5, 6]
linkage_members_ids = []
for i, lid in enumerate(linkage_ids):
linkage_members_ids += [lid for j in range(l... | StarcoderdataPython |
3344599 | import matplotlib.pyplot as plt
import numpy as np
import torch
import torch.backends.cudnn as cudnn
from PIL import Image
from nets.siamese import Siamese as siamese
from utils.utils import letterbox_image, preprocess_input, cvtColor, show_config
#---------------------------------------------------#
# ... | StarcoderdataPython |
1616346 | from django.conf.urls import url
from . import views
app_name = 'website'
urlpatterns = [
url(r'^manual/$',views.manual,name='manual'),
url(r'^reference/$',views.reference,name='reference'),
url(r'^faq/$',views.faq,name='faq'),
url(r'^contact$',views.contact,name='contact'),
url(r'^vios_intro$',v... | StarcoderdataPython |
3380369 | <reponame>boneillhawk/advent2017
import itertools
import copy
import collections
import heapq
import math
import hashlib
def day4a():
f = open('input\\input4.txt', 'r')
lines = [line.strip() for line in f.readlines()]
f.close()
total = 0
for line in lines:
passwords = lin... | StarcoderdataPython |
1795612 | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: sample
Desc :
"""
from collections import Iterable
def flatten(items, ignore_types=(str, bytes)):
for x in items:
if isinstance(x, Iterable) and not isinstance(x, ignore_types):
yield from flatten(x)
else:
yield x
... | StarcoderdataPython |
1644974 | <reponame>IlyaKodua/AutorncoderSignal<filename>Model.py
from torch import nn
import torch.nn.functional as F
import torch
import torchvision
import numpy as np
class DNCNN(nn.Module):
def __init__(self, n_channels, n_filters, kernel_size):
super(DNCNN, self).__init__()
layers = [
nn... | StarcoderdataPython |
1761469 | #
# Copyright (c) 2022 Airbyte, Inc., all rights reserved.
#
from typing import Iterable, Mapping
import requests
from .base import DateSlicesMixin, IncrementalMixpanelStream
class Revenue(DateSlicesMixin, IncrementalMixpanelStream):
"""Get data Revenue.
API Docs: no docs! build based on singer source
... | StarcoderdataPython |
3306855 | """
Copyright (c) 2021 <NAME>
This code is licensed under MIT license (see LICENSE.MD for details)
@author: cheapBuy
"""
import sys
from bs4 import BeautifulSoup
from selenium import webdriver
from source.utils.url_shortener import shorten_url
from webdriver_manager.chrome import ChromeDriverManager
# Set working di... | StarcoderdataPython |
3291227 | from pathlib import Path
from tqdm import tqdm
if __name__ == '__main__':
images_dir = 'images'
query_list_name = 'queries/{}_queries_with_intrinsics.txt'
intrinsics_name = 'intrinsics/{}_intrinsics.txt'
sequence = 'night-rain'
h, w = 1024, 1024
intrinsics = {}
for side in ['left', 'right... | StarcoderdataPython |
3267742 | <filename>dualnback/models.py
class Model:
def load(self):
raise NotImplementedError
def store(self):
raise NotImplementedError
class User(Model):
pass
class Game(Model):
pass
| StarcoderdataPython |
3333280 | "`gen_doc.nbdoc` generates notebook documentation from module functions and links to correct places"
import inspect,importlib,enum,os,re
from IPython.core.display import display, Markdown, HTML
from typing import Dict, Any, AnyStr, List, Sequence, TypeVar, Tuple, Optional, Union
from .docstrings import *
from .core im... | StarcoderdataPython |
30247 | # 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 |
41970 | '''
Created on May 4, 2013
@author: Administrator
'''
import json
import sys
def parseTweets(tweet_file='tweets.txt'):
parsed_tweets = []
with open(tweet_file, 'r') as fin:
for line in fin:
tweet = json.loads(line)
if 'text' in tweet:
parsed_tweets.append(tweet)... | StarcoderdataPython |
1775250 | # Copyright © 2020 Arm Ltd and Contributors. All rights reserved.
# SPDX-License-Identifier: MIT
import tflite_runtime.interpreter as tflite
import numpy as np
import os
def run_mock_model(delegate, test_data_folder):
model_path = os.path.join(test_data_folder, 'mock_model.tflite')
interpreter = tflite.Inter... | StarcoderdataPython |
1652621 | import numpy as np
import seaborn as sns
import matplotlib.pylab as plt
batchSize = 1
semi = False
points = False
if semi:
diag_path = ['results/diag_batch_random_bazinTD_batch' + str(batchSize) + '_vanilla.csv',
'results/diag_batch_random_bazinTD_batch' + str(batchSize) + '.csv',
... | StarcoderdataPython |
40427 | <filename>taggable/__init__.py
from .taggable_sequence import TaggableSequence
from .taggable_sequence import TaggedSegment | StarcoderdataPython |
170274 | """Implementation of Optimal F1 score based on TorchMetrics."""
import torch
from torchmetrics import Metric, PrecisionRecallCurve
class OptimalF1(Metric):
"""Optimal F1 Metric.
Compute the optimal F1 score at the adaptive threshold, based on the F1 metric of the true labels and the
predicted anomaly sco... | StarcoderdataPython |
1668815 | <gh_stars>1-10
class HTTPError(Exception):
def __init__(self, status, json=None):
self.status = status
self.json = json
@staticmethod
def for_status(status, json=None):
if status in range(400, 499):
return ClientError.for_status(status, json)
elif status in range... | StarcoderdataPython |
1790808 | from .FiberPI import * | StarcoderdataPython |
16837 | from __future__ import annotations
from typing import Any, Dict, Optional
from boa3.model.method import Method
from boa3.model.property import Property
from boa3.model.type.classes.classarraytype import ClassArrayType
from boa3.model.variable import Variable
class OracleType(ClassArrayType):
"""
A class use... | StarcoderdataPython |
185389 | <filename>radicalsdk/beamformers.py
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/06_beamformers.ipynb (unless otherwise specified).
__all__ = ['cov_matrix', 'forward_backward_avg', 'aoa_capon']
# Cell
import tensorflow as tf
import tensorflow.linalg as linalg
# Cell
def cov_matrix(x):
"""Computes the covarian... | StarcoderdataPython |
16274 | <reponame>marcoshsq/python_practical_exercises
import math
# Exercise 017: Right Triangle
"""Write a program that reads the length of the opposite side and the adjacent side of a right triangle.
Calculate and display the length of the hypotenuse."""
# To do this we will use the Pythagorean theorem: a^2 = b^2 + c^2
#... | StarcoderdataPython |
1651547 | # coding: utf-8
import glob
import os
import collections
def get_doc_list(base_path):
"""
guide 목록 수집
"""
doc_info = collections.OrderedDict()
doc_path = []
doc_path += glob.glob(os.path.join(base_path, '*', '*'))
# doc_path += glob.glob(os.path.join(base_path, '*', '*_guide'))
# doc_p... | StarcoderdataPython |
56981 | import logging
from django.contrib import auth
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
from django.shortcuts import render
from zapi.forms import LoginForm
logger = logging.getLogger(__name__)
def index(request):
return render(request, "index.html"... | StarcoderdataPython |
143119 | __author__ = 'dave'
from django.shortcuts import render
def ajax(request, ajax_code):
return render(request=request, template_name="hes/ajax/%s.html" % ajax_code, context={})
def coming_soon(request):
return render(request=request, template_name="hes/coming-soon.html", context={})
| StarcoderdataPython |
55833 | import asyncio
import asyncssh
import sys
import os
import crypt
from importlib.util import find_spec
class MySSHServerSession(asyncssh.SSHServerSession):
def __init__(self):
self._input = ''
self._data = None
self.devtype = 'iosxr'
self.run_as_shell = False
self.prompt = '... | StarcoderdataPython |
3253117 | def fbx_objects_elements(root, scene_data):
"""
Data (objects, geometry, material, textures, armatures, etc.).
"""
perfmon = PerfMon()
perfmon.level_up()
objects = elem_empty(root, b"Objects")
perfmon.step("FBX export fetch empties (%d)..." % len(scene_data.data_empties))
for empty in ... | StarcoderdataPython |
3213089 | <reponame>marcusvaltonen/python-homlib
import unittest
from approvaltests import verify
from tests.helpers import verify_numpy_array
import numpy as np
import homlib
class FitzgibbonCVPR2001TestCase(unittest.TestCase):
def setUp(self):
self.p1 = np.array([
[-0.291910956401174, 0.99818110344... | StarcoderdataPython |
3256107 | <reponame>k-donn/ec-apportionment
"""
Show an animation of the Huntington–Hill apportionment method.
usage: python3.8 run.py [-h] -f FILE [-d]
optional arguments:
-h, --help show this help message and exit
-f FILE, --file FILE Path to CSV state population data
-d, --debug Show the plot ins... | StarcoderdataPython |
78404 | <reponame>shovradas/proxy-fellow
import datetime
import time
from flask import url_for
from flask_restful import Resource, abort
from webargs.flaskparser import use_args
from bson.objectid import ObjectId
from core.proxy_checker import HttpProxyChecker
from webapi import api, mongo
from webapi.common import util
from ... | StarcoderdataPython |
171541 | """Download the data from dropbox links.
Example:
Import statement::
from src.data_loading import get_data
"""
import os
import shutil
import requests
import zipfile
from tqdm import tqdm
from src.utils import timeit
from src.constants import (
OCEAN_PATH,
ATMOS_PATH,
DATA_PATH,
FIGURE_DA... | StarcoderdataPython |
143209 | from framework.core.myexception import FuzzException
from threading import Thread
from framework.fuzzer.fuzzobjects import FuzzResult
from framework.utils.myqueue import FuzzQueue
PYPARSING = True
try:
from pyparsing import Word, Group, oneOf, Optional, Suppress, ZeroOrMore, Literal
from pyparsing import Pa... | StarcoderdataPython |
3354657 | import json
import plotly,re
import pandas as pd
import nltk
from nltk.stem import WordNetLemmatizer
from nltk.tokenize import word_tokenize
#nltk.download(['punkt', 'wordnet','stopwords'])
from nltk.corpus import stopwords
from collections import Counter
from flask import Flask
from flask import render_template, req... | StarcoderdataPython |
1785273 | #Written by <NAME> using Python 3.6.4
#Converter is a handy tool to, eh, convert between commonly encountered formats when working with data and files. It can convert from hex to binary, hex to ascii, ascii to hex, as well as perform both Base64 and URL encoding/decoding. Input can be taken from stdin or from a file. ... | StarcoderdataPython |
3378856 | <filename>rss/utilities.py<gh_stars>10-100
import glob
import os
import pika
import redis
from ConfigParser import ConfigParser
def make_redis(host='localhost'):
r = redis.StrictRedis(host=host, port=6379, db=0)
return r
def make_queue(host='localhost'):
connection = pika.BlockingConnection(pika.Connec... | StarcoderdataPython |
183533 | # https://leetcode.com/problems/arithmetic-slices/
class Solution:
def numberOfArithmeticSlices(self, nums: list[int]) -> int:
arithmetic_slices = 0
if len(nums) <= 2:
return arithmetic_slices
last_diff = nums[1] - nums[0]
last_increment = 0
for idx in range(2, l... | StarcoderdataPython |
3256468 | <filename>NewWebsite/learn_flask/10/main.py
from flask import Flask, render_template
from second import second
app = Flask(__name__)
app.register_blueprint(second, url_prefix="")
@app.route("/")
def test():
return "<h1>Test</h1>"
if __name__ == "__main__":
app.run(debug=True) | StarcoderdataPython |
3364316 | <filename>poweroff.py
#!/bin/python
import os
welcomemsg = "\nSpecify the desired action:\n\n"
shoutdown = "s - shoutdown\n"
reboot = "r - reboot\n"
logout = "e - end user session\n"
lock = "l - lock the screen\n"
quit = "q - quit\n"
yourinp = "\nYour input: "
msg = welcomemsg + shoutdown + reboot + logout + lock + q... | StarcoderdataPython |
1771270 | # It's pretty straightforward. Your goal is to create a function that removes the first and last characters of a string.
# You're given one parameter, the original string. You don't have to worry with strings with less than two characters.
def remove_char(s):
return s[1:-1]
assert (remove_char("eloquent")) == "l... | StarcoderdataPython |
3325176 | # -*- coding: utf-8 -*-
# License: See LICENSE file.
class Query(object):
"""Represents query."""
def __init__(self, run, query):
self.run = run
self.query = query
def run(self, world, *args, **kwargs):
""" Reinitializes the object.
Overridden in the constructor."""
... | StarcoderdataPython |
36639 | #!/usr/bin/evn python3
# coding=utf-8
import logging
import redis
from typing import Any
from conf import dev_conf as conf
from util import singleton
@singleton
class Config:
"""
根据指定的配置文件,把conf文件转换成字典
默认情况下使用 conf 中的配置
"""
def __init__(self):
self.config = conf
self.redis_db = N... | StarcoderdataPython |
1603910 | rock = '''
_______
---' ____)
(_____)
(_____)
(____)
---.__(___)
'''
paper = '''
_______
---' ____)____
______)
_______)
_______)
---.__________)
'''
scissors = '''
_______
---' ____)____
______)
__________)
(____)
---.__(___)
'''... | StarcoderdataPython |
163814 | import html
from pyrogram import Client, filters
from pyrogram.errors.exceptions.bad_request_400 import MessageNotModified
from .. import config, help_dict, get_entity, log_errors, public_log_errors
ZWS = '\u200B'
def _generate_sexy(entity, ping):
text = getattr(entity, 'title', None)
if not text:
text... | StarcoderdataPython |
1769112 | <reponame>aragubas/fogoso
#!/usr/bin/python3.7
# Copyright 2020 Aragubas
#
# 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
#
# Unl... | StarcoderdataPython |
3276795 | import numpy as np
import numpy.ma as ma
import matplotlib.pyplot as plt
data = np.loadtxt('faulty_data.dat')
plt.plot(data[:,0], data[:,1], 'o')
x = data[:,0]
y = data[:,1]
mask = y > 35
y_m = ma.masked_array(y, mask)
x_m = ma.masked_array(x, mask)
fit_orig = np.polyfit(x, y, 2)
fit_masked = ma.polyfit(x_m, y_m, 2)... | StarcoderdataPython |
69051 | import sys
import nltk
import re
from nltk.stem import WordNetLemmatizer
from nltk.tokenize import RegexpTokenizer
from nltk.corpus import stopwords
from nltk.corpus import brown
from autocorrect import Speller
sys.path.append("./../")
from services.database_service import (data_basis_query, get_number_of_links_to_be... | StarcoderdataPython |
71664 | <reponame>ooici/coi-services
"""
@author <NAME>
@author <NAME>
@brief Test cases for the tableloader,
table loader is a service to load data products in to postgres and geoserver from the resource registry
"""
from gevent import server
from gevent.baseserver import _tcp_listener
from gevent import pywsgi
from gevent.... | StarcoderdataPython |
1795684 | <filename>examples/args/args.py<gh_stars>10-100
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Project : tql-Python.
# @File : args
# @Time : 2019-11-01 14:46
# @Author : yuanjie
# @Email : <EMAIL>
# @Software : PyCharm
# @Description :
# name or flags - 选项字符串的名字或者列表,例如foo 或者-f... | StarcoderdataPython |
1747471 | <gh_stars>1-10
# Event: LCCS Python Fundamental Skills Workshop
# Date: May 2018
# Author: <NAME>, PDST
# eMail: <EMAIL>
# Purpose: A program to demonstrate the use of variables with turtle graphics
from turtle import *
hideturtle() # hide the turtle
color("red") # set the pen colour to red
lineLength = 5... | StarcoderdataPython |
29296 | <gh_stars>1-10
from django.conf import settings
from django import template
from spreedly.functions import subscription_url
register = template.Library()
@register.simple_tag
def existing_plan_url(user):
return 'https://spreedly.com/%(site_name)s/subscriber_accounts/%(user_token)s' % {
'site_name': setti... | StarcoderdataPython |
69996 | <gh_stars>0
import os
from contextlib import contextmanager
import virtualenvrunner.runner
from crl.devutils.utils import get_randomstring
from crl.devutils.doccreator import DocCreator
from crl.devutils.devpiindex import DevpiIndex
__copyright__ = 'Copyright (C) 2019, Nokia'
class _TmpIndex(DevpiIndex):
def _... | StarcoderdataPython |
3231824 | <gh_stars>0
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
_l3 = Li... | StarcoderdataPython |
3337403 | <filename>distla/tp/tp/tp_lib.py
# Copyright 2021 The Distla Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#... | StarcoderdataPython |
1604525 | <reponame>callat-qcd/project_fkfpi
#!/usr/bin/env python3
# python libraries
import os, sys, shutil, copy
import matplotlib.pyplot as plt
import numpy as np
# Peter Lepage's libraries
import gvar as gv
import lsqfit
# FK / Fpi libraries
sys.path.append('utils')
import io_utils
import chipt
import analysis
import plott... | StarcoderdataPython |
3222537 | <gh_stars>1-10
import logging
from datetime import datetime
import collections, queue, os, os.path
import numpy as np
import pyaudio
import wave
import webrtcvad
from halo import Halo
from scipy import signal
import tkinter as tk
from tkinter.constants import CENTER
import glob
import vibes
import os, os.p... | StarcoderdataPython |
4837215 | import os
os.environ['CUDA_VISIBLE_DEVICES'] = '5'
import cv2
import numpy as np
from maskrcnn_benchmark.config import cfg
from demo.predictor import ICDARDemo, RRPNDemo
from maskrcnn_benchmark.utils.visualize import vis_image, write_result_ICDAR_RRPN2polys, zip_dir
from PIL import Image
import time
config... | StarcoderdataPython |
70008 | #
# PySNMP MIB module ADTRAN-AOS (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ADTRAN-AOS
# Produced by pysmi-0.3.4 at Mon Apr 29 16:58:35 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:... | StarcoderdataPython |
3208500 | from datetime import timedelta
def add_gigasecond(birth_date):
return birth_date + timedelta(seconds=1e9)
| StarcoderdataPython |
1722808 | <gh_stars>0
"""
UI related events.
"""
class DiagramShow:
def __init__(self, diagram):
self.diagram = diagram
class DiagramPageChange:
def __init__(self, item):
self.item = item
self.diagram_page = item.diagram_page
class DiagramSelectionChange:
def __init__(self, diagram_view,... | StarcoderdataPython |
3288918 | #!/usr/bin/env python
# vim: ts=4 sw=4 et
# https://github.com/ilyash/show-struct.git
from __future__ import unicode_literals
import argparse
import collections
import json
import sys
class Outliner(object):
def __init__(self):
self.paths = {}
self.values_for_path = collections.defaultdict(dict)... | StarcoderdataPython |
1609382 | <gh_stars>0
# -*- coding: utf-8 -*- #
# Copyright 2019 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# U... | StarcoderdataPython |
1737884 | <filename>sources/background.py<gh_stars>0
import os
import common_pygame
import random
pygame = common_pygame.pygame
screen= common_pygame.screen
class BackGen():
def __init__(self, single_sprites):
self.single_sprites=single_sprites
self.compteur=0
self.asteroidList=list()
self.ast = self.single_sprites... | StarcoderdataPython |
1786378 | <filename>db/tortoise_config.py
import logging
import os
from tortoise import Tortoise
class DBConfig(object):
def __init__(self):
self.logger = logging.getLogger()
self.modules = {'db': ['db.models.user', 'db.models.account', 'db.models.stats', 'db.models.transaction', 'db.models.muted', 'db.model... | StarcoderdataPython |
1665131 | from pathlib import Path
root_path = Path(__file__).parent.parent
# define the model
import torch
from torch import nn
from torch.nn import functional as F
class TorchModel(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(1, 6, 5, 1)
self.conv2 = nn.Conv2d(6, 16, ... | StarcoderdataPython |
1748259 | """Unit test helper: Offer images with different image modes."""
import numpy as np
import os
import random
import scipy.misc
import string
import tempfile
from PIL import Image
class TempFile:
def __init__(self, img=None):
self.path = self.create_unique_name('.png')
if isinstance(img, Image.Imag... | StarcoderdataPython |
42853 |
import math
import vmath
from vmathlib import vcolor, vutil
import vmathlib
import toy
import keycodes
import drawutil
from unit_manager import Unit
import mathutil
class Shadowman(Unit):
def __init__(self, world, unit_id, param):
super().__init__(world, unit_id, param)
self.camera_transform... | StarcoderdataPython |
3333834 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import datetime
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
m... | StarcoderdataPython |
4830116 | # 角色简体中文名字典(Dictionary)
characterSChineseDic = {
'Reimu_Hakurei': '博丽灵梦',
'Marisa_Kirisame': '雾雨魔理沙',
# 'SinGyoku': '神玉',
'Mima': '魅魔',
# 'Kikuri': '菊理',
'Konngara': '矜羯罗',
# 'YuugenMagan': '幽幻魔眼',
# 'Elis': '依莉斯',
# 'Sariel': '萨丽爱尔',
# 'Onmyou_gyoku': '阴阳玉',
# 'Yamaaruki': '... | StarcoderdataPython |
3265276 | from suls.rersconnectorv4 import RERSConnectorV4
problem = "Problem12"
rers = RERSConnectorV4(f'../rers/TrainingSeqReachRers2019/{problem}/{problem}')
seen_outputs = set()
for i in range(10000):
output = rers.process_input(['7'] * i)
if output not in seen_outputs:
print(output)
seen_outputs.a... | StarcoderdataPython |
61740 |
# This is an auto-generated Django model module.
# You'll have to do the following manually to clean this up:
# * Rearrange models' order
# * Make sure each model has one field with primary_key=True
# * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table
# Feel free... | StarcoderdataPython |
1606383 | <gh_stars>1-10
import string
import operator
import itertools
import collections
import scipy.special
from utils import info, success, warning, error, alphabet
def validate_charset(cs, verbose):
# Try to match the character set with something known
sets = [(string.printable, None),
(string.letters + s... | StarcoderdataPython |
1704800 | <filename>server/processes/serializers/unknown_execution_method_serializer.py
from typing import Any
from ..execution_methods import UnknownExecutionMethod
from .base_execution_method_serializer import (
BaseExecutionMethodSerializer
)
class UnknownExecutionMethodSerializer(BaseExecutionMethodSerializer)... | StarcoderdataPython |
1783578 | <gh_stars>1-10
import os.path as op
from winterops.rhino import Rhino
from winterops.tests import USER_DESKTOP
def run():
f = Rhino.FileIO.File3dm()
p1 = Rhino.Geometry.Point3d(0, 0, 0)
for x in range(10):
for y in range(10):
for z in range(10):
p2 = Rhino.Geometry.Poi... | StarcoderdataPython |
3283325 | <filename>config/settings/__init__.py<gh_stars>0
from .django import *
from .third_party import *
| StarcoderdataPython |
1937 | <filename>tests/python/correctness/simple_test_aux_index.py
#! /usr/bin/env python
#
# ===============================================================
# Description: Sanity check for fresh install.
#
# Created: 2014-08-12 16:42:52
#
# Author: <NAME>, <EMAIL>
#
# Copyright (C) 2013, Cornell Uni... | StarcoderdataPython |
3276211 | # -*- coding: utf-8 -*-
from django.core.urlresolvers import reverse
from django.core import mail
from django.test import TestCase
from django.utils.translation import ugettext as _
from django_selenium.livetestcases import SeleniumLiveTestCase
from users.models import Profile
class RegistrationTest(TestCase):
... | StarcoderdataPython |
3333362 | <gh_stars>0
from django.db import models
from django.conf import settings
from django.shortcuts import reverse
from django.utils import timezone
from django.contrib.auth.models import User
class Item(models.Model):
LABELS = (
("BestSeller", "BestSeller"),
("New", "New"),
("Spicy🔥", "Spicy... | StarcoderdataPython |
12001 | <reponame>amaas-fintech/amaas-core-sdk-python<filename>amaascore/tools/generate_party.py
from __future__ import absolute_import, division, print_function, unicode_literals
from amaasutils.random_utils import random_string, random_decimal
import random
from amaascore.core.reference import Reference
from amaascore.part... | StarcoderdataPython |
3309493 | <reponame>sunjerry019/adventOfCode18
#!/usr/bin/env python3
import numpy as np
import sys
sys.setrecursionlimit(5000)
class Problem():
def __init__(self):
self.input = open("17.example.in","r")
self.inputContents = self.input.readlines()
self.blocks = {} # includes clay and settle... | StarcoderdataPython |
187443 | <filename>qbot/plugins/img.py
import asyncio
import logging
from typing import List, Optional
from urllib.parse import urlparse
import validators
from qbot.command import add_command
from qbot.core import registry
from qbot.image import upload_image
from qbot.message import (
IncomingMessage,
OutgoingMessage,... | StarcoderdataPython |
3310533 | <reponame>rodbv/kamu
from django.db import models, IntegrityError
from books.models import Library, Book, BookCopy
from django.conf import settings
from django.utils import timezone
from waitlist.tasks import send_new_user_on_waitlist_notification
NO_WAITLIST_STATUS = 'NO_WAITLIST'
FIRST_ON_WAITLIST_STATUS = 'FIRST_O... | StarcoderdataPython |
3298976 | <gh_stars>10-100
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys, os
import importlib
import tkinter as tk
from tkinter import ttk
import cv2, time
import Settings
from Keyboard import SwitchKeyboardController
from Camera import Camera
from GuiAssets import MyScrolledText, CaptureArea, ControllerG... | StarcoderdataPython |
1781040 | <reponame>alexeyev/pytrovich
# -*- coding: utf-8 -*-
# well I've tried to use jsonpickle or something of the like but without much luck
class Rule(object):
"""
Exceptions/suffices as lists of strings for checking matches against ones
"""
def __init__(self, male: list = None, female: list = None, ... | StarcoderdataPython |
3331846 | <gh_stars>0
# -*- coding: utf-8 -*-
#
# CookieRevocation - a short Trac plugin to enable the revocation
# of a user's trac_auth cookie.
from pkg_resources import resource_filename
from trac.core import *
from trac.admin import IAdminPanelProvider
from trac.web.chrome import ITemplateProvider, add_notice,... | StarcoderdataPython |
114471 | import proto_example
from proto_example.generated.function_a.v1.function_pb2 import Request
def main():
req = Request()
req.descriptions = "hello from python"
res = proto_example.function_a(req)
print("rust response:", res)
if __name__ == '__main__':
main() | StarcoderdataPython |
3201867 | <gh_stars>10-100
# -*- coding: utf-8 -*-
import numpy
import tempfile
import os
_show_plots_ = False
print("""
***********************************************************
*
*
* Evolution superoperator demo
*
*
***********************************************************
""")
import quantarhei as qr
q... | StarcoderdataPython |
4802945 | <filename>scripts/sources/s_pca_empirical.py<gh_stars>1-10
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.4'
# jupytext_version: 1.2.1
# kernelspec:
# display_name: Python 3... | StarcoderdataPython |
162248 | __author__ = 'kenjif'
| StarcoderdataPython |
162580 | # ======================================================================================================================
# File: Model/MeasureableUnits/DiastaticPowerType.py
# Project: AlphaBrew
# Description: Provides a base class for working with time types in recipes which can have differing units.
... | StarcoderdataPython |
3375679 | <reponame>encukou/naucse<filename>test_naucse/test_schema.py
import pytest
from naucse import models
from test_naucse.conftest import assert_yaml_dump, API_VERSIONS
@pytest.mark.parametrize('version', API_VERSIONS)
@pytest.mark.parametrize('mode', ('in', 'out'))
@pytest.mark.parametrize(
'cls', (models.Root, mo... | StarcoderdataPython |
3207737 | <reponame>mom1/project-semantic-release<filename>tests/parsers/test_scipy.py
from semantic_release.history import scipy_parser
def test_valid_scipy_commit(valid_scipy_commit, expected_response_scipy):
(commit_tag, subject, _, body_parts) = expected_response_scipy
result = scipy_parser(valid_scipy_commit)
... | StarcoderdataPython |
16877 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import logging
import os
import sys
from . import entries, meta
logger = logging.getLogger(__name__)
def build_parser():
prog = os.path.basename(sys.argv[0])
if prog not in ("pyclean", "pyclean.py"):
prog = "pyclean"
parser = argpar... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.