id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
374742 | class Solution:
def canIwin(self, maxint: int, desiredtotal: int) -> bool:
if maxint * (maxint + 1) < desiredtotal:
return False
cache = dict()
def dp(running_total, used):
if used in cache:
return cache[used]
for k in range(maxint, 0, -1):... | StarcoderdataPython |
1806194 | """
Structured information on a temporary state of a tissue sample.
"""
# this file was auto-generated
from datetime import date, datetime
from fairgraph.base_v3 import KGObjectV3, IRI
from fairgraph.fields import Field
class TissueSampleState(KGObjectV3):
"""
Structured information on a temporary state o... | StarcoderdataPython |
6450271 | from bs4 import BeautifulSoup
import dateutil.parser
import requests
html = requests.get('https://www.oasis-open.org/resources/open-repositories/cla/view-individual').text
# with open("oasis.html", 'w') as f:
# f.write(html)
# with open("oasis.html") as f:
# html = f.read()
soup = BeautifulSoup(html, "html.... | StarcoderdataPython |
356628 | <reponame>duttashi/applied-machine-learning
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 23 22:00:08 2020
@author: Ashish
"""
# import sys
# sys.path.append('../') # use the sys.path.append() to call functions from another directory
from helpful_functions.eda_functions import print_data_head, find_null_colum... | StarcoderdataPython |
6574462 | <filename>Item47.py
"""
Item 47: Use __getattr__, __getattribute__, and __set__attr__ for Lazy Attributes
Use __getattr__ and __setattr__ to lazily load and save attributes for an object.
Understand __getattr__ only gets called when accessing a missing attribute while
__getattribute__ gets called every time any attrib... | StarcoderdataPython |
3306338 | <gh_stars>10-100
import sys
import time
import struct
import serial
from hexdump import hexdump
from tqdm import tqdm
SERIALPORT = '/dev/ttyUSB0'
BAUDRATE = 9600
DEBUG = False
def handshake(ser):
print('[HANDSHAKE]')
ser.reset_input_buffer()
ser.reset_output_buffer()
ser.write(b'\x00' * 30)
get_... | StarcoderdataPython |
11283728 | '''Given an integer,N , perform the following conditional actions:
If N is odd, print Weird
If N is even and in the inclusive range of (2,5) , print Not Weird
If N is even and in the inclusive range of (6,20), print Weird
If N is even and greater than 20, print Not Weird'''
#!/bin/python3
N = int(input())
if(N%2!=0... | StarcoderdataPython |
11327449 | """
"""
import sys
import numpy as np
import os
import time
from dnnv.nn import parse as parse_network
from dnnv.properties import parse as parse_property
from pathlib import Path
from typing import Dict, List, Optional
from .cli import parse_args
from .falsifier import falsify
from .utils import init... | StarcoderdataPython |
6442 | <filename>python/testData/editing/enterInIncompleteTupleLiteral.after.py
xs = ('foo', 'bar',
'baz'<caret> | StarcoderdataPython |
309833 | <filename>dynamicmodel/models.py
from django.db import models
from django import forms
from django.contrib.contenttypes.models import ContentType
from django.core.validators import RegexValidator
from .fields import JSONField
from django.core.exceptions import ValidationError
from django.core.cache import cache
class... | StarcoderdataPython |
58569 | """
This module contains a class to describe physical connections between :mod:`Sea.model.components`.
"""
import math
import cmath
import numpy as np
import warnings # Handling of warnings
import abc # Abstract base classes
import logging # Add logging functionality
from ..base import Base
class Connection(Ba... | StarcoderdataPython |
9684658 | <reponame>dinojugosloven/pymalcolm
import unittest
from mock import patch, ANY
import os
from malcolm.core import Process, Context, StringMeta
from malcolm.modules.scanning.controllers import RunnableController
from malcolm.modules.ca.util import catools
from malcolm.core.alarm import Alarm, AlarmSeverity
from malcol... | StarcoderdataPython |
3279505 | import pytest
from pytest_mock import MockerFixture
from pystratis.api.signalr import SignalR
from pystratis.api.signalr.responsemodels import *
from pystratis.core.networks import StraxMain, CirrusMain
@pytest.mark.parametrize('network', [StraxMain(), CirrusMain()], ids=['StraxMain', 'CirrusMain'])
def test_get_conn... | StarcoderdataPython |
3470457 | <filename>Deep Learning - SG segmentation/FCN-DenseNet inference/DeepSGUS - sample.py
# Script for the automatic semantic segmentation of SGUS images
from DeepSGUS import DeepSGUS_CNN
import matplotlib.pyplot as plt
import cv2 as cv # Version 3.7
import numpy as np
import tensorflow.compat.v1 as tf
tf.disable_v2_behav... | StarcoderdataPython |
285647 | from __future__ import absolute_import
from django.contrib import admin
from smsgateway.models import SMS, QueuedSMS
class SMSAdmin(admin.ModelAdmin):
date_hierarchy = 'sent'
list_display = ('direction', 'sent', 'sender', 'to', 'content', 'operator', 'backend', 'gateway', 'gateway_ref')
search_fields = (... | StarcoderdataPython |
6520121 | from .settings import *
APP_ERROR_DB_MODEL = 'utils.TestErrorModel'
| StarcoderdataPython |
250711 | import rospy
import sys
import moveit_commander
from motion_control.moveit_helpers import load_joint_configurations_from_file
if __name__ == '__main__':
moveit_commander.roscpp_initialize(sys.argv)
rospy.init_node("moveit_commander_node")
group_name = rospy.get_param("~move_group")
pose_name = rospy.... | StarcoderdataPython |
12824260 | <reponame>michalnand/reinforcement_learning_im<gh_stars>0
import sys
sys.path.insert(0, '../../')
from libs_common.RLStatsCompute import *
import matplotlib.pyplot as plt
result_path = "./results/"
files = []
files.append("./models/ddpg_baseline/run_0/result/result.log")
files.append("./models/ddpg_baseline/run_1/r... | StarcoderdataPython |
5135072 | # brick_test.py
import unittest
from lego.brick import LegoBrick
class LegoBrick_Test(unittest.TestCase):
def test_wrongInitialization(self):
throws = False
try:
LegoBrick(10, 0)
except ValueError as e:
throws = True
self.assertTrue(
throws,
... | StarcoderdataPython |
4974850 | import sys
import pathlib
import re
from collections import Counter
import numpy as np
p = pathlib.Path(sys.argv[1])
file_dicts = []
for f in p.glob('*'):
with open(f) as in_stream:
d = Counter(re.split(r'\W+', in_stream.read()))
file_dicts.append(d)
voc = []
for d in file_dicts:
voc.exten... | StarcoderdataPython |
3329179 | import tensorflow as tf
import numpy as np
from PIL import Image
from .deeplab import Deeplab_xcep_pascal
from .semantic import obtain_segmentation
import cv2
import time
class alter_bg():
def __init__(self):
self.model = Deeplab_xcep_pascal()
def load_pascalvoc_model(self, model_path):
self.model... | StarcoderdataPython |
5119874 | # -*- coding: utf-8 -*-
"""
Created on Wed Apr 25 11:34:44 2018
@author: conte
"""
import sys
import cv2
import skimage
import numpy
import approaches.approach0.approach0 as a0
import approaches.approach1.approach1 as a1
import approaches.approach2.approach2 as a2
import approaches.approach3.approach3 as a3
import app... | StarcoderdataPython |
5094077 | <filename>saspy/sasbase.py<gh_stars>0
#
# Copyright SAS Institute
#
# 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 |
9701695 | from django.conf.urls.defaults import patterns
from views import *
urlpatterns = patterns('',
(r'^$', presence),
(r'^panel/$', panel),
(r'^error/(\d+)/$', error),
(r'^accounts/login/$', entrar),
(r'^accounts/logout/$', salir),
(r'^cambio/$', cambioPassword),
(r'^registroAlumno/$', registroAlumno),
(r'^regist... | StarcoderdataPython |
5170131 | <gh_stars>10-100
from django.db import models
class BattleRequest(models.Model):
id = models.BigAutoField(primary_key=True)
initiator = models.BigIntegerField()
matchmaker_type = models.IntegerField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto... | StarcoderdataPython |
1981832 | <gh_stars>10-100
import lib.logger as logging
from lib.functions import wait_until, r_sleep
from lib.game import ui
from lib.game.notifications import Notifications
logger = logging.get_logger(__name__)
class Alliance(Notifications):
"""Class for working with Alliance."""
class STORE_ITEM:
ENERGY =... | StarcoderdataPython |
6488389 | <filename>rozipparser/tests/test_small_locality_parsing.py
# coding=utf-8
import unittest
from rozipparser.codeparser import CodeParser
class TestSmallLocalityParsing(unittest.TestCase):
def test_number_of_codes(self):
parser = CodeParser("rozipparser/tests/inputs/small_locality_input.xlsx")
cod... | StarcoderdataPython |
4971234 | from rest_framework import serializers
from django.contrib.auth.models import User
from rest_framework.validators import UniqueValidator
from django.utils.timezone import now
from datetime import datetime
from django.contrib.humanize.templatetags.humanize import naturaltime
from forums.models import Forum
from t... | StarcoderdataPython |
1606744 | <reponame>python20180319howmework/homework<gh_stars>0
a=input("请输入身高")
b=input("请输入体重")
a=float(a)
b=float(b)
BMI=b/(a*a)
print("%d" % BMI)
if (BMI < 18.5):
print("你这么瘦,可以肆无忌惮的大吃大喝了")
elif (18.5 <=BMI < 25):
print("兄弟!你离模特就差八块腹肌了")
elif (25 <= BMI < 30):
print("控制你自己哦!脂肪有点多啦")
else:
print("不能在吃了!跑几圈去吧,你也可以是男神")... | StarcoderdataPython |
9688153 | <gh_stars>1-10
from flask_on_fhir.restful_resources import CodeSystemResource
def test_code_system(client, fhir):
fhir.add_fhir_resource(CodeSystemResource)
res = client.get('/CodeSystem')
assert res.status_code == 200
assert res.json['resourceType'] == 'CodeSystem'
| StarcoderdataPython |
1919734 | <gh_stars>0
from random import choice
from itertools import product
from tkinter import *
def set_default(obj):
if isinstance(obj, set):
return list(obj)
raise TypeError
class Maze:
"""Лабиринт для игры.
Нужен, чтобы можно было добавлять в лабиринт произвольные стены."""
def __init__(se... | StarcoderdataPython |
193168 | <reponame>sympolite/pridebot<filename>src/pridebot_v1_1.py<gh_stars>1-10
#=============================================================
#PRIDE BOT 1.1
#by sympolite
#github.com/sympolite
#femme pride flag by noodle.tumblr.com
#=============================================================
#core modules
import random
im... | StarcoderdataPython |
4922100 | import copy
import pickle
from typing import cast
import numpy as np
import autofit as af
from autoarray.fit import fit as aa_fit
from autoastro.galaxy import galaxy as g
from autoastro.hyper import hyper_data as hd
from autolens.dataset import imaging
from autolens.fit import fit
from autolens.pipeline import visual... | StarcoderdataPython |
5042532 | from embit import bip39
from embit.bip39 import mnemonic_to_bytes, mnemonic_from_bytes
import unicodedata
import hashlib
def calculate_checksum(partial_mnemonic: list, wordlist):
# Provide 11- or 23-word mnemonic, returns complete mnemonic w/checksum
if len(partial_mnemonic) not in [11, 23]:
raise Exc... | StarcoderdataPython |
3232040 | <reponame>triangle1984/vk-bot
from PIL import Image
class Pillowhelper():
def resize_image(input_image_path,
size):
original_image = Image.open(input_image_path)
width, height = original_image.size
resized_image = original_image.resize(size)
width, height = resized_i... | StarcoderdataPython |
3430130 | <gh_stars>1-10
from __future__ import print_function, division, absolute_import
from ..message import BulkFrontendMessage
class Sync(BulkFrontendMessage):
message_id = b'S'
| StarcoderdataPython |
3243081 | <filename>source/main_app.py
from tkinter import *
from tkinter import messagebox
import time
import threading
from splinter import Browser
import re
from urllib.request import urlopen
import sys # for debug purpose
# path for chromedriver
executable_path = {'executable_path':'/usr/local/bin/chromedriver'}
HEADLESS ... | StarcoderdataPython |
6440579 | name = "gcornilib"
| StarcoderdataPython |
3268363 | """Apply correction factors to energy_demand_unconstrained outputs
"""
from smif.exception import SmifException
from smif.model import SectorModel
class EnergyCorrectionFactor_Unconstrained(SectorModel):
"""Adaptor to apply energy correction factors
"""
def simulate(self, data_handle):
"""Read inpu... | StarcoderdataPython |
6489795 | <filename>Page Replacement Policy/First In First Out Algorithm (FIFO).py
# FIFO Page Replacement Program In Python
def FIFO(pages, capacity):
memory = list() # Initializing the memory
pageFaults = 0 # Count of number of page Faults
for page in pages:
if (page not in memor... | StarcoderdataPython |
171223 | import socket, zlib, thread, json, time, collections
from classes import User
PROTOCOL_VERSION = 3
HOST = 'localhost'
PORT = 1338
PREFIX = {'start':'\x02', 'end':'\r\n'}
HOOKS = {}
def Hook(hook):
def deco(func):
if hook not in HOOKS.keys():
HOOKS[hook] = func
return func
raise HookException('Hook %s alre... | StarcoderdataPython |
5072874 | #!/usr/bin/env python
# coding: utf-8
# Copyright (c) Qotto, 2019
import pytest
import asyncio
import os
from avro.schema import NamedSchema
from tonga.stores.manager.kafka_store_manager import KafkaStoreManager
from tonga.models.store.store_record import StoreRecord
from tonga.models.store.store_record_handler impor... | StarcoderdataPython |
1787616 | <reponame>ttung/starfish
from starfish import Experiment
def MERFISH(use_test_data: bool=False):
if use_test_data:
return Experiment.from_json(
"https://d2nhj9g34unfro.cloudfront.net/20181005/MERFISH-TEST/experiment.json")
return Experiment.from_json(
"https://d2nhj9g34unfro.cloudf... | StarcoderdataPython |
8185512 | import numpy as np
import random
import torch
import torch.nn as nn
import sys
import os
sys.path.insert(0, os.path.join(
os.path.dirname(os.path.realpath(__file__)), "../"))
def seed_all(seed=42):
torch.cuda.empty_cache()
random.seed(seed)
np.random.seed(seed)
torch.backends.cudnn.benchmark =... | StarcoderdataPython |
9701037 | <gh_stars>1-10
#!/usr/bin/env python
from datetime import date, timedelta
from django import template
from eventapp.models import Event
register = template.Library()
from datetime import date, timedelta
def get_last_day_of_month(year, month):
if (month == 12):
year += 1
month = 1
else:
... | StarcoderdataPython |
1778476 | '''
Search for fixed points in vicinity of a plane wave.
args: k1, k2 - wave numbers
===Optimization method discussion===
Use now - `lm` with non-zero starting phase; If it fails - switch to other methods
`hybr` - NOT OK: strange jump and breaks my solve_cycle
'lm' - OK if start with non-zero mean phase
'broyden1' ... | StarcoderdataPython |
3402911 | <reponame>lazy-labs/star_resty<filename>star_resty/inject.py<gh_stars>1-10
import operator
from typing import TypeVar, Type, Optional, Generic
from star_resty import Method
__all__ = ('attr',)
T = TypeVar('T')
class InjectAttr(Generic[T]):
__slots__ = ('_func',)
def __init__(self, name=None):
if n... | StarcoderdataPython |
1903983 | # Copyright 2020 Google LLC. 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 applicable law or a... | StarcoderdataPython |
306433 | """Constants."""
import jmespath
PROJECT_NAME = "flake8-nitpick"
ERROR_PREFIX = "NIP"
LOG_ROOT = PROJECT_NAME.replace("-", ".")
TOML_EXTENSION = ".toml"
NITPICK_STYLE_TOML = f"nitpick-style{TOML_EXTENSION}"
DEFAULT_NITPICK_STYLE_URL = f"https://raw.githubusercontent.com/andreoliwa/flake8-nitpick/master/{NITPICK_STYLE_... | StarcoderdataPython |
276822 | <filename>utils/utils.py
import torch
import csv
import numpy as np
def encode_onehot(labels, n_classes):
onehot = torch.FloatTensor(labels.size()[0], n_classes)
labels = labels.data
if labels.is_cuda:
onehot = onehot.cuda()
onehot.zero_()
onehot.scatter_(1, labels.view(-1, 1), 1)
retu... | StarcoderdataPython |
1937858 | <filename>13_module_advanced/04_json/01_json.py
# 1)把python中的字典或者列表,转化为json字符串
# 2)前端返回的json字符串,转换为Python中的字典
import json
dic = {'id': 1, 'name':'我的天哪这么好玩', 'usertype': 0}
s = json.dumps(dic, ensure_ascii=False)
# s = json.dumps(dic) #json处理中文 不用ascii
print(s)
print(type(s))
s = '{"id":1, "name":"我的天哪这么好玩","usertype":... | StarcoderdataPython |
1891402 | <filename>myy/myapp/urls.py
from django.urls import path
from myapp import views
app_name='myapp'
urlpatterns=[
path('',views.hello),
path('add',views.add)
] | StarcoderdataPython |
122939 | <reponame>ChristosChristofidis/h2o-3
import h2o
import sys, os
def demo(func=None, interactive=True, echo=True, test=False):
"""
H2O built-in demo facility
:param func: A string that identifies the h2o python function to demonstrate.
:param interactive: If True, the user will be prompted to continue t... | StarcoderdataPython |
12859073 | # Copyright (c) 2020 Intel Corporation.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, ... | StarcoderdataPython |
1738885 | <filename>tf_ops/grouping/tf_grouping_op_test.py
import tensorflow as tf
import numpy as np
from tf_grouping import query_ball_point, query_ball_point2, group_point
from scipy.spatial.distance import cdist
class GroupPointTest(tf.test.TestCase):
def test(self):
pass
def test_grad(self):
with ... | StarcoderdataPython |
3594221 | # encoding=utf-8
import os
import numpy as np
from Moldata import Moldata
from Reaction import Reaction
import matplotlib.pyplot as plt
def shermo(
input,
Temp=300.0,
sclZPE=1.0,
sclHeat=1.0,
sclS=1.0,
E='N/A',
shermo_path='Shermo'
):
if E=='N/A':
comman... | StarcoderdataPython |
6496539 | <filename>userena/forms.py<gh_stars>10-100
import random
from collections import OrderedDict
from hashlib import sha1
from django import forms
from django.contrib.auth import authenticate
from django.contrib.auth import get_user_model
from django.utils.translation import gettext_lazy as _
from userena import settings... | StarcoderdataPython |
5073889 | <gh_stars>0
import numpy as np
from jax import numpy as jnp
from jax import jit, grad, hessian, vmap, random
from jax.example_libraries import optimizers, stax
from jax.example_libraries.stax import (Dense, Tanh)
import paddlescience as psci
import time
def Network(num_outs, hiden_size):
return stax.serial(
... | StarcoderdataPython |
103126 | import re
from typing import Optional
class BaseModel:
r"""
The Base Class for Model objects.
.. container:: operations
.. describe:: x == y
Checks if two models have the same slug.
.. describe:: x != y
Checks if two models do not have the same slug.
.... | StarcoderdataPython |
4855433 | <reponame>KUTuaNithid/connect4Nithid<gh_stars>10-100
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Aug 12 12:48:21 2018
@author: Arpit
"""
import logging
def setup_logger(name, log_file, level=logging.INFO):
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
handler = ... | StarcoderdataPython |
5095627 | # encoding=utf8
from niapy.algorithms.basic import DifferentialEvolution, DynNpDifferentialEvolution, AgingNpDifferentialEvolution, \
MultiStrategyDifferentialEvolution, DynNpMultiStrategyDifferentialEvolution
from niapy.algorithms.basic.de import cross_rand1, cross_rand2, cross_best1, cross_best2, cross_curr2rand... | StarcoderdataPython |
11374368 | # -*- coding: utf-8 -*-
"""
@author:XuMing<<EMAIL>>
@description:
"""
from text2vec import Similarity
a = '湖北人爱吃鱼'
b = '甘肃人不爱吃鱼'
ss = Similarity(embedding_type='w2v')
ss.get_score(a, b)
print(ss.model.info())
ss = Similarity(embedding_type='bert')
ss.get_score(a, b)
print(ss.model.info())
| StarcoderdataPython |
3277626 | <gh_stars>1000+
from __future__ import division, print_function, absolute_import
import scipy.special as sc
import numpy as np
from numpy.testing import assert_, assert_equal, assert_allclose
def test_zeta():
assert_allclose(sc.zeta(2,2), np.pi**2/6 - 1, rtol=1e-12)
def test_zeta_1arg():
assert_allclose(sc... | StarcoderdataPython |
3340296 | class ChannelTransactionHistory:
def __init__(self, order_id, amount, currency, type, address, recipient, signature, org_id, group_id,
request_parameters, transaction_hash,
status):
self._order_id = order_id
self._amount = amount
self._currency = currency
... | StarcoderdataPython |
144214 | from os import path
from pony.orm.core import db_session
from tornado.web import StaticFileHandler, url, Application
from grepopla.controllers.PlayerController import PlayerController
from grepopla.controllers.IndexController import IndexController
from grepopla.settings import PRODUCTION
app_params = [
url(r'/... | StarcoderdataPython |
8081364 | import doctest
import math
import os
import random
import sklearn
import pandas as pd
import numpy as np
from datetime import timedelta
from sklearn.utils.estimator_checks import check_transformer_general, check_transformers_unfitted
from unittest2 import TestSuite, TextTestRunner, TestCase # or `from unittest import .... | StarcoderdataPython |
12863583 | '''
molecool.io package
configure access to subpackage functions
'''
from .pdb import open_pdb
from .xyz import open_xyz, write_xyz
| StarcoderdataPython |
92627 | <reponame>brownaa/wagtail
from django.contrib.auth import get_user_model
from django.test import TestCase
from wagtail.core.models import Comment, Page
class CommentTestingUtils:
def setUp(self):
self.page = Page.objects.get(title="Welcome to the Wagtail test site!")
self.revision_1 = self.page.s... | StarcoderdataPython |
1814529 | # ******************************************************************************
# Copyright 2017-2018 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.apa... | StarcoderdataPython |
392941 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @author: x.huang
# @date:29/05/19
import time
from pypay import err
from pypay.gateways.wechat import WechatPay
class PosPayImpl(WechatPay):
@staticmethod
def get_trade_type():
return 'MICROPAY'
def pay(self, config_biz: dict):
# todo som... | StarcoderdataPython |
259263 | from django.core.validators import RegexValidator
zip_validate = RegexValidator(r'^[0-9]*$', 'Please enter valid zip code.')
phone_validate = RegexValidator(r'^\s*\d{5}-\d{5}\s*$',
'Please enter valid phone number. Phone number is allowed in following '
... | StarcoderdataPython |
11323206 | ################################################################################
#
# Copyright (c) 2009 The MadGraph5_aMC@NLO Development team and Contributors
#
# This file is a part of the MadGraph5_aMC@NLO project, an application which
# automatically generates Feynman diagrams and matrix elements for arbitrary
# hi... | StarcoderdataPython |
11282503 | import collections
#from . import pyheclib
import .pyheclib
import pandas as pd
import numpy as np
import os
import re
import time
import warnings
import logging
from datetime import datetime, timedelta
from calendar import monthrange
from dateutil.parser import parse
# some static functions
DATE_FMT_ST... | StarcoderdataPython |
6418572 | <reponame>VITA-Group/Large_Scale_GCN_Benchmarking
import gc
import json
import os
import random
from datetime import datetime
import numpy as np
import torch
from options.base_options import BaseOptions
from trainer import trainer
from utils import print_args
def set_seed(args):
torch.backends.cudnn.determinist... | StarcoderdataPython |
8160566 | from setuptools import setup
setup(name='color_naming',
version='0.1',
description='Implementation of ',
url='',
author='<NAME>',
author_email='<EMAIL>',
license='MIT',
packages=['color_naming'],
install_requires=['numpy',],
include_package_data=True,
package... | StarcoderdataPython |
6415078 | <gh_stars>1-10
from __future__ import with_statement
from fabric.api import local
import env
from tasks import deploy
| StarcoderdataPython |
3589942 |
# S60 contacts restore - <NAME> 2010 - Public Domain - no warranty
# Where to find history:
# on GitHub at https://github.com/ssb22/s60-utils
# and on GitLab at https://gitlab.com/ssb22/s60-utils
# and on BitBucket https://bitbucket.org/ssb22/s60-utils
# and at https://gitlab.developers.cam.ac.uk/ssb22/s60-utils
# an... | StarcoderdataPython |
4846319 | # -*- coding: utf-8 -*-
from brewtils.schemas import UserCreateSchema, UserListSchema, UserSchema
from beer_garden.api.http.base_handler import BaseHandler
from beer_garden.api.http.handlers import AuthorizationHandler
from beer_garden.db.mongo.models import User
from beer_garden.user import create_user, update_user
... | StarcoderdataPython |
9743619 | # coding: utf-8
from __future__ import absolute_import
from datetime import date, datetime # noqa: F401
from typing import List, Dict # noqa: F401
from odahuflow.sdk.models.base_model_ import Model
from odahuflow.sdk.models import util
class AuthConfig(Model):
"""NOTE: This class is auto generated by the swa... | StarcoderdataPython |
1939259 | import psycopg2 as db # al hacer esto no hay q escribir mas psycopg2
conexion = db.connect(user='postgres',
password='<PASSWORD>',
host='127.0.0.1',
port='5432',
database='test_db')
# variable para el cursor
cursor = conexion.cur... | StarcoderdataPython |
91882 | <reponame>l0l00l000/C3AE<gh_stars>1-10
#coding=utf-8
import os
import math
import pandas as pd
import tensorflow as tf
import numpy as np
import logging
from sklearn.model_selection import train_test_split
'''
基础的数据处理基类:
现在输入的数据必须满足pandas的输入格式, 各自实现输入对应接口
输出统一成pandas的feather格式
主要是方便标注后台的数据能够... | StarcoderdataPython |
6625131 | <reponame>fatihCinarKrtg/zulip
import logging
import secrets
import urllib
from functools import wraps
from typing import Any, Dict, List, Mapping, Optional, cast
from urllib.parse import urlencode
import jwt
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from django.conf import settings
from django.co... | StarcoderdataPython |
3403975 | <filename>NPTFit/set_dirs.py
###############################################################################
# set_dirs.py
###############################################################################
#
# Define and create the directories required for the scan.
#
######################################################... | StarcoderdataPython |
11281013 | """This module contains the general information for LstorageDasScsiLun ManagedObject."""
from ...ucsmo import ManagedObject
from ...ucscoremeta import MoPropertyMeta, MoMeta
from ...ucsmeta import VersionMeta
class LstorageDasScsiLunConsts:
ADMIN_STATE_OFFLINE = "offline"
ADMIN_STATE_ONLINE = "online"
AD... | StarcoderdataPython |
268221 | <filename>geg.py
#! /usr/bin/env python
def fitness_function(bin_string):
from expression import eval_bin_string
val = eval_bin_string(bin_string)
if val == required_int:
ret = float("inf")
else:
ret = 1 / abs(float(val - required_int))
return ret
if __name__ == '__main__':
im... | StarcoderdataPython |
5139077 | <filename>tests/test_metrics.py<gh_stars>1-10
#!/usr/bin/env python
"""Tests for `lesion_metrics` package."""
import builtins
import pathlib
import medio.image as mioi
import pytest
import lesion_metrics.metrics as lmm
import lesion_metrics.typing as lmt
import lesion_metrics.volume as lmv
backends = ["numpy"]
try:... | StarcoderdataPython |
12846976 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#Author: <NAME>
#Email: <EMAIL>
#For licensing see the LICENSE file in the top level directory.
import unittest, os, sys, base64, itertools, random, time, copy
import copy, collections
from random import randint, seed, shuffle
from zss import compare
from zss.test_tree im... | StarcoderdataPython |
1827201 | <filename>general/slicing.py
import string
a_str = "Monty Python's Flying Circus"
print "example string:", a_str
#last nth element: seq[-n]
print "last element:", a_str[-1]
print "second to last element", a_str[-2]
#nth element through end: seq[(n-1):]
print "third element through end:", a_str[2:]
#last n elements... | StarcoderdataPython |
4967853 |
# coding: utf-8
import QuantLib as ql
QL_USE_INDEXED_COUPON = False
tradeDate = ql.Date(21,5,2009)
ql.Settings.instance().setEvaluationDate(tradeDate)
dep_tenors = [1,2,3,6,9,12]
dep_quotes = [0.003081,0.005525,0.007163,0.012413,0.014,0.015488]
isdaRateHelpers = [ql.DepositRateHelper(dep_quotes[i],
... | StarcoderdataPython |
9790216 | from __future__ import absolute_import
import six
from django.db.models import Q
from sentry.api.bases.organization import (OrganizationEndpoint, OrganizationPermission)
from sentry.api.paginator import OffsetPaginator
from sentry.api.serializers import serialize
from sentry.models import OrganizationMember
from sent... | StarcoderdataPython |
11224267 | #!/usr/bin/env python
"""
Copyright 2014 Wordnik, 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 applica... | StarcoderdataPython |
1925078 | from core.models import Socio
from django.db import models
class File(models.Model):
author: Socio = models.ForeignKey(
'core.Socio', on_delete=models.CASCADE, blank=True, null=True)
title: str = models.CharField(max_length=100, default='Untitled')
content: str = models.TextField()
url = model... | StarcoderdataPython |
219819 | <gh_stars>0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import numpy as np
import pandas as pd
from ..IO import out_results
from ..IO import pkl_data
from ..IO import read_input as rin
def initialize(stat, rslt_data):
# ---------- log
print('\n# ---------- Initialize... | StarcoderdataPython |
249144 | <gh_stars>10-100
import pytest
import numpy as np
from collections import OrderedDict
import contextlib
import arim.geometry as g
from arim import Probe, ExaminationObject, Material, Time, Frame
import arim.im.das as das
import arim.im.tfm
def _random_uniform(dtype, low=0.0, high=1.0, size=None):
z = np.zeros(si... | StarcoderdataPython |
3447374 | <reponame>lalusvipi/siptrackweb
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template import Context, loader
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from siptracklib.utils import object_by_attribute
import siptracklib.... | StarcoderdataPython |
1709672 | import secrets
import deal
deal.activate()
from .candidate import Candidate
from .charspace import Charspace
from .constants import MAX_PASSWORD_LENGTH
from .exceptions import DumbValueError
@deal.safe
@deal.has("random")
@deal.pre(
validator=lambda _: _.length <= MAX_PASSWORD_LENGTH,
exception=DumbValueEr... | StarcoderdataPython |
4922734 | from setupext import find_namespace_packages, setup
# We cannot directly import matplotlib if `MPLCURSORS` is set because
# `sys.path` is not correctly set yet.
#
# The loading of `matplotlib.figure` does not go through the path entry finder
# because it is a submodule, so we must use a metapath finder instead.
@set... | StarcoderdataPython |
1917501 | <reponame>jurajHasik/peps-torch<gh_stars>10-100
import torch
import config as cfg
from ctm.generic.env import ENV
from ctm.generic import rdm
from ctm.pess_kagome import rdm_kagome
from ctm.generic import corrf
from math import sqrt
from numpy import exp
import itertools
def _cast_to_real(t, check=True, imag_eps=1.0e-... | StarcoderdataPython |
3563682 | <reponame>cfergeau/cluster-node-tuning-operator
from . import interfaces
from . import controller
from . import dbus_exporter as dbus
def export(*args, **kwargs):
"""Decorator, use to mark exportable methods."""
def wrapper(method):
method.export_params = [ args, kwargs ]
return method
return wrapper
def signa... | StarcoderdataPython |
3367174 | ##-----------------------------------------------------------
## Copyright 2020 Science and Technologies Facilities Council
## Licensed under the MIT License
## Author <NAME>, STFC Hartree Centre
import h5py
import numpy as np
import argparse
pos_x = []
pos_y = []
pos_z = []
cutoff = []
interactions = []
ids = []
co... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.