id stringlengths 1 7 | text stringlengths 6 1.03M | dataset_id stringclasses 1
value |
|---|---|---|
33692 | from pathlib import Path
from tkinter import Frame, Canvas, Entry, Text, Button, PhotoImage, messagebox
import controller as db_controller
OUTPUT_PATH = Path(__file__).parent
ASSETS_PATH = OUTPUT_PATH / Path("./assets")
def relative_to_assets(path: str) -> Path:
return ASSETS_PATH / Path(path)
def add_reserva... | StarcoderdataPython |
3315738 | <gh_stars>0
# -*- coding: utf-8 -*-
from flask import Flask, current_app, request, jsonify
import io
import base64
import logging
import numpy as np
import cv2
from service import model
def create_app(config, debug=False, testing=False, config_overrides=None):
app = Flask(__name__)
app.config.from_object(conf... | StarcoderdataPython |
3361568 | import sys
import os
import time
import importlib
if sys.version_info < (3,0):
import cPickle as pickle
else:
import pickle
import numpy as np
import argparse
import pdb
import json
parser = argparse.ArgumentParser()
parser.add_argument('metadata_path')
parser.add_argument('--rng_seed', type=int, default=42)
p... | StarcoderdataPython |
149619 | <gh_stars>0
#!/usr/bin/python3
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
# Connect to pin 7 not GPIO 7
GPIO.setup(7, GPIO.OUT)
p = GPIO.PWM(7, 50)
p.start(7.5)
try:
while True:
print("Full Range Movement")
print("Move to Neutral")
p.ChangeDutyCycle(7.5)
time.sl... | StarcoderdataPython |
95275 | <gh_stars>0
from __future__ import absolute_import, print_function, division
from sklearn.datasets import load_digits
import matplotlib.pyplot as plt
from time import time
import numpy as np
from numpy import linalg as LA
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
# Step 1: ... | StarcoderdataPython |
1632815 | <reponame>Noahs-ARK/idea_relations<filename>fighting_lexicon.py
# -*- coding: utf-8 -*-
import os
import json
import math
import collections
import functools
import numpy as np
import word_count as wc
import utils
def get_uniform_alpha(first, second, count=1.0):
word_set = set(first.keys()) | set(second.keys())
... | StarcoderdataPython |
1639666 | <filename>C++/python_test/test_score_pssm.py
#
# Copyright <NAME> 2010
#
import _biopsy as B
B.init()
seq = "ACGCGAGCAGCATCATTATATCGAGCGACGCGGCGCGCGACAAGGACGGCATTATTAGCGAGCTACGACTACGACTTG"
pssms = B.SequenceVec()
hits = B.HitVec()
p_binds = B.score_pssm_on_sequence('M00023', seq, .03, hits)
| StarcoderdataPython |
3254562 | <reponame>shangz-ai/transformers<filename>tests/utils/test_cli.py
# coding=utf-8
# Copyright 2019-present, the HuggingFace Inc. team.
#
# 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
#
# h... | StarcoderdataPython |
3234438 | pkgname = "cldr-common"
url = "https://github.com/unicode-org/cldr/releases"
| StarcoderdataPython |
56726 | <gh_stars>0
from objects.axial_component import AxialComponent
from objects.cross_section import CrossSection
from objects.shape import Shape
from objects.deformations import (
deform_ac,
plane,
concave_ellipsoid,
concave_cylinder_vert,
concave_cylinder_diag_down,
concave_cylinder_diag_up,
c... | StarcoderdataPython |
3268408 | <filename>experiments/convolution_test.py
#!/usr/bin/env python3
# Copyright 2016 <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
#
#... | StarcoderdataPython |
1626503 | import os
from glob import glob
import argparse
from batchlib.reporting.write_cell_size_masks import WriteCellSizeMasks
def write_mask(folder, n_jobs):
table_name = 'cell_segmentation/marker'
seg_key = 'cell_segmentation'
scale_factors = [1, 2, 4, 8, 16]
job = WriteCellSizeMasks(table_name=table_name,... | StarcoderdataPython |
3257588 | # import logging
# import unittest
# import os
# import boto3
#
# from unittest.mock import patch, MagicMock
#
# from sosw.components.tasks_api_client_for_workers import *
#
#
# logger = logging.getLogger()
#
# os.environ["STAGE"] = "test"
# os.environ["autotest"] = "True"
#
# TASK_ID = 'test_task_id'
# LABOURER_ID = '... | StarcoderdataPython |
1675394 | """
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: MIT-0
"""
import logging
from test.testlib.testcase import BaseTestCase
import jsonschema
from mock import patch
import cfnlint.config # pylint: disable=E0401
try: # pragma: no cover
from pathlib import Path
except Imp... | StarcoderdataPython |
63748 | #!/usr/bin/python3
"""Alta3 Research | RZFeeser
Review of Lists and Dictionaries"""
# define a short data set (in real world, we want to read this from a file or API)
munsters = {'endDate': 1966, 'startDate': 1964,\
'names':['Lily', 'Herman', 'Grandpa', 'Eddie', 'Marilyn']} # {} creates dict
# Your solut... | StarcoderdataPython |
3269878 | <reponame>RisalatShahriar/ccNews
# Generated by Django 3.2.6 on 2021-08-23 02:50
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('registration', '0005_alter_data_picture'),
]
operations = [
migrations.RemoveField(
model_name=... | StarcoderdataPython |
157326 | import numpy as np
import matplotlib.pylab as plt
import cv2
from numpy.lib.npyio import save
from skimage.metrics import structural_similarity as ssim
from skimage.metrics import peak_signal_noise_ratio as psnr
import os
from os.path import join as opj
from os.path import exists as ope
from os.path import dirname as o... | StarcoderdataPython |
3288329 | <filename>code_video/main.py
import random
import os
import cv2
import numpy as np
import argparse
import sys
sys.path.append('..')
from model_processor import ModelProcessor
from atlas_utils.camera import Camera
from atlas_utils import presenteragent
from atlas_utils.acl_image import AclImage
import acl
from acl_resou... | StarcoderdataPython |
3340051 | <reponame>tyler-ham/core<filename>src/opnsense/scripts/systemhealth/queryLog.py
#!/usr/local/bin/python3
"""
Copyright (c) 2019 <NAME> <<EMAIL>>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions ar... | StarcoderdataPython |
1782520 | <reponame>RahulSajnani/DRACO-Weakly-Supervised-Dense-Reconstruction-And-Canonicalization-of-Objects
import numpy as np
import cv2
import open3d as o3d
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import torch
from PIL import Image
import json
from mpl_toolkits.mplot3d import Axes3D as mpl_3D
... | StarcoderdataPython |
177025 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2018-11-14 00:31
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('workflow', '0016_auto_20170623_1306'),
]
operations = [
migrations.AddField... | StarcoderdataPython |
4826227 | from crowd_sim.envs.utils.agent import Agent
from crowd_sim.envs.utils.state import JointState, JointState_noV
class Robot(Agent):
def __init__(self, config,section):
super().__init__(config,section)
def act(self, ob):
if self.policy is None:
raise AttributeError('Policy attribute... | StarcoderdataPython |
4809808 | from dataclasses import dataclass, field
from enum import Enum
from typing import Optional
from xsdata.models.datatype import XmlPeriod
__NAMESPACE__ = "NISTSchema-SV-IV-atomic-gDay-enumeration-3-NS"
class NistschemaSvIvAtomicGDayEnumeration3Type(Enum):
VALUE_15 = XmlPeriod("---15")
VALUE_27 = XmlPeriod("---... | StarcoderdataPython |
1615059 | <gh_stars>0
import numpy as np
import cv2
import os
import shutil
# Setting
original_data_folder = r'F:\Dataset\KITTI 2015\training'
destination_folder = r'F:\Dataset\KITTI 2015 Data Augmentation'
copy_size = 200
# blur_kernels = [3]
# scale_ratios = [1.5]
# gaussian_noises = [(0.05, 0, 0.05)] # ratio [0, 1], mean, s... | StarcoderdataPython |
121239 | <reponame>srsuper/Receipt_Number_History<filename>Checker.py
import requests
from bs4 import BeautifulSoup
class Receipt_Numbers(object):
def __init__(self, prize_dict=None):
if not prize_dict:
self._response = requests.request("GET", 'http://invoice.etax.nat.gov.tw/')
self.soup = B... | StarcoderdataPython |
1672302 | import sys
from collections import OrderedDict, defaultdict
import functools
from .ahdl import *
from .block import Block
from .common import error_info
from .env import env
from .ir import *
from .memref import *
from logging import getLogger
logger = getLogger(__name__)
class State(AHDL_BLOCK):
def __init__(se... | StarcoderdataPython |
3338255 | <filename>hw2_source_final.py
from urllib.request import urlopen
from bs4 import BeautifulSoup
import pandas as pd
import re
from bs4.element import NavigableString, Tag
import datetime
import urllib
import requests
import scipy.stats as stats
import math
import matplotlib.pyplot as plt
# Function to scrape strings fr... | StarcoderdataPython |
1648471 | <gh_stars>100-1000
from import_export import fields, resources
from import_export.widgets import ManyToManyWidget
from . models import Tutorial, Tag
class TutorialResource(resources.ModelResource):
tags = fields.Field(
column_name='tags',
attribute='tags',
widget=ManyToManyWidget(Tag, ',',... | StarcoderdataPython |
3306876 | <reponame>dagtann/learning<filename>python_da/p4da/ch10.py
import numpy as np
import pandas as pd
# Data Aggregation and Group Operations =======================================
df = pd.DataFrame({"key1": ["a", "a", "b", "b", "a"],
"key2": ["one", "two", "one", "two", "one"],
"dat... | StarcoderdataPython |
1768744 | <filename>botaclan/google/google_calendar.py<gh_stars>0
from botaclan.constants import GOOGLEAPI_CALENDAR_ID
from google.oauth2 import service_account
from googleapiclient.discovery import build, Resource
from typing import List, Dict
import botaclan.helpers.lists
import copy
import datetime
import logging
log = loggi... | StarcoderdataPython |
10101 | <reponame>zhenglab/EMOD
import torch
from torch import nn
from mmcv.cnn.utils import constant_init, kaiming_init
class SimAttention(nn.Module):
def __init__(self, in_channels):
super(SimAttention, self).__init__()
self.conv_attn = nn.Conv2d(in_channels, 1, kernel_size=1)
self.softm... | StarcoderdataPython |
3295608 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function, division
import caffe
import h5py
import numpy as np
from os.path import join
def test_model():
caffe.set_mode_gpu()
caffe.set_device(0)
root_path = '../../../'
########### testing on SUNCG use uncommoent the follo... | StarcoderdataPython |
3318447 | <gh_stars>0
from typing import TYPE_CHECKING
from contextlib import ContextDecorator
__all__ = ("Session",)
if TYPE_CHECKING:
from .models import MongoModel
class Session(ContextDecorator):
def __init__(self, model: 'MongoModel'):
self._session = model._start_session()
self.model = model
... | StarcoderdataPython |
3200043 | import sqlalchemy
from utility.globals import LOGGER
from sqlalchemy.orm import sessionmaker
def transaction_wrapper(func):
def _wrap_func(*args, **kwargs):
self = args[0]
session = sessionmaker(bind=self.engine, expire_on_commit=False)
# new session. no connections are in use.
... | StarcoderdataPython |
21376 | #!/usr/bin/env python3
import lib
N=1000000
sieve = lib.get_prime_sieve(N)
primes = lib.primes(N, sieve)
primes = primes[4:]
def is_truncatable(n):
num = n
c = 0
while num:
if not sieve[num]:
return False
num = int(num / 10)
c += 1
while c:
num = n % 10**c
if not sieve[num]:
r... | StarcoderdataPython |
3288917 | import textwrap
from text_processing import tokenize_filter_punctuation, remove_words_from_query, extract_operators_from_query, remove_non_alpha_from_string
booleanOperators = ['AND', 'OR', 'NOT', 'and', 'or', 'not']
def split_query_into_words_and_operators(query):
tokens = tokenize_filter_punctuation(query)
... | StarcoderdataPython |
3388413 | from settings.config import item_label
def get_rr_from_list(relevance_array):
relevance_list_size = len(relevance_array)
if relevance_list_size == 0:
return 0.0
for i in range(relevance_list_size):
if relevance_array[i]:
return 1 / (i + 1)
return 0.0
def mrr(reco_items_df... | StarcoderdataPython |
4808585 | # -*- coding: utf-8 -*-
"""
Definition of network architecture
Defintion of convolutional layers
Defintion of batch normalization
"""
import theano
import theano.tensor as T
import numpy as np
class Network:
""" prende in ingresso una lista di ConvLayer e l'immagine
mettere l'immagine in i... | StarcoderdataPython |
1734403 | <gh_stars>0
class Solution:
def firstMissingPositive(self, nums: List[int]) -> int:
nums.sort()
if not nums or 1 not in nums:
return 1
for i in range(1, len(nums)):
if nums[i] != nums[i-1] + 1 and nums[i] != nums[i-1] and nums[i-1] > 0:
... | StarcoderdataPython |
3269014 | <gh_stars>0
from app import app
from flask import render_template,redirect,request,url_for
from flask_login import LoginManager, login_user, current_user, logout_user, login_required
from osp.classes.address import Address
from osp.classes.user import Seller,User
from datetime import datetime
now = datetime.utcnow()
a... | StarcoderdataPython |
159078 | '''Autogenerated by xml_generate script, do not edit!'''
from OpenGL import platform as _p, arrays
# Code generation uses this
from OpenGL.raw.GL import _types as _cs
# End users want this...
from OpenGL.raw.GL._types import *
from OpenGL.raw.GL import _errors
from OpenGL.constant import Constant as _C
import ctypes
_... | StarcoderdataPython |
3270742 | <reponame>LaurentColoma/TicketManager-server
"""
Admin interface manager.
TODO.
"""
from django.contrib import admin
from django.contrib.admin import ModelAdmin
from .models import Application, Version, Module, Impact, Priority, TimeSensitiveness, Reproducibility, Ticket, \
TicketComment, Process, Proposal, Anoma... | StarcoderdataPython |
193098 | <filename>chaizhiyong/L2/IOAndClass.py<gh_stars>1-10
from roles import person,phoneOp
print("欢迎您进入注册页面")
name = input("请输入真实姓名:")
isSuccess = False
while isSuccess == False:
phoneNumber = input("请输入电话号码:")
phoneOpOne = phoneOp(phoneNumber);
print(phoneOpOne)
if phoneOpOne.checkPhoneNumber(phoneNumber):... | StarcoderdataPython |
3255665 | <filename>app/services/engines/event_constants.py
EXIT_ENGINE_EVENT = "exit_engine_event" # 退出引擎事件
LOG_EVENT = "log_event" # 推送日志
ORDER_CREATE_EVENT = "order_create_event" # 新建订单
ORDER_UPDATE_EVENT = "order_update_event" # 更新订单
ORDER_UPDATE_STATUS_EVENT = "order_update_status_event" # 更新订单状态
ORDER_UPDATE_FROZEN_... | StarcoderdataPython |
3384265 | from app import create_app
from flask_script import Manager,Shell,Server
from app.models import User,Role
from flask_migrate import Migrate, MigrateCommand
# Creating app instance
app = create_app('development')
manager = Manager(app)
migrate = Migrate(app,db)
manager.add_command('db',MigrateCommand)
@manager.command... | StarcoderdataPython |
3341946 | <filename>code/optimize.py
"""
Minimize the function
f(x) := - \exp
\left\{-\frac{(x - 5.0)^4}{1.5} \right\}
"""
from scipy.optimize import fminbound
import numpy as np
def f(x): return -np.exp(-(x - 5.0)**4 / 1.5)
print fminbound(f, -10, 10) # Find approx solution
| StarcoderdataPython |
136549 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 19 11:11:30 2019
@author: arlind
"""
import itertools
from statsmodels.tsa.statespace.sarimax import SARIMAX
from sklearn.model_selection import TimeSeriesSplit as tss
from sklearn.metrics import mean_squared_error
import numpy
import ai_analysis.c... | StarcoderdataPython |
3245558 | from .util import read_CSV
#return rows, constraints
def rank(args):
rows, constraints = read_CSV(args)
scored = []
for label, values in rows.items():
score = 1
for i, constraint in enumerate(constraints):
if constraint[0] == 'max':
score /= values[i]
... | StarcoderdataPython |
3333473 | <filename>vesper/signal/tests/test_named_sequence.py
from vesper.tests.test_case import TestCase
from vesper.util.named import Named
from vesper.signal.named_sequence import NamedSequence
class _Item(Named):
def __init__(self, name, value):
super().__init__(name)
self.value = value
... | StarcoderdataPython |
4803565 | <reponame>aroo135/pgoapi
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: pogoprotos/networking/responses/platform_client_actions_response.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.pr... | StarcoderdataPython |
169234 | print('ANALISANDO DADOS')
pessoas = dict()
lista = list()
media = soma = 0
print('-=' * 50)
while True:
pessoas.clear()
pessoas['nome'] = str(input('Nome: '))
pessoas['sexo'] = str(input('Sexo [M/F]: ')).upper().strip()[0]
while pessoas['sexo'] not in 'MF':
print('Erro, digite apenas M ou F.')
... | StarcoderdataPython |
1799513 | <reponame>Nedoko-maki/Internet-Voicechat
import logging
import queue
import socket
import threading
import traceback
import numpy
import pyflac
import select
import sounddevice as sd
import config
logging.basicConfig(
format='%(asctime)s.%(msecs)03d %(levelname)s:\t%(message)s',
level=logging.... | StarcoderdataPython |
3261323 | from heuslertools.tools.measurement import Measurement
import numpy as np
def conv(file):
i=0
for x in open(file):
if i == 2:
yield x.replace('#', 'Number').encode()
else:
yield x.replace(',', '.').encode()
i+=1
def load_sims_data(file):
data = np.genfromtx... | StarcoderdataPython |
9957 | <gh_stars>1-10
# -*- coding: utf-8 -*-
#
# Copyright 2017 Ricequant, 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... | StarcoderdataPython |
85510 | #Practical 36: Find hash of file
import sys
import hashlib
# BUF_SIZE is totally arbitrary, change for your app!
BUF_SIZE = 65536
md5 = hashlib.md5()
sha1 = hashlib.sha1()
with open(sys.argv[1], 'rb') as f:
while True:
data = f.read(BUF_SIZE)
if not data:
break
md5.update(d... | StarcoderdataPython |
161560 | from typing import Optional
from torch.nn import Module
from tha2.nn.base.init_function import create_init_function
from tha2.nn.base.module_factory import ModuleFactory
from tha2.nn.base.nonlinearity_factory import resolve_nonlinearity_factory
from tha2.nn.base.normalization import NormalizationLayerFactory
... | StarcoderdataPython |
1668653 | # Aula 13 - Desafio 46: Contagem regressiva
# Fazer uma uma contagem regressiva de 10 ate 0 com uma pausa de 1s entre os numeros
import time
for n in range(10, 0, -1):
print(f'{n}... ', end='')
time.sleep(1)
print('\n\033[1;30mFELIZ ANO NOVO!!!\033[m', '\033[1m\o/ \o|\033[m'*2)
| StarcoderdataPython |
1782694 | import os
import argparse
import os.path as osp
import glob
import torch
import torch.nn as nn
from reid.utils.data.dataset import Dataset, MixedDataset
from reid.utils.data import build_test_loader
from reid.models.backbone import ResNet
from reid.evaluation.evaluators import Evaluator, IncrementalEvaluator... | StarcoderdataPython |
1737434 | import os
def get_sha1_from_file(base_dir, relative_path):
"""
Try to read base_dir/relative_path. For git head, relative_path should be 'HEAD'.
If it contains a sha1, return it.
If it contains a ref, open base_dir/<ref> and return its contents.
On error, return None
"""
try:
head_... | StarcoderdataPython |
3341970 | import torch
import torch.nn.functional as F
from pytorch_lightning import LightningModule
from torchmetrics.functional import accuracy
from .nnconfig import NNConfig
class BaseModule(LightningModule):
def __init__(self, data_provider, model, config):
super().__init__()
self.model = model
... | StarcoderdataPython |
34701 | <gh_stars>0
import os
import numpy as np
from scipy.misc import imread, imresize
def load_image_labels(dataset_path=''):
labels = {}
with open(os.path.join(dataset_path, 'image_class_labels.txt')) as f:
for line in f:
pieces = line.strip().split()
image_id = pieces[0]
... | StarcoderdataPython |
159229 | <reponame>woollysocks/Betelgeuse_SPINN
import copy
import numpy as np
# PyTorch
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.nn.functional as F
from spinn.util.blocks import MLP
from spinn.util.blocks import the_gpu, to_gpu
from spinn.spinn_core_model import BaseModel as _Base... | StarcoderdataPython |
3235268 | <gh_stars>0
import db as db
from flask import Flask, request
from flask import jsonify
import asyncio, requests
import argparse
parser = argparse.ArgumentParser(description='Optional app description')
parser.add_argument('port', type=int, help='Port To Run The Server')
args = parser.parse_args()
port = args.port
# db.i... | StarcoderdataPython |
4829592 | <filename>sudoku.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
from tkinter import Tk, Label, Frame, Entry, Button, LEFT, RIGHT, END, messagebox
from matrice import Matrice
#from matrice import Matrice
class Application(Tk):
"""Classe de l'application.
Hérite de Tk pour instancier automatiquement une fenè... | StarcoderdataPython |
3289855 | <reponame>faeit/scrapy-selenium<gh_stars>0
from twisted.internet import reactor, defer
# from urllib.parse import urlunparse, urlparse, urlencode, urlsplit, parse_qsl
def deferredsleep(seconds):
"""
:param seconds:
:return:
"""
d = defer.Deferred()
reactor.callLater(0.1, d.callback, seconds)
... | StarcoderdataPython |
4800671 | import web3
import ethereum as eth
import rlp, utils
class Address:
def __init__(self, address, transaction):
self.address = address
self.transaction = transaction
@property
def owner_address(self):
return utils.add_0x_prefix(eth.utils.sha3(
self.owner_public_... | StarcoderdataPython |
3331779 | # coding:utf-8
__author__ = 'frkhit'
import sys
from demo import build_complex_model, build_model, LinearFit
if __name__ == '__main__':
command = "train" if len(sys.argv) < 2 else sys.argv[1]
if command == "simple":
# build model for PAI-EAS
print("building simple model...")
build_mod... | StarcoderdataPython |
199378 | <gh_stars>1-10
# -*- coding: utf-8-*-
import logging
import pkgutil, os
from src.config.path import PLUGINS_PATH
import jieba
from src.components.chatbot import Chatbot
from src.config import load_yaml_settings
class Brain:
"""
指挥第三方插件响应,还是正常对话,还是控制
"""
def __init__(self, mic, profile, iot_client):
... | StarcoderdataPython |
3249854 | <gh_stars>0
from numbers import Number
def square(*, num: Number) -> Number:
return num ** 2
| StarcoderdataPython |
1790733 | <reponame>firattamur/WarpGAN-PyTorch
import torch
import torch.nn as nn
class CustomInstanceNorm2d(nn.Module):
def __init__(self, num_features: int):
"""
Custom InstanceNorm layer for modules to multiple norm with gamma and sum with beta.
:param num_features: C from an expected input o... | StarcoderdataPython |
154315 | """
Implements a Django model, with the API of the standard User,
but contains just the 'username' field. This instance is
persisted in the traditional database configured in your project.
It acts as a proxy to the real user, stored in Cassadra.
It's required because the way Django is designed, and it's
the recommend... | StarcoderdataPython |
167034 | <gh_stars>1-10
# script to remove worms
import numpy as np
from scipy.ndimage.measurements import label
from skimage.measure import regionprops_table
import zarr
import os
from pathlib import Path
from segmentation_pipeline import add_elongation
import pandas as pd
def get_labs_less_than(df, lab_col='label', cond_col... | StarcoderdataPython |
96296 | <reponame>tvandera/nomad
import os
import subprocess
import sys
datasets = [("yahoo", 1.00, 0.0005, 0.5, 300), ("netflix", 0.05, 0.008, 0.5, 300), ("hugewiki", 0.01, 0.008, 0.5, 200)]
numprocs = [32]
numcpus = [4]
dim=100
exp_name=sys.argv[0][:sys.argv[0].rfind('.py')]
#root@master:/yundata/nomad/Scripts/aws# /yun... | StarcoderdataPython |
3222278 | import glob
import os
import json
from tqdm.notebook import tqdm
json_path = "/content/drive/My Drive/Projects/ThaiSum-Dataset/simple-json/test-set-our-sent-segmentation/BertSum"
save_path = "/content/drive/My Drive/Projects/ThaiSum-Dataset/simple-json/test-set-our-sent-segmentation/ARedSum"
json_files = glob.glob(os... | StarcoderdataPython |
3301513 | def read_DOKAoutput_files(config):
"""
All filenames should follow the pattern: ID_num_run_trialnum_direction*.csv
If they don't, use the R script nameFixer_v2.R in LizardTails first.
The summary file for the current DOKA project will be stored in the summary_folder in analysis_results.
:param confi... | StarcoderdataPython |
1771583 | import os, csv, pandas
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objs as go
import pandas_datareader as pdr
from datetime import datetime as dt
# layout = html.Div([
# html.H1('Stick Tockers'),
# dcc.Dropdown(
# id='my-dropdown',
# options=[
# ... | StarcoderdataPython |
3368067 | import re
import subprocess
import requests
import streamlink
session = requests.Session()
def get_oauth(g_oa_client_id, g_oa_client_secret): # This method gets the auth token
params_get_oauth = {
"client_id": g_oa_client_id,
"client_secret": g_oa_client_secret,
"grant_type": "client_cre... | StarcoderdataPython |
3367067 | import setuptools
# Long description
with open('README.md', 'r') as fh:
long_description = fh.read()
# Requirements
def get_requirements():
return [
'selenium>=3.14',
]
setuptools.setup(
name="tweet-capture",
version="0.0.10",
author="<NAME>",
author_email="<EMAIL>",
descrip... | StarcoderdataPython |
180092 | <reponame>alvinwan/MarkdownPy
from markdown import markdownFromFile, markdown
from bs4 import BeautifulSoup
class TreeOfContents:
"""Tree abstraction for markdown source"""
source_type = BeautifulSoup
valid_tags = ('a', 'abbr', 'address', 'area', 'article', 'aside', 'audio',
'b', 'base', 'bdi', '... | StarcoderdataPython |
3285955 | <reponame>SU-ECE-17-7/ibeis
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
#import utool
#print, print_, printDBG, rrr, profile = utool.inject(__name__, '[hsexcept]', DEBUG=False)
import utool as ut
ut.noinject(__name__, '[hsecept]', DEBUG=False)
class QueryException(Except... | StarcoderdataPython |
1794441 | from argparse import ArgumentParser
import os
from app import app
if __name__ == '__main__':
if 'SECRET_KEY' not in os.environ:
print('[WARN] SECRET KEY is not set in the environment variable.')
parser = ArgumentParser('해당 Flask 어플리케이션이 동작하기 위해 필요한 설정 값들을 다루기 위한 Argument Parser입니다.')
parser.add_... | StarcoderdataPython |
194862 | <gh_stars>0
# Refaça o DESAFIO 9, mostrando a tabuada de um número
# que o usuário escolher, só que agora utilizando um laço for.
num = int(input('Digite um valor: '))
for i in range(1,11):
print(f'{num} X {i} = {num*i}') | StarcoderdataPython |
3221846 | from django.contrib import messages
from django.http import HttpResponse
from django.shortcuts import redirect, render
from django.utils.timezone import now
from django.views.decorators.http import require_http_methods
from api.utils import api_login_required, handle_api_errors
from core.admin_menus import AdminMenuIt... | StarcoderdataPython |
1774756 | <reponame>vektorelpython24proje/temelbilgiler
class A:
def __init__(self):
self.a = "A"
@staticmethod
def pi():
return 22/7
obj1 = A()
print(obj1.pi())
import time
#import math
def hesapZaman(fonk):
def icFonk(*args, **kwargs):
basla = time.time()
fonk(*args, **kwargs... | StarcoderdataPython |
176722 | from typing import Dict, Tuple
from unittest.mock import MagicMock
from urllib.parse import urljoin
import pytest
import requests
from pytest_mock.plugin import MockerFixture
from kinto_http import AsyncClient, Client
from kinto_http.constants import DEFAULT_AUTH, SERVER_URL, USER_AGENT
from kinto_http.endpoints impo... | StarcoderdataPython |
13626 | <reponame>alexsocha/mipsplusplus
from mipsplusplus import utils
from mipsplusplus import operations
OPERATOR_ORDERING = [
['addressof', 'not', 'neg'],
['*', '/', '%'],
['+', '-'],
['<<', '>>', '<<<', '>>>'],
['<', '>', '<=', '>='],
['==', '!='],
['and', 'or', 'xor', 'nor'],
['as']
]
EXPR_OPERATORS = s... | StarcoderdataPython |
107921 | n = int(input('Digite o valor de n: '))
i = 1
número = 0
while i <= n:
número = número + 1
if (número % 2 != 0):
i = i + 1
print(número) | StarcoderdataPython |
3336017 | <filename>tasks/__init__.py<gh_stars>1-10
"""
Runnable tasks for this project. Project tooling for build, distribute, etc.
Invoked with the Python `invoke` framework. Tasks should be invoked from the project root directory, not
the `tasks` dir.
Task code is for tooling only and should strictly not be mixed with `src`... | StarcoderdataPython |
37616 | <gh_stars>0
# -*- coding: utf-8 -*-
# Generated by Django 1.11.9 on 2018-06-23 06:06
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('symposion_schedule', '0002_slot_name'),
]
operations = [
migrations.Rem... | StarcoderdataPython |
4843075 | from django.core.management.base import BaseCommand, CommandError
from ...models import Run
from django.contrib.contenttypes.models import ContentType
from ...serializers import ContentTypeIdField
from ...backends import immediate
from rest_framework.exceptions import ValidationError
from django.contrib.auth import get... | StarcoderdataPython |
3261816 | <filename>euler/Q3/3.py
#!/usr/bin/python
from math import ceil, sqrt
number = 600851475143
count=0
div=3
while (number&1)==0:
count=count+1
number=number>>1
count=count+1
if number==1:
count=count+1
number=2
root=ceil(sqrt(number))
count=count+1
while div<=root:
count=count+1
if(numb... | StarcoderdataPython |
4800522 | <reponame>chrooke/cash-flow-calculator
#!/bin/env python
import yaml
from datetime import date, timedelta
from dateutil.relativedelta import relativedelta
from cash_flow.transaction import Transaction
class TransactionStore(object):
def __init__(self):
self.store = []
def addTransactions(self, first_... | StarcoderdataPython |
124850 | MAX_RECIPIENTS_PER_MESSAGE = 5
MSG_BLOOM_FILTER_SIZE = 80
| StarcoderdataPython |
3340381 | <reponame>cswat/fantasy-language-speech-generator
#imports
import json
import re
from django import forms
from django.core.exceptions import ValidationError
class TranslateForm(forms.Form):
#pull fantasy languages from json file and manage how they appear on the form - I commented out the references to fantasy la... | StarcoderdataPython |
4803152 | import random
def print_rect(alpha, height=1, width_mult=1):
li = list(alpha)
for i in range(height):
line = ""
for j in range(width_mult):
random.shuffle(li)
line += "".join(li)
print(line)
print_rect("IJKLMNOP", 8, 1) | StarcoderdataPython |
3303368 | # Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | StarcoderdataPython |
3329880 | from .config import YamlConfig
from .registry import Registry, build_from_cfg, build_ray_obj_from_cfg
__all__ = [
"Registry",
"build_from_cfg",
"build_ray_obj_from_cfg",
"YamlConfig",
]
| StarcoderdataPython |
153800 | # by <NAME>
# Replace magic numbers with named constanst
def calculation(charge1, charge2, distance):
constant = 8.9875517923*1e9
return constant * charge1 * charge2 / (distance**2)
# First Section
# Given two point charges, calcualte the electric force exerted on them.
q1 = int(input('Enter a valu... | StarcoderdataPython |
3210003 | """
Named Params:
>>> def a(abc): pass
...
>>> a(abc=3) # <- this stuff (abc)
"""
def a(abc):
pass
#? 5 ['abc']
a(abc)
def a(*some_args, **some_kwargs):
pass
#? 11 []
a(some_args)
#? 13 []
a(some_kwargs)
| StarcoderdataPython |
3237796 | <filename>kaleidescope/kaleidescope.py<gh_stars>1000+
import argparse
import requests
import random
from PIL import Image
from io import BytesIO
BLOCK_W = 8
BLOCK_H = 8
def extract_symbols(doc, file_key, headers):
canvas = doc['document']['children'][0]
symbols = []
guids = []
for node in canvas['chil... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.