id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
1937597 | <reponame>pguermo/pytest-ansible
import warnings
import ansible.constants
import ansible.utils
import ansible.errors
from ansible.plugins.callback import CallbackBase
from ansible.executor.task_queue_manager import TaskQueueManager
from ansible.playbook.play import Play
# from ansible.plugins.loader import module_load... | StarcoderdataPython |
1788666 | # Generated by the protocol buffer compiler. DO NOT EDIT!
# source: control_delegation.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf.internal import enum_type_wrapper
from google.protobuf import descriptor as _descriptor
from google.protobuf import me... | StarcoderdataPython |
1838980 | a_string = 'Hello World'
print(a_string)
print(a_string[0])
print(a_string[0:5]) # the first five characters
# Sets
basket = {'Apple', 'Orange', 'Apple', 'pear', 'orange', 'banana'}
print(basket) # Duplicates will be removed
a = set('abracadabra')
print(a)
a.add('z')
print(a)
# Frozen sets
b = frozenset('asdada... | StarcoderdataPython |
8039603 | <gh_stars>0
import RPi.GPIO as gpio
import time
class move:
def __init__(self, name):
self.name = name
def init(self):
gpio.setmode(gpio.BCM)
gpio.setup(17, gpio.OUT)
gpio.setup(22, gpio.OUT)
gpio.setup(23, gpio.OUT)
gpio.setup(24, gpio.OUT)
def forward(s... | StarcoderdataPython |
3472358 | <filename>drawwithopencv.py
import numpy as np
import cv2
import keras
from PIL import ImageGrab, Image
#globale variable
canvas = np.zeros([400,400,3],'uint8')
radius = 10
color = (255,255,255)
pressed = False
#fourcc = cv2.VideoWriter_fourcc(*'XVID')
#out = cv2.VideoWriter('digitClassify.avi',fourcc, 20... | StarcoderdataPython |
5064122 | # -*- coding: utf-8 -*-
"""Common Jinja2 filters for manipulating ansible vars."""
import itertools
import math
import operator
import os.path
def hostname(fqdn):
"""Return hostname part of FQDN."""
return fqdn.partition('.')[0]
def domain(fqdn):
"""Return domain part of FQDN."""
return fqdn.partit... | StarcoderdataPython |
11224603 | <filename>adstxt/rabbitmq_test/receive.py
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(host="localhost"))
channel = connection.channel()
channel.queue_declare(queue="hello")
def callback(ch, method, properties, body):
print(" [x] Received : {}".format(body))
channel.basic_consume(qu... | StarcoderdataPython |
6652836 | <gh_stars>0
# Written by <NAME> 07/17
import praw
import pickle
import time
from Structures.Queue import Queue
import RedditSilverRobot
from datetime import datetime
print("Starting up the bots!")
reddit = praw.Reddit(client_id='client_id',
client_secret='client_secret',
user_agen... | StarcoderdataPython |
97564 | <gh_stars>0
#__author__ = 'Gavin'
from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'mysite.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^$','test.views.index',name='index'),
url(r'^2/$','test.views.index2',name='in... | StarcoderdataPython |
5130657 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2014 Ciel, http://ciel.im
# Distributed under terms of the MIT license.
# git ignore delete
import os
from config import USER_PATH
from file_operation import test_folder
from file_operation import test_file
from file_operation import find_all_files
from file_ope... | StarcoderdataPython |
8036778 | <filename>questions/45964913/mesh_lib/model.py
from __future__ import print_function # backwards compatibility
from __future__ import division
# heap queue data structure from standard python libraries
# used for the search algorithm
import heapq
import numpy as np
def dijkstra(vertexes_dict, start_i, target_i):
... | StarcoderdataPython |
8002415 | from abc import ABCMeta, abstractmethod
from threading import Lock
from _pyio import __metaclass__
class VirtualFile(object):
__metaclass__ = ABCMeta
def __init__(self, absRootPath):
self.path = absRootPath
def __enter__(self):
return self
def __exit__(self, *exc):
... | StarcoderdataPython |
1800060 | <reponame>Razz21/Nuxt-Django-E-Commerce-Demo
# Generated by Django 2.2.9 on 2020-01-18 14:45
from decimal import Decimal
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0001_initial'),
]
operations = [
... | StarcoderdataPython |
8154949 | <filename>checkers/CheckersGame.py
import sys
from .Piece import Piece
from .Board import Board, _mirror_action
#sys.path.append('..')
from Game import Game
import numpy as np
import copy
W = 4
H = 8
class CheckersGame(Game):
def __init__(self):
pass
def getInitBoard(self):
return Board()
... | StarcoderdataPython |
1816395 | class AdoptionCenter:
"""
The AdoptionCenter class stores the important information that a
client would need to know about, such as the different numbers of
species stored, the location, and the name. It also has a method to adopt a pet.
"""
def __init__(self, name, species_types, location):
... | StarcoderdataPython |
11387591 | #!/usr/bin/env python
import rospy, math
from servo_controller import Servo
import Adafruit_BBIO.GPIO as GPIO
import Adafruit_BBIO.PWM as PWM
class Car:
def __init__(self, s_pin = "P8_13", f_pin = "P9_14", b_pin = "P9_22", debug = False):
# initialize servo for steering
self.steer = Servo(s_pin)
# save P... | StarcoderdataPython |
4945688 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import torch
import torch.nn as nn
import torch.nn.init as init
import torch.nn.functional as F
class BasicConv(nn.Module):
def __init__(
self,
in_planes,
out_planes,
kernel_size,
stride=1,
padding=0,
dila... | StarcoderdataPython |
3404243 | #########################################
####### Rig On The Fly #######
####### Copyright © 2020 Dypsloom #######
####### https://dypsloom.com/ #######
#########################################
import bpy
from . PolygonShapesUtility import PolygonShapes
from . Utility import StateUtility, Channel
from ... | StarcoderdataPython |
8178549 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import time
import os
from PIL import Image
import torch
import torch.nn as nn
import torchvision
from torch.utils.data import DataLoader, Dataset
% matplotlib inline
warnings.filterwarnings('ignore')
class TwinsDataloader(Da... | StarcoderdataPython |
1955825 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | StarcoderdataPython |
1985869 | <reponame>leVirve/ELD<gh_stars>0
import torch.nn as nn
from .Unet import UNetSeeInDark
def unet(in_channels, out_channels, **kwargs):
return UNetSeeInDark(in_channels, out_channels)
| StarcoderdataPython |
20348 | <reponame>h4ckfu/data<filename>bob-ross/cluster-paintings.py
"""
Clusters Bob Ross paintings by features.
By <NAME> <<EMAIL>>
See http://fivethirtyeight.com/features/a-statistical-analysis-of-the-work-of-bob-ross/
"""
import numpy as np
from scipy.cluster.vq import vq, kmeans, whiten
import math
import csv
def main... | StarcoderdataPython |
3519153 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import sorl.thumbnail.fields
import system.core.models
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='About',
... | StarcoderdataPython |
1816403 | <filename>utils.py
from random import uniform, randint
from abc import abstractmethod, ABC
from time import time, perf_counter
import matplotlib.pyplot as plt
from seed_random import IsolatedBernoulliArm
from permutation import IsolatedPermutation
class Timer:
"""Timer class allows to time a arbitrary blocks of c... | StarcoderdataPython |
11225186 | import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
import pandas as pd
import dash_table
import json
import numpy as np
# from utils.plot_geojson import dart_plot
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
#... | StarcoderdataPython |
4812396 | <reponame>vartagg/rempycs
from rempycs import *
| StarcoderdataPython |
1751040 | <reponame>JoanAzpeitia/lp_sg
# Copyright (c) 2013 Shotgun Software Inc.
#
# CONFIDENTIAL AND PROPRIETARY
#
# This work is provided "AS IS" and subject to the Shotgun Pipeline Toolkit
# Source Code License included in this distribution package. See LICENSE.
# By accessing, using, copying or modifying this work you in... | StarcoderdataPython |
1730697 | #!/usr/bin/env python3
"""
Author : <NAME> <<EMAIL>>
Date : 2021-10-18
Purpose: Translates IUPAC codes
"""
import argparse
import sys
# --------------------------------------------------
def get_args():
"""Get command-line arguments"""
parser = argparse.ArgumentParser(
description='Rock the Casba... | StarcoderdataPython |
4839175 | def get_min_max(ints):
"""
Return a tuple(min, max) out of list of unsorted integers.
Args:
ints(list): list of integers containing one or more integers
"""
# Handle non-list input
if not isinstance(ints, list):
return None, None
# Define variables for min and max value and... | StarcoderdataPython |
229659 | <reponame>WilliamHoltam/Financial-Derivatives-Coursework
"""
Created on Wed Feb 21 10:37:33 2018
@author: <NAME>
"""
import numpy as np
import pandas as pd
import pylab as plt
from scipy.stats import norm, probplot
from matplotlib.ticker import FuncFormatter
headers = ['Date', 'Open', 'High', 'Low', 'Close', 'Adj Cl... | StarcoderdataPython |
40953 | <reponame>loghmanb/daily-coding-problem<filename>google_gas_station.py
'''
Gas Station
Asked in: Bloomberg, Google, DE Shaw, Amazon, Flipkart
Given two integer arrays A and B of size N.
There are N gas stations along a circular route, where the amount of gas at station i is A[i].
You have a car with an unlimited gas ... | StarcoderdataPython |
4859726 | class Sort():
@staticmethod
def bubble_sort(arr):
arr=list(arr)
if len(arr)<=1:
return arr
for i in range(1,len(arr)):
for j in range(len(arr)-i):
if arr[j] > arr[j+1]:
arr[j],arr[j+1]=arr[j+1],arr[j]
return arr
... | StarcoderdataPython |
1878282 | <reponame>pg-irc/pathways-backend
from drf_yasg2 import openapi, views
from rest_framework import permissions
def build_schema_view():
info = openapi.Info(title='Pathways HSDA',
default_version='v1',
description='PeaceGeeks implementation of OpenReferral Human Servic... | StarcoderdataPython |
4965113 | from __future__ import absolute_import
from __future__ import print_function
import numpy as np
from scipy.stats import sigmaclip
from astropy.io import fits
import os
from . import focasifu as fi
def MkBiasTemplate(filename, nsigma=4.0, rawdatadir='', overwrite=False,
outputdir='.'):
path = os.... | StarcoderdataPython |
6555603 | <gh_stars>0
# 一个节点的数据类型,包含左子孩子节点指针 右孩子节点指针 和值
class Node(object):
def __init__(self, item):
self.left = None # 指向左子节点
self.right = None # 指向右子节点
self.item = item # 保存值
# 树的类
class Tree(object):
def __init__(self):
self.root = None # 保存树根所在位置
# 添加节点方法,按照层次由低到高,优先靠左的思想添加... | StarcoderdataPython |
210180 | vl=input().split()
A=int(vl[0])
B=int(vl[1])
if A==B:
print("Nao sao Multiplos")
elif A%B==0 or B%A==0:
print("Sao Multiplos")
else:
print("Nao sao Multiplos")
| StarcoderdataPython |
9699896 | <gh_stars>1-10
from __future__ import absolute_import
from django import forms
from .exceptions import DocumentAlreadyCheckedOut
from .models import DocumentCheckout
from .widgets import SplitTimeDeltaField
class DocumentCheckoutForm(forms.ModelForm):
expiration_datetime = SplitTimeDeltaField()
class Meta:... | StarcoderdataPython |
4921149 | #!/usr/bin/env python3
import sys
import socketserver
import logging
import json
from lib.MyTCPHandler import MyTCPHandler
# Load the server and TCP Handler configuration from file
def load_server_handler_config(config_file):
logging.debug("Opening socketserver config: " + config_file)
with open(config_file,... | StarcoderdataPython |
4823606 | """
Copyright 2010 <NAME>
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 writing... | StarcoderdataPython |
6409960 | """
pluginName = TLShort
Senario Short Timelapse Project
-------------------------------
This setup will save images in number sequence in case date/time is not maintained
due to a reboot and no internet NTP server is available. It will Not create subfolders.
Depending on the full duration of the timelapse sequence i... | StarcoderdataPython |
8079498 | <gh_stars>10-100
"""
Script that pulls prices and rates of specified currencies using forex python.
The data is then formatted and published via redis.
It would be cumbersome to query and reformat the query result with every api request,
especially since the requests are rarely dependant on external inputs.
this way... | StarcoderdataPython |
11384864 | <reponame>chen940303/Diaosier_home
#-*-coding:utf-8-*-
from flask import render_template,request,jsonify
from . import main
@main.app_errorhandler(404)
def page_not_found(e):
if request.accept_mimetypes.accept_json and not request.accept_mimetypes.accept_html:
response=jsonify({'error':'not found'})
... | StarcoderdataPython |
5059442 | from pathlib import Path
from collage.utils import extract_attrs, get_input_shape
import json
import pickle
from os import path
import logging
# @sunggg: [TODO] Need to check hash conflict
# configuration includes operator name, operator type (backend operators from different targets might have the same type),
# data ... | StarcoderdataPython |
5192569 | <gh_stars>1-10
# -*- coding: utf-8 -*-
import uuid
import requests
import hashlib
import time
class Translator:
YOUDAO_URL = 'https://openapi.youdao.com/api'
APP_KEY = ''
APP_SECRET = ''
def encrypt(self, signStr):
hash_algorithm = hashlib.sha256()
hash_algorithm.update(signStr.encode... | StarcoderdataPython |
6502112 | import numpy as np
import time
def compute_roc_points(labels, scores, fprs, use_sklearn=True):
tpr_k_score = []
th_k_score = []
sp_tpr = 0
print(labels.shape)
print(scores.shape)
if use_sklearn:
from sklearn.metrics import roc_curve
roc_fpr, roc_tpr, roc_thresholds = roc_curve... | StarcoderdataPython |
12858957 | import cocotb
from cocotb.clock import Clock
from cocotb.triggers import ClockCycles, RisingEdge, FallingEdge, NextTimeStep, ReadWrite
N = 16
test_input = list(range(N))
async def writer(dut):
for i in test_input:
busy_check = lambda : not dut.ready_for_input.value
while busy_check():
... | StarcoderdataPython |
6662895 | <reponame>xWasp97x/Greenhouse<filename>greenhouse/Dashboard/observer_pattern.py
class Observer:
def update(self, payload):
raise NotImplementedError
class Observable:
def __init__(self):
self.observers = set()
def add_observer(self, observer: Observer):
self.observers.add(observer)
def remove_observer(sel... | StarcoderdataPython |
1896499 | AUTO_UPDATE_TIME = 20
SERVER_INVITE = "https://discord.gg/xP2UPUn"
BOT_INVITE = "https://discord.com/oauth2/authorize?client_id=669978762120790045&permissions=0&scope=bot"
GITHUB_LINK = "https://github.com/pseudocoder10/Lockout-Bot"
ADMIN_PRIVILEGE_ROLES = ['Admin', 'Moderator', 'Lockout Manager']
OWNERS = [515920333... | StarcoderdataPython |
6580564 | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
import IReadiTunes
setup(
name='IReadiTunes',
version=IReadiTunes.__version__,
packages=find_packages(),
author="Mickael",
author_email="<EMAIL>",
description="Tool to get any information about iTunes tracks and playlists quic... | StarcoderdataPython |
1802178 | <reponame>sophy7074/FALCON
#import falcon_kit.mains.run as mod
'''
def test_help():
try:
mod.main(['prog', '--help'])
except SystemExit:
pass
'''
| StarcoderdataPython |
294385 | <filename>PYex/hexGame/hex.py
## <NAME> - franr.com.ar/hex |
## ------------------------------------/
# import os
import random
from threading import Thread
import pygame
# constantes
RUN = True
LONG = 20
AMARILLO = (255, 231, 0)
AMARILLO_C = (255, 255, 50)
AZUL = (0, 127, 245)
AZUL_C = (50, 177, 255)
BLANCO = (255,2... | StarcoderdataPython |
1861333 | import chart_studio
import os
import json
import requests
from requests.auth import HTTPBasicAuth
def get_pages(username, page_size, auth, headers):
url = 'https://api.plot.ly/v2/folders/all?user='+username+'&page_size='+str(page_size)
response = requests.get(url, auth=auth, headers=headers)
if response.... | StarcoderdataPython |
9747534 | # Databricks notebook source
# Instrument for unit tests. This is only executed in local unit tests, not in Databricks.
if 'dbutils' not in locals():
import databricks_test
databricks_test.inject_variables()
# COMMAND ----------
data = spark.range(0, 5)
data.write.format("delta").save(dbutils.widgets.get('out... | StarcoderdataPython |
4951659 | import unittest
from pyspark import SparkContext
class Base(unittest.TestCase):
def setUp(self):
self.sc = SparkContext.getOrCreate()
self.sc.setLogLevel('ERROR')
| StarcoderdataPython |
11273860 | """
Defines Annalist built-in identifier values (URIs)
"""
__author__ = "<NAME> (<EMAIL>)"
__copyright__ = "Copyright 2014, <NAME>"
__license__ = "MIT (http://opensource.org/licenses/MIT)"
import logging
log = logging.getLogger(__name__)
class Curiespace(object):
"""
Placeholder class for CURIE va... | StarcoderdataPython |
6686401 | import pytest
from pytest_mock import MockerFixture
from dataclass_wizard.utils.lazy_loader import LazyLoader
@pytest.fixture
def mock_logging(mocker: MockerFixture):
return mocker.patch('dataclass_wizard.utils.lazy_loader.logging')
def test_lazy_loader_when_module_not_found():
extra_name = 'my-extra'
... | StarcoderdataPython |
3598251 | <gh_stars>0
import logging
import threading
import time
import array
import mlperf_loadgen as lg
import numpy as np
from ..constants import QUERY_COUNT, NANO_SEC, MILLI_SEC
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
cl... | StarcoderdataPython |
3577976 | <filename>core/entities/default_race_entity.py
from core.structs import AbilityScoreStruct
from core.structs import RaceStruct
class DefaultRaceEntity(object):
def __init__(self):
self.race = RaceStruct()
def get_struct(self):
return self.race
def set_ability_score(self, strength=0, cons... | StarcoderdataPython |
1638487 | from rest_framework import serializers
from .models import WorkingHour
class WorkingHourSerializer(serializers.ModelSerializer):
class Meta:
model = WorkingHour
fields = ('id', 'hour')
| StarcoderdataPython |
9742304 | <gh_stars>0
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('assessments', '0007_behavior_... | StarcoderdataPython |
8181912 | <gh_stars>1-10
# -*- coding: utf-8 -*-
import pytest
from roswire.common import PackageDatabase
from roswire.ros1 import ROS1MsgFormat, ROS1Package, ROS1PackageDatabase, ROS1SrvFormat
def test_to_and_from_dict():
pkg = "tf"
msg_tf = ROS1MsgFormat.from_dict(
{
"package": pkg,
"n... | StarcoderdataPython |
171987 | #!/usr/bin/env python3
import sys
import numpy as np
from config import Config
from base import Connect4Base
from random_agent import RandomAgent
from simple_agent import SimpleAgent
from one_step_lookahead_agent import OneStepLookaheadAgent
from n_steps_lookahead_agent import NStepsLookaheadAgent
from cnn_agent impor... | StarcoderdataPython |
9757810 | <reponame>Pavloid21/awx<filename>awx/api/urls/deploytemplate.py
from django.conf.urls import url
from awx.api.views.deploytemplate import (DeployTemplateList, DeployTemplateDetail)
urls = [
url(r'^$', DeployTemplateList.as_view(), name='deploy_template_list'),
url(r'^(?P<pk>[0-9]+)/$', DeployTemplateDetail.as_... | StarcoderdataPython |
11340686 | #!/usr/bin/env python
'''
Created on Jul 29, 2015
@author: adrian
'''
import matplotlib
matplotlib.use('Agg')
import json
import os
import scipy.io as sio
import shutil
import sys
from oct2py import octave
from pprint import pprint
from pylab import * # @UnusedWildImport
PNGDIR = os.path.abspath('.') + '/png/'
... | StarcoderdataPython |
205567 | <filename>200Python/demo/01basic-hello/02basic/dict_set.py
scores = {'AA': 10, 'BB': 20, "CC": 30}
print("AA score:", scores['AA'])
print("Before BB score:", scores['BB'])
scores['BB'] = 100
print("After BB score:", scores["BB"])
age = {1, 2, 3}
print(age)
| StarcoderdataPython |
1870149 | #!/usr/bin/python
'''
1. fasta fname
2. replace with?
'''
from sys import argv,exit
from Bio import SeqIO
try:
fname = argv[1]
repl = argv[2]
except:
exit(__doc__)
f = open(fname, 'r')
records = SeqIO.parse(f,'fasta')
for r in records:
seq = r.seq
newSeq = ''
for l in seq:
if l.lower... | StarcoderdataPython |
31805 | import logging; module_logger = logging.getLogger(__name__)
from pathlib import Path
# ----------------------------------------------------------------------
def get_chart(virus_type, assay, lab, infix="", chart_dir=Path("merges")):
if virus_type in ["bvic", "byam"]:
vt = virus_type[:2] # virus_type[0] + ... | StarcoderdataPython |
8139455 | from helga import settings
from helga.plugins import command
@command('showme', aliases=['whois', 'whothehellis'],
help="Show a URL for the user's intranet page. Usage: helga (showme|whois|whothehellis) <nick>")
def wiki_whois(client, channel, nick, message, cmd, args): # pragma: no cover
"""
Show t... | StarcoderdataPython |
4907520 | <reponame>Trondheim-kommune/Tilskuddsbasen
"""rapport purret dato
Revision ID: 4d76a1567fe8
Revises: <KEY>
Create Date: 2015-01-16 10:33:55.678888
"""
# revision identifiers, used by Alembic.
revision = '4d76a1567fe8'
down_revision = '<KEY>'
from alembic import op
import sqlalchemy as sa
def upgrade():
### co... | StarcoderdataPython |
5074488 | #!/usr/bin/env python
import numpy as np
from despyastro.coords import *
tic, t_ra, t_dec, t_g_lon, t_g_lat, t_ec_lon, t_ec_lat = np.loadtxt("data/tic_data.dat", unpack=True)
tic = tic.astype(int)
ec_lon, ec_lat = gal2ec(t_g_lon, t_g_lat)
ra, dec = ec2eq(ec_lon, ec_lat)
ec_comp = np.column_stack((t_ec_lon, ec_lon, ... | StarcoderdataPython |
8139869 | # this segment tree will support two operations:
# 1. set segment [r, l) equal to v
# 2. For segment [r, l) find number of black parts and their length
# We will keep tuple with 4 elements for T:
# number of black parts, their total length, color of left and right ends
# For L we will keep one value 0 or 1: the lazy up... | StarcoderdataPython |
40776 | from pettingzoo import AECEnv
from pettingzoo.utils import agent_selector
from pettingzoo.utils import wrappers
from pettingzoo.utils.conversions import parallel_wrapper_fn
from gym_stag_hunt.envs.hunt import HuntEnv
from gym.spaces import Box
import cv2
import numpy as np
def env(grid_size=(5, 5), screen_size=(600,... | StarcoderdataPython |
1810565 | <reponame>pysga1996/python-basic-programming<gh_stars>0
import re
txt = 'The rain in Spain'
x = re.search('ai', txt)
print(x) # this will print an object
# Print the position (start- and end-position) of the first match occurrence
print(x.span())
# Print the string passed into the function
print(x.string)
# The re... | StarcoderdataPython |
12801969 | import boto3
import logging
import os
from random import randrange
from urllib.request import urlopen
from random import randint
# It is not recommended to enable DEBUG logs in production,
# this is just to show an example of a recommendation
# by Amazon CodeGuru Profiler.
logging.getLogger('botocore').setLevel(loggi... | StarcoderdataPython |
3575369 | <filename>tests/test_tie_nomove.py
import unittest
from .helpers import C, WHITE, BLACK, NONE
class TestTieNoMove(unittest.TestCase):
def get_board(self, *args, **kwargs):
from chess.models import Board
return Board(*args, **kwargs)
def get_tie(self, *args, **kwargs):
from chess.models... | StarcoderdataPython |
337134 | import click
from esque.cli.options import State, default_options
from .offsets import edit_offsets
from .topic import edit_topic
@click.group(help="Edit a resource.", no_args_is_help=True)
@default_options
def edit(state: State):
pass
edit.add_command(edit_offsets)
edit.add_command(edit_topic)
| StarcoderdataPython |
11163 | import pytest
import cudf
import mock
from cuxfilter.charts.core.non_aggregate.core_non_aggregate import (
BaseNonAggregate,
)
from cuxfilter.dashboard import DashBoard
from cuxfilter import DataFrame
from cuxfilter.layouts import chart_view
class TestCoreNonAggregateChart:
def test_variables(self):
... | StarcoderdataPython |
3599780 | import requests
from allauth.socialaccount.providers.oauth2.views import (
OAuth2Adapter,
OAuth2LoginView,
OAuth2CallbackView,
)
from django.conf import settings
from ditsso_internal.provider import DitSSOInternalProvider
class DitSSOInternalAdapter(OAuth2Adapter):
provider_id = DitSSOInternalProvide... | StarcoderdataPython |
5069368 | from ..model_tests_utils import (
status_codes,
DELETE,
PUT,
POST,
GET,
ERROR,
random_model_dict,
check_status_code,
compare_data
)
from core.models import (
UnitType,
)
unittype_test_data = {}
unittype_tests = [
##----TEST 0----##
#creates an unittype
#gets the unittype
#puts... | StarcoderdataPython |
1799299 | <reponame>dschultz0/awslarry<gh_stars>1-10
import unittest
import larry as lry
ENVIRONMENT_PROD = 'production'
ENVIRONMENT_SANDBOX = 'sandbox'
SANDBOX_HIT = '39HYCOOPKNK26VOMWWPV050D1O9MD5'
SANDBOX_HIT_TYPE = '3W679PTMVMW4B1YPP05F1CL2SYKBXP'
SANDBOX_ASSIGNMENT = '3TEM0PF1Q5W8Q0F8XU7ZRSPG1ARD0O'
PROD_HIT = '30Y6N4AHYOV... | StarcoderdataPython |
346717 | <gh_stars>0
#annapolis
latitude = 38.9784
# longitude = -76.4922
longitude = 283.5078
height = 13 | StarcoderdataPython |
5078216 | <gh_stars>1-10
from typing import Dict
from uuid import UUID, uuid4
import Pyro4
_START_PORT = 13337
Pyro4.config.SERIALIZERS_ACCEPTED = ['pickle']
Pyro4.config.SERIALIZER = 'pickle'
@Pyro4.expose
class Client(object):
def __init__(self, uuid: UUID):
self._uuid: UUID = uuid
def get_uuid(self) -> U... | StarcoderdataPython |
6571369 | import operator
import platform
from abc import ABC, abstractmethod
from collections import namedtuple
from os import get_terminal_size
from typing import NoReturn, Optional
Position = namedtuple("Position", ["x", "y"])
Size = namedtuple("Size", ["width", "height"])
Rectangle = namedtuple("Rectangle", ["x1", ... | StarcoderdataPython |
295099 | """Read in an Ortec SPE file."""
import datetime
import os
import warnings
import dateutil.parser
import numpy as np
from .spectrum_file import (
SpectrumFile,
SpectrumFileParsingError,
SpectrumFileParsingWarning,
)
warnings.simplefilter("always", DeprecationWarning)
class SpeFileParsingError(SpectrumFi... | StarcoderdataPython |
6574471 | <filename>env/Lib/site-packages/pip/req/req_file.py
from __future__ import absolute_import
import os
import re
from pip._vendor.six.moves.urllib import parse as urllib_parse
from pip.download import get_file_content
from pip.req.req_install import InstallRequirement
from pip.utils import normalize_name
_scheme_re =... | StarcoderdataPython |
1625345 | # Generated by Django 2.2.4 on 2019-10-02 18:43
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('django_eveonline_connector', '0003_auto_20190903_2005'),
]
operations = [
migrations.RemoveField(
model_name='eveclient',
na... | StarcoderdataPython |
6621556 | import json
import random
import sys
import time
import deck_stats.deck as deck
def analyze(deck_json):
my_deck = deck.Deck(deck_json)
# don't show dozens/hundreds of hands with less than 1% chance of occuring
num_hands_to_print = 9000
total_runs = 10000
opening_hand_mana = {}
for step in range(0, total_runs)... | StarcoderdataPython |
1642125 | <reponame>SMSajadi99/Python-Advance<gh_stars>0
from collections import defaultdict
n = int(input())
tran = {}
name = []
for i in range(n):
x=input()
x=x.split()
name.extend(x)
# print(name)
def Convert(lst):
res_dct = {(lst[i+1],lst[i+2],lst[i+3]): lst[i] for i in range(0, len(lst), 4)... | StarcoderdataPython |
3553085 | <reponame>mckinly/cms-django<gh_stars>0
"""
Form for creating a user object
"""
import logging
from django import forms
from django.utils.translation import ugettext_lazy as _
from ...models import UserProfile
from ...utils.translation_utils import ugettext_many_lazy as __
from ..custom_model_form import CustomModelF... | StarcoderdataPython |
4959067 | import os
import textwrap
import uuid
from contextlib import contextmanager
import pytest
from dagster import asset, build_init_resource_context, build_input_context, build_output_context
from hacker_news_assets.resources.snowflake_io_manager import (
DB_SCHEMA,
SHARED_SNOWFLAKE_CONF,
connect_snowflake,
... | StarcoderdataPython |
11251088 | <gh_stars>0
# -*-coding:utf-8 -*-
'''
@File : oneho_model.py
@Author : <NAME>
@Date : 2020/5/24
@Desc :
'''
import time
from ServiceOrientedChatbot.reader.data_helper import load_corpus_file
from ServiceOrientedChatbot.utils.logger import logger
class OneHotModel(object):
def __init__(s... | StarcoderdataPython |
1705547 | <gh_stars>10-100
import smtplib
from email.message import EmailMessage
with open('global_config/config.yaml') as settings:
cfg = yaml.load(settings)
from_address = (cfg['from_address'])
to_address = (cfg['to_address'])
password = (cfg['password'])
smtp_server = (cfg['smtp_server'])
smtp_port = (cfg['smtp_port']... | StarcoderdataPython |
1861271 | <reponame>haichungcn/fs-projectmanager-api
"""empty message
Revision ID: 749aafa62aa6
Revises: <PASSWORD>
Create Date: 2019-12-15 00:47:34.859436
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '<KEY>'
down_revision = '<PASSWORD>'
branch_labels = None
depends_o... | StarcoderdataPython |
8006447 | from Game import InvalidMove_Error
from Move import Move
def call_method_on_each(arr, method, *args): # via stackoverflow.com/a/2682075/2474159
for obj in arr:
getattr(obj, method)(*args)
def str2move(move_str: str, board_size: int) -> Move:
if not move_str:
return Move(is_pass=True)
co... | StarcoderdataPython |
9700740 | import numpy as np
from stable_baselines.common.policies import MlpPolicy
from stable_baselines.common import make_vec_env
from stable_baselines import TRPO
import os
import gym
from stable_baselines.common.vec_env import DummyVecEnv, VecNormalize
envid = 'PointMazeLeft-v0'
savedir = "MazeTrainedPoliciesBD"
os.makedir... | StarcoderdataPython |
275233 | <reponame>Hyoshin-Park/Test
class MaxAlgorithm: #최대값 알고리즘
def __init__(self, ns):
self.nums = ns
self.maxNum = 0
self.maxNumIdx = 0
def setMaxIdxAndNum(self):
self.maxNum = self.nums[0]
self.maxNumIdx = 0
for i, n in enumerate(self.nums):
... | StarcoderdataPython |
323911 | """This module defines a very basic store that's used by the CGI interface
to store session and one-time-key information.
Yes, it's called "sessions" - because originally it only defined a session
class. It's now also used for One Time Key handling too.
"""
__docformat__ = 'restructuredtext'
import os, marshal, time
... | StarcoderdataPython |
5114758 | <gh_stars>1-10
""" User Model """
from werkzeug.security import check_password_hash, generate_password_hash
from mongoengine import *
import datetime
import app.config
import jwt
class User(Document):
username = StringField(max_length=50, required=True, unique=True)
password_hash = StringField(max_length=128, ... | StarcoderdataPython |
1886903 | <filename>vPy27/Application.py
import GUI
import Settings
import Socket
import Initialize
from UserList import UserList
class Application():
__gui = ''
__connected = False
__logNames = False
__socket = ''
__userList = UserList()
__saveFile = ''
def __init__(self):
self.__gui = GUI... | StarcoderdataPython |
6423382 | import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
class ContentLayer:
def __init__(self, window_width, window_height, dimensions):
""" Constructor """
self.__window_width = window_width
self.__window_height = window_height
self.__contentAreaDimensions = dim... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.