content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
"""
Script to download the examples from the stac-spec repository.
This is used when upgrading to a new version of STAC.
"""
import os
import argparse
import json
from subprocess import call
import tempfile
from typing import Any, Dict, List, Optional
from urllib.error import HTTPError
import pystac
from pystac.serial... | nilq/baby-python | python |
import numpy as np
import cv2
import os
basepath = os.path.dirname(os.path.abspath(__file__))+"/Sample-Videos/"
def background_subtractor(video_link,method="MOG"):
cap = cv2.VideoCapture(video_link)
if method == "MOG":
fgbg = cv2.createBackgroundSubtractorMOG()
elif method == "MOG2":
fgbg = cv2.createBackgroun... | nilq/baby-python | python |
#!/usr/bin/env python2
#
# Copyright (c) 2016,2018 Cisco and/or its affiliates.
# 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 re... | nilq/baby-python | python |
# Copyright 2017, 2019-2020 National Research Foundation (Square Kilometre Array)
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list... | nilq/baby-python | python |
import pytest
from tgbotscenario.asynchronous import Machine, BaseScene, MemorySceneStorage
from tests.generators import generate_direction
@pytest.mark.parametrize(
("direction",),
(
(None,),
(generate_direction(),)
)
)
def test_transition_not_exists(direction, handler):
class Initi... | nilq/baby-python | python |
#!/usr/bin/env python3
import datetime
import logging
import os
import sys
import time
import urllib.request
import argparse
from imageai.Detection import ObjectDetection
from imageai.Classification import ImageClassification
import simplejson as json
import tweepy
from tweepy import API, Cursor, Stream, OAuthHandler... | nilq/baby-python | python |
import math
import pytz
import singer
import singer.utils
import singer.metrics
import time
from datetime import timedelta, datetime
import tap_ringcentral.cache
from tap_ringcentral.config import get_config_start_date
from tap_ringcentral.state import incorporate, save_state, \
get_last_record_value_for_table
f... | nilq/baby-python | python |
from copy import deepcopy
from datetime import date, timedelta
from hashlib import sha256
import starkbank
from starkbank import BoletoPayment
from .boleto import generateExampleBoletosJson
example_payment = BoletoPayment(
line="34191.09008 61713.957308 71444.640008 2 83430000984732",
scheduled="2020-02-29",
... | nilq/baby-python | python |
import numpy as np
import pandas as pd
import time
from collections import OrderedDict
import argparse
import os
import re
import pickle
import subprocess
def str2bool(v):
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif v.lower() in ('no', 'false', 'f', 'n', '0'):
return False
... | nilq/baby-python | python |
question1 = input("random number ")
question2 = input("another random number ")
if (question1 > question2):
print(question1, ">", question2)
elif (question1 < question2):
print(question1, "<", question2)
else:
print(question1, "=", question2)
| nilq/baby-python | python |
import requests
data = {'stuff': 'things'}
r = requests.post('http://127.0.0.1:5042/incoming', data=data)
print(r.text)
| nilq/baby-python | python |
import json
import requests
from fisherman import exceptions
from fisherman.utils import colors
# Documentation: https://apility.io/apidocs/#email-check
BASE_URL = "https://api.apility.net/bademail/"
def check_email_rep(email, verbose_flag):
try:
colors.print_gray('Casting line - sending email... | nilq/baby-python | python |
import numpy as np
import torch
import torch.nn.functional as F
import torch.nn as nn
from . import dataloader
def default_eval(loader,model,class_acc=False):
data_source = loader.dataset
way = len(data_source.classes)
correct_count = torch.zeros(way).cuda()
counts = torch.zeros(way).cuda()
... | nilq/baby-python | python |
from abc import ABC, abstractmethod
from collections import defaultdict
from enum import Enum
from io import StringIO
from itertools import chain
from os import linesep
from typing import List, Dict, Any, Union, Type, Set, Tuple
class GenericSchemaError(Exception):
pass
class BaseSchemaError(Exception, ABC):
... | nilq/baby-python | python |
"""
What does this module do?
Does it do things?
"""
import logging
from taxii_client import TaxiiClient
__all__ = []
__version__ = '0.1'
__author__ = 'Chris Fauerbach'
__email__ = 'chrisfauerbach@gmail.com'
class EdgeClient(TaxiiClient):
def __init__(self, config):
super(EdgeClient, self).__init__(co... | nilq/baby-python | python |
import torch
import pickle
import torch.utils.data
import time
import os
import numpy as np
from torch_geometric.utils import get_laplacian
import csv
from scipy import sparse as sp
import dgl
from dgl.data import TUDataset
from dgl.data import LegacyTUDataset
import torch_geometric as pyg
from scipy.sparse import csr_... | nilq/baby-python | python |
# 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 applicable law or agreed to in... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Created on Tue May 14 08:26:52 2019
@author: mritch3
"""
from __future__ import print_function
from keras.preprocessing.image import ImageDataGenerator
import numpy as np
import os, glob
import skimage.io as io
import skimage.transform as trans
import matplotlib as mp
from PIL import Image... | nilq/baby-python | python |
from pinger import pinger
import responses
from requests.exceptions import ConnectTimeout
def test_check_site_not_found():
url = 'https://fake.url/'
site = {
'url': url,
'timeout': 1,
}
with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps:
rsps.add(res... | nilq/baby-python | python |
class Attributes:
# Attributes of HTML elements
accept = 'accept' # Specifies the types of files that the server accepts (only for type="file")
accept_charset = 'accept-charset' # Specifies the character encodings that are to be used for the form submission
accesskey = 'accesskey' # Specifies a shor... | nilq/baby-python | python |
from .api import Stage, concat, each, filter, flat_map, from_iterable, map, run, ordered, to_iterable
from .utils import get_namespace
| nilq/baby-python | python |
import numpy as np
import pandas as pd
import geopandas as gpd
from _utils import clean_segments, filter_segments, split_by_dir, pd2gpd, edit_asfinag_file
from _variable_definitions import *
import pickle
# ----------------------------------------------------------------------------------------------------------------... | nilq/baby-python | python |
import enum
import pandas as pd
from data import dataset
class ColumnType(enum.Enum):
sentence1 = 0,
sentence2 = 1,
labels = 2,
columns = [
ColumnType.sentence1.name,
ColumnType.sentence2.name,
ColumnType.labels.name,
]
class SNLIDataset(dataset.DatasetExperiment):
def __init__(... | nilq/baby-python | python |
from pathlib import Path
import yaml
from charms import layer
from charms.reactive import clear_flag, set_flag, when, when_any, when_not
@when('charm.started')
def charm_ready():
layer.status.active('')
@when_any('layer.docker-resource.oci-image.changed', 'config.changed')
def update_image():
clear_flag('c... | nilq/baby-python | python |
import numpy as np
def read_log(log_file=None):
'''This function reads Nalu log files
Currently, the function only reads timing info output by nalu-wind
It would be good to add more functionality to this function
'''
if log_file is None:
raise Exception('Please enter a log file name... | nilq/baby-python | python |
from avalon import api, houdini
def main():
print("Installing OpenPype ...")
api.install(houdini)
main()
| nilq/baby-python | python |
from distutils.version import LooseVersion
import os
import re
import shutil
import typing
import pandas as pd
import audbackend
import audeer
import audformat
from audb.core import define
from audb.core.api import (
cached,
default_cache_root,
dependencies,
latest_version,
)
from audb.core.backward ... | nilq/baby-python | python |
__author__ = 'schelle'
import unittest
import wflow.wflow_sceleton as wf
import os
"""
Run sceleton for 10 steps and checks if the outcome is approx that of the reference run
"""
class MyTest(unittest.TestCase):
def testapirun(self):
startTime = 1
stopTime = 20
currentTime =... | nilq/baby-python | python |
from sqlalchemy import *
from config.base import getBase, getMetaData, getEngine
from utils.checkers import Checkers
from utils.table_names import LstTableNames
if Checkers.check_table_exists(getEngine(), LstTableNames.LST_R1_DATA_CHECK_GENERIC):
class LstR1DataCheckGeneric(getBase()):
__tablename__ = Tab... | nilq/baby-python | python |
# Generated by Django 3.2.7 on 2021-10-13 15:08
from django.db import migrations, models
import django_countries.fields
class Migration(migrations.Migration):
dependencies = [
('profiles', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='userprofile',
... | nilq/baby-python | python |
import os.path, logging
from re import compile as re_compile
from handlers.upstream import Upstream
from handlers.dummy import DummyResponse, ExceptionResponse
from handlers import is_uuid, CDE, CDE_PATH
from content import copy_streams
import annotations
import config, features
import calibre
_BUFFER_SIZE = 64 * 10... | nilq/baby-python | python |
import os
from curtsies.fmtfuncs import cyan, bold, green, red, yellow
MAX_CHAR_LENGTH = 512
MIN_CHAR_LENGTH = 20
NEWLINECHAR = '<N>'
d = 'repos'
paths = []
for dirpath, dirnames, filenames in os.walk(d):
for f in filenames:
path = os.path.join(dirpath, f)
paths.append(path)
print(len(paths))
wit... | nilq/baby-python | python |
#!/usr/bin/env python
import os
from os.path import abspath, dirname, sep
from idagrap.modules.Module import ModuleTestMisc
from idagrap.modules.Pattern import Pattern, Patterns
from idagrap.config.General import config
def get_test_misc():
# Definition-----------------------------------------------------------... | nilq/baby-python | python |
"""Tests the functionality in the dinao.binding module."""
from typing import Generator, Mapping, Tuple
from dinao.binding.binders import FunctionBinder
from dinao.binding.errors import TooManyRowsError
import pytest
from tests.binding.mocks import MockConnection, MockConnectionPool, MockDMLCursor, MockDQLCursor
... | nilq/baby-python | python |
from alento_bot.storage_module.managers.config_manager import ConfigManager
from alento_bot.storage_module.managers.guild_manager import GuildManager, GuildNameNotRegistered, AlreadyRegisteredGuildName
from alento_bot.storage_module.managers.user_manager import UserManager, UserNameNotRegistered, AlreadyRegisteredUserN... | nilq/baby-python | python |
from flask import Blueprint, render_template, session
from app.models import Post
from app.db import get_db
from app.utils.auth import login_required
bp = Blueprint('dashboard', __name__, url_prefix='/dashboard')
@bp.route('/')
@login_required
def dash():
db = get_db()
posts = (
db.query(Post)
.filter(Pos... | nilq/baby-python | python |
from getpass import getpass
def login():
user = input("Enter your username: ")
password = getpass()
return user, password
if __name__ == '__main__':
print(login())
| nilq/baby-python | python |
import logging
from typing import Optional, List
from django.db import models
from django.db.models import Q
from django.db.models.deletion import SET_NULL, CASCADE
from django.db.models.signals import post_delete
from django.dispatch.dispatcher import receiver
from analysis.models.nodes.analysis_node import Analysis... | nilq/baby-python | python |
class Inputs(object):
"""
split-and: inputs.step_a.x inputs.step_b.x
foreach: inputs[0].x
both: (inp.x for inp in inputs)
"""
def __init__(self, flows):
# TODO sort by foreach index
self.flows = list(flows)
for flow in self.flows:
setattr(self, flow._current_s... | nilq/baby-python | python |
from prescription_data import *
trial_patients = ['Denise', 'Eddie', 'Frank', 'Georgia', 'Kenny']
# Remove Earfarin and add Edoxaban
for patient in trial_patients:
prescription = patients[patient]
try:
prescription.remove(warfarin)
prescription.add(edoxaban)
except KeyError:
print(... | nilq/baby-python | python |
# Copyright (c) 2020 Branislav Holländer. All rights reserved.
# See the file LICENSE for copying permission.
import jax
import jax.numpy as jnp
import jax.scipy.stats.norm as jax_norm
from piper.distributions.distribution import Distribution
from piper import core
from piper import utils
class Normal(Distribution)... | nilq/baby-python | python |
import os
import pystache
import re
import sys
sys.path.append("..")
from ansible import build_ansible_yaml
from api import build_resource_api_config
from common.utils import (fetch_api, normal_dir, read_yaml, write_file)
from design.resource_params_tree import generate_resource_properties
from resource import build_r... | nilq/baby-python | python |
import os
basedir = os.path.abspath(os.path.dirname(__file__))
APP_NAME = 'Glocal'
CHOSEN_MEDIA = ['Twitter', 'Instagram', 'Four Square',
'LastFM', 'Eventful', 'Eventbrite']
| nilq/baby-python | python |
import os
import sys
coverage = None
try:
from coverage import coverage
except ImportError:
coverage = None
os.environ['DJANGO_SETTINGS_MODULE'] = 'example_project.settings'
current_dirname = os.path.dirname(__file__)
sys.path.insert(0, current_dirname)
sys.path.insert(0, os.path.join(current_dirname, '..'))
... | nilq/baby-python | python |
#!/usr/bin/env python3.6
# coding=utf-8
import argparse
import asyncio
import datetime
import logging
import pprint
import configparser
import sys
import traceback
import book_utils
import utils
from db_model import get_db_session
from utils import fix_symbol
from ws_exception import WsError
FORMAT = "[%(asctime)s, ... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from azure.storage.blob import BlockBlobService
import UtilityHelper
import asyncio
import requests, datetime
import os, json, threading
import multiprocessing
from azure.eventprocessorhost import (
AbstractEventProcessor,
AzureStorageCheckpointLeaseManager,
EventHubConfig,
E... | nilq/baby-python | python |
Gem_Qty = {"ruby": 25, "diamond": 30,
"emrald": 15, "topaz": 18, "sapphire": 20}
Gem_Price = {"ruby": 2000, "diamond": 4000,
"emrald": 1900, "topaz": 500, "sapphire": 2500}
Gem_Name = input("Enter Gem Names: ").split(",")
Gem_Num = input("Enter Gem Quantities: ").split(",")
Total_Cost = 0
... | nilq/baby-python | python |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator 2.3.3... | nilq/baby-python | python |
import torch
from torch import nn
from transformers import AutoModel, AutoConfig
from pdb import set_trace
def init_weights(module, init_type='xavier'):
"""Initialize the weights"""
if init_type =='default':
return
elif init_type == 'huggingface':
if isinstance(module, nn.Linear):
... | nilq/baby-python | python |
#!/usr/bin/env python3
import sys
class FuelDepotCracker:
def __init__(self):
self.minimum = 271973
self.maximum = 785961
self.position = self.minimum
def is_valid(self, value):
"""Returns boolean is valid fuel depot password?"""
has_duplicate = False
numbers ... | nilq/baby-python | python |
'''def print_args(farg, *args):
print("formal arg: %s" % farg)
for arg in args:
print("another positional arg: %s" % arg)
print_args(1, "two", 3)
'''
def example(a, **kw):
print (kw)
example(3, c=4) # => {'b': 3, 'c': 4} | nilq/baby-python | python |
from .light import light
from .eos import calc_density as density, viscosity
from .rasterize import ladim_raster
| nilq/baby-python | python |
import logging
import unittest
from unittest import TestCase
from facebookproducer.posts.posts_provider import PostsProvider
class PostsProviderTests(TestCase):
def __init__(self, *args, **kwargs):
super(PostsProviderTests, self).__init__(*args, **kwargs)
logging.basicConfig(
format=... | nilq/baby-python | python |
#!/usr/bin/env python
"""
Field
"""
"""
Copyright 2001 Pearu Peterson all rights reserved,
Pearu Peterson <pearu@ioc.ee>
Permission to use, modify, and distribute this software is given under the
terms of the LGPL. See http://www.fsf.org
NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
$Revision... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Conversation module."""
import rospy
from .state_machine import StateMachine
from .rospy_helper import *
import nltk
from nltk.corpus import stopwords
def preprocess_txt(txt):
list_words = ['oh', 'ah', 'okay', 'ok', 'well', 'please', 'first', 'then', 'finally',... | nilq/baby-python | python |
"""Provision hosts for running tests."""
from __future__ import annotations
import atexit
import dataclasses
import functools
import itertools
import os
import pickle
import sys
import time
import traceback
import typing as t
from .config import (
EnvironmentConfig,
)
from .util import (
ApplicationError,
... | nilq/baby-python | python |
from abc import ABC
from .private_torrent import PrivateTorrent
from ..base.sign_in import SignState, check_final_state
from ..base.work import Work
from ..utils.value_hanlder import handle_join_date
class AvistaZ(PrivateTorrent, ABC):
SUCCEED_REGEX = None
def sign_in_build_workflow(self, entry, config):
... | nilq/baby-python | python |
class Audit: # Class for the different sub classes
def __init__(self, json):
self.id = json["id"]
self.action = json["action"]
self.timestamp = json["timestamp"]
self.tenantId = json["tenantId"]
self.customerId = json["customerId"]
self.changedBy = json["changedBy"]
... | nilq/baby-python | python |
from flask import Blueprint
from flask_restful import Api, Resource
root_blueprint = Blueprint("root", __name__)
api = Api(root_blueprint)
class Root(Resource):
def get(self):
return {"status": "success", "message": "TODO react app"}
api.add_resource(Root, "/")
| nilq/baby-python | python |
import os
import numbers
import datetime
from celery import schedules
from celery.beat import Scheduler
from celery.utils.log import get_logger
from sqlalchemy import create_engine, inspect
from sqlalchemy.orm import sessionmaker
from typing import Any, Dict
from .models import Base, TaskEntry
logger = get_logger... | nilq/baby-python | python |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2017 Damian Ziobro <damian@xmementoit.com>
#
# Distributed under terms of the MIT license.
"""
This is hello world application to use Redis NoSQL databas
"""
import redis
REDIS = redis.Redis(host='localhost', port=5000, password='passwor... | nilq/baby-python | python |
from initialize import initialize
import matplotlib.pyplot as plt
x, y = initialize()
x.sort()
y.sort()
plt.plot(x,y)
plt.show() | nilq/baby-python | python |
"""A core utility function for downloading efficiently and robustly"""
def download_file(url, path, progress=False, if_newer=True):
"""Download large file efficiently from url into path
Parameters
----------
url : str
The URL to download from. Redirects are followed.
path : {str, pathlib.... | nilq/baby-python | python |
[print]
[1,3]
[b,]
| nilq/baby-python | python |
from concurrent.futures import ThreadPoolExecutor
import socket
import os
def __handle_message(args_tuple):
conn, addr, data_sum = args_tuple
while True:
data = conn.recv(1024)
data_sum = data_sum + data.decode('utf-8')
if not data:
break
if data_sum != '':
p... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
'''Chemical Engineering Design Library (ChEDL). Utilities for process modeling.
Copyright (C) 2020, Caleb Bell <Caleb.Andrew.Bell@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal... | nilq/baby-python | python |
import json
import os
from os import listdir
from os.path import isfile, join
from pprint import pprint
from database.user import SessionUser
from util.login_spotify import login_spotify
def json_to_database():
"""
Loads the json files from the first experiment into a database, the folder can be specified by... | nilq/baby-python | python |
#!/usr/bin/env python
# coding: utf-8
__author__ = 'ChenyangGao <https://chenyanggao.github.io/>'
__version__ = (0, 0, 2)
__all__ = ['watch']
# TODO: 移动文件到其他文件夹,那么这个文件所引用的那些文件,相对位置也会改变
# TODO: created 事件时,文件不存在,则文件可能是被移动或删除,则应该注册一个回调,因为事件没有被正确处理
plugin.ensure_import('watchdog')
import logging
import posixpath
impo... | nilq/baby-python | python |
import math
LambdaM = {0: None}
L = [2, 1]
Ll = 2
def compute_Lucas(n):
global L
global Ll
while Ll <= n:
L.append(L[-1] + L[-2])
Ll += 1
return L[n]
def struct_thm(n, i=0):
# TODO: make this loop more efficient
# it loops up to log n ^2 times
# get it down to log n by s... | nilq/baby-python | python |
import pandas as pd
## Getting the data ##
# save filepath to variable for easier access
melbourne_file_path = 'melb_data.csv'
# read the data and store data in DataFrame titled melbourne_data
melbourne_data = pd.read_csv(melbourne_file_path)
# print a summary of the data in Melbourne data
print(melbourne_data.descri... | nilq/baby-python | python |
"""Unit test package for publiquese."""
| nilq/baby-python | python |
import pandas as pd
import numpy as np
import pandas2latex_CELEX as p2l
import sys
def formatter_counts(x):
return ('%.2f' % x)
def formatter_percent(x):
return (r'%.2f\%%' % x)
def format_sublex_name(sublex_name):
return (r'\textsc{Sublex}\textsubscript{$\approx$%s}' % sublex_name)
# return (r'\textsc{Sublex}\... | nilq/baby-python | python |
"""Test dynamic width position amplitude routines."""
import jax.numpy as jnp
import numpy as np
import vmcnet.mcmc.dynamic_width_position_amplitude as dwpa
def test_threshold_adjust_std_move_no_adjustment():
"""Test that when mean acceptance is close to target, no adjustment is made."""
target = 0.5
thr... | nilq/baby-python | python |
import sys
input = sys.stdin.readline
n = int(input())
cnt = 0
for i in range(1, n + 1):
if i % 2 == 1:
cnt += 1
print(cnt / n)
| nilq/baby-python | python |
"""
Custom terminal color scheme.
"""
from django.core.management import color
from django.utils import termcolors
def color_style():
style = color.color_style()
style.BOLD = termcolors.make_style(opts = ('bold',))
style.GREEN = termcolors.make_style(fg = 'green', opts = ('bold',))
style.YELLOW = termcolors.make... | nilq/baby-python | python |
#!/usr/bin/env python3
from pathlib import Path
import shutil
import subprocess
import sys
import zipapp
script_dir = Path(__file__).parent
ficdl_path = script_dir.joinpath('ficdl')
dist = script_dir.joinpath('dist')
shutil.rmtree(dist, ignore_errors=True)
dist.mkdir()
shutil.copytree(ficdl_path, dist.joinpath('pk... | nilq/baby-python | python |
from __future__ import unicode_literals
import datetime
import json
import logging
from urllib import urlencode
from django.core.urlresolvers import reverse
from django.http.response import JsonResponse, Http404
from django.shortcuts import render, redirect
from django.template import loader
from django.utils import ... | nilq/baby-python | python |
import re
str = "Edureka"
m = re.match('(..)+',str)
print m.group(1)
print m.group(0)
| nilq/baby-python | python |
#! /usr/bin/env python
import json
import argparse
from typing import Tuple, List
import os
import sys
sys.path.insert(
0, os.path.dirname(os.path.dirname(os.path.abspath(os.path.join(__file__, os.pardir))))
)
from allennlp.common.util import JsonDict
from allennlp.semparse.domain_languages import NlvrLanguage
fr... | nilq/baby-python | python |
import sigvisa_util
from sigvisa.database import db
import numpy as np
import sigvisa.utils.geog
dbconn = db.connect()
cursor = dbconn.cursor()
sql_query = "select distinct fit.arid, lebo.lon, lebo.lat, sid.lon, sid.lat, leba.seaz, fit.azi from leb_origin lebo, leb_assoc leba, leb_arrival l, sigvisa_coda_fits fit, st... | nilq/baby-python | python |
#---------------------------------------------------------------------------
#
# Evolution.py: basics of evolutionary dynamics, Evolution chapter
#
# see Quasispecies.py and Tournament.py for application examples
#
# by Lidia Yamamoto, Belgium, July 2013
#
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -... | nilq/baby-python | python |
__version__ = '0.1.0'
from .registry_client import RegistryClient
| nilq/baby-python | python |
#encoding: utf-8
"""
Following Python and Django’s “batteries included” philosophy, Philo includes a number of optional packages that simplify common website structures:
* :mod:`~philo.contrib.penfield` — Basic blog and newsletter management.
* :mod:`~philo.contrib.shipherd` — Powerful site navigation.
* :mod:`~philo.... | nilq/baby-python | python |
import requests
from django.conf import settings
from django.http import (
Http404,
HttpResponse,
HttpResponseServerError,
JsonResponse,
StreamingHttpResponse,
)
from django.utils.translation import ugettext_lazy as _
from requests import Session
from requests.auth import HTTPBasicAuth
from rest_fra... | nilq/baby-python | python |
from random import choice
def random_placement(board, node):
"""
Chooses a placement at random
"""
available_placements = list(board.get_available_placements())
return choice(available_placements)
def check_for_win_placement(board, node):
"""
Checks if a placement can be made that leads ... | nilq/baby-python | python |
"""
Module for managing a sensor via KNX.
It provides functionality for
* reading the current state from KNX bus.
* watching for state updates from KNX bus.
"""
from xknx.remote_value import RemoteValueControl, RemoteValueSensor
from .device import Device
class Sensor(Device):
"""Class for managing a sensor.""... | nilq/baby-python | python |
"""
Workflow class that splits the prior into a gold standard and new prior
"""
import pandas as pd
import numpy as np
from inferelator_ng.utils import Validator as check
from inferelator_ng import default
def split_for_cv(all_data, split_ratio, split_axis=default.DEFAULT_CV_AXIS, seed=default.DEFAULT_CV_RANDOM_SEED... | nilq/baby-python | python |
from Crypto.Cipher import AES
obj = AES.new('hackgt{oracle_arena_sux_go_cavs}', AES.MODE_CBC, '0000000000000000')
message = "hello world"
padding = 16 - len(message)
print len(
ciphertext = obj.encrypt(message + '/x00' * 16)
print ciphertext
| nilq/baby-python | python |
import os
from scipy.io import loadmat
class DATA:
def __init__(self, image_name, bboxes):
self.image_name = image_name
self.bboxes = bboxes
class WIDER(object):
def __init__(self, file_to_label, path_to_image=None):
self.file_to_label = file_to_label
self.path_to_image = path... | nilq/baby-python | python |
# See http://cookiecutter.readthedocs.io/en/latest/advanced/hooks.html
from datetime import datetime
import io
import pathlib
import shlex
import shutil
import sys
def is_trueish(expression: str) -> bool:
"""True if string and "True", "Yes", "On" (ignorecase), False otherwise"""
expression = str(expression).... | nilq/baby-python | python |
from typing import Any, Dict, Optional
import redis
from datastore.shared.di import service_as_singleton
from datastore.shared.services import EnvironmentService, ShutdownService
# TODO: Test this. Add something like a @ensure_connection decorator, that wraps a
# function that uses redis. It should ensure, that the... | nilq/baby-python | python |
from setuptools import setup
CLASSIFIERS = [
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
'Operating System :: OS Independent',
'Topic :: Documentation',
]
setup(
name = "sphinx-autodoc-pywps",
version = "0.1",
#url = "h... | nilq/baby-python | python |
from django.test import TestCase
from booking.models import Material, RateClass
from booking.tests.factories import MaterialFactory, RateClassFactory
class RateClassModelTest(TestCase):
def test_delete_rateclass_keeps_materials(self):
rateclass = RateClassFactory()
material = MaterialFactory(rate... | nilq/baby-python | python |
import os
import time
from PIL import Image, ImageChops
import progressbar
import argparse
import utils_image
##### MAIN ############
def main():
'''
Parse command line arguments and execute the code
'''
parser = argparse.ArgumentParser()
parser.add_argument('--dataset_path', required=True, type=... | nilq/baby-python | python |
'''
* Copyright (C) 2019-2020 Intel Corporation.
*
* SPDX-License-Identifier: MIT License
*
*****
*
* MIT License
*
* Copyright (c) Microsoft Corporation.
*
* 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... | nilq/baby-python | python |
# Based on
# https://github.com/tensorflow/docs/blob/master/site/en/tutorials/keras/basic_classification.ipynb
# (MIT License)
from __future__ import absolute_import, division, print_function
from tensorflow import keras
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import os
figdir = ".... | nilq/baby-python | python |
from TASSELpy.utils.helper import make_sig
from TASSELpy.utils.Overloading import javaConstructorOverload, javaOverload
from TASSELpy.net.maizegenetics.dna.snp.score.SiteScore import SiteScore
from TASSELpy.net.maizegenetics.dna.snp.byte2d.Byte2D import Byte2D
from TASSELpy.java.lang.Integer import metaInteger
import n... | nilq/baby-python | python |
from .draw_chessboard import draw_chessboard
from .draw_chessboard import draw_tuples
| nilq/baby-python | python |
# Software License Agreement (BSD License)
#
# Copyright (c) 2012, Fraunhofer FKIE/US, Alexander Tiderko
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code mus... | nilq/baby-python | python |
"""
Question:
Remove Nth Node From End of List
Given a linked list, remove the nth node from the end of list and return its head.
For example,
Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given ... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.