id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
4828846 | <filename>tests/functional/test_import/test_import.py<gh_stars>100-1000
from __future__ import unicode_literals
import pytest
import os
from textx import metamodel_from_file, metamodel_from_str
from textx.export import metamodel_export, model_export
def test_import():
"""
Test grammar import.
"""
cu... | StarcoderdataPython |
11286873 | <reponame>azyobuzin/twikoto3
# -*- coding: utf-8 -*-
"""
twikoto3 - Twitter Client
Copyright (C) 2012 azyobuzin
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 3 o... | StarcoderdataPython |
9680720 | <gh_stars>0
from django.db.models.base import ModelState, ModelStateFieldsCacheDescriptor
from django.test import SimpleTestCase
class ModelStateTests(SimpleTestCase):
def test_fields_cache_descriptor(self):
self.assertIsInstance(ModelState.fields_cache, ModelStateFieldsCacheDescriptor)
| StarcoderdataPython |
3580364 | #!/usr/bin/env python
import mailbox
import email.utils
from datetime import datetime
from dateutil.parser import parse
mbox = mailbox.mbox('/home/ibanez/data/ITK/Community/MailingList/python/ITKUsers.txt')
people = {}
messages = {}
threads = {}
def regularizeEmail( inputemail ):
simplifiedemail = message_from.s... | StarcoderdataPython |
252056 | <gh_stars>0
"""
Firecracker Microbenchmark
(c) <NAME>, 2020
File: predict_runtimes.py
Predict runtimes for each benchmark workload.
For this, only the baselines are needed, preferably as much as possible
(to even out small variety in machines)
The functions in this script were merged to p... | StarcoderdataPython |
6473232 | <reponame>dracos/datasette-doublemetaphone<gh_stars>1-10
from datasette_doublemetaphone import prepare_connection
import sqlite3
import pytest
@pytest.mark.parametrize(
"sql,expected",
(
('doublemetaphone_main("richard")', 'RXRT'),
('doublemetaphone_alt("richard")', 'RKRT'),
('doubleme... | StarcoderdataPython |
3368110 | # Copyright (c) 2020 <NAME>
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
from typing import Any, Dict
from google.cloud.bigquery.job import WriteDisposition
from google.cloud.bigquery.query import ScalarQueryParameter, UDFResource
from bq_test_kit.bq_dsl import BQQueryTe... | StarcoderdataPython |
4940365 | import Tkinter
import base64
import thread
from Tkconstants import *
from Tkinter import *
from PIL import Image, ImageTk
import capture
import parse_packet
import time
import ips
alpha=10
global mla
flag=0
global ta
global frame
s_no=1
def iptables():
ipt=Tk()
ipt.wm_title("IPTABLES")
#frame = Tkinter.Fr... | StarcoderdataPython |
4963652 | # -*- coding: utf-8 -*-
"""
Created on Thu Oct 15 18:30:50 2020
@author: mathewjowens
A collect of time conversion routes. Mostly ported from Matlab
"""
import numpy as np
import datetime as datetime
import pandas as pd
def date2jd(*args):
"""
date2mjd(year,month,day, *hour, *miunute, *second)
*... | StarcoderdataPython |
3216109 | <filename>src/posts/admin.py<gh_stars>0
from django.contrib import admin
from .models import Post
class PostAdmin(admin.ModelAdmin):
search_fields = ['content']
admin.site.register(Post, PostAdmin) | StarcoderdataPython |
1885209 | <filename>src/globus_sdk/services/auth/response.py
import json
import logging
import time
from typing import TYPE_CHECKING, Any, Dict, Iterator, Optional, Union, cast
import jwt
from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey
from globus_sdk import exc
from globus_sdk.response import GlobusHTTP... | StarcoderdataPython |
11364120 | <filename>RL_lib/Utils/monitor.py
import numpy as np
from time import time
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
import pylab
import matplotlib
class RL_stats(object):
def __init__(self,logger,allow_plotting=True, x_steps=True):
... | StarcoderdataPython |
1641270 | import pandas as pd
import yfinance as yf
class SourceYahoo:
def __init__(self, index, start_date, end_date, interval="1d"):
self.index = index
self.start_date = start_date
self.end_date = end_date
self.interval = interval
def _download(self, start_date, end_date, interval):
... | StarcoderdataPython |
6421347 | <filename>mayday/item_validator.py
from mayday import constants
class ItemValidator:
def __init__(self, ticket: dict):
self._ticket = ticket
self._validation = list()
self._error_message = list()
def check_ticket(self) -> dict:
self.validate_category()
self.validate_s... | StarcoderdataPython |
1991972 | import datetime
import os
from tempfile import TemporaryDirectory
import pytest
from .model import Assignment
class TestAssignment:
def test_fetch_assignments_by_assignee(self):
assignments = Assignment.objects.filter(assignee="US Well Services")
assert len(assignments) >= 22
assert assi... | StarcoderdataPython |
4920044 | <filename>csmserver/parsers/parser_factory.py
# =============================================================================
# Copyright (c) 2015, Cisco Systems, Inc
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following c... | StarcoderdataPython |
6672706 | """REST APIs, servers and clients for the DDM."""
| StarcoderdataPython |
9699237 | from gi.repository import GLib
import bananagui
_loop = None # Make flake8 happy.
def init():
# Gtk.main() cannot be interrupted with Ctrl+C.
global _loop
_loop = GLib.MainLoop()
def run():
_loop.run()
def quit():
_loop.quit()
def add_timeout(milliseconds, callback):
def real_callbac... | StarcoderdataPython |
3561462 | <filename>setup.py
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
from setuptools import find_packages, setup
from torch.utils.cpp_extension import BuildExtension, CUDAExtension
FASTSEQ_VERSION = '0.2.0'
MIN_FAIRSEQ_VERSION = '0.10.0'
MAX_FAIRSEQ_VERSION = '0.10.2'
MIN_TRANSFORMERS_VERSION =... | StarcoderdataPython |
11288098 | <gh_stars>0
from wickpy import graph
from wickpy import String2Graph
s = String2Graph('36*v1.v3*v4.v3*v2.v2^2*v3.v3')
s.g.draw_nodes()
s.g.draw_edges()
s.g.draw_img()
#g = graph.Graph()
#g.add_node('a')
#g.add_node('b')
#g.add_node('b')
#g.add_node('c')
#g.add_node('d')
#g.add_node('e')
#
#g.add_edge(('a','b'))
#g.ad... | StarcoderdataPython |
224324 | <reponame>MentenAI/menten_gcn
import math
from menten_gcn.decorators.base import Decorator
# from menten_gcn.decorators.geometry import *
# from menten_gcn.decorators.sequence import *
class BareBonesDecorator(Decorator):
"""
This decorator is included in all DataMakers by default.
Its goal is to be the... | StarcoderdataPython |
280273 | <reponame>Ros522/lazy-bot-tester<filename>lazybot/collector/core.py<gh_stars>0
import asyncio
import os
import sys
from typing import NamedTuple
import aioredis
from aioinflux import *
from lazybot.collector.exchanges.bitflyer import BitFlyer
@lineprotocol
class Tick(NamedTuple):
timestamp: TIMEINT
code: TA... | StarcoderdataPython |
3426401 | #!/usr/bin/python
'''
This script will download the yum repository metadata for the
Zabbix 3.0 (LTS) branch and determine the latest version of the
zabbix-server-mysql package. It will then find version of the
same RPM as deployed in the environment. It will determine
how many versions old the running version is and s... | StarcoderdataPython |
9605436 | <reponame>leukeleu/django-fiber-multilingual<filename>fiber/admin_views.py
import json
from django.contrib.admin.views.decorators import staff_member_required
from django.core.urlresolvers import reverse
from django.views.decorators.http import require_POST
from django.contrib.auth import authenticate, login
from djan... | StarcoderdataPython |
393341 | #!/usr/bin/env python
import os.path
import ConfigParser
class Settings():
def __init__(self):
#Set defaults
self.scanMode_LE=False
self.scanMode_Disc=False
self.scanMode_NonDisc=False
self.readTimeout_Disc=0
self.readTimeout_NonDisc=0
self.baseServer_URL=None
self.baseServer_Timeout=8
self.b... | StarcoderdataPython |
218212 | <filename>conv_lstm/__init__.py
from .conv_lstm import ConvLSTM, ConvLSTMCell
__all__ = ["ConvLSTMCell", "ConvLSTM"]
| StarcoderdataPython |
6545213 | <filename>simshop/builders/VerilogSim.py
# Copyright 2010-2011, RTLCores. All rights reserved.
# http://rtlcores.com
# See LICENSE.txt
import os
import time
from CmdArgs import CmdArgs
from CmdRun import CmdRun
import Exceptions
from HMS import HMS
class VerilogSim():
def __init__(self, cfg):
self.cfg = c... | StarcoderdataPython |
8106312 | {
"targets": [
{
"target_name": "equihashverify",
"dependencies": [
],
"sources": [
"support/cleanse.cpp",
"uint256.cpp",
"arith_uint256.cpp",
"random.cpp",
"util.cpp",
... | StarcoderdataPython |
66552 | import os
from pathlib import Path
class Paths:
"""Manages and configures the paths used by WaveRNN, Tacotron, and the data."""
def __init__(self, data_path, voc_id, tts_id):
self.base = Path(__file__).parent.parent.expanduser().resolve()/'outdir'
# Data Paths
self.data = Path(data_pa... | StarcoderdataPython |
1732558 | <reponame>admariner/playground
# Learning is adjusting the weight to reduce the error to 0
# Sensitivity between weight and error
# Derivative, Wikipedia:
# The derivative of a function of a real variable measures the sensitivity to change of the
# function value (output value) with respect to a change in its argument... | StarcoderdataPython |
3551957 | import indicator_ip
if __name__ == '__main__':
indicator_ip.main()
| StarcoderdataPython |
5046219 | <reponame>masashi-y/myccg
from typing import List
from lxml import etree
from depccg.tree import ScoredTree, Tree
from depccg.cat import Category, TernaryFeature, UnaryFeature
def _cat_multi_valued(cat: Category) -> str:
def rec(x: Category):
if x.is_atomic:
if isinstance(x.feature, UnaryFeat... | StarcoderdataPython |
3558390 | import datetime
import json
import os
import pytz
from django.conf import settings
from django.core.files import File
from ..models import Media, Tweet, User
from ...core.utils import truncate_string
from ...core.utils.downloader import DownloadException, filedownloader
# Classes that take JSON data from the Twitter... | StarcoderdataPython |
3385107 | <gh_stars>1-10
import logging
from telegram import Bot
from telegram.ext import Updater
from giru.config import settings
from giru.configure_disptcher import configure_dispatcher
logging.basicConfig(
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
)
def start():
# Initiate... | StarcoderdataPython |
3226381 | <filename>test/common/factories/organization.py<gh_stars>1-10
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import factory
from hyputils.memex import models
from .base import ModelFactory
class Organization(ModelFactory):
class Meta:
model = models.Organization
sqlalchemy_ses... | StarcoderdataPython |
1609731 | <filename>sep/savers/saver.py
from abc import ABC, abstractmethod
import numpy as np
import sep.loaders.loader
class Saver(ABC):
def __init__(self):
self.annotator = None
pass
def close(self):
pass
@abstractmethod
def set_output(self, output_root, loader: sep.loaders.loader... | StarcoderdataPython |
3268312 | import os
import sys
import random
import math
import numpy as np
import skimage.io
import matplotlib
import matplotlib.pyplot as plt
import coco
import utils
import model as modellib
import _visualize
import argparse
import json
import time
import csv
if __name__ == '__main__':
# matplotlib.use('Agg')
parse... | StarcoderdataPython |
3527659 | <reponame>jarchv/capsnet-tensorflow
import tensorflow as tf
import numpy as np
from capsules import CapsLayer
class CapsNet:
def __init__(self,
mode = 'train',
classes = 10,
m_plus = 0.9,
m_minus = 0.1,
lambda_ = 0.5,
alpha = 0.0... | StarcoderdataPython |
4902780 | from datetime import datetime
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from itertools import zip_longest
from flask import current_app
from flask_login import UserMixin
from ..ctf.models import UserChallenge, Challenge, UserMachine, Machine
from ..utils.models import db
from ..utils.cach... | StarcoderdataPython |
6485231 | <gh_stars>1-10
from playingCard import PlayingCard
from cardPile import CardPile
class SuitPile(CardPile):
def __init__(self):
super(SuitPile, self).__init__()
def can_take(self, card):
if self.is_empty():
return card.rank == 'A'
top_card = self.top()
return (top_card.suit == card.suit and
(top_card.... | StarcoderdataPython |
5054513 | import sqlite3
import csv
from modeli import *
def dodaj():
'''Doda različne podatke.'''
# Ladje
dodajLadjo("Reks", 1972, 80)
dodajLadjo("Titanik", 1920, 400)
dodajLadjo("Pršec", 1996, 20)
dodajLadjo("<NAME>", 1970, 10)
dodajLadjo("Volarion", 200, 40)
dodajLadjo("Nataša", 1995, 30)
... | StarcoderdataPython |
3445233 | <reponame>aimee5/sublime_packages<gh_stars>1-10
"""
Common tokens shared between the different regex modules.
Licensed under MIT
Copyright (c) 2015 - 2016 <NAME> <<EMAIL>>
"""
import re
# Unicode string related references
utokens = {
"replace_tokens": set("cCElL"),
"verbose_tokens": set("# "),
"empty": ""... | StarcoderdataPython |
1941878 | <reponame>johnbartholomew/bookwyrm<filename>fedireads/outgoing.py
''' handles all the activity coming out of the server '''
from datetime import datetime
from urllib.parse import urlencode
from django.db import IntegrityError, transaction
from django.http import HttpResponseNotFound, JsonResponse
from django.views.dec... | StarcoderdataPython |
9687805 | import torch
from sklearn.datasets import load_files
def main():
imdb = load_files(r"C:\Users\Charlie\Developer\aclImdb")
imdb.data
if __name__ == '__main__':
main() | StarcoderdataPython |
4814380 | <gh_stars>0
from serverdensity import Response
class CRUD(object):
api = None
def create(self, data=None, **kwargs):
if not data:
data = self._data
return self.__class__(self.api.post(url=self.PATHS['create'], data=data, **kwargs))
def delete(self, _id=None, **kwargs):
... | StarcoderdataPython |
3510744 | #Prva funkcija
def dobrodosao(ime):
print ("Dobrodosao " + ime)
#Druga funkcija
pozdrav = (lambda ime: ("Pozdrav " + ime))
#Treca funkcija
def dobrodoslica(funkcija):
return funkcija("Josip")
print(dobrodoslica(dobrodosao))
print(dobrodoslica(pozdrav))
| StarcoderdataPython |
11290140 | """
Tema: Filter
Curso: Python.
Plataforma: Youtube.
Profesor: <NAME> (Pildoras informaticas).
Alumno: @edinsonrequena.
"""
numbers = [3, 4, 6, 7, 45, 32, 3, 10]
def par(num):
if num % 2 == 0:
return True
print(list(filter(par, numbers)))
| StarcoderdataPython |
1954896 | <filename>eval.py
import argparse
from play import make_env, make_model, get_action
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument(
"--render",
type=int,
choices=[0, 1],
default=0,
)
args = parser.parse_args()
model = make_model("... | StarcoderdataPython |
3422483 | #Q03 - Compare the Triplets || Warmup | StarcoderdataPython |
6417067 | courses = 2
name = "John"
print("Your son", name, "is failing", courses, "subjects")
print(name, "will need to redo", courses, "courses")
name = "Eric"
print(name, "is doing well in geography") | StarcoderdataPython |
6572550 | #PROBLEM NUMBER 04
def met1():
li = []
for i in range(100,1000):
for j in range(100,1000):
prod = str(i*j)
prodr = prod[::-1]
if prod == prodr:
li.append((int(prod),i,j))
return max(li)
def met2():
pass
print(met1())
#print(met2())
| StarcoderdataPython |
6616796 | <reponame>pierre-24/AM-Nihoul-website<gh_stars>0
"""
Utils functions to send an email via Gmail, extended to accept embedded files. Most of the code is due to
https://github.com/jeremyephron/simplegmail/blob/66e776d5211042b2868664ca800bdfc45323732c/simplegmail/gmail.py
"""
from typing import Optional, List
import base... | StarcoderdataPython |
11392482 | from typing import Optional
from discord import Message
from discordmenu.embed.control import EmbedControl
from discordmenu.embed.menu import EmbedMenu
from tsutils.menu.panes import MenuPanes, emoji_buttons
from padinfo.view.simple_text import SimpleTextView, SimpleTextViewState
class SimpleTextNames:
home = '... | StarcoderdataPython |
315805 | import uuid
from datetime import date
from django.conf import settings
from django.db import models
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from django_ilmoitin.utils import send_notification
from enumfields import EnumField
from helsinki_gdpr.models import Serializabl... | StarcoderdataPython |
288448 | #
# Copyright (c) 2015 Red Hat
# Licensed under The MIT License (MIT)
# http://opensource.org/licenses/MIT
#
import django_filters
from pdc.apps.common import filters
from .models import Release, ProductVersion, Product, ReleaseType, Variant, CPE, VariantCPE, BaseProduct, ReleaseGroup
class ActiveReleasesFilter(filt... | StarcoderdataPython |
3521455 | import os
from navrep.envs.markenv import MarkEnv
from navrep.scripts.test_mark_common import load_markeval_statistics, plot_markeval_statistics
if __name__ == "__main__":
os.environ["CUDA_VISIBLE_DEVICES"] = "-1" # disable GPU
# example usage
env = MarkEnv(silent=True) # for plotting only
stats_d... | StarcoderdataPython |
3246331 | """Invocation: python manage.py verify_smartgrid
Verifies that all of the existing smartgrid unlock condition strings are valid.
Prints out the names of any invalid conditions."""
from apps.managers.challenge_mgr.challenge_mgr import MakahikiBaseCommand
from apps.utils import utils
from apps.widgets.smartgrid.model... | StarcoderdataPython |
5132306 | from rstem.accel import Accel
from rstem.sound import Note
import time
accel = Accel()
# Calibrate
z_rest = 0
SAMPLES = 100
for i in range(SAMPLES):
x, y, z = accel.forces()
z_rest += z
time.sleep(0.01)
z_rest /= SAMPLES
# Beep to tell user we're starting recording
beep = Note('A6')
beep.play(0.2).wait()... | StarcoderdataPython |
6563625 | import contextlib
import fcntl
import itertools
import os
import signal
import sys
import time
import mock
import pytest
from paasta_tools import mac_address
skip_if_osx = pytest.mark.skipif(sys.platform == 'darwin', reason='Flock is not present on OS X')
def test_simple(tmpdir):
mac, lock_file = mac_address.... | StarcoderdataPython |
3273509 | <filename>Examples/bmutils/inspect_mate.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
``inspect_mate`` provides more methods to get information about class attribute
than the standard library ``inspect``.
This module is Python2/3 compatible, tested under Py2.7, 3.3, 3.4, 3.5, 3.6.
Includes tester function to ... | StarcoderdataPython |
11270716 | """
Copyright (c) 2020 COTOBA DESIGN, Inc.
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 without limitation
the rights to use, copy, modify, merge, publish, distri... | StarcoderdataPython |
8083871 | # EXERCÍCIO 42
# Refaça o DESAFIO 35 dos triângulos, acrescentando o recurso de mostrar que tipo de triângulo será formado:
# EQUILÁTERO: todos os lados iguais
# ISÓSCELES: dois lados iguais, um diferente
# ESCALENO: todos os lados diferentes
print('-=-' * 20)
print('\t\tAnalisador de Triângulo')
print('-=-' * 20)
a ... | StarcoderdataPython |
3476598 | import warnings
from numbers import Number
from typing import Iterable, List, Optional, Union
import numpy as np
from ..C import (
LEN_RGB,
LEN_RGBA,
RGB,
RGB_RGBA,
RGBA_ALPHA,
RGBA_MAX,
RGBA_MIN,
RGBA_WHITE,
)
from .clust_color import assign_colors_for_list
def process_result_list(r... | StarcoderdataPython |
4914050 | import pandas as pd
import folium
import webbrowser
guidoval = folium.Map(
location=[-21.151944, -42.796944], # Coordenadas retiradas do Google Maps
zoom_start=18
)
folium.Marker([-21.151744,-42.798159], ['<NAME>']).add_to(guidoval)
guidoval.save('opa.html')
url = 'opa.html'
webbrowser.open(... | StarcoderdataPython |
4855153 | from src.module import dummy_module | StarcoderdataPython |
4925236 | from .loggers import cloudwatch_logger
| StarcoderdataPython |
1961632 | import torch
from SDSAE import AutoEncoder, noise
from torchvision.datasets import MNIST
from torch.utils.data import DataLoader
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
enc_length =14
batch_size = 16
# perfrom operations in GPU if possible
device = torch.device('cuda:0' if torch.cud... | StarcoderdataPython |
1818123 | import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from time import sleep
from selenium.common.exceptions import NoSuchElementException
# browser = webdriver.Chrome()
#
# browser.get('http://www.klosebrothers.de/parkcalc')
# assert... | StarcoderdataPython |
6416568 | <gh_stars>1-10
import random
import time
import numpy as np
import csv
import sys
def game():
score=0
with open('words.csv',mode='r') as data:
data=np.array(data.readlines()[0].split(','))
b=np.random.choice(data,5)
print('WELCOME TO TERMINAL BASED FAST TYPING GAME\n')
time.... | StarcoderdataPython |
3380417 | import csv
import glob
import math
import os
import torch
from astropy.io import fits
from six.moves import urllib
import torch
is_torchvision_installed = True
try:
import torchvision
except:
is_torchvision_installed = False
import torch.utils.data
import random
import itertools
import numpy as np
def load_... | StarcoderdataPython |
6598368 | from righteous.settings import EMAIL_USE_TLS
from django.contrib import messages, auth
from django.shortcuts import get_object_or_404, redirect, render
from righteous.db.forms import RegistrationsForm, UserProfileForm
from .models import Account, UserProfile
from carts.models import Cart, CartItem
from carts.views impo... | StarcoderdataPython |
3376370 | <gh_stars>1-10
#!/usr/bin/python3
from typing import List
from re import compile as regCompile, I as regI, Pattern
class Tweet:
def __init__(self, id: str, text: str, urls: List[str], mediaUrls: List[str]):
self.id = id
self.text = text
self.urls = urls
self.mediaUrls = mediaUrls
... | StarcoderdataPython |
4855274 | <gh_stars>1-10
import json
import keras
from attention_with_context import AttentionWithContext
from keras import backend as K
def load_model_custom(path_weights, custom_layer_name):
loaded_model = keras.models.load_model(path_weights, custom_objects={
custom_layer_name: ... | StarcoderdataPython |
9690271 | # :coding: utf-8
from docutils.statemachine import StringList
def get_rst_class_elements(
environment, module_name, module_path_name, whitelist_names=None,
undocumented_members=False, private_members=False,
force_partial_import=False, skip_attribute_value=False, rst_elements=None
):
"""Return :term:`... | StarcoderdataPython |
5194219 | <filename>exploits/vaultpass/off_by_one.py
#!/usr/bin/python3
# send_request has an off-by-one error, allowing us to set the accepted byte to one.
import sys
import socket
import time
ip = sys.argv[1]
PORT = 7777
RECV_TIME = 0.1
# Registering a new user to get last user_id
sock = socket.socket()
sock.connect((ip, P... | StarcoderdataPython |
9675358 | # Steps through a game of Tic-Tac-Toe
from src.game.board_state import BoardState
class Game:
def __init__(self, players) -> None:
self.players = players
self.game_state = BoardState()
self.current_player = 0
self.winner = None
def step(self):
old_state = self.game_st... | StarcoderdataPython |
3387188 | <gh_stars>1-10
from flask import Flask, Response
from flask_restful import Resource, Api
import time
import cv2
import threading
app = Flask(__name__)
api = Api(app)
latest_vision_result = {'state' : 'None', 'range' : 1000000, 'angle' : 900, 'time' : str(time.time())}
class VisionResult(Resource):
def get(self):... | StarcoderdataPython |
11387788 | <reponame>anastasiia-zolochevska/cloud-custodian
"""
Azure Functions
"""
# Docker version from https://hub.docker.com/r/microsoft/azure-functions/
FUNCTION_DOCKER_VERSION = 'DOCKER|mcr.microsoft.com/azure-functions/python:latest'
FUNCTION_EXT_VERSION = '~2'
FUNCTION_EVENT_TRIGGER_MODE = 'azure-event-grid'
FUNCTION_TIME... | StarcoderdataPython |
4910047 | <filename>tests/test_logs.py<gh_stars>0
from mock import Mock
from oops import logs
def test_color():
assert logs.color('red', Mock(no_colors=False)) == 'red'
assert logs.color('red', Mock(no_colors=True)) == ''
| StarcoderdataPython |
3239724 | <gh_stars>1-10
# Write a program that reads two names and a delimiter. It should print the names joined by the delimiter.
# Examples
# Input Output
# John
# Smith
# -> John->Smith
# Jan
# White
# <-> Jan<->White
# Linda
# Terry
# => Linda=>Terry
name_1 = input()
name_2 = input()
delimiter = input()
print(name_1 + del... | StarcoderdataPython |
3285262 | import numpy as np
import pytest
from nlp_profiler.constants import NaN
from nlp_profiler.granular_features.chars_spaces_and_whitespaces \
import count_chars, count_whitespaces, count_characters_excluding_whitespaces, \
gather_repeated_whitespaces, count_repeated_whitespaces # noqa
text_with_a_number = '2833... | StarcoderdataPython |
3233519 | <gh_stars>0
# This file is seperated from the main test file in
# order to simulate models defined in external modules.
import pytest
torch = pytest.importorskip("torch")
tensorflow = pytest.importorskip("tensorflow")
keras = tensorflow.keras
svm = pytest.importorskip("sklearn.svm")
np = pytest.importorskip("numpy")
... | StarcoderdataPython |
3454212 | <filename>myFirstTwitterBot.py<gh_stars>0
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 30 14:24:48 2019
@author: mctwn
This strategy is the following:
1. Search for those posts where ppl comment and follow those who liked
their comments
2. Like all comments
3. Follow back those who follow... | StarcoderdataPython |
9606066 | import os
from setuptools import setup
from setuptools.extension import Extension
import glob
try:
from Cython.Build import cythonize
ext = 'pyx'
except ImportError:
cythonize = None
ext = 'c'
extensions = []
for file in glob.glob('py/loqui/*.%s' % ext):
package = os.path.splitext(os.path.basenam... | StarcoderdataPython |
3561110 | <reponame>atsuhiro/dagster
from dagster import InputDefinition, OutputDefinition, Output, SolidDefinition, check, lambda_solid
def _compute_fn(context, inputs):
passed_rows = []
seen = set()
for row in inputs.values():
for item in row:
key = list(item.keys())[0]
if key not ... | StarcoderdataPython |
3389452 | <filename>src/ghaudit/query/compound_query.py
import functools
import json
import logging
from typing import Any, List, Mapping, Set, TypedDict
import requests
from ghaudit import utils
from ghaudit.auth import AuthDriver
from ghaudit.query.sub_query import SubQuery, ValidValueType
from ghaudit.query.utils import jin... | StarcoderdataPython |
1697866 | # -*- coding: utf-8 -*-
import requests
from lxml import html
import sys
reload(sys) # Python2.5 初始化后会删除 sys.setdefaultencoding 这个方法,我们需要重新载入
sys.setdefaultencoding('utf-8')
def get_general_number(result):
for item in ("About", ",", "results"):
result = result.replace(item, "")
return result
def se... | StarcoderdataPython |
3211043 | <filename>bgp_extrapolator/SQL_querier.py
import psycopg2
import re
from datetime import date
from lib_bgp_data import Database
from progress_bar import progress_bar
from named_tup import What_if_tup
import random
import sys
class SQL_querier:
def __init__(self,cursor_type = None):
if(cursor_type is not No... | StarcoderdataPython |
12813698 | # tests/test_client.py
# выполняет тестирование клиента
# :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
import unittest
import re
from app import create_app, db
from app.models.user import User
# :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
class FlaskClient... | StarcoderdataPython |
8128331 | <reponame>anshul-patel-infostretch/crux-python<gh_stars>0
import os
import pytest
from crux._client import CruxClient
from crux.models import Dataset, Delivery, File, Folder, Label, Resource, StitchJob
@pytest.fixture(scope="module")
def dataset():
os.environ["CRUX_API_KEY"] = "1235"
conn = CruxClient(crux_... | StarcoderdataPython |
9790685 | import sys
import os
sys.path.append('../../software/models/')
from utilFunctions import wavread
"""
A1-Part-1: Reading an audio file
Write a function that reads an audio file and returns 10 consecutive samples of the file starting from
the 50001th sample. This means that the output should exactly contain the 50001t... | StarcoderdataPython |
6568319 | for x in range(100):
if x == 50:
continue
| StarcoderdataPython |
11378254 | from methods import Secant_method
from sympy import *
from sympy.functions import exp
x = Symbol('x')
function_formula = exp(-x) - x
call_func = Secant_method.Secant(function_formula, 1.0, 0.0, 0, 0)
# bool1 = call_func.verify_there_is_a_root()
# print(bool(bool1))
root = call_func.compute_root()
print(root)
call_... | StarcoderdataPython |
12843703 | <reponame>Gravens/AirDimples
import time
from threading import Thread
import cv2
import keyboard
import drawing
import utils
from config import config
from gameplay import GameWithFriendOpenVINO
from utils import log
class DisplayThread(Thread):
def __init__(self, frame_deque, joints_deque, fps=24, gui=None):
... | StarcoderdataPython |
176561 | #!/usr/bin/python
"""
Utility script with functions used in lr classifier and cnn classifier.
For data preparation:
- get_train_test(): from dataframe, and specified columns, get train and test data and labels
- tokenize_text(): tokenize a list of texts, and return tokenized texts
- pad_texts(): add padding t... | StarcoderdataPython |
6489631 | <reponame>RomanDiachenko/FirstTestRepository
import time
from selenium.webdriver import ActionChains
from selenium.webdriver.common.keys import Keys
class MailOperation:
def __init__(self, app):
self.app = app
# Search and choose first mail
def search_mail(self):
driver = self.app.drive... | StarcoderdataPython |
1637752 | <reponame>zlc18/LocalJudge
# -*-coding:utf-8-*-
import logging
from lj.judger import do_judge_run, do_compile, JudgeResultSet
from lj.utils import (
get_data_dir,
get_cases,
read_file
)
logger = logging.getLogger()
# TODO: 支持带空格的文件名?
# TODO: 删除二进制文件
def lj_judge(args):
src = args.src
data_dir = ... | StarcoderdataPython |
11275623 | <filename>calculate_bleu.py
import nltk
import re
from nltk import tokenize
def read_file(path):
text = open(path, encoding='utf-8').read()
titles = []
output = []
not_truth = False
temp_title = None
for line in text.split('\n'):
if line.startswith('>'):
temp_title = tokeni... | StarcoderdataPython |
11298208 | from rpython.rtyper.llinterp import LLInterpreter
from rpython.translator.backendopt.tailrecursion import remove_tail_calls_to_self
from rpython.translator.translator import TranslationContext, graphof
def test_recursive_gcd():
def gcd(a, b):
if a == 1 or a == 0:
return b
if a > b:
... | StarcoderdataPython |
8080660 | <reponame>tupui/rbc
"""Implement Buffer type as a base class to HeavyDB Array and Column types.
HeavyDB Buffer represents the following structure:
template<typename T>
struct Buffer {
T* ptr;
size_t sz;
...
}
that is, a structure that has at least two members where the first is
a pointer to some da... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.