id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
5123492 | ## -------------------------------------------------------------------------------------------------
## -- Project : MLPro - A Synoptic Framework for Standardized Machine Learning Tasks
## -- Package : mlpro.wrappers
## -- Module : pettingzoo.py
## ----------------------------------------------------------------------... | StarcoderdataPython |
8163566 | import zipfile, threading, time, os, platform
Clear_Screen = "cls" if (platform.system() == "Windows") else "clear"
def Main():
os.system(Clear_Screen)
Archive = str(input("What is the file name and extension of the ZIP archive? "))
if (os.path.isfile(Archive) == False):
NotExist(Item = "Archive")... | StarcoderdataPython |
6499970 | <gh_stars>0
#-----------------------------------------
# code forked from https://github.com/openautomation/ROS-GRBL
#
#-----------------------------------------
import serial
import time
import re
# motor driver for XYZ hardware
# Alex & Frank's gantry has the following convention:
# - X axis is perpendicular to the... | StarcoderdataPython |
3305805 | print any(i == 5 for i in xrange(10))
# TODO: move this back to nonzero_exceptions when it's working again:
class MyException(Exception):
pass
class C(object):
def __init__(self, x):
self.x = x
def __nonzero__(self):
raise MyException(self.x)
def __repr__(self):
return "<C %r>... | StarcoderdataPython |
6482070 | <gh_stars>100-1000
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Library that simulates a limit order book from data given by BmfBovespa and use
it to wrangle and clean the dataset used
@author: ucaiado
Created on 07/05/2016
"""
# import libraries
from bintrees import FastRBTree
import numpy as np
import pandas as pd... | StarcoderdataPython |
164409 | # Το προγραμμα προσομειωνει την ριψη ενος κερματος, 10 φορες και θα εμφανιζει
# αν είναι κορώνα ή γράμμα.
import random
def ektelesi():
x = 0
while x != 10:
tyxaios_arithmos()
x = x + 1
print()
print()
def tyxaios_arithmos():
arithmos = random.randint(1, 2)
... | StarcoderdataPython |
6529174 | import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import argparse
"""
Compare F1 Scores of the Fits vs NGram Length
"""
def compareFits(ax,df, fits, output, range, title=None, xaxis=None):
range = int(range) if range is not None else len(df)
for f in fits:
ll = df[df["Model Name... | StarcoderdataPython |
4975819 | <filename>batchrefresh/majorcollege2dict.py
import openpyxl
class majorcollege2dict:
def __init__(self,mappingpath):
self.mappingpath=mappingpath
#专业为key,学院为value
def major_college_mapping(self):
data = openpyxl.load_workbook(self.mappingpath)
sheet1 = data['sheet1']
print(... | StarcoderdataPython |
1915209 | import warnings
warnings.filterwarnings("ignore")
from nose.tools import assert_equal, assert_true
from nerds.models import BiLstmCrfNER
from nerds.utils import load_data_and_labels
import shutil
def test_bilstm_ner():
X, y = load_data_and_labels("nerds/test/data/example.iob")
model = BiLstmCrfNER(max_iter=... | StarcoderdataPython |
1857058 | from .Transport import Transport
from twitter_scraper import get_tweets, get_trends
class TWITTERparser(Transport):
def __init__(self):
self.articles = []
def get(self, tag, n=5, **params) -> list:
for tweet in get_tweets(tag, pages=n):
self.articles.append({'title': tweet['usern... | StarcoderdataPython |
4835835 | #!/usr/bin/env python3
# Copyright (c) 2019 The Bethel Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
from test_framework.test_framework import BethelTestFramework
from test_framework.staticr_util import *
class ... | StarcoderdataPython |
3309795 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# wrapper.py
#
# This file is part of the RoboEarth Cloud Engine framework.
#
# This file was originally created for RoboEearth
# http://www.roboearth.org/
#
# The research leading to these results has received funding from
# the European Union Sev... | StarcoderdataPython |
9718819 | <reponame>orisi/orisi
#### This module doesn't work after the signing procedure refactor. To be done
from basehandler import BaseHandler
from password_db import (
LockedPasswordTransaction,
RSAKeyPairs,
RightGuess,
SentPasswordTransaction)
from util import Util
import base64
import hashlib
import jso... | StarcoderdataPython |
204445 | #!/usr/bin/env python
import sys
from decimal import Decimal
import math
from datetime import datetime
from PyQt5 import QtWidgets
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QIcon
import gui_calculator
import resources
from data_manager import DataManager
def service_info(enable=0):
def w... | StarcoderdataPython |
4940538 | import pytest
import helpers
import mock
import builtins
import types
def test_game_input_returns_int():
with mock.patch.object(builtins, "input", lambda input_str: "22"):
expected_type = int
return_value = helpers.game_input("What is 11+11?", expected_type)
assert isinstance(
... | StarcoderdataPython |
1638165 | from icemet_sensor.laser import Laser
import psutil
import asyncio
import logging
import os
import subprocess as sp
class MyRIO(Laser):
def __init__(self, saku_laser_path="C:/SAKU Laser"):
self._pid = None
self._cmd = [os.path.join(saku_laser_path, "SAKU Laser.exe")]
async def on(self):
self._pid = sp.Pope... | StarcoderdataPython |
294249 | # **args
def save_user(**user):
print(user['name'])
#**user retorna um dict
save_user(id=1, name='admin') | StarcoderdataPython |
1821514 | <reponame>s3dawyXD/cli_code<filename>ztemp/cli_code/cli_doc_auto/pyreg/literal/cons.py<gh_stars>1-10
#!/usr/bin/env python
URL_CRTSH = 'https://crt.sh/?id={id}'
| StarcoderdataPython |
3366390 | import logging
logger = logging.getLogger("FETCH")
| StarcoderdataPython |
6476624 | # -*- coding: utf-8 -*-
# Generated by Django 2.1.7 on 2019-05-19 05:24
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('analytics', '0004_gildings'),
]
operations = [
migrations.AddField(
model_name='submission',
... | StarcoderdataPython |
3371408 | '''
RDA (Remote Data Access) client code to receive data from the Brain Products
BrainVision Recorder.
'''
import time
import numpy as np
from struct import *
from socket import *
import array
from scipy.signal import butter, lfilter
import numpy as np
import matplotlib.pyplot as plt
#import math
# from riglib.filter ... | StarcoderdataPython |
265352 | import pytest
from pytest import approx
from math import nan
import pymap3d.los as los
lla0 = (42, -82, 200)
@pytest.mark.parametrize(
"az,tilt,lat,lon,sr",
[
(0, 0, 10, -20, 1e3),
(0, 90, nan, nan, nan),
(0, 45, 10.009041667, -20, 1.41432515e3),
(45, 45, 10.00639336, -19.9... | StarcoderdataPython |
6701354 | from typing import List
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def constructMaximumBinaryTree(self, nums: List[int]) -> TreeNode:
if not nums:
return None
maxIdx = self.findMaxIndex(nums... | StarcoderdataPython |
3521454 | <reponame>raunak-r/network-monitoring-tool
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
# username - admin
# p/w - administrator
# Create your models here.
class LabReport(models.Model):
clientIP = models.CharField(max_length = 15, primary_key = True)
clientName = mo... | StarcoderdataPython |
301348 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
一些常用函数
"""
import numpy as np
import pyaudio
import wave
import librosa
Punctuation_Ascii_Set = {
'.',
',',
'?',
'!',
'"',
"'",
':',
';',
'(',
')',
'[',
']',
'{',
'}'
}
Punctuation_Unicode_Set = {
'。',... | StarcoderdataPython |
1658962 | """ MARKDOWN
---
YamlDesc: CONTENT-ARTICLE
Title: python lambda Map Filter Reduce
MetaDescription: python lambda, Map, Filter, Reduce, code, tutorials
MetaKeywords: python lambda, Map, Filter, Reduce, code, tutorials
Author: Hemaxi
ContentName: python-lambda
---
MARKDOWN """
""" MARKDOWN
# Python Lambda Expressions
* ... | StarcoderdataPython |
4877288 | import turtle
import random
tt = turtle.Turtle()
tt.speed(0)
tt.color('blue')
for _ in range(random.randint(1, 100)):
tt.forward(random.randint(0, 50))
tt.setheading(random.randint(0, 360))
turtle.done()
| StarcoderdataPython |
1932098 | #!/usr/bin/python3
#
# This file is part of Magnum.
#
# Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019
# <NAME> <<EMAIL>>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
... | StarcoderdataPython |
160872 | import os
import math
import requests
import json
import datetime
import hashlib
from pygdpr.models.dpa import DPA
from bs4 import BeautifulSoup
from pygdpr.services.filename_from_path_service import filename_from_path_service
from pygdpr.services.pdf_to_text_service import PDFToTextService
from pygdpr.specifications i... | StarcoderdataPython |
4864231 | __all__=['misc','data_utils','training','prediction']
from rhced.training import *
from rhced.data_utils import *
from rhced.misc import *
from rhced.prediction import * | StarcoderdataPython |
3464212 | <filename>utils.py
import tqdm
def ngrams(s, r, pad=False):
"""
Takes a list as input and returns all n-grams up to a certain range.
:param s: input list
:param r: range
:param pad: whether to return ngrams containing a "PAD" token
:return: dicttionary {id: ngram}
"""
# add padding
... | StarcoderdataPython |
169883 | <filename>settings.py
# -*- coding: utf-8 -*-
# Copyright (c) 2009, <NAME> <<EMAIL>>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE... | StarcoderdataPython |
1973370 | from tkinter import messagebox
from tree import *
from app import *
app = Application()
tree = BinaryTree()
def traceRoute(node):
route = []
while node is not None:
route.append(node)
node = node.getParent()
return route
def drawRoute(route):
if len(route) == 0:
return
n... | StarcoderdataPython |
11248229 | <filename>fastscape/models/__init__.py
from ._models import (basic_model,
bootstrap_model,
marine_model,
sediment_model)
| StarcoderdataPython |
243818 | from members import Student, Faculty, Member
class Member(Member):
""" Adding __repr__ to Member
>>> joe = Member('<NAME>', '1 Guitar Ave', '<EMAIL>')
>>> joe
Member('<NAME>', '1 Guitar Ave', '<EMAIL>')
>>> [joe]
[Member('<NAME>', '1 Guitar Ave', '<EMAIL>')]
"""
def __repr__(self) ... | StarcoderdataPython |
380640 | import numpy as np
import math
extraNumber = 4 * math.pi * pow(10,-7)
def getNumberCharge():
y1 = input("Input first y: ")
y1 = float(y1)
y2 = input("Input second y: ")
y2 = float(y2)
y3 = input("Input third y: ")
y3 = float(y3)
I1 = input("Input amps one: ")
I1 = float(I1)
I2 = i... | StarcoderdataPython |
4824604 | # MIT License
#
# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020
#
# 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
# r... | StarcoderdataPython |
9716619 | from ResponseGiver import response
import praw
import creds
reddit = praw.Reddit(client_id=creds.CLIENT_ID, client_secret=creds.CLIENT_SECRET,
username=creds.USERNAME, password=<PASSWORD>.PASSWORD, user_agent="realhardik18isgod")
c = 0
for comment in reddit.submission(id='tojzt0').comments:
pr... | StarcoderdataPython |
235125 | import unittest
from unittest.mock import Mock, patch
from spresso.controller.grant.authentication.forward import ProxyHandler
from spresso.controller.grant.authentication.config.forward import \
Forward
class ForwardAuthenticationGrantTestCase(unittest.TestCase):
@patch("spresso.controller.grant.authenticat... | StarcoderdataPython |
11369182 | <reponame>romajs/todo_app<filename>todo/commandline.py
import click, os, sys
cmd_folder = os.path.abspath(os.path.join(os.path.dirname(__file__), 'cli'))
class TodoCLI(click.MultiCommand):
def list_commands(self, ctx):
rv = []
for filename in os.listdir(cmd_folder):
if filename.ends... | StarcoderdataPython |
4856009 | <reponame>pwang00/PrivacyRaven
from contextlib import suppress
import matplotlib.pyplot as plt
import numpy as np
import pytorch_lightning as pl
import torch
from art.estimators.classification import BlackBoxClassifier
from torch.utils.data import Dataset
def set_evasion_model(query, victim_input_shape, victim_input... | StarcoderdataPython |
9768147 | <gh_stars>1-10
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
from . import views
urlpatterns = [
path('', views.index_view, name='index'),
path('register', views.register_view, name='register'),
path('login', views.login_view, name='login'),
pa... | StarcoderdataPython |
284483 | from __future__ import annotations
import numpy as np
import numpy.random as npr
import arlunio as ar
from .data import Rays
from .data import ScatterPoint
from arlunio.color import getcolorf
def random_unit_sphere(n):
a = npr.rand(n) * 2 * np.pi
z = (npr.rand(n) * 2) - 1
r = np.sqrt(1 - (z * z))
r... | StarcoderdataPython |
1670457 | from model.model import captcha_model, model_conv, model_resnet
from data.datamodule import captcha_dm
from utils.arg_parsers import test_arg_parser
import pytorch_lightning as pl
def test(args):
dm = captcha_dm()
model = captcha_model.load_from_checkpoint(args.ckpt, model=model_resnet())
tb_logger = pl.lo... | StarcoderdataPython |
3562697 | <gh_stars>1-10
import os
import yaml
import json
import stat
import certifi
import urllib3
import sys
from traceback import print_exc
import io
import random
import codecs
#############################################
import chess
from chess.variant import find_variant
from chess.pgn import read_game
from cbuild.book... | StarcoderdataPython |
59893 | DATABASE_URI = "postgresql://amoveo:password@localhost:5432/amoveo-explorer"
NODE_INT_URL = "http://localhost:8081"
NODE_EXT_URL = "http://localhost:8080"
try:
from service.settings_local import *
except ImportError:
pass
| StarcoderdataPython |
8072952 | #!/usr/bin/env python
'''
Small script to find most optimal Pokemon team for original 150 Pokemon.
'''
import requests
POKEAPI_URL = 'https://pokeapi.co/api/v2'
def getPokemon():
'''
Generates list of tuples of pokemon names and their types
'''
pokemon = []
for index in range(1, 251):
poke... | StarcoderdataPython |
5030843 | """
Module for working with Sentinel Hub OGC services
"""
import logging
import datetime
from base64 import b64encode
from urllib.parse import urlencode
from shapely.geometry import shape as geo_shape
from .time_utils import get_current_date, parse_time
from .download import DownloadRequest, get_json
from .constants... | StarcoderdataPython |
1988323 | phrase = str(input('Enter a phrase: '))
word = str(input('enter the word you want to count: '))
def count_word_in_phrase(phrase, word):
words = phrase.lower().split()
count = 0
for wd in words:
if wd == word.lower(): count += 1
return count
print(count_word_in_phrase(phrase, word))
| StarcoderdataPython |
1958921 | import os
from azureml.core.conda_dependencies import CondaDependencies
from azureml.core.runconfig import DEFAULT_CPU_IMAGE
from azureml.pipeline.steps import PythonScriptStep
from azureml.core.runconfig import RunConfiguration
from azureml.pipeline.core import PipelineData
from azureml.pipeline.core import PipelinePa... | StarcoderdataPython |
11280499 | from __future__ import print_function, division, absolute_import
import subprocess
import pytest
import numpy as np
from .common import *
from constants import *
from path_planning.bezier_curve import demo_cp, calcBezierPath
from path_planning.stanley_controller import normalizeAngle
def testStanleyControlDemo():
... | StarcoderdataPython |
4989636 | <reponame>rgebhart/nanoBALLS<filename>setup.py
"""A setuptools based setup module.
See:
https://packaging.python.org/en/latest/distributing.html
https://github.com/pypa/sampleproject
"""
from setuptools import setup, find_packages
from os import path
from io import open
here = path.abspath(path.dirname(__file__))
w... | StarcoderdataPython |
6561640 | # criar uma classe dos exemplos de cachorro
class Cachorro:
def __init__(self, nome_e, peso_e, altura_e, raca_e):
#add atributos
self.nome = nome_e
self.peso = peso_e
self.altura = altura_e
self.raca = raca_e
#definir os metodos
def Anda(self):
print(" O cach... | StarcoderdataPython |
12804281 | # Solution by : <NAME>
print(int(input())+1) | StarcoderdataPython |
4810299 | <filename>task2.py
#!/usr/bin/python3
# encoding='utf-8'
# @time:2021/9/15 10:51
# 猜数字
import random
# 初始资金
capital = 500
count = 0
input_num = input("请输入一个0-20的整数:")
# 产生随机数
def suiji():
guess1 = random.randint(0, 20)
# 显示随机数
# print(guess1)
return guess1
# 判断输入是否为数字
def isnum(num):
while Tru... | StarcoderdataPython |
9664373 | <gh_stars>0
import json
import logging
import time
import pandas as pd
from io import StringIO
from sdc_etl_libs.api_helpers.API import API
from sdc_etl_libs.sdc_dataframe.Dataframe import Dataframe, SDCDFTypes
from sdc_etl_libs.sdc_file_helpers.SDCFileHelpers import SDCFileHelpers
logging.basicConfig(level=logging.I... | StarcoderdataPython |
3244148 | import os
import pytest
from leapp.exceptions import StopActorExecution, StopActorExecutionError
from leapp.libraries.actor import library
from leapp import reporting
from leapp.libraries.common.testutils import produce_mocked, create_report_mocked
from leapp.libraries.stdlib import api
from leapp.models import OSRel... | StarcoderdataPython |
6443005 | <reponame>tapiaw38/coeadmin
""" Profile Model """
# Django.
from django.db import models
# Utilities
from coeadmin.utils.models import BaseModel
# Create your models here.
class Profile(BaseModel):
"""
User profile model.
Public profile of each user.
"""
user = models.OneToOneField(
'u... | StarcoderdataPython |
187182 | <reponame>JamesOBenson/speedtest
#pip3 install speedtest-cli
import os, platform
from time import gmtime, strftime
from subprocess import call
import os.path
host = "8.8.8.8"
def check_ping():
times=strftime("%Y-%m-%d %H:%M:%S", gmtime())
response = os.system("ping " + ("-n 1 " if platform.system().lower()=... | StarcoderdataPython |
3321158 | <reponame>Worteks/OrangeAssassin
"""Tests for pad.plugins.image_info."""
import unittest
from tests.util.image_utils import new_email, new_image, new_image_string
try:
from unittest.mock import patch, Mock, MagicMock, call
except ImportError:
from mock import patch, Mock, MagicMock, call
import oa.plugins
fro... | StarcoderdataPython |
6562660 | """
Command: Remix
"""
from argparse import _SubParsersAction, Namespace
from dolbyio_rest_apis.communications import remix
import json
def command_name() -> str:
return 'remix'
def add_arguments(sub_parsers: _SubParsersAction) -> None:
parser = sub_parsers.add_parser(command_name(), help='Remix')
parse... | StarcoderdataPython |
6500672 | <reponame>caputomarcos/tuiuiu.io
from __future__ import absolute_import, unicode_literals
from django.apps import AppConfig
class SearchpromotionsAppConfig(AppConfig):
name = 'tuiuiu.contrib.searchpromotions'
label = 'searchpromotions'
verbose_name = "Tuiuiu search promotions"
| StarcoderdataPython |
11232247 | # -*- coding: utf-8 -*-
"""
Created on Tue Feb 24 08:23:34 2015
@author: Jared
"""
from collections import defaultdict
from datetime import date
import datetime
from dateutil.rrule import rrule, DAILY
import psycopg2
from psycopg2.pool import ThreadedConnectionPool
from psycopg2.extensions import ISOLATION_LEVEL_AUTO... | StarcoderdataPython |
1778486 | import asyncio
import random
from utilities import *
async def twinkle(lights):
background_color = rgb(32, 32, 255)
twinkle_colors = [pretty, warm_white, blue_snowy, good_purple]
for light in lights:
light.set_state(background_color)
states = [None for light in lights]
time_step = 0.1
... | StarcoderdataPython |
3355170 | from flask import Flask
from flaskext.mysql import MySQL
from web import app
#app = Flask(__name__)
#mysql = MySQL()
#app.config['MYSQL_DATABASE_USER'] = 'admin'
#app.config['MYSQL_DATABASE_PASSWORD'] = '<PASSWORD>'
#app.config['MYSQL_DATABASE_HOST'] = 'csgo1m.cj3rigewkoph.us-east-2.rds.amazonaws.com'
#app.config['MY... | StarcoderdataPython |
11279137 | import unittest
import sys
import json
import psutil
from unittest.mock import MagicMock, patch
# Include src directory for imports
sys.path.append('../')
from daemon.src.system_report import DaemonChecker
class TestDaemonCheckerClass(unittest.TestCase):
test_config_path = '/test/config.json'
@classmeth... | StarcoderdataPython |
1628205 | <gh_stars>10-100
# Copyright (c) ASAPP Inc.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import torch
import torch.nn as nn
import torch.nn.functional as F
from fairseq.modules.gelu import gelu, gelu_accurate
@torch.jit.script
def swish... | StarcoderdataPython |
8159808 | from .early_stopper import early_stopper
from .hidden_layers import hidden_layers
from .normalizers import lr_normalizer
| StarcoderdataPython |
5183066 | <filename>src/day04/day04.py
from src.day04.Log import Log
def task2(g):
_guards = list(map(lambda x: x[2], g))
data = list(
map(lambda x: (x.number, x.most_frequent_sleep_minute, x.minutes[x.most_frequent_sleep_minute]), _guards))
data.sort(key=lambda x: x[2], reverse=True)
return data[0][0] ... | StarcoderdataPython |
11372329 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
" Edit distance: module for calculating levenshtein distance and hamming distance "
import time
import random
import Levenshtein
__author__ = "<NAME>"
debug = False
def levenshtein_recur(a, b):
if not a:
return len(b)
if not b:
return len(a)
... | StarcoderdataPython |
8068028 | from datetime import timedelta, date, datetime
from typing import Optional
from tortoise import fields
from tortoise.models import Model
from tortoise.exceptions import DoesNotExist
from app.enum import *
from app.errors import TortDateFieldException
class FieldMixin:
@classmethod
def model_fields(cls):
... | StarcoderdataPython |
6701335 | """gsi_audit_event.py: These tests validate auditing of events for GSI
__author__ = "<NAME>"
__maintainer = "<NAME>"
__email__ = "<EMAIL>"
__git_user__ = "hrajput89"
__created_on__ = "08/17/20 12:31 pm"
"""
from remote.remote_util import RemoteMachineShellConnection
from security.rbac_base import RbacBase
from securi... | StarcoderdataPython |
6475437 | import csv
import cv2
import numpy as np
import os
import numpy as np
import keras
import socketio
from PIL import Image
from keras.models import Sequential
from keras.layers import Flatten, Dense, Lambda
from keras.layers.core import Dense, Activation, Flatten, Dropout
from keras.layers import Cropping2D
from keras.l... | StarcoderdataPython |
4800863 | """Drop registration date column
Revision ID: 1100
Revises: 1090
Create Date: 2018-03-05 13:36:36.395640
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = '1100'
down_revision = '1090'
def upgrade():
op.drop_column... | StarcoderdataPython |
283052 | <gh_stars>10-100
import time
import mock
from unittest import TestCase
from hacheck import cache
se = mock.sentinel
class CacheTestCase(TestCase):
def setUp(self):
cache.configure()
def test_expiry(self):
with mock.patch.object(cache, 'has_expired', return_value=False) as m:
ca... | StarcoderdataPython |
12847677 | <gh_stars>0
# Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# unless required by applica... | StarcoderdataPython |
8062951 | def qsort(L):
return (qsort([y for y in L[1:] if y < L[0]]) +
L[:1] +
qsort([y for y in L[1:] if y >= L[0]])) if len(L) > 1 else L
| StarcoderdataPython |
1601208 | # BOJ 11052
import sys
input = sys.stdin.readline
def solve(n):
for i in range(2, n + 1):
d[i] = packs[i - 1]
for j in range(i):
d[i] = max(d[i], d[i - j] + d[j])
return d[n]
n = int(input())
packs = list(map(int, input().split()))
d = [0] * (n + 1)
d[1] = packs[0]
print(solve(n... | StarcoderdataPython |
3496927 | <gh_stars>0
# Generated by Django 3.0.9 on 2020-09-01 12:19
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main', '0002_auto_20200901_1207'),
]
operations = [
migrations.AlterModelOptions(
name='category',
optio... | StarcoderdataPython |
5001299 | <filename>webpage/preprocess.py
#%% Preprocess Data for Model Prediction
import pickle
import numpy as np
import pandas as pd
import scipy
from sklearn.preprocessing import normalize
# Utils for conversion of different sources into numpy array
def toNumpyArray(data):
data_type = type(data)
if data_type == np.... | StarcoderdataPython |
37637 | <reponame>Teosidonio/Data_Solution<gh_stars>0
# Generated by Django 3.1 on 2020-12-28 14:16
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('environments', '0002_auto_20201228_1548'),
]
operations = [
migrations.AlterModelOptions(
na... | StarcoderdataPython |
11282189 | <reponame>sayerhs/py-exawind
# -*- coding: utf-8 -*-
# pylint: disable=missing-docstring
from pathlib import Path
from exawind.prelude import utils
def test_ensure_directory(tmpdir):
tstdir = tmpdir.mkdir("test_case")
cname = str(tstdir)
newdir = utils.ensure_dir(Path(cname) / "test_dir")
assert newdi... | StarcoderdataPython |
5195343 | import bw2data as bd
import bw2calc as bc
import bw2io as bi
from pypardiso import spsolve
import numpy as np
from pathlib import Path
import json
from consumption_model_ch.strategies.allocation import modify_exchanges
dirpath = Path(__file__).parent.resolve() / "data"
class exiobaseLCA:
def __init__(
... | StarcoderdataPython |
6651353 | <reponame>BigOto2/BlenderRenderDNS<filename>Render2018/lib/geo2ply-OLD.py
import numpy as np
def convgeo2ply(verts, tris, output_path_ply, vcolors=False):
# Determine if vcolors in use
if not type(vcolors) == type(True):
color_on = True
else:
color_on = False
with open(output_path_ply... | StarcoderdataPython |
3248071 | import numpy as np
import cv2
image_list = []
for i in range(198,203):
num = i
print(i)
org_image = cv2.imread('./../OCT_image/1026_with_glass_bead_before_irradiation/Filename_%04d.png'%(num), cv2.IMREAD_GRAYSCALE)[::2,::2]
image = np.array(org_image)
cv2.imshow('org_image', image)
# cv2.wai... | StarcoderdataPython |
4831771 | <filename>test/test_fifo_speculative.py<gh_stars>10-100
import unittest
import itertools
from myhdl import *
from myhdl_lib.fifo_speculative import fifo_speculative
from myhdl_lib import sfifo_beh
import myhdl_lib.simulation as sim
class TestSFifo(unittest.TestCase):
COMMIT = 0
DISCARD = 1
DISCARD_COMMI... | StarcoderdataPython |
3418952 | <reponame>AlessioVallero/algorithms-coursera
# Shuffling a linked list. Given a singly-linked list containing n items, rearrange the items uniformly at random.
# Your algorithm should consume a logarithmic (or constant) amount of extra memory and
# run in time proportional to nlogn in the worst case.
import time
impor... | StarcoderdataPython |
3224738 | <gh_stars>1-10
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Collection of tests for :mod:`orion.core.worker.producer`."""
import copy
import datetime
import pytest
from orion.core.worker.producer import Producer
from orion.core.worker.trial import Trial
class DumbParallelStrategy:
"""Mock object for paralle... | StarcoderdataPython |
1950616 | <gh_stars>1-10
import unittest
import torch
from ..train import train
class Test(unittest.TestCase):
def test_four_hot(self):
test = [
(1.0, -0.2, 2, 2),
(1.0, 1.0, 2, 2),
(1.0, 0.0, 2, 2),
(1.0, -1.0, 2, 2),
(-1.0, -1.0, 2, 2),
(0,... | StarcoderdataPython |
9771783 | from beamngpy import Vehicle, BeamNGpy
from self_driving.beamng_brewer import BeamNGCamera
from self_driving.decal_road import DecalRoad
from self_driving.oob_monitor import OutOfBoundsMonitor
from self_driving.road_polygon import RoadPolygon
from self_driving.simulation_data import SimulationParams, SimulationDataReco... | StarcoderdataPython |
8091980 | """
DATAONE adapter for BCO-DMO
metadata URL:
Taken from contentUrl item in the top-level encoding map of the SO.
lastModified:
Taken from the sitemap, but also available in the SO in the dateModified
element of the top-level encoding map.
PID (record version):
Given by the URL of the landing page.
SID... | StarcoderdataPython |
4886054 | <gh_stars>0
import arrow
from pylaas_core.abstract.abstract_service_unit_test import AbstractServiceUnitTest
from pylaas.technical.date import Date
class TestDate(AbstractServiceUnitTest):
"""Test Lib Date Suite"""
_service_id = 'date'
def s(self):
"""
return date service from contai... | StarcoderdataPython |
11253652 | import boto3
import json
session = boto3.Session(profile_name='cmsFronts')
s3 = session.resource('s3')
bucket = s3.Bucket('facia-tool-store')
configPath = 'PROD/frontsapi/config/config.json'
fileName = 'config.json'
def run():
'''
Finds all collections which are platform specific and share a
collection wi... | StarcoderdataPython |
1632673 | <gh_stars>1-10
import boto3
from botocore.exceptions import ClientError
import json
import os
import datetime
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import logging
logger = logging.getLogger()
if os.environ['DEBUG'] == "Tr... | StarcoderdataPython |
12865005 | # -* coding: utf-8 -*
"""
This module generate the Julia interface declaration for the functions it
finds in a C header. It only handle edge cases for the chemfiles.h header.
"""
from generate.julia.constants import BEGINING
from generate.julia.convert import type_to_julia
from generate import CHFL_TYPES
TYPE_TEMPLA... | StarcoderdataPython |
4965145 | from .node import Node
__all__ = {'Node'}
| StarcoderdataPython |
6684256 | # run in command line
# python index.py
from datetime import datetime
import time
print 'Before - ' + datetime.now().strftime("%Y-%m-%d %H:%M:%S")
time.sleep(2)
print 'After - ' + datetime.now().strftime("%Y-%m-%d %H:%M:%S")
| StarcoderdataPython |
3219785 | """Web API functions."""
import logging
import struct
import shutil
from pathlib import Path
from typing import Iterable, List
import requests
from dacite import from_dict
from nozomi.data import Post
from nozomi.exceptions import InvalidTagFormat, InvalidUrlFormat
from nozomi.helpers import sanitize_tag, create_tag... | StarcoderdataPython |
1809534 | <gh_stars>0
##########################################################################
# If not stated otherwise in this file or this component's Licenses.txt
# file the following copyright and licenses apply:
#
# Copyright 2018 RDK Management
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you ma... | StarcoderdataPython |
9764409 | from __future__ import annotations
import configparser
import datetime
import json
import logging
import os
import time
import uuid
import abc
#@ TODO put_parameter should be activated only is current value is different then the existing one
#@ TODO perf activation will reload SSM if needed and refresh API table
fr... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.