content
stringlengths
0
1.05M
origin
stringclasses
2 values
type
stringclasses
2 values
import sys from twython import Twython import time import json import os import re import dropbox import subprocess # Secret Keys apiKey = "" apiSecret = "" accessToken = "" accessTokenSecret = "" api = Twython(apiKey,apiSecret,accessToken,accessTokenSecret) tweet = api.get_mentions_timeline() results = api.search(q...
nilq/baby-python
python
# -*- coding: utf-8 -*- # @Author: Sam Zhang # @Date: 2020-04-12 15:36:23 # @Last Modified by: Sam Zhang # @Last Modified time: 2020-04-14 11:27:50 from flask import render_template, request, redirect, url_for from ..utils import google_search from . import google @google.route('/', methods=['GET', 'POST']) def ...
nilq/baby-python
python
""" Merge spotify playlists. """ import argparse import logging from playlist import Playlist def spunify(destination_playlist: str, source_playlists: set[str]): """ Merge the source playlists into the destination playlist. :param destination_playlist: The url of the playlist where the tracks w...
nilq/baby-python
python
#!/usr/bin/python3 import random import math import numpy as np """ Constants """ variance = 0.01 CHECKERBOARD_SIZE = 0.2 """ Functions """ # def get_swiss_roll_dataset(numOfSamples): # sample_list = [] # label_list = [] # for x in range(0, numOfSamples): # # noise_test = random.random() # ...
nilq/baby-python
python
#take1 pre = '581634BED11C647479ED07B47702E21EFE8147CFA57BF08E105A81852F70CF2ADD01B9E8191622AA5CAB3129D7B5F9EB007C2AA98E48E6E4793BD624F94D40B6B07072A17748A96153C6681716D8593261DD8E5CD6ADEE644D432BD282CB521FA4EBF64109D79A60EFA887D7E8EBE5EB9B43F16F84CBC705D12D1CD429B0166B' get = ['7rJ1loTd72z8fyA71JWAYODTEPL1TEIbBSXd0O...
nilq/baby-python
python
# -*- coding: utf-8 -*- """ DEPRECATED """ from __future__ import division, print_function import numpy as np from theano import gof import theano.tensor as tt __all__ = ["tensordotDOp"] class tensordotDOp(tt.Op): def __init__(self, func): self.func = func self._grad_op = tensordotDGradientOp(...
nilq/baby-python
python
# -*- coding: utf-8 -*- """ magic is a wrapper around the libmagic file identification library. See README for more information. Usage: >>> import magic >>> magic.from_file("testdata/test.pdf") 'PDF document, version 1.2' >>> magic.from_file("testdata/test.pdf", mime=True) 'application/pdf' >>> magic.fr...
nilq/baby-python
python
# Copyright 2017 The Bazel Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable la...
nilq/baby-python
python
# -*- coding: utf-8 -*- from __future__ import absolute_import # -- stdlib -- # -- third party -- import gevent # -- own -- # -- code -- def instantiate(cls): return cls() def spawn_autorestart(*args, **kwargs): def restart(g): gevent.sleep(1) spawn_autorestart(*args, **kwargs) gevent...
nilq/baby-python
python
from rest_framework.exceptions import MethodNotAllowed from api.sparse.serializers import SparseNodeSerializer, SparseRegistrationSerializer from api.nodes.views import ( NodeDetail, NodeChildrenList, NodeList, LinkedNodesList, NodeLinkedRegistrationsList, ) from api.registrations.views import Regi...
nilq/baby-python
python
# The sole purpose of this method is to convert the .dbf file that we have # received which contains all addresses in the city to a .csv file import dbfread as dbf #To read our .dbf file import csv #To write to .csv def convert_addresses_to_csv(): with open('addresses.csv', 'wb') as csvfile: headere...
nilq/baby-python
python
# pylint:disable=inconsistent-return-statements """ This module provides a class to visualise Click CLI structures """ import io from contextlib import redirect_stdout from copy import deepcopy from typing import Union, Dict, Any, List import treelib from click import Group, MultiCommand from click_tree_viz.click_...
nilq/baby-python
python
from pprint import pformat import click import py42.sdk.queries.fileevents.filters as f from click import echo from pandas import DataFrame from py42.exceptions import Py42InvalidPageTokenError from py42.sdk.queries.fileevents.file_event_query import FileEventQuery from py42.sdk.queries.fileevents.filters import Inser...
nilq/baby-python
python
import os import sys sys.path.append(".") from Utils.HTMLTestRunner import * from Testcases.test_login import Login from Testcases.test_02 import Test02 # get the directory path to output report file dir = os.getcwd() # get all tests from Login class login1 = unittest.TestLoader().loadTestsFromTestCase(Login) test02...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- import unittest import dictc class DictCTest(unittest.TestCase): def setUp(self): pass class BaseDictTest(unittest.TestCase): def setUp(self): from DictC.BaseDict import strip_tags self.strip_tags = strip_tags import re se...
nilq/baby-python
python
from .clusterer import Clusterer class ClusterMerge(): def __init__(self, config): self.clusterer = Clusterer(**config) self.pattern_generator = self.clusterer.pattern_generator def merge(self, base_list, other_list): for [reprA, countA, patternA, linesA] in other_list: ex...
nilq/baby-python
python
from setuptools import setup, find_namespace_packages setup(name='sog', version='0.1', description='A creative remake of the 80s MUD', url='', author='Jason Newblanc', author_email='<first>.<last>(at)gmail.com', license='CC0 1.0', packages=find_namespace_packages(include=['sog...
nilq/baby-python
python
''' Util module to initialize SimpleML and configure database management ''' __author__ = 'Elisha Yadgaran' # Import table models to register in DeclaritiveBase from simpleml.persistables.base_persistable import Persistable import simpleml.datasets.base_dataset import simpleml.pipelines.base_pipeline import simpleml...
nilq/baby-python
python
""" Functions and objects describing electro-optic components. """ from arch.block import Block from arch.models.model import Linear, SymbolicModel from sympy import Matrix, sqrt, exp, I, pi import arch.port as port class Switch2x2(Block): """ extinction_ratio: ratio of desired signal to undesired signal from wron...
nilq/baby-python
python
# """ # All operations for the Electricity Spot Market # Based on the role ClearIterativeCO2AndElectricitySpotMarketTwoCountryRole # # Jim Hommes - 25-3-2021 # """ # import json # from modules.marketmodule import MarketModule # from util.repository import Repository # # # class ElectricitySpotMarketSubmitBids(MarketMod...
nilq/baby-python
python
""" Simple integration tests on the API itself. We make actual ajax requests to the running docker container. """ import os import json import unittest import requests from dotenv import load_dotenv load_dotenv('.env') # The URL of the running server from within the docker container url = 'http://web:5000' service_...
nilq/baby-python
python
# -*- coding: utf-8 -*- """ Python File Template """ import os import string from onmt.keyphrase.pke.utils import compute_document_frequency exec('from __future__ import unicode_literals') import os import sys import random module_path = os.path.abspath(os.path.join('../')) if module_path not in sys.path: sys...
nilq/baby-python
python
#!/usr/bin/env python3 # test_app.py import unittest from unittest.mock import patch from snakegame import app from snakegame.player import Player class TestApp(unittest.TestCase): def setUp(self): self.name = "Bob" self.score = 0 self.high_score_name = "John" self.high_score =...
nilq/baby-python
python
"""Add table for datapath Revision ID: ce8079bf4ab7 Revises: None Create Date: 2017-08-26 21:42:40.469444 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'ce8079bf4ab7' down_revision = None branch_labels = None depends_on = None def upgrade(): op.create_t...
nilq/baby-python
python
"""Mock objects for testing""" SUBMISSION_POST_DATA = { "submission": { "_id": "random_string_from_formio", "data": { "project_name": "123 Market St.", "email": "test@test.com", "phone": "415-867-5309", "name": "Jenny" } } }
nilq/baby-python
python
# Python3 import sys import shutil from pathlib import Path # Get the root path to this repo repo_dir = Path(__file__).parent # Get the os dependant kits path if sys.platform == "win32": install_path = Path(r"~\AppData\Roaming\Luxology\Kits").expanduser() elif sys.platform == "darwin": install_path = Path("...
nilq/baby-python
python
from sqlalchemy.ext.asyncio import AsyncSession from app.crud import dialogue_crud from app.service import dialogue_exist async def get_all_dialogues_for_user(db: AsyncSession, user_id: int): """ Get all dialogues for user :param db: DB :type db: AsyncSession :param user_id: User ...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_compartmentmodels ---------------------------------- Tests for `compartmentmodels` module. The tests for the individual models are in separate files. """ import pytest #import tempfile import os import numpy as np from compartmentmodels.compartmentmodels imp...
nilq/baby-python
python
from typing import Optional from typing import Union import attr @attr.s class Attachment: content_type = attr.ib(type=str) id = attr.ib(type=str) size = attr.ib(type=int) stored_filename = attr.ib(type=str) @attr.s class Reaction: emoji = attr.ib(type=str) target_author = attr.ib(type=Unio...
nilq/baby-python
python
#!/usr/bin/python # coding: utf-8 # Copyright 2018 AstroLab Software # Author: Chris Arnault # # 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...
nilq/baby-python
python
from ast import literal_eval from database.model_people import ModelPeople from database.model_planet import ModelPlanet from database import base import logging import sys # Load logging configuration log = logging.getLogger(__name__) logging.basicConfig( stream=sys.stdout, level=logging.INFO, format='%(a...
nilq/baby-python
python
import numpy.random as rd import numpy as np from display import * from solver import * def init_list(N): balls = [] r = 10. v = 10. x = 400./float(N+1) for i in range(N): m = r*(1.-0.05*i) vv = [-1.*v, 1.*v] vx = [float(i+1)*x, float(i+1)*x] balls.append(Ball(m, m, ...
nilq/baby-python
python
''' source-directory /etc/network/interfaces.d auto lo iface lo inet loopback auto eth0 iface eth0 inet manual allow-hotplug ppp0 iface ppp0 inet wvdial post-up echo "cellular (ppp0) is online" allow-hotplug wlan0 iface wlan0 inet manual wpa-roam /etc/wpa_supplicant/wpa_supplicant.conf allow-hotplug wlan1 iface w...
nilq/baby-python
python
import torch from PIL import Image import numpy as np from torchvision import datasets, models, transforms import os import glob from models import DoveNetG transformsC = transforms.Compose([transforms.Resize((512, 512)), transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]) transformsG = tra...
nilq/baby-python
python
""" Desafio 011 Problema: Faça um programa que leia a largura e a altura de uma parede em metros, calcule a sua área e a quantidade de tinta necessária para pintá-la, sabendo que cada litro de tinta pinta uma área de 2 metros quadrados""" l = float(input('Digite a largura: ')) a = float(i...
nilq/baby-python
python
import torch import torch.nn as nn class FactorizedReduce(nn.Module): """ Reduce feature map size by factorized pointwise(stride=2). """ def __init__(self, C_in, C_out, affine=True): super().__init__() self.relu = nn.ReLU() self.conv1 = nn.Conv2d(C_in, C_out // 2, 1, stride=2, p...
nilq/baby-python
python
from typing import Union, List, Optional from pyspark.sql.types import StructType, StructField, StringType, ArrayType, DataType # This file is auto-generated by generate_schema so do not edit manually # noinspection PyPep8Naming class DetectedIssueSchema: """ Indicates an actual or potential clinical issue w...
nilq/baby-python
python
# simple no arg function def simple_function(): print 'Hello, function!' simple_function() # simple function with argument def fib(n): a, b = 0, 1 while a < n: print a, a, b = b, a+b fib(10) print '' # example of using documentation string (so-called docstring) def other_function(): """Simple gibbrish print...
nilq/baby-python
python
import pytest from pytest import raises from vyper import compiler from vyper.exceptions import InvalidType, UnknownType fail_list = [ """ x: bat """, """ x: HashMap[int, int128] """, """ x: [bar, baz] """, """ x: [bar(int128), baz(baffle)] """, """ struct A: b: B struct B: ...
nilq/baby-python
python
import os, sys import numpy as np from env_handler import EnvHandler from q_function import Q from logger import Logger from agent import Agent from action_selectors.mbie_eb import MBIE_EB from action_selectors.epsilon_greedy import EpsilonGreedy from action_selectors.boltzmann import Boltzmann from action_selectors.uc...
nilq/baby-python
python
#!/bin/python import sys import yaml import datetime if __name__ == '__main__': filename = sys.argv[1] if len(sys.argv) > 1 else '/Volumes/Kea/devel/MOSSCO/code/external/fabm/code/util/standard_variables/variables.yaml' if not filename: sys.exit(1) with open(filename, 'r') as fid: yml = yaml....
nilq/baby-python
python
import pandas as pd from scholarly import scholarly import plotly.express as px def search_author(name, return_list=False): search_query = scholarly.search_author(name) if not return_list: return next(search_query) else: return list(search_query) def search_author_id(id): try: ...
nilq/baby-python
python
from Tkinter import * from common import Codes from ..controllers import AdminDataController from ..handlers.data import Data class Admin(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.elements = {} title_frame = Frame(self) tit...
nilq/baby-python
python
# Import library(toolkit) for deep learning import numpy as np import os import torch import torch.nn as nn import torchvision.transforms as transforms from torch.utils.data import DataLoader, Dataset import pytorchtools as tools import pandas as pd import time import myfunctions as my # read data workspace_dir = './o...
nilq/baby-python
python
# -*- coding: utf-8 -*- """ Created on Sun Apr 5 04:53:01 2020 @author: Infraestructura 3D """ """ 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 limitatio...
nilq/baby-python
python
from django.core.cache import cache from django.test import Client, TestCase from django.urls import reverse class MoviesTest(TestCase): def setUp(self): self.client = Client() cache.clear() def test_view_movies_correct_template(self): """check if the right template is called""" ...
nilq/baby-python
python
#!usr/env/bin python3 interface = input("enter your interface>>") mac = input("enter new mac>>") print (" ") print ("--------------------------------------------------------------------------") import subprocess subprocess.call("ifconfig " + interface + " down",shell=True) subprocess.call("ifconfig " + i...
nilq/baby-python
python
""" Horizontal boxplot with observations ==================================== _thumb: .7, .45 """ import numpy as np import seaborn as sns sns.set(style="ticks", palette="muted", color_codes=True) # Load the example planets dataset planets = sns.load_dataset("planets") # Plot the orbital period with horizontal boxes...
nilq/baby-python
python
# Generated by Django 3.1 on 2020-08-26 08:48 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('mining', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='match_key', name='MK_key_type', ), ...
nilq/baby-python
python
from flask import Blueprint bp = Blueprint("StCourierServer", __name__, url_prefix="/master") from . import view
nilq/baby-python
python
# # This file is part of the PyMeasure package. # # Copyright (c) 2013-2022 PyMeasure Developers # # 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 limit...
nilq/baby-python
python
"""protected field on Address Revision ID: 427743e76984 Revises: f8c342997aab Create Date: 2021-02-02 11:39:45.955233 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '427743e76984' down_revision = 'f8c342997aab' branch_labels = None depends_on = None def upgr...
nilq/baby-python
python
import binance from config import BINANCE_API_KEY, BINANCE_API_SECRET async def connect(): binance_client = binance.Client(BINANCE_API_KEY, BINANCE_API_SECRET) await binance_client.load() return binance_client
nilq/baby-python
python
#!/usr/bin/python import os import pyopencl as cl import numpy as np # initialize OpenCL def initCl(): PACKAGE_PATH = os.path.dirname( os.path.realpath( __file__ ) ); print(PACKAGE_PATH) #CL_PATH = os.path.normpath( PACKAGE_PATH + '../../cl/' ) CL_PATH = os.path.normpath( PACKAGE_PATH + '/../cl' ) ...
nilq/baby-python
python
# -*- coding: utf-8 -*- import sfml as sf WIDTH = 640 HEIGHT = 480 TITLE = "Python SFML Events" window = sf.RenderWindow(sf.VideoMode(WIDTH, HEIGHT), TITLE) while window.is_open: for event in window.events: if type(event) is sf.CloseEvent: window.close() if type(event) is sf.MouseMov...
nilq/baby-python
python
from flask import Flask, request app = Flask(__name__) def getAllPuppies(): return "Getting All the puppies!" def makeANewPuppy(): return "Creating A New Puppy!" def getPuppy(id): return "Getting Puppy with id {}".format(id) def updatePuppy(id): return "Updating Puppy with id {}".format(i...
nilq/baby-python
python
import numpy as np import matplotlib.pylab as pl pl.rcParams['pdf.fonttype'] = 42 pl.rcParams['ps.fonttype'] = 42 fig = pl.figure(figsize=(12,4)) ax = fig.add_subplot(1,2,1) def plot_perf(nlist, err, color, label, errbar=False, perc=20): pl.loglog(nlist, err.mean(0), label=label, color=color) if errbar: ...
nilq/baby-python
python
from __future__ import unicode_literals __all__ = ['core','util'] import os import warnings import ruamel.yaml as yaml __author__ = "Pymatgen Development Team" __email__ ="pymatgen@googlegroups.com" __maintainer__ = "Shyue Ping Ong" __maintainer_email__ ="shyuep@gmail.com" __version__ = "2017.8.16" SETTINGS_FILE = ...
nilq/baby-python
python
import json import requests import xlrd SOURCES = ( ('awois_wrecks', 'http://wrecks.nauticalcharts.noaa.gov/downloads/AWOIS_Wrecks.xls'), ('enc_wrecks', 'http://wrecks.nauticalcharts.noaa.gov/downloads/ENC_Wrecks.xls'), ) if __name__ == '__main__': for source_item in SOURCES: # Source and URL ...
nilq/baby-python
python
__author__ = 'arjun010' from visObject import * from chartDataFormatter import * from dataFactGenerator import * from itertools import combinations, permutations def getPossibleVisualizations(attributeList, dataList, metadataMap): possibleVisualizations = [] possibleDataFacts = [] itemAttribute = None # i...
nilq/baby-python
python
from __future__ import division # X é o numero no qual queremos a raiz quadrada # I quantidade de interações def calc_raizq(x, chute, i): if i < 1: raise ValueError("É necessário pelo menos uma iteração") if chute < 1: chute = 1 if x < 0: return complex(0, calc_raizq(-x, chute, i)...
nilq/baby-python
python
############################################################################ # Copyright ESIEE Paris (2019) # # # # Contributor(s) : Giovanni Chierchia, Benjamin Perret # # ...
nilq/baby-python
python
import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F import pytorch_lightning as pl class Net(pl.LightningModule): def __init__(self): super(Net, self).__init__() self.layer1 = nn.Linear(28*28, 1024) self.layer2 = nn.Linear(1024, 128) se...
nilq/baby-python
python
def foo(x): return x*x y = [1,2,3,4,5] z = list(map(foo,y)) for val in z: print(val)
nilq/baby-python
python
# -*- coding: utf-8 -*- __author__ = "Michele Samorani" import pandas as pd import cplex import time import random TIME_LIMIT_SECONDS = 60 def build_scenarios(show_probs, max_scenarios,seed): """ Builds the scenarios :param show_probs: :type show_probs: list[float] :return: a list of (probability,...
nilq/baby-python
python
# This file is part of the Etsin service # # Copyright 2017-2018 Ministry of Education and Culture, Finland # # :author: CSC - IT Center for Science Ltd., Espoo Finland <servicedesk@csc.fi> # :license: MIT """Language and translation utilities""" from flask import request, session from etsin_finder.auth.authenticatio...
nilq/baby-python
python
import pygame; from .drawable import Drawable; # --------------------------------------------------- *\ # [class] Image() # # * Image element * # # --------------------------------------------------- */ class Image(Drawable): # --------------------------------------------------- *\ # [function] __init__(): # # ...
nilq/baby-python
python
""" This file contains all the sales related resources """ # Third party imports from flask import request, json, abort from flask_restplus import Resource from flask_jwt_extended import jwt_required, get_jwt_identity # Local application imports from app.api.v1.models.sales import Sale from app.api.v1.models.db imp...
nilq/baby-python
python
from flask import Flask, render_template,request, session , redirect , url_for , g,flash, jsonify, make_response, json,flash from flask_mail import Mail,Message from flask_cors import CORS from pusher import pusher from flask_wtf import FlaskForm from wtforms import (StringField ,PasswordField,SubmitField) from w...
nilq/baby-python
python
#!/usr/bin/env python3 # ----------------------------------------------------------------------- # VIZPAIRWISESEQ # Copyright 2015, Stephen Gould <stephen.gould@anu.edu.au> # ----------------------------------------------------------------------- # Script to visualize an integer sequence based on the visualization of #...
nilq/baby-python
python
import sys sys.path.append("../bundle_adjustment/ceres-solver/ceres-bin/lib/") # so import PyCeres import numpy as np import scipy.io as sio import cv2 from utils import geo_utils def order_cam_param_for_c(Rs, ts, Ks): """ Orders a [m, 12] matrix for the ceres function as follows: Ps_for_c[i, 0:3] 3 para...
nilq/baby-python
python
"""Turrets and torpedo mpunt data in a useable form""" from schemas import TURRETS class Turret: """Container for the data needed to draw a turret Args: caliber (int): caliber of the gun in inches (urgh) pos (string): the letter of the turret, like "A", "X", etc... positio...
nilq/baby-python
python
# Copyright (c) 2021, Carlos Millett # All rights reserved. # This software may be modified and distributed under the terms # of the Simplified BSD License. See the LICENSE file for details. import abc from pathlib import Path from .types import Types class Media(abc.ABC): def __init__(self, media_type: Type...
nilq/baby-python
python
class Solution(object): def minDistance(self, w1, w2): if w1 == "": return len(w2) if w2 == "": return len(w1) l1 = len(w1) l2 = len(w2) d=[] for i in range(l1+1): d.append([0] * (l2 + 1)) for i in range(0, l1 + 1): ...
nilq/baby-python
python
import math import os import time import unicodedata from pyrogram.errors import MessageNotModified from help.progress import humanbytes, TimeFormatter import requests from config import Config from tqdm.utils import CallbackIOWrapper from pathlib import Path from tqdm.contrib.telegram import tqdm CHUNK_SI...
nilq/baby-python
python
import click from flask.cli import with_appcontext from goslinks.db.factory import get_model @click.command() @with_appcontext def migrate(): """Creates and migrates database tables.""" for model_name in ("user", "link"): model = get_model(model_name) click.echo(f"Creating table {model.Meta.t...
nilq/baby-python
python
from .nondet import Nondet
nilq/baby-python
python
# test_file.py import io import pytest import graspfile.torfile test_file = "tests/test_data/tor_files/python-graspfile-example.tor" """TICRA Tools 10.0.1 GRASP .tor file""" @pytest.fixture def empty_tor_file(): """Return an empty GraspTorFile instance.""" return graspfile.torfile.GraspTorFile() @pytest...
nilq/baby-python
python
"""Choose python classifiers with a curses frontend.""" from __future__ import unicode_literals import os import curses from collections import namedtuple from .constants import VERSION from .constants import CHECKMARK class BoxSelector(object): # pragma: no cover """Originally designed for accman.py. D...
nilq/baby-python
python
''' Created on 20/01/2014 @author: MMPE See documentation of HTCFile below ''' from __future__ import division from __future__ import unicode_literals from __future__ import print_function from __future__ import absolute_import from builtins import zip from builtins import int from builtins import str from future im...
nilq/baby-python
python
from apscheduler.schedulers.blocking import BlockingScheduler from server.sync import sync_blocks, sync_tokens background = BlockingScheduler() background.add_job(sync_tokens, "interval", seconds=30) background.add_job(sync_blocks, "interval", seconds=5) background.start()
nilq/baby-python
python
######################################################## # plot_norms.py # # Matheus J. Castro # # Version 1.2 # # Last Modification: 11/11/2021 (month/day/year) # # https://github.com/MatheusJCastro...
nilq/baby-python
python
from django.shortcuts import render from django.http import JsonResponse import os import json import time from .api import GoogleAPI from threpose.settings import BASE_DIR from src.caching.caching_gmap import APICaching from decouple import config gapi = GoogleAPI() api_caching = APICaching() PLACE_IMG_PATH = os.p...
nilq/baby-python
python
import os import math import random import argparse def generate_entities(num_entities=100): """generate num_entities random entities for synthetic knowledge graph.""" i = 0 entity_list = [] hex_chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] l = ...
nilq/baby-python
python
# Simple script for drawing the chi-squared density # from rpy import * def draw(df, start=0, end=10): grid = r.seq(start, end, by=0.1) l = [r.dchisq(x, df) for x in grid] r.par(ann=0, yaxt='n') r.plot(grid, l, type='lines') if __name__ == '__main__': print "<Enter> to quit." while 1: ...
nilq/baby-python
python
""" queue.py location queue implementation for ducky25, decides next location to travel to """ class DestinationQueue: def __init__(self): self.queue = [] self.position = 0 def add_to_queue(self, location): self.queue.append(location) def pop_next_destination(self): if len(self.queue) > self.position: ...
nilq/baby-python
python
from logging.config import dictConfig # type: ignore import json from config import CONFIG_DICT done_setup = False def setup_logging(): global done_setup if not done_setup and CONFIG_DICT['LOGGING']: try: logging_config_file_path = CONFIG_DICT['LOGGING_CONFIG_FILE_PATH'] wi...
nilq/baby-python
python
""" MIT License Copyright(c) 2021 Andy Zhou """ from flask import render_template, request, abort from flask.json import jsonify from flask_wtf.csrf import CSRFError from flask_babel import _ def api_err_response(err_code: int, short_message: str, long_message: str = None): if ( request.accept...
nilq/baby-python
python
from tidyms import lcms from tidyms import utils import numpy as np import pytest from itertools import product mz_list = [200, 250, 300, 420, 450] @pytest.fixture def simulated_experiment(): mz = np.array(mz_list) rt = np.linspace(0, 100, 100) # simulated features params mz_params = np.array([mz_li...
nilq/baby-python
python
from flask_login import UserMixin from datetime import datetime from sqlalchemy import ForeignKey from sqlalchemy.orm import backref from app.extensions import db ACCESS = { 'guest': 0, 'user': 1, 'admin': 2 } class User(UserMixin, db.Model): id = db.Column(db.Integer, primary_key=True, unique=Tru...
nilq/baby-python
python
# encoding: utf-8 """ Enumerations related to tables in WordprocessingML files """ from __future__ import ( absolute_import, division, print_function, unicode_literals ) from docxx.enum.base import ( alias, Enumeration, EnumMember, XmlEnumeration, XmlMappedEnumMember ) @alias('WD_ALIGN_VERTICAL') class WD_...
nilq/baby-python
python
# Copyright 2011 OpenStack Foundation # 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 requ...
nilq/baby-python
python
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! import grpc import nlm_pb2 as nlm__pb2 class NLMStub(object): # missing associated documentation comment in .proto file pass def __init__(self, channel): """Constructor. Args: channel: A grpc.Channel. """ self.StrReca...
nilq/baby-python
python
# -*- coding: utf-8 -*- # Copyright (c) 2020, PibiCo and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe.model.document import Document import datetime, time from frappe.utils import cstr from frappe import msgprint, _ from frappe.core.d...
nilq/baby-python
python
from __future__ import division import json import time import serial as _serial import platform import sys if sys.version_info >= (3, 0): import queue else: import Queue as queue from threading import Event, Thread from serial.tools.list_ports import comports from . import IOHandler try: JSONDecodeEr...
nilq/baby-python
python
#!/usr/bin/env python from distutils.core import setup setup( name = 'elastico', version = '0.6.3', description = "Elasticsearch Companion - a commandline tool", author = "Kay-Uwe (Kiwi) Lorenz", author_email = "kiwi@franka.dyndns.org", url = 'https://github.com/klo...
nilq/baby-python
python
from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, BooleanField, SubmitField from wtforms.validators import Required,Email, EqualTo from ..models import User from wtforms import ValidationError class RegisterationForm(FlaskForm): email = StringField('Enter Your email Address', validato...
nilq/baby-python
python
import pytest from nengo_os import SimpleProc, ConventScheduler procs = [ # name id arrival1,+2, comp_t, needed_cores SimpleProc("Cifar", 0, 0, 0, 10, 4038), # test single process SimpleProc("SAR", 1, 0, 0, 100, 3038), #test two procs that can not run together SimpleProc("SAR", 2, 0, ...
nilq/baby-python
python
from daq_server import DAQServer import asyncio server = DAQServer event_loop = asyncio.get_event_loop() # task = asyncio.ensure_future(heartbeat()) task_list = asyncio.Task.all_tasks() async def heartbeat(): while True: print('lub-dub') await asyncio.sleep(10) def shutdown(server): print...
nilq/baby-python
python
import pathlib import numpy as np import simscale_eba.HourlyContinuous as hc epw = hc.HourlyContinuous() # Put any path here path = r'E:\Current Cases\SimScale Objects\examples\epw_to_stat\USA_MA_Boston-Logan.Intl.AP.725090_TMYx.2004-2018.epw' epw.import_epw(pathlib.Path(path)) weather_stats = hc.WeatherStatistics...
nilq/baby-python
python