content stringlengths 5 1.05M |
|---|
# python3 setup.py build_ext --inplace
from distutils.core import setup
from Cython.Build import cythonize
setup(name='PI Count app',
ext_modules=cythonize("pi.pyx")) |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import copy
import logging
from typing import List, Union, Optional, Tuple
import networkx as nx
import numpy as np
import scipy as sp
from .embedding_container import EmbeddingContainer
from .spectral_embedding import _generate_embedding
from ... |
"""This module handles finding and parsing fides configuration files."""
# pylint: disable=C0115,C0116, E0213
import os
from logging import DEBUG, INFO, getLevelName
from typing import Dict, Optional, Union
from pydantic import Field, validator
from .fides_settings import FidesSettings
class APISettings(FidesSett... |
from sqlalchemy import MetaData
from sqlalchemy.orm import sessionmaker, scoped_session
from zope.sqlalchemy import ZopeTransactionExtension
METADATA = MetaData()
def session_maker_factory(engine):
return scoped_session(
sessionmaker(
bind=engine,
autocommit=False,
ex... |
"""optik.help
Provides HelpFormatter and subclasses -- used by OptionParser
to generate formatted help text.
"""
from __future__ import division
# Copyright (c) 2001-2006 Gregory P. Ward. All rights reserved.
# See the README.txt distributed with Optik for licensing terms.
import os
import textwrap
from optik.optio... |
#!/usr/bin/env python2
from sys import argv
input = int(argv[1])
result = str()
days = input // 86400
hours = input // 3600 % 24
minutes = input // 60 % 60
seconds = input % 60
result = '{}d {}h {}m {}s'.format(days, hours, minutes, seconds)
print(result)
|
import sys
import os
import re
import csv, time
# import pandas as pd
import numpy as np
from subprocess import call
fips = '029'
call(['pdftotext','-layout',sys.argv[1]])
pages = []
currentPage = ''
pageNo = 0
precinctre = re.compile("[.\n](\d{5})") # a pinch of regex to find precinct number
# file and header
outf... |
import torch
import torch.nn as nn
def conv3x3(in_planes, out_planes, stride=1, dilation=1):
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=dilation, bias=False, dilation=dilation
)
def conv1x1(in_planes, out_planes, stride=1):
return nn.Conv2d(in_planes, out_pl... |
#Zip Password Cracker
import optparse
import zipfile
from threading import Thread
def extract_zip(zfile, password):
try:
zfile.extractall(pwd=password)
print "[+] Password Found: " + password + '\n'
except:
pass
def main():
parser = optparse.OptionParser("usage %prog "+\
"-f <zipfile> -d... |
import lib.interfaceUtils as interfaceUtils
import lib.worldLoader as worldLoader
import lib.lookup as lookup
import math
import requests
from io import BytesIO
import nbt
import random as rd
NUMBER = 5
def getBiome(x, z, dx, dz):
"""**Returns the chunk data.**"""
x = math.floor(x / 16)
z = math.floor(z ... |
"""
CMSIS-DAP Interface Firmware
Copyright (c) 2009-2013 ARM Limited
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... |
# (C) British Crown Copyright 2016
"""
Functions to create histograms of precipitation rate from CMIP5 data
Output can be saved as netCDF files using iris.save
Written by Gill Martin
(C) British Crown Copyright 2016
"""
import os.path
import sys
import numpy as np
import iris
def extend_cube_with_dimcoord(cube,dimc... |
from src.controllers.StockController import StockController
from src.controllers.Controller import Controller
|
# -*- coding: utf-8 -*-
# Aufgaben 6, 7, 20, 21, 24, 30, 34, 39, 38, 41, 43 Bis Dienstag
# -----------------
# 41 list in nested loop
# -----------------
words = ['attribution', 'confabulation', 'elocution',
'sequoia', 'tenacious', 'unidirectional']
s = sorted(set([''.join([c for c in w if c in 'aeiou']) fo... |
"""
Definitions, documentation, default values and validation functions for core
Brian preferences.
"""
from numpy import float32, float64, int32
from brian2.core.preferences import BrianPreference, prefs
__all__ = []
def dtype_repr(dtype):
return dtype.__name__
def default_float_dtype_validator(dtype):
... |
#Construction of a minimal NFA accepting a set of strings over {a, b} in
#which each string of the language starts with ‘ab’.
def stateX(n):
if(len(n)==0):
print("string not accepted")
else:
if (n[0]=='a'):
stateY(n[1:])
elif (n[0]=='b'):
print("string not accepted")
def stateY(n):
... |
def ensureFocusHandler():
JS("""
return (focusHandler !== null) ? focusHandler : (focusHandler =
@{{createFocusHandler}}());
""")
def createFocusHandler():
JS("""
return function(evt) {
// This function is called directly as an event handler, so 'this' is
// set up by the b... |
#!/usr/bin/env python3
import os, sys
def readFile(filename):
with open(filename, "rb") as f:
return f.read().decode("utf-8")
def writeFile(filename, data):
with open(filename, "wb") as f:
f.write(data.encode("utf-8"))
filtersXml = sys.argv[1]
code = readFile(filtersXml)
# Add missing Set... |
"""Treadmill event daemon, subscribes to scheduler events.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import click
from treadmill import eventmgr
def init():
"""Top level command handler."""
@clic... |
def selection_sort(arr):
for i in range(len(arr)):
min = i # index of min elem
for j in range(i+1,len(arr)):
# arr[j] is smaller than the min elem
if arr[j] < arr[min]:
min = j
arr[i],arr[min] = arr[min],arr[i] # swap
# print... |
#Copyright [2017] [Mauro Riva <lemariva@mail.com> <lemariva.com>]
#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 ... |
#!/usr/bin/env python3
import chess
import os
import sys
import time
'''
Given a position
get legal moves for that position
for each move
print(fen)
return count of legal moves for that position
u64 Perft(int depth)
{
MOVE move_list[256];
int n_moves, i;
u64 nodes = 0;
if (depth == ... |
'''File Generator Module'''
# modify PATH variable according to the filepath you want generate files in
PATH = "./textfiles/input/input"
file_no = int(input('Enter Number of Files : '))
msg = input('Enter text : ')
print('Length of text is {}'.format(len(msg)))
def generate_files(num):
'''Function for generatin... |
# WARNING: This scripts submits two actual orders
# IMPORTS ---------------------------------------------------------------
# Standard packages
import unittest
import pdb
# Third party packages
pass
# Local packages
from ccat.model.exchange.order import Order
# TESTS ----------------------------------------------... |
#!/usr/bin/env python
from hyperopt import fmin, tpe, hp, Trials
import sys
from .optimization_data import OptimizationData
from .optimization_model import OptimizationModel
from .hyopt import *
from .optimization_metrics import *
import json
import tempfile
import subprocess
from kopt.utils import merge_dicts
import ... |
from tool.runners.python import SubmissionPy
class JonSubmission(SubmissionPy):
def run(self, s):
res = 0
for l in s.splitlines():
words = l.split(" ")
m = mapping(words[:10])
res += m[norm(words[11])] * 1000
res += m[norm(words[12])] * 100
... |
from twisted.internet.protocol import Protocol
from twisted.internet.protocol import Factory
from twisted.internet.endpoints import TCP4ServerEndpoint
from twisted.internet import reactor
from random import randrange
from sys import stdout
from handler_client import ClientHandler
from data_state import Conn
## commen... |
# -*- coding: utf-8 -*-
"""
Take a video file and randomly shuffle segments from it.
Created on Tue Feb 9 20:39:11 2021
@author: CodeWanderer
"""
import moviepy.editor
import random
#Parameter
filepath = '10s count.avi'
#Sequence of starting and ending frame times (in seconds)
startstop = [(0,1),
... |
#!/usr/bin/env python3
import asyncio
import atexit
import calendar
import decimal
import serial
import sys
import time
import scpi
import scpi.transports.rs232
import scpi.transports.gpib.prologix
import scpi.wrapper
class HP34970a(scpi.SCPIDevice):
async def configure_thermocouple(self, channels, probe_type='... |
"""Implements the LEABRA algorithm, v7.0"""
from leabra7.events import Phase
from leabra7.events import PlusPhase
from leabra7.events import MinusPhase
from leabra7.events import NonePhase
from leabra7.net import Net
from leabra7.oscill import Oscill
from leabra7.specs import LayerSpec
from leabra7.specs import Oscill... |
import re
PAGE = 'page'
INSPECT = 'inspect'
ACTION = 'action'
TAKE = 'take'
QUERY = 'query'
SORT = 'sort'
GROUP = 'group'
WHERE = 'where'
FIELD = 'field'
ID = 'id'
DATA = 'data'
SPACE = 'space'
RESOURCE = 'resource'
PARAMETERS = 'parameters'
LEVELED_FEATURES = {
GROUP,
TAKE,
SORT,
WHERE,
PAGE,
}
... |
import os
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from PIL import Image, ImageChops
update = False
def threshold(thres, img):
lim = img.convert('L')
table = []
for i in range(256):
if i < thres:
table.append(0)
else:
... |
# Copyright 2015 Oliver Cope
#
# 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, ... |
import pytest
from src.database import get_database
@pytest.fixture()
def db(tmp_path):
database = get_database()
return database
|
# This file is part of pyplink.
#
# The MIT License (MIT)
#
# Copyright (c) 2014 Louis-Philippe Lemieux Perreault
#
# 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, includ... |
# menuTitle : 03: Experiment - Purple
# shortCut : command+control+shift+3
"""
Mark currently-selected glyphs as "worked on,"
so it's clear they have been edited.
"""
from markLib.markGlyphs import markGlyphs
from markLib.settings import markSettings
f = CurrentFont()
markGlyphs(f, markSettings["experiment"])
|
"""Plottable sounds interface."""
import matplotlib.pyplot as plt
from waves.sound.figure import figure
def plot(sound, show=True, **kwargs):
fig, axs = figure(sound, **kwargs)
if show:
plt.show()
|
"""
Home page script
"""
import dash_html_components as html
import dash_bootstrap_components as dbc
layout = html.Div([
dbc.Container([
dbc.Row([
dbc.Col(html.H1('Introduction', style={
'font-family': 'Overpass, sans-serif',
'font-size': '450%', 'font-weight': ... |
# Generated by Django 3.1.2 on 2021-10-02 13:44
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('payment_module', '0005_auto_20210924_0054'),
]
operations = [
migrations.AddField(
model_name='commission',
name='st... |
import unittest
import random
import time
import numpy as np
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '../../'))
from codes.problems.function_Ackley import function_Ackley
class Test(unittest.TestCase):
def test_1(self):
p = function_Ackley(10)
p.init()
... |
import sys
import unittest
import logging
from pysecm.ric import RIC
from pysecm.ric.index import IndexRIC
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
class IndexTests(unittest.TestCase):
def test_index_rics(self):
rics = ['.SPX', '.VIX6M', '.GSPTSE']
for ric in rics:
... |
import math, random
import gym
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from rllite.common import ReplayBuffer
from IPython.display import clear_output
import matplotlib.pyplot as plt
USE_CUDA = torch.cuda.is_available()
class TinyQRDQN(nn.Module):
def __init__(self, ... |
# Module: asteroidservice.py
from iocompython import Root, EndPoint
import ioterminal
import asteroidapp
import queue, random, time
running_apps = {}
def main():
global root, callback_queue
root = Root('asteroid',security='certfile=myhome.crt,keyfile=secret/myhome.key')
root.queue_events()
ioterminal... |
import logging
import random
import socket
import threading
from urllib.parse import urlsplit, urljoin
from mebo.stream.auth import challenge_response
from mebo.stream.rtp import (
RTPStream
)
from mebo.stream.sdp import (
SDP
)
from mebo.stream.rtsp import (
RTSPResponse,
RTSPRequest,
)
from meb... |
import uuid
from pymongo import MongoClient
client = MongoClient(port=27017)
db = client.cards
DEFAULT_PFP = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSwOAz9F23MraOeH5RtdAj883MB-ywpMIPYSv36fcSVFazd1DQANyabtJ3eKBgRw1_t2PM&usqp=CAU"
def create_user(nickname, username, pfp=DEFAULT_PFP, publish=False):
us... |
class FileAnalyzer:
def __init__(self, filename):
self._filename = filename
with open(filename, 'r') as f:
self._content = f.read()
for c in ".@:()_=#[]":
self._content = self._content.replace(c, ' ')
def display_content(self):
return self._conten... |
from os.path import isabs, expanduser
from xmtrace import xmtrace
@xmtrace
def xm_path_is_absolute(lua, ph):
return isabs(expanduser(ph))
|
import socket
import time
import select
from socket_manager import SocketManager
class SocketServerManager(SocketManager):
def __init__(self, server_ip, port, *args, **kwargs):
super(SocketServerManager, self).__init__(server_ip, port, *args, **kwargs)
def _connect(self):
server_sock = socket... |
"""
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
In... |
from itertools import chain
from typing import Dict, Any, List, Iterable, Type
from argo_client.interaction import ArgoException
class SAWException(Exception):
data: Dict[str, Any]
code: int
stdout: str
stderr: str
def __init__(self, ae: ArgoException) -> None:
super().__init__(ae.message... |
from django.urls import include, path
from rest_framework.routers import DefaultRouter
from ticket_app import views
router = DefaultRouter()
router.register(r'ticket', views.TicketViewSet, basename='Ticket')
urlpatterns = [
path('', include(router.urls)),
]
|
# parameters and paths
from simple_dqn_agent import SimpleDQNAgent
from anon_env import AnonEnv
DIC_EXP_CONF = {
"RUN_COUNTS": 3600,
"TRAFFIC_FILE": [
"cross.2phases_rou01_equal_450.xml"
],
"MODEL_NAME": "SimpleDQN",
"NUM_ROUNDS": 200,
"NUM_GENERATORS": 3,
"LIST_MODEL":
["Si... |
import numpy as np
import time
from code.simulator import *
from code.cost_functions import residual_acc, residual_gyr
from code.helpers import *
from code.utilities import *
np.set_printoptions(edgeitems=30, linewidth=1000, formatter={'float': '{: 0.4f}'.format})
def monte_carlo_cycle(N_samples, dt, theta_acc, the... |
# Generated by Django 3.1.4 on 2021-05-27 09:58
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('Global', '0008_remove_automatıons_content'),
]
operations = [
migrations.CreateModel(
name='Advertisementss',
fields... |
from datetime import timedelta, datetime
from difflib import SequenceMatcher
from functools import reduce
from itertools import zip_longest, compress, chain, product, combinations
from math import sqrt, ceil
from typing import Generator
def clamp(value: float, smallest: float = 0, largest: float = 1) -> float:
... |
import psycopg2
import pytest
from portal.db import get_db
from portal.grades import get_grades, grade_calc
# Join Table - To View
# SELECT a.name, g.points_earned a.points
# FROM assignments a, grades g
# WHERE g.assignment_id = a.id;
# Join Table - If Course ID is needed
# SELECT a.course_id, a.section, a.name, g.... |
import editor # Needed for InteractiveLogger
import os
import json
class InteractiveLogger:
def __init__(self, LOG_DIR ):
self.LOG_DIR = LOG_DIR
self.string_data = []
print '[InteractiveLogger] LOG_DIR = ', LOG_DIR
print '[InteractiveLogger] mkdir -p ', LOG_DIR
try:
... |
import contextlib
from nose.tools import assert_equal, assert_false, assert_raises, assert_true
from mock import call, patch, MagicMock
@contextlib.contextmanager
def fake_timeout_fail(*args, **kwargs):
from unicornherder.timeout import TimeoutError
raise TimeoutError()
|
import os
import re
from typing import Any, Optional, Text
from pathlib import Path
from rasa.shared.exceptions import RasaException
import rasa.shared.utils.io
def relative_normpath(f: Optional[Text], path: Text) -> Optional[Path]:
"""Return the path of file relative to `path`."""
if f is not None:
... |
class SerializationException(Exception):
def __init__(self, error_message, path, result, backup_path=None):
self.path = path
self.backup_path = backup_path
self.result = result
super(SerializationException, self).__init__(error_message)
class DeserializationException(Excepti... |
# coding=utf-8
# Copyright 2018 The Google AI Language Team 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 required by ... |
import unittest
import re
from g1.asyncs import kernels
from g1.asyncs.bases import locks
from g1.asyncs.bases import servers
from g1.asyncs.bases import tasks
class SuperviseServerTest(unittest.TestCase):
def setUp(self):
super().setUp()
self.queue = tasks.CompletionQueue()
self._asser... |
# Generated by Django 4.0.1 on 2022-03-23 22:39
from django.db import migrations, models
import encrypted_fields.fields
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='GoElectricRebateApplication'... |
# Protean
import pytest
from mock import patch
from protean.core.subscriber import BaseSubscriber
from protean.utils import fully_qualified_name
# Local/Relative Imports
from .elements import NotifySSOSubscriber, Person, PersonAdded
class TestSubscriberInitialization:
def test_that_base_subscriber_class_cannot_... |
# -*- coding: utf-8 -*-
import os
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.db import models
from django.db.models import Q
from django.utils.translation import ugettext_lazy as _
from django.utils.safestring import mark_safe
... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
def sum_of_multiples(limit, multiples):
sum = 0
for multiple in range(limit):
for divisor in multiples:
if multiple % divisor == 0:
sum += multiple
break
return sum
|
from pathlib import Path
import wget
import pickle
import os
import pandas as pd
import numpy as np
import torch
import torch.nn as nn
from copy import deepcopy as c
def get_project_root() -> Path:
return Path(__file__).parent.parent
PROJECT_ROOT = get_project_root()
def _exist_dataset_on_disk(dataset):
f... |
import sys
def maxTrianglePath(filename):
# maxColSum is the running max sum for each column
# It will have num columns + 1 entries to support n + 1 comparisons
maxColSum = [0,0]
# File automatically closes when deleted
f = open(filename, 'r')
for rowNum, line in enumerate(f):
# Convert... |
# -*- coding: utf-8 -*-
'''
Coldsweat - RSS aggregator and web reader compatible with the Fever API
Copyright (c) 2013—2016 Andrea Peltrin
Portions are copyright (c) 2013 Rui Carmo
License: MIT (see LICENSE for details)
'''
__author__ = 'Andrea Peltrin and Rui Carmo'
__version__ = (0, 9, 8, '')
__license__ = 'MIT'
... |
import os
import unittest
# import sys
# sys.path.insert(0, '/Users/anchuang/learn/filter/')
from filter import spam_filter
class BayesTest(unittest.TestCase):
def setUp(self):
try:
os.remove(os.path.join(spam_filter.BASE_DIR, 'cache/vector.cache'))
os.remove(os.path.join(spam_fil... |
import unittest
from nextnanopy.utils.datasets import Data, Variable, Coord
from nextnanopy.utils.datasets import default_unit
import numpy as np
class TestDatasets(unittest.TestCase):
def test_Data(self):
ds = Data(name='test', value=2)
self.assertEqual(ds.name, 'test')
self.assertEqual(d... |
import torch
from .kernel import Kernel
class NormalizedKernel(Kernel):
""" Base class for normalized kernels """
def default_density(self):
raise NotImplementedError
def set_density(self):
raise NotImplementedError
def log_prob(self, state):
return torch.sum(self.density.lo... |
from algorithms.linalg_utils import *
def model(f, g, b, x, p, delta):
if la.norm(p) > delta:
raise ArithmeticError('P must not be bigger than delta, p and delta:', p, la.norm(p), delta)
return f(x) + np.matmul(g(x).T, p) + .5*np.matmul(np.atleast_1d(np.matmul(p.T, b)), p)
def trust_region(f, g, hf,... |
from time import time
import argumentparser
import pandas as pd
import os
from ngram import LanguageModel, NaiveBayesClassifier
import logging
BASE_DIR = os.path.dirname(os.path.realpath(__file__))
# logging_filename = os.path.join(BASE_DIR, "logging", "process_times.log")
# logging.basicConfig(
# filename=loggi... |
from rest_framework.viewsets import ViewSet
from rest_framework.response import Response
from rest_framework import status
from core.models import Book
class BooksView(ViewSet):
def create(self, request):
data = request.data
print(data)
book = Book()
book.insert(data)
ret... |
import nmap
import csv
from os import getcwd
print(" _____ _____ _____ _____ _____ _____ ")
print(" /\ \ /\ \ /\ \ /\ \ ... |
"""Tests for geoprocessing services."""
# Python 2/3 compatibility
from __future__ import (absolute_import, division, print_function, unicode_literals)
from future.builtins.disabled import *
from future.builtins import *
from future.standard_library import install_aliases
install_aliases()
# Third-party imports
impor... |
def from_string_pdbid(item, molecular_system=None, atom_indices='all', frame_indices='all'):
from molsysmt.forms.ids.api_id_PDB import to_mmtf_MMTFDecoder as id_PDB_to_mmtf_MMTFDecoder
from molsysmt.native.io.molsys.classes import from_mmtf_MMTFDecoder as mmtf_Decoder_to_molsysmt_MolSys
tmp_item, tmp_mole... |
returnedDate = [ int( x ) for x in input( ).split( ' ' ) ]
dueDate = [ int( x ) for x in input( ).split( ' ' ) ]
fine = 0
if returnedDate[ 2 ] > dueDate[ 2 ]:
fine = 10000
elif returnedDate[ 2 ] < dueDate[ 2 ]:
fine = 0
elif returnedDate[ 2 ] == dueDate[ 2 ] and returnedDate[ 1 ] > dueDate[ 1 ]:
fine = 50... |
import os
from sandbox.rocky.tf.baselines.nn_baseline import NNBaseline
from sandbox.rocky.tf.core.network import ConvNetwork
from sandbox.rocky.tf.policies.gaussian_conv_feature_policy import GaussianConvFeaturePolicy
from sandbox.rocky.tf.policies.gaussian_conv_policy import GaussianConvPolicy
from rllab.baselines.ze... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Helper functions and functions for plotting gamma-ray images."""
import numpy as np
from astropy.coordinates import Angle
__all__ = ["colormap_hess", "colormap_milagro", "MapPanelPlotter"]
__doctest_requires__ = {("colormap_hess", "colormap_milagro"):... |
import matplotlib
matplotlib.use('AGG')
from datetime import datetime
from stem_pytools import NERSC_data_paths as ndp
from aqout_postprocess_spatial_paper import AqoutContainerSpatialPaper
t0 = datetime.now()
runs = ndp.get_Spatial_Paper_runs()
sib_runs = ['SiB_calc', 'SiB_mech']
aqcs = {this_run: AqoutContainerSp... |
__author__ = 'dylan'
# Sets of Flow Scheduling requests used to test ARScheduling module
test_dictionary = {
1: [("10.0.0.1", "00:00:00:00:00:01", "10.0.0.2", "00:00:00:00:00:02", "1", "00:00", "00:01"),
("10.0.0.1", "00:00:00:00:00:01", "10.0.0.2", "00:00:00:00:00:02", "2", "00:00", "00:01"),
("10... |
import numpy as np
def source(x,y,xs,ys): return 0.5*np.log((x-xs)**2+(y-ys)**2)
GAUSS2 = 0.5*(1+np.sqrt(1/3)) # gaussian-quadrature sample point
def potential(x,y,x0,y0,x1,y1,G=source,args=()):
"Gaussian quadrature estimate of the potential influence function"
def dG(s): return G(x,y,x0*(1-s)+x1*s,y0*(1-s)+y1*s,... |
import os.path as osp
import argparse
parser = argparse.ArgumentParser(description='YsqNet')
parser.add_argument('--rootDir', default=osp.abspath(osp.join(osp.dirname(__file__))), type=str,
help='choose the dir of dataset')
parser.add_argument('--dataDir', default='/home/stu4/user/ysq/voc2007',
... |
"""Initial revision consolidating previous revisions 1 to 6"""
import time
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '0007'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
op.create_table(
'roles',
sa.Column('i... |
import scapy.all as scapy
import psutil
import logging
import binascii
import datetime
logging.basicConfig(format='%(levelname)s - %(asctime)s - %(message)s',
datefmt='%d-%b-%y %H:%M:%S',
level=logging.INFO)
class Network:
def __init__(self, interface):
self.interfa... |
__version__ = '0.0.9a1' |
from contextlib import contextmanager
from http import HTTPStatus
from fastapi.concurrency import contextmanager_in_threadpool
from fastapi.requests import Request
from fastapi.responses import RedirectResponse
from fastapi.routing import APIRouter
from watch_n_learn.authentication.main import get_user, remove_authen... |
# flake8: noqa
from __future__ import print_function, unicode_literals, absolute_import
# Configure logging and initialize the root sprokit logger
from kwiver.vital import vital_logging
vital_logging._configure_logging()
logger = vital_logging.getLogger(__name__)
|
"""UNIT TEST for OLR plot
"""
import numpy as np
import sys
sys.path.append('../TropicalCyclones_py2')
import olr_stamps as olr
o = olr.OLR()
o.olrloop()
|
#!/usr/bin/env python
# coding: utf-8
# Import modules
import math
import numpy as np
import pandas as pd
import os
import shutil
from time import time
import obspy
from obspy.geodetics import locations2degrees
from datetime import datetime, timedelta, timezone
from obspy import UTCDateTime, read, read_inventory, read... |
from django.urls import path
from contact.views import ListView, DetailView, ContactAPI
urlpatterns = [
path('<int:id>/', DetailView.as_view(), name='details'),
path('', ListView.as_view(), name='list'),
path('api/', ContactAPI.as_view())
]
|
from .nsw_config import NSWConfig
from .vic_config import VictoriaConfig
def config_factory(location: str):
if location == 'VIC':
return VictoriaConfig()
if location == 'NSW':
return NSWConfig()
return None
|
TEXT_INPUT = "text input"
POSITIVE_INPUT = "positive input"
|
# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/
TIME_ZONE = 'UTC'
USE_TZ = True
|
# Licensed to Modin Development Team under one or more contributor license agreements.
# See the NOTICE file distributed with this work for additional information regarding
# copyright ownership. The Modin Development Team licenses this file to you under the
# Apache License, Version 2.0 (the "License"); you may not u... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2017-11-01 15:53
from __future__ import absolute_import, unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('django_celery_beat', '0004_auto_20170221_0000'),
]
operations = [
... |
# Convert .json from labelme to VOC .xml format.
from collections import OrderedDict
import json
import os
from utils import *
class2skip = [
# 'sign', 'window', 'tree'
]
# ROOT = '/Users/yisun/Desktop/Robotics_SemanticLines/data/KAIST_labeled/'
# ROOT = '/Users/yisun/Desktop/Robotics_SemanticLines/data/KAIST_q... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.