content
stringlengths
0
1.05M
origin
stringclasses
2 values
type
stringclasses
2 values
""" Copyright (c) 2017-2020 ABBYY Production LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in wr...
nilq/baby-python
python
from __future__ import absolute_import, unicode_literals import os from celery import Celery # Set default settings for celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'stratahq.settings') app = Celery('strathq') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @ap...
nilq/baby-python
python
from flask import session import csv, pymssql, datetime import threading table_lock = threading.Lock() def create_csv_rep(orgid, filename): table_lock.acquire() host = "197.189.232.50" username = "FE-User" password = "Fourier.01" database = "PGAluminium" conn = pymssql.connect(host...
nilq/baby-python
python
from granule_ingester.processors.EmptyTileFilter import EmptyTileFilter from granule_ingester.processors.GenerateTileId import GenerateTileId from granule_ingester.processors.TileProcessor import TileProcessor from granule_ingester.processors.TileSummarizingProcessor import TileSummarizingProcessor from granule_ingeste...
nilq/baby-python
python
import sys input = sys.stdin.readline # import accumulate takes too much memory def accumulate(A): n = len(A) P = [0] * (n + 1) for k in range(1, n + 1): P[k] = P[k - 1] + A[k - 1] return P count = 0 length = 0 lower_bound = 0 cups, fill = map(int, input().split()) cuplist = [0] * (cups + 2)...
nilq/baby-python
python
import PyPDF2 pdf1File = open('meetingminutes.pdf', 'rb') pdf2File = open('meetingminutes2.pdf', 'rb') pdf1Reader = PyPDF2.PdfFileReader(pdf1File) pdf2Reader = PyPDF2.PdfFileReader(pdf2File) pdfWriter = PyPDF2.PdfFileWriter() for pageNum in range(pdf1Reader.numPages): pageObj = pdf1Reader.getPage(pageNum) p...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Created on Nov 7, 2015 Don't blink... @author: Juan_Insuasti ''' import sys import datetime import os.path import json class Logger: def __init__(self, logName="Log", file="log.txt", enabled=True, printConsole=True, saveFile=False, saveCloud=False): self....
nilq/baby-python
python
from setuptools import setup # Load in babel support, if available. try: from babel.messages import frontend as babel cmdclass = {"compile_catalog": babel.compile_catalog, "extract_messages": babel.extract_messages, "init_catalog": babel.init_catalog, "update_cat...
nilq/baby-python
python
from typing import Union from notion.models.annotations import Annotations class RichText(): """ https://developers.notion.com/reference/rich-text """ TYPES = ["text", "mention", "equation"] def __init__(self, plain_text: str = None, href: str = None, annotations: Union[dict, Annotations] = Non...
nilq/baby-python
python
""" Handles running extensions inside a sandbox, which runs outside the primary Petronia memory space with OS specific constraints. """ from .module_loader import create_sandbox_module_loader
nilq/baby-python
python
# -*- coding: utf-8 -*- # Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is # holder of all proprietary rights on this computer program. # You can only use this computer program if you have closed # a license agreement with MPG or you get the right to use the computer # program from someone who is...
nilq/baby-python
python
from fastai.conv_learner import * from fastai.dataset import * from tensorboard_cb_old import * import cv2 import pandas as pd import numpy as np import os from sklearn.model_selection import train_test_split from sklearn.metrics import f1_score import scipy.optimize as opt import torch import torch.nn as nn import t...
nilq/baby-python
python
"""Reverse-engineered client for the LG SmartThinQ API. """ from .core import * # noqa from .client import * # noqa from .ac import * # noqa from .dishwasher import * # noqa from .dryer import * # noqa from .refrigerator import * # noqa from .washer import * # noqa __version__ = '1.3.0'
nilq/baby-python
python
# dic = {'key': 'value', 'key2': 'value2'} import json # # ret = json.dumps(dic) # 序列化 # print(dic, type(dic)) # print(ret, type(ret)) # # res = json.loads(ret) # 反序列化 # print(res, type(res)) # 问题1 # dic = {1: 'value', 2: 'value2'} # ret = json.dumps(dic) # 序列化 # print(dic, type(dic)) # print(ret, type(ret)) # # r...
nilq/baby-python
python
__author__ = 'xubinggui' class Student(object): def __init__(self, name, score): self.name = name self.score = score def print_score(self): print(self.score) bart = Student('Bart Simpson', 59) bart.print_score()
nilq/baby-python
python
import unittest from app.models import Pitch, User from flask_login import current_user from app import db class TestPitch(unittest.TestCase): def setUp(self): self.user_joe = User( username='jack', password='password', email='xyz@gmail.com') self.new_pitch = Pitch(title="Test", pitch...
nilq/baby-python
python
# -*- coding: utf-8 -*- from abc import ABCMeta, abstractmethod from .unique_identifiable import CloudioUniqueIdentifiable class CloudioObjectContainer(CloudioUniqueIdentifiable): """Interface to be implemented by all classes that can hold cloud.iO objects.""" __metaclass__ = ABCMeta @abstractmethod ...
nilq/baby-python
python
import os, sys; sys.path.append(os.path.join("..", "..", "..")) from pattern.en import parse, Text # The easiest way to analyze the output of the parser is to create a Text. # A Text is a "parse tree" of linked Python objects. # A Text is essentially a list of Sentence objects. # Each Sentence is a list of Word objec...
nilq/baby-python
python
import re from enum import Enum from operator import attrgetter from re import RegexFlag from typing import List, Union, Match, Dict, Optional from annotation.models.models import Citation from annotation.models.models_enums import CitationSource from library.log_utils import report_message from ontology.models import...
nilq/baby-python
python
import pprint from flask import Flask from flask import request app = Flask(__name__) @app.route('/', methods=['POST']) def hello_world(): content = request.get_json(silent=True) pprint.pprint(content) return content
nilq/baby-python
python
#! /usr/bin/env python from __future__ import print_function import tensorflow as tf import os, collections, sys, subprocess, io from abc import abstractmethod import numpy as np def flattern(A): ''' Flatten a list containing a combination of strings and lists. Copied from https://stackoverflow.com/questions/1786...
nilq/baby-python
python
# -*- coding: utf-8 -*- """ RandOm Convolutional KErnel Transform (ROCKET) """ __author__ = ["Matthew Middlehurst", "Oleksii Kachaiev"] __all__ = ["ROCKETClassifier"] import numpy as np from joblib import delayed, Parallel from sklearn.base import clone from sklearn.ensemble._base import _set_random_states from sklea...
nilq/baby-python
python
# Generated by Django 2.2.1 on 2019-05-29 20:37 import json from django.db import migrations def normalize_webhook_values(apps, schema_editor): Channel = apps.get_model("api", "Channel") for ch in Channel.objects.filter(kind="webhook").only("value"): # The old format of url_down, url_up, post_data s...
nilq/baby-python
python
from easyidp.io.tests import test import easyidp.io.metashape import easyidp.io.pix4d import easyidp.io.pcd
nilq/baby-python
python
#!/usr/bin/python # (C) 2005 British Broadcasting Corporation and Kamaelia Contributors(1) # All Rights Reserved. # # You may only modify and redistribute this under the terms of any of the # following licenses(2): Mozilla Public License, V1.1, GNU General # Public License, V2.0, GNU Lesser General Public Licens...
nilq/baby-python
python
import pytest from channels.generic.websocket import ( AsyncJsonWebsocketConsumer, AsyncWebsocketConsumer, JsonWebsocketConsumer, WebsocketConsumer, ) from channels.testing import WebsocketCommunicator # @pytest.mark.asyncio # async def test_websocket_consumer(): # """ # Tests that WebsocketConsumer is i...
nilq/baby-python
python
from PySide6.QtCore import QAbstractTableModel, Qt class PandasModel(QAbstractTableModel): def __init__(self, data): super().__init__() self._data = data def rowCount(self, index): return self._data.shape[0] def columnCount(self, parnet=None): return self._data.shape[1] ...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Copyright (c) 2019 Cisco and/or its affiliates. This software is licensed to you under the terms of the Cisco Sample Code License, Version 1.1 (the "License"). You may obtain a copy of the License at https://developer.cisco.com/docs/licenses All use o...
nilq/baby-python
python
#!/usr/bin/env python # vim: ai ts=4 sts=4 et sw=4 import re import logging from rapidsms.apps.base import AppBase from .models import Location logger = logging.getLogger(__name__) class App(AppBase): PATTERN = re.compile(r"^(.+)\b(?:at)\b(.+?)$") def __find_location(self, text): try: ...
nilq/baby-python
python
class Weapon: def __init__(self, name, damage, range): self.name = name self.damage = damage self.range = range def hit(self, actor, target): if target.is_alive(): if (self.range >= (target.pos_x - actor.pos_x) + (target.pos_y - actor.pos_y)): ...
nilq/baby-python
python
# flake8: noqa # # Root of the SAM package where we expose public classes & methods for other consumers of this SAM Translator to use. # This is essentially our Public API #
nilq/baby-python
python
class Solution: def trap(self, height: List[int]) -> int: n = len(height) if n<=2:return 0 stack = [] ans = 0 for i,num in enumerate(height): while stack and height[stack[-1]]<num: cur = stack.pop() if stack: ans...
nilq/baby-python
python
import random def int_to_list(n): n=str(n) l=list(n) return l class CowsAndBulls: def __init__(self): self.number = "" self.digits = 0 self.active = False def makeRandom(self, digit): digits = set(range(10)) first = random.randint(1, 9) second_to_las...
nilq/baby-python
python
""" Build a parse tree to evaluate a fully parenthesised mathematical expression, ((7+3)∗(5−2)) = ? * / \ + - / \ / \ ...
nilq/baby-python
python
#! /usr/bin/env python import re import csv import click import numpy as np from scipy.stats import spearmanr from hivdbql import app from hivdbql.utils import dbutils from hivdbql.models.isolate import CRITERIA_SHORTCUTS np.seterr(divide='raise', invalid='raise') db = app.db models = app.models GENE2DRUGCLASS = {...
nilq/baby-python
python
""" Manages drawing of the game """ from typing import List, Tuple, Any import colorsys import random import pygame import settings from game_state import GameState, Snake, Pizza Color = Tuple[int, int, int] class Colors: """ Basic colors """ CLEAR_COLOR = (240, 240, 240) BLACK = (0, 0, 0) DARK_YELLO...
nilq/baby-python
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from re import findall from string import printable from struct import unpack from src.capturePkt.networkProtocol import NetworkProtocol class Telnet(NetworkProtocol): IAC = 0xff codeDict = {236: 'EOF', 237: 'SUSP', 238: 'ABORT',...
nilq/baby-python
python
#-*- coding: utf-8 -*- ''' Created on 2017. 11. 06 Updated on 2017. 11. 06 ''' from __future__ import print_function import os import cgi import re import time import codecs import sys import subprocess import math import dateutil.parser from datetime import datetime from commons import Subjects from x...
nilq/baby-python
python
#!/usr/bin/env python3 # # Copyright (c) 2018 Sébastien RAMAGE # # For the full copyright and license information, please view the LICENSE # file that was distributed with this source code. # import logging import argparse import time from zigate import connect logging.basicConfig(level=logging.INFO) parser = argparse...
nilq/baby-python
python
import os import sys import argparse from cuttsum.event import read_events_xml from cuttsum.nuggets import read_nuggets_tsv from cuttsum.util import gen_dates import streamcorpus as sc import numpy as np from sklearn.feature_extraction import DictVectorizer import codecs def main(): event_file, rc_dir, event_title...
nilq/baby-python
python
# coding: utf-8 # 2020/1/3 @ tongshiwei __all__ = ["get_net", "get_bp_loss"] from mxnet import gluon from .WCLSTM import WCLSTM from .WCRLSTM import WCRLSTM from .WRCLSTM import WRCLSTM def get_net(model_type, class_num, embedding_dim, net_type="lstm", **kwargs): if model_type == "wclstm": return WCLST...
nilq/baby-python
python
"""LiteDRAM BankMachine (Rows/Columns management).""" import math from migen import * from litex.soc.interconnect import stream from litedram.common import * from litedram.core.multiplexer import * class _AddressSlicer: def __init__(self, colbits, address_align): self.colbits = colbits self.ad...
nilq/baby-python
python
from django.contrib import admin from mptt.admin import MPTTModelAdmin from .models import Business, Category, Request @admin.register(Business) class BusinessAdmin(admin.ModelAdmin): list_display = ('name', 'location', 'main_category') ordering = ('name',) filter_horizontal = ('other_categories', 'deliv...
nilq/baby-python
python
import uuid from cinderclient import exceptions as cinder_exceptions from ddt import ddt, data from django.conf import settings from django.test import override_settings from novaclient import exceptions as nova_exceptions from rest_framework import status, test import mock from six.moves import urllib from waldur_op...
nilq/baby-python
python
########################################################################## # # Copyright (c) 2008-2010, Image Engine Design 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: # # * Redis...
nilq/baby-python
python
# -*- coding: utf-8 -*- import codecs import numpy as np import tensorflow as tf from Transformer.config.hyperparams import Hyperparams as pm class Data_helper(object): def __init__(self): self.pointer = 0 def mini_batch(self): X, Y = self.load_train_datasets() num_batch ...
nilq/baby-python
python
import os import glob def delete_given_file(image_name): file_name = image_name.split(".")[0] IMG_PATH = "./annotated_dataset/img" TXT_PATH = "./annotated_dataset/txt_label" XML_PATH = "./annotated_dataset/xml_label" img_file = f"{IMG_PATH}/{file_name}.jpg" txt_file = f"{TXT_PATH}/{file_name...
nilq/baby-python
python
#!/usr/bin/env python # Copyright (c) 2020 - for information on the respective copyright owner # see the NOTICE file and/or the repository # <https://github.com/boschresearch/amira-blender-rendering>. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance w...
nilq/baby-python
python
""" Transitions (Perturbation Kernels) ================================== Perturbation strategies. The classes defined here transition the current population to the next one. pyABC implements global and local transitions. Proposals for the subsequent generation are generated from the current generation density estimat...
nilq/baby-python
python
from test.ga.ga import GaTestCase from test.ga.population import PopulationTestCase from test.ga.individual import IndividualTestCase __all__ = ( "GaTestCase", "PopulationTestCase", "IndividualTestCase" )
nilq/baby-python
python
def get_key(): if isinstance(self.instance, def clean(): pass
nilq/baby-python
python
from screen.drawing.color import * from screen.drawing.color import __all__ as _color__all__ from screen.drawing.colorinterpolationmethod import * from screen.drawing.colorinterpolationmethod import __all__ as _colorinterpolationmethod__all__ from screen.drawing.style import * from screen.drawing.style import __all__ a...
nilq/baby-python
python
from types import FunctionType import backends __storage = backends.default() def set_storage(BackendInstance): global __storage __storage = BackendInstance def make_cached(make_key, f): def cached(*args, **kwargs): cache_key = make_key(args=args, kwargs=kwargs) if __storage...
nilq/baby-python
python
""" Created on Wed Jan 15 11:17:10 2020 @author: mesch """ from colorama import init, Fore, Back init(autoreset=True) #to convert termcolor to wins color import copy from pyqum.instrument.benchtop import RSA5 as MXA from pyqum.instrument.benchtop import PSGA from pyqum.instrument.modular import AWG from pyqum.instrum...
nilq/baby-python
python
from datetime import datetime import hashlib from werkzeug.security import generate_password_hash, check_password_hash from itsdangerous import TimedJSONWebSignatureSerializer as Serializer from markdown import markdown import bleach from flask import current_app, request, url_for from flask_login import UserMixin, Ano...
nilq/baby-python
python
from typing import Any, Dict, Iterable, List import pandas as pd from fugue.dataframe import ArrayDataFrame from fugue.exceptions import FugueInterfacelessError from fugue.extensions.transformer import ( Transformer, _to_transformer, transformer, register_transformer, ) from pytest import raises from t...
nilq/baby-python
python
from header_common import * from header_dialogs import * from header_operations import * from module_constants import * #################################################################################################################### # During a dialog, the dialog lines are scanned from top to bottom. # If the dialo...
nilq/baby-python
python
#!/usr/bin/python import sys import h5py if __name__ == "__main__": files = sys.argv[1:] files.extend(sys.stdin.readlines()) for file in files: file = file.strip() with h5py.File(file, 'r') as f: f['/entry1/instrument/parameters/y_pixels_per_mm'][0] = 0.321
nilq/baby-python
python
""" Tests CoreML Scaler converter. """ import unittest import numpy import coremltools from sklearn.preprocessing import StandardScaler from onnxmltools.convert.coreml.convert import convert from onnxmltools.utils import dump_data_and_model class TestCoreMLScalerConverter(unittest.TestCase): def test_scaler(self...
nilq/baby-python
python
total_bill = 124.56 procent_10 = 0.10 procent_12 = 0.12 procent_15 = 0.15 split_people = 7 tip = total_bill * procent_12 + total_bill print(tip) print(tip) total = tip / float(split_people) print(round(total, 2))
nilq/baby-python
python
from guardian.core import ObjectPermissionChecker class ObjectPermissionCheckerViewSetMixin: """add a ObjectPermissionChecker based on the accessing user to the serializer context.""" def get_serializer_context(self): context = super().get_serializer_context() if self.request: per...
nilq/baby-python
python
# -------------------------------------------------------------------------- # Source file provided under Apache License, Version 2.0, January 2004, # http://www.apache.org/licenses/ # (c) Copyright IBM Corp. 2015, 2016 # -------------------------------------------------------------------------- """ This is a problem ...
nilq/baby-python
python
import os from minicps.devices import PLC from temperature_simulator import TemperatureSimulator from Logger import hlog import time class EnipPLC1(PLC): #builds upon the tags of the swat example # These constants are used mostly during setting up of topology NAME = 'plc1' IP = ' 10.0.2.110' MAC = '...
nilq/baby-python
python
from setuptools import setup, find_packages setup(name='donkeypart_keras_behavior_cloning', version='0.1.3', description='Library to control steering and throttle actuators.', long_description="no long description given", long_description_content_type="text/markdown", url='https://github....
nilq/baby-python
python
from trading_bot import app, create_app def init_app(): # TODO add test config class create_app() def reset_managers(): create_app() app.symbol_manager._symbols = [] app.exchange_manager._exchanges = [] app.exchange_manager._exchanges_by_name = {} app.indicator_manager._indicators = [] ...
nilq/baby-python
python
import cv2 import numpy as np import math import time import testAAE import testAAEWithClassifier import region def quantizeAngle(angle): if angle >= 0: if angle >= 90: if angle >= 45: quantized = 2 else: quantized = 1 elif angle >= 135: ...
nilq/baby-python
python
def read_input(): # for puzzles where each input line is an object with open('input.txt') as fh: for line in fh.readlines(): if line.strip(): yield line.strip() def read_input_objs(): # for puzzles with newline-separated objects as input with open('input.txt') as fh...
nilq/baby-python
python
import PySimpleGUI as sg use_custom_titlebar = False def make_window(theme=None): NAME_SIZE = 23 def name(name): dots = NAME_SIZE - len(name) - 2 return sg.Text( name + ' ' + '•' * dots, size=(NAME_SIZE, 1), justification='r', pad=(0, 0), ...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for :mod:`orion.algo.tpe`.""" import numpy import pytest from scipy.stats import norm from orion.algo.space import Categorical, Fidelity, Integer, Real, Space from orion.algo.tpe import ( TPE, CategoricalSampler, GMMSampler, adaptive_parzen_estima...
nilq/baby-python
python
import pygame import random screen_size = [360, 600] screen = pygame.display.set_mode(screen_size) pygame.font.init() background = pygame.image.load('background.png') user = pygame.image.load('user.png') chicken = pygame.image.load('chicken.png') def display_score(score): font = pygame.font.SysFont('Comic Sans ...
nilq/baby-python
python
from flask import request, jsonify, Blueprint from flask_jwt_extended import ( create_access_token, create_refresh_token, jwt_refresh_token_required, get_jwt_identity ) from flasgger import swag_from from myapi.models import User from myapi.extensions import pwd_context, jwt from myapi.api.doc.login_do...
nilq/baby-python
python
import psycopg2 import os from dotenv import load_dotenv import sqlite3 import pandas as pd import datetime from psycopg2.extras import execute_values load_dotenv() # connecting to our elephant sql rpg database RPG_DB_NAME = os.getenv('RPG_DB_NAME', default='oops') RPG_DB_USER = os.getenv('RPG_DB_USER', default='oop...
nilq/baby-python
python
import time def time_training(fitter): """Print the time taken for a machine learning algorithm to train. Parameters: fitter(function): function used to train the model Returns: None """ start = time.time() fitter() end = time.time() diff = end - start print(f'Traini...
nilq/baby-python
python
################################################################################ # Module: decision.py # Description: Agent decision function templates # Rafal Kucharski @ TU Delft, The Netherlands ################################################################################ from math import exp import random import...
nilq/baby-python
python
import boto3 from aws_cdk import ( core as cdk, aws_events as events, aws_events_targets as events_targets, aws_glue as glue, aws_iam as iam, aws_lambda as lmb, aws_lambda_python as lambda_python, aws_logs as logs, aws_s3 as s3, aws_s3_notifications as s3_notifications, aws_k...
nilq/baby-python
python
import matplotlib.pyplot as plt from typing import List, Tuple, Union from mathplotlib.base import BaseElement, Curve2D from mathplotlib.style import Style from mathplotlib.utils import update_with_default class Text(BaseElement): """ Draws a bit of text """ on_curve_params = dict( horiz...
nilq/baby-python
python
import argparse import math import PIL.Image import PIL.ImageDraw import sys def choose_guideline_style(guideline_mod): if guideline_mod % 16 == 0: return ('#1f32ff', 3) if guideline_mod % 8 == 0: return ('#80f783', 2) if guideline_mod % 4 == 0: return ('#f4bffb', 1) def in_ellipso...
nilq/baby-python
python
class GQL: # Client -> Server message types. CONNECTION_INIT = "connection_init" START = "start" STOP = "stop" CONNECTION_TERMINATE = "connection_terminate" # Server -> Client message types. CONNECTION_ERROR = "connection_error" CONNECTION_ACK = "connection_ack" DATA = "data" ER...
nilq/baby-python
python
# -*- coding:utf-8 -*- import time from tqdm import tqdm import requests from lxml import etree headers = {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Encoding': 'gb2312,utf-8', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:57.0) Gecko/201001...
nilq/baby-python
python
# coding: utf-8 """ Eclipse Kapua REST API No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501 OpenAPI spec version: 1.0 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import ...
nilq/baby-python
python
import datetime import sys import pathlib current_dir = pathlib.Path(__file__).resolve().parent sys.path.append( str(current_dir) + '/../' ) from lib.config import get_camera_config from service.camera import take_pictures """ cronによって毎分実行される その分にタイマーが設定されているカメラの撮影リクエストを送信する python3 cameras.py """ def main(): n...
nilq/baby-python
python
"""Dataset specification for hit graphs using pytorch_geometric formulation""" # System imports import os # External imports import numpy as np import pandas as pd import torch from torch.utils.data import Dataset, random_split import torch_geometric def load_graph(filename): with np.load(filename) as f: ...
nilq/baby-python
python
""" author: Rene Pickhardt (rene.m.pickhardt@ntnu.no) Date: 15.1.2020 License: MIT Checks which nodes are currently online by establishing a connection to those nodes. Results can later be studied with `lightning-cli listpeers` or when `jq` is installed with `lcli getinfo | jq ".num_peers"` This tool is intended to b...
nilq/baby-python
python
"""Helper methods.""" from typing import Tuple, Optional from rest_framework import status from rest_framework.response import Response def validate_request_body( request, ) -> Tuple[Optional[Response], Optional[dict]]: """ Validate the json body of a request. :param request: django request :ret...
nilq/baby-python
python
# -*- coding: utf-8 -*- """ Created on Fri Apr 3 20:07:19 2020 https://zhuanlan.zhihu.com/p/78452993 @author: lenovo """ import torch from torch.nn import Sequential as Seq, Linear as Lin, ReLU from torch_geometric.nn import MessagePassing from torch_geometric.datasets import TUDataset # dataset = TUDataset(roo...
nilq/baby-python
python
class Web3ClientException(BaseException): pass class MissingParameter(Web3ClientException): pass class TransactionTooExpensive(Web3ClientException): pass class NetworkNotFound(Web3ClientException): pass
nilq/baby-python
python
import gdo def f(): import time time.sleep(10) gdo.concurrent( gdo.RunGraph( "slee", "sleep 2", "slle2", "sleep 5", "pysleep", f, "true", "true") .req("slee", "true") )
nilq/baby-python
python
#!/usr/bin/python #PIN 0-8 3v3 pull-up default, 9-27 pull-down default # Pin # for relay connected to heating element (Note: GPIO pin#) he_pin = 26 brew_pin = 22 steam_pin = 27 led_pin = 13 # Default goal temperature set_temp = 96. set_steam_temp = 145. #Use Fahrenheit? use_fahrenheit = False # Default alarm time...
nilq/baby-python
python
# -*- coding: utf-8 -*- import os from codecs import open from setuptools import setup here = os.path.abspath(os.path.dirname(__file__)) # load the package's __version__.py module as a dictionary about = {} with open(os.path.join(here, "profiler", "__version__.py"), "r", "utf-8") as f: exec(f.read(), about) tr...
nilq/baby-python
python
"""recode entities Revision ID: 4212acfa7aec Revises: 235fd19bb942 Create Date: 2016-12-01 10:24:07.638773 """ import logging # from pprint import pprint from alembic import op import sqlalchemy as sa import uuid log = logging.getLogger('migrate') revision = '4212acfa7aec' down_revision = '235fd19bb942' SCHEMA = ...
nilq/baby-python
python
import os # Reserves disk space by saving binary zeros to a file a given size class DiskSpaceReserver: def __init__(self, path: str, size: int): self.path = path self.size = size def reserve(self): with open(self.path, 'wb') as f: f.write(b'\0' * self.size) def releas...
nilq/baby-python
python
import uuid from core import db, logging, plugin, model from core.models import conduct, trigger, webui from plugins.occurrence.models import action class _occurrence(plugin._plugin): version = 5.0 def install(self): # Register models model.registerModel("occurrence","_occurrence","_action",...
nilq/baby-python
python
#!/usr/bin/env python import imp import io import os from setuptools import setup, find_packages def read(*filenames, **kwargs): encoding = kwargs.get("encoding", "utf-8") sep = kwargs.get("sep", "\n") buf = [] for filename in filenames: with io.open(filename, encoding=encoding) as f: ...
nilq/baby-python
python
# -*- coding: utf-8 -*- # Copyright (c) 2015, nishta and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe.utils import getdate, validate_email_add, today from frappe.model.document import Document from planning.planning.myfunction import ma...
nilq/baby-python
python
import logging from impala.dbapi import connect from .settings import ImpalaConstants, NEED_CERTIFICATE from .error import ImpalaConnectError, ImpalaQueryError class ImpalaWrapper: def __init__(self, host=ImpalaConstants.HOST, port=ImpalaConstants.PORT, user=ImpalaConstants.USER, database=None, ...
nilq/baby-python
python
from quixstreaming import QuixStreamingClient from flask import Flask, request from datetime import datetime from waitress import serve import os import json import hmac import hashlib # Quix injects credentials automatically to the client. # Alternatively, you can always pass an SDK token manually as an argument. cl...
nilq/baby-python
python
import re import json from ..extractor.common import InfoExtractor from ..utils import ( js_to_json ) class sexixnetIE(InfoExtractor): #http://www.txxx.com/videos/2631606/stepmom-seduces-teen-babe/ _VALID_URL = r'https?://(?:www\.)?sexix\.net' def _real_extract(self, url): webpage = self._...
nilq/baby-python
python
""" https://www.hackerrank.com/challenges/no-idea There is an array of integers. There are also disjoint sets, and , each containing integers. You like all the integers in set and dislike all the integers in set . Your initial happiness is . For each integer in the array, if , you add to your happiness. If , yo...
nilq/baby-python
python
from entities import FeedEntity as FE FEEDS = ( FE('rss', 'The Verge', 'https://www.theverge.com/rss/index.xml'), FE('rss', 'VB', 'https://feeds.feedburner.com/venturebeat/SZYF'), # FE('rss', 'TNW', 'https://thenextweb.com/feed/'), FE('rss', 'ARS Technica', 'http://feeds.arstechnica.com/arstechnica/in...
nilq/baby-python
python
class RoomAlreadyEmpty(Exception): pass class CannotAllocateRoom(Exception): pass
nilq/baby-python
python