id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
357591 | # this module is the template of all environment in this project
# some basic and common features are listed in this class
class ENVError(Exception):
def __init__(self, value_):
self.__value = value_
def __str__(self):
print('Environment error occur: ' + self.__value)
class ENV:
def __ini... | StarcoderdataPython |
3444647 | from sysbot_helper import bot_main
bot_main()
| StarcoderdataPython |
11309340 | import geomtwo.msg as gms
import matplotlib.pyplot as plt
import cmath as cm
class Vector:
def __init__(self, *args, **kwargs):
if len(args) is 2:
self._data = complex(*args)
return
if len(args) is 1:
if isinstance(args[0], (self.__class__, gms.Vector)):
... | StarcoderdataPython |
6616831 | <reponame>niladell/DockStream
from dockstream.utils.enums.taut_enum_enums import TautEnumEnum
from dockstream.utils.execute_external.execute import ExecutorBase
EE = TautEnumEnum()
class TautEnumExecutor(ExecutorBase):
"""For the execution of the "TautEnum" binary."""
def __init__(self, prefix_execution=No... | StarcoderdataPython |
8099894 | from django.conf.urls import url
from django.contrib import admin
from django.contrib.sitemaps.views import sitemap
from django.http import HttpResponse
from django.urls import path, include
from apps.finder import views
from apps.accounts import views as account_views
from apps.maintenance import views as maintenance... | StarcoderdataPython |
6647046 | #!/usr/bin/env python
# Simple script to convert molecular structures into Faunus AAM
# format. Uses OpenBabel's python interface to read a multitude
# of different input formats. Openbabel can be installed in
# anacona using:
# conda install --channel https://conda.anaconda.org/openbabel openbabel
# python 2/3 compat... | StarcoderdataPython |
241074 | <filename>possum/dev_possum_unsharp_mask.py
#!/usr/bin/python
import itk
from sys import argv
from optparse import OptionParser, OptionGroup
class unsharpMaskImageFilter():
def __init__(self, InputImage, sigmaArray, ammount):
"""
Simple workflow implementing unsharp masking.
"""
i... | StarcoderdataPython |
5171468 | <reponame>david-zwicker/py-utils
'''
Created on Nov 4, 2016
@author: <NAME> <<EMAIL>>
'''
from __future__ import division
import unittest
import networkx as nx
import six
from .. import graphs
class TestGraphs(unittest.TestCase):
_multiprocess_can_split_ = True # let nose know that tests can run parallel
... | StarcoderdataPython |
6494971 | from unittest import mock, TestCase
from taguri.minter import TagUriMinter
class TagUriMinterTestCase(TestCase):
@mock.patch('taguri.minter.authority_name_validator', return_value=True)
def test_minter_validates_authority_name(self, validator):
TagUriMinter('example.org', '2018')
self.assertTr... | StarcoderdataPython |
3315897 | <gh_stars>1-10
########################################################################################
## ##
## THIS LIBRARY IS PART OF THE SOFTWARE DEVELOPED BY THE JET PROPULSION LABORATORY ##
## IN THE CONTEXT OF THE GPU ACCELERA... | StarcoderdataPython |
8163170 | from .problem import Pathpacking as Problem
| StarcoderdataPython |
6522099 | import argparse
import torch
from torch import nn
from torch import optim
from torch.autograd import Variable
from torchvision import datasets, transforms, models
from torchvision.datasets import ImageFolder
import torch.nn.functional as F
from PIL import Image
from collections import OrderedDict
import time
impor... | StarcoderdataPython |
11293532 | import numpy as np
import matplotlib.pyplot as plt
import sys
sys.path.append('../src/')
from pysfa import SFA
# generate data
# -----------------------------------------------------------------------------
np.random.seed(123)
m = 2000
k_beta = 2
k_gama = 1
k_deta = 1
x = np.random.randn(m,k_beta)
z = np.ones((m,k_ga... | StarcoderdataPython |
9667621 | <filename>SImple_Resturant/main.py
import getpass
class Person:
def __init__(self, name):
self.name = name
self.state = False
def login(self):
while True:
self.username = input("Enter Your UserName: ")
self.password = getpass.getpass(prompt="Password: ")
... | StarcoderdataPython |
8030288 | <reponame>kdeltared/tcex
#!/usr/bin/env python
"""TcEx Framework LayoutJson."""
# standard library
import json
import logging
import os
from collections import OrderedDict
class LayoutJson:
"""Object for layout.json file.
Args:
filename (str, optional): The config filename. Defaults to layout.json.
... | StarcoderdataPython |
12810668 | <gh_stars>0
import multiprocessing
import os
from typing import Union
import torchvision
from torch.utils.data import DataLoader, Subset
from torchvision import transforms
from root import from_root
from src.misc.utils import read_lines
DATA_DIRPATH = from_root("data/cifar10")
SPLIT_DIRPATH = from_root("splits/cifar... | StarcoderdataPython |
6586071 | import os
import time
import concurrent.futures as cf
class ParallelExecutor:
def __init__(self, cf_reader, img_parser, pf_handler, workers, num_to_do, db = None, output_dir = None):
self.db = db
self.cf_reader = cf_reader
self.img_parser = img_parser
self.pf_handler = pf_handler
... | StarcoderdataPython |
3323297 | from sympy import factorint
x = int(input("how many: \n"))
i = 2
while True:
if all(len(factorint(a)) == x for a in range(i, i + x)):
print(i)
break
i += 1
| StarcoderdataPython |
4816330 | # (c) 2022 <NAME> MOPFPPP
# This code is licensed under the MIT license (see LICENSE.txt for details)
"""
Add traversing links to the nodes in the tree
"""
def tree_add_links(tree):
"""
TO DO: docstring this
"""
return _tree_adjust_links(4, tuple(map(_tree_set_first_links(
tuple(map(_t... | StarcoderdataPython |
3407650 | <filename>pw_console/py/table_test.py
# Copyright 2021 The Pigweed Authors
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... | StarcoderdataPython |
241474 | <filename>SM_openSMILE/openSMILE_preprocessing/convert_dir_to_flac.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
convert_dir_to_flac.py
Script to quickly convert all mp3 and mxf files in a directory to
flac files.
Author:
– <NAME>, 2016 (<EMAIL>)
© 2016, Child Mind Institute, Apache v2.0 License
@autho... | StarcoderdataPython |
3323681 | <reponame>tkinjo1985/lobe_fastapi<gh_stars>1-10
from base64 import b64encode
from io import BytesIO
from PIL import Image
def image2base64(image_file):
try:
image = Image.open(image_file).convert('RGB')
except Exception as err:
print(err)
else:
buffered = BytesIO()
image.... | StarcoderdataPython |
3248325 | <reponame>arunraja-hub/Preference_Extraction
#!/usr/bin/env python
import time
from vizdoom import *
game = DoomGame()
game.load_config("custom.cfg")
game.set_labels_buffer_enabled(True)
game.set_mode(Mode.SPECTATOR)
game.init()
episodes = 10
for i in range(episodes):
game.new_episode()
while not game.is_ep... | StarcoderdataPython |
4943975 | <reponame>geoblr008/covid-19-tracker
from bs4 import BeautifulSoup
import requests
data_check = []
worldmetersLink = "https://www.worldometers.info/coronavirus/"
html_page = requests.get(worldmetersLink)
bs = BeautifulSoup(html_page.content, 'html.parser')
search = bs.select("div tbody tr td")
def data_cleanup(array... | StarcoderdataPython |
5166786 | <reponame>splhack/loam
import magma as m
from mantle.xilinx.spartan3.RAMB import ROMB16
from loam.boards.papilioone import PapilioOne
from loam.shields.megawing import MegaWing
megawing = MegaWing(PapilioOne)
megawing.Clock.on()
megawing.Switch.on(8)
megawing.LED.on(8)
main = megawing.main()
rom = range(1024)
for i... | StarcoderdataPython |
272674 | # MIT License
#
# Copyright (c) 2019 Red Hat, 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... | StarcoderdataPython |
6547452 | from .base import *
from .gmail import *
from .twilio import *
| StarcoderdataPython |
3563677 | import re
from django.contrib.auth.models import User
from django.test import TestCase
from django.conf.urls import url
from django.http import HttpResponse
from django.template import Template, RequestContext
def simple_view(request):
t = Template('{% load websockets %}{% websocket_info %}')
c = RequestConte... | StarcoderdataPython |
225590 | <gh_stars>0
#II.5 General Equilibrium
#II.5.1
import numpy as np
from numba import jit
class Household:
r=0.04
ro=0.06
beta=1/(1+ro)
sigmay=0.5
Y=[1-sigmay,1+sigmay]
def __init__(self,
r=0.04, # interest rate
... | StarcoderdataPython |
1684761 | # ---------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# ---------------------------------------------------------
import json
import logging
import os
import pickle
import numpy as np
import pandas as pd
from sklearn.externals import joblib
import azure... | StarcoderdataPython |
3317055 | g1 = 1 # GL1
def display():
l1 = 2 # GL2
print(l1) # GL3
print(g1) # GL4
display()
print(g1) # GL5
print(l1) # GL6
| StarcoderdataPython |
9703892 | from torch.autograd import Variable
import torchvision.models as models
import torch.nn.functional as F
import torch.optim as optim
import torch.nn as nn
import numpy as np
import random
import torch
import copy
import pdb
from base.base_envs import BaseState
class State(BaseState):
def loss_fn(self, prediction... | StarcoderdataPython |
1779017 | <reponame>ml-research/MoRT_NMI
import matplotlib.pyplot as plt
from scipy.stats import pearsonr
import numpy as np
import csv
import os
from matplotlib import rc
from mort import dataMoral
import seaborn as sns
rc('font', **{'family':'sans-serif','sans-serif':['Arial']})
sns.set(style='ticks', palette='Set2')
rc('tex... | StarcoderdataPython |
9607813 | """Support for Wink water heaters."""
import logging
import pywink
from homeassistant.components.water_heater import (
ATTR_TEMPERATURE,
STATE_ECO,
STATE_ELECTRIC,
STATE_GAS,
STATE_HEAT_PUMP,
STATE_HIGH_DEMAND,
STATE_PERFORMANCE,
SUPPORT_AWAY_MODE,
SUPPORT_OPERATION_MODE,
SUPPO... | StarcoderdataPython |
5089806 | import mock
import pytest
import requests
import suds.transport
import suds_requests
def test_no_errors():
m = mock.Mock(__name__='m')
f = suds_requests.handle_errors(m)
assert f() == m.return_value
def test_HTTPError():
resp = mock.Mock(status_code=404,
content='File not found'... | StarcoderdataPython |
3376446 | from JumpScale import j
def cb():
from .BtrfsExtension import BtrfsExtension
return BtrfsExtension()
j.sal._register('btrfs', cb)
| StarcoderdataPython |
11305587 | # -*- coding: utf-8 -*-
from kalasearch import Client
import json
myclient = Client("YOUR_APP_ID", "YOUR_API_KEY")
index = myclient.get_index("YOUR_INDEX_ID")
documents = [
{"name": "周杰伦"},
{"name": "陈冠希"}
]
print(index.add_objects(documents))
options = {
"searchableFields": ["name", "story"],
"... | StarcoderdataPython |
1654640 | import numpy as np
def generate_complex_multiplication_tensor (dtype=float):
complex_multiplication_tensor = np.zeros((2,2,2), dtype=dtype)
complex_multiplication_tensor[0,0,0] = 1
complex_multiplication_tensor[0,1,1] = -1
complex_multiplication_tensor[1,0,1] = 1
complex_multiplication_tensor[1,1... | StarcoderdataPython |
78547 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# This file is part of CbM (https://github.com/ec-jrc/cbm).
# Author : <NAME>
# Credits : GTCAP Team
# Copyright : 2021 European Commission, Joint Research Centre
# License : 3-Clause BSD
"""
Project: Copernicus DIAS for CAP 'checks by monitoring'.
Functions for... | StarcoderdataPython |
6636645 | <filename>lib/tools.py
import pygame
class Dragger(object):
#TODO: implement auto-drop (after a timeout) so the system
# doesn't freeze?
def __init__(self):
self.button = None
def __del__(self):
self.drop()
def grabbing(self):
return pygame.event.get_grab()
def grab(self, button=No... | StarcoderdataPython |
3303490 | <reponame>fotonauts/fwissr-python
# conf.py
import os
import json
import yaml
def merge_conf(to_hash, other_hash, path=[]):
"merges other_hash into to_hash"
for key in other_hash:
if (key in to_hash and isinstance(to_hash[key], dict)
and isinstance(other_hash[key], dict)):
... | StarcoderdataPython |
9707461 | # importacao de bibliotecas
import requests
from bs4 import BeautifulSoup
import pandas as pd
import time
# criacao de funcao
def coletar_votos():
"""
Função para acessar cada URL de votação nominal.
E coletar os votos, nome de deputado, partido e uf.
"""
# import CSV scraped with def definir_link_nominal()
... | StarcoderdataPython |
4855435 | def get_data():
return [
(519432,525806),
(632382,518061),
(78864,613712),
(466580,530130),
(780495,510032),
(525895,525320),
(15991,714883),
(960290,502358),
(760018,511029),
(166800,575487),
(210884,564478),
(555151,523163),
(681146,515199),
(563395,522587),
(738250,512126),
(923525,503780),
(595148... | StarcoderdataPython |
345148 | <reponame>pushpendradahiya/pegasus<gh_stars>0
# Copyright 2020 The PEGASUS Authors..
#
# 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 |
12808379 | from base64 import b64decode, b64encode
from json import dumps
from aiohttp import web
from service.handler import LweHandler
from service.rlwe import RLWE
from service.db import DB
db = DB()
algo = RLWE(16, 929)
handler = LweHandler(algo, DB())
app = web.Application()
app.add_routes([
web.get('/get_pub_key', ... | StarcoderdataPython |
306389 | # Palindrome Permutation
# Given a string, write a function to check if it is a permutation of a palindrome. A palindrome is a word or phrase that is the same forwards and backwards. A permutation is a rearrangement of letters. The palindrome does not need to be limited to just dictionary words. You can ignore cas... | StarcoderdataPython |
5114866 | from math import factorial
n, k = map(int, input().split())
coefficient = factorial(n) // (factorial(k) * factorial(n-k))
print(coefficient) | StarcoderdataPython |
6648835 | def gene_position(gff_file, get_dict=True):
"""Get the start and end position of each gene and determine their respective length.
Input is a .gff file downloaded from https://www.ensembl.org/Saccharomyces_cerevisiae/Info/Index
Output is a dictionary that includes all gene names as keys. The values are lists... | StarcoderdataPython |
9795004 | <filename>biopen_smoothing_model_code.py
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 21 12:44:21 2020
@author: Vishnu
"""
import glob
from skimage import io
from scipy import ndimage
import numpy as np
#Imports all images (glucose, buffer, and rhodamine for NAD(P)H and Fluo-4) into arrays
NADH_g_... | StarcoderdataPython |
6675454 | #
# Copyright 2021 Red Hat Inc.
# SPDX-License-Identifier: Apache-2.0
#
"""Test Cache of worker tasks currently running."""
import logging
from unittest.mock import patch
from django.core.cache import cache
from django.test.utils import override_settings
from masu.processor.worker_cache import WorkerCache
from masu.t... | StarcoderdataPython |
3511447 | '''
Some funcs to generate HTML visualizations.
Run from the folder you intend to save the HTML page so
the relative paths in the HTML file are correct and PIL can find the images on disk.
Requires local images, but should be pretty easy to set up an apache server (or whatev)
and host them as long as the relative paths... | StarcoderdataPython |
1755199 | #!/usr/bin/env python
import argparse
import time
import textwrap
import pytricia
from _pybgpstream import BGPStream, BGPRecord, BGPElem
import yaml
def main():
parser = argparse.ArgumentParser()
parser.formatter_class = argparse.RawDescriptionHelpFormatter
parser.description = textwrap.dedent('''\
... | StarcoderdataPython |
3558744 | <reponame>agustin380/book-rest-example<gh_stars>0
import click
from app.api import app
from app import settings
@click.group()
def cmds():
pass
@cmds.command()
@click.option('--port', default=5000, type=int,
help='Set server port')
@click.option('--host', default='0.0.0.0', type=str,
... | StarcoderdataPython |
11394193 | import datetime
import timestring
from flask import Blueprint, request, jsonify, abort, make_response
from ..models.meetup import Meetup
from ..models.user import User
from ..models.question import Question, Voting, Comment
from ..utils.base_vals import BaseValidation, token_required
from ..utils.question_vals import Q... | StarcoderdataPython |
3263140 | <filename>model/ksdkt.py
"""
DKT with the following expansions:
- Pre-training Regularizaiton
- Knowledge State Vector Loss
~~~~~
Author: <NAME> (@qqhann)
"""
import logging
import math
import os
import pickle
import random
import sys
import time
import warnings
from math import ceil, log
from pathlib import Path
from ... | StarcoderdataPython |
1917138 | import os
from pathlib import Path
from typing import Union
__all__ = ['PathType', 'path_lca', 'path_add_suffix']
PathType = Union[str, Path] # a union type for all possible paths
def path_lca(this: Path, other: PathType) -> Path:
r"""
Return the `lowest common ancestor <https://en.wikipedia.org/wiki/Lowes... | StarcoderdataPython |
5045213 | import qiniu
# 需要填写你的 Access Key 和 Secret Key
access_key = '<KEY>'
secret_key = '<KEY>'
# 内容空间的名称
bucket_name = "infonews"
# 上传文件
def upload_img(data):
q = qiniu.Auth(access_key, secret_key)
key = None # 上传文件名 不设置会自动生成随机名称
token = q.upload_token(bucket_name)
ret, info = qiniu.put_data(token, key, d... | StarcoderdataPython |
149723 | import pytest
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from catboost import CatBoostClassifier
from pydrift import DataDriftChecker, ModelDriftChecker, DriftCheckerEstimator
from pydrift.exceptions import (ColumnsNotMatchException,
... | StarcoderdataPython |
341910 | data1 = "10" # String
data2 = 5 # Int
data3 = 5.23 # Float
data4 = False # Bool
print(data1)
print(data2)
print(data3)
print(data4) | StarcoderdataPython |
4993389 | <reponame>Naoyg/HomeCredit
"""
変数選択
"""
from pathlib import Path
import hydra
import pandas as pd
from sklearn.feature_selection import SequentialFeatureSelector
from sklearn.linear_model import LogisticRegression
REPO = Path(__file__).resolve().parents[2]
col_idx = "SK_ID_CURR"
col_target = "TARGET"
def load_data... | StarcoderdataPython |
390842 | <filename>test/integration/smoke/test_router_dhcphosts.py
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Ap... | StarcoderdataPython |
201414 | while True:
n = int(input())
if n == 0: break
l = 1
o = '+'
while l <= n:
v = l
c = 1
while c <= n:
if c != n: print('{:>3}'.format(v), end=' ')
else:
print('{:>3}'.format(v))
o = '-'
if v == 1: o = '+'
... | StarcoderdataPython |
5077600 | import logging
import math
from pandas import DataFrame
from ..features.types import get_type_map_raw
from ..features.feature_metadata import R_INT, R_FLOAT, R_CATEGORY
logger = logging.getLogger(__name__)
# TODO: Documentation
def get_approximate_df_mem_usage(df: DataFrame, sample_ratio=0.2):
if sample_ratio... | StarcoderdataPython |
3264671 | <gh_stars>0
import numpy as np
import itertools as it
class SymbolicArray(np.ndarray):
def __new__(cls, arr, symbolic=None, **kwargs):
if isinstance(arr, cls):
return arr
arr = np.array(arr, copy=False, **kwargs)
obj = arr.view(cls)
obj.symbolic = str(symbolic or np.arr... | StarcoderdataPython |
1661213 | <reponame>IvanNardini/2-Engineering<filename>MachineLearningPlatforms/Kubeflow/applications/base/pipelines/conditionals/component.py
#!/usr/bin/env python3
# This is an example for testing conditions in Kubeflow
# Steps:
# 1 - Define functions
# 2 - Define lightweight python components
# 3 - Write the component to a f... | StarcoderdataPython |
6444967 | <gh_stars>0
import os
from cli import main_script
if __name__ == "__main__":
main_script()
| StarcoderdataPython |
5115947 | <gh_stars>1-10
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__docformat__ = 'restructuredtext en'
{% set cfg = salt['mc_utils.json_load'](cfg) %}
{% set data = cfg.data %}
{% set settings = cfg.data.settings %}
{% macro renderbool(opt)%}
{{opt}} = {%if data.get(opt, False)%}True{%else%}False{%endif%}
{% endmacro %}
im... | StarcoderdataPython |
6426711 | #Importing Libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
KPN = pd.read_csv('/Data/Code_Data/new_data.csv', usecols=[1,2,3,4,5
... | StarcoderdataPython |
11353248 | <filename>depricated/km.py
from __future__ import division
import numpy as np
from collections import defaultdict
import json
import itertools
from sklearn import cluster, preprocessing, manifold
from datetime import datetime
import sys
class KeplerMapper(object):
def __init__(
self,
cluster_algor... | StarcoderdataPython |
11249132 | from .activity import Activity | StarcoderdataPython |
9611930 | import time
import json
import requests
from binance.client import Client
with open('keys.json', 'r') as file:
keys = json.loads(file.read())['binance']
client = Client(keys['key'], keys['secret'])
rub = lambda: float(requests.get('https://blockchain.info/tobtc?currency=RUB&value=1000').text) / 1000
btc_to_rub =... | StarcoderdataPython |
1899462 | """
Core admin setup
"""
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.utils.translation import gettext_lazy as _
from core.forms import CustomUserCreationForm
from core.models import User, Post
@admin.register(User)
class UserCoreAdmin(UserAdmin):
fieldsets = (
(_('... | StarcoderdataPython |
1686930 | #! /usr/bin/env python
from enum import IntEnum
from aoc.intcode import IntCodeCPU, InterruptCode
from aoc.utils import load_input
class Color(IntEnum):
BLACK = 0
WHITE = 1
class Direction(IntEnum):
UP = 0
DOWN = 1
LEFT = 2
RIGHT = 3
class TurnDirection(IntEnum):
LEFT = 0
RIGHT = ... | StarcoderdataPython |
1667522 | <reponame>lorainemg/autogoal
from typing import List
from autogoal.experimental.metalearning.datasets import Dataset
from autogoal.experimental.metalearning.metalearner import MetaLearner
from autogoal.experimental.metalearning.distance_measures import cosine_measure, l2_distance, l1_distance
class NNMetaLearner(Meta... | StarcoderdataPython |
4878816 | load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
def enkit_deps():
excludes = native.existing_rules().keys()
if "io_bazel_rules_go" not in excludes:
http_archive(
name = "io_bazel_rules_go",
sha256 = "69de5c704a05ff37862f7e0f5534d4f479418afc21806c887db544a31... | StarcoderdataPython |
1867457 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'browserUi.ui'
#
# Created by: PyQt5 UI code generator 5.15.6
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import ... | StarcoderdataPython |
3456367 | <reponame>CodeButt3rs/CodeButt3rsBot
import datetime
import discord
import asyncio
import json
import random
import threading
from random import randrange
from discord_components.component import ButtonStyle
from discord_components import Button
from DatabaseTools import Database
from discord.ext import commands
from ... | StarcoderdataPython |
11295972 | import pytest
import pandas as pd
from calculator import Calculate
@pytest.mark.parametrize(
"test_input, expected",
[("3+5", {"elevator":[1]}),
("2+4", {"elevator":[]}),
("6*9", {"elevator":[]})
],
)
def test_eval(test_input, expected):
test_df = pd.DataFrame({"listing_id": [1], "desc_addi... | StarcoderdataPython |
1634184 | import asyncio
from copy import deepcopy
from dataclasses import dataclass
from importlib.resources import path
from subprocess import Popen
from typing import List, Optional
import google.protobuf
from multiaddr import Multiaddr
import hivemind.hivemind_cli as cli
import hivemind.p2p.p2p_daemon_bindings.p2pclient as... | StarcoderdataPython |
6673 | from rest_framework.response import Response
from rest_framework.decorators import api_view
from rest_framework.reverse import reverse
from rest_framework_simplejwt.tokens import RefreshToken
@api_view(['GET'])
def root(request, fmt=None):
return Response({
'v1': reverse('api_v1:root', request=request, fo... | StarcoderdataPython |
9647096 | # test_cmalpha.py
# <NAME>, April 2014
# Reference: Aircraft Dynamics: from Modeling to Simulation, by <NAME>
# ----------------------------------------------------------------------
# Imports
# ----------------------------------------------------------------------
import SUAVE
import numpy as np
from SUAVE.Methods.F... | StarcoderdataPython |
3422256 |
# -*- coding: utf-8 -*-
import pytest
import sys
from .test_base_class import TestBaseClass
from .as_status_codes import AerospikeStatus
from aerospike import exception as e
from aerospike import predicates as p
import time
aerospike = pytest.importorskip("aerospike")
try:
import aerospike
except:
print("Ple... | StarcoderdataPython |
12850404 | """
Constraint functions for grasp sampling
Author: <NAME>
"""
from abc import ABCMeta, abstractmethod
import numpy as np
class GraspConstraintFn(object):
"""
Abstract constraint functions for grasp sampling.
"""
__metaclass__ = ABCMeta
def __init__(self, config):
# set params
sel... | StarcoderdataPython |
4803003 | <reponame>tychen5/Audio_Tagging_Challenge
import os
import sys
import time
import math
import random
import pickle
import numpy as np
import pandas as pd
from keras.utils import to_categorical
# map_path = path of 'map.pkl'
map_path = sys.argv[1]
# base_path = directory of all the data (train_label.csv, X_train.npy)... | StarcoderdataPython |
12804648 | <filename>trpg_bot/trpg_bot.py
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import os
import re
import traceback
import discord
import redis
from logic import CommandInterpreterLogic, DropboxLogic, ModeSelectorLogic
if __name__ == '__main__':
TOKEN = os.environ['DISCORD_BOT_TOKEN']
REDIS = os.environ['REDIS_U... | StarcoderdataPython |
9740360 | import math
from fwk.metrics import Metric
from fwk.config import Config
class EpochCounter(Metric):
def __init__(self) -> None:
super().__init__()
self.epoch = None
self.total_epochs = None
def on_before_epoch(self, local_variables):
self.epoch = local_variables['epoch']
... | StarcoderdataPython |
8149729 | <gh_stars>100-1000
import time
import unittest
import torch
import numpy as np
import random
from functools import lru_cache
from models.diagonaled_mm_2d import diagonaled_mm2d, mask_invalid_locations
@lru_cache()
def get_2dmask(seq_len, nx, ny, w, d):
return torch.BoolTensor([
[
abs(i // ny -... | StarcoderdataPython |
1894446 | <reponame>gabriel-vitor/Python-projects
import sys
import random
import time
#Nesse primeiro projeto, o professor da disciplina não permitiu utilizar funçoes (modularizar o código), porque o assunto ainda não tinha sido dado.
#Sendo assim, esse projeto ficou muito extenso. Como a discplina era introdutória e eu era in... | StarcoderdataPython |
8076142 | __author__ = 'j'
import pandas as pd
FACTOR = 10
def convertCSV(filelists, factor):
allcsv = pd.DataFrame()
for i, file in enumerate(filelists):
a = pd.read_csv(file, header=1)
a.index = a[a.columns[0]]
a = pd.DataFrame(a[a.columns[4]])
a.columns = [str(i)]
if allcsv.e... | StarcoderdataPython |
4983595 | <filename>tests/test_forms.py
import pytest
from squall import File, Form, Squall, UploadFile
from squall.testclient import TestClient
app = Squall()
@app.post("/files/")
async def create_file(
file: UploadFile = File(...), fileb: UploadFile = File(...), token: str = Form(...)
):
file = await file.read()
... | StarcoderdataPython |
5087725 | import os
import re
import yaml
from yaml.loader import Reader, Scanner, Parser, Composer, SafeConstructor, Resolver
from glob import glob
from urllib.request import urlopen
from selectolax.parser import HTMLParser
# import for pdf to text
import io
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
... | StarcoderdataPython |
9756790 | <gh_stars>1-10
PRICES = {
1: 299,
3: 800,
6: 900,
12: 999
}
| StarcoderdataPython |
11341561 | import logging
import sys
import time
import datetime
import signal
from multiprocessing.managers import SyncManager
class AspineClient:
def __init__(self, host: str = "127.0.0.1", port: int = 5116, authkey: str = "123456", *args, **kwargs):
logging.debug(f"Start initializing client at {datetime.datetime... | StarcoderdataPython |
5041218 | <reponame>Ascend/modelzoo
# Copyright 2020 Huawei Technologies Co., Ltd
#
# Licensed under the BSD 3-Clause License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/BSD-3-Clause
#
# Unless required by appli... | StarcoderdataPython |
5138091 | <filename>epookman_gui/ui/widgets/mainWindow.py<gh_stars>1-10
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This file is part of epookman_gui.
# License: MIT, see the file "LICENCS" for details.
from PyQt5.QtCore import (QCoreApplication, QSize)
from PyQt5.QtWidgets import (QFrame, QHBoxLayout, QVBoxLayout, QWidget,... | StarcoderdataPython |
6513198 | #! /usr/bin/python
# coding=utf8
# gom.py -- Command line tool for managing a Github organization
# Originally from https://github.com/bertvv/github-org-mgmt
# conversion to python 3 by <NAME>
import sys
from .github_org import GithubOrganizationManager as OrgMgr
#
# Helper functions
#
def usage():
print("""
Us... | StarcoderdataPython |
3537091 | # Databricks CLI
# Copyright 2017 Databricks, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"), except
# that the use of services to which certain application programming
# interfaces (each, an "API") connect requires that the user first obtain
# a license for the use of the APIs from Databricks,... | StarcoderdataPython |
4896959 | <gh_stars>1-10
#!/usr/bin/env python3
#
# Copyright 2021 Graviti. Licensed under MIT License.
#
"""Utility classes."""
from .attr import AttrsMixin, attr, attr_base, camel, upper
from .common import EqMixin, MatrixType, common_loads, locked
from .deprecated import DefaultValueDeprecated, Deprecated, Disable, KwargsDe... | StarcoderdataPython |
9657121 | <gh_stars>10-100
"""Miniature script:
Takes a plaintext email and
* Truncates quotes nested past depth 2
* Removes Evan's signature (3 lines long)
* Runs it through Markdown
"""
import sys
from pathlib import Path
import markdown
signature_lines = 0
signature_found = False
content = ""
for line in sys.stdin:
if ... | StarcoderdataPython |
6641159 | <reponame>kapot65/python-df-tcp
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 12 11:18:05 2016
@author: chernov
"""
import os
import sys
import asyncio
main_dir = os.path.realpath(os.path.join(os.path.dirname(__file__), ".."))
if not main_dir in sys.path: sys.path.append(main_dir)
del main_dir... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.