content
stringlengths
0
1.05M
origin
stringclasses
2 values
type
stringclasses
2 values
from .drm_service import DRMService from .fairplay_drm_service import FairPlayDRM from .aes_drm_service import AESDRM class TSDRMService(DRMService): MUXING_TYPE_URL = 'ts' def __init__(self, http_client): super().__init__(http_client=http_client) self.FairPlay = FairPlayDRM(http_client=http...
nilq/baby-python
python
#!/usr/bin/python import yaml import json #Reading from YAML file print "\n***Printing from the YAML file***" yamlfile = 'yamloutput.yml' with open (yamlfile) as f: yamllist = yaml.load(f) print yamllist print "\n" #Reading from JSON file print "\n***Printing from the JSON file***" jsonfile = 'jsonoutput.json'...
nilq/baby-python
python
# Copyright 2018 StreamSets Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writi...
nilq/baby-python
python
import json import cv2 import matplotlib.pyplot as plt import numpy as np import os from labelme import utils from skimage import img_as_ubyte import PIL.Image import random JSON_DIR = 'json' LABELCOLOR = { # 设定label染色情况 'product': 1, 'product': 2, 'product': 3, 'product': 4, } VOCVersion = 'VOC2012...
nilq/baby-python
python
from setuptools import setup with open('README.md') as f: long_description = f.read() setup( name='nicebytes', author='Philipp Ploder', url='https://github.com/Fylipp/nicebytes', description='human-readable data quantities', long_description=long_description, long_description_content_type=...
nilq/baby-python
python
# -*- coding: utf-8 -*- """ profiling.tracing ~~~~~~~~~~~~~~~~~ Profiles deterministically by :func:`sys.setprofile`. """ from __future__ import absolute_import import sys import threading from .. import sortkeys from ..profiler import Profiler from ..stats import RecordingStatistics, VoidRecordingStatis...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Project: Appraise evaluation system Author: Matt Post <post@cs.jhu.edu> This script takes a set of parallel files and writes out the XML file used to setup the corresponding Appraise tasks. usage: $ build_xml.py [-h] [-id ID] [-source SOURCELANG] [-target TARGETL...
nilq/baby-python
python
import datetime import discord from dotenv import dotenv_values TOKEN = dotenv_values(".env")["TOKEN"] class Client(discord.Client): async def on_ready(self): members = getlist(self.guilds[0]) votes = {} for member in members: votes[member] = 0 for member in members: ...
nilq/baby-python
python
from django.template.loader import get_template from django_better_admin_arrayfield.forms.widgets import DynamicArrayWidget def test_template_exists(): get_template(DynamicArrayWidget.template_name) def test_format_value(): widget = DynamicArrayWidget() assert widget.format_value("") == [] assert w...
nilq/baby-python
python
import collections class contributor: def __init__(self, name, index): self.name = name self.index = index self.ratings = collections.defaultdict(list) def __str__(self) -> str: return self.name def __repr__(self) -> str: return self.name ...
nilq/baby-python
python
import json import hashlib from dojo.models import Finding class TruffleHogJSONParser(object): def __init__(self, filename, test): data = filename.read() self.dupes = dict() self.items = () for line in data.splitlines(): json_data = self.parse_json(line) f...
nilq/baby-python
python
import requests import csv key=input('Masukan produk yang akan dicari:') limit=input('Masukan limit produk:') hal = input('Masukan berapa halaman ke berapa:') write = csv.writer(open('eCommerce/hasil/{}.csv'.format(key), 'w', newline='')) header = ['nama produk','harga','terjual','rating produk','nama toko','lokasi t...
nilq/baby-python
python
from pytube import YouTube from tqdm import tqdm import ffmpeg import html # insert test link here! yt = YouTube('https://www.youtube.com/watch?v=2A3iZGQd0G4') audio = yt.streams.filter().first() pbar = tqdm(total=audio.filesize) def progress_fn(self, chunk, *_): pbar.update(len(chunk)) yt.register_on_progress_ca...
nilq/baby-python
python
import argparse import json import multiprocessing import os import pickle import random from multiprocessing import Pool, cpu_count import nltk import numpy as np import torch from tqdm import tqdm from src.data_preprocessors.transformations import ( NoTransformation, SemanticPreservingTransformation, BlockS...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- from math import exp import os import re import sys # This code implements the non-linear regression method described in: # Jean Jacquelin 2009, # Régressions et équations intégrales, # sec. REGRESSIONS NON LINEAIRES des genres : PUISSANCE, EXPONENTIELLE, LOGARITHME, WEI...
nilq/baby-python
python
from setuptools import setup setup(name='pkgtest', version='1.0.0', description='A print test for PyPI', author='winycg', author_email='win@163.com', url='https://www.python.org/', license='MIT', keywords='ga nn', packages=['pkgtest'], install_requires=['numpy>=1.1...
nilq/baby-python
python
import boto3 import botocore import sys import os class S3Client: def __init__(self, bucket, key): self.client = boto3.client('s3') self.bucket = bucket self.key = key def get_content_length(self): try: return int(self.client.get_object(Bucket=self.bucket, Key=self....
nilq/baby-python
python
import io import os import time import zipfile import h5py import numpy as np import pandas as pd from PIL import Image from django.http import HttpResponse from rest_framework.permissions import IsAuthenticated from rest_framework.request import Request from rest_framework.response import Response from rest_framework...
nilq/baby-python
python
# Hello, I'm party bot, I will be called from wsgi.py once from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackQueryHandler from Bot.models import TelegramUser, Action, Day, WeekDay, Event, Vote, BotMessage, Advertisement from telegram import InlineKeyboardButton, InlineKeyboardMarkup, Re...
nilq/baby-python
python
from trex_stl_lib.api import * class STLS1(object): def get_streams (self, direction = 0, **kwargs): s1 = STLStream(name = 's1', packet = STLPktBuilder(pkt = Ether()/IP(src="16.0.0.1",dst="48.0.0.1")/UDP(dport=12,sport=1025)/(10*'x')), mode = STLTXSingleBurst(...
nilq/baby-python
python
import collections from .base import BaseItertool from .iter_dispatch import iter_ from .tee import tee _zip = zip class product(BaseItertool): """product(*iterables, repeat=1) --> product object Cartesian product of input iterables. Equivalent to nested for-loops. For example, product(A, B) returns t...
nilq/baby-python
python
r""" Lattice posets """ #***************************************************************************** # Copyright (C) 2011 Nicolas M. Thiery <nthiery at users.sf.net> # # Distributed under the terms of the GNU General Public License (GPL) # http://www.gnu.org/licenses/ #*****************************...
nilq/baby-python
python
# uncompyle6 version 3.2.4 # Python bytecode 2.7 (62211) # Decompiled from: Python 2.7.15 (v2.7.15:ca079a3ea3, Apr 30 2018, 16:30:26) [MSC v.1500 64 bit (AMD64)] # Embedded file name: ctypes.macholib.framework import re __all__ = [ 'framework_info'] STRICT_FRAMEWORK_RE = re.compile('(?x)\n(?P<location>^.*)(?:^|/)\n(?P...
nilq/baby-python
python
# bc_action_rules_bc.py from pyke import contexts, pattern, bc_rule pyke_version = '1.1.1' compiler_version = 1 def speed_up(rule, arg_patterns, arg_context): engine = rule.rule_base.engine patterns = rule.goal_arg_patterns() if len(arg_patterns) == len(patterns): context = contexts.bc_context(rule) tr...
nilq/baby-python
python
""" Created_at: 06 Oct. 2019 10:20:50 Target: EPISODES: set nullable `episodes.published_at` """ from playhouse.migrate import * from migrations.models import database previous = "0002_23052019_migration" def upgrade(): migrator = PostgresqlMigrator(database) migrate(migrator.drop_not_null("episodes", "pu...
nilq/baby-python
python
#!/usr/bin/python from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext import os import sys hidapi_topdir = os.path.join(os.getcwd(), 'hidapi') hidapi_include = os.path.join(hidapi_topdir, 'hidapi') def hidapi_src(platform): return os.path.join(hidapi_to...
nilq/baby-python
python
#!/bin/python import csv import sys import struct filename_in = sys.argv[1] filename_out = sys.argv[2] with open(filename_in) as csv_file: csv_reader = csv.reader(csv_file, delimiter = ','); line_count = 0 fileout = open(filename_out, "wb") fileout.write(struct.pack('b', 0)) fileout.w...
nilq/baby-python
python
# Copyright 2015-2021 SWIM.AI inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to ...
nilq/baby-python
python
import torch import random from layers import SEAL from tqdm import trange from utils import hierarchical_graph_reader, GraphDatasetGenerator class SEALCITrainer(object): """ Semi-Supervised Graph Classification: A Hierarchical Graph Perspective Cautious Iteration model. """ def __init__(self,args): ...
nilq/baby-python
python
# Copyright (c) 2017 NVIDIA Corporation import torch import argparse from reco_encoder.data import input_layer from reco_encoder.model import model import torch.optim as optim from torch.optim.lr_scheduler import MultiStepLR import torch.nn as nn from torch.autograd import Variable import copy import time from pathlib ...
nilq/baby-python
python
# Copyright 2017 Become Corp. 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...
nilq/baby-python
python
"""Module for all encryption""" # standard imports import hashlib import binascii from os import urandom, getenv from uuid import uuid4 # third party imports from authlib.specs.rfc7519 import jwt # local imports from api.utilities.constants import CHARSETS from api.utilities.constants import MESSAGES from api.utilit...
nilq/baby-python
python
from common import * ## for debug def dummy_transform(image): print ('\tdummy_transform') return image # kaggle science bowl-2 : ################################################################ def resize_to_factor2(image, mask, factor=16): H,W = image.shape[:2] h = (H//factor)*factor w = (W //...
nilq/baby-python
python
import wrapper as w import json outFile = open("data/tgt/linear/test.txt", "w") with open("data/tgt/giant_news0tgt0.txt", "r") as inFile: for line in inFile: serialized = json.loads(line[line.index("\t"):]) ex = w.GrapheneExtract(serialized) linear = ex.linearize() if linear != "": outFile.write(line[:lin...
nilq/baby-python
python
""" Copyright(c) 2021 Authors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files(the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicen...
nilq/baby-python
python
from clases.catastrofe import catastrofe from clases.catastrofe import AlDiaSiguiente from clases.yinyang import Yin from clases.yinyang import Yang from clases.herenciaMultiple import Pared from clases.herenciaMultiple import Ventana from clases.herenciaMultiple import Casa from clases.herenciaMultiple import ParedCor...
nilq/baby-python
python
# Exercise 2.12 from math import * ballRadius = float(input("Please enter the radius: ")) ballVolume = 4 / 3 * pi * ballRadius ** 3 ballSpace = 4 * pi * ballRadius ** 2 print("The Volume of the ball is", ballVolume) print("The Superficial Area of the ball is", ballSpace)
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- # These imports are for python3 compatibility inside python2 from __future__ import absolute_import from __future__ import division from __future__ import print_function import threading import time import cachetools from apex.aprs import util as aprs_util from .util im...
nilq/baby-python
python
# Copyright (C) 2013-2016 DNAnexus, Inc. # # This file is part of dx-toolkit (DNAnexus platform client libraries). # # 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.a...
nilq/baby-python
python
from structural.composite.logic.order_calculator import OrderCalculator class Product(OrderCalculator): def __init__(self, name: str, value: float) -> None: self._name = name self._value = value @property def name(self) -> str: return self._name @property def value(self) ...
nilq/baby-python
python
# Copyright (C) 2016-2021 Alibaba Group Holding 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 l...
nilq/baby-python
python
#!/usr/bin/env python3 # Copyright 2019 Kohei Morita # # 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 o...
nilq/baby-python
python
__author__ = 'marcos'
nilq/baby-python
python
import pytest from kgx.config import get_biolink_model_schema def test_valid_biolink_version(): try: schema = get_biolink_model_schema("2.2.1") except TypeError as te: assert False, "test failure!" assert ( schema == "https://raw.githubusercontent.com/biolink/biolink-model...
nilq/baby-python
python
import os import tensorflow as tf from tensorflow.python.client import device_lib from tensorflow.python.training.distribute import DistributionStrategy from tensorflow.contrib.distribute import MirroredStrategy, TPUStrategy from time import time from estimator import CustomEstimator from dataset import dataset_fn, da...
nilq/baby-python
python
from .log import Code, warning, info, debug, debug_line, ModuleError from . import Config, Export from .stages import main from .utils import get_temp_folder from .checker import check, check_equality from .dsp import channel_count, size from .utils import random_file import soundfile as sf import numpy as np import o...
nilq/baby-python
python
# generated by datamodel-codegen: # filename: openapi.yaml # timestamp: 2021-12-31T02:53:00+00:00 from __future__ import annotations from datetime import datetime from enum import Enum from typing import Annotated, Any, List, Optional from pydantic import BaseModel, Field class ServiceUpdateNotFoundFault(Base...
nilq/baby-python
python
from typing import List, Union, Optional, Dict, MutableMapping, Any, Set import itertools import math import numbers import copy import operator import warnings import attr from .load_dump import dumps as demes_dumps Number = Union[int, float] Name = str Time = Number Size = Number Rate = float Proportion = float _...
nilq/baby-python
python
import json import urllib3 http = urllib3.PoolManager() request = http.request('GET','https://booksbyptyadana.herokuapp.com/books') data = request.data print(request.status) if len(data) > 0: book_dict = dict() books = json.loads(data.decode('utf-8')) for book in books: book_dict[book['book_name'...
nilq/baby-python
python
from abc import ABC from distutils.version import LooseVersion from typing import Union class Capabilities(ABC): """Represents capabilities of a connection / back end.""" def __init__(self, data): pass def version(self): """ Get openEO version. DEPRECATED: use api_version instead""" ...
nilq/baby-python
python
#!../../../.env/bin/python import os import numpy as np import time a = np.array([ [1,0,3], [0,2,1], [0.1,0,0], ]) print a row = 1 col = 2 print a[row][col] assert a[row][col] == 1 expected_max_rows = [0, 1, 0] expected_max_values = [1, 2, 3] print 'expected_max_rows:', expected_max_rows print 'expected_...
nilq/baby-python
python
from utils import overloadmethod, ApeInternalError from astpass import DeepAstPass import cstnodes as E class Sentinel: def __init__(self, value): self.value = value def __repr__(self): return f'Sentinel({self.value!r})' def is_sentinel(x): return isinstance(x, Sentinel) def is_iterable(...
nilq/baby-python
python
import unittest import numpy as np from laika.raw_gnss import get_DOP, get_PDOP, get_HDOP, get_VDOP, get_TDOP from laika.lib.coordinates import geodetic2ecef class TestDOP(unittest.TestCase): def setUp(self): self.receiver = geodetic2ecef((0, 0, 0)) self.satellites = np.array([ [18935913, -3082759,...
nilq/baby-python
python
# This utility should only be invoked via the itimUtil.sh wrapper script. # Support utility to submit ITIM object changes via the ITIM API. Changes are specified # through a text file. # Changes are submitted asynchronously and status is reported later in the output. # See usage information in the wrapper script. # ...
nilq/baby-python
python
import random from careers.career_enums import GigResult from careers.career_gig import Gig, TELEMETRY_GIG_PROGRESS_TIMEOUT, TELEMETRY_GIG_PROGRESS_COMPLETE from sims4.localization import TunableLocalizedStringFactory from sims4.tuning.instances import lock_instance_tunables from sims4.tuning.tunable import TunableRefe...
nilq/baby-python
python
"""Plugwise Switch component for HomeAssistant.""" from __future__ import annotations from typing import Any from plugwise.exceptions import PlugwiseException from homeassistant.components.switch import SwitchEntity from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant, ca...
nilq/baby-python
python
# Copyright (c) 2020 Simons Observatory. # Full license can be found in the top level "LICENSE" file. import numpy as np from toast.timing import function_timer, Timer from toast.utils import Logger from ..sim_hwpss import OpSimHWPSS def add_sim_hwpss_args(parser): parser.add_argument( "--hwpss-file",...
nilq/baby-python
python
import pandas as pd import numpy as np from pyam import utils def test_pattern_match_none(): data = pd.Series(['foo', 'bar']) values = ['baz'] obs = utils.pattern_match(data, values) exp = [False, False] assert (obs == exp).all() def test_pattern_match_nan(): data = pd.Series(['foo', np.n...
nilq/baby-python
python
from __future__ import absolute_import, division, print_function from appr.models.kv.channel_kv_base import ChannelKvBase from appr.models.kv.etcd.models_index import ModelsIndexEtcd class Channel(ChannelKvBase): index_class = ModelsIndexEtcd
nilq/baby-python
python
# coding: utf-8 """ RLSData.py The Clear BSD License Copyright (c) – 2016, NetApp, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted (subject to the limitations in the disclaimer below) provided that the following conditions are met: * Redi...
nilq/baby-python
python
# Generated by Django 3.1.2 on 2020-10-30 15:25 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('pages', '0001_initial'), ] operations = [ migrations.AlterModelOptions( name='page', options={'ordering': ['order', ...
nilq/baby-python
python
import csv import cv2 import pandas as pd import numpy as np import os import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.utils import shuffle import sklearn import tensorflow as tf import pickle import keras from sklearn.externals import joblib from keras.models import Se...
nilq/baby-python
python
"""Auto-generated file, do not edit by hand. SA metadata""" from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata PHONE_METADATA_SA = PhoneMetadata(id='SA', country_code=966, international_prefix='00', general_desc=PhoneNumberDesc(national_number_pattern='(?:[1-467]|92)\\d{7}|5\\d{8}|8\\d{9}', p...
nilq/baby-python
python
from rest_framework.viewsets import ModelViewSet from exam.models import TblExamRecord as Model from exam.serializers import RecordSerializer as Serializer class RecordViewset(ModelViewSet): queryset = Model.objects.all().order_by('-id') serializer_class = Serializer
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.response.AlipayResponse import AlipayResponse class MybankCreditSupplychainCreditpayAmountQueryResponse(AlipayResponse): def __init__(self): super(MybankCreditSupplychainCreditpayAmountQueryResponse, self).__init__() s...
nilq/baby-python
python
import string import numpy import copy from domrl.engine.agent import Agent """ class Agent(object): def choose(self, decision, state): return decision.moves[0] class StdinAgent(Agent): def choose(self, decision, state): # Autoplay if len(decision.moves) == 1: return [0]...
nilq/baby-python
python
"""Functional tests for pylint."""
nilq/baby-python
python
import time from wrf.cache import _get_cache from wrf import getvar from netCDF4 import Dataset as nc #a = nc("/Users/ladwig/Documents/wrf_files/wrf_vortex_single/wrfout_d02_2005-08-28_00:00:00") #b = nc("/Users/ladwig/Documents/wrf_files/wrf_vortex_single/wrfout_d02_2005-08-28_03:00:00") a = nc("/Users/ladwig/Documen...
nilq/baby-python
python
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** from .. import _utilities import typing # Export this package's modules as members: from ._enums import * from .get_key import * from .get_managed_hsm ...
nilq/baby-python
python
import datetime import json from flask_testing import TestCase from config import create_app from db import db from models import ParkModel from models.pay_type import PayType from tests.base import generate_token from tests.factories import AdminUserFactory from tests.helpers_for_tests import GenerateTarifeData cl...
nilq/baby-python
python
# -*- coding: utf-8 -*- from django.http import HttpResponseRedirect from django.views.decorators.http import require_http_methods, require_GET from django.contrib import messages from django.contrib.auth.decorators import login_required from django.core.exceptions import PermissionDenied from django.contrib.auth impo...
nilq/baby-python
python
import re from datetime import datetime class HadoopSeriesParser: def __init__(self): self.attribute_count = 8 self.foundation_date_regex = r'^([^\t]*\t){1}"\d{4}"\^\^<http://www.w3.org/2001/XMLSchema#date>.*$' def parse(self, result_data): lines_attributes = [] ### Structure # <http://dbpedia.org/resour...
nilq/baby-python
python
import sys import os import pytest import pandas as pd import arcus.ml.dataframes as adf import logging from unittest.mock import patch from collections import Counter logging.basicConfig(level=logging.DEBUG) mylogger = logging.getLogger() # initialize list of lists categorical_data = [['BE', 10], ['FR', 15], ['BE...
nilq/baby-python
python
#/usr/bin/python # Copyright 2013 by Hartmut Goebel <h.goebel@crazy-compilers.com> # Licence: GNU Public Licence v3 (GPLv3), but not for military use import subprocess import argparse GRAPH_HEADER = ''' digraph "%s" { nodesep=0; sep=0; ranksep=0 ratio="compress" packmode="node"; pack=1 pad=0 splines=true ...
nilq/baby-python
python
import os import pickle from tqdm import tqdm from config import data_file, thchs30_folder # split in ['train', 'test', 'dev'] def get_thchs30_data(split): print('loading {} samples...'.format(split)) data_dir = os.path.join(thchs30_folder, 'data') wave_dir = os.path.join(thchs30_folder, split) sa...
nilq/baby-python
python
#!/bin/env python2 import cairo import os.path this = os.path.dirname(__file__) def millimeters_to_poscript_points(mm): inches = mm / 25.4 return inches * 72 def css_px_to_poscript_points(px): inches = px / 96. return inches * 72 cairo.PDFSurface(os.path.join(this, "A4_one_empty_page.pdf"), ...
nilq/baby-python
python
import numpy as np from torch.utils.data import Subset from sklearn.model_selection import train_test_split def split_data(dataset,splits=(0.8,0.2),seed=None): assert np.sum(splits) == 1 assert (len(splits)==2) | (len(splits)==3) if len(splits) == 2: train_idx, test_idx, _, _ = train_test_split(ra...
nilq/baby-python
python
from __future__ import print_function # ---------------------------------------------------------------- # Copyright 2016 Cisco Systems # # 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 # # ...
nilq/baby-python
python
import torch import torch.nn as nn import torch.nn.functional as F class Matching(nn.Module): def __init__(self, vis_dim, lang_dim, jemb_dim, jemb_drop_out): super(Matching, self).__init__() self.vis_emb_fc = nn.Sequential(nn.Linear(vis_dim, jemb_dim), nn.B...
nilq/baby-python
python
import torch import torch.nn as nn class LeNet(torch.nn.Module): """This is improved version of LeNet """ def __init__(self): super(LeNet, self).__init__() self.network = nn.Sequential(nn.Conv2d(1, 6, kernel_size=5, padding=2), nn.ReLU(), nn.MaxPool2d(...
nilq/baby-python
python
# -*- test-case-name: twisted.positioning.test -*- # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ The Twisted positioning framework. @since: 14.0 """
nilq/baby-python
python
# Copyright 2013-2022 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.package import * class Libpam(AutotoolsPackage): """Example PAM module demonstrating two-factor authentic...
nilq/baby-python
python
# Copyright 2020 The TensorFlow 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 applica...
nilq/baby-python
python
''' This code loads the results and prepares Fig8a. (c) Efrat Shimron, UC Berkeley, 2021 ''' import os import matplotlib.pyplot as plt import numpy as np R = 4 pad_ratio_vec = np.array([1, 2]) print('============================================================================== ') print(' ...
nilq/baby-python
python
from django.core.urlresolvers import reverse from django.contrib.auth import get_user_model from django.contrib.auth.models import Permission from django.core.paginator import Paginator from go.base import utils from go.base.tests.helpers import GoDjangoTestCase, DjangoVumiApiHelper from go.vumitools.api import VumiAp...
nilq/baby-python
python
import py from pypy.translator.cli.test.runtest import compile_function from pypy.translator.oosupport.test_template.backendopt import BaseTestOptimizedSwitch class TestOptimizedSwitch(BaseTestOptimizedSwitch): def getcompiled(self, fn, annotation): return compile_function(fn, annotation, backendopt=True)
nilq/baby-python
python
""" Low level *Skype for Linux* interface implemented using *XWindows messaging*. Uses direct *Xlib* calls through *ctypes* module. This module handles the options that you can pass to `Skype.__init__` for Linux machines when the transport is set to *X11*. No further options are currently supported. Warning PyGTK fr...
nilq/baby-python
python
#! /usr/bin/env python3 # encoding: UTF-8 # # Python Workshop - Conditionals etc #2 # # We'll later cover learn what happens here import random # # Guess a number # Find a random number between 0 and 100 inclusive target = random.randint(0, 100) # TODO: # Write a while loop that repeatedly asks the user to guess th...
nilq/baby-python
python
#! /usr/bin/env python import cyvcf2 import argparse import sys from collections import defaultdict, Counter import pandas as pd import signal import numpy as np from shutil import copyfile import pyfaidx from random import choice from pyliftover import LiftOver from Bio.Seq import reverse_complement from mutyper imp...
nilq/baby-python
python
############################################################################### # $Id$ # $Author$ # # Routines to create the inquisitor plots. # ############################################################################### # system import import threading import string import os # enstore imports import Trace impor...
nilq/baby-python
python
# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function) import pytest from .. import Backend from . import AVAILABLE_BACKENDS @pytest.mark.parametrize('key', AVAILABLE_BACKENDS) def test_Dummy(key): be = Backend(key) d0 = be.Dummy() d1 = be.Dummy() assert d0 == d0 ...
nilq/baby-python
python
# Copyright 2021 Xiaomi Corp. (authors: Fangjun Kuang # Mingshuang Luo) # # See ../../../../LICENSE for clarification regarding multiple authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the Licen...
nilq/baby-python
python
import time import cv2 import numpy as np import tflite_runtime.interpreter as tflite def _inference(interpreter, input_details, input_data): '''Inference (internal function) TensorFlow Lite inference the inference result can be get to use interpreter.get_tensor Arguments: - interpreter: tflite...
nilq/baby-python
python
# Copyright 2020-present NAVER Corp. Under BSD 3-clause license import subprocess import sys import os.path as path from typing import List, Optional def run_python_command(local_path: str, args: List[str], python_binary: Optional[str] = None, notbash = True): """ run a python subprocess :param local_path:...
nilq/baby-python
python
import numpy from numpy.testing import * from prettyplotting import * from algopy.utpm import * # STEP 0: setting parameters and general problem definition ############################################################ # Np = number of parameters p # Nq = number of control variables q # Nm = number of measurements # P ...
nilq/baby-python
python
#!/usr/bin/python3 # -*- coding: utf-8 -*- """Day 2 of AdventOfCode.com: iterating over arrays doing simple arithmetic""" import os from numpy import product def present_wrap_area(dimensions): """ :param dimensions: list of 3 floats: length, width and height :return: area of wrapping """ wrap_area...
nilq/baby-python
python
# Copy from web_set_price.py of Trading Stock Thailand # Objective : Create Program to store financial data of company # From set.or.th # sk 2018-12-05 import urllib from bs4 import BeautifulSoup import numpy as np import pandas as pd from os.path import join, exists from os import remove, makedirs import urllib2 #s...
nilq/baby-python
python
import nltk import json import argparse from collections import Counter def build_word2id(seq_path, min_word_count): """Creates word2id dictionary. Args: seq_path: String; text file path min_word_count: Integer; minimum word count threshold Returns: word2id: Dictionary; word-to-i...
nilq/baby-python
python
# -*- coding:utf-8 -*- # Python 字典类型转换为JSON对象 data1 = { 'no': 1, 'name':'Runoob', 'url':'http://www.runoob.com' } # 对数据进行编码 import json json_str = json.dumps(data1) print("Python原始数据:", repr(data1)) print("JSON对象:", json_str) # 将JSON对象转换为Python字典 # 对数据进行解码 data2 = json.loads(json_str) print("data2...
nilq/baby-python
python
import re def checkIP(IP): regex='^([2][0-5][0-5]|[1]{0,1}[0-9]{1,2})\.([2][0-5][0-5]|[1]{0,1}[0-9]{1,2})\.([2][0-5][0-5]|[1]{0,1}[0-9]{1,2})\.([2][0-5][0-5]|[1]{0,1}[0-9]{1,2}$)' return re.match(regex,IP) def checkIP2(n): return n<=255 a=['123.4.2.222', '0.0.0.0', '14.123.444.2', '1.1.1.1'] print "***** CHECK USI...
nilq/baby-python
python