id stringlengths 1 7 | text stringlengths 6 1.03M | dataset_id stringclasses 1
value |
|---|---|---|
1744617 | <reponame>arj119/FedML
import logging
import torch
from torch import nn
import torch.nn.functional as F
import torchvision.transforms as tfs
from torchvision.utils import make_grid
import wandb
from torch.utils.data import TensorDataset, DataLoader
from itertools import cycle
from fedml_api.model.cv.generator import ... | StarcoderdataPython |
1787411 | <filename>code/P3.py
import numpy as np
from numpy import linalg as LA
import pandas as pd
import matplotlib.pyplot as plt
import os
from utils import covariance, LinearLeastSquare, TotalLeastSquare, RANSAC
np.set_printoptions(formatter={'all':lambda x: str(x)})
file =os.path.join("../data","insurance_data.csv")
... | StarcoderdataPython |
1761354 | import testbase
from sqlalchemy import *
class CompileTest(testbase.AssertMixin):
"""test various mapper compilation scenarios"""
def tearDownAll(self):
clear_mappers()
def testone(self):
global metadata, order, employee, product, tax, orderproduct
metadata = BoundMetaData(... | StarcoderdataPython |
4806799 | <gh_stars>1-10
from django.shortcuts import render
from sitecampus.models import Autor, Post
# Create your views here.
def index(request):
posts = Post.objects.all()
context = {'posts': posts}
return render(request, 'index.html', context=context )
| StarcoderdataPython |
3293956 | import torch
import torch.nn as nn
from torchvision.models.resnet import resnet50
from torchvision.models.vgg import vgg16
import dino.vision_transformer as vits
#import moco.vits as vits_moco
def get_model(arch, patch_size, device):
# Initialize model with pretraining
url = None
if "moco" ... | StarcoderdataPython |
102902 | from baserow.contrib.database.formula.exceptions import BaserowFormulaException
class InvalidNumberOfArguments(BaserowFormulaException):
def __init__(self, function_def, num_args):
if num_args == 1:
error_prefix = "1 argument was"
else:
error_prefix = f"{num_args} arguments... | StarcoderdataPython |
1789207 | import os
import re
from argparse import ArgumentParser
from argparse import ArgumentTypeError
def parse_arguments():
"""
Method to parse arguments, any check need is made on the type argument, each type represents a function.
:return: Parsed arguments
"""
parser = ArgumentParser(descri... | StarcoderdataPython |
3395639 | <reponame>dyning/AlexNet-Prod<gh_stars>10-100
import numpy as np
import torch
from torchvision.models.alexnet import alexnet
from reprod_log import ReprodLogger
if __name__ == "__main__":
# load model
# the model is save into ~/.cache/torch/hub/checkpoints/alexnet-owt-4df8aa71.pth
# def logger
repro... | StarcoderdataPython |
172172 | from pyflowline.algorithms.auxiliary.check_head_water import check_head_water
def remove_small_river(aFlowline_in, dThreshold_in):
nFlowline = len(aFlowline_in)
aFlowline_out=list()
if nFlowline == 1:
aFlowline_out.append(aFlowline_in[0])
else:
lID = 0
for i in ra... | StarcoderdataPython |
86523 | # Copyright (c) 2012, GPy authors (see AUTHORS.txt).
# Licensed under the BSD 3-clause license (see LICENSE.txt)
from ....core.parameterization.parameter_core import Pickleable
from GPy.util.caching import Cache_this
from ....core.parameterization import variational
import rbf_psi_comp
import ssrbf_psi_comp
import ssl... | StarcoderdataPython |
1652747 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#Author:Winston.Wang
from collections import Iterable
print("---------使用生成器替换列表生成式节约空间----------");
#列表生成式
print([v for v in range(10)])
#[]替换为()变成生成器
g = (v for v in range(10));
print(g)
#获取生成器的值
print(next(g))
print(next(g))
print(next(g))
print(next(g))
#判断generator是否式... | StarcoderdataPython |
3363091 | import json
import pytest
from share.tasks import ingest
from tests import factories
@pytest.mark.django_db
class TestIngestJobConsumer:
def test_no_output(self):
raw = factories.RawDatumFactory(datum=json.dumps({
'@graph': []
}))
job = factories.IngestJobFactory(raw=raw)
... | StarcoderdataPython |
1669981 | from .analyzer import Analyzer
| StarcoderdataPython |
1606077 | <reponame>NeCTAR-RC/manuka<gh_stars>0
"""make user_id unique
Revision ID: 4b8f295e23e2
Revises: 53c5ca8ba<PASSWORD>
Create Date: 2020-04-30 15:58:32.976300
"""
from alembic import op
# revision identifiers, used by Alembic.
revision = '4<PASSWORD>'
down_revision = '53<PASSWORD>ba<PASSWORD>'
branch_labels = None
depe... | StarcoderdataPython |
113891 | <reponame>bhhaskin/bryans.website
from allauth.account.adapter import DefaultAccountAdapter
class ClosedAccountAdapter(DefaultAccountAdapter):
def is_open_for_signup(self, request):
return False
| StarcoderdataPython |
3211445 | import pytest
from astropy import units as u
import numpy as np
from xrtpy.response.channel import Channel
import pkg_resources
import sunpy
import sunpy.map
from sunpy.data import manager
import scipy.io
import sunpy.io.special
channel_names = [
"Al-mesh",
"Al-poly",
"C-poly",
"Ti-poly",
"Be-thin"... | StarcoderdataPython |
352 | # -*- coding: utf-8 -*-
from .__module__ import Module, dependency, source, version
from .tools import Tools
from .boost import Boost
from .python import Python
@dependency(Tools, Python, Boost)
@source('git')
@version('4.0.1')
class Opencv(Module):
def build(self):
return r'''
RUN ln -fs /usr/sh... | StarcoderdataPython |
3235299 | from django.http import FileResponse
from django.shortcuts import render
def get_file_serve_view(filename:str):
def get_file(request):
return FileResponse(open('web_interface/oss-web/build/{}'.format(filename), 'rb'))
return get_file
| StarcoderdataPython |
3344 | import torch
import torchvision
import torchvision.transforms as transforms
import os.path
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
transform = transforms.Compose(
[transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
root = os.path.join(BASE_DIR, '../data/')
trainset ... | StarcoderdataPython |
3383709 | <reponame>Holt59/Project-Matthew<filename>matlab/demos/UDPCommunication/PC/reception.py
from socket import *
s = socket(AF_INET, SOCK_DGRAM)
s.bind(('', 9000))
while True:
s.recv(4) | StarcoderdataPython |
48030 | <gh_stars>0
#!/bin/bash/python
#
# Importation des librairies utiles
import json
import os
import pipes
import time
import datetime
import sys
import zipfile
from os.path import basename
import paramiko
import logging
import boto3
from botocore.exceptions import ClientError
# Declaration des variables
DATETIME = time... | StarcoderdataPython |
1669842 | <filename>djangoFiles/logs/dbio.py<gh_stars>10-100
from base.dbio import AbstractBaseDbIO
from logs.models import AccessLog
class AccessLogDbIO(AbstractBaseDbIO):
def __init__(self):
self.model_name = AccessLog
| StarcoderdataPython |
3343223 | import os
import cv2
from constants import MODULE_CLASSIFIER_DIR
from cv_helpers import get_classifier_directories, apply_offset_to_locations, show
from modules import Type, ModuleSolver
from modules.maze_cv import get_maze_params, get_button_locations
from modules.maze_solution import find_path_through_maze, UP, RIG... | StarcoderdataPython |
3231416 | # -*- coding: utf-8 -*-
"""
Created on Wed Jan 24 17:36:27 2018
@author: rantala2
"""
import mne
import sys
import subprocess
# import os
def createBem(subj):
src = mne.setup_source_space(subj, n_jobs=2)
subprocess.call(['mne', 'watershed_bem', '-s', subj])
model = mne.make_bem_model(subj, conductivity=... | StarcoderdataPython |
3231052 | <filename>utils/pymeta_helper.py
#/usr/bin/python
# Copyright 2014 <NAME>. 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... | StarcoderdataPython |
63481 | <gh_stars>0
"""
Tests for skcore baseclasses
"""
import pytest
from sksurgerycore.baseclasses.tracker import SKSBaseTracker
def test_tracker_baseclass():
"""
We should throw not implemented error when we make a tracker without
the required functions.
"""
class BadTracker(SKSBaseTracker):# pylint:... | StarcoderdataPython |
3374867 | __title__ = 'ics'
__version__ = '0.5'
__author__ = '<NAME>'
__license__ = 'Apache License, Version 2.0'
__copyright__ = 'Copyright 2013-2019 <NAME> and individual contributors'
| StarcoderdataPython |
1672406 | <reponame>welch/sportsball
# -*- coding: utf-8 -*-
from .arrow import Arrow
from .factory import ArrowFactory
from .api import get, now, utcnow
| StarcoderdataPython |
1720098 | <gh_stars>1-10
from flask_restful import Api
from . import api_bp
from .controllers import UserController, UserList, TaskList, TaskController
api = Api(api_bp)
api.add_resource(UserList, "/users/")
api.add_resource(UserController, "/users/<u_id>/")
api.add_resource(TaskList, "/users/<u_id>/tasks/")
api.add_resource(... | StarcoderdataPython |
1638846 | <gh_stars>0
#ss HelloWorld.py $($Env:SPARK_HOME + "\README.md")
import sys
from pyspark.sql import SparkSession
from pyspark.sql.functions import lit
if __name__ == '__main__':
numArgs = len(sys.argv)
if numArgs > 1:
print("----------------------------------------------------------------------")
... | StarcoderdataPython |
1709958 | <filename>RU_EN_examples/muse.py
from __future__ import absolute_import, division
import sys
import logging
import tensorflow_hub as hub
import tensorflow_text
# Set PATHs
PATH_TO_SENTEVAL = '../'
PATH_TO_DATA = '../data'
# import SentEval
sys.path.insert(0, PATH_TO_SENTEVAL)
import senteval
# SentEval prepare and... | StarcoderdataPython |
1666314 | <filename>Lib/site-packages/sciplot/sciplotUI.py
# -*- coding: utf-8 -*-
"""
SciPlot-PyQt: Publication-ready scientific plotting for Python
==============================================================
SciPlot-PyQt (aka SciPlot) is a user-interface/matplotlib wrapper built with
PyQt5 that allows interactive plotting... | StarcoderdataPython |
3248319 | <filename>olist_data_warehouse/project/src/data_warehouse/create_data_warehouse.py
# This file contains the functions "" that create the dataware house, fact table, dimentional tables, etc.
def create_data_warehouse_schema(cursor):
"""
Summary: Creates the Olist Data Warehouse Database Schema.
Args:... | StarcoderdataPython |
165622 | from egpo_utils.egpo.egpo import EGPOTrainer
from egpo_utils.human_in_the_loop_env import HumanInTheLoopEnv
from egpo_utils.train.utils import initialize_ray
initialize_ray(test_mode=False)
def get_function(ckpt):
trainer = EGPOTrainer(dict(
env=HumanInTheLoopEnv,
# ===== Training =====
... | StarcoderdataPython |
3359416 | #!/usr/bin/env python3
def solution(a: list) -> int:
"""
>>> solution([3, 1, 2, 4, 3])
1
"""
return min(abs(sum(a[:i]) - sum(a[i:])) for i in range(len(a)))
def solution(a: list) -> int:
"""
>>> solution([3, 1, 2, 4, 3])
1
"""
sums = [0] * len(a)
acum = 0
for i, x in ... | StarcoderdataPython |
1687586 | <gh_stars>1-10
# Default time after which transaction processing should be aborted.
DEFAULT_TX_TIME_TO_LIVE = "3600000ms"
# Default transaction gas price to apply.
DEFAULT_TX_GAS_PRICE = 10
# Default transaction fee to apply.
DEFAULT_TX_FEE = int(1e11)
# Default transaction fee for native transfers.
DEFAULT_TX_FEE_N... | StarcoderdataPython |
98772 | import re
import copy
from inspect import getmembers, ismethod
from collections import OrderedDict
class Viewer:
_attribute_regex = re.compile(r'^__.*__$')
METHOD = lambda k, v: ismethod(v)
FIELD = lambda k, v: not ismethod(v)
ATTRIBUTE = lambda k, v: Viewer._attribute_regex.match(k)
NOT_ATTRIBUTE... | StarcoderdataPython |
20917 | #!/usr/bin/env python3
# do not hesitate to debug
import pdb
# python computation modules and visualization
import numpy as np
import sympy as sy
import scipy as sp
import matplotlib.pyplot as plt
from sympy import Q as syQ
sy.init_printing(use_latex=True,forecolor="White")
def Lyapunov_stability_test_linear(ev):
... | StarcoderdataPython |
176231 | <gh_stars>0
from io import BytesIO
from pathlib import Path
from typing import IO
from typing import List
from typing import Optional
from typing import Type
from typing import TypeVar
from typing import Union
from httpx import AsyncClient
from httpx import Response as HttpResponse
from consigliere.telegram import De... | StarcoderdataPython |
130263 | """
Parsing text file into Experiment instance using strictyaml
(github.com/crdoconnor/strictyaml/)
The aim here is to make config:
* possible to use even for non-programmers
* hard to misuse
* easy debuggable
Hence, the process of parsing config is a bit more complicated than
it could be, but it produces more useful... | StarcoderdataPython |
1623187 | # @Author: <NAME> <varoon>
# @Date: 18-08-2017
# @Filename: kernel_convolution_ex.py
# @Last modified by: varoon
# @Last modified time: 18-08-2017
import cv2
import numpy as np
#GOAL: Apply the following kernel convolution to an image: [-1,0,1||-1,5,-1||0,-1,0]
#applying a sharpening kernel convolution manually... | StarcoderdataPython |
1789539 | from utils.log import Log
from falcon import testing
from api import api
from reader.arg import Arg_Reader
from about import title, version
from extra.lcp_config import LCPConfig
from extra.clients_starter import end_client_threads
class LCPTestBase(testing.TestCase):
log = None
def setUp(self):
super... | StarcoderdataPython |
164693 | """This module provides configuration values used by the application."""
import logging
import os
from collections.abc import Mapping, Sequence
from logging import config as lc
from typing import Any, Optional, Union, final
import jinja2
import yaml
from pydantic import AnyHttpUrl, BaseModel, BaseSettings, EmailStr, H... | StarcoderdataPython |
1659159 | # -*- coding: utf-8 -*-
"""Dynamic inventories of Docker containers, served up fresh just for Ansible."""
import click
import json
import requests
import sys
if sys.version_info.major == 3:
import docker_dynamic_inventory.docker_dynamic_inventory as ddi
else:
import docker_dynamic_inventory as ddi
@click.c... | StarcoderdataPython |
1720722 | <reponame>03b8/TEfy<filename>tefy/__init__.py
from .tefy import OxGaWrap
__version__ = '0.1.3'
| StarcoderdataPython |
3293121 | <gh_stars>0
"""
目录结构:
├── ready_train_img.py # 脚本
├── big # 大图集合
│ └── 20220304-170511.jpeg
├── small # 小图集合
│ ├── 1
│ ├── 2
│ ├── 3
│ ├── 4
│ └── 5
├── suture # 导出集合
│ └── 20220304-170511.jpeg
运行:
python ready_train_img.py --img_path "./big" --simg_path "./small"
test某方法输出:
python ready_train_img.py --... | StarcoderdataPython |
31002 | <gh_stars>0
from io import BytesIO
import requests
from celery import Celery
from api import send_message, send_photo
from imdb2_api import get_movie_by_imdb_id
from imdb_api import IMDBAPIClient
# celery -A tasks worker --log-level INFO
app = Celery(
"tasks", backend="redis://localhost:6379/0", broker="redis://... | StarcoderdataPython |
4838413 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Preparing to run it:
# brew install pipenv # or other installation method
# pipenv install
# generate a personal access token at https://github.com/settings/tokens
# Running it:
# GITHUB_TOKEN=<PASSWORD> pipenv run python add-metadata.py < template.md > README... | StarcoderdataPython |
129447 | <reponame>Opendigitalradio/ODR-StaticPrecorrection
#!/usr/bin/env python
import numpy as np
from scipy import signal, optimize
import sys
import matplotlib.pyplot as plt
import dab_util as du
def gen_omega(length):
if (length % 2) == 1:
raise ValueError("Needs an even length array.")
halflength = int(... | StarcoderdataPython |
21368 | <reponame>dev1farms2face/f2f
from django.shortcuts import render
# Create your views here.
def subscribe(request):
return render(request, "subscribe.html",
{'data': {}})
| StarcoderdataPython |
189542 | <reponame>Vinicius-Tanigawa/Undergraduate-Research-Project
#Runway.py
#
# Created: Mar, 2014, SUAVE Team
# Modified: Jan, 2016, <NAME>
# ----------------------------------------------------------------------
# Imports
# ----------------------------------------------------------------------
from SUAVE.Core import D... | StarcoderdataPython |
49212 | with open('input', 'r') as file:
aim = 0
horizontal = 0
depth = 0
simple_depth=0
for line in file:
[com, n] = line.split(' ')
n = int(n)
if com == 'forward':
horizontal += n
depth += aim * n
elif com == 'down':
aim += n
... | StarcoderdataPython |
1602140 | <reponame>Nuullll/llvm-test-suite<gh_stars>10-100
"""Test module to collect compile time metrics. This just finds and summarizes
the *.time files generated by the build."""
from litsupport.modules import timeit
import os
def _getCompileTime(context):
# We compile multiple benchmarks in the same directory in Singl... | StarcoderdataPython |
3298742 | <reponame>ramsuthar305/MIT-research-and-consultancy
import hashlib
from app import *
from flask import session
import os
#from pyresparser import ResumeParser
from bson import ObjectId
class Users:
def __init__(self):
self.mongo = mongo.db
def check_user_exists(self, username):
result = self.mongo.users.find_... | StarcoderdataPython |
55559 | <gh_stars>1-10
import time
from dronekit import connect, TimeoutError
vehicle = connect('127.0.0.1:14551', wait_ready=True, timeout=60)
# vehicle = connect('tcp:127.0.0.1:5762', wait_ready=True, timeout=60)
try:
vehicle.wait_for_mode("GUIDED")
vehicle.wait_for_armable()
vehicle.arm()
time.sleep(1)
... | StarcoderdataPython |
1607061 | import unittest # Targeting Python 3
import footoe.helpers as h
class TestHelpers(unittest.TestCase):
def test_sanity(self):
self.assertEqual(sum([7, 7, 7, 7, 7, 7]), 42, "Should be 42")
def test_get_prefootnotes(self):
sample_text = "Here is one [^1] and another [^another]"
ex... | StarcoderdataPython |
4818852 | from typing import List, Union
from stability_label_algorithm.modules.argumentation.argumentation_theory.literal import Literal
from stability_label_algorithm.modules.argumentation.argumentation_theory.queryable import Queryable
def queryable_set_is_consistent(queryable_list: List[Union[Literal, Queryable]]) -> bool... | StarcoderdataPython |
3239834 | from snakeskin.pheremones import BasePheremoneModel
from snakeskin.pheremones import Max
# this is incomplete and needs some thought
TRAIL_DTYPE = [
("amplitude","float32"),
("epoch","float32"),
("width","float32")
]
class PheremoneTrail(object):
def __init__(self):
self.coefficients = []
... | StarcoderdataPython |
1706655 | <reponame>valq7711/bottlefly
import json as json_mod
import cgi
from tempfile import TemporaryFile
from io import BytesIO
from functools import partial
from ..common_helpers import touni
from .helpers import (
parse_qsl,
cache_in,
FileUpload,
FormsDict
)
from .errors import RequestError, BodyParsingEr... | StarcoderdataPython |
4806805 | <filename>blender/arm/props_collision_filter_mask.py
import bpy
class ARM_PT_RbCollisionFilterMaskPanel(bpy.types.Panel):
bl_label = "Collections Filter Mask"
bl_space_type = "PROPERTIES"
bl_region_type = "WINDOW"
bl_context = "physics"
bl_parent_id = "ARM_PT_PhysicsPropsPanel"
@cla... | StarcoderdataPython |
1785129 | # This part allows to import from main directory
import os
import sys
sys.path.insert(0, os.path.dirname('__file__'))
from unittest.mock import patch, call, Mock
import lib.nonogram as nonogram
def test_ModeData_initialisation_empty():
mode_data = nonogram.ModeData()
assert mode_data.fig == None
assert m... | StarcoderdataPython |
136887 | <filename>chrome/common/extensions/docs/server2/api_models_test.py
#!/usr/bin/env python
# Copyright 2013 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.
import json
import unittest
from api_models import APIModels
from c... | StarcoderdataPython |
3376269 | """
mingprovider Module
This contains the class which allows sprox to interface with any database.
Copyright © 2009 <NAME>
Original Version by <NAME> 2009
Released under MIT license.
"""
from bson.errors import InvalidId
import itertools
from sprox.iprovider import IProvider
from sprox.util import timestamp
impor... | StarcoderdataPython |
151203 | #A function for randomly generating prime numbers, including very large primes. The function does this by generating random odd numbers
#and testing their primality using the Fermat primality test. Note that the Fermat test is a probabilistic test which incorrectly labels
#some composite numbers ("pseudoprimes") as pri... | StarcoderdataPython |
1658267 | <filename>deeprank/utils/get_h5subset.py
#!/usr/bin/env python
"""Extract first N groups of a hdf5 to a new hdf5 file.
Usage: python {0} <hdf5 input file> <hdf5 output file> <number of groups to write>
Example: python {0} ./001_1GPW.hdf5 ./001_1GPW_sub10.hdf5 10
"""
import sys
import h5py
USAGE = __doc__.format(__f... | StarcoderdataPython |
3220261 | <filename>Recursion/tower_of_hanoi.py
def towerofhanoi(n, source, aux, dest):
# Please add your code here
if n==1:
print(source,"",dest)
return
towerofhanoi(n-1, source, dest, aux)
print(source,"",dest)
towerofhanoi(n-1, aux, source, dest)
n=int(input())
towerofhanoi(n, 'a', 'b', 'c... | StarcoderdataPython |
3259087 | <filename>fdp/services.py<gh_stars>0
from pathlib import Path
import requests
from data_pipeline_api.registry.download import download_from_config_file
def registry_installed():
user_home = Path.home()
scrc_dir = user_home.joinpath(".scrc")
return scrc_dir.exists()
def registry_running():
try:
... | StarcoderdataPython |
53555 | <reponame>marcinbodnar/debugger<filename>api/src/near/debugger_api/web/blueprint.py
import json
from flask import current_app, Blueprint, jsonify, request
from near.debugger_api.models import (
BeaconBlock, ContractInfo, ListBeaconBlockResponse, ListShardBlockResponse,
PaginationOptions, ShardBlock, Transacti... | StarcoderdataPython |
3270030 | import streamlit as st
import pandas as pd
import numpy as np
# read cleaned population_total data
pop_total = pd.read_csv("../data/clean/population_total.csv", sep=",", na_values='')
pop_total.set_index(['Year', 'Country'], inplace=True)
st.write(pop_total)
#print(pop_total[pop_total['PopTotal']<0])
# read cleaned ... | StarcoderdataPython |
3346577 | <reponame>brettkoonce/fairscale
from .auto_wrap import auto_wrap, default_auto_wrap_policy, enable_wrap, wrap
| StarcoderdataPython |
1787219 | class GenericObject(object):
STORAGE_PREFIX = "object"
PROPERTIES_IGNORE_DUMP = ()
PROPERTIES_IGNORE_LOAD = ()
def __init__(self, storage, *args, **kwargs):
self._storage = storage
self._storage_id = ":".join((
self.STORAGE_PREFIX,
kwargs.get("id", "changeme")
... | StarcoderdataPython |
1747047 | <reponame>mdietrichstein/xai-statlog-heart
def create_rf_estimator(verbose, random_state, n_jobs):
from sklearn.ensemble import RandomForestClassifier
return RandomForestClassifier(n_estimators=50, min_samples_split=2, min_samples_leaf=2,
max_features='auto', max_depth=30, boot... | StarcoderdataPython |
1749331 | # Generated by the protocol buffer compiler. DO NOT EDIT!
# sources: frontend_pb.proto
# plugin: python-betterproto
from dataclasses import dataclass
import betterproto
class Unit(betterproto.Enum):
"""TODO: should metric be 0? (i.e. the default)"""
imperial = 0
metric = 1
class ThemeVariant(betterpr... | StarcoderdataPython |
1631671 | <filename>reactivex/operators/_sequenceequal.py
from typing import Callable, Iterable, List, Optional, TypeVar, Union
import reactivex
from reactivex import Observable, abc, typing
from reactivex.disposable import CompositeDisposable
from reactivex.internal import default_comparer
_T = TypeVar("_T")
def sequence_eq... | StarcoderdataPython |
191241 | <reponame>kamyabdesign/DRF_Django
from django.db import models
from rest_framework import serializers
from blog.models import Article
class ArticleSerializer(serializers.ModelSerializer):
class Meta:
model = Article
fields = '__all__'
| StarcoderdataPython |
1653282 | <reponame>RvstFyth/discordballz
"""
Manages the selection phase.
--
Author : DrLarck
Last update : 19/10/19 (DrLarck)
"""
# dependancies
import asyncio
# utils
# translation
from utility.translation.translator import Translator
# displayer
from utility.cog.displayer.character import Character_displayer
fr... | StarcoderdataPython |
4824537 | <gh_stars>0
#!/usr/bin/python
#
# Copyright 2018-2021 Polyaxon, Inc.
#
# 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... | StarcoderdataPython |
1602039 | <gh_stars>1-10
"""
This file expands all mujoco include nodes (i.e., it flatten the file).
This can be a useful utility for debugging.
"""
import argparse
from lisdf.parsing.mjcf import MJCFVisitorFlatten
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("file")
args = parser.parse_args()
... | StarcoderdataPython |
1665506 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
SleekXMPP: The Sleek XMPP Library
Copyright (C) 2010 <NAME>
This file is part of SleekXMPP.
See the file LICENSE for copying permission.
"""
import sys
import logging
import getpass
from optparse import OptionParser
import sleekxmpp
import chat.uti... | StarcoderdataPython |
1746727 | #!/usr/bin/env python2
import unittest, os, shutil
from planet import config, splice, logger
from xml.dom import minidom
workdir = 'tests/work/apply'
configfile = 'tests/data/apply/config-%s.ini'
testfeed = 'tests/data/apply/feed.xml'
class ApplyTest(unittest.TestCase):
def setUp(self):
testfile = open(t... | StarcoderdataPython |
154963 | import unittest
import models.EndNode as n
class TestEndNode(unittest.TestCase):
def setUp(self):
self.a = n.EndNode('192.168.0.1', id = 1)
self.b = n.EndNode('192.168.0.1')
self.c = n.EndNode('192.168.0.3')
def testEquality(self):
self.assertTrue(self.a == self.a)
self... | StarcoderdataPython |
3217310 | <reponame>mqlight/qpid-proton
#
# 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 Apache License, Version 2.0 ... | StarcoderdataPython |
3263759 | #!/usr/bin/python3
# Info:
# <NAME>.
from datetime import date
def age(birth_date):
# determines important info based on given age (in form YYYY-MM-DD)
today = date.today()
expected_death = date(2080, 12, 14)
years_alive = today.year - birth_date.year
days_alive = (today - birth_date).days
d... | StarcoderdataPython |
64593 | """Support for Sonarr sensors."""
from datetime import timedelta
import logging
from typing import Any, Callable, Dict, List, Optional
from sonarr import Sonarr, SonarrConnectionError, SonarrError
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import DATA_GIGABYTES
from homeassistant.he... | StarcoderdataPython |
3356838 | import toml
from lambda_cache import __version__
def test_version():
"""
Test that version in __init.py__ matches pyproject.toml file
"""
with open('../pyproject.toml') as toml_file:
config = toml.load(toml_file)
version = config.get('tool').get('poetry').get('version')
assert ... | StarcoderdataPython |
1772471 | <filename>output/python_checkkeyplace.py
from statistics import mean
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
plt.style.use("ggplot") # グラフのデザインを指定する
sns.set_palette('Set2') # グラフの色を指定する
import warnings
warnings.filterwarnings('ignore') # 警告メッセージを出ないようにしている
hakohige_labels=[]
ha... | StarcoderdataPython |
3320233 | <reponame>vhte/bagpipewriter<filename>tests/test_bagpipemanager.py
from bagpipemanager.bagpipemanager import BagpipeManager
def test_get_properties(mocker):
sheet = mocker.Mocker()
manager = BagpipeManager()
| StarcoderdataPython |
3371713 | <reponame>DrLarck/DiscordBallZ_
"""
Manager the levelling
--
Author : DrLarck
Last update : 15/02/20 (DrLarck)
"""
# dependancies
import asyncio
from random import randint
# util
from utility.database.database_manager import Database
from utility.cog.character.getter import Character_getter
# leveller
class Level... | StarcoderdataPython |
3276129 | """
An active learning example using linear regression.
-- <EMAIL>
"""
# pylint: disable=invalid-name
# pylint: disable=no-name-in-module
# pylint: disable=abstract-method
import numpy as np
try:
from scipy.stats import multivariate_normal
except ImportError:
from numpy.random import multivariate_normal
# Loc... | StarcoderdataPython |
145013 |
from rest_framework import serializers
from authx.models import User
from rest_framework_jwt.utils import jwt_payload_handler as drf_jwt_payload_handler
class UserSerializer(serializers.ModelSerializer):
password = serializers.CharField(
style={'input_type': 'password'},
wr... | StarcoderdataPython |
3308596 | <filename>settings.py
#demo/settings.py
from os import environ
SECRET_KEY = environ.get('connectiondata') | StarcoderdataPython |
1667308 | <gh_stars>1-10
from nodes.serializers import NodeListSerializer
from rest_framework import serializers
from users.serializers import UserSerializer
from .models import Post
class PostCreateSerializer(serializers.ModelSerializer):
user = serializers.ReadOnlyField(source="user.username")
class Meta:
m... | StarcoderdataPython |
1787990 | <reponame>Elyavor/ITMO_ICT_WebDevelopment_2021-2022
from rest_framework import serializers
from .models import Subject
class SubjectSerializer(serializers.ModelSerializer):
class Meta:
model = Subject
fields = '__all__'
| StarcoderdataPython |
179418 | # -*- coding: utf-8 -*-
"""
class Horizon for accessing horizon
Created on Fri July 20 2017
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
__author__ = "yuhao"
import pandas as pd
class Horizon(object):
"""
Horizon using excel file as input
... | StarcoderdataPython |
3226858 | # -*- coding: utf-8 -*-
# cython: language_level=3
# Copyright (c) 2020 Nekokatt
# Copyright (c) 2021 davfsa
#
# 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 w... | StarcoderdataPython |
3262530 | #@ Python in interactive mode properly initializes sys.argv
testutil.call_mysqlsh(["--py", "-i" ,"-e", "import sys; print('sys.argv = {0}'.format(sys.argv))"]) | StarcoderdataPython |
170097 | import argparse
from pathlib import Path
if __name__=="__main__":
parser = argparse.ArgumentParser()
parser.add_argument('--input', type=str, required=True,
help='input corpus to split into words')
parser.add_argument('--output', type=str, required=True,
help... | StarcoderdataPython |
1604298 | import os
import unittest
from pathlib import Path
from src.qchainpy.client import Client
class TestClientMethods(unittest.TestCase):
def setUp(self):
key_path = os.path.join(Path(__file__).resolve().parent, 'keys/private.key')
self.client = Client(
api_url=os.getenv('API_URL', default... | StarcoderdataPython |
1703970 | AVAILABLE_IDS= {"ensembl_gene_id": {
"uri": "http://identifiers.org/ensembl.gene/",
"example": "ENSG00000139618"
},
"entrez_gene_id": {
"uri": "http://identifiers.org/hgnc/",
"example": 1017
},
"hgnc_gene_symbol": {
"uri": "http://identifiers.org/hgnc.symbol/",
"example": "CDK7"
},
"hgvs_id": {
"uri": ... | StarcoderdataPython |
1759006 | <filename>utils/help_command.py
import asyncio
from math import ceil
import discord
from discord.ext import commands
class CommandHelpEntry:
def __init__(self, name, usage, desc):
self.name = name
self.usage = usage
self.desc = desc
class CustomHelpCommand(commands.DefaultHelpCommand):
... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.