content
stringlengths
0
1.05M
origin
stringclasses
2 values
type
stringclasses
2 values
import math import threading from django.core.cache import caches from .settings import CACHE_HELPERS_ALIAS CACHE_HELPERS_KEY = 'cache_helpers_key' def set_cache_bust_status(bust_key=None): cache = caches[CACHE_HELPERS_ALIAS] cache.set(CACHE_HELPERS_KEY, bust_key) def get_bust_key(): cache = caches[...
nilq/baby-python
python
""" Provides the functionality to feed TF templates with Jerakia lookups """ import sys import os from jerakia import Jerakia from terraform_external_data import terraform_external_data def retrieveLookupInfo(query,item): lookitem = query[item] lookuppath =lookitem.split('/') key = lookuppath.pop() na...
nilq/baby-python
python
"""Internal helpers for dataset validation.""" from pathlib import Path from typing import Any, Iterable, List, Optional, Sequence, Tuple, Union import numpy as np import pandas as pd from biopsykit.utils._types import _Hashable, path_t from biopsykit.utils.exceptions import FileExtensionError, ValidationError, Value...
nilq/baby-python
python
from terminaltables import SingleTable import requests import os from dotenv import load_dotenv def predict_salary(min_salary, max_salary): if min_salary == None or min_salary == 0: average_salary = max_salary*0.8 elif max_salary == None or max_salary == 0: average_salary = min_salary*1.2 ...
nilq/baby-python
python
import numpy as np import matplotlib.pyplot as plt teilnehmer = int(input("Teilnehmer: ")) a = list() x = np.arange(1, teilnehmer+1) y = np.zeros(teilnehmer) a.append(float(input("Geheimnis: "))) for i in range(teilnehmer-1): a.append(float(input(f"Koeffizient a{i+1}: "))) for i in range(teilnehmer): for j in ...
nilq/baby-python
python
#/usr/bin/env python from __future__ import absolute_import # Charge transfer efficiency by EPER, now as a pipe task! import lsst.pex.config as pexConfig import lsst.pipe.base as pipeBase import sys import numpy as np import argparse from .MaskedCCD import MaskedCCD import lsst.geom as lsstGeom import lsst.afw.math ...
nilq/baby-python
python
from datetime import datetime from sqlalchemy import create_engine, Column, Integer, DateTime from sqlalchemy.ext.declarative import as_declarative, declared_attr from sqlalchemy.orm import sessionmaker, scoped_session from config.config import SQLALCHEMY_DATABASE_URI engine = create_engine(SQLALCHEMY_DATABASE_URI) ...
nilq/baby-python
python
from typing import List class Solution: def plusOne(self, digits: List[int]) -> List[int]: N = len(digits) for i in reversed(range(N)): digit = digits[i] if digit == 9: digits[i] = 0 else: digits[i] += 1 return di...
nilq/baby-python
python
import timeit import CoolProp.CoolProp as CP def time_check(N, h, p, TTSE = False, mode = 'TTSE'): if TTSE: if mode =='TTSE': setup = "import CoolProp; import CoolProp.CoolProp as CP; CP.enable_TTSE_LUT('Water'); CP.set_TTSE_mode('Water','TTSE'); CP.Props('T','H',500,'P',10000,'Water'); IWate...
nilq/baby-python
python
import numpy as np import pandas as pd import logging logger = logging.getLogger(__name__) def approximate_curve(data, bin_number): binned = pd.cut(data.capacity_factor, bin_number) # bins = np.arange(1, len(data.datetime) / bin_number + 1) # logger.debug("bins: {}".format(bins)) # digitized = np....
nilq/baby-python
python
"""There is a vehicle obscuring a pedestrian that conflicts with your path.""" from flow.envs.multiagent import Bayesian0NoGridEnv from flow.networks import Bayesian1Network from flow.core.params import SumoParams, EnvParams, InitialConfig, NetParams from flow.core.params import SumoCarFollowingParams, VehicleParams f...
nilq/baby-python
python
from datetime import datetime, timedelta from typing import Optional from utils.utils import format_date class Event: """Event object to store data about a Google Calendar event""" def __init__( self, event_id: str, link: str, title: str, location: Optional[str], description: Optional[str], all_day: ...
nilq/baby-python
python
from __future__ import absolute_import, division, print_function from cctbx.array_family.flex import ( # noqa: F401; lgtm abs, acos, arg, asin, atan, atan2, bool, ceil, compare_derivatives, complex_double, condense_as_ranges, conj, cos, cosh, cost_of_m_handl...
nilq/baby-python
python
# @Author: BingWu Yang <detailyang> # @Date: 2016-03-29T17:47:44+08:00 # @Email: detailyang@gmail.com # @Last modified by: detailyang # @Last modified time: 2016-04-10T16:54:56+08:00 # @License: The MIT License (MIT) import ply.yacc as yacc import eslast as ast from esllexer import ESLLexer tokens = ESLLexer....
nilq/baby-python
python
from discord.ext import commands import config class Bot(commands.Bot): async def invoke(self, ctx): if self.user.mentioned_in(ctx.message): # Mention was processed in on_message. return if ctx.invoked_with: await ctx.send(config.response) async def on_mes...
nilq/baby-python
python
#!/usr/bin/env python3 import altair as alt import pandas import selenium def vegaGraphics( cmdTag, id1, id2, parameters, sql, transformedData, verbose,): """Create interactive charts for specified data""" # making function more explicit cmdTag = cmd...
nilq/baby-python
python
from ark.thread_handler import ThreadHandler from factory import Factory import time class GuiTasks(object): @classmethod def loop(cls): time.sleep(1) GuiTasks.get_active_threads() @classmethod def get_active_threads(cls): GUI = Factory.get('GUI') max_threads = len(Thr...
nilq/baby-python
python
import inject from flask import Flask, Response, send_from_directory, send_file class StaticRoute: @staticmethod @inject.autoparams() def init(flask: Flask) -> None: @flask.route("/static/<path:path>") def send_static(path: str) -> Response: return send_from_directory(f"static"...
nilq/baby-python
python
# Exercise 31: Making Decisions print "You enter a dark room with two doors. Do you go through door #1 or door #2?" door = raw_input("> ") if door == "1": print "There's a giant bear here eating a cheese cake. What do you do?" print "1. Take the cake." print "2. Scream at the bear." print "3. Turn back quietly" ...
nilq/baby-python
python
# Generated by Django 3.1.1 on 2020-10-08 02:15 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), ('rameniaapp', '0009_auto_...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015, 2016, 2017 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public Li...
nilq/baby-python
python
#!/usr/bin/env python #Creates an instance in /home/pi/.config/lxsession/LXDE-pi/autostart which will autolaunch the server on the pi user account. import time print "Copy the path of the shortcut file by right clicking it and clicking 'copy path(s)'." print "Paste the path when prompted by right clicking in the term...
nilq/baby-python
python
class Book(): ''' Creates a book object that can be used to populate a web page Inputs: - title: the title of the book [str] - author: the author of the book [str] - series: the series the book belongs to or None [str] - review_text: a short blurb about the book [str] - image_url: a plac...
nilq/baby-python
python
# -*- coding: utf-8 -*- from .base import Smoother __all__ = ['Smoother']
nilq/baby-python
python
from os.path import join, dirname from textx import metamodel_for_language def test_example(): mm = metamodel_for_language('questionnaire') questionnaire = mm.model_from_file(join(dirname(__file__), 'example.que')) assert len(questionnaire.questions) == 6 assert questionnaire.questions[3].text == 'Au...
nilq/baby-python
python
# -*- coding: UTF-8 -*- import threading import json import re from datetime import datetime from flask import current_app from flask_jwt import current_identity, jwt_required from flask_restful import Resource, request from marshmallow import EXCLUDE, ValidationError from sqlalchemy.exc import SQLAlchemyError from c...
nilq/baby-python
python
""" Discovering structure in heatmap data ===================================== _thumb: .4, .2 """ import pandas as pd import seaborn as sns sns.set(font="monospace") # Load the brain networks example dataset df = sns.load_dataset("brain_networks", header=[0, 1, 2], index_col=0) # Select a subset of the networks use...
nilq/baby-python
python
from django.db import models class Position(models.Model): w = models.CharField(max_length=128, null=True, blank=True) x = models.CharField(max_length=128, null=True, blank=True) y = models.CharField(max_length=128, null=True, blank=True) z = models.CharField(max_length=128, null=True, blank=True) ...
nilq/baby-python
python
# -*- coding: UTF-8 -*- # Copyright 2016-2018 Rumma & Ko Ltd # License: BSD, see LICENSE for more details. """ A library of `invoke <http://docs.pyinvoke.org/en/latest/index.html>`__ tasks. See :doc:`/invlib`. .. autosummary:: :toctree: tasks utils """ from __future__ import print_function from __future__ ...
nilq/baby-python
python
from flask import request, jsonify, current_app, make_response, session import random from info.libs.yuntongxun import sms from . import passport_blue from info.utils.response_code import RET from info.utils.captcha.captcha import captcha from info import redis_store,constants,db # 导入模型类 from info.models import User im...
nilq/baby-python
python
from mpf.tests.MpfGameTestCase import MpfGameTestCase from mpf.core.rgb_color import RGBColor class TestBlinkenlight(MpfGameTestCase): def get_config_file(self): return 'config.yaml' def get_platform(self): return 'smart_virtual' def get_machine_path(self): return 'tests/machine...
nilq/baby-python
python
import mysql.connector mydb = mysql.connector.connect( host = 'localhost', user = "root", #passwd = "ant904", database = "spl" #auth_plugin='mysql_native_password' ) myCursor = mydb.cursor() qusTimeList=list() qusTimeList.append("0:00:03") qusTimeList.append("0:00:02") qusTimeList.append("0:00:...
nilq/baby-python
python
from toee import * def OnBeginSpellCast( spell ): print "Vampiric Touch OnBeginSpellCast" print "spell.target_list=", spell.target_list print "spell.caster=", spell.caster, " caster.level= ", spell.caster_level game.particles( "sp-necromancy-conjure", spell.caster ) def OnSpellEffect( spell ): print "Vampiric T...
nilq/baby-python
python
from django.contrib import admin from .models import District, Quarter, Community admin.site.register(District) admin.site.register(Quarter) admin.site.register(Community)
nilq/baby-python
python
# Copyright (C) 2020 Intel Corporation # # 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 wri...
nilq/baby-python
python
import os import codecs from io import StringIO from pytest import fixture from rave import filesystem class DummyProvider: def __init__(self, files): self.files = files; def list(self): return self.files def has(self, filename): return filename in self.list() def open(self,...
nilq/baby-python
python
"""Forward measurements from Xiaomi Mi plant sensor via MQTT. See https://github.com/ChristianKuehnel/plantgateway for more details. """ ############################################## # # This is open source software licensed under the Apache License 2.0 # http://www.apache.org/licenses/LICENSE-2.0 # ################...
nilq/baby-python
python
# # This file contains the Python code from Program 6.2 of # "Data Structures and Algorithms # with Object-Oriented Design Patterns in Python" # by Bruno R. Preiss. # # Copyright (c) 2003 by Bruno R. Preiss, P.Eng. All rights reserved. # # http://www.brpreiss.com/books/opus7/programs/pgm06_02.txt # class StackAsArray(...
nilq/baby-python
python
print('----->DESAFIO 48<-----') print('Vou te mostrar a soma de todos os números impares múltiplos de 3 que estão no intervalo de 1 a 500!') soma = 0 for c in range(0, 501): if c > 0 and c % 2 != 0 and c % 3 == 0: soma += c print(soma)
nilq/baby-python
python
################################################################# # Name: randDLA.py # # Authors: Michael Battaglia # # Function: Program simulates diffusion limited aggregation # # using Monte Carlo Methods. ...
nilq/baby-python
python
#import import random import os import numpy dic = {} with open("points3D.txt","r") as n: for line in n: a = line.split(" ") temp = [] temp.append(float(a[1])) temp.append(float(a[2])) temp.append(float(a[3])) dic[a[0]] = temp[:] print(dic["1"]) ...
nilq/baby-python
python
def getone(coll, key, default=None): try: value = coll[key] except [IndexError, KeyError, TypeError]: return default; else: return value;
nilq/baby-python
python
#!/usr/bin/env python2.7 # Copyright 2019 The Fuchsia Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from __future__ import print_function import argparse import itertools import json import os import sys SCRIPT_DIR = os.path.dirna...
nilq/baby-python
python
#!/usr/bin/env python import vtk from vtk.test import Testing from vtk.util.misc import vtkGetDataRoot VTK_DATA_ROOT = vtkGetDataRoot() # Create renderer stuff # ren1 = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren1) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renW...
nilq/baby-python
python
from collections import defaultdict with open('day10/input.txt', 'r') as file: data = sorted([int(x.strip()) for x in file.readlines()]) data = [0] + data data.append(data[-1] + 3) jolt_1, jolt_3 = 0, 0 for i in range(len(data)): current = data[i - 1] if (data[i] - current) == 1: jolt_1 += 1 ...
nilq/baby-python
python
from django.contrib.auth.hashers import make_password from rest_framework import serializers from .models import User from rest_framework_simplejwt.serializers import TokenObtainPairSerializer from rest_framework import response, status class RegisterSerializer(serializers.ModelSerializer): class Meta: mo...
nilq/baby-python
python
import tensorflow as tf # GPU版Tensor Flowを、特定のGPUで実行する GPU_INDEX = 2 tf.config.set_soft_device_placement(True) tf.debugging.set_log_device_placement(True) gpus = tf.config.experimental.list_physical_devices('GPU') if gpus: try: logical_gpus = tf.config.experimental.list_logical_devices('GPU') pr...
nilq/baby-python
python
import pytest from package_one.module_one import IntegerAdder @pytest.fixture def adder(): print("Test set-up!") yield IntegerAdder() print("Test tear-down") def test_integer_adder(adder): assert adder.add(1, 2) == 3 """ In case you'd like to declare a fixture that executes only once per module, then...
nilq/baby-python
python
def snail(array): results = [] while len(array) > 0: results += array[0] del array[0] if len(array) > 0: for i in array: results += [i[-1]] del i[-1] if array[-1]: results += arra...
nilq/baby-python
python
import os from google.appengine.ext.webapp import template from base_controller import CacheableHandler from models.event import Event class EventWizardHandler(CacheableHandler): CACHE_VERSION = 1 CACHE_KEY_FORMAT = "event_wizard" def __init__(self, *args, **kw): super(EventWizardHandler, self)....
nilq/baby-python
python
""" MIT License Copyright (c) 2021 martinpflaum 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, ...
nilq/baby-python
python
__author__ = "Jeremy Nelson" import csv import datetime import json import urllib2 from json_ld.utilities.creator import JSONLinkedDataCreator class JohnPeabodyHarringtonJSONLinkedDataCreator(JSONLinkedDataCreator): CC_URI = 'http://id.loc.gov/authorities/names/n84168445' LOC_URI = 'http://id.loc.gov/autho...
nilq/baby-python
python
from .algo.algo_endpoints import AlgoEndpoints from .graph.graph_endpoints import GraphEndpoints from .query_runner.query_runner import QueryRunner class IndirectEndpoints(AlgoEndpoints, GraphEndpoints): def __init__(self, query_runner: QueryRunner, namespace: str): super().__init__(query_runner, namespac...
nilq/baby-python
python
#-*- coding:utf-8 -*- import generate_chat import seq2seq_model import tensorflow as tf import numpy as np import os os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" os.environ["CUDA_VISIBLE_DEVICES"] = "-1" if __name__ == '__main__': _, _, source_vocab_size = generate_chat.get_vocabs(generate_chat.vocab_encode_file...
nilq/baby-python
python
import tkinter as tk from src.ui.core import SortableTable from src.library.model import PlaylistModel class Table(SortableTable): def __init__(self, parent, logger, library): SortableTable.__init__(self, parent, logger) self.library = library self.add_column('Playlist Name', sortable=True) self.init_treevie...
nilq/baby-python
python
from slicegan import preprocessing, util import torch import torch.nn as nn import torch.backends.cudnn as cudnn import torch.optim as optim import time import matplotlib import wandb # 1. Start a new run wandb.init(project='SuperRes', name='SliceGAN train', entity='tldr-group') def train(pth, imtype, datatype, real_...
nilq/baby-python
python
from typing import List from ..error import GraphQLError from ..language import DocumentNode from ..type import GraphQLSchema __all__ = ["find_deprecated_usages"] def find_deprecated_usages( schema: GraphQLSchema, ast: DocumentNode ) -> List[GraphQLError]: # pragma: no cover """Get a list of GraphQLError i...
nilq/baby-python
python
from .target_generators import HeatmapGenerator from .target_generators import ScaleAwareHeatmapGenerator from .target_generators import JointsGenerator __all__ = ['HeatmapGenerator', 'ScaleAwareHeatmapGenerator', 'JointsGenerator']
nilq/baby-python
python
import re from typing import Annotated, Any, Optional import pytest from arti import ( Annotation, Artifact, Fingerprint, PartitionDependencies, Producer, StoragePartitions, ) from arti import producer as producer_decorator # Avoid shadowing from arti.internal.models import Model from arti.in...
nilq/baby-python
python
from pathlib import Path from fhir.resources.valueset import ValueSet as _ValueSet from oops_fhir.utils import ValueSet from oops_fhir.r4.code_system.feeding_device_codes import ( FeedingDeviceCodes as FeedingDeviceCodes_, ) from oops_fhir.r4.code_system.snomed_ct import SNOMEDCT __all__ = ["FeedingDeviceCod...
nilq/baby-python
python
import time import os import numpy as np from perform.constants import REAL_TYPE class RomSpaceMapping: """Base class for mapping to/from the state/latent space.""" def __init__(self, sol_domain, rom_domain, rom_model): rom_dict = rom_domain.rom_dict model_idx = rom_model.model_idx ...
nilq/baby-python
python
from dl.nn.Module import Module import dl.graph.op as OP from dl.graph import variable class DropoutLayer(Module): """ Dropout layer object. """ def __init__(self, rate: float): """ Dropout layer object. Parameters ---------- rate: Dropout rate. ...
nilq/baby-python
python
import torch.distributed as dist from .trainer import Trainer from ..util import DDP def average_gradients(model): """ Gradient averaging. """ size = float(dist.get_world_size()) for param in model.parameters(): if param.grad is not None: dist.all_reduce(param.grad.data, op=dist.Reduce...
nilq/baby-python
python
from .answer import Answer, CalculatedAnswer, DragText, NumericalAnswer from .enums import * from .questions import (QCalculated, QCalculatedMultichoice, QCalculatedSimple, QCloze, QDescription, QDragAndDropImage, QDragAndDropMarker, QDragAndDropText, QEssay, ...
nilq/baby-python
python
import warnings from collections import OrderedDict import pandas as pd from . import dtypes, utils from .alignment import align from .variable import IndexVariable, Variable, as_variable from .variable import concat as concat_vars def concat( objs, dim=None, data_vars="all", coords="different", ...
nilq/baby-python
python
import re import os try: from urlparse import urlparse except: from urllib.parse import urlparse from .exceptions import FieldValidationException from .universal_forwarder_compatiblity import UF_MODE, make_splunkhome_path from .contrib.ipaddress import ip_network try: from .server_info import ServerInfo...
nilq/baby-python
python
import os import pandas as pd import pytest from probatus.feature_elimination import EarlyStoppingShapRFECV, ShapRFECV from probatus.utils import preprocess_labels from sklearn.linear_model import LogisticRegression from sklearn.metrics import get_scorer from sklearn.model_selection import RandomizedSearchCV, Stratifi...
nilq/baby-python
python
# -*- coding: utf8 -*- from base import Stock class Uzmanpara(Stock): stockURL = "http://uzmanpara.milliyet.com.tr/borsa/hisse-senetleri/{0}/" priceQuery = '.realTime > .price-arrow-down, .realTime > .price-arrow-up' volumeQuery = '.realTime table tr td' timezone = "Europe/Istanbul" @classmethod ...
nilq/baby-python
python
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals import sys from pkg_resources import load_entry_point from subprocess import check_call def main(): check_call([sys.executable, 'setup.py', 'build_ext', '--inplace']) if '--with-coverage' not in sys.argv: sys.argv.extend(('--with-co...
nilq/baby-python
python
"""Tests for ht.events.manager module.""" # ============================================================================= # IMPORTS # ============================================================================= # Third Party import pytest # Houdini Toolbox import ht.events.manager from ht.events.event import Houdin...
nilq/baby-python
python
from .. cupy_utils import to_numpy, trapz, xp from ..utils import powerlaw import numpy as np from astropy.cosmology import Planck15 class PowerLawRedshift(object): """ Redshift model from Fishbach+ https://arxiv.org/abs/1805.10270 Note that this is deliberately off by a factor of dVc/dz """ de...
nilq/baby-python
python
from flask import Flask from flask_bootstrap import Bootstrap app = Flask(__name__) Bootstrap(app) with app.app_context(): import routes import stats if __name__ == "__main__": app.config['DEBUG'] = True app.run()
nilq/baby-python
python
from receptor_affinity.mesh import Mesh from wait_for import TimedOutError import time import pytest @pytest.yield_fixture( scope="function", params=[ "test/perf/flat-mesh.yaml", "test/perf/tree-mesh.yaml", "test/perf/random-mesh.yaml", ], ids=["flat", "tree", "random"], ) def ...
nilq/baby-python
python
# Copyright 2021 Gakuto Furuya # # 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 writ...
nilq/baby-python
python
#!/usr/bin/env python import os import sys path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) sys.path.insert(0, path) import django def manage_16ormore(): os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings") from django.core.management import execute_from_command_line execut...
nilq/baby-python
python
#Adding python objects to database import sqlite3 from employee import Employee #we are calling in the Employee class from the program which we made earlier, they must be in the same directory conn=sqlite3.connect('sql.db') c = conn.cursor() #c.execute("""CREATE TABLE employees ( # first text, # ...
nilq/baby-python
python
from XTax import Tax import io import unittest import unittest.mock class Test_XTax(unittest.TestCase): def test_TaxInitYear(self): MyTax = Tax(2019,autoload=False) self.assertEqual(MyTax.Year, 2019) @unittest.mock.patch('sys.stdout', new_callable=io.StringIO) def test_TaxInitLog(self,mock...
nilq/baby-python
python
import sys try: import threading except ImportError: import dummy_threading as threading py32 = sys.version_info >= (3, 2) py3k = sys.version_info >= (3, 0) py2k = sys.version_info <= (3, 0) if py3k: string_types = str, import itertools itertools_filterfalse = itertools.filterfalse if py3...
nilq/baby-python
python
import sys import Heuristic import RandomProblem import SolveProblem def main(): # auto random file if no input if len(sys.argv) != 4: RandomProblem.createRandomProblem('rand_in.txt', 8, 16) pf = SolveProblem.ARA('rand_in.txt', 'rand_log.txt', 3, Heur...
nilq/baby-python
python
"""Playbook Create""" # standard library import base64 import json import logging from typing import Any, Dict, Iterable, List, Optional, Union # third-party from pydantic import BaseModel # first-party from tcex.key_value_store import KeyValueApi, KeyValueRedis from tcex.utils.utils import Utils # get tcex logger l...
nilq/baby-python
python
from moviepy.editor import * clip = (VideoFileClip("../output_videos/project_video.mp4").subclip(10, 40).resize(0.3)) clip.write_gif("../output_videos/project_video.gif")
nilq/baby-python
python
# -*- coding: utf-8 -*- """ admin security exceptions module. """ from pyrin.core.exceptions import CoreException, CoreBusinessException from pyrin.security.exceptions import AuthorizationFailedError class AdminSecurityException(CoreException): """ admin security exception. """ pass class AdminSecu...
nilq/baby-python
python
# -*- coding: utf-8 -*- # # Copyright (c), 2018-2019, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author ...
nilq/baby-python
python
#! /usr/bin/env python3 # Conditions: # * A child is playing with a ball on the nth floor of a tall building # * The height of this floor, h, is known # * He drops the ball out of the window. The ball bounces (for example), # to two-thirds of its height (a bounce of 0.66). # * His mother looks out of a window 1.5 me...
nilq/baby-python
python
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: lbrynet/schema/proto/source.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import ...
nilq/baby-python
python
# -*- coding: utf-8 -*- """ Created on Mon Aug 9 23:58:12 2021 @author: AKayal """ from collections import namedtuple from typing import List, NamedTuple import datetime from datetime import date class personal_details(NamedTuple): """ Using the typing module, we can be even more explicit about our data stru...
nilq/baby-python
python
from whirlwind.store import create_task from delfick_project.norms import sb, dictobj, Meta from tornado.web import RequestHandler, HTTPError from tornado import websocket import binascii import logging import asyncio import json import uuid log = logging.getLogger("whirlwind.request_handlers.base") class Finished(...
nilq/baby-python
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon May 22 14:33:38 2017 @author: paul """ from weatherTLKT import Weather typ='ens' for ss in range(1,9): if typ=='solo': mydate='20171127' website='http://nomads.ncep.noaa.gov:9090/dods' model='gfs' resolution='0p25' url=website+'...
nilq/baby-python
python
from django.views.generic import TemplateView, ListView, DetailView from . import models class DashboardView(TemplateView): template_name = "organizations/dashboard.html" class OrganizationDetailView(DetailView): template_name = "organizations/organization_details.html" model = models.Organization clas...
nilq/baby-python
python
import csv import xlsxwriter import datetime # Sequence Analysis Data Object # Holds all items needed for analysis class SeqData: its_dict = None seq_config = None num_threads = None output_format = None def __init__(self, its_dict, seq_config, num_threads, output_format): self.num_threads...
nilq/baby-python
python
import pandas as pd from strategy.astrategy import AStrategy from processor.processor import Processor as p from datetime import timedelta import pytz from tqdm import tqdm from time import sleep pd.options.mode.chained_assignment = None class ProgressReport(AStrategy): def __init__(self,start_date,end_date,modelin...
nilq/baby-python
python
from functools import reduce from operator import mul import numpy as onp from numpy.testing import assert_allclose import pytest import scipy.stats as osp_stats import jax from jax import grad, lax, random import jax.numpy as np from jax.scipy.special import logit import numpyro.contrib.distributions as dist from n...
nilq/baby-python
python
import os import os.path as osp import sys import numpy.random import torch.nn from deltalogger.deltalogger import Deltalogger from reinforce_modules.utils import ConfusionGame, get_defense_visual_fool_model from utils.train_utils import StateCLEVR, ImageCLEVR_HDF5 sys.path.insert(0, osp.abspath('.')) import random ...
nilq/baby-python
python
from django.conf import settings from django.urls import path, include from rest_framework.routers import DefaultRouter from api.search.product import views # Create a router and register our viewsets with it. router = DefaultRouter() router.register(r"search", views.ProductDocumentView, basename="product_search") ...
nilq/baby-python
python
import copy import numpy as np # configure matplotlib for use without xserver import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt def get_neuron_features(features, neurons): """ Gets neuron activations from activations specified by `neurons`. Args: features: numpy arraylike of s...
nilq/baby-python
python
''' Multiples of 3 and 5 ''' sum = 0 for i in range(1000): if i%3 == 0 or i%5 == 0: sum = sum + i print sum
nilq/baby-python
python
#!/usr/bin/env python import sys, gym, time # # Test yourself as a learning agent! Pass environment name as a command-line argument, for example: # # python keyboard_agent.py SpaceInvadersNoFrameskip-v4 # import gym_game import pygame if len(sys.argv) < 3: print('Usage: python keyboard_agent.py ENV_NAME CONFIG_FILE...
nilq/baby-python
python
import enum import re import string from typing import Text, List from xml.sax import saxutils import emoji from six import string_types from collections.abc import Iterable from tklearn.preprocessing import TextPreprocessor __all__ = [ 'Normalize', 'TweetPreprocessor', ] @enum.unique class Normalize(enum.E...
nilq/baby-python
python
from flask import Flask, request, jsonify, render_template from flask_cors import CORS import math import pickle app = Flask(__name__) CORS(app) uniq_fire_date = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'July', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] uniq_county = ['No Data', 'Skamania', 'Cowlitz', 'Thurston', 'Okanoga...
nilq/baby-python
python
def mallow(y, y_pred, y_sub, k, p): """ Return an mallows Cp score for a model. Input: y: array-like of shape = (n_samples) including values of observed y y_pred: vector including values of predicted y k: int number of predictive variable(s) used in the model p: int number of predictive var...
nilq/baby-python
python