content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
import pytest
from ethereum import tester
from functools import (
reduce
)
from fixtures import (
MAX_UINT,
fake_address,
token_events,
owner_index,
owner,
wallet_address,
get_bidders,
fixture_decimals,
contract_params,
get_token_contract,
token_contract,
create_contr... | nilq/baby-python | python |
import progressbar
def test_with():
with progressbar.ProgressBar(max_value=10) as p:
for i in range(10):
p.update(i)
def test_with_stdout_redirection():
with progressbar.ProgressBar(max_value=10, redirect_stdout=True) as p:
for i in range(10):
p.update(i)
def test_w... | nilq/baby-python | python |
#!/usr/bin/env python
#
# Copyright 2016 Steve Kyle. 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 require... | nilq/baby-python | python |
from .find_maximum_value_binary_tree import find_maximum_value, BST
def test_find_maximum_value_tree_with_one_value():
one_value = BST([5])
assert find_maximum_value(one_value) == 5
def test_find_maximum_value_tree_with_two_values():
one_value = BST([10, 2])
assert find_maximum_value(one_value) == 1... | nilq/baby-python | python |
import matplotlib.pyplot as plt
import networkx as nx
import os
import random
import warnings
from matplotlib.backends import backend_gtk3
from settings import OUTPUT_DIR
warnings.filterwarnings('ignore', module=backend_gtk3.__name__)
RESTART_PROBABILITY = 0.15
STEPS_MULTIPLIER = 100
def random_walk_sample(grap... | nilq/baby-python | python |
from collections import KeysView
def find(iterable: list or KeysView, key=lambda x: x):
for elem in iterable:
if key(elem):
return elem
return None
def index(iterable: list, key=lambda x: x) -> int:
x = 0
for elem in iterable:
if key(elem):
return x
x += 1
return -1
| nilq/baby-python | python |
from django.apps import AppConfig
class CalToolConfig(AppConfig):
name = 'cal_tool'
| nilq/baby-python | python |
#
#
# 0=================================0
# | Kernel Point Convolutions |
# 0=================================0
#
#
# ----------------------------------------------------------------------------------------------------------------------
#
# Callable script to start a training on Myhal... | nilq/baby-python | python |
#!/usr/bin/env python
"""Split large file into multiple pieces for upload to S3.
S3 only supports 5Gb files for uploading directly, so for larger CloudBioLinux
box images we need to use boto's multipart file support.
This parallelizes the task over available cores using multiprocessing.
Usage:
s3_multipart_upload.... | nilq/baby-python | python |
#!/usr/bin/env python
# coding: utf-8
###################################################################################################
#
# File : frame_study.py
#
# Auhtor : P.Antilogus
#
# Version : 22 Feb 2019
#
# Goal : this python file read raw data image , and can be used for specific sensor diagnostic like :
... | nilq/baby-python | python |
#!/usr/bin/python
#
# Copyright 2012 Sonya Huang
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | nilq/baby-python | python |
class Solution(object):
def lengthOfLongestSubstringTwoDistinct(self, s):
"""
:type s: str
:rtype: int
"""
if not s:
return 0
c = s[0]
maxlen = 0
chars = set([c])
llen = 0
start = 0
end = 0
for i, cc in enume... | nilq/baby-python | python |
import sys
from sqlalchemy import create_engine
import pandas as pd
import numpy as np
import re
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from nltk.stem import PorterStemmer, WordNetLemmatizer
from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer
from sklearn.mod... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8
# Copyright 2017-2019 The FIAAS Authors
#
# 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
#
# Unle... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
#
# michael a.g. aïvázis <michael.aivazis@para-sim.com>
# (c) 1998-2022 all rights reserved
# support
import qed
# custom properties
def selectors(default={}, **kwds):
"""
A map from selector names to their legal values
"""
# build the trait descriptor and return it
retur... | nilq/baby-python | python |
#!/usr/bin/env python
import numpy
from numpy.random import RandomState
from sklearn.datasets import make_friedman1
from sklearn.model_selection import train_test_split
from typing import Union
from backprop.network import Network
_demo_problem_num_train_samples: int = 1000
_demo_problem_num_test_samples: int = 100
... | nilq/baby-python | python |
# Copyright 2020 Board of Trustees of the University of Illinois.
#
# 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 ... | nilq/baby-python | python |
import numpy as np
from mrcnn import utils
def build_rpn_targets(image_shape, anchors, gt_class_ids, gt_boxes, config):
"""Given the anchors and GT boxes, compute overlaps and identify positive
anchors and deltas to refine them to match their corresponding GT boxes.
anchors: [num_anchors, (y1, x1, y2, x2)... | nilq/baby-python | python |
from django import forms
from django.contrib import admin
from django.utils.safestring import mark_safe
from .models import Episode, ShowDate
from .tasks import generate_peaks
class ShowsCommonModelAdminMixin:
save_on_top = True
list_filter = ("published", "show_code")
list_display_links = ("show_code", ... | nilq/baby-python | python |
""" Events emitted by the artist model """
from dataclasses import dataclass
from typing import List, Optional
from OpenCast.domain.event.event import Event, ModelId
@dataclass
class ArtistCreated(Event):
name: str
ids: List[ModelId]
thumbnail: Optional[str]
@dataclass
class ArtistThumbnailUpdated(Eve... | nilq/baby-python | python |
from unittest import TestCase
from lie2me import Field
class CommonTests(object):
def get_instance(self):
return self.Field()
def test_submitting_empty_value_on_required_field_returns_error(self):
field = self.get_instance()
field.required = True
value, error = field.submit(f... | nilq/baby-python | python |
import os
import sys
from RLTest import Env
from redisgraph import Graph, Node, Edge
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from base import FlowTestsBase
redis_graph = None
male = ["Roi", "Alon", "Omri"]
female = ["Hila", "Lucy"]
class testGraphMixLabelsFlow(FlowTestsBase):
def __init__... | nilq/baby-python | python |
import io
import logging
from typing import List, Union
LOG = logging.getLogger(__name__)
class FileHelper:
"""Encapsulates file related functions."""
def __init__(self, filepath, line_idx, contents):
self.filepath = filepath
self.line_idx = line_idx
self.contents = contents
@cl... | nilq/baby-python | python |
#!/usr/bin/python
import sys
import tarfile
import json
import gzip
import pandas as pd
import botometer
from pandas.io.json import json_normalize
## VARIABLE INITIATION
#system argument
# arg 1 = 'rs' or 'sn'
# arg 2 = hour file 6,7 or 8 ?
# arg 3 = start row
# arg 4 = end row
# arg 5 = key selection, 1,2,3,4
# sn 7... | nilq/baby-python | python |
from analyzers.utility_functions import auth
from parsers.Parser import Parser
class HthParser(Parser):
__url = "https://fantasy.premierleague.com/api/leagues-h2h-matches/league/{}/?page={}&event={}"
__HUGE_HTH_LEAGUE = 19824
def __init__(self, team_id, leagues, current_event):
super().__init__(t... | nilq/baby-python | python |
import numpy as np
from math import log2
from scamp_filter.Item import Item as I
from termcolor import colored
def approx(target, depth=5, max_coeff=-1, silent=True):
coeffs = {}
total = 0.0
current = 256
for i in range(-8, depth):
if total == target:
break
... | nilq/baby-python | python |
###########################################################
# Re-bindings for unpickling
#
# We want to ensure class
# sage.modular.congroup_element.CongruenceSubgroupElement still exists, so we
# can unpickle safely.
#
###########################################################
from sage.modular.arithgroup.arithgroup... | nilq/baby-python | python |
"""Impementation for print_rel_notes."""
def print_rel_notes(
name,
repo,
version,
outs = None,
setup_file = "",
deps_method = "",
toolchains_method = "",
org = "bazelbuild",
changelog = None,
mirror_host = None):
tarball_name = ":%s-%... | nilq/baby-python | python |
#!/usr/bin/env python
# Run VGG benchmark series.
# Prepares and runs multiple tasks on multiple GPUs: one task per GPU.
# Waits if no GPUs available. For GPU availability check uses "nvidia-smi dmon" command.
# 2018 (C) Peter Bryzgalov @ CHITECH Stair Lab
import multigpuexec
import time
import os
import datetime
#... | nilq/baby-python | python |
from distutils.core import Extension, setup
import numpy as np
setup(
name="numpy_ctypes_example",
version="1.0",
description="numpy ctypes example",
author="Mateen Ulhaq",
author_email="mulhaq2005@gmail.com",
maintainer="mulhaq2005@gmail.com",
url="https://github.com/YodaEmbedding/experim... | nilq/baby-python | python |
"""
Copyright 2015 Paul T. Grogan, Massachusetts Institute of Technology
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicabl... | nilq/baby-python | python |
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
# pylint: ... | nilq/baby-python | python |
from utils.QtCore import *
class CustomAddCoinBtn (QPushButton):
def __init__(
self
):
super().__init__()
self.setCursor(Qt.PointingHandCursor)
self.setText('Add coin')
self.setObjectName('add_coin_btn')
self.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.P... | nilq/baby-python | python |
from typing import Callable, List
import numpy as np
from qcodes.instrument.base import Instrument
from qcodes.instrument.parameter import Parameter
from qcodes.instrument.channel import InstrumentChannel, ChannelList
from qcodes.utils import validators as vals
from .SD_Module import SD_Module, keysightSD1, Signadyne... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from urllib import request
import sys, os
import time, types, json
import os.path as op
import win32api, win32con, win32gui
# default_encoding = 'utf-8'
# if sys.getdefaultencoding() != default_encoding:
# reload(sys)
# sys.setdefaultencoding(default_encoding)
TRY_TIMES = 1
DEFA... | nilq/baby-python | python |
from django.shortcuts import render
from django.urls import reverse, reverse_lazy
from django.views.generic import ListView, DetailView, DeleteView
from django.views.generic.edit import CreateView, UpdateView
from django.contrib.auth.mixins import PermissionRequiredMixin
from .models import AdvThreatEvent, NonAdvThrea... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# @COPYRIGHT_begin
#
# Copyright [2010-2014] Institute of Nuclear Physics PAN, Krakow, Poland
#
# 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.apac... | nilq/baby-python | python |
import os
from optparse import make_option
from django.core.management import call_command, BaseCommand
from django.conf import settings
from fixture_generator.base import get_available_fixtures
from django.db.models.loading import get_app
class Command(BaseCommand):
"""
Regenerate fixtures for all applicatio... | nilq/baby-python | python |
# coding: utf-8
# Copyright (c) Max-Planck-Institut für Eisenforschung GmbH - Computational Materials Design (CM) Department
# Distributed under the terms of "New BSD License", see the LICENSE file.
"""
Builtin tools that come with pyiron base.
"""
from abc import ABC
from pyiron_base.job.factory import JobFactory
__... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from yandex_checkout import ReceiptItem
from yandex_checkout.domain.common.receipt_type import ReceiptType
from yandex_checkout.domain.common.request_object import RequestObject
from yandex_checkout.domain.models.receipt_customer import ReceiptCustomer
from yandex_checkout.domain.models.settlem... | nilq/baby-python | python |
# Copyright 2020 Google LLC
#
# 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, ... | nilq/baby-python | python |
from flaky import flaky
from .. import SemparseTestCase
from allennlp.models.archival import load_archive
from allennlp.predictors import Predictor
class TestAtisParserPredictor(SemparseTestCase):
@flaky
def test_atis_parser_uses_named_inputs(self):
inputs = {"utterance": "show me the flights to seat... | nilq/baby-python | python |
# Generated by Django 3.2.3 on 2021-05-29 21:11
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('discordbot', '0021_auto_20210529_2045'),
]
operations = [
migrations.AddField(
model_name='member',
name='settings',... | nilq/baby-python | python |
# Author: Jintao Huang
# Time: 2020-5-24
import torch.nn as nn
from .utils import FrozenBatchNorm2d
default_config = {
# backbone
"pretrained_backbone": True,
"backbone_norm_layer": nn.BatchNorm2d,
"backbone_freeze": ["conv_first", "layer1", "layer2"],
# "backbone_freeze": [""], # freeze backbone... | nilq/baby-python | python |
# TOO EASY
T = int(input())
for _ in range(T):
lower, upper = map(int, input().split())
n = int(input())
# a < num <= b
for _ in range(n):
mid = (lower+upper)//2
print(mid)
res = input()
if res == "TOO_SMALL":
lower = mid + 1
elif res == "TOO_BIG":
... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from odoo import _, api, fields, models
class Trainer(models.Model):
_name = "bista.trainer"
_description = "Bista Training Management System - Trainer"
_rec_name = "name"
profile_image = fields.Binary(string="Profile Image", attachement=True)
first_name = fields.Char(str... | nilq/baby-python | python |
#coding: utf-8
#!python3
# 5) Solicite o preço de uma mercadoria e o percentual de desconto. Exiba o valor do desconto
# e o preço a pagar:
p_produto = float(input('Valor produto: '))
p_desconto = float(input('Percentual de desconto: '))
p_produto_atual = p_produto - (p_produto*p_desconto/100)
print('Preço... | nilq/baby-python | python |
# Generated by Django 2.2.16 on 2020-10-02 08:37
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('routes', '0047_source_id_nullable'),
('routes', '0048_athlete_activities_imported'),
]
operations = [
]
| nilq/baby-python | python |
#!/usr/bin/env python3
import unittest
import numpy as np
from selfdrive.test.longitudinal_maneuvers.maneuver import Maneuver
def run_cruise_simulation(cruise, t_end=100.):
man = Maneuver(
'',
duration=t_end,
initial_speed=float(0.),
lead_relevancy=True,
initial_distance_lead=100,
cruise_valu... | nilq/baby-python | python |
from __future__ import print_function
from mmstage import MicroManagerStage
| nilq/baby-python | python |
# Copyright: 2006-2011 Brian Harring <ferringb@gmail.com>
# License: GPL2/BSD
"""
exceptions thrown by the MergeEngine
"""
__all__ = ("ModificationError", "BlockModification",
"TriggerUnknownCset",
)
class ModificationError(Exception):
"""Base Exception class for modification errors"""
def __init__(sel... | nilq/baby-python | python |
# Generated by Django 2.1.7 on 2019-04-16 15:14
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('materials', '0068_auto_20190415_2140'),
]
operations = [
migrations.RenameField(
model_name='dataset',
old_name='experimenta... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
flask_security.recoverable
~~~~~~~~~~~~~~~~~~~~~~~~~~
Flask-Security recoverable module
:copyright: (c) 2012 by Matt Wright.
:license: MIT, see LICENSE for more details.
"""
from flask import current_app as app
from werkzeug.local import LocalProxy
from werkzeug.securi... | nilq/baby-python | python |
import pandas as pd
import numpy as np
import os
import matplotlib.pyplot as plt
from sklearn.metrics import classification_report,accuracy_score,f1_score,precision_score,recall_score
from scikitplot.metrics import plot_confusion_matrix
class eval_metrics():
def __init__(self,targets,preds,classes):
try:
... | nilq/baby-python | python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import unittest
import itertools
from saliency_map import *
from utils import OpencvIo
class GaussianPyramidTest(unittest.TestCase):
def setUp(self):
oi = OpencvIo()
src = oi.imread('./images/fruit.jpg')
self.__gp = GaussianPyramid(src)
def t... | nilq/baby-python | python |
# MODULE: TypeRig / Core / Ojects
# -----------------------------------------------------------
# (C) Vassil Kateliev, 2017-2020 (http://www.kateliev.com)
# (C) Karandash Type Foundry (http://www.karandash.eu)
#------------------------------------------------------------
# www.typerig.com
# No warranties. By using ... | nilq/baby-python | python |
from pyomac.clustering.cluster_utils import (
ModalSet,
IndexedModalSet,
indexed_modal_sets_from_sequence,
modal_sets_from_lists,
modal_clusters,
single_set_statistics,
filter_clusters,
plot_indexed_clusters
)
| nilq/baby-python | python |
# TextChart - Roll The Dice
import pygwidgets
from Constants import *
class TextView():
def __init__(self, window, oModel):
self.window = window
self.oModel = oModel
totalText = ['Roll total', '']
for rollTotal in range(MIN_TOTAL, MAX_TOTAL_PLUS_1):
totalText.append(r... | nilq/baby-python | python |
"""
Exercise 1
Write a function that takes a string as an argument and displays the letters
backward, one per line.
"""
def backwards(word):
x = len(word) - 1
while x >= 0:
print(word[x])
x -= 1
backwards("hello")
| nilq/baby-python | python |
# with open('./space.text', 'w') as message:
# message.write('我是写入的数据\n')
# message.write('我再写一段文字哦\n')
# message.write('继续写入\n')
with open('./space.text', 'a') as msg:
msg.write('附加一段文字\n')
msg.write('继续附加一段\n')
| nilq/baby-python | python |
import modeli, dobi_zneske
from bottle import *
import hashlib # racunaje md5
import json,requests
import pandas as pd
secret = "to skrivnost je zelo tezko uganiti 1094107c907cw982982c42"
def get_administrator():
username = request.get_cookie('administrator', secret=secret)
return username
def get_user(a... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
filepath = sys.argv[1]
path, filename = os.path.split(filepath)
filename, ext = os.path.splitext(filename)
for i in os.listdir(os.getcwd()+'/'+path):
file_i, ext = os.path.splitext(i)
if i.startswith(filename+'_segmented') and ext == '.ttl':
# ... | nilq/baby-python | python |
from datetime import datetime, timedelta
import pendulum
import prefect
from prefect import task, Flow
from prefect.schedules import CronSchedule
import pandas as pd
from io import BytesIO
import zipfile
import requests
schedule = CronSchedule(
cron="*/30 * * * *",
start_date=pendulum.datetime(2021... | nilq/baby-python | python |
import ROOT as root
qMap_Ag_C0_V0 = root.TProfile2D("qMap_Ag_C0_V0","qMap_Ag_C0 (V0)",52,0,52,80,0,80,0,0);
qMap_Ag_C0_V0.SetBinEntries(3585,29768);
qMap_Ag_C0_V0.SetBinEntries(3586,79524);
qMap_Ag_C0_V0.SetBinEntries(3639,83953);
qMap_Ag_C0_V0.SetBinEntries(3640,124982);
qMap_Ag_C0_V0.SetBinEntries(3641,14345);
qMap_... | nilq/baby-python | python |
from . import start_watcher
def main():
start_watcher() | nilq/baby-python | python |
from .market import Market, TradeException
import time
import hmac
import urllib.parse
import urllib.request
import requests
import hashlib
import config
import database
from datetime import datetime
class PrivateBter(Market):
url = "https://bter.com/api/1/private/"
def __init__(self):
super().__ini... | nilq/baby-python | python |
import rlkit.misc.hyperparameter as hyp
from rlkit.launchers.launcher_util import run_experiment
import os
from rlkit.misc.asset_loader import sync_down
def experiment(variant):
from rlkit.core import logger
demo_path = sync_down(variant['demo_path'])
off_policy_path = sync_down(variant['off_policy_path'... | nilq/baby-python | python |
# Generated by Django 3.2.7 on 2021-09-27 02:08
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='profile',
name='user_type',
... | nilq/baby-python | python |
# encoding: utf-8
"""
route.py
Created by Thomas Mangin on 2015-06-22.
Copyright (c) 2009-2017 Exa Networks. All rights reserved.
License: 3-clause BSD. (See the COPYRIGHT file)
"""
from exabgp.protocol.family import SAFI
from exabgp.bgp.message.update.nlri.qualifier import RouteDistinguisher
from exabgp.configurati... | nilq/baby-python | python |
'''This file provides editor completions while working on DFHack using ycmd:
https://github.com/Valloric/ycmd
'''
# pylint: disable=import-error,invalid-name,missing-docstring,unused-argument
import os
import ycm_core
def DirectoryOfThisScript():
return os.path.dirname(os.path.abspath(__file__))
# We need to te... | nilq/baby-python | python |
from twisted.trial import unittest
from signing.persistence import Persistence
class PersistenceTests(unittest.TestCase):
def setUp(self):
self.persistence = Persistence()
def test_set_get(self):
d = self.persistence.set('somekey', 'somefield', 'somevalue')
d.addCallback(lambda _: sel... | nilq/baby-python | python |
""" Module storing the `~halotools.sim_manager.CachedHaloCatalog`,
the class responsible for retrieving halo catalogs from shorthand
keyword inputs such as ``simname`` and ``redshift``.
"""
import os
from warnings import warn
from copy import deepcopy
import numpy as np
from astropy.table import Table
from ..utils.pyt... | nilq/baby-python | python |
import unittest, os
import cuisine
USER = os.popen("whoami").read()[:-1]
class Text(unittest.TestCase):
def testEnsureLine( self ):
some_text = "foo"
some_text = cuisine.text_ensure_line(some_text, "bar")
assert some_text == 'foo\nbar'
some_text = cuisine.text_ensure_line(some_text, "bar")
assert some_tex... | nilq/baby-python | python |
import math
import numpy as np
from utils.functions.math.coordinate_trans import coordinate_transformation_in_angle
def circle_make(center_x, center_y, radius):
'''
Create circle matrix(2D)
Parameters
-------
center_x : float in meters
the center position of the circle coordinate x
cen... | nilq/baby-python | python |
import numpy as np
import pandas as pd
from sklearn.ensemble import ExtraTreesRegressor, GradientBoostingRegressor
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline, make_union
from sklearn.preprocessing import MaxAbsScaler
from tpot.builtins import StackingEstimator
# NOT... | nilq/baby-python | python |
# 454. 4Sum II
import collections
class Solution:
def fourSumCount(self, A, B, C, D):
"""
:type A: List[int]
:type B: List[int]
:type C: List[int]
:type D: List[int]
:rtype: int
"""
ab = {}
for a in A:
for b in B:
ab... | nilq/baby-python | python |
import soundfile as sf
import numpy as np
import librosa
from scipy import signal
import cPickle
import src.config as cfg
def to_mono(wav):
if wav.ndim == 1:
return wav
elif wav.ndim == 2:
return np.mean(wav, axis=-1)
def calculate_logmel(rd_fd):
wav, fs = sf.read(rd_fd)
wav = to_mono... | nilq/baby-python | python |
from datetime import datetime as dt
from ..ff.window import Window
class BrowserSession(object):
def __init__(self, ss_json):
self._windows = WindowSet(ss_json["windows"])
self._start_time = dt.fromtimestamp(ss_json["session"]["startTime"] / 1000)
self._selected_window = ss_json["selectedW... | nilq/baby-python | python |
import numpy as np;
import xlrd;
import xlwt;
sheet = xlrd.open_workbook('data1.xls');
workbook = xlwt.Workbook(encoding = 'ascii');
worksheet = workbook.add_sheet('school')
data = sheet.sheets()[0];
row = data.nrows;
col = data.ncols;
for i in range(0,row):
for j in range(0,col):
worksheet.write(i, j... | nilq/baby-python | python |
import json
import sys
import os
import typer
from typing import List
import time
from .logger import get_logger
from .config.imports import check_imports
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
logger = get_logger()
cli = typer.Typer()
@cli.command('setup')
def setup_auto():
chk_libs = ['tensorflow', 'torch',... | nilq/baby-python | python |
import re
import matplotlib.pyplot as plt
import numpy as np
import sklearn
from sklearn import svm
from sklearn import linear_model, tree
from sklearn.ensemble import RandomForestClassifier
from sklearn import neural_network
import copy
path = r"D:\THU\curriculum\Software Engineering\Course_Project\data_1109_0427_RGB... | nilq/baby-python | python |
import csv
import re
from os import path
import numpy as np
FIELDNAMES = 'timeStamp', 'response_time', 'request_name', "status_code", "responseMessage", "threadName", "dataType",\
"success", "failureMessage", "bytes", "sentBytes", "grpThreads", "allThreads", "URL", "Latency",\
"IdleTime", "C... | nilq/baby-python | python |
from setuptools import setup, find_packages
setup(
name='taxies',
version='0.1.dev',
packages=find_packages(),
include_package_data=True,
install_requires=[
'Click',
],
entry_points='''
[console_scripts]
taxies=taxies.scripts.taxies:cli
''',
) | nilq/baby-python | python |
"""App.
"""
import logging
import sys
from django.apps import AppConfig
from configs.part_detection import DF_PD_VIDEO_SOURCE_IS_OPENCV
logger = logging.getLogger(__name__)
class AzurePartDetectionConfig(AppConfig):
"""App Config."""
name = "vision_on_edge.azure_part_detections"
def ready(self):
... | nilq/baby-python | python |
"""
Query suggestion hierarchical encoder-decoder code.
The code is inspired from nmt encdec code in groundhog
but we do not rely on groundhog infrastructure.
"""
__docformat__ = 'restructedtext en'
__authors__ = ("Alessandro Sordoni")
__contact__ = "Alessandro Sordoni <sordonia@iro.umontreal>"
import theano
import th... | nilq/baby-python | python |
# Copyright 2013-2015 ARM Limited
#
# 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 w... | nilq/baby-python | python |
# 源程序文件名
SOURCE_FILE = "{filename}.hs"
# 输出程序文件名
OUTPUT_FILE = "{filename}.out"
# 编译命令行
COMPILE = "ghc {source} -o {output} {extra}"
# 运行命令行
RUN = 'sh -c "./{program} {redirect}"'
# 显示名
DISPLAY = "Haskell"
# 版本
VERSION = "GHC 8.0.2"
# Ace.js模式
ACE_MODE = "haskell"
| nilq/baby-python | python |
# Generated by Django 2.1.7 on 2019-10-03 20:35
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('core', '0017_auto_20190921_1849'),
]
operations = [
migrations.RemoveField(
model_name='estrutu... | nilq/baby-python | python |
import torch
from torch.optim import Adam,SGD
from opt import opt
import math
import random
import collections
from torch.utils.data import sampler
import torch.nn as nn
def extract_feature( model, loader):
features = torch.FloatTensor()
for (inputs, labels) in loader:
ff = torch.FloatTensor(inputs.... | nilq/baby-python | python |
# WRITE YOUR SOLUTION HERE:
def add_numbers_to_list(numbers: list):
if len(numbers) % 5 != 0:
numbers.append(numbers[-1] +1 )
add_numbers_to_list(numbers)
if __name__=="__main__":
numbers = [1,3,4,5,10,11]
add_numbers_to_list(numbers)
print(numbers) | nilq/baby-python | python |
#!/usr/bin/env python
import os, subprocess
from autopkglib import Processor, ProcessorError
__all__ = ["IzPackExecutor"]
class IzPackExecutor(Processor):
"""Runs IzPack installer with all install options checked."""
input_variables = {
"app_root": {
"required": True,
"des... | nilq/baby-python | python |
"""
@author Yuto Watanabe
@version 1.0.0
Copyright (c) 2020 Yuto Watanabe
"""
| nilq/baby-python | python |
import cProfile
import argparse
from app import Application
def parse_args():
parser = argparse.ArgumentParser(
description="A keyboard-oriented image viewer")
parser.add_argument("path", type=str, nargs='?', default="",
help="the file or directory to open")
parser.add_argum... | nilq/baby-python | python |
__author__ = 'Mario'
import wx
import wx.xrc
from Engine_Asian import AsianOption
###########################################################################
## Class MainPanel
###########################################################################
class PanelAsian ( wx.Panel ):
def __init__( self, parent )... | nilq/baby-python | python |
import tqdm
import numpy as np
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.nn.functional as F
from models.generator import ResNetGenerator
from train_script.utils import *
from utils.val import validation
from utils.quantize_model import *
def adjust_learning_rate... | nilq/baby-python | python |
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root@localhost/flask_db'
db = SQLAlchemy(app)
class UserDB(db.Model):
id = db.Column(db.Integer,primary_key=True)
username = db.Column(db.String(32),unique=True)
passw... | nilq/baby-python | python |
from .DtnAbstractParser import DtnAbstractParser
from enum import Enum
from pydantic import PositiveInt, PositiveFloat
import sys
from typing import List, Optional, Set, Union
class RouterMode(str, Enum):
FAST = 'fast'
SLOW = 'slow'
class RouterAlgorithm(str, Enum):
CGR = 'cgr'
BFS = 'bfs'
class DtnL... | nilq/baby-python | python |
import numpy as np
import tensorflow as tf
class InferenceGraph:
def __init__(self):
pass
def run_inference_for_single_input_frame(self, model, input_frame,log, log_path):
"""
Method Name: run_inference_for_single_input_frame
Description: This function make prediction ... | nilq/baby-python | python |
import selenium
import glob
from numpy import arange
from random import sample
from sys import exit
from time import sleep
from progress.spinner import Spinner
from progress.bar import ChargingBar
from threading import Thread
from selenium import webdriver
from selenium.webdriver.firefox.options import Option... | nilq/baby-python | python |
from .page_article import * | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.