content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
import utils as util
import tensorflow as tf
import numpy as np
def forecast_model(series, time,forecastDays):
split_time=2555
time_train=time[:split_time]
x_train=series[:split_time]
split_time_test=3285
time_valid=time[split_time:split_time_test]
x_valid=series[split_time:split_time_test]
... | nilq/baby-python | python |
# terrascript/provider/hashicorp/template.py
# Automatically generated by tools/makecode.py (24-Sep-2021 15:28:21 UTC)
import terrascript
class template(terrascript.Provider):
"""terraform-provider-template"""
__description__ = "terraform-provider-template"
__namespace__ = "hashicorp"
__name__ = "te... | nilq/baby-python | python |
import itertools
from typing import List, Tuple
from card_utils import deck
from card_utils.deck.utils import (
rank_partition,
suit_partition,
ranks_to_sorted_values
)
from card_utils.games.gin.deal import new_game
def deal_new_game():
""" shuffle up and deal each player 7 cards,
put one car... | nilq/baby-python | python |
"""\
Setup Kubernetes on cloud
"""
import logging
import os
import sys
sys.path.append(os.path.abspath("../.."))
import main
def start(config, machines):
"""Setup Kubernetes on cloud VMs using Ansible.
Args:
config (dict): Parsed configuration
machines (list(Machine object)): List of machi... | nilq/baby-python | python |
class Player(object):
"""A class used to represent a poker player.
Attributes:
name: name of the player
stack: amount of money the player has
hand: two Cards
"""
def __init__(self, name, stack, hand):
"""Inits Player with name, stack, and two cards that will compose their hand"""
self.name = name
self... | nilq/baby-python | python |
import re
import requests
from hashlib import sha1
from urllib.parse import urlsplit
from apphelpers.rest.hug import user_id
from app.libs import asset as assetlib
from app.libs import publication as publicationlib
from app.models import AssetRequest, asset_request_statuses
from app.models import moderation_policies, ... | nilq/baby-python | python |
model = dict(
type='LiteFlowNet',
encoder=dict(
type='NetC',
in_channels=3,
pyramid_levels=[
'level1', 'level2', 'level3', 'level4', 'level5', 'level6'
],
out_channels=(32, 32, 64, 96, 128, 192),
strides=(1, 2, 2, 2, 2, 2),
num_convs=(1, 3, 2, ... | nilq/baby-python | python |
# Copyright 2021 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | nilq/baby-python | python |
"""
Codemonk link: https://www.hackerearth.com/problem/algorithm/lonely-monk-code-monk-ebca6e4a/
Being alone in the new world, Monk was little afraid and wanted to make some friends. So he decided to go the famous
dance club of that world, i.e "DS Club" and met a very beautiful array A of N integers, but for some reas... | nilq/baby-python | python |
#!/usr/bin/python
n = int(input())
matrix = []
res = []
for _ in range(n):
matrix.append([int(i) for i in input().split()])
for i in range(2 * n):
for j in range(n):
if 0 <= i - j < n:
res.append(matrix[i - j][j])
print(' '.join(map(str, res)))
| nilq/baby-python | python |
"""
Run PCA using the covariance matrix estimated with empirical Bayes
"""
import numpy as np
import scanpy.api as sc
import simplesc
if __name__ == '__main__':
data_path = '/netapp/home/mincheol/parameter_estimation/inteferon_data/'
adata = sc.read(data_path + 'interferon.raw.h5ad')
estimator = simplesc.Sing... | nilq/baby-python | python |
import os, sys; sys.path.insert(0, os.path.join("..", ".."))
from pattern.en import sentiment, polarity, subjectivity, positive
# Sentiment analysis (or opinion mining) attempts to determine if
# a text is objective or subjective, positive or negative.
# The sentiment analysis lexicon bundled in Pattern focuses on ad... | nilq/baby-python | python |
import numpy as np
import tensorflow as tf
class MNIST:
"""MNIST dataset wrapper.
Attributes:
x_train: np.ndarray, [B, 28, 28, 1], dataset for training.
x_test: np.ndarray, [B, 28, 28, 1], dataset for testing.
y_train: np.ndarray, [B], label for training, 0 ~ 9.
y_test: np.ndar... | nilq/baby-python | python |
import os
import unittest
import json
from cloudsplaining.scan.managed_policy_detail import ManagedPolicyDetails
from cloudsplaining.scan.group_details import GroupDetailList
from cloudsplaining.scan.role_details import RoleDetailList
from cloudsplaining.scan.user_details import UserDetailList
from cloudsplaining.scan.... | nilq/baby-python | python |
"""This module defines some handy :py:class:`Importable` elements.
An ``Importable`` is usually composed of two different parts:
* A *natural key* used to identify *the same* element across different systems.
This is the only required component for an ``Importable``.
* An optional set of properties that form *the ... | nilq/baby-python | python |
import rosnode
import subprocess
import time
import os
ros_nodes = rosnode.get_node_names()
if not '/robot_state_publisher' in ros_nodes:
os.system('ifconfig eth0 192.168.0.2')
command='roslaunch sick_tim sick_tim571_2050101.launch'
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
... | nilq/baby-python | python |
#!/usr/bin/env python3
"""
Requires:
python-mnist
numpy
sklearn
"""
import sys
sys.path.insert(0, 'src/')
import mnist
import numpy as np
from numpy.linalg import norm as l21_norm
from sklearn.metrics.cluster import normalized_mutual_info_score as nmi
import os
np.random.seed(int(os.environ.get('seed', '42')))
print... | nilq/baby-python | python |
#!/usr/bin/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 ag... | nilq/baby-python | python |
from kafka import KafkaConsumer
from kafka import KafkaProducer
import time
import os
import json
print('Pinger Demo 1.0')
kafka_url = str(os.environ['KAFKA_URL'])
kafka_port = int(os.environ['KAFKA_PORT'])
kafka_address = kafka_url + ':' + str(kafka_port)
consumer = None
while True:
try:
consumer ... | nilq/baby-python | python |
import tkinter.filedialog as tk
import pandas as pd
class Dados():
def __init__(self):
super().__init__()
def importarDados(self):
file_name = tk.askopenfilename(filetypes=(('csv files', '*.csv'), ('csv files', '*.csv')))
return file_name
def abrirArquivoCsv(self,file_name):
... | nilq/baby-python | python |
#!/usr/bin/python
import sys
import zlib
import time
import os
import requests
import re
#import requests-futures
from baseconv import base62
from etaprogress.progress import ProgressBar
def main():
PROGRAM_NAME = "zbing"
if len(sys.argv) != 3:
print("USAGE: python "+PROGRAM_NAME+".py <URL> <length>")
prin... | nilq/baby-python | python |
import pathlib
import unittest
from deep_hipsc_tracking import pipeline
# Tests
class TestPipelineStages(unittest.TestCase):
def test_stages_exist(self):
cls = pipeline.ImagePipeline
exp = [
'write_config_file',
'extract_frames',
'ensemble_detect_cells',
... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 20 13:39:18 2020
@author: Administrator
"""
from __future__ import division
import time
import torch
import torch.nn as nn
from torch.autograd import Variable
import numpy as np
import cv2
# from models_nolambda import *
from models_nolambda_focallossw impo... | nilq/baby-python | python |
#!/usr/bin/env python
from scipy import *
from scipy import weave
from scipy import linalg
from pylab import *
import sys
def ReadKlist(fklist, ReadBS=False):
fk = open(fklist,'r')
data = fk.readlines()
nkp = [line[:3]=='END' for line in data].index(True)
if data[nkp][:3]!='END':
print 'wrong ... | nilq/baby-python | python |
"""Hacking, by Al Sweigart al@inventwithpython.com
The hacking mini-game from "Fallout 3". Find out which seven-letter
word is the password by using clues each guess gives you."""
__version__ = 1
import random, sys
# Setup the constants:
# The "filler" characters for the board.
GARBAGE_CHARS = '~!@#$%^&*()_+-={}[]|... | nilq/baby-python | python |
class Settings:
database_location = "./db/instapy.db"
browser_location = "./assets/chromedriver"
| nilq/baby-python | python |
"""
Luxafor abstracted interface
"""
import time
from .api import API
from .constants import (
LED_FLAG_BOTTOM, LED_FLAG_MIDDLE, LED_FLAG_TOP,
LED_POLE_BOTTOM, LED_POLE_MIDDLE, LED_POLE_TOP
)
LEDS = [
['LED_FLAG_TOP', 1, LED_FLAG_TOP],
['LED_FLAG_MIDDLE', 2, LED_FLAG_MIDDLE],
['LED_FLAG_BOTTOM', 3... | nilq/baby-python | python |
student_scores = {
"Harry": 81,
"Ron": 78,
"Hermione": 99,
"Draco": 74,
"Neville": 62,
}
# TODO-1: Create an empty dictionary called student_grades.
student_grades = {}
# TODO-2: Write your code below to add the grades to student_grades.👇
for student_name in student_scores:
score = s... | nilq/baby-python | python |
import os
import time
def get_exec_out(sxcute_str):
out_list = os.popen(sxcute_str).readlines()
return out_list
if __name__ == '__main__':
excute_str = 'nvidia-smi'
out_list = get_exec_out(excute_str)
# print(out_list)
for oo in out_list:
if oo.find('python') != -1:
#... | nilq/baby-python | python |
bind = ["0.0.0.0:8000"]
workers = 4
threads = 2
max_requests = 10000
max_requests_jitter = 100
accesslog = "-"
errorlog = "-"
limit_request_line = 0
| nilq/baby-python | python |
from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
import warnings
with warnings.catch_warnings():
warnings.simplefilter("ignore")
# Register nbextension
def _jupyter_nbextension_paths():
return [{
'section': 'notebook',
'src': 'static',
'dest... | nilq/baby-python | python |
# zwei 12/16/2013
# accumulate generator
def group_iter(iterator, n):
# print(iterator)
accumulator = []
for item in iterator:
accumulator.append(item)
if len(accumulator) == n:
yield accumulator
accumulator = []
if len(accumulator... | nilq/baby-python | python |
from typing import List
from cloudrail.knowledge.context.aws.ec2.security_group import SecurityGroup
from cloudrail.knowledge.context.aws.networking_config.network_configuration import NetworkConfiguration
from cloudrail.knowledge.context.aws.networking_config.network_entity import NetworkEntity
from cloudrail.knowled... | nilq/baby-python | python |
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class XsdkExamples(CMakePackage):
"""XSDK Examples show usage of libraries in the XSDK package.""... | nilq/baby-python | python |
import pytest
from mold.parser import TemplateSyntaxError, parse
from mold.tokenizer import tokenize
from .common import load_fixture
def test_alltags():
filename, contents = load_fixture("alltags")
assert list(parse(tokenize(filename, contents)))
def test_unexpected_end():
filename, contents = load_f... | nilq/baby-python | python |
#!/usr/bin/env python
"""
Create factor graphs for LQR control
Author: Gerry Chen, Yetong Zhang, and Frank Dellaert
"""
import gtsam
import numpy as np
import matplotlib.pyplot as plt
from dynamics_lti import create_lti_fg, plot_trajectory, solve_lti_fg
def add_lqr_costs_fg(graph, X, U, Q, R, x_goal=np.array([])):
... | nilq/baby-python | python |
# coding: UTF-8
# Install XIMEA software package
# Copy 'XIMEA\API\Python\v3\ximea' to 'PythonXX\Lib'
from ximea import xiapi
import cv2
import numpy as np
# Connect to camera
cam = xiapi.Camera()
cam.open_device_by_SN('XXXXXXXX') # Enter serial number of your Ximea camera
# Configuration
cam.set_exp... | nilq/baby-python | python |
import pytest
from sqlalchemy.orm import Session
from connexion_sql_utils import BaseMixin, BaseMixinABC, get, event_func, \
to_json
from .conftest import Foo
import json
def test_save():
foo = Foo(bar='some data')
foo.save()
assert Foo.query_by(bar='some data').first() is not None
foo.id = 'b... | nilq/baby-python | python |
from platform import node
import torch
import torch.nn as nn
from torch.nn import functional as F
from torch.nn.modules import padding
from torch.nn.modules.normalization import LayerNorm
from models.modules import BiMatchingNet
from models.treeGNN import TreeGNN
import pdb
class BranT(nn.Module):
def __init__(se... | nilq/baby-python | python |
import logging
from lib.amazon_properties import get_properties_compilers_and_libraries, get_specific_library_version_details
logger = logging.getLogger(__name__)
logger.level = 9
# def test_should_contain_some_compilers_and_libraries():
# [_compilers, _libraries] = get_properties_compilers_and_libraries('c++', ... | nilq/baby-python | python |
class Cache(object):
def __init__(self, capacity = -1):
self.capacity = capacity
self.cache = {}
self.index = {}
@property
def size(self):
return len(self.cache)
@property
def has_capacity(self):
return (self.capacity == -1) or (self.capacity > len(self.cache))
def set(self, key, value):
if... | nilq/baby-python | python |
from serpent.environment import Environment
from serpent.input_controller import KeyboardKey
from serpent.utilities import SerpentError
import time
import collections
import numpy as np
class StartRegionsEnvironment(Environment):
def __init__(self, game_api=None, input_controller=None, episodes_per_startregi... | nilq/baby-python | python |
import asyncio
import aiohttp
import pickle
import csv
from bs4 import BeautifulSoup
import re
import argparse
import sys
import getpass
import time
def parse_arguments():
parser = argparse.ArgumentParser(
description=(
'Descarga las paginas [START, FINISH) del foro de la facultad.\n'
'El tamanno def... | nilq/baby-python | python |
from numpy import array,dot
from numpy.linalg import inv
from getopt import getopt
import sys
def calc_displacements(initial,final):
icoord=parse_poscar(initial)[1]
fcoord=parse_poscar(final)[1]
disp=fcoord-icoord
return disp
def parse_poscar(ifile):
with open(ifile, 'r') a... | nilq/baby-python | python |
import math
import numpy
from sympy import Rational, gamma, prod
class NSphereScheme:
def __init__(self, name, dim, weights, points, degree, citation):
self.name = name
self.dim = dim
self.degree = degree
self.citation = citation
if weights.dtype == numpy.float64:
... | nilq/baby-python | python |
def findDecision(obj): #obj[0]: Coupon, obj[1]: Education, obj[2]: Occupation
# {"feature": "Education", "instances": 23, "metric_value": 0.9986, "depth": 1}
if obj[1]<=2:
# {"feature": "Coupon", "instances": 16, "metric_value": 0.896, "depth": 2}
if obj[0]<=3:
# {"feature": "Occupation", "instances": 11, "met... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""Test to verify that the scheduled actions are properly executed."""
import os
import test
from datetime import datetime
import pytz
from celery.contrib.testing.worker import start_worker
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core import... | nilq/baby-python | python |
# -*- coding:utf-8 -*-
# @atime : 2021/1/24 12:58 下午
"""
edit distance
https://leetcode-cn.com/problems/edit-distance/
"""
def solution1(word1: str, word2: str):
"""
计算编辑距离
Args:
word1 (str): 字符串1
word2 (str): 字符串2
Returns: (int) distance
"""
if not word1 or not word2:
... | nilq/baby-python | python |
#
# This file is part of the FFEA simulation package
#
# Copyright (c) by the Theory and Development FFEA teams,
# as they appear in the README.md file.
#
# FFEA is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software ... | nilq/baby-python | python |
# 1. python 中函数的工作原理
import inspect
frame = None
def bar():
global frame
frame = inspect.currentframe()
def foo():
bar()
# python.exe 会用一个叫做 PyEvalFrameEx(c函数)去执行foo函数,首先会创建一个栈帧(stack_frame)
"""
python 一切皆对象,栈帧对象, 字节码对象
当foo调用子函数bar, 又会创建一个栈帧
所有的栈帧都是分配在 堆内存 上,这就决定了栈帧可以独立于调用者存在
(Python 动态语言 函数调用完成,栈帧不会销毁... | nilq/baby-python | python |
# conding=utf-8
import Putil.base.logger as plog
logger = plog.PutilLogConfig('data_sampler_factory').logger()
logger.setLevel(plog.DEBUG)
from Putil.demo.deep_learning.base import data_sampler as standard
from util import data_sampler as project
def data_sampler_factory(args, data_sampler_source, data_sampler_name... | nilq/baby-python | python |
# file_loader.py
"""
Importe les bibliotheques "XML", "SQLite" et "Pygame"
"""
import xml.etree.ElementTree as ET
import sqlite3
import pygame as pg
vec = pg.math.Vector2
"""
Classe SpriteSheet
- But : decouper les sprites en fonction des donnees XML fournies.
- Fonctionnement : decoupe l'image associee grace aux co... | nilq/baby-python | python |
from storage import read_region_snapshot, _round_15min
import datetime
from dateutil.parser import parse
def test_read_region_snapshot():
read_region_snapshot('slc_ut', '2021-09-01T00:00:00Z')
def test__round_15min():
ts = parse('2021-01-31T23:59:01Z')
ret = _round_15min(ts)
assert ret == parse('202... | nilq/baby-python | python |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
from .cumulative_return import cumulative_return_graph
from .score_ic import score_ic_graph
from .report import report_graph
from .rank_label import rank_label_graph
from .risk_analysis import risk_analysis_graph
| nilq/baby-python | python |
from django.apps import AppConfig
class GameForumOtherConfig(AppConfig):
name = 'tulius.gameforum.other'
label = 'game_forum_other'
| nilq/baby-python | python |
import pickle
import time
import os
import random
from time import sleep
import communicate.dealer_pb2 as dealer_pb2
import communicate.dealer_pb2_grpc as rpc
# V1.4
# 0 黑桃 1 红桃 2 方片 3 草花
# 牌的id: 0-51
'''
牌面level编号
皇家同花顺:10
同花顺 :9
四条 :8
葫芦 :7
同花 :6
顺子 :5
三条 :4
... | nilq/baby-python | python |
# Buy first thing in the morning
# Sell the moment we get 1% profit after commission
# Buy again
# Cut losses only when it is at 80%.
# repeat
# The idea
# we should buy in 10% increments (tunable) throughout the day if the price is going up
# every buy should be around 10 mins apart (tunable)
# Thus we ... | nilq/baby-python | python |
#!/usr/bin/env python3
# ----------------------------------------------------------------------------
# Copyright (c) 2020--, Qiyun Zhu.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------... | nilq/baby-python | python |
from __future__ import absolute_import
# need to get system mendeley library
from mendeley.exception import MendeleyException
import mendeley as mendeley_lib
import os
def get_mendeley_session():
mendeley_client = mendeley_lib.Mendeley(
client_id=os.getenv("MENDELEY_OAUTH2_CLIENT_ID"),
client_sec... | nilq/baby-python | python |
# Copyright 2014 Alistair Muldal <alistair.muldal@pharm.ox.ac.uk>
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# Th... | nilq/baby-python | python |
from . import item, user
| nilq/baby-python | python |
import layer
import torch.nn as nn
import torch
from torch.autograd import Variable
try:
import ipdb
except ImportError:
pass
class Translator(object):
def __init__(self, opt, model=None, dataset=None):
self.opt = opt
if model is None:
checkpoint = torch.load(opt.model)
... | nilq/baby-python | python |
from server.settings.base import * # noqa
| nilq/baby-python | python |
import numpy as np
import scipy.stats as stats
class SimpleImputer:
""" Simple mean/most frequent imputation. """
def __init__(self, ncat, method='mean'):
self.ncat = ncat
assert method in ['mean', 'mode'], "%s is not supported as imputation method." %method
self.method = method
d... | nilq/baby-python | python |
from netmiko.cdot.cdot_cros_ssh import CdotCrosSSH
__all__ = ["CdotCrosSSH"]
| nilq/baby-python | python |
from .helpers import deprecated_alias
@deprecated_alias('ioat_scan_copy_engine')
@deprecated_alias('scan_ioat_copy_engine')
def ioat_scan_accel_engine(client):
"""Enable IOAT accel engine.
"""
return client.call('ioat_scan_accel_engine')
| nilq/baby-python | python |
import time
import paddle
import paddle.fluid as fluid
from network import word2vec_net
from conf import *
import logging
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger("fluid")
logger.setLevel(logging.INFO)
def get_dataset_reader(inputs):
dataset = fluid.Datase... | nilq/baby-python | python |
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
"""Client and server classes corresponding to protobuf-defined services."""
import grpc
from lndgrpc.compiled import signer_pb2 as lndgrpc_dot_compiled_dot_signer__pb2
class SignerStub(object):
"""Signer is a service that gives access to the s... | nilq/baby-python | python |
"""
@name: PyHouse/Project/src/_test/test_testing_mixin.py
@author: D. Brian Kimmel
@contact: D.BrianKimmel@gmail.com
@copyright: (c) 2014-2019 by D. Brian Kimmel
@license: MIT License
@note: Created on Oct 6, 2014
@Summary:
Passed all 16 tests - DBK - 2019-06-23
"""
from Modules.Core import PyHouseI... | nilq/baby-python | python |
import unittest
import gtirb
from helpers import SearchScope, parameterize_one
class ByteIntervalsOnTests(unittest.TestCase):
@parameterize_one(
"scope", (SearchScope.ir, SearchScope.module, SearchScope.section)
)
def test_byte_intervals_on(self, scope):
ir = gtirb.IR()
m = gtirb.... | nilq/baby-python | python |
from django.contrib import admin
from .models import Tags,Category,Blog
admin.site.register([Tags,Category,Blog])
# Register your models here.
| nilq/baby-python | python |
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
from typing import Any, Dict, Optional, Tuple, Union
from packaging.utils import canonicalize_name as canonicalize_project_name
from pants.engine.targ... | nilq/baby-python | python |
import numpy as np
import mbuild as mb
from mbuild.lib.bulk_materials import AmorphousSilicaBulk
from mbuild.lib.recipes import SilicaInterface
from mbuild.tests.base_test import BaseTest
class TestSilicaInterface(BaseTest):
def test_silica_interface(self):
tile_x = 1
tile_y = 1
thickness... | nilq/baby-python | python |
import unittest
import importlib
import asyncio
import time,os
from contextlib import contextmanager
import hashlib
from datetime import datetime
@contextmanager
def add_to_path(p):
import sys
old_path = sys.path
sys.path = sys.path[:]
sys.path.insert(0, p)
try:
yield
finally:
s... | nilq/baby-python | python |
import random
import decimal
import datetime
from dateutil.relativedelta import relativedelta
def gen_sale(store_no, store_id, date):
# double christmas eve, every other
seasonality = 1
if date[5:len(date) - 1] == '12-24':
seasonality = 2
elif int(date[5:7]) == 12:
seasonality = 1.75
... | nilq/baby-python | python |
"""https://open.kattis.com/problems/kornislav"""
nums = list(map(int, input().split()))
nums.remove(max(nums))
print(min(nums) * max(nums))
| nilq/baby-python | python |
import os
from random import shuffle
########### input ########
b=10
raw_data = 'yahoo_raw_train'
userwise_data = 'yahoo_userwise_train_split%d'%b
###########################
fr = open(raw_data,'r')
nr = int(fr.readline())
for i in range(b):
f=open('raw%d'%i,'w')
if i == b-1:
tt = nr - i*(nr/b)
f.write('%d\n... | nilq/baby-python | python |
class Solution:
def singleNumber(self, nums):
res = 0
# Exploit associative property of XOR and XORing the same number creates 0
for i in nums:
res ^= i
return res
z = Solution()
nums = [4, 2, 1, 2, 1]
print(z.singleNumber(nums))
| nilq/baby-python | python |
from typing import Dict, Optional, Tuple
import uuid
import pandas as pd
from tqdm import tqdm_notebook
def flatten_df(
df: pd.DataFrame,
i: int = 0,
columns_map: Optional[Dict[str, str]] = None,
p_bar: Optional[tqdm_notebook] = None,
) -> Tuple[pd.DataFrame, Dict[str, str]]:
"""Expand lists and ... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import uuid
import scrapy
from scrapy import Selector
from GAN_data.items import GanDataItem
class UmeiSpider(scrapy.Spider):
name = 'umei'
# allowed_domains = ['https://www.umei.cc/tags/meinv_1.htm']
start_urls = ['https://www.umei.cc/tags/meinv_1.htm']
def parse(self, r... | nilq/baby-python | python |
from supervised_gym.experience import ExperienceReplay, DataCollector
from supervised_gym.models import * # SimpleCNN, SimpleLSTM
from supervised_gym.recorders import Recorder
from supervised_gym.utils.utils import try_key
from torch.optim import Adam, RMSprop
from torch.optim.lr_scheduler import ReduceLROnPlateau
fro... | nilq/baby-python | python |
"""
This module contains tools for handling evaluation specifications.
"""
import warnings
from operator import itemgetter
from ruamel.yaml import YAML
from panoptic_parts.utils.utils import (
_sparse_ids_mapping_to_dense_ids_mapping as dict_to_numpy, parse__sid_pid2eid__v2)
from panoptic_parts.specs.dataset_spec... | nilq/baby-python | python |
from typing import Tuple
import numpy as np
from tensorflow import Tensor
from decompose.distributions.distribution import Distribution
from decompose.distributions.normal import Normal
from decompose.distributions.product import Product
class NormalNormal(Product):
def fromUnordered(self, d0: Distribution,
... | nilq/baby-python | python |
import spacy
from spacy.lang.en.stop_words import STOP_WORDS
from string import punctuation
from heapq import nlargest
class Summarizer:
def __init__(self):
print("Summarizer is being initiallized...")
def summarize(self, text):
# test1 = inputField.get('1.0', tk.END)
#test2 = numField... | nilq/baby-python | python |
from django.shortcuts import render, redirect
from django.views.decorators.csrf import csrf_exempt
from rest_framework.authtoken.models import Token
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import AllowAny
from rest_framework.status import (
HTTP_400_BAD_REQ... | nilq/baby-python | python |
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
class HelicalGenerator():
def __init__(self, start_pos, des_pos, # total_time, dt, z_max=0.01,
start_vel=[0,0,0], des_vel=[0,0,0], m=1):
# self.theta = 0
self.x = 0
self.y = 0
... | nilq/baby-python | python |
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | nilq/baby-python | python |
from enum import Enum
from pydantic import BaseModel
class DeleteBookResponseStatus(Enum):
"""status codes for deleting a book"""
success = "book deleted"
borrowed = "book still borrowed"
fail = "book not deleted"
class DeleteBookResponseModel(BaseModel):
""""""
status: DeleteBookResponse... | nilq/baby-python | python |
import string
"""
- Atividade de Logica para Computação.
- Autores: Paulo Henrique Diniz de Lima Alencar, Yan Rodrigues e Alysson Lucas Pinheiro.
- Professor: Alexandre Arruda.
"""
# Alphabet
atoms = list(string.ascii_lowercase)
operatores = ["#", ">", "&", "-"]
delimiters = ["(", ")"]
# Removing blank... | nilq/baby-python | python |
from typing import Tuple, Union
import pygame
from pygame_gui.core.colour_gradient import ColourGradient
from pygame_gui.core.ui_font_dictionary import UIFontDictionary
from pygame_gui.core.utility import render_white_text_alpha_black_bg, apply_colour_to_surface
from pygame_gui.elements.text.html_parser import CharSt... | nilq/baby-python | python |
import os
import sys
sys.path.append('..')
sys.path.append('.')
import mitogen
VERSION = '%s.%s.%s' % mitogen.__version__
author = u'Network Genomics'
copyright = u'2021, the Mitogen authors'
exclude_patterns = ['_build', '.venv']
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinxcontrib.programout... | nilq/baby-python | python |
from ..definitions.method import MethodDefinition
from ..definitions.outputparameter import OutputParameterDefinition
from .method import ServiceMethod
class ServiceOutputParameter(object):
def __call__(self, name, convertType=None, many=False, optional=False, page=False, per_page=None):
def decorato... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import pdb
import argparse
import sys as sys
import logging as logging
import time as time
import oneapi as oneapi
import oneapi.models as models
import oneapi.utils as mod_utils
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
parser = ... | nilq/baby-python | python |
from ixnetwork_restpy.base import Base
from ixnetwork_restpy.files import Files
class IPv6_Encapsulation_Header(Base):
__slots__ = ()
_SDM_NAME = 'ipv6Encapsulation'
_SDM_ATT_MAP = {
'Security Paramaters Index': 'ipv6Encapsulation.header.spi',
'Sequence Number': 'ipv6Encapsulation.header.s... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""spear2sc.spear_utils: Utitlity methods to read SPEAR files"""
def process_line(line):
""" (list of str) -> list of list of float
Parses line, a line of time, frequency and amplitude data output by
SPEAR in the 'text - partials' format.
Returns a list of timepoints. Each ti... | nilq/baby-python | python |
import threading
import os
import json
import time
from rsa import sign
from server import server_start
from client import send
from var import my_id
if os.name == "nt":
os.system("cls")
else:
os.system("clear")
if os.sys.argv[1] == "server":
server = threading.Thread(target = server_start())
server.s... | nilq/baby-python | python |
from allennlp_dataframe_mapper.transforms.base import RegistrableTransform # NOQA
from allennlp_dataframe_mapper.transforms.hash_name import HashName # NOQA
from allennlp_dataframe_mapper.transforms.preprocessing import ( # NOQA
FlattenTransformer,
LabelEncoder,
Logarithmer,
MinMaxScaler,
Standar... | nilq/baby-python | python |
##Classes for future implementation
def stats_player(name_player, data_df):
condition = data_df["Player" == name_player]
df_single_player = data_df[condition]
class Player():
def __init__(self, three_shot, two_shot, one_shot):
self.three_shot = three_shot
self.two_shot = two_shot
... | nilq/baby-python | python |
# Calculando a raiz quadrada de um número.
n = 81 ** (1/2)
print(f'A raiz quadrada de 81 é {n}') | nilq/baby-python | python |
import cmsisdsp as dsp
import numpy as np
import cmsisdsp.fixedpoint as f
import cmsisdsp.mfcc as mfcc
import scipy.signal as sig
from mfccdebugdata import *
from cmsisdsp.datatype import Q31
import cmsisdsp.datatype as dt
mfccq31=dsp.arm_mfcc_instance_q31()
sample_rate = 16000
FFTSize = 256
numOfDctOutputs = 13
... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.