text string | size int64 | token_count int64 |
|---|---|---|
from setuptools import find_packages, setup
setup(
name='django-studentsdb-app',
version='1.0',
author=u'Vova Khrystenko',
author_email='ovod88@bigmir.net',
packages=find_packages(),
license='BSD licence, see LICENCE.txt',
description='Students DB application',
long_description=open('RE... | 460 | 156 |
from .words import *
class Node:
def __init__(self ,docId, freq = None):
self.freq = freq
self.doc = docId
self.nextval = None
class SlinkedList:
def __init__(self ,head = None):
self.head = head
linked_list_data = {}
for word in unique_words_all:
linked_list_data[word] = ... | 1,142 | 396 |
#!/usr/bin/env python
import pathlib
import matplotlib.pyplot as plt
import torch
import pyro
from state_space import state_space_model
SEED = 123
torch.manual_seed(SEED)
pyro.set_rng_seed(SEED)
def main():
figdir = pathlib.Path('./figures')
figdir.mkdir(exist_ok=True)
# demo predictive capacity
... | 2,201 | 812 |
#!/usr/bin/env python
"""Test era module"""
import unittest
import os
from os.path import join
from shutil import rmtree
import numpy as np
from modred import era, parallel, util
from modred.py2to3 import range
def make_time_steps(num_steps, interval):
"""Helper function to find array of integer time steps.
... | 11,554 | 3,504 |
def my_function() -> str:
return "todo bien"
| 49 | 18 |
#!/usr/bin/env python3
# import additional code to complete our task
import shutil
import os
# move into the working directory
os.chdir("/home/student/mycode/")
# copy the fileA to fileB
shutil.copy("5g_research/sdn_network.txt", "5g_research/sdn_network.txt.copy")
# copy the entire directoryA to directoryB
shutil.... | 368 | 130 |
# coding=utf-8
'''
Ce fichier contient un script permettant de lier une application web en, PHP 5.6 avec Symfony et doctrine, avec l'administration d'un serveur et nottament de son pare-feu (iptables)
Permet d'ouvrir des ports pour des adresses IPs récupérer en base de données et ajouté via l'application web.
'''
__au... | 3,020 | 1,046 |
from typing import Any, List, Mapping, Sequence
import jsonschema
from dataclasses import dataclass, field
from sqlalchemy.orm import scoped_session
from vardb.datamodel.jsonschemas.load_schema import load_schema
from vardb.datamodel import annotation
@dataclass
class ConverterConfig:
elements: Sequence[Mapping[s... | 2,277 | 649 |
import os
import cv2
import numpy as np
from utils.augmentations import Albumentations, augment_hsv, copy_paste, letterbox
from models.common import DetectMultiBackend
from utils.datasets import IMG_FORMATS, VID_FORMATS, LoadImages, LoadStreams
from utils.general import (LOGGER, check_file, check_img_size, check_imshow... | 1,266 | 465 |
#!/usr/bin/env python
# coding: utf-8
import pandas as pd
def get_age(name):
df = pd.read_excel("test.xlsx", sheet_name="Sheet1", headers=True)
print("*"*20)
print(df)
print("*"*20)
rows, cols = df[df['Name']==name].shape
print(rows, cols, "^^^")
if rows==1:
age = df[df['Name... | 884 | 349 |
import tensorflow as tf
import numpy as np
import cv2
import os
import rospy
from timeit import default_timer as timer
from styx_msgs.msg import TrafficLight
CLASS_TRAFFIC_LIGHT = 10
MODEL_DIR = 'light_classification/models/'
IMG_DIR = 'light_classification/img/'
DEBUG_DIR = 'light_classification/result/'
class TL... | 8,638 | 2,776 |
import math
import torch
from torch.utils.data import Sampler
import torch.distributed as dist
import numpy as np
def get_valid_starts_and_ends(get_frame_arguments: np.ndarray, min_state_index: int = 0):
get_frame_arguments = get_frame_arguments[:] # put on the memory if the array is zarr
scene_change_poin... | 3,540 | 1,117 |
from . import v1
from .request import Request
from .util import task, extract_id
class Vault(v1.SysEndpoint):
def __init__(self, addr, token=None, cert=None, verify=True):
token = extract_id(token)
self.req_handler = Request(addr, 'v1', token=token,
cert=cert, v... | 1,680 | 523 |
import json,sys,re,math
from random import random
import numpy as np
from pprint import pprint
from sklearn import svm
from sklearn.pipeline import Pipeline
from sklearn.feature_extraction.text import CountVectorizer,TfidfTransformer
from sklearn.feature_extraction import DictVectorizer
from sklearn.naive_bayes import... | 2,559 | 999 |
from api import app
if __name__ == '__main__':
with open('urls.json', 'w') as fj:
fj.write('')
app.run() | 121 | 47 |
# -*- coding: utf-8 -*-
"""
@author: Shashank Sapaliga, Shashwat Sagar, Ishpreet Kaur, Dhwani Shah
"""
from Processor.Processor import Processor
from WebScrapper.Scrapper import Scrapper
import json
import os
print("The Data is being scrapped please wait!!!!!!!!!!")
start=0
flag = 1
scrap = Scrapper()
... | 932 | 341 |
import json
data = '''
{
"name" : "Chuck",
"phone" : {
"type" : "intl",
"number" : "+1 734 303 4456"
},
"email" : {
"hide" : "yes"
}
}'''
info = json.loads(data)
print 'Phone:',info["phone"]
print 'Number:',info["phone"]["number"]
| 259 | 118 |
# ========================= eCAL LICENSE =================================
#
# Copyright (C) 2016 - 2019 Continental Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http... | 2,384 | 759 |
import csv
import cv2
import numpy as np
from scipy import ndimage
# Setup Keras
from keras.models import Sequential, Model
from keras.layers import Flatten, Dense, Lambda, Dropout
from keras.layers.convolutional import Conv2D
from keras.layers.pooling import MaxPooling2D
from keras.layers import Cropping2D
from sklear... | 5,022 | 1,501 |
# Copyright (c) 2014-2020 Cloudify Platform Ltd. 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 b... | 3,414 | 1,089 |
# Generated by Django 2.0.7 on 2018-07-22 10:16
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('common', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='miscstorageentry',
name='value',
... | 370 | 123 |
# MTS Log protocol -- http://www.innovatemotorsports.com/support/downloads/Seriallog-2.pdf
# Serial: 8-N-1-19.2 kbit/sec
# Packet periodicity: 81.92 milliseconds (12.2 hertz) (8 MHz / 655360)
# Sample resolution: 10 bits (0..5V at 0.1% resolution)
import Header
from word import *
| 282 | 119 |
"""
data表
create by judy
2019/02/20
插入data表前判断数据是否存在于数据库中
update by judy 2019/03/22
作为当前数据的唯一标识,保留当前数据的uniqueid
不再需要account来分辨不同的账号,因为uniqueid确实回事独一无二的
update by judy 2019/03/27
"""
from datacontract.outputdata import EStandardDataType
import traceback
from commonbaby.helpers import helper_time
from commonbaby.sql i... | 6,688 | 2,002 |
from resorganizer.aux import *
class Command(object):
"""Command is an abstraction for any command line able to be executed. Command line has the components:
program name, params (flags followed by some values, e.g. -f filename), flags (alone flags. e.g. -f)
and trailing arguments. Some of these may be op... | 4,461 | 1,143 |
"""Created on Sat Oct 01 2015 16:24.
@author: Nathan Budd
"""
import numpy as np
def coe2mee(COE, mu=1.):
"""
Convert classical orbital elements to modified equinoctial elements.
Parameters
----------
COE : ndarray
mx6 array of elements ordered as [p e i W w nu].
mu : float
S... | 931 | 400 |
#
# Copyright (c) 2015 Red Hat
# Licensed under The MIT License (MIT)
# http://opensource.org/licenses/MIT
#
"""
Use the provided metadata generator if you wish to support OPTIONS requests on
list url of resources that support bulk operations. The only difference from
the generator provided by REST Framework is that it... | 2,602 | 613 |
import re
txt = "Hello welcome to hacktober fest"
x = re.search("hacktober", txt)
| 83 | 29 |
from django import template
register = template.Library()
@register.inclusion_tag('templatetags/form_field.html')
def show_form_field(field, icon=False):
return {'field': field, 'icon': icon}
@register.inclusion_tag('templatetags/learning_resource.html')
def show_resource(resource):
return {'resource': resou... | 324 | 100 |
#
#
# 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 n... | 2,040 | 561 |
import random
from music_theory.note import Note
class Mode:
def __init__(self):
self._modes = [
# Major oriented
"Ionian",
"Dorian",
"Phrygian",
"Lydian",
"Mixo",
"Aeolian",
"Locrian",
# Melodic ... | 1,347 | 418 |
from utils import *
car = get_car()
# Positive cases. Can't print the result because the address may change
# from run to run.
#
dbgscript.search_memory(car['name'].address-16, 100, b'FooCar', 1)
dbgscript.search_memory(car['name'].address-16, 100, b'FooCar', 2)
# Negative cases.
#
# 4 is not a multipl... | 878 | 353 |
words_file = open('wordlist.txt')
print("export const VALIDGUESSES6 = [")
for word in words_file.read().split('\n'):
word = word.strip()
if word.isalpha() and len(word) == 6:
print(' "%s",' % word.lower())
print("];") | 234 | 85 |
graph = {}
n = input().split(' ')
node, edge, start = map(int, n)
for i in range(edge):
edge_number = input().split(' ')
n1, n2 = map(int, edge_number)
if n1 not in graph:
graph[n1] = [n2]
elif n2 not in graph[n1]:
graph[n1].append(n2)
if n2 not in graph:
graph[n2] = [... | 1,132 | 387 |
from django.test import TestCase
from . import models
# Create your tests here.
class FlowTest(TestCase):
def setUp(self):
flow = models.ReportFlow.objects.create(
specification='od-base.pd.ard.rd')
self.fielduser = models.ROUser(Office='pso-borong')
self.fielduser.Flow = flow... | 1,470 | 460 |
from topfarm.utils import smart_start
import numpy as np
from topfarm.tests import npt
from topfarm import TopFarmProblem
from py_wake.examples.data import hornsrev1
from py_wake.deficit_models.noj import NOJ
from topfarm.easy_drivers import EasyScipyOptimizeDriver
from topfarm.constraint_components.boundary import Ci... | 6,094 | 2,823 |
import yaml
from jinja2 import Template
from argparse import ArgumentParser
parser = ArgumentParser("Specifying the YAML File")
parser.add_argument("-d", "--data-file",
help="Please specify the YAMl file.",
required=True
)
parser.add_argument("-t", "--templat... | 1,459 | 413 |
import torch
from src import config, models
from src.models import WGANGPGModel, WGANGPDModel
from src.datasets import PositiveDataset
from ._base import Base
class WGANGP(Base):
def __init__(self):
super().__init__(WGANGPGModel(), WGANGPDModel())
def _fit(self):
d_optimizer = torch.optim.Ad... | 2,415 | 776 |
import pickle
from sys import intern
from numpy import uint32
import numpy as np
import zarr
from napari_plugin_engine import napari_hook_implementation
from qtpy.QtWidgets import QWidget, QHBoxLayout, QPushButton
from magicgui import magic_factory
import pathlib
import napari
def viterbrain_reader(path: str) -> lis... | 2,050 | 723 |
#!/usr/bin/env python
# encoding: utf8
#
# Copyright © Burak Arslan <burak at arskom dot com dot tr>,
# Arskom Ltd. http://www.arskom.com.tr
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are ... | 5,122 | 1,729 |
import pandas as pd
import re
import numpy as np
import os
import sys
from collections import OrderedDict, defaultdict
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns
# from theano import *
# load state data
az_year = pd.read_csv("data/csv/price_expenditures/sector/az/price/teacd.csv", e... | 488 | 168 |
#
# PySNMP MIB module TPLINK-COMMANDER-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TPLINK-COMMANDER-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:16:55 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (defau... | 3,657 | 1,500 |
from typing import Any, Dict, Optional, Union
from ConfigSpace.configuration_space import ConfigurationSpace
from ConfigSpace.hyperparameters import (
CategoricalHyperparameter,
)
import imgaug.augmenters as iaa
from imgaug.augmenters.meta import Augmenter
import numpy as np
from autoPyTorch.datasets.base_datas... | 2,410 | 631 |
'''
Unittests/Chemical/Building_Blocks/aminoacids
_____________________________________________
Unit tests for aminoacid lookups.
:copyright: (c) 2015 The Regents of the University of California.
:license: GNU GPL, see licenses/GNU GPLv3.txt for more details.
'''
# load modules/submodules
import ... | 974 | 346 |
#!/usr/local/CyberCP/bin/python
import os
import os.path
import sys
import django
sys.path.append('/usr/local/CyberCP')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CyberCP.settings")
django.setup()
import json
from plogical.acl import ACLManager
import plogical.CyberCPLogFileWriter as logging
from plogical.virtual... | 61,304 | 16,498 |
import sympy as sp
from sympy.solvers.solveset import linsolve
def printa_latex(eq):
# Lê J e M no lado esquerdo da equação
J_lt = eq[0][1]
M_lt = eq[0][2]
# Monta o código em LaTeX para o lado esquerdo da equação
lado_esquerdo = '|' + sp.latex(J_lt) + ';' + sp.latex(M_lt) + '\\rangle' + '='
... | 8,970 | 3,577 |
from typing import List
from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordRequestForm
from sqlalchemy.ext.asyncio import AsyncSession
from src.schema import user as user_schema, task as task_schema
from src.cruds import user as user_crud
from src.libs import authen... | 1,653 | 509 |
from unittest import TestCase
import maguey
class TestSystems(TestCase):
def test_add_system(self):
pass
def test_delete_system(self):
pass
| 166 | 52 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time : 18-5-15 下午4:54
# @Author : Guoliang PU
# @File : regressor_with_kerasSquential.py
# @Software: tfwrapper
import numpy as np
np.random.seed(1337)
from keras.models import Model
from keras.layers import Dense
from keras.layers import Activation
import matp... | 1,321 | 591 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This is a skeleton file that can serve as a starting point for a Python
console script. To run this script uncomment the following line in the
entry_points section in setup.cfg:
Then run `python setup.py install` which will install the command `download`
inside your c... | 13,238 | 3,821 |
from tkinter import *
from tkinter import messagebox
rootWidget = Tk()
rootWidget.title("Message Box Example")
def messageBox():
response = messagebox.showinfo(title="Show Info", message="Message")
Label(rootWidget, text = response).pack()
Button(rootWidget,text= "Click Me!!", command = messageBox).pack()
... | 344 | 105 |
# 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 writing, software
# ... | 5,409 | 1,969 |
import re
import markdown
from django.contrib import messages
from django.db.models import Q
from django.shortcuts import render, get_object_or_404, redirect
from django.utils.text import slugify
from django.views.generic import ListView, DetailView
from markdown.extensions.toc import TocExtension
from pure_pagination.... | 2,977 | 1,130 |
from django.apps import AppConfig
class SentryConfig(AppConfig):
name = 'sentry'
| 87 | 28 |
import pytest
from nbformat.v4.nbbase import new_notebook, \
new_markdown_cell, new_code_cell, new_raw_cell
import jupytext
from jupytext.compare import compare_notebooks, \
test_round_trip_conversion as round_trip_conversion
jupytext.file_format_version.FILE_FORMAT_VERSION = {}
def test_raise_on_different_m... | 4,284 | 1,405 |
def hello(name):
return 'Hello ' + 'name'
def test_hello():
assert hello('name') == 'Hello name' | 105 | 35 |
#!/usr/bin/env python
class MatrixUtil:
@classmethod
def allocateMatrix(cls, numRows, numCols):
rv = [0.0] * numRows
for i in range(numRows):
rv[i] = [0.0] * numCols
return rv
@classmethod
def allocateMatrixAsRowMajorArray(cls, numRows, numCols):
return [0.... | 1,921 | 550 |
# uncompyle6 version 3.7.4
# Python bytecode 3.7 (3394)
# Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)]
# Embedded file name: T:\InGame\Gameplay\Scripts\Server\plex\plex_service.py
# Compiled at: 2020-03-06 03:39:09
# Size of source mod 2**32: 8464 bytes
from ... | 4,279 | 1,483 |
import os
KEY = os.environ['KEY']
from urllib.parse import parse_qs, urlparse
import requests
def getid(url):
if url.startswith("http"):
try:
url_data = urlparse(url)
query = parse_qs(url_data.query)
return query["v"][0]
except KeyError:
return ur... | 962 | 320 |
"""
This is is a part of the DeepLearning.AI TensorFlow Developer Professional Certificate offered on Coursera.
All copyrights belong to them. I am sharing this work here to showcase the projects I have worked on
Course: Introduction to TensorFlow for Artificial Intelligence, Machine Learning, and Deep Learning
... | 6,109 | 2,329 |
with open("input.txt") as input_file:
lines = input_file.readlines()
result = 0
for line in lines:
print(line.strip(), result)
result += int(line.strip())
print(result)
| 182 | 62 |
# pylint: disable=redefined-outer-name
# pylint: disable=unused-argument
# pylint: disable=unused-import
import json
import subprocess
import sys
from pathlib import Path
from typing import Callable, Dict
import pytest
import models_library
pytest_plugins = [
"pytest_simcore.repository_paths",
"pytest_simcor... | 1,435 | 483 |
# Copyright (c) 2017, Enthought, Inc.
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in LICENSE.txt and may be redistributed only
# under the conditions described in the aforementioned license. The license
# is also available online at http://www.ent... | 3,974 | 1,277 |
from robot.libraries.BuiltIn import BuiltIn
import os
import percy
class RobotFrameworkPercy():
ROBOT_LIBRARY_SCOPE = 'TEST SUITE'
def __init__(self):
self.percy_runner = None
def Percy_Initialize_Build(self, **kwargs):
driver = BuiltIn().get_library_instance('SeleniumLibrary').driver
... | 1,146 | 349 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 17 11:02:21 2019
@author: elizabethhutton
"""
import pandas as pd
import numpy as np
from sklearn.manifold import TSNE
from matplotlib import pyplot as plt
from sklearn.cluster import KMeans
from wordcloud import WordCloud
from yellowbrick.cluster ... | 3,434 | 1,173 |
from netmiko import ConnectHandler
from getpass import getpass
device1 = {
'host' : 'cisco4.lasthop.io',
'username' : 'pyclass',
'password' : getpass(),
'device_type' : 'cisco_ios',
'global_delay_factor' : 2,
}
net_connect = ConnectHandler(**device1)
print(net_connect.find_prompt())
output = net_... | 1,095 | 381 |
# -*- coding: utf-8 -*-
import os
import telebot
import time
import random
import threading
from emoji import emojize
from telebot import types
from pymongo import MongoClient
import traceback
token = os.environ['TELEGRAM_TOKEN']
bot = telebot.TeleBot(token)
fighters=[]
btimer=10
names=['Волк', 'Осёл', 'Кроль', 'Паж... | 4,094 | 1,509 |
import os
import numpy as np
import pytest
from napari_svg import napari_get_writer
from napari.layers import Image, Labels, Points, Shapes, Vectors
@pytest.fixture
def layer_data_and_types():
np.random.seed(0)
layers = [
Image(np.random.rand(20, 20)),
Labels(np.random.randint(10, ... | 2,404 | 814 |
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
... | 4,701 | 1,279 |
def selection_10():
# Library import
import numpy
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
# Library version
matplotlib_version = matplotlib.__version__
numpy_version = numpy.__version__
# Histo binning
xBinning = numpy.li... | 29,988 | 23,834 |
# Generated by Django 3.1.5 on 2021-01-07 21:50
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Category... | 4,198 | 1,208 |
n kjhimport Tkinter
window = Tkinter.Tk()
button = Tkinter.Button(window, text="do not press this because i will kill you.", width=40)
button.pack(padx=10, pady=10)
clickCount=0
def onClick(event):
global clickCount
clickCount = clickCount + 1
if clickCount == 1:
button.configure(text="seriously? do. not. press. i... | 505 | 188 |
from django.contrib import messages
from django.http import HttpResponseRedirect
from django.utils.functional import cached_property
from django.utils.translation import ugettext as _
from django.utils.translation import ugettext_noop, ugettext_lazy
from couchdbkit import ResourceNotFound
from memoized import memoized... | 5,381 | 1,556 |
"""
Code for the optimization and gaming component of the Baselining work.
@author: Maximilian Balandat, Lillian Ratliff
@date Mar 2, 2016
"""
import numpy as np
import pandas as pd
import logging
from gurobipy import GRB, Model, quicksum, LinExpr
from pandas.tseries.holiday import USFederalHolidayCalendar
from datet... | 53,884 | 15,847 |
from setuptools import setup, find_packages
setup(name='aiml',
version='1.0',
description='ML Automation',
author='MSDS ML',
author_email='edjdavid@users.noreply.github.com',
packages=find_packages(),
install_requires=[
'numpy',
'pandas',
'matplotlib',
... | 380 | 119 |
"""
WikiRacer is a project of stong1108.
https://github.com/stong1108/WikiRacer
Rewritten for Python 3.8 by Tamás Csertán (csertant)
"""
from .wikiracer import check_pages, find_shortest_path, get_result, redirected
from .wikiracer_threaded import check_page_threaded, find_shortest_path_threaded, result_threaded
| 315 | 119 |
#
# prp-htcondor-portal/provisioner
#
# BSD license, copyright Igor Sfiligoi 2021
#
# Main entry point of the provisioner process
#
import sys
import time
from . import provisioner_logging
from . import provisioner_htcondor
from . import provisioner_k8s
from . import event_loop
def main(namespace, max_pods_per_clust... | 1,115 | 404 |
""" Class for absorption line component
"""
from __future__ import print_function, absolute_import, division, unicode_literals
# Python 2 & 3 compatibility
try:
basestring
except NameError:
basestring = str
import pdb
import numpy as np
import warnings
from astropy import constants as const
from astropy impo... | 33,142 | 10,426 |
# Front matter
##############
import os
from os import fdopen, remove
from tempfile import mkstemp
from shutil import move
import glob
import re
import time
import pandas as pd
import numpy as np
from scipy import constants
from scipy.optimize import curve_fit, fsolve
from scipy.interpolate import interp1d
import matpl... | 3,305 | 1,491 |
import numpy as np, pandas as pd, json, os, datetime, time
from order import Order
class Strategies():
def __init__(self):
self._dict = {}
def add(self, name, strategy):
self._dict[name] = strategy
def compute(self, arrs, index):
list_order = []
for name,strate... | 1,730 | 547 |
import os
from datetime import datetime
from dateutil import parser as datetime_parser
from dateutil.tz import tzutc
from flask import Flask, url_for, jsonify, request
from flask.ext.sqlalchemy import SQLAlchemy
from utils import split_url
basedir = os.path.abspath(os.path.dirname(__file__))
db_path = os.path.join(ba... | 9,129 | 3,020 |
#License: https://bit.ly/3oLErEI
def test(strs):
return [*map(len, strs)]
strs = ['cat', 'car', 'fear', 'center']
print("Original strings:")
print(strs)
print("Lengths of the said list of non-empty strings:")
print(test(strs))
strs = ['cat', 'dog', 'shatter', 'donut', 'at', 'todo', '']
print("\nOriginal string... | 411 | 161 |
"""Test cases."""
import unittest
import logging
from speedtest2dynamodb import parse_output
class SpeedTest2DynamoDBTestCase(unittest.TestCase):
"""Collection of tests."""
def setUp(self):
self.logger = logging.getLogger()
def test_parse_output_bit(self):
"""Test output that contains on... | 2,644 | 999 |
#!/usr/bin/env python3
"""文件解析器,对dns分发的rules和白名单ip列表进行解析
文件格式:一条规则就是一行,#开头的表示注解:
"""
class FilefmtErr(Exception): pass
def __drop_comment(line):
"""删除注释"""
pos = line.find("#")
if pos < 0:
return line
return line[0:pos]
def __read_from_file(fpath):
result = []
fdst = open(fpath, "r... | 2,078 | 815 |
"""Module containing the context definition."""
import os
from contextlib import contextmanager
from typing import Any, Callable, Dict, List, Union
from failprint.runners import run as failprint_run
from duty.exceptions import DutyFailure
CmdType = Union[str, List[str], Callable]
class Context:
"""
A simp... | 2,918 | 781 |
import cv2
import numpy as np
import picamera
import time
def identifySq(pt, w, h):
tlx = 80
tly = 210
ppx = 94
ppy = 82
sqx = (pt[0]-(tlx-ppx/2))/ppx
sqy = (pt[1]-(tly-ppy/2))/ppy
# print ("ID",pt, w, h, sqx, sqy)
if sqx < 0 or sqx >= 4 or sqy < 0 or sqy >= 4:
return 0, False
... | 2,802 | 1,199 |
import re
import discord
from data.model import Tag
class TagModal(discord.ui.Modal):
def __init__(self, bot, tag_name, author: discord.Member) -> None:
self.bot = bot
self.tag_name = tag_name
self.author = author
self.tag = None
super().__init__(title=f"Add tag {self.tag... | 7,193 | 2,019 |
#!/usr/bin/env python
# coding: utf-8
# In[3]:
import pandas as pd
# In[4]:
weather_data = pd.read_csv("weatherHistory.csv")
# weather_data.columns = weather_data.iloc[0]
# weather_data.columns
# weather_data
# weather_data.head()
weather_data.columns.values
# In[5]:
weather_data = weather_data.iloc[1:]
# ... | 3,096 | 1,261 |
import NLQ_Preprocessor as preProcessor
import NLP_Engine as nlpEngine
import NLQ_Interpreter as interpreter
import nltk
import time
class NLQ_Chunker:
def __init__(self):
self.preprocessor = preProcessor.PreProcessor()
self.nlp_engine = nlpEngine.NLP_Engine()
self.interpreter = interpre... | 1,263 | 407 |
from spi_driver_base import DriverSPIBase, ChannelOrder
class DriverLPD8806(DriverSPIBase):
"""Main driver for LPD8806 based LED strips on devices like the Raspberry Pi and BeagleBone"""
def __init__(self, num, c_order=ChannelOrder.RGB, use_py_spi=True, dev="/dev/spidev0.0", SPISpeed=2):
super(Driver... | 2,722 | 936 |
import os
import time
from gatenlp import logger, Document
class TestTokenizers01:
def makedoc(self):
return Document(" This is a 💩 document. It has two sentences and 14 tokens. ")
def test_nltk_tokenizers01(self):
"""
Unit test method (make linter happy)
"""
try:... | 3,476 | 1,101 |
from src.neural_networks.art_fuzzy import ARTFUZZY
import numpy as np
def test_If_I_isintance_numpy():
A = ARTFUZZY([1.0, 2.0])
assert isinstance(A.I, np.ndarray)
def test_If_W_isintance_numpy():
A = ARTFUZZY([1.0, 2.0])
assert isinstance(A.I, np.ndarray) | 282 | 130 |
'''Tests for methods in helpers/no_import_common_class/utilities.py'''
# pylint: disable=missing-function-docstring
# pylint: disable=redefined-outer-name
import pytest
import helpers.no_import_common_class.paragraph_helpers as helpers
import utilities.random_methods as utils
import testing.data.dict_constants as cons... | 2,801 | 1,016 |
#!/usr/bin/env python3
"""
DEPRECATED: better use trainv2.py together with conf files. This file persists as not everything in it has been moved to
trainv2.py, but in most cases the other one should be used.
"""
import argparse
import os
import pathlib
import yaml
from typing import Dict
import collections
import to... | 17,823 | 5,616 |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'EditKey.ui'
#
# Created by: PyQt5 UI code generator 5.14.0
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_EditKey(object):
def setupUi(self, EditKey):
EditKey.setO... | 9,020 | 3,139 |
CANAIS_ADM = {
"diretoria": 441263190832185350,
"secretaria": 731689039853518848
}
SAUDACOES = ["Olá!", "Oi!", "Iai!"]
GUIA_ANONIMA_ID = 956319073568976967
msg_ajuda = "**::ola** | **::oi** | **::iai** | **::athena**: Mande um ola caloroso para mim, e responderei!\n" \
"**::cool** `texto`: Você po... | 5,584 | 2,062 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "Christian Heider Nielsen"
__doc__ = ""
from .discounting import *
from .generalised_advantage import *
from .nstep import *
| 187 | 70 |
from arbre_binaire import AB
def parfait(ngd):
"""
Fonction qui renvoit un arbre binaire parfait à partir de
son parcourt en profondeur préfixe ngd de type str
"""
cle = ngd[0]
ab1 = AB(cle)
if len(ngd) > 1:
ngd_g = ngd[1 : len(ngd) // 2 + 1]
ngd_d = ngd[len(ngd) // 2 + 1 :... | 1,376 | 545 |
import numpy as np
from spharpy.samplings.helpers import sph2cart
from scipy.spatial import cKDTree
class Coordinates(object):
"""Container class for coordinates in a three-dimensional space, allowing
for compact representation and convenient conversion into spherical as well
as geospatial coordinate syste... | 12,091 | 3,512 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Creating Sequence to Sequence Models
# -------------------------------------
# Here we show how to implement sequence to sequence models.
# Specifically, we will build an English to German translation model.
#
import io
import os
import string
import sys
from collect... | 11,572 | 3,680 |
"""
Django settings for hxmirador project.
Generated by 'django-admin startproject' using Django 2.0.7.
For more information on this file, see
https://docs.djangoproject.com/en/2.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.0/ref/settings/
"""
import os
... | 6,077 | 2,159 |