id stringlengths 2 8 | text stringlengths 16 264k | dataset_id stringclasses 1
value |
|---|---|---|
340193 | <filename>pizza_store/enums/__init__.py
from pizza_store.enums.permissions import CategoryPermission, ProductPermission
from pizza_store.enums.role import Role
__all__ = ["CategoryPermission", "ProductPermission", "Role"]
| StarcoderdataPython |
6425483 | <filename>course1/week2/quiz2/PredictingHousePrices.py
# coding: utf-8
# #Fire up graphlab create
# In[35]:
import graphlab
# #Load some house sales data
#
# Dataset is from house sales in King County, the region where the city of Seattle, WA is located.
# In[36]:
sales = graphlab.SFrame('home_data.gl/')
# I... | StarcoderdataPython |
3342306 | import csv
import logging
import json
import math
import random
import re
import time
import urllib.request
from pathlib import Path
import sys
import pandas as pd
import get_edgar.common.my_csv as mc
logger = logging.getLogger(__name__)
EDGAR_PREFIX = "https://www.sec.gov/Archives/"
SEC_PREFIX = "https://www.sec.go... | StarcoderdataPython |
4925683 | from src.api_server import APIServer
import threading
import time
#The Scheduler is a control loop that checks for any pods that have been created
#but not yet deployed, found in the etcd pendingPodList.
#It transfers Pod objects from the pendingPodList to the runningPodList and creates an EndPoint object to store in ... | StarcoderdataPython |
71344 | <reponame>lsteffenel/dask-tutorial
## verbose version
delayed_read_csv = delayed(pd.read_csv)
a = delayed_read_csv(filenames[0])
b = delayed_read_csv(filenames[1])
c = delayed_read_csv(filenames[2])
delayed_len = delayed(len)
na = delayed_len(a)
nb = delayed_len(b)
nc = delayed_len(c)
delayed_sum = delayed(sum)
tota... | StarcoderdataPython |
17378 | #!/usr/bin/python
#-*-coding:utf-8-*-
import json
import sys
import time
# TBD: auto discovery
# data_path = "/proc/fs/lustre/llite/nvmefs-ffff883f8a4f2800/stats"
data_path = "/proc/fs/lustre/lmv/shnvme3-clilmv-ffff8859d3e2d000/md_stats"
# use a dic1/dic2 to hold sampling data
def load_data(dic):
# Open file ... | StarcoderdataPython |
11267071 | # -----------------------------------------------------------------------------
# pytermor [ANSI formatted terminal output toolset]
# (C) 2022 <NAME> <<EMAIL>>
# -----------------------------------------------------------------------------
import unittest
from datetime import timedelta
from pytermor import format_time... | StarcoderdataPython |
11311046 | import sys
class ImageGen:
"""
Handles the construction of the ASCII art
rectangles that represent what software,
styles and influences should be used
for the next project.
"""
def __init__(self, typeface='#'):
self.typeface = typeface
def software(self, ident=''):
imag... | StarcoderdataPython |
9785014 | # coding: utf-8
# (C) Copyright IBM Corp. 2019, 2020.
#
# 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 la... | StarcoderdataPython |
11375766 | <gh_stars>1-10
from typing import List, Dict, Any, Callable, Union, Tuple, Optional
from multiprocessing.connection import Connection
from functools import partial
import multiprocessing
import textwrap
import gym
import numpy as np
import torch
import torch.nn as nn
from regym.rl_algorithms.replay_buffers import Sto... | StarcoderdataPython |
1942774 | <filename>testbed/scripts/calculate_algorand_throughput.py
#!/usr/local/bin/python3
import sys
import math
block_size = int(sys.argv[1])
size_in_txns = int(block_size / 100000 * 429)
deadline = int(size_in_txns / 3521 * 250)
print("Actual block size: {} txns, deadline: {} ms".format(size_in_txns, deadline))
| StarcoderdataPython |
1781288 | from django.contrib import admin
from .models import ImageModel
# Register your models here.
admin.site.register(ImageModel)
| StarcoderdataPython |
11367390 | <filename>pinocchio/decorator.py
"""
decorator extension for 'nose'.
Allows you to decorate functions, classes, and methods with attributes
without modifying the actual source code. Particularly useful in
conjunction with the 'attrib' extension package.
"""
import sys
err = sys.stderr
import logging
import os
from ... | StarcoderdataPython |
3279424 | <reponame>GreyElaina/TransQualityControl
#!/usr/bin/python3
import src.branch_error_check.branch_main
import src.duplicate_key_check.duplicate_main
import src.format_char_check.format_main
if __name__ == '__main__':
branch_json = src.branch_error_check.branch_main.branch_check('./project/assets')
duplicate_jso... | StarcoderdataPython |
9627303 | <reponame>therealAJ/CoachMe<filename>server/server.py
from flask import Flask, request, render_template
from predict import makeprediction, makegridprediction
app = Flask(__name__)
@app.route('/')
def home():
return render_template('home.html')
@app.route('/prediction', methods=["POST"])
def startPrediction():
... | StarcoderdataPython |
3465941 | <filename>model/models.py
import torch.nn as nn
import torch.nn.functional as F
from torchvision import models
class CRNet(nn.Module):
"""
definition of CRNet
"""
def __init__(self):
super(CRNet, self).__init__()
self.meta = {'mean': [131.45376586914062, 103.98748016357422, 91.4623489... | StarcoderdataPython |
3275459 | <gh_stars>0
#!/usr/bin/env python
#
# rm_pycache.py
#
from __future__ import print_function
import argparse
import os
import sys
import re
import shutil
class CleanPyCacheApp(object):
def __init__(self):
self._verbose = True
def main(self):
python_dirs = self._parse_command_line(sys.argv[1:... | StarcoderdataPython |
3229323 | from openbabel import OBMol, OBConversion
def convert_str(str_data, in_format, out_format):
mol = OBMol()
conv = OBConversion()
conv.SetInFormat(in_format)
conv.SetOutFormat(out_format)
conv.ReadString(mol, str_data)
return (conv.WriteString(mol), conv.GetOutFormat().GetMIMEType())
def to_inc... | StarcoderdataPython |
11277475 | from .constants import config, Ingredient
from pyrebase import pyrebase
from .database import Database
from psycopg2 import Error
firebase = pyrebase.initialize_app(config)
db = firebase.database() # Get a reference to the database service
class BagOfIngredients:
"""
BagOfIngredient class. Creates a BagOfIn... | StarcoderdataPython |
18243 | <reponame>esgomezm/spec-bioimage-io
import shutil
import traceback
from pathlib import Path
from pprint import pprint
from typing import List, Optional, Union
from marshmallow import ValidationError
from bioimageio.spec import export_resource_package, load_raw_resource_description
from bioimageio.spec.shared.raw_node... | StarcoderdataPython |
5101267 | <filename>utils/jenkinshelper.py
'''
helper functions for jenkins automatic processes
'''
import datetime
import os
import ssl
import requests
from blazarclient import exception as blazarexception
import chi
from croniter import croniter
from dateutil import tz
import json
import traceback
from urllib import parse as... | StarcoderdataPython |
316596 | import pywikibot, re, os, requests, json
from datetime import date, datetime, timedelta
#from customFuncs import basic_petscan
site = pywikibot.Site("lv", "wikipedia")
site.login()
site.get_tokens('edit')
def do_api_req(wikipedia,title,cont=''):
params = {
"action": "query",
"format": "json",
"prop... | StarcoderdataPython |
9628825 | from django.db import models
from django_analyses.models.input.definitions.input_definitions import \
InputDefinitions
from django_analyses.models.input.definitions.number_input_definition import \
NumberInputDefinition
from django_analyses.models.input.types.float_input import FloatInput
class FloatInputDefi... | StarcoderdataPython |
5123396 | <reponame>seroanlph/BinnedFit
#!/usr/bin/python
import iminuit as imin
import numpy as np
import inspect
import sys
from os import system
from scipy.stats import kstest
class UnbinnedLLH():
def __init__(self, model, x, start):
if np.ma.isMaskedArray(x):
self.x = x.compressed()
elif ty... | StarcoderdataPython |
3290354 | <reponame>phisolani/optimal_wifi_slicing
from gekko import GEKKO
m = GEKKO() # Initialize gekko
m.options.SOLVER=1 # APOPT is an MINLP solver
# optional solver settings with APOPT
m.solver_options = ['minlp_maximum_iterations 500', \
# minlp iterations with integer solution
'mi... | StarcoderdataPython |
4906631 | ######################################################################################################################
# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. #
# ... | StarcoderdataPython |
4951781 | #!/usr/bin/python
import re
import zipfile
import tempfile
import shutil
import os
import unittest
import subprocess
class generator_zip(unittest.TestCase):
def setUp(self):
self.tmp_dir = tempfile.mkdtemp('generator_zip')
def tearDown(self):
shutil.rmtree(self.tmp_dir)
def read_zip(sel... | StarcoderdataPython |
3312866 | <gh_stars>0
import mysql.connector
conn = mysql.connector.connect(user="root",password="",database="python")
cursor = conn.cursor()
cursor.execute('select * from user where id = %s', ('1',))
values = cursor.fetchall()
print(values)
cursor.execute('select * from user')
values = cursor.fetchall()
print(values)
conn.comm... | StarcoderdataPython |
265601 | from models.split_googlenet import Split_googlenet
from models.split_resnet import Split_ResNet18,Split_ResNet34,Split_ResNet50,Split_ResNet101
from models.split_densenet import Split_densenet121,Split_densenet161,Split_densenet169,Split_densenet201
__all__ = [
"Split_ResNet18",
"Split_ResNet34",
"Split_... | StarcoderdataPython |
4898276 | <filename>chromusic.py
"""####################################################################
# Copyright (C) #
# 2020 <NAME>(<EMAIL>) #
# Permission given to modify the code as long as you keep this #
# declaration at the top ... | StarcoderdataPython |
5096529 | # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Tests for L{twisted.internet.abstract}, a collection of APIs for implementing
reactors.
"""
from __future__ import division, absolute_import
from twisted.trial.unittest import SynchronousTestCase
from twisted.internet.abstract import isIPv6... | StarcoderdataPython |
6463330 | <gh_stars>10-100
import json as json_handler
from balebot.models.constants.errors import Error
from balebot.models.factories import message_factory
class BotApiQuotedMessage:
def __init__(self, json):
if isinstance(json, dict):
json_dict = json
elif isinstance(json, str):
... | StarcoderdataPython |
395977 | # -*- coding: utf-8 -*-
"""
Created on Mon Mar 23 16:05:17 2020
@author: yuanh
"""
import os
import shutil
from openpyxl import load_workbook
import numpy as np
it = 6
flag = 0
nPop = 100
if flag == 1:
n = 9
index = np.zeros((n, 1))
wb = load_workbook('Positions.xlsx')
sheet ... | StarcoderdataPython |
8069931 | <filename>learner_model/SeqRNN.py
"""
The core model
"""
import os
from os import path
import time
import settings
import keras
from keras.models import Model
from keras.preprocessing import sequence
from keras.layers import Input, Dense, Dropout, Embedding, LSTM, TimeDistributed
import keras.backend as K
import num... | StarcoderdataPython |
3311188 | <reponame>mineo/edaboweb
#!/usr/bin/env python
# coding: utf-8
# Copyright © 2015 <NAME>
# License: MIT, see LICENSE for details
from flask.ext.sqlalchemy import SQLAlchemy
from sqlalchemy.dialects.postgresql import JSONB, UUID
db = SQLAlchemy()
class Playlist(db.Model):
id = db.Column(db.Integer, primary_key=Tr... | StarcoderdataPython |
1675582 | <filename>mafiaTokenStore.py
import json
import os
import boto3
from slack import WebClient
from slack.errors import SlackApiError
from util.env import getEnvVar
from util.slack_payload_parser import parse_payload
APP_CLIENT_ID = getEnvVar('APP_CLIENT_ID')
APP_CLIENT_SECRET = getEnvVar('APP_CLIENT_SECRET')
TOKEN_SOURC... | StarcoderdataPython |
9663131 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2021 Intel Corporation
#
# 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 |
5162749 | def is_k_anonymous(partition, k):
if len(partition) < k:
return False
return True
def is_l_diverse(df, partition, sensitive_column, l):
diversity = len(df.loc[partition][sensitive_column].unique())
return diversity >= l
def is_t_close(df, partition, sensitive_column, global_freqs, p):
to... | StarcoderdataPython |
61182 | <gh_stars>0
import numpy as np
# activation functions and its derivatives
def tanh(x):
return np.tanh(x)
def tanh_prime(x):
return 1-np.tanh(x)**2
def sigmoid(x):
return 1/(1+np.exp(-x))
def sigmoid_prime(x):
return sigmoid(x)*(1-sigmoid(x))
| StarcoderdataPython |
3242378 | <reponame>theotherphp/relay
"""
Main app - setup, signal handling and graceful shutdown
"""
import os
from signal import signal, SIGTERM, SIGINT
from functools import partial
from tornado.ioloop import IOLoop
from tornado.web import Application, StaticFileHandler
from tornado.httpserver import HTTPServer
from relay_... | StarcoderdataPython |
4988159 | from random import randint
from retrying import retry
import apysc as ap
from apysc._display.x_interface import XInterface
from apysc._expression import expression_data_util
from apysc._type import value_util
class TestXInterface:
@retry(stop_max_attempt_number=15, wait_fixed=randint(10, 3000))
... | StarcoderdataPython |
3399630 | # richard -- video index system
# Copyright (C) 2012, 2013 richard contributors. See AUTHORS.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at ... | StarcoderdataPython |
5169821 | import inspect
from abc import ABCMeta, abstractmethod
from functools import partial
from typing import List, get_type_hints
from guniflask.beans.constructor_resolver import ConstructorResolver
from guniflask.beans.definition import BeanDefinition
from guniflask.beans.definition_registry import BeanDefinitionRegistry
... | StarcoderdataPython |
1944981 | <filename>scripts/arcresthelper/__init__.py<gh_stars>1-10
import common
import securityhandlerhelper
import featureservicetools
import orgtools
import portalautomation
import publishingtools
import resettools
__version__ = "3.0.1"
| StarcoderdataPython |
6517780 | from tkinter import Tk, Button, Label
from tkinter import Canvas
from random import randint
root = Tk()
root.title("Catch the ball Game")
root.resizable(False, False)
# for defining the canvas
canvas = Canvas(root, width=600, height=600)
canvas.pack()
# variable for the vertical distance travelled by ball
limit = 0
... | StarcoderdataPython |
6644971 | #!/usr/bin/env python3
import click
import logging
from mujoco_worldgen.util.envs import EnvViewer, examine_env
from mujoco_worldgen.util.path import worldgen_path
from mujoco_worldgen.util.parse_arguments import parse_arguments
logger = logging.getLogger(__name__)
# For more detailed on argv information, please ha... | StarcoderdataPython |
8096174 | # Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from pants.backend.helm.goals import lint, package, publish, tailor
from pants.backend.helm.target_types import (
HelmArtifactTarget,
HelmChartTarget,
HelmUnitTestTestsGenerato... | StarcoderdataPython |
4987740 | <reponame>CamelKing1997/AICVTools
import os
import shutil
import sys
from stat import *
import argparse
def walkfolder(srcdir, tardir):
index = 1
for root, dirs, files in os.walk(srcdir, True):
for file in files:
shutil.copy(os.path.join(root, file), tardir)
index += 1
... | StarcoderdataPython |
40056 | #!/usr/bin/env python3.5
import sys
import os
import logging
import numpy as np
import musm
from sklearn.utils import check_random_state
from textwrap import dedent
#1Social Choice
_LOG = musm.get_logger('adt17')
PROBLEMS = {
'synthetic': musm.Synthetic,
'pc': musm.PC,
}
USERS = {
'noiseless': musm.Noi... | StarcoderdataPython |
12815134 | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2022-04-08 00:20 bucktoothsir <<EMAIL>>
#
# Distributed under terms of the MIT license.
"""
"""
import capstone as ct
import keystone as kt
ARCH_DIC = {'x86':[ct.CS_ARCH_X86, kt.KS_ARCH_X86],
'arm':[ct.CS_ARCH_ARM, kt.KS_AR... | StarcoderdataPython |
4861245 | <gh_stars>1-10
import sys
from tqdm import tqdm
#Sample output run
#python meta_file_parser.py test_for_meta_parsing.txt meta_data/meta_file_monthly_ids_range.tsv
#Pass the country/lang file that you want to extract
opened_file = open(sys.argv[1])
#Pass the meta-file as provided in the repo
meta_file_opened = open(... | StarcoderdataPython |
1820520 | from .common import AlterResource, CreateResource, DeleteResource, GetResource, ListResources
from .. import config, serializers
class StorageProviderMixin(object):
SERIALIZER_CLS = serializers.StorageProviderSchema
@staticmethod
def _get_api_url(**kwargs):
return config.config.CONFIG_HOST
@... | StarcoderdataPython |
4827491 | from typing import List
cube = lambda x: x**3
def fibonacci(n: int) -> List[int]:
if n == 0:
return []
if n == 1:
return [0]
nums = [0, 1]
for i in range(2, n):
nums.append(nums[i-1] + nums[i-2])
return nums
if __name__ == '__main__':
n = int(input())
print(l... | StarcoderdataPython |
9784084 | <reponame>AndreasKaratzas/stonne
from tools.codegen.model import *
from tools.codegen.api.types import TensorOptionsArguments, LegacyDispatcherArgument, ThisArgument
import tools.codegen.api.cpp as cpp
from typing import Union, Sequence
# This file describes the translation of JIT schema to the legacy
# dispatcher A... | StarcoderdataPython |
6697182 | <filename>scripts/slave/build_scan_db.py<gh_stars>0
#!/usr/bin/env python
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Contains configuration and setup of a build scan database.
The database is a ve... | StarcoderdataPython |
6636607 | <reponame>AbinavRavi/PipelineDP
import abc
import typing
import pickle
from dataclasses import dataclass
from functools import reduce
import pipeline_dp
@dataclass
class AccumulatorParams:
accumulator_type: type
constructor_params: typing.Any
def merge(accumulators: typing.Iterable['Accumulator']) -> 'Accum... | StarcoderdataPython |
249805 |
# <NAME>
# # idealista HTML Selenium Scrapping to MongoDB
import pandas as pd
from selenium import webdriver
from bs4 import BeautifulSoup
from pymongo import MongoClient
from pprint import pprint
import datetime
import time
from selenium.webdriver.firefox.options import Options
client = MongoClient('') # MongoDB i... | StarcoderdataPython |
1718849 | """
This inline script can be used to dump flows as HAR files.
example cmdline invocation:
mitmdump -s ./har_dump.py --set hardump=./dump.har
filename endwith '.zhar' will be compressed:
mitmdump -s ./har_dump.py --set hardump=./dump.zhar
"""
import json
import base64
import typing
import tempfile
import re
from d... | StarcoderdataPython |
8033787 | from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from datetime import timedelta
from uuid import uuid4
from django.test import TestCase
from django.utils.timezone import now
from kolibri.core.auth.test.test_api import FacilityFactory
from kolibri.co... | StarcoderdataPython |
11390514 | <filename>azure-mgmt-datafactory/azure/mgmt/datafactory/operations/__init__.py
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license infor... | StarcoderdataPython |
8009678 | from collections import deque
import sys
import numpy as np
import pylab as pl
def findpeaks_naive(f, W=100):
"""
Iterator to find the peaks in a set of data points.
The algorithm is dumb. It checks to see if each element is greater
than the W values to the left and W values to the right.
Args:... | StarcoderdataPython |
4894427 | <reponame>sonntagsgesicht/auxilium
# -*- coding: utf-8 -*-
# auxilium
# --------
# Python project for an automated test and deploy toolkit.
#
# Author: sonntagsgesicht
# Version: 0.2.4, copyright Wednesday, 20 October 2021
# Website: https://github.com/sonntagsgesicht/auxilium
# License: Apache License 2.0 (see L... | StarcoderdataPython |
5124108 | <reponame>BrancoLab/LocomotionControl<gh_stars>0
from math import sin, cos, atan2, sqrt, pi, hypot, acos
import numpy as np
from scipy.spatial.transform import Rotation as Rot
import sys
sys.path.append("./")
from control.paths.utils import mod2pi, pi_2_pi
from control.paths.waypoints import Waypoints, Waypoint
fro... | StarcoderdataPython |
3206276 | <gh_stars>1-10
import csv
import os.path
import matplotlib
matplotlib.rcParams.update({'font.size': 20})
from matplotlib import pyplot as plt
import numpy as np
itr_interval = 200
max_itr = 1e4
fields = [
# 'Return',
'Success Rate',
# 'Collision Rate',
'Inference Accur... | StarcoderdataPython |
1621331 | <reponame>ncrubin/chemftr
"""Test cases for util.py
"""
from chemftr.utils import QR, QI, QR2, QI2, power_two
def test_QR():
""" Tests function QR which gives the minimum cost for a QROM over L values of size M. """
# Tests checked against Mathematica noteboook `costingTHC.nb`
# Arguments are otherwise ra... | StarcoderdataPython |
5189803 | from ....expressions import Symbol, Constant, FunctionApplication as Fa
from ....expression_walker import PatternWalker, add_match
from ..chart_parser import (
Grammar,
Rule,
RootRule,
ChartParser,
_lu,
DictLexicon,
)
S = Symbol("S")
NP = Symbol("NP")
PN = Symbol("PN")
VP = Symbol("VP")
V = Sy... | StarcoderdataPython |
3336726 | <filename>src/botservice/azext_bot/botservice/models/__init__.py<gh_stars>0
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license informat... | StarcoderdataPython |
6406428 | #coding=utf-8
import json
from core.helper.crypt import pwd_crypt
from core.helper.globalvar import global_const
from copy import copy
import os
class config_parser:
# 自定义异常,找不到对应的服务器记录
class ErrorNotFind(BaseException):
def __init__(self):
pass
def __str__(self):
... | StarcoderdataPython |
11326762 | <gh_stars>100-1000
import numpy as np
import matplotlib.pylab as plt
import copy
# add angler to path (not necessary if pip installed)
import sys
sys.path.append("..")
# import the main simulation and optimization classes
from angler import Simulation, Optimization
from angler.plot import Temp_plt
# import some stru... | StarcoderdataPython |
5169541 | #-------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#--------------------------------------------------------------------------
import os
i... | StarcoderdataPython |
2749 | """
Module for higher level SharePoint REST api actions - utilize methods in the api.py module
"""
class Site():
def __init__(self, sp):
self.sp = sp
@property
def info(self):
endpoint = "_api/site"
value = self.sp.get(endpoint).json()
return value
@property
def w... | StarcoderdataPython |
9719596 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2017-05-01 17:35
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('file_repository', '0006_auto_20161108_2010'),
('problems', '0079_merge'),
]
... | StarcoderdataPython |
11241656 | <reponame>jkklapp/sheila2<filename>sheila2_test.py
import unittest
import os
from sheila2 import Sheila
class BasicTestCase(unittest.TestCase):
def setUp(self):
self.sheila = Sheila("testdb", "test.cst")
def tearDown(self):
try:
os.remove("test.cst")
except OSError:
... | StarcoderdataPython |
12856527 |
import gym
import numpy as np
import tensorflow as tf
import time
from actor_critic.policy import A2CBuilder
from actor_critic.util import discount_with_dones, cat_entropy, fix_tf_name
from common.model import NetworkBase
from common.multiprocessing_env import SubprocVecEnv
from tqdm import tqdm
class ActorCritic(... | StarcoderdataPython |
6462514 | <filename>src/menu.py
# _*_coding:utf-8_*_
from os import environ
if 'PYGAME_HIDE_SUPPORT_PROMPT' not in environ:
environ['PYGAME_HIDE_SUPPORT_PROMPT'] = ''
del environ
import PIL
import pygame
from PIL import Image
from pygame import Surface
from life_game import GridUniverse
from typing import Tuple, List, Opti... | StarcoderdataPython |
11293318 | <filename>Python Pandas.py
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 15 18:16:26 2018
@author: Manoj.Prabhakar
"""
import numpy as np
import pandas as pd
from numpy.random import randn
import os
# Series
labels = ['a','b','d','e']
data = [10,30,50,70]
ar = np.array(data)
d={'a':10,'b':30,'c':5... | StarcoderdataPython |
11381221 | from django.conf import settings
from elasticsearch_dsl import DocType, Date, String, Long, Ip, Nested, \
Object, Index, MetaField, analyzer, FacetedSearch, Q, TermsFacet, \
InnerObjectWrapper, DateHistogramFacet, SF
class Client(InnerObjectWrapper):
pass
class DnsRecord(DocType):
domain = String(i... | StarcoderdataPython |
1989911 | <reponame>data-science-misis/rec-sys
import pandas as pd
from data_provider import database, popular
MAX_RECOMMENDATION_COUNT = 100
def predict_popular(k=10):
n = min(k, MAX_RECOMMENDATION_COUNT)
return popular()[:n]
def get_user_ids():
return database()['user_id'].unique().tolist()
def predict_col... | StarcoderdataPython |
1754492 | <filename>rllib/policy/q_function_policy/epsilon_greedy.py
"""Epsilon Greedy Policy."""
import torch
from rllib.util.neural_networks import get_batch_size
from .abstract_q_function_policy import AbstractQFunctionPolicy
class EpsGreedy(AbstractQFunctionPolicy):
"""Implementation of Epsilon Greedy Policy.
A... | StarcoderdataPython |
4807195 | #!/usr/bin/python
from sys import argv, exit
from Bio import SeqIO
f = open(argv[1],'r')
records = SeqIO.parse(f,'fasta')
for r in records:
seq = str(r.seq).replace('-', 'N')
print(">%s\n%s\n"%(r.description, seq))
f.close()
| StarcoderdataPython |
9708075 |
DEBUG = True
TEMPLATE_DEBUG = True
SITE_ID = 1
DATABASES = {
'default': {
'NAME': 'db.sqlite',
'ENGINE': 'django.db.backends.sqlite3',
}
}
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.c... | StarcoderdataPython |
8037671 | # Generated by Django 3.2 on 2021-05-09 17:35
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('store', '0002_product_image'),
]
operations = [
migrations.RemoveField(
model_name='shippingaddress',
name='landmark',
... | StarcoderdataPython |
3228636 | from kingfisher_scrapy.base_spider import SimpleSpider
from kingfisher_scrapy.util import components
class NicaraguaSolidWaste(SimpleSpider):
"""
Domain
Solid Waste Mitigation Platform (SWMP)
Spider arguments
from_date
Download only data from this date onward (YYYY-MM-DD format). Defau... | StarcoderdataPython |
1973311 | "Unit tests of larry.__getitem__"
from nose.tools import assert_raises, assert_equal
import numpy as np
from numpy.testing import assert_array_equal
nan = np.nan
from la import larry
from la.util.testing import assert_larry_equal as ale
def make_larrys():
a1 = np.array([[ 1.0, nan],
[ 3.0, 4.... | StarcoderdataPython |
9669382 | # Copyright (C) 2021 Intel Corporation
# SPDX-License-Identifier: BSD-3-Clause
"""Sigma Delta neuron."""
import torch
from . import base
from ..dendrite import Sigma
from ..axon import Delta
def neuron_params(device_params, scale=1 << 6):
"""Translates device parameters to neuron parameters.
Parameters
... | StarcoderdataPython |
6529433 | from django.db import DatabaseError
from django.test import TestCase
from app.models import SmallInteger
class SmallIntegerTests(TestCase):
def setUp(self):
self.int0_id = SmallInteger.objects.create(small_integer=0).id
self.int1_id = SmallInteger.objects.create(small_integer=1111).id
def te... | StarcoderdataPython |
3399722 | <reponame>lochbrunner/ant-challenge
from dataclasses import dataclass
from typing import List, Optional
from abc import ABC, abstractmethod
from enum import Enum
class Semantic(Enum):
ALY = 1
ENEMY = 2
SUGAR = 3
OWN_HILL = 4
OTHERS_HILL = 5
@dataclass
class ViewRay:
distance: float
sema... | StarcoderdataPython |
3339938 | Version = "2.0"
if __name__ == "__main__":
print (Version)
| StarcoderdataPython |
9700291 | # Generated by Django 3.0.7 on 2020-08-07 03:52
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('syndication_app', '0005_auto_20200807_0011'),
]
operations = [
migrations.CreateModel(
... | StarcoderdataPython |
3287711 | <filename>app/urls.py
from django.urls import path
from .views import *
urlpatterns = [
path('', apioverview),
path('task-list/', tasklist),
path('task-detail/<int:pk>/', taskdetail),
path('task-create/', taskcreate),
path('task-update/<int:pk>/', taskupdate),
path('task-delete/<int:pk>/', tas... | StarcoderdataPython |
358403 | # Generated by Django 3.2.5 on 2021-07-21 22:54
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0003_user_staff'),
]
operations = [
migrations.CreateModel(
name='Survey',
fields=[
('id... | StarcoderdataPython |
23785 | <reponame>misantroop/jsonpickle
# -*- coding: utf-8 -*-
"""Test miscellaneous objects from the standard library"""
import uuid
import unittest
import jsonpickle
class UUIDTestCase(unittest.TestCase):
def test_random_uuid(self):
u = uuid.uuid4()
encoded = jsonpickle.encode(u)
decoded = j... | StarcoderdataPython |
159073 | from aiida_firecrest.scheduler import FirecrestScheduler
from aiida_firecrest.transport import FirecrestTransport
def test_init_scheduler():
FirecrestScheduler()
def init_transport(firecrest_server):
transport = FirecrestTransport(
url=firecrest_server.url,
token_uri=firecrest_server.token_u... | StarcoderdataPython |
8077161 |
from . import fnoUtils as utils
def getDailyData(instrumentType, dailyData):
'''
Returns all Daily Data In Ascending date order after doing the following conversion:
Current in memory dailyData format:
{
date1-string : {
date: date1,
... | StarcoderdataPython |
12842139 | <filename>codes/scripts/generate_mod_LR_bic.py
import os
import sys
import cv2
import numpy as np
import torch
try:
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from data.util import imresize_np
from utils import util
except ImportError:
pass
def generate_mod_LR_bic():... | StarcoderdataPython |
5104158 | # -*- coding: utf-8 -*-
"""One-component GEMC through RaspaBaseWorkChain"""
from __future__ import absolute_import
from __future__ import print_function
import sys
import click
from aiida.common import NotExistent
from aiida.engine import run, submit
from aiida.orm import Code, Dict
from aiida.plugins import Workflow... | StarcoderdataPython |
9728202 | from batchglm.models.base import _Estimator_Base, _EstimatorStore_XArray_Base
from batchglm.models.base import _InputData_Base
from batchglm.models.base import _Model_Base, _Model_XArray_Base
from batchglm.models.base import _Simulator_Base
from batchglm.models.base import INPUT_DATA_PARAMS
import batchglm.data as dat... | StarcoderdataPython |
1683502 | """
This module contains the implementation of the Classes: ModelGenerationMushroomOnline, ModelGenerationMushroomOnlineDQN,
ModelGenerationMushroomOnlineAC, ModelGenerationMushroomOnlinePPO, ModelGenerationMushroomOnlineSAC,
ModelGenerationMushroomOnlineDDPG and ModelGenerationMushroomOnlineGPOMDP.
The Class ModelG... | StarcoderdataPython |
189940 | # -*- coding: utf-8 -*-
""" MIMEタイプ """
TEXT = "text/plain"
HTML = "text/html"
CSS = "text/css"
JS = "application/javascript"
XML = "application/xml"
XHTML = "application/xhtml+xml"
JSON = "application/json"
SVG = "image/svg+xml"
def needs_charset(mime_type):
""" charset指定が必要なMIMEタイプか? """
return mime_t... | StarcoderdataPython |
3442530 | <reponame>bearcatt/mega.pytorch
import random
import sys
import numpy as np
from PIL import Image
from .vid import VIDDataset
from mega_core.config import cfg
# modified from torchvision to add support for max size
def get_size(min_size, max_size, image_size):
if not isinstance(min_size, (list, tuple)):
... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.