content stringlengths 5 1.05M |
|---|
from JavPy.embed.fembed import fembed
from JavPy.embed.avgle import avgle
from JavPy.embed.smartshare_tv import smartshare_tv
from JavPy.embed.hydrax_net import hydrax_net
from JavPy.embed.playfinder_xyz import playfinder_xyz
from JavPy.embed.javcl_me import javcl_me
embeds = [avgle, hydrax_net]
def decode(url):
... |
"""
Freyr - A Free stock API
""" |
# BGR colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GRAY25 = (64, 64, 64)
GRAY50 = (128, 128, 128)
GRAY75 = (192, 192, 192)
GRAY33 = (85, 85, 85)
GRAY66 = (170, 170, 170)
BLUE = (255, 0, 0)
GREEN = (0, 255, 0)
RED = (0, 0, 255)
CYAN = (255, 255, 0)
MAGENTA = (255, 0, 255)
YELLOW = (0, 255, 255)
ORANGE = (0, 12... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2016-2017, Cabral, Juan; Luczywo, Nadia
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retai... |
# coding: utf-8
# This file is a part of VK4XMPP transport
# © simpleApps, 2013 — 2016.
import re
import urllib
import time
from printer import *
VK_AUDIO_SEARCH_LINK = "https://vk.com/search?c[q]=%s&c[section]=audio"
WALL_LINK = "https://vk.com/wall%(to_id)s_%(id)s"
WALL_COMMENT_LINK = "https://vk.com/wall%(owner_id... |
from bs4 import BeautifulSoup
import re, requests
from insides.bcolors import bcolors
def Googling(mail,_verbose=None):
if _verbose != None:
try:
print(f"{bcolors.WARNING} -- Google Searching... [Pastebin & Throwbin]{bcolors.ENDC}")
print(f"{bcolors.FAIL}!{bcolors.ENDC}"+"Google Search may not work properly.... |
import os
from dataclasses import dataclass
from typing import Iterable, Iterator, Tuple
from diamond_miner.defaults import (
DEFAULT_FAILURE_RATE,
DEFAULT_PREFIX_LEN_V4,
DEFAULT_PREFIX_LEN_V6,
PROTOCOLS,
UNIVERSE_SUBSET,
)
from diamond_miner.format import format_ipv6
from diamond_miner.generators.... |
from check_index import *
def check_objects(o):
assert is_list(o)
assert len(o) == 1
check_index_object(o[0], "cmakeFiles", 1, 0, check_object_cmakeFiles)
def check_input(actual, expected):
assert is_dict(actual)
expected_keys = ["path"]
if expected["isGenerated"] is not None:
expecte... |
from classifier import FeeClassifier
from flask import Flask, jsonify
app = Flask(__name__)
@app.route("/")
def root():
return app.send_static_file('index.html')
@app.route("/nn")
@app.route("/nn/<int:fee_per_byte>")
@app.route("/nn/<int:fee_per_byte>/<int:mempool_megabytes>")
@app.route("/nn/<int:fee_per_byte>/... |
from .lexer import Lexer |
import re
from django import forms
from django.contrib.auth import get_user_model
from django.contrib.contenttypes.models import ContentType
from django.contrib.postgres.forms.array import SimpleArrayField
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Q
from django.utils.safestring... |
"""
With these settings, tests run faster.
"""
from .base import * # noqa
from .base import env
import os
# GENERAL
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#debug
DEBUG = env.bool('DJANGO_DEBUG', default=False)
# https://do... |
# -*- coding: utf-8 -*-
"""
Tests against the classes representing FIQL query objects.
"""
from __future__ import unicode_literals
from __future__ import absolute_import
import unittest
from fiql_parser import (Operator, Constraint, Expression,
FiqlObjectException)
class TestObjects(unittest.TestCase):
... |
"""Users serializers"""
from .users import *
|
"""
Example code for creating and visualizing
cluster of county-based cancer risk data
"""
# Flavor of Python - desktop or CodeSkulptor
DESKTOP = True
import math
import random
import cluster
from urllib.request import urlopen
# conditional imports
if DESKTOP:
import algos
import plot
else:
#import user... |
number = 3
while True:
user_input = input('Play the Game...? (Y/n). ').lower()
if user_input == 'n':
break
user_number = int(input("Guess a numba."))
if user_number == number:
print('You figured it out~!')
elif abs(number - user_number) == 1:
print('Ohh... so close. Just 1... |
from flask import Flask, request, render_template
import os
import pydocumentdb.document_client as document_client
import pygal
from pygal.style import BlueStyle
# CosmosDB connection and DB settings
cosmos_db_endpoint = os.environ['COSMOS_DB_ENDPOINT']
cosmos_db_masterkey = os.environ['COSMOS_DB_MASTERKEY']
cosmos_db... |
import boto3
import click
import time
import docker
from docker.errors import APIError
from swarm_controller.swarm import Swarm
class SwarmNode:
def __init__(self, docker_host, availability_zone, hostname, local_ip, instance_id):
self.hostname = hostname
self.local_ip = local_ip
self.spe... |
import pickle
import numpy as np
import copy
import motor_skills
import motor_skills.core.mj_control as mjc
from motor_skills.envs.mj_jaco import MjJacoEnv, MjJacoDoor
from mujoco_py import cymj
from mujoco_py import load_model_from_path, MjSim, MjViewer
model = load_model_from_path('/home/abba/msu_ws/src/motor_skil... |
#! python
# -*- coding: utf-8 -*-
import math
import torch
from torch.nn import Parameter
import torch.nn as nn
class ReLU(nn.Hardtanh):
def __init__(self, inplace=False):
super(ReLU, self).__init__(0, 20, inplace)
def __repr__(self):
inplace_str = 'inplace' if self.inplace else ''
r... |
# Generated by Django 2.0.3 on 2018-07-29 09:12
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('shoptrans', '0011_auto_20180728_1146'),
]
operations = [
migrations.RemoveField(
model_name='product',
name='first_a... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""exif sort implementation"""
# BSD 2-Clause License
#
# Copyright (c) 2019, Yasuhiro Okuno (Koma)
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#... |
# -*- coding: UTF-8 -*-
import httplib
import md5
import urllib
import random
import demjson
import sys
import config
reload(sys)
sys.setdefaultencoding('utf8')
def translate_baidu(q):
'从百度获取翻译'
appid = config.appid
secretKey = config.secretKey
httpClient = None
myurl = '/api/trans/vip/translate'
fromLang = co... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""The setup script."""
from setuptools import setup, find_packages
with open('README.md', 'r') as readme_file:
readme = readme_file.read()
requirements = [
"dicom2nifti",
"dicompyler-core",
"lifelines",
"itk",
"minepy",
"numpy",
"numpy>... |
"""
Tests of calf.lexer
Tests both basic functionality, some examples and makes sure that arbitrary token sequences round
trip through the lexer.
"""
import calf.lexer as cl
from conftest import parametrize
import pytest
def lex_single_token(buffer):
"""Lexes a single token from the buffer."""
return next... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('archive', '0007_screenshot_internetarchive_id'),
]
operations = [
migrations.RenameField(
model_name='screenshot... |
# Copyright 2014 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 agr... |
"""
给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/majority-element
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
from math import floor
class Solution:
def majorityElement(self, nums) -> int:
elem_nums = set(nums)
... |
from django.shortcuts import render
from django.utils.translation import ugettext_lazy as _
from .models import MultipleMultipleFileFieldModel
def index(request):
temp = MultipleMultipleFileFieldModel.objects.first()
if not temp:
return render(request, 'index.html',
{
... |
from pygments.lexer import RegexLexer, bygroups, using, words
from pygments.token import *
from pygments.lexers.shell import BashLexer
import re
class SingularityLexer(RegexLexer):
"""
Lexer for `Singularity definition files
<https://www.sylabs.io/guides/3.0/user-guide/definition_files.html>`_.
"""
... |
import csv
import argparse
import random
from tqdm import tqdm
import os
parser = argparse.ArgumentParser()
parser.add_argument('-folder', type=str, default='.',
help='path to images folder')
parser.add_argument('-ratio', type=float, default=0.9,
help='ratio of the train set (de... |
def func_args(logger):
"""Function decorator logging arguments of functions.
func_args: allows passing of parameters to decorator (e.g. Logger instance)
func_decorator: decorates function and logs its arguments
Parameters:
----------
logger: instance of Logger class
"""
def fun... |
import logging
RESULT_TYPE = 'result_type'
RESULT_FILE = 'file'
RESULT_MEMORY = 'memory'
logging.basicConfig(format='%(asctime)s: %(name)s: %(levelname)s: %(message)s',
level=logging.DEBUG)
finders = {} |
import math
import cv2
from dataclasses import dataclass
from typing import List
import numpy as np
import torch
import torchvision
from fcos.models import FCOS, normalize_batch
MIN_SCORE = 0.05
DEFAULT_MAX_DETECTIONS = 3000
@dataclass
class Detection:
score: float
object_class: int
bbox: np.ndarray #... |
from tool.runners.python import SubmissionPy
import math
class EvqnaSubmission(SubmissionPy):
def trees_encountered(self, grid, w, h, slope):
d_x, d_y = slope
n_trees = 0
x, y = 0, 0
while y < h:
if grid[y][x] == '#':
n_trees += 1
x = (x + d... |
from typing import Dict
from data_structure.host_info import HostInfo, VoyagerConnectionStatus
from event_emitter import ee
from event_handlers.voyager_event_handler import VoyagerEventHandler
from event_names import BotEvent
class MiscellaneousEventHandler(VoyagerEventHandler):
def __init__(self, config):
... |
# Authors: Gavin Niendorf <gavinniendorf@gmail.com>
#
# Custom warnings and error classes used in TracePy.
#
# License: MIT
class NormalizationError(Exception):
""" Custom exception for unnormalized input. """
class NotOnSurfaceError(Exception):
""" Error for rays that do not intersect with a surface. """
cl... |
import os
import boto3
from getpass import getpass
from dotenv import load_dotenv
dotenv_path = os.path.join(os.path.dirname(__file__), ".env")
load_dotenv(dotenv_path)
idp_client = boto3.client("cognito-idp", region_name=os.getenv("REGION_NAME"))
username = input("[*] Enter Your Email Address: ")
password = getpass("... |
#!/usr/bin/env python3
import numpy as np
import matplotlib.pyplot as plt
import h5py, sys
def help():
"""
This script plots
(1) transverse intergated entropy/density as function of rapidity
(2) Projection of entropy/density onto x-y (eta=0) plane
(3) ............................. onto y-eta (x=0) pl... |
#!/opt/local/bin/pypy -tt
#!/opt/local/bin/pypy -tt -m cProfile
# -*- coding: utf-8 -*-
# Copyright (C) 2013-2014 Chris Hinsley
import sys, os, time
from operator import itemgetter
from array import array
MAX_PLY = 10
MAX_TIME_PER_MOVE = 10
PIECE_VALUE_FACTOR = 3
KING_VALUE, QUEEN_VALUE, ROOK_VALUE = 1000000, 9 * PI... |
import numpy as np
import math
from .split import split1
from .util import add_value
from . import global_val as gv
import pdb
def __vert1(j, z, f, x1, x2, f1, f2):
if j == 0:
j1 = 1
else:
j1 = 0
x = z[j1]
if x1 == math.inf:
x1 = z[j]
f1 = f1 + f[j]
elif x2 == mat... |
from flask_frozen import Freezer
from app import app
from shutil import copyfile
from helpers import load_data
freezer = Freezer(app)
@freezer.register_generator
def user_details():
users = load_data('sorted_users_acc_days_30.json')
for user in users:
yield {'user_name': user['user_name']}
if __na... |
__all__ = ["RealtimeBoxOffice"]
import tushare as ts
from flask_restful import Resource
def get_realtime_boxoffice():
return ts.realtime_boxoffice().to_json()
class RealtimeBoxOffice(Resource):
"""获取实时电影票房数据,30分钟更新一次票房数据,可随时调用。
返回值说明:
BoxOffice 实时票房(万)
Irank 排名
MovieName 影片名
boxPer 票房占... |
import os, pickle,sys
import matplotlib.pyplot as pl
import matplotlib.dates as mdates
import scipy as sp
from mpl_toolkits.basemap.cm import sstanom
from g5lib import plotters as pltrs
from datetime import datetime
dsetname='HadISST'
varname='sst'
path=os.environ['NOBACKUP']+'/verification/'+dsetname
varname='sst'
... |
import sys
import paho.mqtt.client as mqtt
from PyQt5.QtWidgets import QDialog, QApplication, QHeaderView, QTableWidgetItem
from PyQt5.QtCore import QTimer
from MQTTVehicelWasherDebuggingPanel import *
from logInInterface import *
from mqttRemoteMessage import *
class LoginInterface(QDialog):
"""This is the user l... |
#!/usr/bin/env python3
"""
Ver 1.0 - First version
Ver 2.0 - Uses database for match SUB file name and read Sublist.ini for match Sub string
Ver 3.0 - Uses GUI for parameter input
Ver 4.0 - Re-develop this application by Python3
Ver 4.1 - Add GUI
Ver 4.2 - Add convert Sub file from simple chinese to TW traditional chi... |
from pulser import Register
import networkx as nx
import matplotlib.pyplot as plt
def plot_initial_graph_nx(G, num_vertexes):
mapping = dict(zip(G, range(0, num_vertexes)))
G = nx.relabel_nodes(G, mapping)
nx.drawing.nx_pylab.draw(G, pos=dict(G.nodes(data='pos')), with_labels=True)
plt.show()
re... |
import numpy as np
from numpy import ndarray
def check_label_input(y, name):
if isinstance(y, np.ndarray):
if not np.issubdtype(y.dtype, np.integer):
raise ValueError("{} array must have integer dtype".format(name))
if y.ndim != 1:
raise ValueError("{} array must be 1-dimen... |
def create_query_check_lock(users):
return '''\
set pages 200 lines 200
col ORACLE_USERNAME format a16
col OS_USER_NAME format a15
col OWNER format a10
col OBJECT_NAME format a30
col PROGRAM format a50
col OBJECT_TYPE format a15
select count(1) from (
SELECT session_id, s.serial#, oracle_username, os_user_name, owner... |
import os
import logging
import json
logging.basicConfig(
level=logging.DEBUG,
format='[%(asctime)s] [%(name)s] [%(levelname)s] (%(message)s)',
datefmt='%Y-%m-%d %H:%M:%S'
)
logging.info('Loggers ready !')
# CHANGE THIS DICT AND THE "image_label_generator" function
# if you have different class of emoti... |
"""Simple Hail query example."""
import click
import hail as hl
from bokeh.io.export import get_screenshot_as_png
from analysis_runner import output_path
GNOMAD_HGDP_1KG_MT = (
'gs://gcp-public-data--gnomad/release/3.1/mt/genomes/'
'gnomad.genomes.v3.1.hgdp_1kg_subset_dense.mt'
)
@click.command()
@click.op... |
#!/usr/bin/env python
def main():
print("Hello World!")
|
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 26 12:51:58 2015
@author: Wasit
"""
import numpy as np
from matplotlib import pyplot as plt
# the saleman starts from node0 and find the shortest
# to visit all nodes before comming back to node0
def tsp(A=[],nodes=[],prenode=[],visit={}):
if len(nodes)==1:
... |
from setuptools import setup, find_packages
from codecs import open
version = open('packaging/VERSION').read().strip()
requirements = open('packaging/requirements.txt').read().split("\n")
test_requirements = open('packaging/requirements-test.txt').read().split("\n")
with open('README.rst', encoding='utf-8') as f:
... |
import unittest
loader = unittest.TestLoader()
tests = loader.discover('./cases/', pattern='*.py')
testRunner = unittest.runner.TextTestRunner()
testRunner.run(tests)
|
#!/usr/bin/env python
import optparse
import os
import re
import sys
chplenv_dir = os.path.dirname(__file__)
sys.path.insert(0, os.path.abspath(chplenv_dir))
import overrides
from utils import memoize
@memoize
def get(flag='wide'):
wide_val = overrides.get('CHPL_WIDE_POINTERS', 'struct')
define = ''
if... |
__________________________________________________________________________________________________
sample 92 ms submission
class Solution:
def cyclic(self, graph, node, current, visited):
visited.add(node)
current.add(node)
for neighbor in graph[node]:
if neighbor not in vis... |
#!/usr/bin/env python
# Test whether a client connects correctly with a zero length clientid.
import context
import paho_test
rc = 1
keepalive = 60
connect_packet = paho_test.gen_connect("", keepalive=keepalive, proto_name="MQTT", proto_ver=4)
connack_packet = paho_test.gen_connack(rc=0)
disconnect_packet = paho_te... |
### TUPLES ###
'''
Before we continue, I strongly encourage you to take a
look at the Working with Errors document provided to
your instructor.
When programming, there is times where we might want to
contain our data in some way so that we can interact
with large bodies of data without typing a ludicrous
amou... |
# Rushy Panchal
# iTunes.py
# Provides an easy interface to access the Itunes API
import urllib2
import urllib
import json
import sys
'''
The Search class provides a simple interface to access the iTunes Search API
Examples
search = Search()
search.album("Songs of Innocence, U2") # find by album
search.song("Madn... |
import random
import numpy as np
import torch
import mmcv
import cv2
from mmcv.parallel import MMDataParallel, MMDistributedDataParallel
from mmcv.runner import (DistSamplerSeedHook, EpochBasedRunner, OptimizerHook,
build_optimizer)
from mmdet.core import DistEvalHook, EvalHook, Fp16Optimizer... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import os
import argparse
import logging
from pathlib import Path
import shutil
import soundfile as sf
from tempfile im... |
from datetime import datetime
from config import Config
from .models import Users
def authenticate(email, password):
user = Users.query.filter_by(email=email).first()
if not user or not user.verify_password(password):
return None
return user
def identity(payload):
user_id = payload['identi... |
from ..deps import *
import markdown
from starlette.responses import StreamingResponse
import io
router = APIRouter(
prefix = "/bot",
tags = ["Bots"],
include_in_schema = False
)
@router.get("/")
async def bot_rdir(request: Request):
return RedirectResponse("/")
@router.get("/{bot_id}")
async def bot_... |
#!/bin/env python3.6
from time import sleep
from pynq.overlays.base import BaseOverlay
base = BaseOverlay("base.bit")
rgbleds = [base.rgbleds[i] for i in range(4, 6)]
leds = [base.leds[i] for i in range(4)]
# Toggle board LEDs leaving small LEDs lit
for i in range(8):
[l.off() for l in leds]
[rgbled.off() f... |
# Generated by Django 3.2.4 on 2021-07-01 18:08
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("contacts", "0001_initial"),
]
operations = [
migrations.AlterModelOptions(
name="accinstcontlink",
options={"managed": False... |
#!/usr/bin/env python2
import unittest
import vl
import pandas as pd
class TestLines(unittest.TestCase):
def test(self):
network_type = 'walk'
address = 'R. John Kennedy, 180 - Barra da Tijuca, Rio de Janeiro - RJ, 22620-260, Brazil'
df = pd.read_csv("vagas.csv")
lines = vl.get_way... |
from pipeline_live.data.iex import factors
from pipeline_live.data.iex.pricing import USEquityPricing
def test_factors():
assert factors.AverageDollarVolume.inputs[0] == USEquityPricing.close
|
import json
import yaml
from kubernetes import config
from kubernetes import client
def create_object(body, namespace):
group, version = body['apiVersion'].split('/')
plural = body['kind'].lower() + 's'
config.load_incluster_config()
api_instance = client.CustomObjectsApi()
response = api_instan... |
import sys
import click
from lps.config import GlobalConfig
from lps.factory import synth_map
from lps.core import output, population
CONTEXT_SETTINGS = dict(help_option_names=["-h", "--help"])
@click.command(context_settings=CONTEXT_SETTINGS)
@click.argument(
'config_path',
type=str
)
def cli(config_path)... |
def GetMessages(data):
for x in data:
print(x)
|
# -*- coding: utf-8 -*-
# MIT License
#
# Copyright (c) 2019 Jean-François Boismenu
#
# See LICENSE at the root of this project for more info.
from emnes.apu.pulse import Pulse
from emnes.apu.frame_sequencer import FrameSequencer
from emnes.apu.status import Status
from emnes.apu.triangle import Triangle
from emnes.ap... |
from network import GNet
if __name__ == '__main__':
generator = GNet()
generator.AddScale(1024)
print(generator) |
import numpy as np
import pandas as pd
from slimeda.histogram import histogram
import pytest
from vega_datasets import data
def test_histogram_single_chart():
"""Tests that a single chart is created for a single column"""
# create a dummy data frame with four columns for testing
df = data.cars()
chart... |
import os, cv2
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # dont show any tensorflow warning messages
import tensorflow as tf
from PIL import Image
import numpy as np
'''
Image_Classification Class
Description:
1. Used to process and train data to utilize to classify
different types of debris in any type of body... |
import urllib.request as ur
import simplejson as json
###This is an example call to the api
###This example was written for Python 3
#first make a request to the API endpoint url
req = ur.Request('https://6rthd8ogcg.execute-api.us-east-1.amazonaws.com/prod/stockdata')
#then add the headers - the first is the key fo... |
from pygame import mixer
import os.path
import json
print("Loading data.json")
dataFile = open('data.json', 'r')
audioMap = json.loads(dataFile.read())
dataFile.close()
mixer.init()
while True:
key = raw_input('Enter keyword (exit to quit): ')
if key == 'exit':
break
if not key in audioMap:
print('Could not ... |
# Copyright 2020 Open Source Robotics Foundation, Inc.
#
# 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... |
import django
from django.apps import apps, AppConfig
from django.contrib.auth.management import _get_all_permissions
from django.core import exceptions
from django.db import DEFAULT_DB_ALIAS, router
from django.db.models.signals import post_migrate
from django.utils import six
def update_ctypes_permissions(app_confi... |
import argparse
import torch
import torch.nn as nn
import utils
def count_conv2d(m, x, y):
x = x[0] # remove tuple
fin = m.in_channels
fout = m.out_channels
sh, sw = m.kernel_size
# ops per output element
kernel_mul = sh * sw * fin
kernel_add = sh * sw * fin - 1
bias_ops = 1 if m.b... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
config_file = 'search.conf'
api_version = '2015-02-28'
# SS:SS:SS or SS:SS -> # of sec
def get_sec_from_timestr(s):
arr=s.split(':')
if len(arr) == 3:
return str(int(arr[0])* 3600 + int(arr[1])*60 + int(arr[2]) )
elif len(arr) == 2:
... |
__version__ = '0.0.1'
__all__ = ('__version__',)
|
#!/usr/bin/env python
from os import system
log = f'to_summary.log'
# Defaults follow each option as a comment after '#'.
I = ' -i ../Data/' # -i ../Data/ # input directory
O = ' -o ../Output/' # -o ../Output/ # output directory
C = ' -c 0.95' # -c 0.95 # confidence limit
B = ' -b ../Data/Bib/bib.csv' # -b ../Da... |
import numpy as np
from Hilbert import hilbert
# m=5
# n=2**m
# string=" "
# for i in range(0,n):
# if(i>99):
# string=string+str(i)+" "
# elif(i>9):
# string=string+str(i)+" "
# else:
# string=string+str(i)+" "
# print(string)
# listmd=[[0,0] for i in ra... |
"""Provides Symbolic and Reference classes"""
from abc import ABC, abstractmethod
from typing import Any
from varname import varname
from .utils import evaluate_expr
from .context import ContextBase, ContextError
from .expression import Expression
from .function import Function
class Reference(Expression, ABC):
... |
import dash
from utils import basic_modes, get_props
from dash.dash_table import DataTable
import pytest
def get_app(props=dict()):
app = dash.Dash(__name__)
baseProps = get_props()
baseProps.update(dict(sort_action="native"))
baseProps.update(props)
app.layout = DataTable(**baseProps)
... |
from __future__ import unicode_literals
from jsonschema2code.schema_validation.type_validators.custom_type import CustomTypeSchemaValidator
from jsonschema2code.schema_validation.type_validators.date_type import DateTypeSchemaValidator
from jsonschema2code.schema_validation.type_validators.integer_type import IntegerT... |
# coding: utf-8
"""
LogicMonitor REST API
LogicMonitor is a SaaS-based performance monitoring platform that provides full visibility into complex, hybrid infrastructures, offering granular performance monitoring and actionable data and insights. logicmonitor_sdk enables you to manage your LogicMonitor account... |
#
# Example file for working with conditional statements
#
def main():
x, y = 10, 100
# conditional flow uses if, elif, else
# conditional statements let you use "a if C else b"
if __name__ == "__main__":
main()
|
# -*- coding: utf-8 -*-
#!/usr/bin/python
from __future__ import print_function
import random
from datetime import datetime
# import dateutil.parser
class PuzzleA():
def __init__(self, taskName="taskA"):
print("[PuzzleA] new task created: %s" % (taskName))
def process(self, task):
print(... |
import unittest
from katas.kyu_7.functional_addition import add
class AddTestCase(unittest.TestCase):
def test_equals(self):
add_one = add(1)
self.assertEqual(add_one(3), 4)
def test_equals_2(self):
add_three = add(3)
self.assertEqual(add_three(3), 6)
|
# coding:utf-8
from typing import Mapping, Any
import os
import functools
import io
import tempfile
import pytest
from itertools import chain, repeat
from copy import deepcopy
from sklearn.base import BaseEstimator
from multipledispatch import dispatch
from bourbaki.application.config import (
load_config,
dump... |
from django.http import HttpResponse
from . import models
def simple_detail(request, slug):
model = models.SimpleModel.objects.get(slug=slug)
return HttpResponse(model.slug)
def related_detail(request, slug):
model = models.RelatedModel.objects.get(slug=slug)
related = model.related.all()
relat... |
import os
import sqlite3
from calendar import timegm
from datetime import datetime, timedelta
from time import gmtime
import constants
from constants import JOB_TYPE_YEAR, JOB_TYPE_DAY, JOB_TYPE_HOUR, JOB_TYPE_MONTH
from rollup import rollup_sensor
from time_series import Timeseries
from util import epoch_to_date, int... |
# coding: utf-8
# Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c... |
# Utility layer definitions
import numpy as np
import tensorflow as tf
from .interpolate import trilinear_interpolation
class GridEncoding3D(tf.keras.layers.Layer):
"""3d Grid Layer
"""
def __init__(self, nbins : int, out_dims : int, bounds=None, transform=False, interp=True):
"""Initializes the 3D... |
from common import Scraper, ScrapeResult
class WalmartScrapeResult(ScrapeResult):
def parse(self):
alert = False
tag = self.soup.find('button',{"data-automation":"cta-button"})
if tag and 'add to cart' in str(tag).lower():
alert = True
return True
class WalmartScraper... |
# Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: dan@reciprocitylabs.com
# Maintained By: dan@reciprocitylabs.com
from ggrc import db
from ggrc.models.mixins import (
Base, Titled, Described,... |
import numpy as np
from string import punctuation
def extract_words(input_string):
for c in punctuation:
input_string = input_string.replace(c, ' ')
array = input_string.split()
array = array[2:]
occurences = array[1::2]
words = array[0::2]
return words, occurences
def extract_track_id... |
from datetime import datetime, date
def start_of_year(my_date):
"""
Gives the starting date of a month given any date
:param my_date: date, str
:return: str
"""
my_date = datetime.strptime(my_date, '%Y-%m-%d')
starting_date = date(my_date.year, 1, 1)
starting_date = star... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.