id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
6512722 | from pyspark import SparkContext, SQLContext
import pyspark.sql.functions as sql
import pyspark.sql.types as types
sc = SparkContext(appName="SmallIDB")
sqlContext = SQLContext(sc)
idb_df_version = "20161119"
idb_df = sqlContext.read.load("/guoda/data/idigbio-{0}.parquet"
.format(idb_df... | StarcoderdataPython |
8196355 | <gh_stars>1-10
import os
import tempfile
import unittest
from unittest import mock
from dbt import linker
try:
from queue import Empty
except ImportError:
from Queue import Empty
def _mock_manifest(nodes):
return mock.MagicMock(nodes={
n: mock.MagicMock(unique_id=n) for n in nodes
})
class L... | StarcoderdataPython |
1631628 | <filename>pyblaze/nn/modules/__init__.py
from .distribution import TransformedNormalLoss, TransformedGmmLoss
from .gp import GradientPenalty
from .lstm import StackedLSTM, StackedLSTMCell
from .made import MADE
from .normalizing import NormalizingFlow
from .residual import LinearResidual
from .transforms import AffineT... | StarcoderdataPython |
1735039 | from django.db import models
from django.contrib.auth.models import User, AbstractBaseUser, PermissionsMixin, BaseUserManager
from django.utils.http import urlquote
from django.utils.text import slugify
import datetime
import pytz
# Create your models here.
class AuthorManager(BaseUserManager):
def _create_us... | StarcoderdataPython |
96537 | <filename>train.py
import tensorflow as tf
import numpy as np
np.random.seed(1234)
import os
import pickle
from importlib import import_module
from log import Logger
from batching import *
tf.flags.DEFINE_string("data_dir", "./data", "The data dir.")
tf.flags.DEFINE_string("sub_dir", "WikiPeople", "The sub data dir.")... | StarcoderdataPython |
9798350 | <filename>kill_jobs.py
#!/usr/bin/env python3
# Copyright 2020, <NAME>
#
# 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 b... | StarcoderdataPython |
3371232 | import os
import glob
import random
import time
import json
from datetime import datetime
from statistics import mean
import argparse
from PIL import Image
import numpy as np
from scipy.io import loadmat
import cv2
import torch
import torch.optim as optim
from torch.autograd import Variable
import torch.nn.functional... | StarcoderdataPython |
3510072 | import cv2
import colorsys
import numpy as np
import pandas as pd
### get the images and scale them by 1/10 to get the of a 10x10 area ###
ImgL = cv2.imread('image_1.png')
resizeImgL = cv2.resize(ImgL, (0,0), fx=0.1, fy=0.1)
ImgR = cv2.imread('image_2.png')
resizeImgR = cv2.resize(ImgR, (0,0), fx=0.1, fy=0.1)
ImgS = c... | StarcoderdataPython |
1603843 | import numpy as np
def _recall_values(labels, x_absolute=False, y_absolute=False):
n_docs = len(labels)
n_pos_docs = sum(labels)
x = np.arange(1, n_docs + 1)
recall = np.cumsum(labels)
if not x_absolute:
x = x / n_docs
if y_absolute:
y = recall
else:
y = recall /... | StarcoderdataPython |
8086665 | <filename>model/encoders.py
import torch
import torch.nn as nn
from model.blocks import (BridgeConnection, LayerStack,
PositionwiseFeedForward, ResidualConnection, clone)
from model.multihead_attention import MultiheadedAttention
class EncoderLayer(nn.Module):
def __init__(self, d_... | StarcoderdataPython |
3201880 | # Stock data visualization dashboard
# Awesome-quent list of packages for fin data: https://github.com/wilsonfreitas/awesome-quant#data-sources
import os
import pandas as pd
import matplotlib.pyplot as plt
import pandas_datareader as web
import finnhub
from dateutil import parser
import datetime as dt
# Dash imports
... | StarcoderdataPython |
4811465 | import profiles
from pointSource import PixelizedModel as PM, GaussianModel as GM
from math import pi
def cnts2mag(cnts,zp):
from math import log10
return -2.5*log10(cnts) + zp
_SersicPars = [['amp','n','pa','q','re','x','y'],
['logamp','n','pa','q','re','x','y'],
['amp','n','q... | StarcoderdataPython |
8015242 | # -*- coding: utf-8 -*-
#
# python_common/mysql_utf8.py
#
# Apr/21/2010
#
# --------------------------------------------------------
def mysql_utf8_proc (cursor):
sql_str="SET NAMES utf8"
cursor.execute (sql_str)
#
# --------------------------------------------------------
| StarcoderdataPython |
3238598 | #-*-coding-utf-8-*-
import logging
from datetime import datetime
from rest_framework import generics
from rest_framework import status
from rest_framework.response import Response
from rest_framework.decorators import api_view
from django.conf import settings
from django.contrib.auth.models import User
from django.u... | StarcoderdataPython |
375343 | '''
Created 01.10.2020
@author: ED
'''
from abc import ABC
class commutation_selection_ap_feature(ABC):
def __init__(self, parent):
self._motorInterface = parent
def setMode(self, mode):
self._motorInterface.setAxisParameter(self._motorInterface.AP.CommutationMode, mode)
d... | StarcoderdataPython |
5052299 | <reponame>sedders123/zoloto<gh_stars>0
from pathlib import Path
from cv2 import VideoCapture, imread
from .base import BaseCamera
class ImageFileCamera(BaseCamera):
def __init__(self, image_path: Path, **kwargs):
self.image_path = image_path
super().__init__(**kwargs)
def capture_frame(self... | StarcoderdataPython |
5011517 | import pytest
import eth_account # https://github.com/ethereum/eth-account
from brownie.network.account import Accounts # https://github.com/eth-brownie
ADDRESS_LENGTH = 42
ADDRESS_PREFIX = '0x'
DEFAULT_PATH = "m/44'/60'/0'/0/0"
MNEMONIC_NUM_WORDS = 12
ACCOUNT_MNEMONIC = 'candy maple cake sugar pudding... | StarcoderdataPython |
5143126 |
'''
请定义一个队列并实现函数max得到队列里的最大值,要求函数max、push_back和pop_front 的时间复杂度都是0(1)。
'''
import queue
class MaxQueue:
def __init__(self):
self.deque = queue.deque()
def max_value(self):
return max(self.deque) if self.deque else -1
def push_back(self, value):
self.deque.append(value)
def pop_front(self):
return se... | StarcoderdataPython |
1717256 | <reponame>dibondar/PyPhotonicReagents
"""
Calibrate shaper
"""
# Add main directory to enable imports
if __name__ == '__main__' :
import os
os.sys.path.append(os.path.abspath('..'))
import wx, h5py, time
import numpy as np
from scipy.interpolate import pchip_interpolate, PchipInterpolator
from scipy.optimize impor... | StarcoderdataPython |
5039075 | import os
import shutil
def apply_license(license):
license_file = get_license_file(license)
license_folder = ".licenses"
# Copy the chosen license file to root
shutil.copy(os.path.join(license_folder, license_file), "LICENSE")
# Remove the license folder
shutil.rmtree(license_folder)
def ... | StarcoderdataPython |
11344725 | <reponame>ckamtsikis/cmssw<gh_stars>100-1000
import FWCore.ParameterSet.Config as cms
import CalibTracker.SiStripESProducers.SiStripQualityESProducer_cfi
ssqcabling = CalibTracker.SiStripESProducers.SiStripQualityESProducer_cfi.siStripQualityESProducer.clone()
ssqcabling.appendToDataLabel = cms.string("onlyCabling")
... | StarcoderdataPython |
6436377 | """Async Driver Method."""
import inspect
import os
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor, as_completed
from ...app import App
from ...contracts import QueueContract
from ...drivers import BaseQueueDriver
from ...exceptions import QueueException
from ...helpers import HasColoredComman... | StarcoderdataPython |
1766237 | #!/usr/bin/env python3
"""Tests for the ClientSocket class."""
import unittest
from ibapipy.core.client_socket import ClientSocket
from multiprocessing import Queue
TEST_ACCOUNT_NAME = 'DU109588'
class ClientSocketTests(unittest.TestCase):
"""Test cases for the ClientSocket class."""
def test_constructor(s... | StarcoderdataPython |
11247571 | <gh_stars>1-10
import re
from typing import NoReturn, Optional, TypeVar, Union
import unittest.mock as mock
import discord
__all__ = (
'MagicMock_',
'get_embeds', 'get_contents',
'assert_success', 'assert_warning', 'assert_error', 'assert_info',
'assert_no_reply', 'assert_one_if_list', 'assert_in', 'a... | StarcoderdataPython |
3232601 | <reponame>bkryza/atlssncli
# -*- coding: utf-8 -*-
#
# Copyright 2019 <NAME> <<EMAIL>>
#
# 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
#
# Un... | StarcoderdataPython |
3250551 | <filename>tests/test_LCSQ.py
import algorithms.LCSQ as algo
import unittest
import os
script_dir = os.path.dirname(__file__) # absolute dir the script is in
class TestAlgo(unittest.TestCase):
def test_LCSQ_1(self):
"""
Rosalind Test
:return:
"""
sample_answer = 'AACTTG'... | StarcoderdataPython |
12836658 | <reponame>Podcastindex-org/podping.cloud<filename>hive-watcher/simple-watcher.py
# simple-watcher.py
#
# Simple version of Hive Podping watcher - no options, just runs
# The only external library needed is "beem" - pip install beem
# Beem is the official Hive accessing library for Python.
#
# Version 1.1
from datetime... | StarcoderdataPython |
11279142 | import gym
import numpy as np
import random
from keras.layers import Dense, InputLayer
from keras.models import Sequential
from collections import deque
from keras.optimizers import Adam, SGD
model = Sequential()
model.add(InputLayer(batch_input_shape=(None, 4)))
model.add(Dense(10, activation='relu'))
model.add(Den... | StarcoderdataPython |
9697366 | from os import path
import glob
import json
from stix_shifter.stix_translation.src.modules.base.base_data_mapper import BaseDataMapper
class DataMapper(BaseDataMapper):
def __init__(self, options):
mapping_json = options['mapping'] if 'mapping' in options else {}
basepath = path.dirname(__file__)... | StarcoderdataPython |
3588687 | <filename>src/sql_queries.py
# tables name
TABLES_NAME = """
SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE='BASE TABLE'
"""
# get columns name
COLUMNS_NAME = """
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = ?
"""
# get columns auto increment
COLUMNS... | StarcoderdataPython |
327755 | from .models import ImagerProfile
from django.forms import ModelForm
class ProfileEditForm(ModelForm):
"""Instantiate user profile edit forms."""
class Meta:
model = ImagerProfile
fields = [
'bio',
'phone',
'location',
'website',
'fee... | StarcoderdataPython |
5191198 | #!/usr/bin/env python3
#############################################
# #
# Test module for Edge2.py #
# Author: <NAME> #
# Date: 06/Apr/2019 #
# Modified: 07/Nov/2019 #
# ... | StarcoderdataPython |
3333754 | import glob
import logging
import os
import shutil
import subprocess
from urlparse import urlparse
from bd2k.util.exceptions import require
from toil.lib.docker import dockerCall
_log = logging.getLogger(__name__)
def download_url(job, url, work_dir='.', name=None, s3_key_path=None, cghub_key_path=None):
"""
... | StarcoderdataPython |
5188988 | <reponame>rdzeldenrust/Honeybee<filename>src/Honeybee_Radiance Metal Material By Color.py
# By <NAME>
# <EMAIL>
# Honeybee started by <NAME> is licensed
# under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
"""
Radiance Metal Material By Color
Create a Standard Radiance Metal Material. Many thanks t... | StarcoderdataPython |
1637987 | import os
file_chars_reference = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
def create_letters_text_files():
try:
# Obtenemos la ruta absoluta del directorio en el que estamos trabajando
script_directory = os.path.dirname(__file__)
for letter in file_chars_reference:
file_path = f"{script_d... | StarcoderdataPython |
235210 | <filename>src/stop_words.py
import nltk
from nltk.corpus import stopwords
NLTK_MAPPING = { "en": "english", "pt": "portuguese" }
custom_stop_words = {}
# Portuguese
custom_stop_words['pt'] = []
# English
custom_stop_words['en'] = [
"app",
"good",
"excellent",
"awesome",
"please",
"they",
... | StarcoderdataPython |
4840507 | import sys
from getpass import getpass
from json import dumps
from typing import Any, Dict, List, Optional, TextIO, Union
from streamlink.plugin.plugin import UserInputRequester
from streamlink_cli.utils import JSONEncoder
class ConsoleUserInputRequester(UserInputRequester):
"""
Request input from the user o... | StarcoderdataPython |
8165727 | <filename>app/user_api.py
from flask import abort, request, jsonify, url_for
from app import app, database
from app.api_auth import token_auth
from app.api_tools import get_single_json_entity
from app.errors import bad_request, error_response
from app.models import Users
A_USER_QUERY_TEMPLATE = """
SELECT users.id F... | StarcoderdataPython |
3582461 | <filename>steambird/boecie/forms.py<gh_stars>0
"""
This module contains the Django Form classes which are used in the Boecie views.
"""
from enum import Enum, auto
from django import forms
from django.forms import HiddenInput, MultipleHiddenInput
from django.urls import reverse_lazy
# noinspection PyUnresolvedReferen... | StarcoderdataPython |
1787661 | # -*- coding: utf-8 -*-
"""Utilities for ComPath."""
import logging
from typing import Collection, Mapping
import pandas as pd
__all__ = [
'write_dict',
'dict_to_df',
]
logger = logging.getLogger(__name__)
def write_dict(data: Mapping[str, Collection[str]], path: str) -> None:
"""Write a dictionary t... | StarcoderdataPython |
12822035 | # Generated by Django 3.0.5 on 2020-04-16 15:03
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('jobs', '0013_auto_20200415_0345'),
]
operations = [
migrations.AlterField(
model_name='applicant',
name='applicant_s... | StarcoderdataPython |
8148131 | <gh_stars>0
def get_data():
data = []
data_file = open("data.txt")
for val in data_file:
data.append(val.strip())
data_file.close()
print(f"read {len(data)} lines\n")
return data
def check_data(data):
return None
def main():
data = get_data()
check_data(data)
main(... | StarcoderdataPython |
11213023 | <reponame>kaitlin/afsbirez
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('sbirez', '0029_auto_20150804_2055'),
]
operations = [
migrations... | StarcoderdataPython |
8192148 |
import numpy as np
from text_selection.kld.kld_iterator import get_minimun_indices
def test_one_entry__returns_zero():
array = np.array([1.2], dtype=np.float64)
min_value, min_indices = get_minimun_indices(array)
assert min_value == 1.2
np.testing.assert_array_equal(min_indices, np.array([0]))
def test_two... | StarcoderdataPython |
5139028 | from django.shortcuts import render
from django.contrib.auth.forms import UserCreationForm
from django.urls import reverse_lazy
from django.views import generic
class SignUp(generic.CreateView): # generic view default django
form_class = UserCreationForm # form default
success_url = reverse_lazy('login') # li... | StarcoderdataPython |
12814792 | from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
| StarcoderdataPython |
8012705 | from requests import get
from enum import Enum
def all_node_conected_in_node_url(node_url: str = None) -> dict:
if node_url == None:
full_url = f'{Node.mainnet_url.value}/peers/all'
else:
full_url = f'{node_url}/peers/all' # You have pass your node url with https or other contents
res... | StarcoderdataPython |
3347053 | import numpy as np
import torch
import torch.nn.functional as F
from .strategy import Strategy
from tqdm import tqdm
class AdversarialBIM(Strategy):
def __init__(self, dataset, net, eps=0.05):
super(AdversarialBIM, self).__init__(dataset, net)
self.eps = eps
def cal_dis(self, x):
nx = ... | StarcoderdataPython |
30090 | """Models and utilities for processing SMIRNOFF data."""
import abc
import copy
import functools
from collections import defaultdict
from typing import (
TYPE_CHECKING,
Any,
DefaultDict,
Dict,
List,
Tuple,
Type,
TypeVar,
Union,
)
import numpy as np
from openff.toolkit.topology impor... | StarcoderdataPython |
1966156 | # Copyright (c) 2022 Mira Geoscience Ltd.
#
# This file is part of geoapps.
#
# geoapps is distributed under the terms and conditions of the MIT License
# (see LICENSE file at the root of this source code package).
from copy import deepcopy
import numpy as np
from geoh5py.objects import Points
from geoh5py.works... | StarcoderdataPython |
3531508 | <reponame>s-broda/nmt
from __future__ import absolute_import, division, print_function, unicode_literals
import tensorflow as tf
import unicodedata
import re
import io
import os
# Converts the unicode file to ascii
def unicode_to_ascii(s):
return ''.join(c for c in unicodedata.normalize('NFD', s)
if unicoded... | StarcoderdataPython |
399488 | <gh_stars>1-10
from django.db import models
from django.urls import reverse_lazy
from django.utils.text import slugify
from django.utils.translation import ugettext_lazy as _
from projects.models import Attribute
class FooterLink(models.Model):
link_text = models.CharField(max_length=255, verbose_name=_("link te... | StarcoderdataPython |
5084431 | from django.contrib.auth import get_user_model
import pytest
from rest_framework import status
from quiz.users.views import AuthViewSet
User = get_user_model()
pytestmark = pytest.mark.django_db
def test_signup_status_created(user_payload, rf, ct):
"""Test vaild user payload may sinup with status code 201.""... | StarcoderdataPython |
8187693 | # encoding: utf-8
# module _sha
# from (built-in)
# by generator 1.147
# no doc
# no imports
# Variables with simple values
blocksize = 1
digestsize = 20
digest_size = 20
# functions
def new(*args, **kwargs): # real signature unknown
"""
Return a new SHA hashing object. An optional string argument
ma... | StarcoderdataPython |
3465834 | <gh_stars>0
name = 'ru_sent_tokenize'
from .tokenizer import ru_sent_tokenize, PAIRED_SHORTENINGS, SHORTENINGS, JOINING_SHORTENINGS
| StarcoderdataPython |
6533357 | # Given a list of rules, find how many bag colours can contain one shiny gold bag
# Assume all colour descriptors contain 2 words (e.g., "mirrored chartreuse")
# pattern = re.compile('([a-z]+ [a-z]+) bag')
# For each rule, get colours = pattern.findall(rule) => returns array
# First colour in array = outermost colour;... | StarcoderdataPython |
1648342 | <reponame>liaison/LeetCode
class Solution:
def findShortestSubArray(self, nums: List[int]) -> int:
num_range_dict = {}
max_count = 0
for index, num in enumerate(nums):
if num in num_range_dict:
start, end, count = num_range_dict[num]
new_count = ... | StarcoderdataPython |
11206849 | <reponame>GersbachKa/tabletop_pta
from __future__ import division, print_function
import numpy as np
def zeropadtimeseries(x, T):
'''
zero pad the time-series x by duration T
to nearest power of 2
'''
######################
# special case: no zero-padding if T=0
if T==0:
y = x
... | StarcoderdataPython |
3433277 | # -*- coding: utf-8 -*-
"""hypertext transfer protocol (HTTP/2)
:mod:`pcapkit.protocols.application.httpv2` contains
:class:`~pcapkit.protocols.application.httpv2.HTTPv2`
only, which implements extractor for Hypertext Transfer
Protocol (HTTP/2) [*]_, whose structure is described as
below:
======= ========= ==========... | StarcoderdataPython |
207649 | <gh_stars>1-10
"""Convolutional Layer implementation."""
import logging
import numpy as np
import tensorflow as tf
from tensorflow.python.keras import initializers
from tensorflow.python.keras.utils import conv_utils
import tf_encrypted as tfe
from tf_encrypted.keras.engine import Layer
from tf_encrypted.keras import... | StarcoderdataPython |
155780 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2019 KuraLabs S.R.L
#
# 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 applicabl... | StarcoderdataPython |
1795778 | <filename>taxonomy/cgi-bin/browse.py
#!/usr/bin/python
# Brutally primitive reference taxonomy browser.
# Basically just a simple shim on the taxomachine 'taxon' method.
# Intended to be run as a CGI command, but it can be tested by running it
# directly from the shell; just set the environment QUERY_STRING to be
# th... | StarcoderdataPython |
1791377 | <gh_stars>0
# coding: utf8
#########################################################################
## This is a samples controller
## - index is the default action of any application
## - user is required for authentication and authorization
## - download is for downloading files uploaded in the db (does streaming)
... | StarcoderdataPython |
3448431 | <reponame>eswan18/remarker<filename>premark/presentation.py
import sys
from functools import reduce
from operator import add
from pathlib import Path
import logging
from typing import Union, List, Iterable, NamedTuple, Optional
from pkg_resources import resource_filename
from dataclasses import dataclass
from jinja2 i... | StarcoderdataPython |
3416551 | # encoding: utf-8
import re
import base64
from ..utils import int_or_none
from ..utilsEX import download_webPage_by_PYCURL
from ..extractor.common import InfoExtractor
from ..extractor.generic import GenericIE
class GoMoviesIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?(?:gomovies|gostream)\.\w+/film/[\w-... | StarcoderdataPython |
12817091 | from Drivers.ImageModelDriver import *
from Drivers.ImageDisplayDriver import *
from Drivers.ReadDriver import *
from PIL import Image
class ImageLesson2:
@staticmethod
def run():
# Загружаем фото c12-85v.xcr
loaded_image_c12_85v = ReadDriver.image_binary_read(
'lesson2/', 'c12-85... | StarcoderdataPython |
1646856 | <gh_stars>1-10
# coding=utf-8
"""Testing the NetworkBilling view.
Usage:
$ python manage.py test endagaweb.NetworkNotification
Copyright (c) 2016-present, Facebook, Inc.
All rights reserved.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree... | StarcoderdataPython |
6462719 | <reponame>utsw-bicf/gudmap_rbk.rna-seq
#!/usr/bin/env python3
import argparse
import pandas as pd
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument(
'-r', '--repRID', help="The replicate RID.", require... | StarcoderdataPython |
11308302 | from memory.space import Bank, Reserve, Allocate, Write
import instruction.asm as asm
class Steal:
def __init__(self, rom, args):
self.rom = rom
self.args = args
def enable_steal_chances_always(self):
#Always steal if the enemy has an item.
# If the enemy has both ra... | StarcoderdataPython |
3515729 | <filename>planet/scripts/tasks.py
# Copyright 2019 The PlaNet Authors. 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... | StarcoderdataPython |
3518214 | <reponame>devaos/sublime-remote<gh_stars>1-10
# -*- coding: utf-8 -*-
import sys
import unittest
import env
import mocks.sublime
sys.modules["sublime"] = mocks.sublime.MockSublime()
import remote.sublime_api as sublime_api
class TestSublimeHelperFunctions(unittest.TestCase):
def test_active_project_bad_args(sel... | StarcoderdataPython |
11381360 | <gh_stars>0
import numpy as np
from scipy.special import gamma
from skimage import color
class MLVMeasurement():
def __init__(self):
self.gam = np.linspace(0.2,10,9801)
def __estimateggdparam(self,vec):
gam = self.gam
r_gam = (gamma(1/gam)*gamma(3/gam))/((gamma(2/gam)) ** 2)
si... | StarcoderdataPython |
201031 | import Encoding
# import SPIMITOOL
def test_encoding():
gaps = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
encoder = Encoding.Encoding()
en_gamma_gaps = encoder.run(gaps, "g")
en_delta_gaps = encoder.run(gaps, "d")
print("gap gamma encode delta encode")
for i in gaps:
print(str(i) + " " ... | StarcoderdataPython |
155841 | <gh_stars>1-10
from time import sleep
loop = False
while not loop:
n1 = float(input('Primeira nota: '))
n2 = float(input('Segunda nota: '))
m = (n1 + n2) / 2
if n1 <= 10 and n2 <= 10:
print(f'Sua média foi de: {m}')
if m < 5:
print(f'\033[31mREPROVADO!!\033[31m\n')
... | StarcoderdataPython |
1711726 | #!/usr/bin/env python
import sys
from setuptools import find_packages, setup
setup(
name='kite.metrics',
version='0.1.0',
author='<NAME>.',
description='Kite Metrics',
packages=find_packages(),
install_requires=[
"jinja2>=2",
"PyYAML>=5",
"click>=7",
],
entry_poi... | StarcoderdataPython |
11222323 | """Console entrypoint for creating PCR primers"""
import argparse
import sys
from typing import List
from . import __version__, primers, Primer
from .primers import PRIMER_FMT
def run():
"""Entry point for console_scripts.
Create primers and log the results.
"""
args = parse_args(sys.argv[1:])... | StarcoderdataPython |
6612390 | <reponame>riihikallio/tsoha
from flask import render_template
from flask_login import login_required
from application import app
from application.reports.models import sales_by_category, sales_by_customer
@app.route("/reports/", methods=["GET"])
@login_required
def reports():
return render_template("reports/show... | StarcoderdataPython |
1867172 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import migrate_sql.operations
class Migration(migrations.Migration):
dependencies = [
('test_app', '0003_auto_20160108_0048'),
('test_app2', '0001_initial'),
]
operations = [
... | StarcoderdataPython |
4818627 | <reponame>guptav96/DeepRL<filename>examples.py
#######################################################################
# Copyright (C) 2017 <NAME>(<EMAIL>) #
# Permission given to modify the code as long as you keep this #
# declaration at the top #
###############... | StarcoderdataPython |
6447148 | <filename>aws-py-dynamicresource/mysql_dynamic_provider.py
# Copyright 2016-2020, Pulumi Corporation. All rights reserved.
import mysql.connector as connector
from mysql.connector import errorcode
from pulumi import Input, Output, ResourceOptions
from pulumi.dynamic import *
from typing import Any, Optional
import bi... | StarcoderdataPython |
1898817 | from __future__ import absolute_import
import os
import sys
from dateutil import parser
from threading import Thread
from anyjson import dumps, loads
from amqp.protocol import queue_declare_ok_t
from kombu.exceptions import ChannelError
from kombu.five import Empty, Queue
from kombu.log import get_logger
from kombu.... | StarcoderdataPython |
9742034 | <gh_stars>0
from django.apps import AppConfig
class DtConfig(AppConfig):
name = 'dt'
| StarcoderdataPython |
6542101 | __author__ = '<NAME>'
from renderchan.module import RenderChanModule
import subprocess
import os, sys
from distutils.version import StrictVersion
from xml.etree import ElementTree
class RenderChanOliveModule(RenderChanModule):
def __init__(self):
RenderChanModule.__init__(self)
self.conf[... | StarcoderdataPython |
12827626 | from django.core.management import call_command
from django.core.management.base import BaseCommand
from core.cli.mixins import CliInteractionMixin
from redmine import Redmine
class Command(BaseCommand, CliInteractionMixin):
help = "Syncronizes all data to Redmine instance."
def __init__(self, *args, **kwar... | StarcoderdataPython |
4894946 | <filename>tests/tree_xml_parser_note_processor_tests.py
from unittest import TestCase
from mock import patch
from regparser.test_utils.node_accessor import NodeAccessor
from regparser.test_utils.xml_builder import XMLBuilder
from regparser.tree.xml_parser import note_processor
class NoteProcessingTests(TestCase):
... | StarcoderdataPython |
3559777 | <gh_stars>1000+
# The major idea of the overall GNN model explanation
import argparse
import os
import dgl
import torch as th
import torch.nn as nn
import torch.nn.functional as F
from dgl import load_graphs
from models import dummy_gnn_model
from NodeExplainerModule import NodeExplainerModule
from utils_graph impor... | StarcoderdataPython |
4870658 | <filename>pyjpboatrace/utils/str2num.py
def str2num(s: str, typ: type, default_val=None):
''' string to number whose type is the type given as typ.
typ must be int, float or complex
Note: Failure of casting returns default_val
'''
if typ not in [int, float, complex]:
raise NotImplementedE... | StarcoderdataPython |
1723819 | from email.message import EmailMessage
import logging
from mailbox import MH
from operator import itemgetter
from pathlib import Path
from typing import List, Union
from mailbits import email2dict
import pytest
from outgoing import Sender, from_dict
from outgoing.senders.mailboxes import MHSender
@pytest.mark.paramet... | StarcoderdataPython |
4851939 | <reponame>shenwei0329/rdm-flasky<gh_stars>0
# -*- coding: utf-8 -*-
#
# 生成数据文件,并通过邮件发送
# ============================
# 2019.8.1 @Chengdu
#
from DataHandler import exceltools
import mongodb_class
mongo_db = mongodb_class.mongoDB()
line_number = 1
def write_title(_book, _titles):
_v = 0
for _t in _titl... | StarcoderdataPython |
5019702 | # Copyright 2018 Spotify AB. 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 ag... | StarcoderdataPython |
271987 | <filename>plugins/Weather.py
from robot.sdk.AbstractPlugin import AbstractPlugin
import requests
from robot import logging,config
logger = logging.getLogger(__name__)
class Plugin(AbstractPlugin):
# 创建一个查询天气的技能
def handle(self, query):
logger.info('命中 <天气> 插件')
city = config.get('/location')... | StarcoderdataPython |
1824502 | <reponame>hrozan/utfpr-final-paper<filename>legacy/smart-object/main.py
import json
import logging
import time
from app.config import get_config, DEVELOPMENT
from app.network import mqtt_client_factory, fetch_broker_config
from app.system import get_system_information
DATA_TOPIC = 'system/data'
def main():
app_... | StarcoderdataPython |
4806972 | <gh_stars>10-100
from django.db import models
from auditable.models import Commentable
class ExclusionAgreement(Commentable):
"""
Container for a single instance of "Exclusion Agreement"
"""
class Meta:
db_table = 'compliance_report_exclusion_agreement'
db_table_comment = 'Container for ... | StarcoderdataPython |
83011 | import time
import multiprocessing as mp
from multiprocessing import Pool as ProcessPool
import numpy as np
import pandas as pd
from floris.utils.tools import valid_ops as vops
from floris.utils.tools import farm_config as fconfig
from floris.utils.visualization import wflo_eval as vweval
from floris.utils.visualizat... | StarcoderdataPython |
8073739 | <filename>Arquitectura de Software/Practica 1 (Calculadora)/classes.py
#! usr/bin/python
from math import sqrt
from math import pow
from math import sin
from math import cos
from math import tan
from math import radians
class CalculadoraBasica():
def __init__(self, numX, numY):
self.numX = numX... | StarcoderdataPython |
5159451 | <filename>tests/behavioural/features/steps/collection_exercise_field.py
from behave import given, when
@given("the collection_exercise is set to '{collection_exercise}'")
@when("the collection_exercise is set to '{collection_exercise}'")
def step_impl_the_collection_exercise_is_set_to(context, collection_exercise):
... | StarcoderdataPython |
3513774 | #!/usr/bin/env python3
#
# # Copyright (c) 2021 Facebook, inc. and its affiliates. All Rights Reserved
#
#
from uimnet import utils
from uimnet import algorithms
from uimnet import workers
from omegaconf import OmegaConf
from pathlib import Path
import torch
import torch.distributed as dist
import torch.multiprocessi... | StarcoderdataPython |
8128946 | from mir.io.feature_io_base import *
import numpy as np
class ChromaIO(FeatureIO):
def read(self, filename, entry):
if(filename.endswith('.csv')):
f=open(filename,'r')
lines=f.readlines()
result=[]
for line in lines:
line=line.strip(... | StarcoderdataPython |
194873 | <reponame>bsulman/INTERFACE-model-experiment-synthesis<gh_stars>1-10
import CORPSE
from pylab import *
import pandas
# 5% clay
params_lowclay={
'vmaxref':[1500,50,600], #Relative maximum enzymatic decomp rates
'Ea':[37e3,54e3,50e3], # Activation energy
'kC':[0.01,0.01,0.01], # Michaelis-Menton parame... | StarcoderdataPython |
383788 | """Observationally-based results and scaling relations
"""
import numpy as np
__all__ = ["lbol_from_5100ang_runnoe2012", "lbol_from_3000ang_runnoe2012",
"lbol_from_1450ang_runnoe2012", "lbol_from_2to10kev_all_runnoe2012",
"lbol_from_2to10kev_RL_runnoe2012", "lbol_from_2to10kev_RQ_runnoe2012"]
... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.