content
stringlengths
0
1.05M
origin
stringclasses
2 values
type
stringclasses
2 values
import uuid from django.db.models import Model, UUIDField, DateTimeField class TimeStampedModel(Model): # id = UUIDField( # primary_key=True, # default=uuid.uuid4, # editable=False # ) created_at = DateTimeField( auto_now_add=True, verbose_name='Created datetim...
nilq/baby-python
python
import pickle import unittest from typing import Optional import boost_histogram as bh import numpy as np from bootstraphistogram import BootstrapHistogram def _standard_error_mean(size, sigma=1.0): return sigma / np.sqrt(size) def _standard_error_std(size, sigma=1.0): return np.sqrt(sigma ** 2 / (2.0 * s...
nilq/baby-python
python
''' Simple build error dialog, access to logs etc. ''' import os.path import os os.environ['NO_AT_BRIDGE'] = '0' import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk # pylint:disable=no-name-in-module class Handler(object): ''' Implicit signal handlers declared in glade. ''' def...
nilq/baby-python
python
tot18 = 0 totM = 0 tot20 = 0 while True: idade = int(input('idade: ')) sexo =' ' while sexo not in 'MF': sexo = str(input('Escolha o sexo:[M/F]: ')) if idade >= 18: tot18 += 1 if sexo == 'M': totM += 1 if sexo == 'F': tot20 += 1 r = ' ' wh...
nilq/baby-python
python
# coding: utf-8 import uuid def createUUID(): return uuid.uuid4().fields[ 0 ] def createUUIDList( listSize ): ret = [0] * listSize for i in range( listSize ): ret[ i ] = uuid.uuid4().fields[ 0 ] return ret def float2int( v, defaultValue = 0 ): if( isinstance( v, float ) ): ret...
nilq/baby-python
python
# -*- coding: utf-8 -*- # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Time Series Analysis -- Python/NumPy implementation # # Author: Jakob Rørsted Mosumgaard # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ##########################################...
nilq/baby-python
python
# Generated by Django 2.2.13 on 2021-11-17 18:05 from django.db import migrations, models import ic_marathon_app.validators class Migration(migrations.Migration): dependencies = [ ('ic_marathon_app', '0010_auto_20201101_0745'), ] operations = [ migrations.AlterField( model_n...
nilq/baby-python
python
import sys sys.path.insert(0,'../..') import json import requests from tqdm import tqdm from lxml import etree from app import base heroes_url = 'http://heroesjson.com/heroes.json' image_prefix = 'http://us.battle.net/heroes/static' class ChampionImporter(base.ChampionImporter): def get_objects(self): ...
nilq/baby-python
python
import mysql.connector from flask import Flask, request, jsonify, redirect import json from datetime import datetime from furl import furl app = Flask(__name__) mydb = mysql.connector.connect( host="127.0.0.1", #port=3308, #user="python_boi", user="admin", #passwd="qrXEoFtaVXGkuJHT", passwd=""...
nilq/baby-python
python
import sys from time import sleep import pygame from bullet import Bullet from alien import Alien def check_keydown_events(event,ai_settings, screen,ship, bullets): """Responde a pressionamentos de tecla.""" # Move a espaçonave para a direira if event.key == pygame.K_RIGHT: ship.moving_right = Tru...
nilq/baby-python
python
''' gsconfig is a python library for manipulating a GeoServer instance via the GeoServer RESTConfig API. The project is distributed under a MIT License . ''' __author__ = "David Winslow" __copyright__ = "Copyright 2012-2018 Boundless, Copyright 2010-2012 OpenPlans" __license__ = "MIT" from geoserver.support import R...
nilq/baby-python
python
from pandas import * from math import ceil from sklearn.ensemble import GradientBoostingRegressor, VotingRegressor from sklearn.metrics import mean_absolute_error from sklearn.model_selection import train_test_split import numpy as np # Load the data print('Reading the data...') data = read_csv("insurance.csv") print(...
nilq/baby-python
python
import math as math # import random # class Particle (object): # """Paticle module""" # def __init__ (self, mass=1.0, x=0.0, y=0.0, vx=0.0, vy=0.0): # self.mass = mass # self.x = x # self.y = y # self.vx = vx # self.vy = vy # # def __str__ (self): # ...
nilq/baby-python
python
import pytest from spellbot.settings import Settings class TestMigrations: @pytest.mark.nosession def test_alembic(self, settings: Settings): from spellbot.models import create_all, reverse_all create_all(settings.DATABASE_URL) reverse_all(settings.DATABASE_URL)
nilq/baby-python
python
settings = { "aoi":"https://gdh-data.ams3.digitaloceanspaces.com/scarborough.geojson", "systems":["GI", "TRANS", "URBAN", "AG", "HYDRO"], "outputdirectory":"output", "workingdirectory": "working", "sentinelscene": "S2B_MSIL1C_20171126T112359_N0206_R037_T30UXF_20171126T132429", "rivers":"rivers/rivers.shp", "w...
nilq/baby-python
python
# 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, software # distributed under the Li...
nilq/baby-python
python
#!/usr/bin/env python import sys import ast import operator def main(): with open(sys.argv[1]) as infile: for line in infile: topic = ast.literal_eval(line) sorted_x = sorted(topic.items(), key=operator.itemgetter(1), reverse=True) print " ".join([i[0] for i in sorted_x...
nilq/baby-python
python
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.Create...
nilq/baby-python
python
import os from random import shuffle import csv def getGenderDict(): return { 'aia' : ['female',0], 'bonnie' : ['female',0], 'jules' : ['male',1], 'malcolm' : ['male',1], 'mery' : ['female',0], 'ray' : ['male',1] } def getEmotionDict(): return { 'anger' : 0, 'disgust' : 1, 'fear' : 2, 'joy'...
nilq/baby-python
python
# coding: utf-8 #model url: http://nixeneko.2-d.jp/hatenablog/20170724_facedetection_model/snapshot_model.npz import urllib.request import os def download_model(url, dest): destdir = os.path.dirname(dest) if not os.path.exists(destdir): os.makedirs(destdir) print("Downloading {}... \nThis ma...
nilq/baby-python
python
from cartography.driftdetect.model import load_detector_from_json_file from cartography.driftdetect.detect_drift import perform_drift_detection from unittest.mock import MagicMock def test_detector_no_drift(): """ Test that a detector that detects no drift returns none. :return: """ mock_session =...
nilq/baby-python
python
# -*- coding: utf-8 -*- """ deserializer interface module. """ from abc import abstractmethod from threading import Lock from pyrin.core.structs import CoreObject, MultiSingletonMeta from pyrin.core.exceptions import CoreNotImplementedError class DeserializerSingletonMeta(MultiSingletonMeta): """ deserializ...
nilq/baby-python
python
import csv import sys import os import os.path as path from datetime import datetime import math import pandas as pd from utility import Logger as log DEBUG = False def log(message): if DEBUG: print(message) def main(argv): workspace = '' # datasets = { # 'pecanstreet': ['California'...
nilq/baby-python
python
from rqalpha.api import * def init(context): context.S1 = "510500.XSHG" context.UNIT = 10000 context.INIT_S = 2 context.MARGIN = 0.08 context.FIRST_P = 0 context.holdid = 0 context.sellcount = 0 context.inited = False logger.info("RunInfo: {}".format(context.run_info)) def before...
nilq/baby-python
python
#// #//------------------------------------------------------------------------------ #// Copyright 2007-2011 Mentor Graphics Corporation #// Copyright 2007-2011 Cadence Design Systems, Inc. #// Copyright 2010 Synopsys, Inc. #// All Rights Reserved Worldwide #// #// Licensed under the Apache License, Version...
nilq/baby-python
python
def rt(ip): return [10,15,20]
nilq/baby-python
python
from unittest import TestCase from ua_model.utils import validate_branch_point_positions class TestFunctionUtils(TestCase): def test_validate_branch_point_positions(self): with self.subTest(msg='valid parameters'): self.assertIsNone(validate_branch_point_positions(t_0=0.1, t_in=1.0)) ...
nilq/baby-python
python
# -*- coding: utf-8 -*- # Copyright 2018 Nagoya University (Tomoki Hayashi) # Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) """TTS Interface realted modules.""" from espnet.asr.asr_utils import torch_load try: import chainer except ImportError: Reporter = None else: class Reporter(chainer....
nilq/baby-python
python
# Generated by Django 2.2.5 on 2019-09-09 17:38 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('product', '00...
nilq/baby-python
python
#!/usr/bin/env python3 from data_stack.dataset.factory import BaseDatasetFactory from data_stack.dataset.iterator import DatasetIteratorIF from data_stack.dataset.meta import MetaFactory from outlier_hub.datasets.toy_datasets.uniform_noise.iterator import UniformNoiseIterator from typing import List, Tuple, Dict, Any ...
nilq/baby-python
python
n = int(input()) // 4 print(n * n)
nilq/baby-python
python
import pandas as pd import numpy as np from web_constants import * from signatures import Signatures, get_signatures_by_mut_type from project_data import ProjectData, get_selected_project_data from compute_reconstruction import compute_reconstruction from scale_samples import scale_samples def plot_reconstruction(ch...
nilq/baby-python
python
# # PySNMP MIB module ADTRAN-IF-PERF-HISTORY-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ADTRAN-IF-PERF-HISTORY-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 16:59:29 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version ...
nilq/baby-python
python
from collections import OrderedDict import gin import matplotlib.cm as cm import numpy as np import pandas as pd import plotly.graph_objs as go import seaborn as sns import torch from graphviz import Digraph from matplotlib import pyplot as plt from sklearn.cluster import KMeans from sklearn.decomposition import PCA i...
nilq/baby-python
python
#!/usr/bin/env python3 # coding: utf-8 from zencad import * def section(w, h, l, t, d, d2): return ( box(2 * t + w, t + l, 2 * t + h) - box(w, l, h).translate(t, 0, t) - box(w - 2 * d, l, h + 2 * t).translate(t + d, 0, 0) - box(w, l + t, h - d2).translate(t, 0, d2 + t) ) # n...
nilq/baby-python
python
import uuid import time import hashlib import json def get_event_metadata(): return { "run_id": str(uuid.uuid1()), "event_id": str(uuid.uuid4()) } # python does some pretty pretting to json objects, we have to change the # separators to have a bare bone stringifying/dumping function, which wi...
nilq/baby-python
python
"""Tables Utilities""" import logging from typing import Dict import numpy as np import tensorflow as tf from deepr.utils.field import TensorType LOGGER = logging.getLogger(__name__) class TableContext: """Context Manager to reuse Tensorflow tables. Tensorflow does not have a ``tf.get_variable`` equival...
nilq/baby-python
python
#!/usr/bin/env python from nbformat import v3, v4 import os import sys with open(sys.argv[1]) as f: text = f.read() nb = v3.reads_py(text) nb = v4.upgrade(nb) with open(os.path.splitext(sys.argv[1])[0] + ".ipynb", "w") as f: f.write(v4.writes(nb))
nilq/baby-python
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from typing import List import functools from .plot_manager import plot_manager class Plot: """ Plotting function wrapper. """ def __init__(self, name, data_requirements: List, func): self.plot_func = func self.data_requirements = data_r...
nilq/baby-python
python
from django.shortcuts import render from branca.element import MacroElement from jinja2 import Template # generic base view from django.views.generic import TemplateView #folium import folium import geojson from folium import plugins import pandas as pd from folium.plugins import MarkerCluster # import ee # fr...
nilq/baby-python
python
from operator import attrgetter from typing import Set import pandas as pd from investmentstk.models.bar import Bar BarSet = Set[Bar] def barset_from_csv_string(csv_string: str) -> BarSet: """ Expected format: date,open,high,low,close without headers """ barset = set() rows = csv_stri...
nilq/baby-python
python
import re from typing import Optional from pydantic import BaseModel, validator class InputQuery(BaseModel): dataStructureName: str version: str population: Optional[list] include_attributes: Optional[bool] = False @validator('version') def check_for_sem_ver(cls, version): pattern = ...
nilq/baby-python
python
from django.db import models class ResourceGroupTextAttributeDefinition(models.Model): class Meta: unique_together = ('name', 'resource_group',) name = models.CharField(max_length=100, blank=False) resource_group = models.ForeignKey('ResourceGroup', ...
nilq/baby-python
python
from pathlib import Path from tempfile import TemporaryDirectory import json import os import unittest from moto import mock_s3 from schematics.exceptions import DataError import boto3 as boto from hidebound.exporters.s3_exporter import S3Config, S3Exporter # ----------------------------------------------------------...
nilq/baby-python
python
#!/usr/bin/python ##------------------------------------------------------------------- ## @copyright 2017 DennyZhang.com ## Licensed under MIT ## https://www.dennyzhang.com/wp-content/mit_license.txt ## ## File : refresh_containers.py ## Author : Denny <contact@dennyzhang.com> ## Description : Restart a list of dock...
nilq/baby-python
python
from barcode import Code128 from svgwrite import cm, mm, px import svgwrite Drawing = svgwrite.Drawing class Size(): def __init__(self, w, h, unit='px'): self.width = w self.height = h self.unit = unit def getS(self, float_precision=2): """String Size -> width[unit], height[uni...
nilq/baby-python
python
""" Simple driver for Monarch GO AT modemcontrol commands """ from time import sleep from logging import getLogger from ..provisioner import ProvisionerError ASCII_EOT = b'\x04' class AtDriver(): """ Low-level AT modem command driver. """ def __init__(self, fwinterface): """ Connstr...
nilq/baby-python
python
import abc import filecmp import inspect import os import shutil from ctranslate2.specs import catalog from ctranslate2.specs.model_spec import ModelSpec def _list_specs(): return { symbol: getattr(catalog, symbol) for symbol in dir(catalog) if inspect.isclass(getattr(catalog, symbol)) an...
nilq/baby-python
python
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render def base(request): return render(request, 'base.html', {}) def report(request): context = {'title': '报表平台'} return render(request, 'reports/report.html', context) def histogram(request): """柱状图""" ...
nilq/baby-python
python
#!/usr/bin/python hostname = 'localhost' username = 'root' password = '' database = 'pythonconn' # Simple routine to run a query on a database and print the results: def doQuery( conn ) : cur = conn.cursor() ''' first='Shreyas' last='Patil' user='Flamestriker' passw='12345' ''' # cur.ex...
nilq/baby-python
python
# Processando uma resposta de API import requests # Faz uma chamada de API e armazena a resposta url = 'https://api.github.com/search/repositories?\ q=language:python&sorts=stars' r = requests.get(url) print('Status code:', r.status_code) # Armazena a resposta da API em uma variável response_dict = r.json() print('T...
nilq/baby-python
python
import json, os import copy class sesh: def __init__(self, sessionUUID, TotalEvents, VersionControlEvents, EditEvents, CommandEvents, DocumentEvents, ActivityEvents, NavigationEvents, TestRunEvents, WindowEvents, CompletionEvents, SystemEvents, DebuggerEvents, SolutionEvents, IDEStateEvents, UndefinedEvents): ...
nilq/baby-python
python
# -*- coding: utf-8 -*- # Copyright (c) 2017, masonarmani38@gmail.com and Contributors # See license.txt from __future__ import unicode_literals import frappe import unittest class TestProductionWaste(unittest.TestCase): pass def tear_down(): filters =dict({ "from" : "01-09-2017 17:49:55", "to":"01-12-2017 17...
nilq/baby-python
python
import os import time import torch from options.test_options_CMU import TestOptions from torch.autograd import Variable import numpy as np from PIL import Image from torch.utils.data import DataLoader # from utils.label2Img import label2rgb from dataloader.transform import Transform_test from dataloader.dataset import ...
nilq/baby-python
python
#!/usr/bin/env python import os import smtplib import mimetypes import argparse from email.mime.multipart import MIMEMultipart from email import encoders from email.message import Message from email.mime.audio import MIMEAudio from email.mime.base import MIMEBase from email.mime.image import MIMEImage from email.mime....
nilq/baby-python
python
# flake8: noqa from .gs_counterfactuals import growing_spheres_search
nilq/baby-python
python
import logging import random import numpy as np connect_success = True logger = logging.getLogger(__name__) set_l3t_count = 0 clear_l3t_count = 0 def connect(ami_str): logger.debug('simulated pyami connect') if not connect_success: raise RuntimeError('simulated fail') else: Entry._conne...
nilq/baby-python
python
# -*- coding: utf-8 -*- # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type import pytest import os.path from getpass import getuser from os import remove, rmdir from socket import gethostn...
nilq/baby-python
python
# Copyright (c) 2015, VMRaid Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals def execute(): from vmraid.installer import remove_from_installed_apps remove_from_installed_apps("shopping_cart")
nilq/baby-python
python
__license__ = 'MIT License <http://www.opensource.org/licenses/mit-license.php>' __author__ = 'Lucas Theis <lucas@theis.io>' __docformat__ = 'epytext' from django.db import models from publications.models.orderedmodel import OrderedModel from string import replace, split, strip class Type(OrderedModel): class Meta: ...
nilq/baby-python
python
import keras # noqa: F401 import numpy as np import tensorflow as tf import wandb from wandb.keras import WandbCallback def main(): wandb.init(name=__file__) model = tf.keras.models.Sequential() model.add(tf.keras.layers.Conv2D(3, 3, activation="relu", input_shape=(28, 28, 1))) model.add(tf.keras.la...
nilq/baby-python
python
class NotImplemented(Exception): def __init__(self, *args, **kwargs): Exception.__init__(self, args, kwargs) class NoSuchVirtualMachine(Exception): def __init__(self, *args, **kwargs): Exception.__init__(self, args, kwargs) class InvalidOperation(Exception): def __init__(self, *args, **kw...
nilq/baby-python
python
from .wide_resnet50 import WideResNet50 __all__ = ["WideResNet50"]
nilq/baby-python
python
# -*- coding: utf-8 -*- """ Created on Mon Mar 28 16:35:56 2022 @author: Pedro """ def score(mode: str, puntosp1: int, puntosp2: int, name1: str, name2: str, puntajes: tuple, auto_ch: str)->str: """Funcion que simula un game de Tenis, ya sea de forma manual, es decir con intervencion del usuario en los puntos...
nilq/baby-python
python
import json import sys class PolicyResolver(): def __init__(self): self.desc = [] self.desc_by_label = {} def read_json(self, fname): ''' reads the JSON produced by the cle preprocessor ''' with open(fname) as f: fs = f.read() desc1 = jso...
nilq/baby-python
python
""" Unit tests: testing a small bit of code like function or class in isolation of the system From the developers perspective """ import mimetypes import os from pathlib import Path import cv2 import pytest from ..colordetect import ColorDetect, VideoColor, col_share def test_image_vid_parsed_to_class(image, video...
nilq/baby-python
python
""" Main application """ import logging from aiohttp import web from .db import setup_db from .rest import setup_rest, create_router from .session import setup_session from .settings import CONFIG_KEY log = logging.getLogger(__name__) def create(config): """ Initializes service """ log.debug("I...
nilq/baby-python
python
import sys import os def find_directories(directory): for dirpath, dirs, files in os.walk(str(directory)): for dr in dirs: print(dr) if __name__ == '__main__': find_directories(sys.argv[1])
nilq/baby-python
python
''' Programa para jugar al tateti Valentin Berman 13/02/20 ''' # Constantes NADA = '-' X = 'x' O = 'o' MOV = 'hay movimientos' GANA_X = 1 GANA_O = -1 EMPATE = 0 MAX = 'max' # el jugador con X es el MAX MIN = 'min' # el jugador con O es el MIN # Clases class Tateti(): ''' Clase que define un tablero de tateti ...
nilq/baby-python
python
# coding: utf-8 from enum import Enum from six import string_types, iteritems from bitmovin_api_sdk.common.poscheck import poscheck_model class PositionUnit(Enum): PIXELS = "PIXELS" PERCENTS = "PERCENTS"
nilq/baby-python
python
from ares.Lib import Ares """ GENERAL PURPOSE --------------- This script will aim to show how to store data into a database - nothing more Finally database_connection_2.py will show a simple example of data extraction using the AReS connectors capabilities (see the scripts example connectors.py for more info),do s...
nilq/baby-python
python
import numpy as np from boid import Boid width = 100 height = 100 flock = [Boid(*np.random.rand(2)*100, width, height) for _ in range(5)] def updatePositions(): global flock for boid in flock: boid.apply_behaviour(flock) boid.update() boid.edges() print("-----FRAME 1-----") updatePos...
nilq/baby-python
python
__version__ = "0.0.1" version = __version__
nilq/baby-python
python
import pytest from django.contrib.admin.options import get_content_type_for_model from django.contrib.auth.models import Permission from django.contrib.gis.geos import Point from django.utils.timezone import now from rest_framework.authtoken.models import Token from rest_framework.test import APIClient from bikesharin...
nilq/baby-python
python
from uwsgidecorators import * import gevent @spool def longtask(*args): print args return uwsgi.SPOOL_OK def level2(): longtask.spool(foo='bar',test1='test2') def level1(): gevent.spawn(level2) def application(environ, start_response): start_response('200 OK', [('Content-Type', 'text/html')]) ...
nilq/baby-python
python
st=input("Enter String") r=st.split(" ") l=[] s=" " for i in r: d=list(i) if d[0]=='i' or d[0]=='o': for ele in d: s=s+ele l.append(s) s=" " vowel=" ".join(l) print(vowel)
nilq/baby-python
python
# Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import secrets import sys import tempfile import time import boto3 import bottle import sqlalchemy as db import common.auth as _auth import co...
nilq/baby-python
python
import jax.numpy as jnp from jax import jit from onnx_jax.handlers.backend_handler import BackendHandler from onnx_jax.handlers.handler import onnx_op from onnx_jax.pb_wrapper import OnnxNode @onnx_op("Less") class Less(BackendHandler): @classmethod def _common(cls, node: OnnxNode, **kwargs): @jit ...
nilq/baby-python
python
from flask import Flask, jsonify, request, render_template, flash, redirect, url_for from flask_cors import CORS import subprocess from subprocess import Popen, PIPE from subprocess import check_output import pandas as pd import pickle import sklearn import numpy as np from PIL import Image import os from werkzeug.util...
nilq/baby-python
python
# This File Will Loop execute. from machine import Pin import time LED = Pin(18, Pin.OUT) # Set Running Led # Python and WebDAV cross, which leads to the Python sequence is not stable. # So You Can Switch Python and WebDAV through external Button to stable execute. Button = Pin(27, Pin.IN) while 0 == Button.value():...
nilq/baby-python
python
from .utils import * Any = Var(annotation=typing.Any) AnyList = Var(annotation=list) Int = Var(annotation=int) Float = Var(annotation=float) Str = Var(annotation=str) Array = Var(annotation=np.ndarray, name='Array') ArrayList = Var(annotation=TList[Array], name='ArrayList') FloatDict = Var(annotation=TDict[str, float]...
nilq/baby-python
python
while True: try: a=input() except EOFError: break except KeyboardInterrupt: break print(a)
nilq/baby-python
python
import logging import numpy as np import pandas as pd import pytest import calc # noqa from const import ProdStatRange from schemas import ProductionWellSet from tests.utils import MockAsyncDispatch from util.pd import validate_required_columns logger = logging.getLogger(__name__) @pytest.fixture(scope="session")...
nilq/baby-python
python
import glob import matplotlib.image as mpimg import os.path from davg.lanefinding.Pipeline import Pipeline def demonstrate_lane_finding_on_test_images(data): pipeline = Pipeline() for idx in range(len(data)): # Read in a test image img = mpimg.imread(data[idx]) # Process it ...
nilq/baby-python
python
import argparse import os import torch import torch.nn as nn import torch.nn.parallel import torch.optim as optim import torch.utils.data import torch.nn.functional as F import time from dataloader import KITTILoader as DA import utils.logger as logger import models.anynet parser = argparse.ArgumentParser(description...
nilq/baby-python
python
import os import logging from typing import Dict, Tuple from .read import AppDataReader from .fstprocessor import FSTDirectory, FSTFile from ... import utils _logger = logging.getLogger(__name__) class AppExtractor: def __init__(self, fst_entries: Tuple[Dict[str, FSTDirectory], Dict[str, FSTFile]]): se...
nilq/baby-python
python
""" vtelem - A module for basic frame interfaces. """ # built-in import math from typing import Any, Dict, Tuple # internal from vtelem.classes.byte_buffer import ByteBuffer from vtelem.classes.type_primitive import TypePrimitive, new_default from vtelem.enums.primitive import random_integer FRAME_OVERHEAD = new_def...
nilq/baby-python
python
##################################################################################### # # Copyright (c) Microsoft Corporation. All rights reserved. # # This source code is subject to terms and conditions of the Microsoft Public License. A # copy of the license can be found in the License.html file at the root of this...
nilq/baby-python
python
import source import rssfeeds from flask import Flask app = Flask(__name__) # Server test route @app.route('/hello') def hello_world(): return 'Hello, multiverse!' # Server main route @app.route('/') def display_urls(): test_response = "\n*** START ***\n" # Read the source file feed_urls = sourc...
nilq/baby-python
python
# Copyright 2013 Cloudera 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 kivy.app import App from kivy.uix.widget import Widget from color_util import get_normalized_color from Chessboard import Chessboard, Color, Square class ChessGame(Widget): def on_touch_down(self, touch): return class ChessApp(App): def build(self): game = ChessGame() return ga...
nilq/baby-python
python
# -*- coding: utf-8 -*- """Implentation of command `/logs`. """ from docker_utils import ( ContainerSelector, DockerCommand ) class Logs(DockerCommand): """Implementation of command `/start`. """ __HELP__ = """▪️ Usage: `/logs CONTAINER`: Shows logs of a container.""" LOG_LINES_TO_FETCH: int...
nilq/baby-python
python
"""Test searching volume content.""" from itertools import repeat from random import randrange import json from django.test import TestCase, Client from django.test import RequestFactory from django.urls import reverse from apps.users.tests.factories import UserFactory from ...iiif.manifests.tests.factories import Mani...
nilq/baby-python
python
from pyliterature import Pyliterature urls = [ 'http://science.sciencemag.org/content/355/6320/49.full', 'http://www.nature.com/nature/journal/v541/n7635/full/nature20782.html', 'http://www.sciencedirect.com/science/article/pii/S1751616116301138', 'http://pubs.acs.org/doi/full/10.1021/acscatal.6b029...
nilq/baby-python
python
class Simple: def hello(self): return 'Hello' def world(self): return 'world!' def hello_world(self): return '%s %s' % (self.hello(), self.world())
nilq/baby-python
python
import json f = open('./config.json') config = json.load(f) print(config['URL']) for k, v in config.items() : print(k, ":", v)
nilq/baby-python
python
import socket print(socket.gethostbyaddr("8.8.8.8")) print(socket.gethostbyname("www.google.com"))
nilq/baby-python
python
"""Sokoban environments.""" import random import numpy as np from gym_sokoban.envs import sokoban_env_fast from alpacka.envs import base class Sokoban(sokoban_env_fast.SokobanEnvFast, base.ModelEnv): """Sokoban with state clone/restore and returning a "solved" flag. Returns observations in one-hot encodin...
nilq/baby-python
python
from registration.models import Events, Registration from rest_framework import serializers class EventListSerializer(serializers.HyperlinkedModelSerializer): has_users = serializers.SerializerMethodField() class Meta: model = Events fields = ['title', 'text', 'date', 'has_users'] def ge...
nilq/baby-python
python
from __future__ import print_function from pipelineWrapper import PipelineWrapperBuilder import logging import os import yaml logging.basicConfig(level=logging.INFO) log = logging.getLogger() desc = """UCSC Precision Immuno pipeline""" config = ("""patients: {sample_name}: tumor_dna_fastq_1 : {tumor_dn...
nilq/baby-python
python