content
stringlengths
0
1.05M
origin
stringclasses
2 values
type
stringclasses
2 values
#!/usr/bin/python # -*- coding:utf-8 -*- # 遍历根资产的子域名 import sys import requests import threading import time,json,re from bs4 import BeautifulSoup class subdomain(object): def __init__(self,url): self.url = url self.set_dns = set() self.set_ip138 = set() self.set_crt = set() ...
nilq/baby-python
python
from pkwscraper.lib.controller import Controller """ This example shows the invalid votes percentage in communes (gminy). It also shows how much of these votes where invalid because of putting voting mark next to 2 or more candidates. This is considered to be main indication of probability of elections falsification....
nilq/baby-python
python
# coding=utf-8 # Copyright 2018 The Tensor2Tensor 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 # # Unless required by applicable...
nilq/baby-python
python
import os class GeneralConfig: # General validation_split = 0.2 seed = 42 verbose = True architecture_type = "PretrainedResNet50" # Data image extension image_extension = ".jpg" pip_packages = [ "tensorflow==2.2", "numpy", "pandas", "matplotlib", ...
nilq/baby-python
python
from .GeometricRestriction import GeometricRestriction class SizingClusterAreas(GeometricRestriction): """The SizingClusterAreas object defines a sizing cluster areas geometric restriction. The SizingClusterAreas object is derived from the GeometricRestriction object. Notes ----- This object can...
nilq/baby-python
python
import logging import logging.handlers from traceback import format_stack from brotab.inout import in_temp_dir def _init_logger(tag, filename: str): FORMAT = '%(asctime)-15s %(process)-5d %(levelname)-8s %(filename)s:%(lineno)d:%(funcName)s %(message)s' MAX_LOG_SIZE = 50 * 1024 * 1024 LOG_BACKUP_COUNT = ...
nilq/baby-python
python
import cv2 import numpy as np from numpy.linalg import norm import os import json SZ = 20 PROVINCE_START = 1000 MAX_WIDTH = 2000 def point_limit(point): if point[0] < 0: point[0] = 0 if point[1] < 0: point[1] = 0 def deskew(img): m = cv2.moments(img) if abs(m['mu02']) < 1e-2: ...
nilq/baby-python
python
""" Test method for Sub opcode """ from easier68k.simulator.m68k import M68K from easier68k.core.opcodes.cmpi import Cmpi from easier68k.core.models.assembly_parameter import AssemblyParameter from easier68k.core.enum.ea_mode import EAMode from easier68k.core.enum.register import Register from easier68k.core.enum.op_...
nilq/baby-python
python
from typing import Mapping from collections import OrderedDict import copy from torch.utils.data import DataLoader from catalyst.core.callback import Callback, CallbackOrder from catalyst.core.runner import IRunner class PeriodicLoaderCallback(Callback): """Callback for runing loaders with specified period. ...
nilq/baby-python
python
from google.appengine.ext.webapp.mail_handlers import InboundMailHandler from google.appengine.runtime import apiproxy_errors from google.appengine.ext import ndb from models.rawmail import RawMail from models.post import Post from models.settings import Settings from models.userimage import UserImage from models.slug ...
nilq/baby-python
python
"""Multiple Correspondence Analysis (MCA)""" import numpy as np import pandas as pd from sklearn import utils from . import ca from . import one_hot class MCA(ca.CA): def fit(self, X, y=None): utils.check_array(X, dtype=[str, np.number]) if not isinstance(X, pd.DataFrame): X = pd.D...
nilq/baby-python
python
listOfWords = ['wordOne', 'wordTwo', 'wordThree', 'wordFour', 'wordFive'] listOfInts = [] for i in listOfWords: listOfInts.append(len(i)) print("List of words:" + str(listOfWords)) print("List of wordlength:" + str(listOfInts))
nilq/baby-python
python
import asyncio import logging import os import random from aiohttp import WSServerHandshakeError, ClientConnectorError from cryptology import ClientWriterStub, Keys, run_client, exceptions from datetime import datetime from decimal import Context, ROUND_DOWN, Decimal from pathlib import Path from typing import Optiona...
nilq/baby-python
python
#!/usr/bin/python #coding:utf-8 from bs4 import BeautifulSoup import requests url='http://www.moko.cc/mtb.html' r=requests.get(url, verify=False) content=r.content soup=BeautifulSoup(content,'lxml') modlist=soup.find_all('div','sub_show') link=[] for i in modlist: if i==modlist[-1] or i==modlist[0]: continu...
nilq/baby-python
python
import pytest # run tests only if snappy is available snappy = pytest.importorskip("snappy") def test_snappy(): import snappy from snappy import (ProductIO, ProductUtils, ProgressMonitor, jpy)
nilq/baby-python
python
from collections import Counter import nltk from nltk import * import numpy as np import xml.etree.ElementTree as ET import tmx trigram_measures = nltk.collocations.TrigramAssocMeasures() bigram_measures = nltk.collocations.BigramAssocMeasures() class CorpusUtil(object): __slots__ = 'tokenFrequencies', 'nGr...
nilq/baby-python
python
from aiogram import types from aiogram.dispatcher import FSMContext from aiogram.dispatcher.filters import Text from misc import bot, dp, admin_ids from certificate import Certificate, get_all_certificates, set_all_certificates import logging from .menu import menu_keyboard from .states import AdminState, admin_keyboar...
nilq/baby-python
python
n1 = float(input("Digite um número: ")) print("O sucessor de {} é {} e o seu antecessor é de {}" .format(n1,n1+1,n1-1))
nilq/baby-python
python
# vim: tabstop=4 shiftwidth=4 softtabstop=4 """ [VRM DRIVER] VRM CLIENT. """ from cinder.openstack.common import log as logging from cinder.openstack.common.gettextutils import _ from cinder.volume.drivers.huawei.vrm.base_proxy import BaseProxy TASK_WAITING = 'waiting' TASK_RUNNING = 'running' TASK_SUCCESS = 'suc...
nilq/baby-python
python
from collections import namedtuple from csv import QUOTE_ALL from unittest import TestCase import pytest from bonobo import CsvReader, CsvWriter from bonobo.constants import EMPTY from bonobo.util.testing import ( BufferingNodeExecutionContext, ConfigurableNodeTest, FilesystemTester, ReaderTest, WriterTest ) csv...
nilq/baby-python
python
from textwrap import dedent import re from ansi2html import Ansi2HTMLConverter import mistune from jinja2 import Markup import pygments import pygments.lexers from pygments.lexer import RegexLexer, bygroups from pygments.token import Generic, Text, Comment import pygments.formatters.html ansi_convertor = Ansi2HTMLCo...
nilq/baby-python
python
class Cell: pass class Fish(Cell): name = 'F' @staticmethod def update(neighbours): cnt = neighbours.count(Fish.name) if cnt == 2 or cnt == 3: return Fish() else: return Void() class Crayfish(Cell): name = 'C' @staticmethod def update(nei...
nilq/baby-python
python
# flake8: noqa from __future__ import unicode_literals import sys import django from django.conf import settings # removed get_queryset <> get_query_set see, #29 #from django.db.models import Manager ## Monkey patch: # #try: # Manager.get_query_set = Manager.get_queryset #except AttributeError: # Manager.get_q...
nilq/baby-python
python
name = 'lib_csv' title = 'lib_csv: functions to read and write csv files' version = '0.1.0' url = 'https://github.com/bitranox/lib_csv' author = 'Robert Nowotny' author_email = 'rnowotny1966@gmail.com' shell_command = 'lib_csv' def print_version() -> None: print('version: 0.1.0') def print_info() -> None: p...
nilq/baby-python
python
# -*- coding: utf-8 -*- # Generated by Django 1.11.1 on 2017-09-12 19:12 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('logger', '0040_auto_20170912_1504'), ] operations = [ migrations.AlterField...
nilq/baby-python
python
from fabric.api import run, quiet from braid import succeeds, cacheInEnvironment @cacheInEnvironment def distroName(): """ Get the name of the distro. """ with quiet(): lsb = run('/usr/bin/lsb_release --id --short', warn_only=True) if lsb.succeeded: return lsb.lower() ...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_acp-calendar ------------ Tests for `acp-calendar` models module. """ import datetime import os from unittest import mock from django.test import TestCase from django.test import override_settings from acp_calendar.initial_data import get_holiday_type_list, g...
nilq/baby-python
python
load("//:plugin.bzl", "ProtoPluginInfo") ProtoCompileInfo = provider(fields = { "label": "label object", "plugins": "ProtoPluginInfo object", "descriptor": "descriptor set file", "outputs": "generated protoc outputs", "files": "final generated files", "protos": "generated protos (copies)", ...
nilq/baby-python
python
import concurrent.futures import urllib.request import time URLS = ['http://www.foxnews.com/', 'http://www.cnn.com/', 'http://europe.wsj.com/', 'http://www.bbc.co.uk/', 'http://some-made-up-domain.com/', 'http://www.nytimes.com', 'http://www.facebook.com', 'http:...
nilq/baby-python
python
#!/usr/local/uvcdat/bin/python # Functions to convert between representations of energy flux and # water flux (precipitation and evoporation) variables. # TODO: perhaps move the physical constants used here to atmconst.py. # These are: # - latent heat of vaporization (water) # - density (water...
nilq/baby-python
python
from random import choice #============================================================================== """ Split a String in Balanced Strings Balanced strings are those that have an equal quantity of 'L' and 'R' characters. Given a balanced string s, split it in the maximum amount of balanced strings. Return the ...
nilq/baby-python
python
# -*- coding:utf-8 -*- # author: donttouchkeyboard@gmail.com # software: PyCharm import openpyxl from style.default import ExcelFontStyle from core.base import TableCommon if __name__ == '__main__': """ 二级表头示例 """ wb = openpyxl.Workbook() ws = wb.active wb = TableCommon.excel_write_commo...
nilq/baby-python
python
#!/usr/bin/env python # coding=utf8 ''' Created on Jul 7, 2012 @author: gf ''' import os import Util import ethtool def GetInfoString(): active_interfaces = ethtool.get_active_devices() all_interfaces = GetInterfaceList() for i in active_interfaces: if ethtool.get_flags('%s' % i) & ethtool.IFF_PO...
nilq/baby-python
python
''' Created on Jan 24, 2013 @author: mdickson ''' import inworldz.maestro.uuid as genuuid import inworldz.util.user as user import inworldz.util.estate as estate import inworldz.util.properties as DefaultProperties import inworldz.maestro.MaestroStore as store from inworldz.maestro.ServiceBase import ServiceBase fro...
nilq/baby-python
python
import math import textClasses def title_word_feature(title, processed_text): """ List of values from 0 to 1 rating the number title words that appear in the sentence""" title_word_feature_values = [] # Calculate the number of common words with the title that the sentence has word_intersection = [s...
nilq/baby-python
python
""" """ import os import numpy as np import pandas as pd import xarray as xr from osgeo import gdal from src.utils.constants import ( REGIONS, LANDCOVER_MAP, LANDCOVER_PERIODS, LANDCOVER_PADDING ) if __name__ == "__main__": # Project's root os.chdir("../..") for region in REGIONS: ...
nilq/baby-python
python
import fnmatch from functools import wraps def asgi_cors_decorator( allow_all=False, hosts=None, host_wildcards=None, callback=None ): hosts = hosts or [] host_wildcards = host_wildcards or [] # We need hosts and host_wildcards to be b"" hosts = set(h.encode("utf8") if isinstance(h, str) else h f...
nilq/baby-python
python
from __future__ import division, print_function import numpy as np from scipy.constants import pi from numpy.fft import fftshift from scipy.fftpack import fft, ifft try: import accelerate jit = accelerate.numba.jit autojit = accelerate.numba.autojit complex128 = accelerate.numba.complex128 float64...
nilq/baby-python
python
class Solution: def countConsistentStrings(self, allowed: str, words: List[str]) -> int: c = 0 allowed = set(allowed) for word in words: # word = set(word) for letter in word: if letter not in allowed: break else: ...
nilq/baby-python
python
#!/usr/bin/python import sys, ctypes """ rdi contains argc rsi contains argv (in reverse) - Note rdi decrements """ def echo_args(): # See function 'echo_args' in echo.asm global rdi, rsi, rdx, stack stack.append(rdi) # "push" stack.append(rsi) # "push" ## Stack alignment?? rsp = index or ...
nilq/baby-python
python
from abc import ABC, abstractmethod from zpy.api.reponse import Builder from zpy.api.stages import Decrypt from zpy.logger import g_log from zpy.api.errors import ErrorBuilder from flask import Flask from typing import Any from flask.wrappers import Request, Response from zpy.utils.Encryptor import AESEncryptor import ...
nilq/baby-python
python
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import torch from maskrcnn_benchmark.modeling.box_coder import BoxCoder from maskrcnn_benchmark.structures.bounding_box import BoxList from maskrcnn_benchmark.structures.boxlist_ops import cat_boxlist from maskrcnn_benchmark.structures.boxlist_ops...
nilq/baby-python
python
from __future__ import print_function import argparse import shutil import torch import torchvision import random import os import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torchvision import datasets, transforms from torch.optim.lr_scheduler import StepLR from torch.utils.tensorbo...
nilq/baby-python
python
""" These test cover Google searches """ import pytest from pages.result import GoogleResultPage from pages.search import GoogleSearchPage @pytest.mark.parametrize('phrase', ['nintendo', 'xbox', 'steam']) def test_basic_google_search(browser, phrase): search_page = GoogleSearchPage(browser) result_page = Goog...
nilq/baby-python
python
from modern_greek_accentuation.accentuation import is_accented, where_is_accent, put_accent, count_syllables,\ put_accent_on_the_antepenultimate, put_accent_on_the_penultimate, remove_all_diacritics, put_accent_on_the_ultimate from modern_greek_accentuation.syllabify import modern_greek_syllabify from modern_gree...
nilq/baby-python
python
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import os import warnings from builtins import str from typing import Any, Dict, Optional, Text from rasa.nlu.extractors.entity_synonyms import EntitySynonymMapper cl...
nilq/baby-python
python
import numpy as np import torch import random from skimage import io, transform import torch.nn.functional as F from torchvision import transforms torch.manual_seed(17) random.seed(42) class Resize(object): """Rescale the image in a sample to a given size. Args: output_size (tuple or int): Desired ou...
nilq/baby-python
python
import argparse # import paraview modules. from paraview.web import pv_wslink from paraview.web import protocols as pv_protocols from paraview import simple from wslink import server from enlil import EnlilDataset # ============================================================================= # Create custom PVServe...
nilq/baby-python
python
from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('all/', views.BlogList.as_view(), name='blog-list'), path('bloggers/',views.BlogAuthorList.as_view(), name='blogauthor-list'), path('bloggers/<int:pk>',views.BlogAuthorDetail.as_view(),name='bloga...
nilq/baby-python
python
def main(): #fh, abs_path = mkstemp() antImages = 4000 first = 4 second = 4 newFileName = '%s_%s_bench_door_%s'%(first, second, antImages) with open(newFileName + '_local.txt','w') as new_file: with open('4_4_bench_door_4000_final.txt') as old_file: lines = old_file.readlin...
nilq/baby-python
python
# Generated from Java9.g4 by ANTLR 4.8 from antlr4 import * if __name__ is not None and "." in __name__: from .Java9Parser import Java9Parser else: from Java9Parser import Java9Parser # This class defines a complete listener for a parse tree produced by Java9Parser. class Java9Listener(ParseTreeListener): ...
nilq/baby-python
python
import argparse import pysam from ragtag_utilities.utilities import reverse_complement """ Like bedtools getfasta, but use the gff ID attribute as the FASTA header and always force strandedness. """ def main(): parser = argparse.ArgumentParser(description="Get fasta sequences from a GFF file") parser.add_...
nilq/baby-python
python
"""Runs inference on clips much longer than 1s, by running a sliding window and aggregating predictions.""" from argparse import ArgumentParser from config_parser import get_config import torch import numpy as np import librosa from utils.misc import get_model from tqdm import tqdm import os import glob import json ...
nilq/baby-python
python
import flask import json import inspect from .handle import Resource from .route import RouteFactory from .utils import Logger from .error import RequestError from .db import TinyBDDatabase class App(object): def __init__(self, base_route, db=None): self.base_route = base_route self.debug = True ...
nilq/baby-python
python
# Copyright 2016 Google 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 writing, ...
nilq/baby-python
python
from django.test import TestCase from base.models import Comic, Character, Creator, Story from rest_framework.test import APIClient from rest_framework import status from django.urls import reverse class ComicTestCase(TestCase): """Test suite for the api views.""" def setUp(self): """Define the test ...
nilq/baby-python
python
from collections import OrderedDict def contains_duplicate_extra_space(nums): seen = {} for i, val in enumerate(nums): if val in seen: return True else: seen[val] = i return False def contains_duplicate_2(nums, k): seen = dict() for i, val in enumerate(...
nilq/baby-python
python
import math from kivy.properties import ObjectProperty, Clock, NumericProperty from cobiv.libs.magnet import Magnet from cobiv.modules.views.browser.eolitem import EOLItem class DraggableItem(Magnet): thumb = ObjectProperty(None, allownone=True) container = ObjectProperty(None) cell_size = NumericPropert...
nilq/baby-python
python
"""Submodule that handles the generation of periodic table information.""" from __future__ import annotations import typing from .atomic_masses import ATOMIC_MASSES def atomic_symbols_to_mass(atoms: typing.Sequence[str]) -> list[float]: """Converts atomic symbols to their atomic masses in amu. Parameters ...
nilq/baby-python
python
# # Copyright (C) 2009 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and ...
nilq/baby-python
python
# -*- coding: utf-8 -*- """ Created on Wed Jul 27 10:55:34 2016 The plain vanila implementation of Recurrent Neural Network @author: yaric """ import time import datetime from random import uniform import numpy as np import scipy.io as sio class RNN(object): def __init__(self, n_features, n_outputs, n_neur...
nilq/baby-python
python
from baiji.serialization import json from baiji.serialization.json import JSONDecoder class BlmathJSONDecoder(JSONDecoder): def __init__(self): super(BlmathJSONDecoder, self).__init__() self.register(self.decode_value) def decode_value(self, dct): from blmath.value import Value ...
nilq/baby-python
python
class Solution: def nthUglyNumber(self, n): """ :type n: int :rtype: int """ if n < 1: return 0 ugly = [0]*n ugly[0] = 1 i2 = i3 = i5 = 0 nm_2, nm_3, nm_5 = 2, 3, 5 for i in range(1, n): ugly[i] = min(nm_2, nm_3,...
nilq/baby-python
python
def slices(series, length): if length < 1 or length > len(series): raise ValueError("length too high") i = 0 result = [] while i+length <= len(series): result.append(series[i:i+length]) i+=1 return result
nilq/baby-python
python
name = input("What is your name?\n") print ("Hello", name)
nilq/baby-python
python
from keras.datasets import mnist import os from pandas import DataFrame from PIL import Image from autokeras.utils import ensure_dir ensure_dir('mnist/train') ensure_dir('mnist/test') (x_train, y_train), (x_test, y_test) = mnist.load_data() # x_train = x_train.reshape(x_train.shape + (1,)) # x_test = x_test.reshape(...
nilq/baby-python
python
from django.http import HttpResponse # from django.shortcuts import render # Create your views here. def home(request): return HttpResponse('Olá Django')
nilq/baby-python
python
import os import subprocess if os.environ.get("HEXA_FEATURE_FLAG_S3FS", "false") == "true": for bucket_name in os.environ.get("AWS_S3_BUCKET_NAMES", "").split(","): path_to_umount = os.path.join(f"/home/jovyan/s3-{bucket_name}") subprocess.run( [ "umount", ...
nilq/baby-python
python
"""Returns compiled regex from regular expression.""" import re import pytest from mklists.returns import compile_regex # pylint: disable=anomalous-backslash-in-string # These are just tests... def test_compile_regex(): """Returns compiled regex from simple string.""" regex = "NOW" assert isinstance(co...
nilq/baby-python
python
from __future__ import print_function, division import scipy #Import Require Libraries import matplotlib.pyplot as plt import cv2 import pandas from keras.applications.vgg16 import VGG16 from keras.models import Sequential from keras.layers import Dense,Dropout from keras.layers import LeakyReLU from kera...
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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
nilq/baby-python
python
# Copyright (c) 2019, Digi International, Inc. # # 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, pu...
nilq/baby-python
python
#write a function to convert decimal number to binary, octal and Heaxdecimal equivalent n = input("Enter the Decimal") print("BINARY EQUIVALENT",bin(n)) print("OCTAL EQUIVALENT",oct(n)) print("HEXADECIMAL EQUIVALENT",hex(n))
nilq/baby-python
python
from microbit import * import time while True: temp_c = pin1.read_analog() / 10.23 - 20 temp_f = int(temp_c * 9 / 5 + 32) display.scroll(temp_f) time.sleep(0.5)
nilq/baby-python
python
from argparse import Namespace, ArgumentParser import os import torch from torch import nn from torch.nn import functional as F from torchvision import datasets import torchvision.transforms as transforms from utils import datautils import models from utils import utils import numpy as np import PIL from tqdm import t...
nilq/baby-python
python
from flask import Flask , request , jsonify , make_response from flask_cors import CORS import pymysql #import config from config import db_host, db_user, db_passwrd, db_db, config_domain from check_encode import random_token, check_prefix from display_list import list_data from auth import auth shorty_api = Flask(__...
nilq/baby-python
python
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from beanmachine.ppl.experimental.gp.kernels import all_kernels from beanmachine.ppl.experimental.gp.likelihoods import all_likelihoods __...
nilq/baby-python
python
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
nilq/baby-python
python
from django.urls import path from . import views app_name = 'search' urlpatterns = [ path('theorem', views.SearchTheoremView.as_view(), name='index'), ]
nilq/baby-python
python
from rest_framework import viewsets from rest_framework.response import Response from rest_framework.decorators import action from rest_framework.authentication import BasicAuthentication from rest_framework.authentication import SessionAuthentication from rest_framework.permissions import IsAuthenticated from databa...
nilq/baby-python
python
from django.urls import path from . import views urlpatterns = [ path('config-creator/', views.config_creator, name='config_creator'), path('data-generator/', views.data_generator, name='data_generator'), ]
nilq/baby-python
python
# 导入需要的包文件 from flask import Blueprint, request from flask_restx import Api, Resource """ 创建一个蓝图,相当于创建项目组成的一部分,主要是方便我们管理自己的项目; 比如你的项目由很多个子项目构成,那么把为每一个子项目创建一个蓝图来创建对应的接口,好过于 把所有的接口都放在同一个.py文件吧! 这里创建蓝图Blueprint类还有很多其他的参数可选,大家可以看Blueprint类的源码,里面介绍的很清晰,英文不好的童鞋 请自觉学习英文; """ app_one_api = Blueprint('app_one_api', __name__)...
nilq/baby-python
python
# coding=utf-8 # -------------------------------------------------------------------------- # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from ...
nilq/baby-python
python
import numpy as np import statistics import pandas as pd import time import os from sklearn.metrics import f1_score, accuracy_score from sklearn.multiclass import OneVsRestClassifier from sklearn.neighbors import KNeighborsClassifier from sklearn.metrics import confusion_matrix from sklearn.svm import SVC from sklearn...
nilq/baby-python
python
#!python3 a = (x for x in range(3)) print(next(a)) print(next(a)) print(next(a)) try: print(next(a)) # -> raises StopIteration except StopIteration: print("StopIteration raised")
nilq/baby-python
python
import torch import torch.nn as nn from torch.autograd import Variable from torch import optim import torch.nn.functional as F class FFNet(nn.Module): def __init__(self, input_size, output_size, hidden_size=64): super(FFNet, self).__init__() # one hidden layer self.fc1 = nn.Linear(input_s...
nilq/baby-python
python
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # 解法一:44 ms 13.9 MB import queue class Solution: def levelOrder(self, root: TreeNode) -> List[List[int]]: if not root: return [] ...
nilq/baby-python
python
from __future__ import annotations import typing as t from functools import wraps from graphql import GraphQLArgument from graphql import GraphQLBoolean from graphql import GraphQLEnumType from graphql import GraphQLField from graphql import GraphQLFloat from graphql import GraphQLID from graphql import GraphQLInputF...
nilq/baby-python
python
# this_dict={ # "brand":'Ford', # "model":'Mutang', # "year": 1964 # } # print(this_dict) # #### # # Access items # x=this_dict['model'] # print(x) # ## Access items with get method # x=this_dict.get('model') # print(x) # ########### # # Change value in dictionary # this_dict['year']=2019 # print(this_d...
nilq/baby-python
python
from __future__ import absolute_import, division, print_function, unicode_literals import six import sys from echomesh.util.registry.Registry import Registry def register_module(class_path, *modules, **kwds): module = sys.modules[class_path] registry = Registry(class_path, class_path=class_path, **kwds) ...
nilq/baby-python
python
# Copyright 2020 Akamai Technologies, Inc # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to...
nilq/baby-python
python
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # =========================================================================== # # Project : MLStudio # # Version : 0.1.0 # # File : regression.py ...
nilq/baby-python
python
from django import forms from django.contrib.auth.models import User class POSTForm(forms.Form): username = forms.CharField( label='Username', max_length=30, help_text='Enter a unique name for your login', widget=forms.TextInput(attrs={ 'required': 'required', 'title': 'Enter a unique name for your...
nilq/baby-python
python
#!/usr/bin/env python # encoding: utf-8 # # Stylus, Copyright 2006-2009 Biologic Institute # # 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....
nilq/baby-python
python
from datetime import datetime from django.contrib.auth import get_user_model from django.test import TestCase from django.urls import reverse from rest_framework import status from rest_framework.test import APIClient from freezegun import freeze_time from core.models import CoffeType, Harvest from core.serializers...
nilq/baby-python
python
#!/usr/bin/python3 # -*- coding: utf-8 -*- # # Copyright 2015 Pascual Martinez-Gomez # # 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 # ...
nilq/baby-python
python
""" Color definitions for various charts https://htmlcolorcodes.com/color-chart/ """ colors = { 'orange1': '#E74C3C', 'blue1': '#1B4F72', 'blue2': '#2874A6', 'blue3': '#3498DB', 'blue4': '#85C1E9' }
nilq/baby-python
python
# coding=utf-8 import time import asyncio import logging from asyncio import CancelledError import aiohttp import async_timeout from freehp.extractor import extract_proxies log = logging.getLogger(__name__) class ProxySpider: def __init__(self, config, loop=None): self._proxy_pages = config.get('proxy...
nilq/baby-python
python
"""open_discussions constants""" from rest_framework import status PERMISSION_DENIED_ERROR_TYPE = "PermissionDenied" NOT_AUTHENTICATED_ERROR_TYPE = "NotAuthenticated" DJANGO_PERMISSION_ERROR_TYPES = ( status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN, ) ISOFORMAT = "%Y-%m-%dT%H:%M:%SZ"
nilq/baby-python
python
# from apps.ots.event.signal_event import SignalEvent from apps.ots.strategy.risk_manager_base import RiskManagerBase class NaiveRiskManager(RiskManagerBase): def __init__(self): self.refl = '' def get_mkt_quantity(self, signalEvent): return 100
nilq/baby-python
python