text string | size int64 | token_count int64 |
|---|---|---|
"""
Faça um programa que leia dois vetores de 10 elementos. Crie um vetor que seja a intersecçao entre os 2 vetores
anteriores, ou seja, que contém apenas os números que estao em ambos os vetores. Nao deve conter números repetidos.
"""
from random import randint
vetor1 = []
vetor2 = []
inter = []
for x in range(10):
... | 524 | 207 |
# Testing module instance_type.h
import pytest
import ec2_compare.internal.instance_type.h
def test_get_internal_data_instance_type_h_get_instances_list():
assert len(ec2_compare.internal.instance_type.h.get_instances_list()) > 0
def test_get_internal_data_instance_type_h_get():
assert len(ec2_compare.internal.in... | 343 | 124 |
#!/bin/python3
import sys
# t = int(input().strip())
# for a0 in range(t):
# G = [
# "7283455864",
# "6731158619",
# "8988242643",
# "3830589324",
# "2229505813",
# "5633845374",
# "6473530293",
# "7053106601",
# "0834282956",
# "4607924137"
# ]
# P = ["9505", "3845", "3530"]
G... | 1,529 | 581 |
import os
import logging
import tempfile
log = logging.getLogger(__name__)
class PidFile(object):
""" A small helper class for pidfiles. """
PID_DIR = '/var/run/rollbard'
def __init__(self, program, pid_dir=None):
self.pid_file = "%s.pid" % program
self.pid_dir = pid_dir or self.get_defa... | 1,764 | 536 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('server', '0018_auto_20151124_1654'),
]
operations = [
migrations.CreateModel(
name='UpdateHistoryItem',
... | 1,388 | 393 |
#!/usr/bin/env python
#
import sys, cpp, kernel, glob, os, re, getopt, clean_header, subprocess
from defaults import *
from utils import *
def usage():
print """\
usage: %(progname)s [kernel-original-path] [kernel-modified-path]
this program is used to update all the auto-generated clean headers
used by... | 3,624 | 1,240 |
""" batch iterator"""
from __future__ import absolute_import
import ctypes
from ddls.base import check_call, LIB, c_str, c_array
from ddls.hpps.tensor import Tensor
class Batch(object):
""" The BatchIterator
"""
def __init__(self, handle):
""" The batch from iterator
"""
self.hand... | 1,816 | 525 |
import autograd.numpy as anp
import numpy as np
from autograd import value_and_grad
from pymoo.factory import normalize
from pymoo.util.ref_dirs.energy import squared_dist
from pymoo.util.ref_dirs.optimizer import Adam
from pymoo.util.reference_direction import ReferenceDirectionFactory, scale_reference_directions
c... | 3,520 | 1,066 |
#!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
import argparse
import json
parser = argparse.ArgumentParser()
parser.add_argument("-seqs",
required=True,
type=str,
default=None,
help="File contain... | 1,555 | 640 |
from django.apps import AppConfig
class XmptConfig(AppConfig):
name = 'xmpt'
| 83 | 30 |
import numpy as np
import math
import fatpack
import matplotlib.pyplot as plt
import pandas as pd
#Create a function that reutrns the Goodman correction:
def Goodman_method_correction(M_a,M_m,M_max):
M_u = 1.5*M_max
M_ar = M_a/(1-M_m/M_u)
return M_ar
def Equivalent_bending_moment(M_ar,Neq,m):
P = M_ar... | 787 | 355 |
# Programmer friendly subprocess wrapper.
#
# Author: Peter Odding <peter@peterodding.com>
# Last Change: March 2, 2020
# URL: https://executor.readthedocs.io
"""
Portable process control functionality for the `executor` package.
The :mod:`executor.process` module defines the :class:`ControllableProcess`
abstract bas... | 12,040 | 2,960 |
from logging import basicConfig, getLogger, INFO
from connect_to_ledger import create_qldb_driver
from amazon.ion.simpleion import dumps, loads
logger = getLogger(__name__)
basicConfig(level=INFO)
from constants import Constants
from register_person import get_scentityid_from_personid,get_scentity_contact
from sampled... | 10,945 | 2,887 |
"""
All components and wrappers currently
supported by rewx.
"""
import wx
import wx.adv
import wx.lib.scrolledpanel
import wx.media
ActivityIndicator = wx.ActivityIndicator
Button = wx.Button
BitmapButton = wx.BitmapButton
CalendarCtrl = wx.adv.CalendarCtrl
CheckBox = wx.CheckBox
# CollapsiblePane = wx.CollapsiblePa... | 1,467 | 469 |
#!/usr/bin/python
# Copyright (c) 2009, Purdue University
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# Redistributions of source code must retain the above copyright notice, this
# list ... | 3,733 | 1,368 |
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 21 16:41:09 2020
@author: rafae
Exercício
Você deve criar uma classe carro que vai possuir dois atributos
compostos por outras duas classes:
1) motor;
2) Direção.
O motor terá a responsabilidade de controlar a velocidade.
Ele oferece os seguintes atributos:
1) Atribu... | 4,247 | 1,632 |
Collection = "items"
| 21 | 7 |
"""
Very advanced Employee management system.
"""
from dataclasses import dataclass
from typing import List
FIXED_VACATION_DAYS_PAYOUT = 5 # The fixed nr of vacation days that can be paid out.
@dataclass
class Employee:
"""Basic representation of an employee at the company."""
name: str
role: str
... | 3,829 | 1,104 |
def debug_transformer(func):
def wrapper():
print(f'Function `{func.__name__}` called')
func()
print(f'Function `{func.__name__}` finished')
return wrapper
@debug_transformer
def walkout():
print('Bye Felicia')
walkout() | 261 | 81 |
import functools
import logging
from typing import Callable
from logging_context.context.base import BaseContext
from .context import get_logging_context
def context_logging_factory(record_factory: Callable, context: BaseContext) -> Callable:
@functools.wraps(record_factory)
def wrapper(*args, **kwargs):
... | 850 | 237 |
#!/usr/bin/env python
import re
import sys
import time
import logging
import asyncore
import optparse
from datetime import datetime
import schedule
from pymongo import MongoReplicaSetClient, MongoClient
from async_s5 import AsyncSocks5Client
from async_http import AsyncHTTPClient
from async_http_tunnel import Async... | 6,840 | 2,175 |
# %% [Algorithm 1c Loop]
# # MUSHROOMS
# %% [markdown]
# ## Binary Classification
# %% [markdown]
# ### Imports
# %%
import os
import pandas as pd
import numpy as np
import tensorflow as tf
from tensorflow import keras
import matplotlib.pyplot as plt
# %% [markdown]
# ### Load Data
dataset = pd.read_csv(r"C:\User... | 16,438 | 6,382 |
from galaxydb.column import Column
from galaxydb.scheme import Scheme
from galaxydb.logic import Logic
from galaxydb.table import Table
from galaxydb.constants import *
from galaxydb.statics import *
| 206 | 66 |
# NOTE: This changes a/b to produce a floating point approximation of that
# ratio, not the integer quotient. For integer quotient, use a//b instead.
from __future__ import division
import fourier_parameterization
import numpy as np
import multiindex
import symbolic
import sympy
import tensor
# TODO: look at and use... | 19,291 | 6,573 |
import pantilthat
class Tripod(object):
def __init__(self):
self.horizontal = 0
self.vertical = 0
self.step_size = 5
pantilthat.pan(0)
pantilthat.tilt(0)
def left(self):
if (-80 < self.horizontal):
self.horizontal = self.horizontal - self.step_size
... | 1,029 | 325 |
import collections
import contextlib
import os.path
import typing
from contextlib import ExitStack
from pathlib import Path
from typing import BinaryIO, Dict, Optional, Generator, Iterator, Set
from mercury_engine_data_structures import formats, dread_data
from mercury_engine_data_structures.formats.base_resource impo... | 5,592 | 1,737 |
def preprocess(text):
text=text.replace('\n', '\n\r')
return text
def getLetter():
return open("./input/letter.txt", "r").read()
| 142 | 51 |
# Created by Joshua de Guzman on 09/07/2018
# @email code@jmdg.io
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status, generi... | 4,665 | 1,259 |
import os
import unittest
from bmaclient.utils import get_api_key_from_file
DATA_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data')
class APIKeyTest(unittest.TestCase):
def test_get_api_key_from_file(self):
path = os.path.join(DATA_DIR, 'api_key.txt')
key = get_api_key_from_... | 837 | 316 |
from django import forms
from django.forms import ModelForm
from .models import Plan
class DateInput(forms.DateInput):
input_type = "date"
class AddPlanForm(ModelForm):
class Meta:
model = Plan
# fields = fields = '__all__'
fields = [
"date",
"meal",
... | 498 | 149 |
#!/usr/bin/env python
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import pandas as pd
from conversion import read_imgs_masks
from os.path import isfile, basename
XERR=0.1
ELINEWIDTH=3
CAPSIZE=5
CAPTHICK=3
FMT='cD'
def harm_plot(ydata, labels, outPrefix, bshell_b):
'... | 2,856 | 1,128 |
"""
Tests for the badframes detection routines.
"""
import numpy as np
import vip_hci as vip
def test_badfr_corr():
im1 = vip.var.create_synth_psf(shape=(19, 19), fwhm=2)
im2 = vip.var.create_synth_psf(shape=(19, 19), fwhm=(2, 4))
cube = np.array([im1, im2, im1, im2])
gind, bind = vip.preproc.cube_d... | 1,913 | 812 |
"""
MIT License
Copyright (c) 2021 Li Pan
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... | 13,774 | 4,333 |
from CGATReport.Tracker import *
from CGATReport.Utils import PARAMS as P
from IsoformReport import *
###############################################################################
# parse params
###############################################################################
DATABASE = P.get('', P.get('sql_backend'... | 3,049 | 1,026 |
import torch
from torch import Tensor
from torch.utils.data import Dataset
from torchvision import io
from pathlib import Path
from typing import Tuple
from torchvision import transforms as T
class CelebAMaskHQ(Dataset):
CLASSES = [
'background', 'skin', 'nose', 'eye_g', 'l_eye', 'r_eye', 'l_brow', 'r_br... | 2,063 | 875 |
# -*- coding: utf-8 -*-
# Resource object code
#
# Created by: The Resource Compiler for PyQt5 (Qt v5.9.6)
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore
qt_resource_data = b"\
\x00\x00\x2d\x15\
\x89\
\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\
\x00\x00\xc8\x0... | 282,158 | 262,118 |
print('Gerador de PA\n','==-'*10)
primeiro = int(input('Primeiro termo:'))
razao = int(input('Razao da PA:'))
termo = primeiro
c = 1
total = 0
mais = 10
while mais != 0:
total = total + mais
while c <= total:
print(f'{termo} ->', end='')
c += 1
termo += razao
print('PAUSA')
mais ... | 430 | 169 |
from enum import Enum
from .Conversions import list_to_csv_quoted_str, value_to_quoted_str, list_to_csv_str, value_to_str, enum_list_to_str, enum_scalar_to_str
from .Types import DataType
def value_to_scpi_string(data, data_type: DataType):
"""Method to be used in the driver implementation.
Convert data to SCPI st... | 4,409 | 1,427 |
"""This example read the settings and print them out, so you can check how they get loaded.
"""
# noinspection PyUnresolvedReferences,PyPackageRequirements
from settings import my_settings as settings
print("Redis Host:", settings.redis_host)
print("Redis Port:", settings.redis_port)
print("Redis Port / 2:", settings... | 565 | 178 |
import sys
import table_gen
import doc_gen
import graph_gen
import array_gen
import os
def main(argv):
outdir = './sf1_dataset_output/'
if os.path.exists(outdir):
os.system("rm -rf "+outdir)
os.mkdir(outdir)
earthquake_dirpath = argv[1]
shelter_dirpath = argv[2]
gps_dirpath = argv[3]
... | 1,109 | 402 |
#!/usr/bin/env python
# coding=utf-8
#
# A module for create a multi-agent system over Ad-hoc networks
# Copyright (C) 2017-2018
# Juan Sebastian Triana Correa <justrianaco@unal.edu.co>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as publ... | 4,450 | 1,518 |
#!/usr/bin/env python
from setuptools import setup
NAME = 'testrail_reporter'
DESCRIPTION = 'Nosetests Plugin to Report Test Results to TestRail.'
VERSION = open('VERSION').read().strip()
LONG_DESC = open('README.rst').read()
LICENSE = open('LICENSE').read()
setup(
name=NAME,
version=VERSION,
author='Char... | 1,565 | 525 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'ipetrash'
# SOURCE: https://github.com/mozilla/bleach
# SOURCE: https://bleach.readthedocs.io/en/latest/clean.html#allowed-protocols-protocols
# pip install bleach
import bleach
# List of allowed protocols
print('List of allowed protocols:', bleach.san... | 871 | 330 |
import symro
import symro.src.handlers.metaentitybuilder as eb
from symro.src.parsing.amplparser import AMPLParser
from symro.test.test_util import *
# Scripts
# ----------------------------------------------------------------------------------------------------------------------
FIXED_DIM_SCRIPT = """
set I = {1, 2... | 4,920 | 1,966 |
"""
Created on Wed March 30 11::00 2022
@author: Frédérique Leclerc
"""
from tracemalloc import start
from numpy import number
from Screen import Screen as Screen
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import *
from PyQt5.QtGui import QFont, QPixmap
from PIL import Image
#from Ergocycle.source.StartWindow i... | 14,042 | 4,468 |
import boto3
import uuid
import json
import os
def lambda_handler(event, context):
record = event['Records'][0]
s3bucket = record['s3']['bucket']['name']
s3object = record['s3']['object']['key']
print(s3object.split(".")[0].split("-")[2])
if s3object.split(".")[0].split("-")[2] ... | 1,412 | 497 |
""" Blacklist_token class method and model """
import datetime
class BlacklistToken:
"""Blacklist token class
1. initializes the class with the user token and the time created
"""
def __init__(self, token):
self.token = token
self.blacklisted_on = datetime.datetime.now()
def add... | 773 | 217 |
"""
-----------------------------------------------------------------------------------------------------------
Package: AequilibraE
Name: Loads datasets into AequilibraE binary files
Purpose: Implements dataset creation
Original Author: Pedro Camargo (c@margo.co)
Contributors:
Last edited by: Ped... | 3,631 | 1,031 |
MainWindow.clearData()
MainWindow.openPreWindow()
box = CAD.Box()
box.setName('Box_1')
box.setLocation(0,0,0)
box.setPara(10,10,10)
box.create()
cylinder = CAD.Cylinder()
cylinder.setName('Cylinder_2')
cylinder.setLocation(0,0,0)
cylinder.setRadius(5)
cylinder.setLength(10)
cylinder.setAxis(0,0,1)
cylinder... | 781 | 354 |
from typing import Any
from uuid import UUID, uuid4
import celery
from app import crud, models, schemas
from app.api import deps
from app.core.config import settings
from app.utils import auth
from app.core import tasks
from fastapi import APIRouter, Depends, HTTPException, Body, Query
from sqlalchemy.orm import Sessi... | 1,040 | 325 |
from mushroom_rl.utils.table import Table
def EligibilityTrace(shape, name='replacing'):
"""
Factory method to create an eligibility trace of the provided type.
Args:
shape (list): shape of the eligibility trace table;
name (str, 'replacing'): type of the eligibility trace.
Returns:
... | 991 | 308 |
class Parrot():
def __init__(self, squawk, is_alive=True):
self.squawk = squawk
self.is_alive = is_alive
african_grey = Parrot('Polly want a Cracker?')
norwegian_blue = Parrot('', is_alive=False)
def squawk(self):
if self.is_alive:
return self.squawk
else:
... | 440 | 168 |
def solution(S, K):
# write your code in Python 3.6
day_dict = {0:'Mon', 1:'Tue', 2:'Wed', 3:'Thu', 4:'Fri', 5:'Sat', 6:'Sun'}
return day_dict[list(day_dict.values()).index(S)+K]
S='Wed'
K=2
print(solution(S,K))
| 226 | 110 |
n = int(input('Me diga um número qualquer: '))
re = n % 2
if re == 0:
print('O número {} é PAR!'.format(n))
else:
print('O número {} é ÍMPAR!'.format(n))
| 162 | 68 |
from numpy import random
class BaseSchedule(object):
"""Maintains logic for deciding whether to consequate trials.
This base class provides the most basic reinforcent schedule: every
response is consequated.
Methods:
consequate(trial) -- returns a boolean value based on whether the trial
... | 6,927 | 1,889 |
from typing import Any, List, Dict, Iterator, Callable
import torch
import torch.nn as nn
import torch.nn.functional as F
from transformers import AutoTokenizer, RobertaForMultipleChoice
import torchfly
from torchfly.nn.transformers import GPT2LMHeadModel
from torchfly.training import FlyModel
from torchfly.nn.losses ... | 7,766 | 2,495 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 10 14:12:28 2022
@author: 1517suj
"""
from model import Yolov1
import torch
import torch.optim as optim
import torchvision.transforms as T
import cv2
from utils import (
non_max_suppression,
mean_average_precision,
intersection_over_unio... | 5,622 | 2,272 |
import pathlib
from setuptools import setup
# The directory containing this file
HERE = pathlib.Path(__file__).parent
# The text of the README file
README = (HERE / "README.md").read_text()
setup(
name="satisfy-calc",
version="1.1.3",
description="Command line crafting tree visualizer for Sat... | 1,812 | 556 |
from .detectors import *
from .max_iou_assigner_v2 import MaxIoUAssignerV2 | 74 | 29 |
# Generated by Django 3.1.6 on 2021-03-01 10:15
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('projects', '0014_environment_appenv'),
]
operations = [
migrations.RemoveField(
model_name='fla... | 2,195 | 664 |
from TestOutput import LogManager
class Auth_Test:
def __init__(self):
self.logger = LogManager('AuthTest')
self.logger.writeTestEvent('AuthTest', 'Test Started')
if __name__ == "__main__":
Auth_Test() | 210 | 73 |
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import sessionmaker
from app.core.config import settings
engine = create_async_engine(settings.ASYNC_SQLALCHEMY_DATABASE_URI)
SessionLocal = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
| 298 | 94 |
MIN_SUPPORT = 2
MIN_ALL_CONF = 0.05
| 37 | 25 |
produtos = {1: 4.0, 2: 4.5, 3: 5.0, 4: 2.0, 5: 1.5}
produto, quantidade = [int(num) for num in input().split()]
total = produtos[produto] * quantidade
print('Total: R$ {:.2f}'.format(total))
| 195 | 97 |
# Code Listing #3
"""
Prime number iterator class
"""
class Prime(object):
""" A prime number iterator for first 'n' primes """
def __init__(self, n):
self.n = n
self.count = 0
self.value = 0
def __iter__(self):
return self
def __next__(self):
""" Return ne... | 1,168 | 354 |
""" Stopwatch
A simple stopwatch for measuring time
"""
from datetime import datetime
class Stopwatch:
"""Stopwatch object for measuring time"""
def __init__(self):
self._start = None
def start(self):
"""Starts watch by setting start time to now"""
self._start = datetime.now(... | 444 | 121 |
"""
Takes the MNIST dataset as input (images and labels separated)
and creates a new dataset only with 0's and 1's
"""
import numpy as np
DATA_PATH = "data/raw/"
OUTPUT_PATH = "data/processed/mnist/"
X = np.loadtxt(DATA_PATH + "mnist2500_X.txt")
labels = np.loadtxt(DATA_PATH + "mnist2500_labels.txt")
X_new = []
labe... | 623 | 269 |
import os
import sys
import copy
import math
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from models.nets import MLP
# Original code from : https://github.com/WangYueFt/dgcnn/blob/master/pytorch/model.py
def knn(x, k):
inner = -2*torch.matmul(x.transpose(2, 1), x)
xx ... | 7,364 | 3,098 |
import torch.nn as nn
class BasicBlock(nn.Module):
def __init__(self, cᵢ, cₒ, s=1, dropout=0., activate_before_residual=False):
super().__init__()
self.activate_before_residual = activate_before_residual
# residual path
self.conv0 = nn.Conv2d(cᵢ, cₒ, 3, s, 1, bias=False)
s... | 2,794 | 1,163 |
"""Utils Module."""
from trisicell.ul._hclustering import (
dist_cosine_ignore_na,
dist_dendro,
dist_l1_ignore_na,
hclustering,
)
from trisicell.ul._packages import (
import_graph_tool,
import_graphviz,
import_gurobi,
import_mpi4py,
import_rpy2,
)
from trisicell.ul._trees import (
... | 1,565 | 646 |
#!/usr/bin/env python
import argparse, sys, socket, random, struct, time
from scapy.all import sendp, send, get_if_list, get_if_list, get_if_hwaddr, hexdump
from scapy.all import Packet
from scapy.all import Ether, IP, IPv6, UDP, TCP
sip_port=5060
def get_if():
iface=None
for i in get_if_list():
# ... | 2,137 | 765 |
"""HSL class."""
from ...spaces import Space, Cylindrical
from ...cat import WHITES
from ...gamut.bounds import GamutBound, FLG_ANGLE, FLG_PERCENT
from ... import util
from ... import algebra as alg
from ...types import Vector
from typing import Tuple
def srgb_to_hsl(rgb: Vector) -> Vector:
"""SRGB to HSL."""
... | 2,898 | 1,175 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
# Create your models here.
class Passage(models.Model):
DIRECTIONS = (
('N', 'North'),
('E', 'East'),
('S', 'South'),
('W', 'West'),
('U', 'Up'),
('D', 'Down'),
)
room_x = models.IntegerField()
room_y = model... | 950 | 374 |
"""Tests for the variable-length integers."""
import io
import pytest
from binobj import varints
@pytest.mark.parametrize(
"value,expected",
((0, b"\0"), (127, b"\x7f"), (128, b"\x81\x00"), (65535, b"\x83\xff\x7f")),
)
def test_encode_vlq_basic(value, expected):
assert varints.encode_integer_vlq(value)... | 3,181 | 1,486 |
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Setting(models.Model):
user_id = models.ForeignKey(User, on_delete=models.CASCADE)
class TimeTrackingSetting(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
max_daily_work_ti... | 725 | 232 |
from __future__ import print_function
import os
import sys
import pcbnew
import numpy as np
import pprint
def inch_to_nanometer(value):
return (value*25.4)*1e6
def nanometer_to_inch(value):
return value/(25.4*1.e6)
def nm_to_mm(value):
return value*1.e-6
def mm_to_nm(value):
return value*1.e6
def... | 2,646 | 931 |
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license.
import sys
import iotc
from iotc import IOTConnectType, IOTLogLevel
from random import randint
import base64
import hmac
import hashlib
gIsMicroPython = ('implementation' in dir(sys)) and ('name' in dir(sys.implementation)) and (sys.imp... | 2,199 | 826 |
#!/usr/bin/env python
# encoding: utf-8
"""
variant_consumer.py
Consumes batches of variants and annotates them. Each batch is a dictionary
with variant_id:s as keys and dictionaries with variant information.
The variants will get different annotations depending on input
Created by Måns Magnusson on 2013-03-01.
Cop... | 5,842 | 1,502 |
import os
import sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from dartsapp import game, player, darts_helper
from dartsapp.exceptions import BullseyeHasNoTriple, FieldDoesNotExist,\
NoPlayerRegistered, OptionsNotSet,\
... | 343 | 100 |
from .models import *
from datetime import datetime
from django.core.exceptions import ObjectDoesNotExist
import json
from WebAppsMain.settings import TEST_WINDOWS_USERNAME, TEST_PMS, TEST_SUPERVISOR_PMS, TEST_COMMISSIONER_PMS
from WebAppsMain.testing_utils import HttpPostTestCase, HttpGetTestCase
from django.db.models... | 80,150 | 23,557 |
import cv2
import caffe
import tools
import sys
import os
import numpy as np
from functools import partial
import config
def gen_scales(w, h, min_imgsize, net_imgsize):
scales = []
scale = float(net_imgsize) / min_imgsize;
minhw = min(w, h) * scale;
while minhw > net_imgsize:
scales.append(sc... | 3,794 | 1,566 |
import os
import fnmatch
# extensions can be a single tring like '.png' or '.jpg'
# or a list of extensions. they should all be lowercase
# but the . is important.
def list_all_files(directory, extensions=None):
for root, dirnames, filenames in os.walk(directory):
for filename in filenames:
bas... | 515 | 143 |
"""
2.6 – Citação famosa 2: Repita o Exercício 2.5, porém, desta vez, armazene o nome da pessoa famosa em uma variável chamada famous_person. Em seguida, componha sua mensagem e armazene-a em uma nova variável chamada message. Exiba sua mensagem.
"""
famous_person = "René Descartes"
message = "As paixões são todas boa... | 452 | 158 |
import random
import copy
import time
from numba import jit
from array_creator import create_test_set
from measure import get_elapsed_data
@get_elapsed_data
def scratch_lin_search(test_set):
hit = False
for key, arr in test_set:
for i in arr:
if i == key:
break
@get_elaps... | 662 | 227 |
#!/usr/bin/env python
# Licensed under a 3-clause BSD style license - see LICENSE.rst
# Use "distribute" - the setuptools fork that supports python 3.
from distribute_setup import use_setuptools
use_setuptools()
from distutils.command import sdist
import glob
import os
import sys
from setuptools import setup, find_p... | 3,997 | 1,199 |
# -*- coding: utf-8 -*-
"""
Copyright (c) Microsoft Corporation.
Licensed under the MIT License.
"""
from abc import ABC, abstractmethod
from typing import Any, Callable, Optional, Type
class Serializer(ABC):
"""Serializer base class."""
@abstractmethod
def serialize(
self, obj: object,
... | 606 | 176 |
from django.apps import AppConfig
class MmConfig(AppConfig):
name = 'MM'
| 84 | 32 |
import _config
import _utils
CONFIG_PATH = "config.toml"
def main():
config = _config.read(CONFIG_PATH)
for path_name in [x.in_ for x in config.directorios]:
_utils.list_jpg_files_in_dir(path_name)
if __name__ == "__main__":
main()
| 258 | 98 |
def merge_dicts(*dicts):
"""
Given any number of dicts, shallow copy and merge into a new dict,
precedence goes to key value pairs in latter dicts.
"""
result = {}
for d in dicts:
result.update(d)
return result
def evaluate_term(term, **kwargs):
return term.evaluate(**kwargs)... | 360 | 114 |
import random
class Skyline:
area = 0
max_height = 0
xmin = 0
height = []
width = []
x_pos = []
xmax = 0
def __init__(self, xmin, height, xmax):
self.xmin = xmin
self.height = [height] * ((xmax - xmin) + 1)
self.xmax = xmax
self.x_pos = list(range(xmin... | 11,067 | 4,198 |
import time
class SocketWrap(object):
def __init__(self, sock, ip=None, port=None, host="", target=""):
self._sock = sock
self.ip = ip
self.port = port
self.host = host
self.target = target
self.recved_data = 0
self.recved_times = 0
self.create_time... | 1,699 | 575 |
import pytest
from bigxml.handler_marker import _ATTR_MARKER, xml_handle_element, xml_handle_text
from bigxml.nodes import XMLText
def test_one_maker_element():
@xml_handle_element("abc", "def")
def fct(arg):
return arg * 6
assert getattr(fct, _ATTR_MARKER, None) == (("abc", "def"),)
assert ... | 2,859 | 1,082 |
"""Stockgrid DD View"""
__docformat__ = "numpy"
import argparse
from typing import List
from datetime import timedelta
import requests
import pandas as pd
import matplotlib.pyplot as plt
from tabulate import tabulate
from gamestonk_terminal.config_plot import PLOT_DPI
from gamestonk_terminal.feature_flags import USE_I... | 8,073 | 2,479 |
"""
This example demonstrates SQL Schema generation for each DB type supported.
"""
from tortoise import fields
from tortoise.fields import SET_NULL
from tortoise.models import Model
class Tournament(Model):
tid = fields.SmallIntField(pk=True)
name = fields.CharField(max_length=100, description="Tournament n... | 2,428 | 734 |
# Copyright (c) 2014 Rackspace, 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 applicable law or agreed to in wr... | 9,025 | 3,171 |
from __future__ import unicode_literals
import six
class StringUtils(object):
"""
Utility class for handling strings.
"""
@staticmethod
def to_unicode(value):
"""
Returns the string representation of the given L{value} if it is not C{None}. Otherwise,
returns ... | 1,889 | 525 |
arr=[int(x) for x in input().split()]
sum=0
for i in range(1,(arr[2]+1)):
sum+=arr[0]*i
if sum<=arr[1]:
print(0)
else:
print(sum-arr[1])
| 149 | 70 |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import re
import json
from ansible.plugins.terminal import TerminalBase
from ansible.errors import AnsibleConnectionFailure
from ansible.module_utils._text import to_bytes, to_text
class TerminalModule(TerminalBase):
termin... | 2,578 | 851 |
from numpy.core.fromnumeric import size
import utils as u
import numpy as np
import heapq as hq
s = """\
1163751742
1381373672
2136511328
3694931569
7463417111
1319128137
1359912421
3125421639
1293138521
2311944581
"""
#cave = np.array([[int(x) for x in l] for l in s.splitlines()])
cave = u.import_data("./data/inpu... | 1,690 | 720 |
from xmlrpc.client import Boolean
import boto3
import logging
from datetime import date, datetime
from botocore.exceptions import ClientError
import json
from json_datetime_serializer import json_datetime_serializer
from kms_client import kmsClient
from search_kms_using_account_id import search_kms_using_account_id
fro... | 1,861 | 610 |