text stringlengths 3.07k 12.6k |
|---|
import pandas as pd
import numpy as np
import os
def consolidate_data(file_root):
data_folder = os.path.join(os.getcwd(), 'data')
files = pd.Series(os.listdir(data_folder), name='Document')
file_filter = files.str.contains(file_root)
data = [pd.read_excel(os.path.join(data_folder, f))
... |
""" Define classes for generating test datasets based on alternating signal snippets.
"""
import sys
import copy
import numpy as np
from typing import Sequence, Union
from bioslds.markov import SemiMarkov
from bioslds.utils import rle_encode
class SwitchingSnippetSignal:
""" A signal generated from switching ... |
#!/usr/bin/env python
# Copyright 2016 Battelle Energy Alliance, LLC
#
# 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 ... |
import os
import argparse
import os.path as osp
import glob
import torch
import torch.nn as nn
from reid.utils.data.dataset import Dataset, MixedDataset
from reid.utils.data import build_test_loader
from reid.models.backbone import ResNet
from reid.evaluation.evaluators import Evaluator, IncrementalEvaluator... |
import argparse
import math
import random
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
T = 10
def weak_learner(temp_X, temp_y, D):
m, d = temp_X.shape
F_star, theta_star, j_star = float('inf'), 0, 0
for j in range(d):
sorted_indexes = temp_X[:, j].argsort()
xj ... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
"""
This is a test for SwitchML RDMA.
"""
import unittest
import logging
import grpc
import pdb
import ptf
from ptf.testutils import *
from bfruntime_client_base_tests import BfRuntimeTest
import bfrt_grpc.bfruntime_pb2 as bfruntime_pb2
imp... |
#
# Copyright (C) 2012, <NAME>
# Copyright (C) 2011, <NAME>
# Copyright (C) 2005, <NAME>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) ... |
## Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
## SPDX-License-Identifier: MIT-0
import sys
import os
import json
import random
import datetime
import boto3
start_time = datetime.datetime.now()
no_of_days = 30
workload_contexts_distribution = [2, 15, 20, 18, 30, 15]
workload_contexts = {
"... |
from flask import Flask, request, redirect, render_template, session
from flask_socketio import SocketIO
# custom imports
from helpers.twilio import process_response, send_mass_message, send_chat_message
from helpers.database import get_all_students, get_alert_names, get_alert_template, get_audience_names, get_last_rea... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.autograd import Variable
import torchvision
from torchvision import datasets, transforms, models
import matplotlib
# % matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
imp... |
"""
McOpt (Multicommodity Optimal Transport) -- https://github.com/aleable/McOpt
Contributors:
<NAME>
<NAME>
<NAME>
"""
import numpy as np
import networkx as nx
from scipy.sparse import csr_matrix
from scipy.sparse import diags
from scipy.sparse import identity
from scipy.sparse.linalg import spsolve
de... |
from sstcam_simulation.data import get_data
from sstcam_simulation.utils.photon_incidence_angles import PhotonIncidenceAnglesWindow
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from scipy.interpolate import interp1d
class Window:
def __init__(self, incidence_angles, transmission):
... |
import torch
import torch.nn as nn
import pickle
import math
from sklearn.decomposition import PCA
from data_pipe.northeuralex import NortheuralexInfo
from data_pipe.celex import CelexInfo
class Context(nn.Module):
def __init__(self, hidden_size, nlayers=1):
super().__init__()
self.nlayers = nlay... |
"""
Plotting Tools for persistence diagrams and cocycles
"""
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon
def plotDGM(dgm, color = 'b', sz = 20, label = 'dgm', axcolor = np.array([0.0, 0.0, 0.0]), marker = None):
if dgm.size == 0:
return
# Create Lists
#... |
# -*- coding: utf-8 -*-
"""
biothings_explorer.utils
~~~~~~~~~~~~~~~~~~~~~~~~~~
This module provides utility functions that are used within bioThings_explorer
that are also useful for external consumption.
"""
import json
import yaml
from os.path import commonprefix
import requests
import graphviz
from .config impor... |
import logging
import flask_login
import mediacloud.error
from flask import jsonify, request
from operator import itemgetter
import server.views.apicache as shared_apicache
import server.views.topics.apicache as apicache
from server import app, mc, executor
from server.auth import user_mediacloud_key, user_mediacloud_... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 1 21:26:07 2021
some useful tools for implement dynamic encirclement
@author: tjards
"""
import numpy as np
import quaternions as quat
# delta_phi_desired = 2Pi/N
def polar2cart(r, theta):
#note: accepts and return radians
x = r*np.cos... |
#coding=utf-8
import requests
import requests.exceptions
import urllib.parse
from contextlib import closing
from functools import lru_cache
import base64
import zlib
import json
import traceback
from portal import web_portal
import const
from utils import normdomain, load_gfwlist
API_VERSION = 'APIv5'
PORTAL_ROOT='h... |
# -*- coding: utf-8 -*-
from collections import deque
import re
import sys
import os
try:
from sublime_plugin import EventListener
import sublime
except ModuleNotFoundError:
EventListener = type('EventListener', (object, ), {})
if sys.version_info > (3, 4):
from typing import Tuple, List, Deque, Itera... |
""" Tests the writing of the species section
"""
import os
from ioformat import read_text_file
import mess_io.writer
PATH = os.path.dirname(os.path.realpath(__file__))
SPC1_LABEL = 'Mol1'
SPC2_LABEL = 'Mol1'
WELL_LABEL = 'W1'
BIMOL_LABEL = 'P1'
TS_LABEL = 'B1'
# Data Strings
MOL_MESS_STR = """RRHO
Core RigidRotor... |
"""
Test the mutators operate as desired.
SUT: Corpus
Area: Mutators
Class: Functional
Type: Unit test
"""
import unittest
try:
from unittest.mock import patch
except ImportError:
# Python 2 backport of mock
from mock import patch
import pythonfuzz.corpus as corpus
class FakeCorpus(object):
... |
# -*- coding: utf-8 -*-
# Copyright (c) 2019-2021 <NAME>.
# All rights reserved.
# Licensed under BSD-3-Clause-Clear. See LICENSE file for details.
from django.db import models
from decimal import Decimal
class HistCompetitie(models.Model):
""" Deze database tabel bevat een overzicht van alle historische com... |
import math
import numpy as np
import tensorflow as tf
from tensorflow.keras import layers
from tensorflow.keras import backend as K
class PositionLayer(tf.keras.layers.Layer):
def __init__(self, embedding_size, **kwargs):
self.embedding_size = embedding_size
super(PositionLayer, self).__init__(*... |
from termcolor import colored
import copy
def eventPrint(operations, alg):
print("{} edit distance actions are listed below:".format(alg))
print("Total action count = {}\n".format(len(operations)))
for op in operations:
print("\t- {}".format(op))
print()
def backtrack(alg, dataMatrix, dim1, ... |
import functools
import string
import typing as t
from mypy.errorcodes import ErrorCode
from mypy.nodes import (
Expression,
FuncDef,
LambdaExpr,
NameExpr,
RefExpr,
StrExpr,
)
from mypy.options import Options
from mypy.plugin import (
MethodContext,
Plugin,
)
from mypy.types import (
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# pypll.py
#
# Copyright (c) 2018 <NAME>
#
# 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 limitati... |
from s5v2 import *
from prettytable import PrettyTable
def my_table(): # no arguments are passed in, which seems a bit weird. We're hard-coding a function that only does one thing.
x = PrettyTable(['Style', 'Average Price']) # setup a new pretty table list and give and give it two list items
x.add_row(['Print', pret... |
import numpy as np
from collections import deque
import rospy
NORMAL_MAXIMUM = 16384
BUFFER_NP_TYPE = '<i2' # little endian, signed short
def normalize(snd_data):
"""Average the volume out
"""
r = snd_data * (NORMAL_MAXIMUM * 1. / max(1, np.abs(snd_data).max()))
return r.astype(snd_data.dtype)
... |
import json
# import sqlite3
import os
import logging
import coloredlogs
coloredlogs.install(level='DEBUG', format='%(levelname)s%(asctime)s:%(message)s',)
from flask import request, url_for, Response, jsonify, g, redirect
from flask_api import FlaskAPI, status, exceptions
from flask_api.decorators import set_parsers
... |
import argparse
import numpy as np
import pandas as pd
from settings import experiments, lambdas, functions, TRANSIENT_VALUE, RESULT_DIR
from statistics import response_time_blockchain, number_users_system, calculate_transient, mean_error, \
bar_plot_metrics, bar_plot_one_metric, plot_transient, new_plot, new_plo... |
import pymysql
import time
import bs4
import requests
import re
import json
import datetime
from multiprocessing import Pool
with open('config.json', 'r') as f:
config = json.load(f)
database = config['database connection']
with open(config['track user path'], 'r') as f:
baseusers = [i.strip('\n') fo... |
import os
import random
import fakeredis
import pytest
from sqlalchemy import create_engine, inspect
from sqlalchemy.dialects.postgresql.base import PGInspector
from sqlalchemy.orm import sessionmaker
from testing import postgresql
from backend.database.objects import Player
from tests.utils.database_utils import cre... |
import numpy as np
import scipy
import warnings
def norms_init(B=None, Binv=None):
"""
Initialize norms to use.
The primal space is the space of variables, the dual space is
the space of the gradients.
Operator B transforms the primal space to the dual.
l2_norm_sqr(x) := ||x||^2... |
# -*- coding: utf-8 -*-
"""I/O for the relational database for embeddings."""
import json
import os
import random
import sys
from typing import Any, Iterable, Mapping, Optional, Tuple, Union
import click
from gensim.models import Word2Vec
from sqlalchemy.orm import Session
from tqdm import tqdm, trange
from .models... |
#!/usr/bin/env python
import random # for seed, random
import sys # for stdout
################################### TEST PART ##################################
# Tests align strands and scores
# Parameters types:
# score = int example: -6
# plusScores = string example: " 1 1 1"
# minu... |
# -*- coding: utf-8 -*-
"""
Helper functions for calculating the shear wave anisotropy (SWA)
Author: <NAME>
Date: 29 February 2020
"""
import pathlib
import numpy as np
import pandas as pd
import pyproj
def vbar(vmodel, event_depth, station_elevation):
"""
Calculates the average velocity between source and... |
# Copyright 2018 <NAME>
#
# 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, softwa... |
# encoding:utf-8
import os
import demjson
import requests
import datetime
from jqdatadir.china.common.util_file import *
'''
20190724
查找2B法则,在日线中查找
中间间隔>3
1 明显趋势 顶底都高于/低于前顶底
2 横盘趋势 ABC 顶底点的大小关系不明确 左尖/右尖三角,乱形都有
只处理 趋势 和 2B 其他不识别
'''
url_season = "http://172.16.17.32:8281/json/data.... |
from socket import *
import threading
from threading import Thread
import tkinter
import pyaudio
import time
def Receive():
while True:
try:
msg = client_socket.recv(BuffferSize).decode("utf8")
if msg[0:12] == "{modifyList}":
setNameList(msg[12:])
else:
msg_list.insert(tkinter.END, msg)
except OS... |
from math import sqrt, pi, acos, acosh, nan
from numba import cuda
from .angles import (
# D_to_M,
D_to_nu,
E_to_M,
E_to_nu,
F_to_M,
F_to_nu,
M_to_D,
M_to_E,
M_to_F,
# nu_to_D,
# nu_to_E,
# nu_to_F,
)
@cuda.jit(device=True)
def D_to_M_near_parabolic(D, ecc):
x = ... |
# https://code.activestate.com/recipes/576871-spline-demonstrator/
import tkinter
from tkinter import*
def mod(a,b):
return ( a % b)
def StandardKnot():
global m
knot = []
L = len(points) - 2
if L <= m -2 :
print('make more points than m')
return []
for i in range(m - 1):
... |
"""
Moodstocks API Client
---------------------
- Copyright (C) 2014 by Moodstocks SAS.
- Licensed under MIT/X11
- See https://moodstocks.com/ for more information.
"""
DEFAULT_EP = "http://api.moodstocks.com/v2"
from requests.auth import HTTPDigestAuth
import requests
import json
import os
import base64
version =... |
import torch
import torch.nn as nn
from torch import Tensor
from .Embedding import PositionalEmbedding
from .loss import SCELoss
from utils import generate_square_subsequent_mask
from typing import List, Tuple, Optional
class CapDecoder(nn.Module):
def __init__(self, num_layers, embed_dim, nhead, dim_feedforward... |
import random
import logging
from ask_sdk_core.skill_builder import SkillBuilder
from ask_sdk_core.dispatch_components import (
AbstractRequestHandler, AbstractExceptionHandler,
AbstractRequestInterceptor, AbstractResponseInterceptor)
from ask_sdk_core.utils import is_request_type, is_intent_name
from ask_sdk_... |
"""
Workarounds for limitations of the simplekv API.
"""
import logging
import time
from urllib.parse import quote
from simplekv.contrib import VALID_KEY_RE_EXTENDED
try:
# azure-storage-blob < 12
from azure.storage.blob import BlockBlobService as _BlockBlobService
from azure.common import (
Azure... |
import sys,os
sys.path.insert(0,'..')
""" Learned ADMM Plus
Reference : Learned Primal-Dual Reconstruction (<NAME>,<NAME>)
https://github.com/adler-j/learned_primal_dual
Run this script to evauluate parameters trained in learned_admm_plus.py.
"""
import adler
adler.util.gpu.setup_one_gpu()
from adler.odl.phanto... |
# coding=utf-8
# @File : Using_API.py
# @Author: PuJi
# @Date : 2018/4/3 0003
import sys
from fileHelper.ipfs_module import ulord_transmitter
from dbHelper import dbhelper
from fileHelper import util
import json
import requests
# metadata = {"license": "ULORD Inc", "description": "", # 1
# "languag... |
import os
import sys
cwd = os.getcwd()
sys.path.append(cwd)
from time import sleep
import pybullet as p
import numpy as np
def setUpWorld(initialSimSteps=100):
"""
Reset the simulation to the beginning and reload all models.
Parameters
----------
initialSimSteps : int
Returns
-------
... |
# Quick and dirty demonstration of a git exposure exploitation by <NAME>
# The author disclaims copyright to this source code.
import argparse
import asyncio
import os
import re
import aiohttp
from utils import print_warn, print_green, fetch, batch
parser = argparse.ArgumentParser(
description='Download files f... |
import numpy as np
# file template
# each row is "rel_id rel_type word1 word2"
# rel_type is 0 if not any subword information and any integer > 0 identifies the particular type of morphological relation
# filters out any words that aren't in the model vocabulary
def clean_dset(inpath, outpath, model):
filein = op... |
import time
import queue
import warnings
import numpy as np
import reip
class Rebuffer(reip.Block):
'''Collect numpy arrays and convert them to a different resolution'''
def __init__(self, size=None, duration=None, *a, sr_key='sr', **kw):
assert size or duration, 'You must specify a size or duration.'... |
from datetime import datetime
import requests
from PyQt5 import QtWidgets, QtCore
import clientui
import user_and_passui
import errorui
URL = 'http://127.0.0.1:5000/'
VERSION = "1.0.0"
THEMES = ["color: rgb(255, 255, 255); background-color: rgba(0, 255, 254, 0);",
"background-color: qlineargradient(spread:p... |
import matplotlib as mpl
mpl.rcParams['lines.linewidth'] = 3
mpl.rcParams['figure.figsize'] = (10,8)
mpl.rcParams['axes.grid']=True
def bigfonts(size=20,family='sans-serif'):
from matplotlib import rc
rc('font',size=size,family=family)
rc('axes',labelsize=size)
rc('axes',titlesize=size)
rc('xtick... |
#!/usr/bin/env python
# -*- encoding: UTF-8 -*-
# @author: <EMAIL>
# @date: 2013-09-17
# @brief: use python to parse binary file
# @depend: construct
# structs_little_endian.py or structs_big_endian.py
import os, sys, struct, codecs, inspect, binascii, optparse, construct
def write_dict(fdWriter, dictObj):
... |
from __future__ import print_function, division, absolute_import
import os
from fontTools.misc.py23 import *
from ufo2ft.preProcessor import (
OTFPreProcessor, TTFPreProcessor, TTFInterpolatablePreProcessor)
from ufo2ft.featureCompiler import FeatureCompiler
from ufo2ft.outlineCompiler import OutlineOTFCompiler,... |
import sys
import os
import numpy as np
from sacremoses import MosesTokenizer, MosesDetokenizer
# for training MT or NAT models
md = MosesDetokenizer(lang='en')
model_root = "/private/home/chuntinz/work/assets/fairseq-domain-shift/saved_ha_models"
bpe_dir = "/checkpoint/chuntinz/data/multi-zh-en/detok/mix-data-bpe/mix... |
import time
import math
from fairseq.tokenizer import tokenize_line
# from fairseq_ext.amr_reform.o10_action_reformer_subtok import AMRActionReformerSubtok
def replace_unk(hypo_str, src_str, alignment, align_dict, unk, line_tokenizer=tokenize_line):
# Tokens are strings here
hypo_tokens = line_tokenizer(hyp... |
def init_actions_(service, args):
"""
this needs to returns an array of actions representing the depencies between actions.
Looks at ACTION_DEPS in this module for an example of what is expected
"""
return {
'test': ['install']
}
def test(job):
import sys
try:
log = j.l... |
# Copyright (C) 2019-2020 Intel Corporation
#
# SPDX-License-Identifier: MIT
import os
import os.path as osp
import tempfile
from datetime import timedelta
from enum import Enum
import django_rq
from django.utils import timezone
import pandas as pd
from openpyxl.workbook.child import INVALID_TITLE_REGEX
import re
im... |
""" This file contains code for a fully convolutional
(i.e. contains zero fully connected layers) neural network
for detecting lanes. This version assumes the inputs
to be road images in the shape of 80 x 160 x 3 (RGB) with
the labels as 80 x 160 x 1 (just the G channel with a
re-drawn lane). Note that in order to view... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
CNN 卷积神经网络
学习准确率达到: 96-97%
AdamOptimizer: 学习速率要低于 0.001 否则容易梯度消失
"""
from __future__ import print_function
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
# 预测准确率... |
import os, csv, requests, json, time, sys
import scraper, config
from multiprocessing.dummy import Pool as ThreadPool
def get_recent_run():
#find the most timestamp of shops added to the archive
scraper.pprint('--get recent run')
files = os.listdir("./data")
dates = []
for f in files:
sub_... |
# Helper functions and wrappers around the google APIs
from __future__ import print_function
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from apiclient import errors
from email.mime.audio import MIMEAudio
from em... |
#
# Copyright (c) 2016 Intel Corporation. All rights reserved
#
"""schema cleanup removing unused tables
Revision ID: 0fb66069a81f
Revises: <PASSWORD>
Create Date: 2016-10-03 14:13:22.740117
"""
# revision identifiers, used by Alembic.
revision = '0fb66069a81f'
down_revision = '<PASSWORD>'
branch_labels = None
from... |
"""
Define Keypair object for holding key id to keypair mapping, and functions to
get default public and private keys for the fence app. The app must be
configured with the attribute ``app.keypairs``.
Attributes:
Keypair: object for storing key id to keypair associations
default_public_key (Callable[[flask.Fla... |
from utils.decorators import timer, debug
from utils.task import Task
from utils.load import load_task_json
import numpy as np
from copy import deepcopy
class Node:
def __init__(self, fish_num, parent):
self.parent = parent
if isinstance(fish_num, int):
self.value = fish_num
... |
import datetime
import json
import dash
import pytz
from dash import html, dash_table, dcc, Output, Input
import pandas as pd
from dash.exceptions import PreventUpdate
from app import app
import plotly.graph_objects as go
class GraphBuilder():
def __init__(self):
self.json_data = None
self.tota... |
import os
from django.conf import settings
from django.urls import reverse
from django.db import models as models
from django.utils import timezone
from django_extensions.db import fields as extension_fields
from django.contrib.postgres.fields import ArrayField
from django.contrib.auth.models import User
from django.c... |
# -*- coding: utf-8 -*-
import schedule
import time
import importlib
import logging
import re
from glob import Glob
from drivers.oasisunit import OasisUnit
from dborm import turhousedb
class TurhouseOasisDriverError(Exception):
pass
class TurhouseOasis(object):
'''
Daemon servicing oasis units
... |
from django.db import models
from django.db.models import Q
from django.contrib.auth.models import User
from tinymce.models import HTMLField
import datetime as dt
# from vote.models import VoteModel
class Editor(models.Model):
first_name = models.CharField(max_length = 30)
last_name = models.CharField(max_leng... |
#!/usr/bin/python
##-------------------------------------------------------------------
## @copyright 2017 DennyZhang.com
## Licensed under MIT
## https://www.dennyzhang.com/wp-content/mit_license.txt
##
## File : cleanup_old_files.py
## Author : Denny <<EMAIL>>
## Created : <2017-05-03>
## Updated: Time-stamp: <2017... |
#!/usr/bin/env python3
###############################################################################
# #
# Calculates dYdX general config and synthetic asset hash values. #
# ... |
from httpx import URL
from httpx.exceptions import InvalidURL
import pytest
def test_idna_url():
url = URL("http://中国.icom.museum:80/")
assert url == URL("http://xn--fiqs8s.icom.museum:80/")
assert url.host == "xn--fiqs8s.icom.museum"
def test_url():
url = URL("https://example.org:123/path/to/somewh... |
# Copyright 2017 AT&T Intellectual Property. All other 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... |
import logging
import asyncio
import os
from pyrogram import filters
from pyrogram.handlers import MessageHandler
from pyrogram.errors.exceptions.bad_request_400 import MessageIdInvalid
from altruz.core.altruz_database.altruz_db_conf import get_log_channel
from altruz.core.altruz_database.altruz_db_sudos import get_s... |
#######################################################################
#
# InfoBar Tuner State for Enigma-2
# Coded by betonme (c) 2011 <glaserfrank(at)gmail.com>
# Support: http://www.i-have-a-dreambox.com/wbb2/thread.php?threadid=162629
#
# This program is free software; you can redistribute it and/or
# ... |
###############################################################################
# Copyright (c) 2007-2018, National Research Foundation (Square Kilometre Array)
#
# Licensed under the BSD 3-Clause License (the "License"); you may not use
# this file except in compliance with the License. You may obtain a copy
# of the ... |
#import gevent
#from gevent import monkey; monkey.patch_all()
import time
from datetime import datetime, timedelta
import feedparser as fp
import pytz
subscriptions = [
'http://feedpress.me/512pixels',
'http://www.leancrew.com/all-this/feed/',
'http://ihnatko.com/feed/',
'http://blog.ashleynh.me/feed... |
import machine
import network
import neopixel
import time
import ntptime
brightness = 12
timeBrightness = brightness//12
pixels = 60
dataPin = 5
hourColor = (0,0,brightness)
minuteColor = (0,brightness,0)
secondColor = (brightness,0,0)
timerColor = (timeBrightness,0,timeBrightness)
secondsInYear = 60 * 60 * 24 * 365
... |
from db import db
from flask import session
from werkzeug.security import check_password_hash, generate_password_hash
def create_campaign(title, password):
hash_value = generate_password_hash(password)
creator_id = session.get("user_id", 0)
sql = """INSERT INTO campaigns (title, creator_id, created_at,
... |
# Copyright 2018 Google Inc. 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 a... |
import os
import lxml.etree as ET
from functools import reduce
import logging
import pkg_resources
ns = ET.FunctionNamespace("http://nextnet.top/functions")
ns.prefix = "nn"
class FileResolver(ET.Resolver):
def resolve(self, url, pubid, context):
return self.resolve_filename(url, context)
@ns
def urlen... |
"""Chunkify an ISOBMFF segment. Either as library or command line tool."""
# The copyright in this software is being made available under the BSD License,
# included below. This software may be subject to other third party and contributor
# rights, including patent rights, and no such rights are granted under this lic... |
import curses
import logging
import os
import re
from textwrap import dedent
import npyscreen
from initiative.constants import STAT_DISPLAY
from initiative.models.encounter import Encounter, Member
from initiative.ui.custom_mutt import _CustomMutt
from initiative.ui.helpful_controller import HelpfulController
from in... |
import gc
import gzip
import time
import json
import shutil
import os,sys
import tldextract
import collections
import pandas as pd
from tqdm import tqdm
import urllib.request
from multiprocessing import Pool
# !mkdir data
# !wget https://commoncrawl.s3.amazonaws.com/crawl-data/CC-MAIN-2019-22/cc-index.paths.gz
# !gzip... |
import time
import os
def programaparasalvar():
# coding: utf-8
"""
Este projeto está sendo desenvolvido inteiramente
Por <NAME>, e eu disponibilizei este projeto
Para o público, para que o conhecimento s... |
from unicorn import *
from enum import Enum
from termcolor import colored, cprint
from .utils import dict_add
class MemoryType(Enum):
STACK_MEMORY = 0
HEAP_MEMORY = 1
TEXT_MEMORY = 2
USER_MEMORY = 3
UNMAPPED_MEMORY = 4
UNDEFINED_MEMORY = 5
UNINITIALIZED_STACK_MEMORY = 6
UNINITIALIZ... |
import pandas as pd
import torch
import torch.nn as nn
import torch.utils.data
from torch_model_base import TorchModelBase
from utils import progress_bar
from torch_autoencoder import TorchAutoencoder
from torch.autograd import Variable
__author__ = "Simranjit"
__version__ = "CS224u, Stanford, Spring 2020"
class MMDV... |
"""Everything related to O2 power. Hoooo baby."""
import math
import numpy as np
import pandas as pd
from . import util
def o2_power_ss(speed_series, grade_series=None):
"""Calculates steady-state oxygen consumption in the moderate domain.
For more info, see `heartandsole_local/heartandsole/powerutils.py`.
... |
# Databricks CLI
# Copyright 2017 Databricks, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"), except
# that the use of services to which certain application programming
# interfaces (each, an "API") connect requires that the user first obtain
# a license for the use of the APIs from Databricks,... |
import itertools
from collections import OrderedDict
from django.conf import settings
import mock
from nose.tools import eq_, ok_
import mkt.site.tests
from mkt.constants.features import (APP_FEATURES, FeaturesBitField,
FeatureProfile)
MOCK_APP_FEATURES_LIMIT = 45
MOCK_APP_FEATU... |
import configparser
from jinja2 import (Environment, FileSystemLoader, PackageLoader,
select_autoescape)
import logging
import os
import pathlib
from PIL import Image
import re
import sqlite3
import stat
import subprocess
import sys
from photo_album import (Album, Package, CustomArgumentParser)
logger = loggi... |
'''predict from images'''
import argparse
import os
import sys
from tqdm import tqdm
import numpy as np
import cv2
import json
import keras
import tensorflow as tf
# Allow relative imports when being executed as script.
if __name__ == "__main__" and __package__ is None:
sys.path.insert(0, os.path.join(os.path.dir... |
# USAGE
# python webstreaming.py --ip 0.0.0.0 --port 8000
# import the necessary packages
import numpy as np
from imutils.video import VideoStream
from flask import Response
from flask import Flask
from flask import render_template
from time import sleep
import imutils
import threading
import argparse
import datetim... |
from time import sleep
from typing import Tuple, Optional
from urllib.parse import quote_plus
import logging
import requests
import shelve
from ..common import progress_bar
from ..types import Document, Author, DocumentSet, DocumentIdentifier
def extract_id(item):
if item is None or not item.get('title'):
... |
"""Monomer class with parameters and methods."""
from typing import Tuple, Union
import pandas as pd
from rdkit import Chem
from rdkit.Chem.Descriptors import ExactMolWt
from rdkit import rdBase
from rdkit.Chem.rdchem import Mol
functionality_smarts = {
"ols": "[C,c;!$(C=O)][OH]",
"aliphatic_ols": "[C;!$(C=O... |
#!/usr/bin/env python
"""Cohesity Python REST API Class Library and Helper Functions - v0.1 - <NAME> - December 2018"""
##########################################################################################
# Install Notes
# =============
#
# Requires module: requests
# sudo easy_install requests
# - or -
... |
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... |
"""Vector space model for information retrieval
Returns all documents matching the entered search query, in decreasing order
of cosine similarity, according to the vector space model
"""
import glob
import math
import re
import sys
from collections import defaultdict
from functools import reduce
from nltk.corpus imp... |
import json
import random
import glob
import os
import string
from collections import OrderedDict
questions = {}
user_answers = OrderedDict()
current_question = None
current_solution = None
formatted_solution = None
possible_solutions = None
requires = ['db']
def start_quiz(bot, c, e, args):
# TODO: I assume ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.