content
stringlengths
0
1.05M
origin
stringclasses
2 values
type
stringclasses
2 values
#!/usr/bin/env python3 import matplotlib matplotlib.use('agg') import os import sys import yt import matplotlib.pyplot as plt import numpy as np from functools import reduce from mpl_toolkits.axes_grid1 import ImageGrid # assume that our data is in CGS from yt.units import cm, amu from yt.frontends.boxlib.api impor...
nilq/baby-python
python
#!/usr/bin/python3 # This is not really an example but rather some code to test # the behaviour of the pruss interconnect with regard to # concurrent requests to the same local memory. import sys sys.path.insert( 0, '../src' ) from ti.icss import Icss import ctypes pruss = Icss( "/dev/uio/pruss/module" ) pruss.init...
nilq/baby-python
python
#!/usr/bin/env python import os from django.contrib.auth.management.commands import createsuperuser from django.core.management import CommandError class Command(createsuperuser.Command): help = 'Create a superuser' def handle(self, *args, **options): password = os.getenv('db_pass') username ...
nilq/baby-python
python
class Solution: def XXX(self, l1: ListNode, l2: ListNode) -> ListNode: out = l1 carry = 0 lv = l2.val while True: val = l1.val + lv l1.val = val % 10 lv = val > 9 # carry if l1.next: if l2.nex...
nilq/baby-python
python
# -*- coding: utf-8 -*- """ The ProductInfo elements. """ from typing import Union import numpy # noinspection PyProtectedMember from ..sicd_elements.base import Serializable, DEFAULT_STRICT, _StringDescriptor, \ _DateTimeDescriptor, _ParametersDescriptor, ParametersCollection, \ _SerializableListDescriptor ...
nilq/baby-python
python
# -*- coding: utf-8 -*- from __future__ import division """ Trains a ResNeXt Model on Cifar10 and Cifar 100. Implementation as defined in: Xie, S., Girshick, R., Dollár, P., Tu, Z., & He, K. (2016). Aggregated residual transformations for deep neural networks. arXiv preprint arXiv:1611.05431. """ __author__ = "P...
nilq/baby-python
python
from pathlib import Path from os import path from enum import Enum import numbers from collections.abc import Iterable import io import base64 from pptx import Presentation from pptx.enum.chart import XL_CHART_TYPE, XL_LEGEND_POSITION from pptx.chart.data import CategoryChartData, XyChartData, BubbleChartData from ppt...
nilq/baby-python
python
# Generated by Django 2.0.7 on 2018-08-06 11:36 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('principal', '0004_tienda_uuid'), ] operations = [ migrations.AddField( model_name='ciudad', name='url_pagina', ...
nilq/baby-python
python
import warnings from contextlib import contextmanager from veros import runtime_settings, runtime_state, veros_kernel class Index: __slots__ = () @staticmethod def __getitem__(key): return key def noop(*args, **kwargs): pass @contextmanager def make_writeable(*arrs): orig_writeable =...
nilq/baby-python
python
# coding: utf-8 import logging from typing import Dict, List, Iterable from overrides import overrides from allennlp.common import Params from allennlp.common.checks import ConfigurationError from allennlp.common.file_utils import cached_path from allennlp.data.dataset_readers.dataset_reader import DatasetReader fro...
nilq/baby-python
python
from Core.GlobalExceptions import Exceptions from Services.NetworkRequests import requests from Services.Utils.Utils import Utils from Download.Downloader.Engine.Config import Config from Download.Downloader.Task.PrioritizedTask import PrioritizedTask class SegmentDownloader(PrioritizedTask): def __init__(self, u...
nilq/baby-python
python
import json from optimism.JaxConfig import * from optimism import Mesh def read_json_mesh(meshFileName): with open(meshFileName, 'r', encoding='utf-8') as jsonFile: meshData = json.load(jsonFile) coordinates = np.array(meshData['coordinates']) connectivity = np.array(meshData['connectivi...
nilq/baby-python
python
#Benjamin Ramirez August 9, 2016 #making class to keep track of encoder ticks on wheels import RPi.GPIO as GPIO class Encoder(object): def __init__ (self, a_pin_num, b_pin_num): self.a_pin = a_pin_num self.b_pin = b_pin_num GPIO.setmode(GPIO.BCM) GPIO.setup(s...
nilq/baby-python
python
from flask_wtf import FlaskForm from wtforms import IntegerField, SelectField, SelectMultipleField, SubmitField, \ StringField from wtforms.validators import DataRequired, Optional, NumberRange class Search(FlaskForm): min_age = IntegerField('From-years', validators=[Optional(), NumberRange(0, 1000, 'Too big ...
nilq/baby-python
python
# SPDX-FileCopyrightText: 2022 Stephan Lachnit <stephanlachnit@debian.org> # # SPDX-License-Identifier: EUPL-1.2 """ This module contains tools to manipulate DEP5 documents. """ from .classes import DEP5Document, DEP5FilesParagraph, DEP5HeaderParagraph, DEP5LicenseParagraph, DEP5Metadata from .convert_calir import c...
nilq/baby-python
python
from rest_framework.exceptions import NotFound, PermissionDenied from users.models import User, Role from events.models import Event from events.logic.event import get_events def check_user_event_same_organization(view_method): def _arguments_wrapper( instance, request, requester: User, event_id: int, *a...
nilq/baby-python
python
from taskplus.core.actions import ListTasksRequest def test_list_tasks_request_without_parameters(): request = ListTasksRequest() assert request.is_valid() is True assert request.filters is None def test_list_tasks_request_with_filters(): filters = dict(name='task') request = ListTasksRequest(fi...
nilq/baby-python
python
from flask import Flask, redirect, url_for, render_template, current_app from api import Refran app = Flask(__name__) @app.route('/') def home(): refran = Refran() return render_template('index.html', linea=refran.generate_refran()) if __name__ == '__main__': app.run(debug=True)
nilq/baby-python
python
import subprocess from common.mapr_logger.log import Log class OSCommand(object): @staticmethod def run(statements): response, status = OSCommand.run2(statements) return response @staticmethod def run3(statements, username=None, use_nohup=False, out_file=None, in_background=False, us...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ ObsPy implementation for parsing the sc3ml format to an Inventory object. This is a modified version of obspy.io.stationxml. :author: Mathijs Koymans (koymans@knmi.nl), 11.2015 - [Jollyfant@GitHub] :copyright: The ObsPy Development Team (devs@obspy.org) :licen...
nilq/baby-python
python
""" Code taken from: https://uvadlc-notebooks.readthedocs.io/en/latest/tutorial_notebooks/tutorial11/NF_image_modeling.html#Normalizing-Flows-as-generative-model https://github.com/didriknielsen/survae_flows/blob/master/survae/transforms/surjections/slice.py """ from typing import Iterable, List from FrEIA.modu...
nilq/baby-python
python
# -*- coding: utf-8 -*- """ Created on Mon Sep 13 12:39:40 2021 @author: Clau Paper: Energy sufficiency (SDEWES LA 2022) User: Public lighting - LOWLANDS """ from core import User, np User_list = [] #Definig users PL = User("Public lighting ", 1) User_list.append(PL) #Appliances PL_lamp_post = PL.Appliance(PL,1...
nilq/baby-python
python
#!/usr/bin/env python # coding: utf-8 # In[1]: import numpy as np import pandas as pd import matplotlib.pyplot as plt df_train = pd.read_csv('train.csv') country = df_train['Country/Region'] country_set = list(set(country)) country_set = sorted(country_set) province = df_train['Province/State'] for i in range(len...
nilq/baby-python
python
#!/usr/bin/env python3 import Bio from Bio.Seq import Seq my_seq = Seq("ATGAGTACACTAGGGTAA") print(my_seq) rc = my_seq.reverse_complement() pep = my_seq.translate() print("revcom is", rc) print("re-revcom is", rc.reverse_complement()) print(pep)
nilq/baby-python
python
import loadgenome as lg import parse as prs import makepdf as mpdf import sys, getopt #print lg.loadgen("sample genomes/23andme_sample.txt") # def main(argv): input_file = '' output_file = '' usage = 'Usage: python main.py -i <input_file> -o <output_file>' try: opts, args = getopt.getopt(argv,...
nilq/baby-python
python
import cv2 import numpy as np import os from glob import glob #imagefiles = sorted(glob('./inputs/*.jpg')) imagefiles = glob('./inputs/*.jpg') images = [] for filename in imagefiles: img = cv2.imread(filename) images.append(img) stitcher = cv2.Stitcher.create() _, res = stitcher.stitch(images) cv2.imshow('Panor...
nilq/baby-python
python
import streamlit as st import time from helpers import * from streamlit.script_runner import RerunException @st.cache(suppress_st_warning=True) # 👈 Changed this def expensive_computation(a, b): # 👇 Added this st.write("Cache miss: expensive_computation(", a, ",", b, ") ran") time.sleep(2) # This makes...
nilq/baby-python
python
{ "targets": [ { "target_name": "equihashverify", "dependencies": [ ], "sources": [ "src/blake/blake2-config.h", "src/blake/blake2-impl.h", "src/blake/blake2-round.h", "src/blake/blake2....
nilq/baby-python
python
#Load libraries. import pandas as pd import numpy as np from sklearn.decomposition import PCA from sklearn.metrics.cluster import adjusted_rand_score import phenograph import matplotlib.pyplot as plt from pylab import * #Write function. #Accept a dictionary of normalized matrices where the keys are downsample lev...
nilq/baby-python
python
# # RegistrationManager.py # # (c) 2020 by Andreas Kraft # License: BSD 3-Clause License. See the LICENSE file for further details. # # Managing resource / AE registrations # from Logging import Logging from typing import Tuple, List from Constants import Constants as C from Configuration import Configuration from res...
nilq/baby-python
python
#!/bin/python3 import sys t = int(input().strip()) for a0 in range(t): n, k = input().strip().split(' ') n, k = [int(n),int(k)] a = [int(a_temp) for a_temp in input().strip().split(' ')] arrived_on_time = 0 for student_arrival in a: if student_arrival <= 0: ...
nilq/baby-python
python
"""Tests for clover.data_ingest.parsing.parsers.table_structures""" # pylint: disable=too-many-lines import copy import pytest import sqlalchemy as sa import sqlalchemy.dialects.postgresql as sa_pg import sqlalchemy.sql.elements as sa_elements import sqlalchemy.sql.functions as sa_func from yalchemy import table_stru...
nilq/baby-python
python
import torch try: import torch_kdtree # if built with setuptools except: import os, sys; sys.path.append(os.path.join(os.path.dirname(__file__), "../../build")) # if built with cmake import torch_kdtree from torch_cluster import radius from scipy.spatial import cKDTree from time import time import numpy as ...
nilq/baby-python
python
from abc import ABCMeta, abstractmethod class AlgebraicClass(metaclass=ABCMeta): """ Esta clase agrega estructura de algebra de frobenius a las clases """ @abstractmethod def __repr__(self): """ Este metodo permite que se pueda mostrar una clase en pantalla """...
nilq/baby-python
python
from __future__ import print_function, absolute_import import argparse import os.path as osp import random import numpy as np import sys import time import shutil import h5py from tqdm import tqdm import torch from torch import nn from torch.backends import cudnn from torch.utils.data import DataLoader import torch.di...
nilq/baby-python
python
# Copyright 2017-present Open Networking Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
nilq/baby-python
python
import json import requests from .config import BASE_URL, GIST_URL class Do: def __init__(self, gist): self.gist = gist def getMyID(self,gist_name): ''' Getting gistID of a gist in order to make the workflow easy and uninterrupted. ''' r = requests.get( '%s'%BASE_URL+'/users/%s/gists' % self.gist.use...
nilq/baby-python
python
text = """ Alice was beginning to get very tired of sitting by her sister on the bank, and of having nothing to do: once or twice she had peeped into the book her sister was reading, but it had no pictures or conversations in it, "and what is the use of a book," thought Alice "without pictures or conversations?" So she...
nilq/baby-python
python
import unittest from omniglot.omni import OmnilingualProcessor from omnilingual import LanguageCode class TestOmni(unittest.TestCase): def setUp(self): self.omni = OmnilingualProcessor(None) self.maxDiff = None if __name__ == "__main__": unittest.main()
nilq/baby-python
python
import pytest import os import time import socket from urllib.parse import urlparse def is_port_open(hostname, port): return socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect_ex((hostname, port)) == 0 @pytest.fixture(scope="session") def ENDPOINT(): return os.environ.get('URI_SERVER', 'http://local...
nilq/baby-python
python
# Generated by Django 3.0.1 on 2019-12-25 21:42 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Circle', fields=[ ('id', models.AutoField(a...
nilq/baby-python
python
# Copyright The PyTorch Lightning team. # # 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 i...
nilq/baby-python
python
import asyncio import logging import signal import socketio import urllib _API_V2_NAMESPACE = '/api/v2/socket_io' _RECONNECT_ATTEMPTS = 1 # We most commonly get disconnected when the session # expires, so we don't want to try many times _LOGGER = logging.getLogger(__name__) class SmartboxAPIV2Namespace(socketio.As...
nilq/baby-python
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright 2021 4Paradigm # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required ...
nilq/baby-python
python
#! /usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals, absolute_import, division, print_function import re import logging import time import os import sys currentdir = os.path.dirname(os.path.realpath(__file__)) parentdir = os.path.dirname(currentdir) sys.path.append(parentdir) from...
nilq/baby-python
python
# Misc comptrollerAddress = "0xAB1c342C7bf5Ec5F02ADEA1c2270670bCa144CbB" curveAddressProvider = "0x0000000022D53366457F9d5E68Ec105046FC4383" ethZapAddress = "0x5A0bade607eaca65A0FE6d1437E0e3EC2144d540" eurt_namehash = "0xd5aa869323f85cb893514ce48950ba7e84a8d0bf062a7e3058bcc494217da39f" masterChefAddress = "0xbD17B1ce62...
nilq/baby-python
python
# GENERATED BY KOMAND SDK - DO NOT EDIT import komand import json class Input: HASH = "hash" class Output: FOUND = "found" REPORTS = "reports" THREATSCORE = "threatscore" class LookupHashInput(komand.Input): schema = json.loads(""" { "type": "object", "title": "Variables", "pr...
nilq/baby-python
python
""" Created: 2001/08/05 Purpose: Turn components into a sub-package __version__ = "$Revision: 1.1 $" __date__ = "$Date: 2001/12/11 23:47:11 $" """
nilq/baby-python
python
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. from __future__ import absolute_import, division, print_function, unicode_literals BOOTSTRAP_XAR = "bootstrap_xar....
nilq/baby-python
python
# Copyright (c) 2018 FlashX, LLC # # 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, distrib...
nilq/baby-python
python
import json import logging from pathlib import Path from typing import Any, Iterable, List, Set, Union import numpy as np import pandas as pd from hyperstyle.src.python.review.application_config import LanguageVersion from hyperstyle.src.python.review.common.file_system import Extension from hyperstyle.src.python.revi...
nilq/baby-python
python
""" Extract functions for space time raster, 3d raster and vector datasets (C) 2012-2013 by the GRASS Development Team This program is free software under the GNU General Public License (>=v2). Read the file COPYING that comes with GRASS for details. :authors: Soeren Gebbert """ from .core import get_tgis_message_int...
nilq/baby-python
python
import FWCore.ParameterSet.Config as cms enableSonicTriton = cms.Modifier()
nilq/baby-python
python
# PLY package # Author: David Beazley (dave@dabeaz.com) # https://dabeaz.com/ply/index.html __version__ = '4.0' __all__ = ['lex','yacc']
nilq/baby-python
python
import hvac import os client = hvac.Client(url='https://localhost:8200', verify=False) # use false for testing only (self signed cert on dev machine) client.token = os.environ['VAULT_TOKEN'] secret = client.secrets.kv.v2.read_secret_version(mount_point="apikeys_prod", path='keys') # https://hvac.readthedocs.io/en/stab...
nilq/baby-python
python
from selenium import webdriver import time import arrow from datetime import datetime from bs4 import BeautifulSoup import threading from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.keys import Keys import os ''' Created on 13 Sep 2013 Updated 12 Nov 2017 @author: rob dobson ''' ...
nilq/baby-python
python
import argparse import logging MEDIUM_CHOICES = ["CD", "SACD", "DVD", "DVD-A", "Blu-ray", "Web", "Vinyl", "78RPM Vinyl", "LP", "Vinyl LP", "45RPM Vinyl LP", "EP", "Vinyl EP", "45RPM Vinyl EP", "180g Vinyl LP", "180g 45RPM Vinyl L...
nilq/baby-python
python
""" ===================================== Hawkes simulation with exotic kernels ===================================== Simulation of Hawkes processes with usage of custom kernels """ import matplotlib.pyplot as plt import numpy as np from tick.base import TimeFunction from tick.hawkes import SimuHawkes, HawkesKernelE...
nilq/baby-python
python
#!/usr/bin/env python3 import subprocess import os from libsw import file_filter, settings, build_queue, build_index, logger def register_ip(ip): path = settings.get('install_path') + 'etc/remote-deploy' return file_filter.AppendUnique(path, ip, True).run() def unregister_ip(ip): path = settings.get('i...
nilq/baby-python
python
# Copyright 2020 The FastEstimator 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 appl...
nilq/baby-python
python
import sys from itertools import product import intake def all_params(): all_params = {} cat = intake.open_catalog('catalog.yaml') for item in cat: description = cat[item].describe() params = description["user_parameters"] params = {params[i]["name"]: params[i]["allowed"] for i ...
nilq/baby-python
python
from logging import error, info, basicConfig, getLogger, warning from os import environ as env from gitlabdata.orchestration_utils import ( postgres_engine_factory, snowflake_engine_factory, query_executor, ) from google_sheets_client import GoogleSheetsClient from qualtrics_client import QualtricsClient f...
nilq/baby-python
python
# Interactive Help '''digitando help() no console python Ou help(print) ou print(input.__doc__)''' # Docstrings '''def contador(i, f, p): """==> Faz uma contagem e mostra na tela. :param i: início da contagem :param f: fim da contagem :param p: passo da contagem :return: sem retorn...
nilq/baby-python
python
from .sql import SQL from .sac import SAC from .drsac import DRSAC
nilq/baby-python
python
import jaxopt import numpy as np import pandas as pd import tinygp import jax import jax.numpy as jnp from io import StringIO import matplotlib.pyplot as plt from plotting import * import pickle from jax.config import config config.update("jax_enable_x64", True) bands = 'ugrizY' N_bands = len(bands) class Multiband(...
nilq/baby-python
python
# A function can return only one value. # # If the value is a tuple ... # the effect is the same as returning multiple values. # Quontient & Reminder: # # To compute the quontient and reminders it is better to ... # compute both at the same time. quot = 7//3 rem = 7%3 assert (quot, rem) == (2, 1) quot, rem = divmod...
nilq/baby-python
python
from llvmlite.ir import IdentifiedStructType from rial.ir.metadata.StructDefinition import StructDefinition class RIALIdentifiedStructType(IdentifiedStructType): definition: StructDefinition module_name: str def __init__(self, context, name, packed=False): super().__init__(context, name, packed)...
nilq/baby-python
python
# -*- coding: cp1254 -*- #if external software is used for Analysis (Excel,Weka, R. etc) #This script Convert excel file to raster (susceptibility map) and calculate ROC #The excel file must be include x and y coordinates and Probability values as z #To calculate AUC test and train data required. They were calculated w...
nilq/baby-python
python
objConstructors = {'dyn_vals.get' : {'constructor' : 'DynamicValuec', 'type' : 'DynamicValuei', 'fields' : ['bucket_size', 'bucket_time']}} typeConstructors = {'DynamicValuec' : 'DynamicValuei'} stateObjects = {'flow_emap' : emap, ...
nilq/baby-python
python
""" This is CoLA Bot code that uses slurk interface. CoLA bot handles the dialogue between two players who need to collaborate togther to solve a task. In each game room, we show the players - images, text information, logical rules. They need to discuss together and reach an agreement. So, the two important comm...
nilq/baby-python
python
from pykitml.testing import pktest_graph, pktest_nograph @pktest_graph def test_adult(): import os.path import numpy as np import pykitml as pk from pykitml.datasets import adult # Download the dataset if(not os.path.exists('adult.data.pkl')): adult.get() # Load adult data set input...
nilq/baby-python
python
#!/usr/bin/env python # encoding: utf-8 class OsfStorageError(Exception): pass class PathLockedError(OsfStorageError): pass class SignatureConsumedError(OsfStorageError): pass class VersionNotFoundError(OsfStorageError): pass class SignatureMismatchError(OsfStorageError): pass class VersionSta...
nilq/baby-python
python
""" Suggest types for untyped code. """ import ast from collections import defaultdict from dataclasses import dataclass, field from types import FunctionType from typing import Any, Dict, Iterator, List, Mapping, Optional, Sequence, Tuple, Union from .safe import safe_getattr, safe_isinstance from .error_code impor...
nilq/baby-python
python
from __future__ import division import casadi as ca from planner import Planner __author__ = 'belousov' class Simulator: # ======================================================================== # True noisy trajectory # =======================================================...
nilq/baby-python
python
import os from .login import * from .action import * from .box import * os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'
nilq/baby-python
python
"""Created by Alysha Kester-Terry 3/12/2021 for GoodRx This file is to set up the driver for a specific site. We want to make this scalable in case there could be multiple environments or web UI URLs we may want to hit. """ import logging def get_app_url(App, environment='test'): """To define the search engine URL by...
nilq/baby-python
python
# Copyright 2019 Contributors to Hyperledger Sawtooth # # 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 ...
nilq/baby-python
python
############################################## # sudo apt-get install -y python3-picamera # sudo -H pip3 install imutils --upgrade ############################################## import multiprocessing as mp import sys from time import sleep import argparse import cv2 import numpy as np import time try: from armv...
nilq/baby-python
python
from argparse import ArgumentParser from os import rename, walk from os.path import join, splitext PLACEHOLDER_VARIABLE = 'base-angular-app' PLACEHOLDER_TITLE = 'Base Angular App' PLACEHOLDER_OWNER = 'BaseAngularAppAuthors' EXCLUDED_DIRECTORIES = ['.git', '.idea', 'node_modules'] EXCLUDED_FILES = ['replacer....
nilq/baby-python
python
import os import datetime import json from officy import JsonFile, Dir, File, Stime from rumpy import RumClient father_dir = os.path.dirname(os.path.dirname(__file__)) seedsfile = os.path.join(father_dir, "data", "seeds.json") infofile = os.path.join(father_dir, "data", "groupsinfo.json") FLAG_JOINGROUPS = True PORT ...
nilq/baby-python
python
from gquant.dataframe_flow import Node from gquant.dataframe_flow._port_type_node import _PortTypesMixin from gquant.dataframe_flow.portsSpecSchema import ConfSchema class DropNode(Node, _PortTypesMixin): def init(self): _PortTypesMixin.init(self) cols_required = {} self.required = { ...
nilq/baby-python
python
# todo: strict version class Accessor: def split_key(self, k, *, sep="/"): return [normalize_json_pointer(x) for x in k.lstrip(sep).split(sep)] def split_key_pair(self, k, *, sep="@"): if sep not in k: return self.split_key(k), [] else: access_keys, build_keys = ...
nilq/baby-python
python
#!/usr/bin/env python3 from os import listdir from os.path import isdir, isfile, join def get_focus(day): day = int(day.split(" ")[1].split(":")[0]) if day == 1: return "Chest" elif day == 2: return "Quads" elif day == 3: return "Back" elif day == 4: ret...
nilq/baby-python
python
import numpy as np import matplotlib.pyplot as plt import seaborn as sns import pandas as pd from scipy import interpolate import torch import tqdm from neural_clbf.controllers import NeuralObsBFController, ObsMPCController from neural_clbf.experiments import ( RolloutSuccessRateExperiment, ExperimentSuite, ...
nilq/baby-python
python
import pandas as pd from pdia.extendedInfoParser.parseExtendedInfo import errorCode def parseCalculatorEvents(eInfo): """Parse a calculator event string, return parsed object or None """ assert (isinstance(eInfo, pd.Series)) try: res = eInfo.apply(lambda x: {"Calculator": x}) except: ...
nilq/baby-python
python
import csv import datetime as dt import hashlib import io import re from decimal import Decimal from django.utils.dateparse import parse_date from django.utils.encoding import force_str from django.utils.text import slugify def parse_zkb_csv(data): f = io.StringIO() f.write(force_str(data, encoding="utf-8", ...
nilq/baby-python
python
import time import pygame from pygame.locals import K_ESCAPE, K_SPACE, QUIT, USEREVENT COUNTDOWN_DELAY = 4 def timerFunc(countdown, background): print("Timer CallBack", time.time()) print(countdown) print("--") # Display some text font = pygame.font.Font(None, 36) text = font.render(str(cou...
nilq/baby-python
python
#!/usr/bin/env python # coding=utf-8 import re import time import string from urlparse import urlparse from comm.request import Req from conf.settings import DICT_PATH from core.data import result from core.data import fuzz_urls from Queue import Empty class FuzzFileScan(Req): def __init__(self, site, timeout, d...
nilq/baby-python
python
from gql.schema import make_schema_from_path from pathlib import Path def test_make_schema_from_path(): schema = make_schema_from_path(str(Path(__file__).parent / 'schema')) assert set(schema.query_type.fields.keys()) == {'me', 'addresses'} assert set(schema.mutation_type.fields.keys()) == {'createAddres...
nilq/baby-python
python
# -*- coding: utf8 -*- import requests, json, time, os requests.packages.urllib3.disable_warnings() cookie = os.environ.get("cookie_smzdm") def main(*arg): try: msg = "" SCKEY = os.environ.get('SCKEY') s = requests.Session() s.headers.update({'User-Agent':'Mozilla/5.0 (Windows NT...
nilq/baby-python
python
from setuptools import setup with open("README.md", "r", encoding="utf-8") as fh: long_description = fh.read() setup( name="streambook", author="Alexander Rush", author_email="arush@cornell.edu", version="0.1.2", packages=["streambook"], long_description=long_description, long_descript...
nilq/baby-python
python
class WebserialError(Exception): pass class EqualChapterError(WebserialError): pass class NoChaptersFoundError(WebserialError): pass class LocalAheadOfRemoteError(WebserialError): pass
nilq/baby-python
python
""" Lambdas AS known as expression lambda or lambdas. Function anonymous # FUnction Python def sum(a, b): return a + b def function(x): return 3 * x + 1 print(function(4)) # 13 print(function(7)) # 22 # Expression lambda lambda x: 3 * x + 1 # How can I use expression lambda? calculation = lambda x: 3...
nilq/baby-python
python
from userbot.utils import admin_cmd from telethon.tl.functions.users import GetFullUserRequest import asyncio @borg.on(admin_cmd(pattern="pmto ?(.*)")) async def pmto(event): if event.reply_to_msg_id: reply_message = await event.get_reply_message() chat_id=await event.client(GetFullUserRe...
nilq/baby-python
python
import asyncio import sys import os project_root = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../..')) sys.path.insert(0, project_root) from ahk import AHK, AsyncAHK from unittest import TestCase, IsolatedAsyncioTestCase from PIL import Image from itertools import product import time cl...
nilq/baby-python
python
from django.contrib import admin from certificates.models import ProductionSiteCertificate from certificates.models import DoubleCountingRegistration, DoubleCountingRegistrationInputOutput class ProductionSiteCertificateAdmin(admin.ModelAdmin): list_display = ('production_site', 'get_certificate_type', 'certifica...
nilq/baby-python
python
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
nilq/baby-python
python
"""tipo torneo Revision ID: 016 Revises: 015 Create Date: 2014-05-27 22:50:52.173711 """ # revision identifiers, used by Alembic. revision = '017' down_revision = '016' from alembic import op import sqlalchemy as sa def upgrade(): op.create_table('tipo_torneo', sa.Column('id', sa.Integer, primary_key=...
nilq/baby-python
python
class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def detectCycle(self, head: ListNode) -> ListNode: if head is None or head.next is None: return None slow = head fast = head while fast.next and fast.next.next: ...
nilq/baby-python
python
import logging import subprocess LOG = logging.getLogger(__name__) def run(*cmd, **kwargs): """Log and run a command. Optional kwargs: cwd: current working directory (string) capture: capture stdout and return it (bool) capture_stderr: redirect stderr to stdout and return it (bool) env: env...
nilq/baby-python
python