content
stringlengths
0
1.05M
origin
stringclasses
2 values
type
stringclasses
2 values
import base64 import logging from tornado.escape import json_decode from tornado.web import Finish from db import UserStatus from emailer import send_verification_email, send_password_reset_email from service.property import get_property, set_property from service.user import ( get_user, get_user_profile, ...
nilq/baby-python
python
from bs4 import BeautifulSoup from collections import Counter from string import punctuation def word_frequencies(url): """ Downloads the content from the given URL and returns a dict {word -> frequency} giving the count of each word on the page. Ignores HTML tags in the response. :param url: Full URL ...
nilq/baby-python
python
import numpy as np array = np.array([['08', '02', '22', '97', '38', '15', '00', '40', '00', '75', '04', '05', '07', '78', '52', '12', '50', '77', '91', '08'], ['49', '49', '99', '40', '17', '81', '18', '57', '60', '87', '17', '40', '98', '43', '69', '48', '04', '56', '62', '00'], ['81', '49', '31', '73', '55', '79', '...
nilq/baby-python
python
import os import logging import cfn_storage_gateway_provider import cfn_cache_provider import cfn_file_share_provider log = logging.getLogger() log.setLevel(os.environ.get("LOG_LEVEL", "INFO")) def handler(request, context): if request['ResourceType'] == 'Custom::StorageGatewayNfsFileShare': return cfn_f...
nilq/baby-python
python
import matplotlib.pyplot as plt import numpy as np import numpy.random as random import re import textstat from scipy import stats from scipy.stats import spearmanr #coding:utf-8 ############### #一般図書のYL x = [8, 6.6, 8.5, 6.5, 5, 7, 6, 5, 5, 5, 6.5, 6.5, 7, 8.2, 7.6, 7.5, 7.5, 7.3, 7, 8.2, 8, 8.5, 7, 6.6, 7.7, 7...
nilq/baby-python
python
import asyncio from collections import OrderedDict import logging import uuid import msgpack import re import types from wolverine.module import MicroModule from wolverine.module.controller.zhelpers import unpackb, packb, dump from wolverine.module.service import ServiceMessage logger = logging.getLogger(__name__) c...
nilq/baby-python
python
""" Class Encore CIS 211 w/ Joseph contest.py Author: Joseph Goh Updated: 03/04/2021 """ from typing import List, Dict class Hometown: def __init__(self, name: str): self.name = name self.champions = [] def get_total_wins(self) -> int: total = 0 for champ in self.champions: ...
nilq/baby-python
python
#!/usr/bin/env python3 """ Copyright (c) 2018 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 la...
nilq/baby-python
python
'''Adapte o código do desafio #107, criando uma função adicional chamada moeda() que consiga mostrar os números como um valor monetário formatado.''' import moeda preco = float(input('Digite o preço: R$ ')) print(f'A metade de {moeda.moeda(preco)} é {moeda.moeda(moeda.metade(preco))}') print(f'O dobro de {moeda.moeda...
nilq/baby-python
python
input = open('/Users/krishjain/Desktop/AdventOfCode/Day 6/input.txt', "r").read() input = input.split("\n\n") countOfAnswersPerGroup = [] for i in input: listOfAnswersToWhichAnsweredYes = [] for j in i.replace("\n", ""): listOfAnswersToWhichAnsweredYes.append(j) unorderedListOfAnswers = list...
nilq/baby-python
python
import matplotlib.pyplot as plt env_map = [(8.92, 283.86), (17.83, 283.44), (68.13, 720.79), (112.8, 892.9), (140.79, 888.92), (101.75, 533.38), (106.89, 478.2), (115.39, 449.42), (117.73, 405.24), (111.25, 342.38), (87.73, 243.69), (113.38, 286.37), (121.92, 281.75), (124.33, 264.21), (124.39, 244.14), (125.74, 228.7...
nilq/baby-python
python
# # Copyright (c) 2013-2014 Wind River Systems, Inc. # # SPDX-License-Identifier: Apache-2.0 # import cStringIO import httplib2 import re import sys import fixtures from inventoryclient import exc from inventoryclient import shell as inventoryclient_shell from inventoryclient.tests import utils from testtools import ...
nilq/baby-python
python
# coding: utf-8 # http://gitlab.skoltech.ru/shapeev/mlip-dev/blob/master/src/external/python/mlippy/cfgs.py from __future__ import print_function import numpy as np class Cfg: pos = None lat = None types = None energy = None forces = None stresses = None desc = None grade = None def...
nilq/baby-python
python
from bitrue.client import Client if __name__ == '__main__': client = Client(api_key='', api_secret='', ) trades = client.get_my_trades() print(client._order_format_print(trades)) ''' symbol id orderId origClientOrderId price qty comm...
nilq/baby-python
python
# coding=utf-8 # Copyright 2022 The Balloon Learning Environment Authors. # # 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 require...
nilq/baby-python
python
liste = ["ali", "veli"] print(liste) if "al" not in liste: print("var")
nilq/baby-python
python
from .optim_low import * __all__ = ["OptimMP"]
nilq/baby-python
python
"""empty message Revision ID: dcbee03e3639 Revises: Create Date: 2018-07-10 04:25:35.968792 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'dcbee03e3639' down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands auto gene...
nilq/baby-python
python
from trezor import wire from trezor.messages import MessageType def boot(): # only enable LoadDevice in debug builds if __debug__: wire.add(MessageType.LoadDevice, __name__, "load_device") wire.add(MessageType.ResetDevice, __name__, "reset_device") wire.add(MessageType.BackupDevice, __name__, ...
nilq/baby-python
python
from __future__ import print_function import sys import os import requests from datetime import datetime from random import randint import re class Facegrab: def __init__(self): self.base_url = "http://graph.facebook.com/picture?id={}&width=800" self.sess = requests.Session() self.sess.hea...
nilq/baby-python
python
from polygon import WebSocketClient from polygon.websocket.models import WebSocketMessage from typing import List import asyncio c = WebSocketClient(subscriptions=["T.*"]) async def handle_msg(msgs: List[WebSocketMessage]): for m in msgs: print(m) async def timeout(): await asyncio.sleep(1) pri...
nilq/baby-python
python
import numpy as np #import tensorflow as tf from PIL import Image from PIL import ImageDraw from PIL import ImageFont from tqdm import tqdm import argparse import sys import cv2 import math rgb = True def draw_bboxes (img, boxes, outname): for i in range(len(boxes)): xmin,ymin,xmax,ymax,cat = boxes[i] c...
nilq/baby-python
python
from pylama_dmypy import VERSION from setuptools import setup, find_packages # fmt: off setup( name = "pylama-dmypy" , version = VERSION , packages = find_packages(include="pylama_dmypy.*", exclude=["tests*"]) , extras_require = { 'tests': [ "pylama==8.3.8" , "mypy==0.942" ...
nilq/baby-python
python
# -*- coding: utf-8 -*- __all__ = ('SlashCommandPermissionOverwriteWrapper', 'SlashCommandWrapper', ) from functools import partial as partial_func from ...discord.guild import Guild from ...discord.preconverters import preconvert_snowflake from ...discord.interaction import ApplicationCommandPermissionOverwrite UNL...
nilq/baby-python
python
from collections import deque, defaultdict import sys N = int(input()) ab = [] for i in range(N - 1): ab.append(tuple(map(int, input().split()))) c_list = list(map(int, input().split())) c_list.sort() c_que = deque(c_list) cnt = defaultdict(int) outs = defaultdict(list) for a, b in ab: cnt[a - 1] += 1 cn...
nilq/baby-python
python
################################################# # SN74HC595 with software SPI ESP12-E # # Sums up 1 bit by 1 bit till 255 is reached # # Author: Miguel Sama # # Date: 19/06/2018 # ################################################# from machine import...
nilq/baby-python
python
#!/usr/bin/env python # -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2008,2009,2010,2011,2012,2013,2014,2015,2016 Contributor # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with...
nilq/baby-python
python
import clr if clr.use35: clr.AddReference("Microsoft.Scripting") clr.AddReference("Microsoft.Dynamic") clr.AddReference("Microsoft.Scripting.Core") import Microsoft.Scripting.Ast as Exprs from Microsoft.Scripting.ComInterop import ComBinder from Microsoft.Scripting.Utils import (Action, Func)...
nilq/baby-python
python
import os import json, boto3 def lambda_handler(event, context): print("Trigger Event: ") print(event) region = os.environ['REGION'] elbv2_client = boto3.client('elbv2', region_name=region) available_target_groups = os.environ['AVAILABLE_TARGET_GROUPS'] arr_available_target_groups = available_...
nilq/baby-python
python
import RPi.GPIO as GPIO import time pinServo=40 GPIO.cleanup() GPIO.setmode(GPIO.BOARD) GPIO.setup(pinServo, GPIO.OUT) servo=GPIO.PWM(pinServo, 50) servo.start(0) while True: ang = int(input()) # if (ang>170 and ang < 0): # print('angulo no posible') # break # else: servo.ChangeDutyCycle((ang*12/180)) time.sleep(...
nilq/baby-python
python
from cdmanager import cd import os import shutil from pathlib import Path working_folder = '../data/tfs_rep_2/' destination_folder = '../gemFiles/rep2/' with cd(working_folder): for root, dirs, files in os.walk('./'): #print(dirs) if 'GEMout' in dirs: namedir = str(root.replace('./', '...
nilq/baby-python
python
from __future__ import annotations import decimal import re import pytest from django.core.validators import MaxValueValidator, MinValueValidator, URLValidator from rest_framework import serializers from rest_framework.fields import ( BooleanField, CharField, DateField, DateTimeField, DecimalField...
nilq/baby-python
python
from typing import Optional from pydantic import BaseModel, Field class ScopeCreate(BaseModel): scope_name: str = Field(max_length=32) description: str = Field(max_length=128) default: Optional[bool] = Field(default=False) class ScopeUpdate(BaseModel): description: str = Field(max_length=128) clas...
nilq/baby-python
python
def day2_1(): total = 0 for line in open('day2input.txt'): l, w, h = line.split('x') l, w, h = int(l), int(w), int(h) area = 2*l*w + 2*w*h + 2*h*l slack = min(l*w, w*h, h*l) total += area + slack print total def day2_2(): total = 0 for line in open('day2inpu...
nilq/baby-python
python
# PROJECT DECEMBRE 2019 # PROJECT STAR MAP / DATABASE # By Enguerran VIDAL # This file contains the database handling functions. ############################################################### # IMPORTS # #############################################################...
nilq/baby-python
python
from OpenGL.GL import * from OpenGL.GLUT import * from OpenGL.GLU import * import pydart import controller import numpy as np import pickle import action as ac from numpy.linalg import inv import mmMath state = {} state['DrawAxis'] = True state['DrawGrid'] = True state['DrawDataAbs'] = True state['DrawDataRelGlobal'] ...
nilq/baby-python
python
#!/usr/bin/python # -*- coding: UTF-8 -*- from django.conf.urls import include, url from django.contrib import admin from gps.view.index import * urlpatterns = [ url('^getPeople/$', getPeople), url('^getGPS/$', getGPS), url('^sendGPS/$', sendGPS), ]
nilq/baby-python
python
import csv import glob import math import os import sys from random import random, seed from timeit import default_timer as timer import time from statistics import mean from pathlib import Path import networkx as nx import numpy as np from scapy.layers.inet import IP, UDP from scapy.utils import PcapWriter, PcapReader...
nilq/baby-python
python
import os import sys import glob import pickle import shutil import argparse import tensorflow as tf def _int64_feature(value): return tf.train.Feature(int64_list=tf.train.Int64List(value=[value])) def _bytes_feature(value): return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value])) def read_pickle_fr...
nilq/baby-python
python
#!/usr/bin/pyton import numpy as np from matplotlib import pyplot as plt from matplotlib import animation import pdb import os directory=os.path.basename(__file__)[:-3] if not os.path.exists('texFiles/'+str(directory)): os.system('mkdir texFiles/'+str(directory)) path='texFiles/'+str(directory) """ Comparison ...
nilq/baby-python
python
import logging from contextlib import closing from typing import Any, Dict, Optional from flask_appbuilder.security.sqla.models import User from flask_babel import gettext as _ from sqlalchemy.engine.url import make_url from sqlalchemy.exc import DBAPIError, NoSuchModuleError from rabbitai.commands.base import BaseCo...
nilq/baby-python
python
""" Created on Mon Jan 18 12:34:06 2021 Note this is working with ETABs v19, comtypes v1.1.7. It is not working on my local machiene only on the remote desktop @author: aguter """ import numpy as np import os import sys import comtypes.client import matplotlib.pyplot as plt ProgramPath = r"C:\Program Files...
nilq/baby-python
python
# Copyright (c) 2021, NVIDIA CORPORATION. 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 appli...
nilq/baby-python
python
from unittest import mock from src.video_player import VideoPlayer def test_flag_video_with_reason(capfd): player = VideoPlayer() player.flag_video("amazing_cats_video_id", "dont_like_cats") out, err = capfd.readouterr() lines = out.splitlines() assert len(lines) == 1 assert "Successfully fla...
nilq/baby-python
python
from app import db from app import models from flask import Blueprint bp = Blueprint("setup", __name__) @bp.route("/", methods=["POST"], strict_slashes=False) def setup(): models.Base.metadata.create_all(db.get_engine()) return "<h1> Created DB successfully! </h1>"
nilq/baby-python
python
try: from setuptools import setup except ImportError: print("No setuptools package, using distutils.core") from distutils.core import setup import unittest def my_test_suite(): test_loader = unittest.TestLoader() test_suite = test_loader.discover('tests', pattern='test_*.py') return test_suite setup...
nilq/baby-python
python
from .compare_gw import *
nilq/baby-python
python
from django import forms from django.forms import widgets from django.utils.translation import ugettext as _ from .models import Organization from .utils import get_data_source_model class OrganizationForm(forms.ModelForm): class Meta: model = Organization fields = ( 'data_source', '...
nilq/baby-python
python
import inspect import sys import threading from typing import Callable, Union, TypeVar, Any, Generic, Optional, List, Iterable class PromiseResolver: __slots__ = ("_promise", ) def __init__(self, promise): self._promise = promise def resolve(self, val): if self._promise is None: return self._promise._re...
nilq/baby-python
python
from __future__ import annotations import multiprocessing import queue import threading import time from dataclasses import dataclass, field from multiprocessing import Queue, Process from queue import Empty from threading import Thread from typing import List, Dict import psutil import requests from MHDDoS.attack i...
nilq/baby-python
python
from .convscore_solver import SolverConvScore import torch from utils import to_var from tqdm import tqdm from math import isnan import numpy as np class SolverConvScoreSSREM(SolverConvScore): def __init__(self, config, train_data_loader, eval_data_loader, is_train=True, model=None): super(SolverConvScore...
nilq/baby-python
python
import numpy as np import cv2 as cv def cv_imshow(title='Res',img=None): print(img.shape) cv.imshow(title,img) cv.waitKey(0) cv.destroyAllWindows() def image_normalization(img, img_min=0, img_max=255): """This is a typical image normalization function where the minimum and maximum of the imag...
nilq/baby-python
python
# Lint as: python3 # Copyright 2020 DeepMind Technologies Limited. 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 # # ...
nilq/baby-python
python
#!/usr/bin/env python from __future__ import print_function import math import rospy from geometry_msgs.msg import Twist from nav_msgs.msg import Odometry from b2_logic.nodes.pilot import PilotNode, PVelocityController from b2.msg import Proximity DEFAULT_NODE_NAME = "pilot_node" # Subscribes DEFAULT_PROXIMITY_TOP...
nilq/baby-python
python
from aws_cdk import ( aws_s3 as s3, core ) class CdkExampleS3Stack(core.Stack): def __init__(self, scope: core.Construct, construct_id: str, **kwargs) -> None: super().__init__(scope, construct_id, **kwargs) bucket = s3.Bucket( self, "mytestbucket", bucket_name="m...
nilq/baby-python
python
""" opencadd.io.core Defines the base class for the io module. """ from pathlib import Path class _Base: """ Base class for io classes. """ def __init__(self): """ This class contains no __init__ initialization. """ raise RuntimeError("This class only support initia...
nilq/baby-python
python
from django.test import TestCase from django.template import Template, Context class TemplateTagTest(TestCase): def setUp(self): pass def test_tag(self): content = ( "{% load logical_rules_tags %}" "This is a {% testrule test_is_pizza 'pizza' %}test{% e...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -* import urllib2 import urllib import cookielib import re from config import WEIBO_ACCOUNT, WEIBO_PWD class Fetcher(object): def __init__(self, username=None, pwd=None, cookie_filename=None): self.cj = cookielib.LWPCookieJar() if cookie_filename is not ...
nilq/baby-python
python
""" Pop does not care what it is removing in case of set Since set is an unordered collection """ from prescription_data import patients trial_patients = {'Denise', 'Eddie', 'Frank', 'Georgia', 'Kenny'} while trial_patients: patient = trial_patients.pop() print(patient, end=':') prescription = patients[pa...
nilq/baby-python
python
# Copyright 2016-2017 SAP SE # # 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
import argparse import pymongo import uuid import datetime import pprint import copy from datetime import timedelta from starflyer import ScriptBase from camper.app import markdownify from logbook import Logger log = Logger('Migration') def daterange(start_date, end_date): for n in range(int ((end_date - start_d...
nilq/baby-python
python
import json from datetime import datetime import time import PySimpleGUI as sg import os import keyring # for password storage import hashlib # import all the custom functions from functionalities import * # import all the window formats from windows import * if __name__ == "__main__" : # check if...
nilq/baby-python
python
#To test how fast rotations.py is from rotations import * import numpy as np from timeit import default_timer as timer ranx5 = np.random.randint(10,size=(100000,3)) ranx6 = np.random.randint(10,size=(1000000,3)) ranx7 = np.random.randint(10,size=(10000000,3)) ranx8 = np.random.randint(10,size=(100000000,3)) start = t...
nilq/baby-python
python
from os import getenv, getppid, kill, system from configparser import ConfigParser from typing import Union, Optional from psutil import process_iter from datetime import datetime from subprocess import Popen from signal import SIGHUP from pathlib import Path from sys import platform from re import match from typer im...
nilq/baby-python
python
import stanza from stanza.protobuf import DependencyEnhancerRequest, Document, Language from stanza.server.java_protobuf_requests import send_request, add_sentence, JavaProtobufContext ENHANCER_JAVA = "edu.stanford.nlp.trees.ud.ProcessUniversalEnhancerRequest" def build_enhancer_request(doc, language, pronouns_patt...
nilq/baby-python
python
from .pygbe import *
nilq/baby-python
python
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from ... import _utilities __...
nilq/baby-python
python
import carla from leaderboard.envs.map_utils import * def viz(args): client = carla.Client('localhost', 2000) client.set_timeout(10.0) world = client.load_world(args.town_name) carla_map = world.get_map() spawn_points = carla_map.get_spawn_points() blueprint_library = world.get_bluepri...
nilq/baby-python
python
import os import os.path as path import shutil import unittest from cache import Cache, format_as_timestamp from pathlib import Path from datetime import datetime, timedelta test_folder = 'test-files' db_file_name = path.join(test_folder, 'test.db') table_name = 'cache' folder_path = path.join(test_folder...
nilq/baby-python
python
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django.db.models.deletion from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('api', '0...
nilq/baby-python
python
import time import torch import numpy as np import pandas as pd import scipy from h5py import File import itertools, random from tqdm import tqdm from loguru import logger import torch.utils.data as tdata from typing import List, Dict class TrainHDF5Dataset(tdata.Dataset): """ HDF5 dataset indexed by a labels...
nilq/baby-python
python
import utils.train as train class DataSet: def __init__(self, config, problem): self.config = config self. problem = problem self.update() def update(self): if not self.config.test: y_, x_, y_val_, x_val_ = ( train.setup_input_sc( ...
nilq/baby-python
python
import json from pathlib import Path from typing import Dict import pandas as pd import sha_calc as sha_calc from gmhazard_calc.im import IM from gmhazard_calc import gm_data class BranchUniGCIM(sha_calc.UniIMiDist, sha_calc.CondIMjDist): """Represents the GCIM for a specific IMi and branch Parameters: ...
nilq/baby-python
python
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! import grpc from google.ads.google_ads.v4.proto.resources import campaign_bid_modifier_pb2 as google_dot_ads_dot_googleads__v4_dot_proto_dot_resources_dot_campaign__bid__modifier__pb2 from google.ads.google_ads.v4.proto.services import campaign_bid_...
nilq/baby-python
python
import os import matplotlib.pyplot as plt import matplotlib.pylab as pylab import time from subprocess import Popen, PIPE import numpy as np import pickle N = 20 def fail_if_error(error): if error: print(error) raise AssertionError() def remove_min_max(x): trimmed = x[:] trimmed.remove(ma...
nilq/baby-python
python
from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse from .validators import validate_file_size # Create your models here. #this models.py file means realtional table or schema in the databse and title, content etc are fields in the...
nilq/baby-python
python
import pathlib from typing import Callable, Union import click __version__ = "21.5.16" APP_NAME = "cldb" app_dir = pathlib.Path(click.get_app_dir(APP_NAME, roaming=False, force_posix=True)) cache_root = app_dir / "cache" config = { "bs_features": "lxml", } from . import models # noqa: E402 SpecFetcher = Cal...
nilq/baby-python
python
#!/usr/bin/env python # Copyright 2016 DIANA-HEP # # 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 a...
nilq/baby-python
python
import time from environment_server.actor_data import ActorData import traceback def replay_buffer_process(params, batch_sizes, batch_addresses, transition_queue, replay_lock): try: from replay_buffer import replay_client import random batch_data = [ActorData(params, b, a) for b, a in zip(...
nilq/baby-python
python
# (C) Copyright 2007-2021 Enthought, Inc., Austin, TX # All rights reserved. # # This software is provided without warranty under the terms of the BSD # license included in LICENSE.txt and may be redistributed only under # the conditions described in the aforementioned license. The license # is also available online at...
nilq/baby-python
python
# Models import tensorflow as tf import numpy as np from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2_as_graph import time import pickle import os import sklearn from sklearn.ensemble import RandomForestRegressor os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' import warnings war...
nilq/baby-python
python
import networkx as nx import numpy as np import matplotlib.pyplot as plt n = {'nodes':20,'edges':3} G = nx.barabasi_albert_graph(n['nodes'],n['edges']) max_degree = max(nx.degree(G).values()) min_sigmoid = 0.5 max_sigmoid = np.exp(1)/(1.+np.exp(1)) degrees = nx.degree(G) sigmoid = lambda value: (1./(1+np.exp(-valu...
nilq/baby-python
python
#!/usr/bin/python2 import optparse import os import shutil import stat import subprocess import sys from builds.GpBuild import GpBuild def install_gpdb(dependency_name): status = subprocess.call("mkdir -p /usr/local/gpdb", shell=True) if status: return status status = subprocess.call( "ta...
nilq/baby-python
python
''' Pulls segmentation masks from the database and exports them into folders with specifiable format (JPEG, TIFF, etc.). 2019 Benjamin Kellenberger ''' import os import argparse if __name__ == '__main__': parser = argparse.ArgumentParser(description='Export segmentation map annotations from databa...
nilq/baby-python
python
# -*- coding: utf-8 -*- from django.contrib.auth.models import User from django.urls import reverse from django.test import TestCase, Client import base64 import mock import adal class AuthTestCase(TestCase): client = Client() home_url = reverse('home') auth_url = reverse('auth') auth_ip_url = reverse...
nilq/baby-python
python
from tempfile import NamedTemporaryFile from ..cache import get_cache_key, get_hexdigest, get_hashed_mtime from ..utils import compile_less from ..settings import LESS_EXECUTABLE, LESS_USE_CACHE,\ LESS_CACHE_TIMEOUT, LESS_ROOT, LESS_OUTPUT_DIR, LESS_DEVMODE,\ LESS_DEVMODE_WATCH_DIRS from django.conf import sett...
nilq/baby-python
python
import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="deepof", version="0.1.4", author="Lucas Miranda", author_email="lucas_miranda@psych.mpg.de", description="deepof (Deep Open Field): Open Field animal pose classification tool ", long_d...
nilq/baby-python
python
import pygame pygame.font.init() class Font(): title = pygame.font.SysFont('Arial', 60) place = pygame.font.SysFont('Arial', 32) normal_text_large = pygame.font.SysFont('Arial', 32) normal_text_small = pygame.font.SysFont('Arial', 24) card_energy = pygame.font.SysFont('Arial', 28) card_name = ...
nilq/baby-python
python
#!/usr/bin/env python # # file: Connection.py # author: Cyrus Harrison <cyrush@llnl.gov> # created: 6/1/2010 # purpose: # Provides a 'Connection' class that interacts with a redmine instance to # extract results from redmine queries. # import urllib2,urllib,csv,getpass,warnings from collections import namedtuple fr...
nilq/baby-python
python
# -*- coding: utf-8 -*- """ Created on Thu Mar 2 17:33:00 2017 @author: spauliuk """ """ File ODYM_Functions Check https://github.com/IndEcol/ODYM for latest version. Contains class definitions for ODYM standard abbreviation: msf (material-system-functions) dependencies: numpy >= 1.9 scipy >= 0.14 Reposi...
nilq/baby-python
python
import inspect class ExecutionOrder(): """An Enum that is used to designate whether a TestSet's tests need to be run sequentially or can be run in any order.""" UNORDERED = 0 SEQUENTIAL = 1 class TestSet(): """A very general class that represents an arbitrary set of tests. By default each tes...
nilq/baby-python
python
from . import EncodedNumber from . import RandomizedIterativeAffine from phe import paillier
nilq/baby-python
python
""" data generator class """ import os import numpy as np import cv2 import copy from LibMccnn.util import readPfm import random from tensorflow import expand_dims #import matplotlib.pyplot as plt from skimage.feature import local_binary_pattern class ImageDataGenerator: """ input image patch pairs gen...
nilq/baby-python
python
import pytest xgcm = pytest.importorskip("xgcm") from xarrayutils.build_grids import rebuild_grid from numpy.testing import assert_allclose from .datasets import datagrid_dimtest, datagrid_dimtest_ll @pytest.mark.parametrize( "test_coord", ["i", "j", "i_g", "j_g", "XC", "XG", "YC", "YG", "dxC", "dxG", "dyC",...
nilq/baby-python
python
#!/usr/bin/env python from mailanalyzer import statistics from mailanalyzer import parsing from collections import defaultdict import datetime import csv import time # path to directory with Dovecot mailing list archive dir_name = '' # output path output = 'output/dovecot/{}_'.format(time.strftime('%Y%m%d_%H%M')) # ...
nilq/baby-python
python
# -*- coding: utf-8 -*- """ Train a simple deep ResNet on the UPavia 2D dataset. Exception: Only layers of same output shape can be merged using sum mode. Layer shapes: [(None, 7, 7, 128), (None, 4, 4, 128)] """ from keras.datasets import cifar10 from keras.preprocessing.image import ImageDataGenerator from keras.uti...
nilq/baby-python
python
import numpy as np from datetime import datetime from twisted.internet.defer import inlineCallbacks from EGGS_labrad.lib.clients.cryovac_clients.RGA_gui import RGA_gui class RGA_client(RGA_gui): name = 'RGA Client' BUFFERID = 289961 def __init__(self, reactor, cxn=None, parent=None): super().__...
nilq/baby-python
python
import glob import os import getpass print(" ------------------------\n| Piggy's Trolling Tools: |\n| :-: File Deleter :-: |\n ------------------------\n") where = input("Input directory where files should be deleted: ") regex = input("Enter regex to match files (example: important*.txt): ") os.chdir(whe...
nilq/baby-python
python
""" Basic atmosphere functions This dark flight model predicts the landing sight of a meteoroid by propagating the position and velocity through the atmosphere using a 5th-order adaptive step size integrator (ODE45). Created on Mon Oct 17 10:59:00 2016 @author: Trent Jansen-Sturgeon """ import numpy as np from scipy.i...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- import _env # noqa from controller._base import AdminHandler from misc._route import route @route('/category') class Index(AdminHandler): def get(self): self.render()
nilq/baby-python
python