text string | size int64 | token_count int64 |
|---|---|---|
import numpy as np
import math
from pandas import DataFrame
def min_rw_index(prices, start, end):
"""
Searches min price index inside window [start,end]
:param prices: in list format
:param start: window start index
:param end: window end index
:return:
"""
matching_index = start
... | 17,132 | 5,510 |
from cymepy.export_manager.base_definations import ExportManager
from cymepy.common import EXPORT_FILENAME
import json
import os
class Writer(ExportManager):
def __init__(self, sim_instance, solver, options, logger, **kwargs):
super(Writer, self).__init__(sim_instance, solver, options, logger, **kwargs)
... | 772 | 230 |
import discord
from redbot.core import Config, checks, commands
listener = getattr(commands.Cog, "listener", None) # red 3.0 backwards compatibility support
if listener is None: # thanks Sinbad
def listener(name=None):
return lambda x: x
class Fenrir(commands.Cog):
"""
Various unreasonabl... | 5,320 | 1,612 |
from .gobigger_structed_simple_model import GoBiggerHybridActionSimpleV3
from .my_gobigger_structed_model_v1 import MyGoBiggerHybridActionV1 | 140 | 49 |
# -*- coding = utf-8 -*-
# @Time: 2022/4/13 19:35
# @Author: Anshang
# @File: Client.py
# @Software: PyCharm
import socket
from multiprocessing import Process, Pipe
def connection(pipe: Pipe, username, password):
ip_bind = ("127.0.0.1", 9900)
c = socket.socket()
c.connect(ip_bind)
login = 'login ' + ... | 1,967 | 682 |
import unittest
import warnings
from unittest.mock import (
patch,
)
from uuid import (
UUID,
uuid4,
)
from minos.common import (
Model,
)
from minos.networks import (
BrokerMessageV1,
BrokerMessageV1Payload,
BrokerMessageV1Status,
BrokerMessageV1Strategy,
)
from tests.utils import (
... | 11,677 | 3,228 |
from invoke import Collection
from . import (
container,
cpython,
func,
git,
libs,
mxnet,
runtime,
)
ns = Collection(
container,
cpython,
func,
git,
libs,
mxnet,
runtime,
)
| 231 | 86 |
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder
from kivy.app import App
import YP03
import sys
import dfgui
import pandas as pd
Builder.load_string('''
<faceTool>:
num1: num1
result: result
orientation: 'vertical'
BoxLayout:
orientation: 'horizontal'
Label:
... | 2,416 | 700 |
from AdjacencyAttentionWithoutSelfloopTransformers import (
AdamW,
T5ForConditionalGeneration,
T5Tokenizer,
get_linear_schedule_with_warmup
)
from torch.utils.data import DataLoader
from src.dataset import JsonDatasetWQ, JsonDatasetPQ
from datetime import strftime, localtime
from tqdm.auto import tqdm
from om... | 3,196 | 1,057 |
import logging
from flask import Response, make_response, request
from microraiden import HTTPHeaders as header
from flask_restful.utils import unpack
from microraiden.channel_manager import (
ChannelManager,
)
from microraiden.exceptions import (
NoOpenChannel,
InvalidBalanceProof,
InvalidBalanceAmoun... | 7,344 | 1,986 |
"""
the nk-Record
=============
Offset Size Contents
0x0000 Word ID: ASCII-"nk" = 0x6B6E
0x0002 Word for the root-key: 0x2C, otherwise 0x20
0x0004 Q-Word write-date/time in windows nt notation
0x0010 D-Word Offset of Owner/Parent key
0x0014 D-Word number of sub-Keys
0x001C D-Word Offset of the sub-key lf-Records
0x0... | 4,241 | 1,899 |
import attr
@attr.s
class HANItem:
sentences = attr.ib()
label = attr.ib()
| 85 | 33 |
import datetime
from typing import List, Union
import numpy as np
from sqlalchemy.dialects.postgresql import insert
from sqlalchemy.types import Date, Float, Integer, Numeric, String
import omicron
from omicron import db
from omicron.client.quotes_fetcher import get_valuation
class Valuation(db.Model):
__tablen... | 4,637 | 1,785 |
import caffe
from caffe import layers as L
from caffe import params as P
def conv_bn_scale_relu(bottom, num_output=64, kernel_size=3, stride=1, pad=0):
conv = L.Convolution(bottom, num_output=num_output, kernel_size=kernel_size, stride=stride, pad=pad,
param=[dict(lr_mult=1, decay_mult=1)... | 8,064 | 3,035 |
from datetime import datetime
from glasskit.commands import Command
from glasskit import ctx
from ask.models.post import BasePost
from ask import force_init_app
POST_INDEX_SETTINGS = {
"settings": {
"analysis": {
"normalizer": {
"lower": {
"type": "custom"... | 3,145 | 869 |
# -*- coding: UTF-8 -*-
"""
split_by_area
===========
Script : split_by_area.py
Author : Dan_Patterson@carleton.ca
Modified: 2018-08-27
Purpose : tools for working with numpy arrays
Notes:
-----
The xs and ys form pairs with the first and last points being identical
The pairs are constructed ... | 6,350 | 2,374 |
from scipy import linalg
from sklearn.decomposition import PCA
from scipy.optimize import linear_sum_assignment as linear_assignment
import numpy as np
"""
A function that takes a list of clusters, and a list of centroids for each cluster, and outputs the N max closest images in each cluster to its centroids
"""
def cl... | 2,081 | 705 |
// This is the text editor interface.
// Anything you type or change here will be seen by the other person in real time.
import java.util.*;
public class HelloWorld {
public static boolean isSentence(String s, HashSet<String> d) {
return false;
}
public static void main(String[] args) {
... | 1,247 | 434 |
from django.conf import settings
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.views.generic import TemplateView
from phantastes import views
from django.contrib import admin
urlpatterns = patterns(
"",
url(r"^$", views.index, name="home"),
url... | 860 | 287 |
import os, sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from flask.ext.script import Manager, Server
from app import app
manager = Manager(app)
manager.add_command("runserver", Server(
use_debugger = True,
use_reloader = True,
host = '0.0.0.0')
)
if __name__ == "__main__":
... | 335 | 129 |
'''
Samuel Remedios
NIH CC CNRM
Train PhiNet to classify MRI modalities
'''
import os
import json
from keras.callbacks import ModelCheckpoint, TensorBoard, ReduceLROnPlateau, EarlyStopping
from keras import backend as K
from keras.models import model_from_json
from models.phinet import phinet, phinet_2D
from models.mu... | 5,035 | 1,693 |
from .base_resources import Resource, ResourceCollection, ResourceList
class APICompany(Resource, ResourceCollection):
def __init__(self, client, endpoint='', filters=None):
self.resources = (
APIBanks,
APICurrencies,
APIBankAccount,
APIBankAccounts
... | 960 | 278 |
import copy
import time
from datetime import datetime
import binascii
import graphviz
import random
from .models.enums.start_location import StartLocation
from .models.enums.goal import Goal
from .models.enums.statue_req import StatueReq
from .models.enums.entrance_shuffle import EntranceShuffle
from .models.enums.ene... | 325,343 | 138,841 |
import datetime
import os
import time
from enum import Enum
import sys
from MediaPlayer.Player import vlc
from MediaPlayer.Player.vlc import libvlc_get_version, Media, MediaList
from Shared.Events import EventManager, EventType
from Shared.Logger import Logger, LogVerbosity
from Shared.Observable import Observable
fr... | 8,938 | 2,739 |
# Primitive reimplementation of the buildflag_header scripts used in the gn build
def _buildflag_header_impl(ctx):
content = "// Generated by build/buildflag_header.bzl\n"
content += '// From "' + ctx.attr.name + '"\n'
content += "\n#ifndef %s_h\n" % ctx.attr.name
content += "#define %s_h\n\n" % ctx.at... | 937 | 332 |
import unittest
from led8x8m import LedMatrix
class TestLedMatrix(unittest.TestCase):
def test_pin_numbers(self):
self.assertEqual(len(LedMatrix.PIN_X), 8)
self.assertEqual(len(LedMatrix.PIN_Y), 8)
set_x = set(LedMatrix.PIN_X)
set_y = set(LedMatrix.PIN_Y)
self.assertEqual(l... | 737 | 269 |
# Space: O(n)
# Time: O(n)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def convertBST(self, root):
if (root is None) or (root.left is None an... | 1,240 | 384 |
"""Exploits currently supported
Straightforward to add more following the basic model presented here
"""
from .action import Exploit
import time
def wait_for_job_completion(job_info, client):
if job_info is not None:
if "error" in job_info:
return
job_is_running = True
while... | 14,652 | 4,713 |
# Copyright 2018-2021 Xanadu Quantum Technologies 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... | 10,178 | 3,337 |
try: paraview.simple
except: from paraview.simple import *
paraview.simple._DisableFirstRenderCameraReset()
PlotOverLine6 = GetActiveSource()
PlotOverLine6.Input = []
PlotOverLine6.Source = []
XYChartView1 = GetRenderView()
Delete(PlotOverLine6)
AnimationScene1 = GetAnimationScene()
AnimationScene1.EndTime = 1.0
Ani... | 3,106 | 1,418 |
#!/usr/bin/env python
import unittest
from acme import Product
from acme_report import generate_products, ADJECTIVES, NOUNS
class AcmeProductTests(unittest.TestCase):
"""Making sure Acme products are the tops!"""
def test_default_product_price(self):
"""Test default product price being 10."""
... | 1,420 | 438 |
from discord.ext import commands
import discord
from datetime import datetime
from src import util
from tools.checker import Checker,Embed
class Meta(commands.Cog):
"""Commands relating to the bot itself."""
def __init__(self, bot):
self.bot = bot
self.start_time = datetime.now()
bot.r... | 909 | 302 |
import os
import logging
from contextlib import contextmanager
from tempfile import TemporaryDirectory, mkdtemp
from pathlib import Path
from six import string_types
from sciencebeam_trainer_delft.utils.io import copy_file, path_join
LOGGER = logging.getLogger(__name__)
def _is_cloud_location(filepath):
retur... | 2,399 | 771 |
from logging import warning
from api import gitlab
from utilities import validate, types
gitlab = gitlab.GitLab(types.Arguments().url)
def get_all(projects):
snippets = {}
for project in projects:
for key, value in project.items():
details = gitlab.get_project_snippets(key)
i... | 1,048 | 327 |
import requests
if __name__ == "__main__":
headers = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
'Accept-Language': 'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',
'User-Agent': 'Mozilla/5.0 (Macintosh; ... | 670 | 277 |
from __future__ import annotations
__all__ = ('WatcherContext', 'Watcher')
import asyncio
import os
import time
from concurrent.futures import Executor, ThreadPoolExecutor
from contextlib import AsyncExitStack
from functools import partial
from typing import Awaitable, Callable, Optional, Protocol, Set, TypeVar, Un... | 6,708 | 1,906 |
import matplotlib.pyplot as plt
import requests
import pandas as pd
import json
data = requests.get(r'https://www.bitstamp.net/api/v2/order_book/ethbtc')
data = data.json()
bids = pd.DataFrame()
bids['quantity'] = [i[1] for i in data['bids']]
bids['price'] = [i[0] for i in data['bids']]
asks = pd.DataFrame()
asks['pr... | 2,709 | 1,151 |
import sys
script, input_encoding, error = sys.argv
def main(language_file, encoding, errors):
line = language_file.readline()
if line:
print_line(line, encoding, errors)
return main(language_file, encoding, errors)
def print_line(line, encoding, errors):
next_lang = line.strip()
raw_bytes = next_lang.encode(encoding, ... | 525 | 166 |
"""This module provides plugins for various imaging formats.
Standard plugins provides support for DICOM and Nifti image file formats.
"""
# Copyright (c) 2013-2018 Erling Andersen, Haukeland University Hospital, Bergen, Norway
import logging
import sys
import numpy as np
logger = logging.getLogger(__name__)
(SOR... | 5,728 | 1,936 |
import os
import aiohttp
import asyncio
import json
import time
import datetime
import logging
import gidgethub
import requests
from gidgethub import aiohttp as gh_aiohttp
import sys
import pandas as pd
sys.path.append("..")
from utils.auth import get_jwt, get_installation, get_installation_access_token
from utils.test... | 9,652 | 3,102 |
import threading
import urllib2
import json
import time
import curses
_SERVER = 'http://localhost:6543'
def post(message, token):
headers = {'X-Messaging-Token': token}
req = urllib2.Request(_SERVER, headers=headers)
req.get_method = lambda: 'POST'
message = {'text': message}
req.add_data(json.d... | 2,579 | 850 |
from .div2k import *
| 21 | 9 |
from .abstract import AbstractAgentBasedModel
import keras.backend as K
import numpy as np
from tensorflow import TensorShape
from keras.layers import Dense, Reshape
class TrajectorySamplerNetwork(AbstractAgentBasedModel):
'''
Supervised model. Takes in a set of trajectories from the current state;
lear... | 2,993 | 876 |
# Image ROI(Region of Images)
import cv2 as cv
img = cv.imread('Photes/messi.jpg')
cv.imshow('Orginal Messi_Football',img)
ball = img[280:340, 330:390]
img[273:333, 100:160] = ball
cv.imshow('Change Messi_Football',img)
"""
import matplotlib.pyplot as plt
data = plt.imread('Photes/messi.jpg')
plt.... | 351 | 173 |
# parsetab.py
# This file is automatically generated. Do not edit.
# pylint: disable=W,C,R
_tabversion = '3.10'
_lr_method = 'LALR'
_lr_signature = 'statement_listleftPLUSMINUSleftMULTIPLYDIVIDEAND ATOM BANG BOOL COLON COMMA DIVIDE ELIF ELSE END EQUAL EXIT FUN GT ID IF IMPORT LBRACE LBRACKET LPAREN LT MAC MINUS MULT... | 26,717 | 18,957 |
#!/usr/bin/env python
# import required modules:
#
import os
import sys
import string
import random
from random import shuffle
from pathlib2 import Path
import linecache
import time
# This class shuffles songs without repeating and keeps track of where
# it left off. See '-help' option for more details.
#
class shuff... | 5,253 | 1,298 |
"""conftest.py for stepseries."""
from threading import Event
from typing import Dict, Tuple
import pytest
from stepseries.responses import DestIP
from stepseries.step400 import STEP400
# store history of failures per test class name and per index in parametrize (if parametrize used)
_test_failed_incremental: Dict[... | 3,151 | 953 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Start Pymol and Bokeh server """
from __future__ import print_function
import time
import shlex
import subprocess
__author__ = "Jérôme Eberhardt"
__copyright__ = "Copyright 2016, Jérôme Eberhardt"
__lience__ = "MIT"
__maintainer__ = "Jérôme Eberhardt"
__email__ = "... | 1,334 | 477 |
import logging
from django.core.exceptions import ObjectDoesNotExist
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
from ...apps.users.utils import fetch_remote_user, create_local_user_from_remote_backend, \
update_local_user_from_rem... | 6,113 | 1,778 |
from django.db.backends.base.creation import BaseDatabaseCreation
class DatabaseCreation(BaseDatabaseCreation):
def create_test_db(self, *args, **kwargs):
import os
db_name = super().create_test_db()
here = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
wi... | 768 | 241 |
import numpy as np
from rampwf.utils import BaseGenerativeRegressor
class GenerativeRegressor(BaseGenerativeRegressor):
def __init__(self, max_dists, target_dim):
self.decomposition = 'autoregressive'
def fit(self, X_array, y_array):
pass
def predict(self, X_array):
# constant p... | 656 | 220 |
from copy import deepcopy
import os
ROOT = os.path.dirname(os.path.abspath(__file__)) + '/'
import numpy as np
from numpy.random import normal
from astropy import log as logger
from astropy.io import fits
from astropy.wcs import WCS
from .psf import GaussianPSF, FilePSF, FunctionPSF
from .utils.plot import MakePlots... | 29,982 | 9,276 |
#!/usr/bin/python
import argparse
from src.SCXML_Parser.Scxml_parsor import Scxml_parsor
from src.arduino_helper.generate_fsm import generate_fsm
parser = argparse.ArgumentParser()
parser.add_argument('-f', action='store', dest='file', type=str, required=False, default="fsm.xml")
inargs = parser.parse_args()
print ... | 435 | 153 |
import os,array
import pickle
import numpy as np
import sys
xid=pickle.load(open(sys.argv[1]))
asm_code_path=sys.argv[2]
train_or_test=asm_code_path.split('_')[-1]
X = np.zeros((len(xid),2000))
for cc,i in enumerate(xid):
f=open(asm_code_path+'/'+i+'.asm')
ln = os.path.getsize(asm_code_path+'/'+i+'.asm') # len... | 769 | 351 |
"""
Generate Validation Certificate bases on Azure IoT Hub Verification Code
Based on sample code from the cryptography library docs:
https://cryptography.io/en/latest/x509/tutorial/#creating-a-self-signed-certificate
"""
import datetime
from pathlib import Path
from cryptography.hazmat.primitives import has... | 1,961 | 718 |
import FWCore.ParameterSet.Config as cms
from HeavyIonsAnalysis.JetAnalysis.jets.akPu4PFJetSequence_PbPb_mc_cff import *
#PU jets with 10 GeV threshold for subtraction
akPu4PFmatch10 = akPu4PFmatch.clone(src = cms.InputTag("akPu4PFJets10"))
akPu4PFparton10 = akPu4PFparton.clone(src = cms.InputTag("akPu4PFJets10"))
ak... | 1,307 | 473 |
from django.conf.urls import include
from django.urls import path
from django.contrib import admin
from . import views
app_name = 'annotationweb'
urlpatterns = [
path('', views.index, name='index'),
path('datasets/', views.datasets, name='datasets'),
path('add-image-sequence/<int:subject_id>/', views.add_i... | 2,796 | 911 |
import numpy as np
import tensorflow as tf
def deconv_layer(output_shape, filter_shape, activation, strides, name):
scale = 1.0 / np.prod(filter_shape[:3])
seed = int(np.random.randint(0, 1000)) # 123
with tf.name_scope('conv_mnist/conv'):
W = tf.Variable(tf.random_uniform(filter_shape,
... | 7,015 | 2,483 |
import torch.nn as nn, torch.nn.functional as F, torch.distributions as D, torch.nn.init as init
from basalganglia.reinforce.util.torch_util import *
class PolicyNetwork(nn.Module):
def __init__(self, env, hidden_layer_width=128, init_log_sigma=0, min_log_sigma=-3):
super(PolicyNetwork, self).__init__()
... | 2,237 | 749 |
from displayarray.frame.frame_publishing import pub_cam_loop_opencv, pub_cam_thread
import displayarray
import mock
import pytest
import cv2
from displayarray.frame.np_to_opencv import NpCam
import numpy as np
import displayarray.frame.subscriber_dictionary as subd
import displayarray.frame.frame_publishing as fpub
d... | 4,894 | 1,791 |
import random
a1 = str(input(' diga o nome do aluno 1 '))
a2 = str(input(' diga o nome do aluno 2 '))
a3 = str(input(' diga o nome do aluno 3 '))
a4 = str(input(' diga o nome do aluno 4 '))
lista = [a1, a2, a3, a4]
escolhido = random.choice(lista)
print('O aluno soteado é o aluno {}'.format(escolhido))
| 308 | 134 |
# encoding:utf-8
import pika
import time
credentials = pika.PlainCredentials('guest', 'guest')
connection = pika.BlockingConnection(pika.ConnectionParameters(
host='s1004.lab.org',
port=5672,
virtual_host='/',
credentials=credentials))
channel = connection.channel()
channel.exchange_declare(exchange='... | 563 | 178 |
"""
Created on Nov 1, 2015
@author: ionut
"""
import logging
DEBUG = False
LOG_LEVEL = logging.INFO
DSN = "dbname=photomap user=postgres password=pwd host=127.0.0.1 port=5432"
TEMPLATE_PATH = "templates"
STATIC_PATH = "static"
MEDIA_PATH = "/home/ionut/nginx/media"
SECRET = "some_secret"
| 295 | 132 |
import typing
from collections import Counter
import numpy as np
from pytest import approx
from zero_play.connect4.game import Connect4State
from zero_play.game_state import GameState
from zero_play.heuristic import Heuristic
from zero_play.mcts_player import SearchNode, MctsPlayer, SearchManager
from zero_play.playo... | 11,031 | 4,016 |
print('Sequência de Fibonacci')
print('='*24)
t = int(input('Número de termos da sequência: '))
print('='*24)
c = 3
termo1 = 0
termo2 = 1
print('A sequência é ({}, {}, '.format(termo1, termo2), end='')
while c <= t:
termo3 = termo1 + termo2
print('{}'.format(termo3), end='')
print(', ' if c < t else '', end... | 387 | 168 |
#This code is a practice on Histogram Equalization
#Coded by: CSEMN (Mahmoud Nasser - Sec 4)
#Supervised by: Dr.Mohamed Berbar
__author__ = 'Mahmoud Nasser'
from tkinter import *
from tkinter import ttk
import cv2 as cv # if not installed please consider running : pip install opencv-python
from PIL import ImageTk,Image... | 3,992 | 1,358 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File: scenes/main_menu_manager.py
# -------------------
# Divine Oasis
# Text Based RPG Game
# By wsngamerz
# -------------------
import logging
import random
from divineoasis.assets import Assets
from divineoasis.audio_manager import AudioManager
from divineoasi... | 3,336 | 1,080 |
"""email templates"""
from builtins import object
class Email(object):
"""
Data structure that contains email content data
"""
msg_plain = ''
msg_html = ''
subject = u''
salt = ''
class myADSTemplate(Email):
"""
myADS email template
"""
msg_plain = """
SAO/NASA AD... | 469 | 143 |
#
# Open addresses Spatial Research
# Display Candidate Address Components From OS Open Map & Open Roads
#
#
# Version 1.0 (Python) in progress
# Author John Murray
# Licence MIT
#
# Purpose Display Candidate Address Components
#
import MySQLdb
import collections
import sys
# Database co... | 1,914 | 678 |
"""
Custom decorators
=================
Custom decorators for various tasks and to bridge Flask with Eve
"""
from flask import current_app as app, request, Response, abort
from functools import wraps
from ext.auth.tokenauth import TokenAuth
from ext.auth.helpers import Helpers
# Because of circu... | 2,645 | 691 |
# Generated by Django 2.2.5 on 2019-09-05 09:39
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('home', '0045_auto_20190409_1450'),
]
operations = [
migrations.AlterField(
model_name='leaguebadgeroundentry',
name=... | 3,978 | 1,149 |
#!/bin/sh
# it's a kind of magic to run python with -B key
# https://stackoverflow.com/questions/17458528/why-does-this-snippet-with-a-shebang-bin-sh-and-exec-python-inside-4-single-q
''''exec python3 -B -- "$0" ${1+"$@"} # '''
import os
import re
import setuptools
import setuptools.command.test
import sys
base_path... | 2,017 | 699 |
from collections import OrderedDict
from graphene import Field # , annotate, ResolveInfo
from graphene.relay import Connection, Node
from graphene.types.objecttype import ObjectType, ObjectTypeOptions
from graphene.types.utils import yank_fields_from_attrs
from mongoengine import DoesNotExist
from .converter import... | 4,613 | 1,262 |
from django.conf import settings
from django.db import models
from django.utils.translation import gettext_lazy as _
class Workspace(models.Model):
code = models.CharField(_('코드'), max_length=40, unique=True, editable=False)
name = models.CharField(_('이름'), max_length=50, unique=True)
owner = models.Forei... | 1,936 | 744 |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | 7,033 | 2,219 |
"""Miscelanous tools."""
| 25 | 11 |
import os
from setuptools import setup, find_packages
DIR_PATH = os.path.dirname(os.path.abspath(__file__))
with open(os.path.join(DIR_PATH, 'README.md')) as file:
long_description = file.read()
install_requires = [line.rstrip('\n') for line in open(os.path.join(DIR_PATH, 'requirements.txt'))]
setup(
name=... | 831 | 301 |
import card_dispenser
import time
card_dispenser_object = card_dispenser.card_dispenser()
while True:
card_dispenser_object.give_card()
time.sleep(10) | 159 | 60 |
# -*- coding: utf-8 -*-
import logging
from typing import Any, Dict, List, Mapping
try:
from collections import Mapping as CollectionsMapping
except ImportError:
from collections.abc import Mapping as CollectionsMapping
from brewtils.models import Parameter, Resolvable
from brewtils.resolvers.bytes import By... | 4,062 | 934 |
b = float(input('\033[36mQual a largura da parede? \033[m'))
h = float(input('\033[32mQual a altura da parede? \033[m'))
a = b * h
print('\033[36mSua parede tem dimensão {} x {} e sua área é de {:.3f}m².\033[m'.format(b, h, a))
print('\033[32mPara pintar essa parede, você precisará de {}L de tinta.\033[m'.format(a ... | 327 | 161 |
#!/usr/bin/env python3
NUMBER_OF_MARKS = 5
def avg(numbers):
return sum(numbers) / len(numbers)
def valid_mark(mark):
return 0 <= mark <= 100
def read_marks(number_of_marks):
marks_read = []
for count in range(number_of_marks):
while True:
mark = int(input(f'Enter mark #{coun... | 1,062 | 387 |
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'UserProfile.sjtu_id'
db.add_column(u'account_userprofile'... | 8,668 | 2,801 |
from multiprocessing import Pool, Queue
import multiprocessing
import threading
import time
def test(x):
x0,x1,x2 = x
time.sleep(2)
return x0+x1+x2, x0*x1*x2
# if p==10000:
# return True
# else:
# return False
class Dog():
def __init__(self):
pass
def go(self,name... | 1,689 | 739 |
from dudes.Ranks import Ranks
import numpy as np
import sys
def printDebug(DEBUG, l):
if DEBUG: sys.stderr.write(str(l) + "\n")
def group_max(groups, data, pre_order=None):
if pre_order is None:
order = np.lexsort((data, groups))
else:
order = pre_order
groups = groups[order] #this is only needed if grou... | 893 | 328 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 3 10:27:25 2019
@author: alishbaimran
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from imutils import paths
from sklearn.metrics import classification_report
from sklearn.metrics import accuracy_score
f... | 4,169 | 1,474 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.17 on 2019-07-12 18:40
from __future__ import unicode_literals
import core.helpers
from django.db import migrations, models
import django.db.models.deletion
import simple_history.models
class Migration(migrations.Migration):
initial = True
dependencies = [... | 24,503 | 7,226 |
class Vertex:
'''This class will create Vertex of Graph, include methods
add neighbours(v) and rem_neighbor(v)'''
def __init__(self, n): # To initiate instance Graph Vertex
self.name = n
self.neighbors = list()
self.color = 'black'
def add_neighbor(self, v): # To add... | 2,205 | 693 |
# encoding: utf-8
from antlr4 import *
from io import StringIO
from typing.io import TextIO
import sys
def serializedATN():
with StringIO() as buf:
buf.write("\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\3@")
buf.write("\u027b\4\2\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7\t\7")
buf.writ... | 213,896 | 74,822 |
import cv2 as cv # opencv
import copy # for deepcopy on images
import numpy as np # numpy
from random import randint # for random values
import threading # for deamon processing
from pathlib import Path # for directory information
import os # for directory information
from constants import constants # const... | 14,876 | 5,303 |
from pygame import *
from random import randint
window = display.set_mode((700, 500))
display.set_caption('Шутер')
lost = 0
c = 0
class GameSprite(sprite.Sprite):
def __init__(self, player_image, player_x, player_y, player_w, player_h, player_speed):
super().__init__()
self.image = transform.scale(i... | 3,061 | 1,249 |
import os
import numpy as np
import torch
import torch.nn as nn
import torchvision
import torch.utils.data as Data
import torchvision.transforms as transforms
import torchvision.datasets as datasets
from torch.autograd import Variable
from torch.nn import functional as F
from action40_config import config
import vgg16_... | 5,948 | 2,149 |
# Coding: utf-8
"""Script para analisar, agrupar dados provenientes dos logs da ferramenta
de migração das coleções SciELO."""
import argparse
import functools
import json
import logging
import re
import sys
from enum import Enum
from io import TextIOWrapper, IOBase
from typing import Callable, Dict, List, Optional, ... | 15,627 | 4,980 |
# -*- coding: utf-8 -*-
# _ __
# | |/ /___ ___ _ __ ___ _ _ ®
# | ' </ -_) -_) '_ \/ -_) '_|
# |_|\_\___\___| .__/\___|_|
# |_|
#
# Keeper Commander
# Copyright 2015 Keeper Security Inc.
# Contact: ops@keepersecurity.com
#
import logging
import subprocess
import re
def rotate(record, n... | 786 | 259 |
from punting.twodim.twosynthetic import random_harville_market
def test_synthetic():
n = 7
m = random_harville_market(n=n, scr=-1)
if __name__=='__main__':
test_synthetic() | 188 | 77 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
"""Specifies static assets (CSS, JS) required by the CATMAID front-end.
This module specifies all the static files that are required by the
synapsesuggestor front-end.
"""
from collections import OrderedDict
JAVASCRIPT = OrderedDict()
JAVASCRIPT['syna... | 488 | 174 |
from pathlib import Path
import click
import cligj
import geojson
import mercantile
from shapely.geometry import asShape, box
from shapely.ops import split
@click.command()
@cligj.features_in_arg
@click.option(
'-z',
'--min-zoom',
type=int,
required=True,
help='Min zoom level to create tiles for'... | 3,019 | 994 |
from __future__ import annotations
from typing import List, Optional
from xrpl import CryptoAlgorithm
from xrpl.core.addresscodec import encode_account_public_key, encode_node_public_key
from xrpl.core.keypairs import derive_keypair, generate_seed
from xrpl.wallet import Wallet
from slk.config.helper_classes import ... | 2,262 | 680 |
from flask import Flask,Response
from flask import render_template
import os
from os import path,system
from flask import request
import json
from flask_cors import CORS
import shutil
# Model Definition
import math
import serialization
import numpy as np
import types
from enum import Enum
import video_capture
#pathToPy... | 5,132 | 1,506 |
import lightgbm as lgb
from .model import Base_Model
from src.utils import Pkl
class Model_LightGBM(Base_Model):
def train(self, x_trn, y_trn, x_val, y_val):
validation_flg = x_val is not None
# Setting datasets
d_trn = lgb.Dataset(x_trn, label=y_trn)
if validation_flg:
... | 1,526 | 504 |
### DEPRECATE THESE? OLD VERSIONS OF CLEANING FUNCTIONS FOR JUST EBIKES
### NO LONGER WORKING WITH THESE
import pandas as pd
import numpy as np
from shapely.geometry import Point
import geopandas as gpd
from cabi.utils import which_anc, station_anc_dict
from cabi.get_data import anc_gdf
gdf = anc_gdf()
anc_dict = st... | 4,031 | 1,497 |