content stringlengths 5 1.05M |
|---|
# Creates manual snapshots of RDS Instances
import boto3
import datetime
import time
def lambda_handler(event, context):
#connecting to rds client interface
rds = boto3.client('rds')
#creates place holder for instances to be backed up
instances_to_backup = []
response = rds.describe_db_instances()
i... |
#!/usr/bin/python
## This uses ephemeral.
import optparse, os, shutil, sys, tempfile, glob, shlex, vcf, pysam, tarfile
from subprocess import *
import subprocess
CHUNK_SIZE = 2**20 #1mb
def cleanup_before_exit( tmp_dir ):
if tmp_dir and os.path.exists( tmp_dir ):
shutil.rmtree( tmp_dir )
def __main__()... |
from collections import OrderedDict
import logging
import os
import shutil
import subprocess
import simtk.unit as units
from intermol.desmond.desmond_parser import load, save
DES_PATH = ''
logger = logging.getLogger('InterMolLog')
# terms we are ignoring for now.
#'en': 'Raw Potential',
#'E_x': 'Extended En.',
un... |
import networkx as nx
from omlt.neuralnet.layer import Layer
class NetworkDefinition:
def __init__(self, scaling_object=None, scaled_input_bounds=None):
"""
Create a network definition object used to create the neural network
formulation in Pyomo
Args:
scaling_object :... |
#!/usr/bin/env python3
import sys, os, json, csv
from math import log
import matplotlib.pyplot as plt
import numpy as np
from scipy.interpolate import make_interp_spline, BSpline
# CREDITS
# Interpolation based upon: https://stackoverflow.com/questions/5283649/plot-smooth-line-with-pyplot
# Logarithmic scale: https:/... |
#!/usr/bin/env python3
#******************************************************************************
# (C) 2018, Stefan Korner, Austria *
# *
# The Space Python Library is free software; you can redi... |
# Copyright (C) 2020 Electronic Arts Inc. All rights reserved.
import pandas
class GameHistoryEntry:
def __init__(self, tick, state, player_identity_list, player_policy_list, player_action_list,
player_value_estimate_list, player_reward_list):
self.tick = tick
self.state = state... |
'''
minesweeper in the console... works pretty ok
'''
import numpy as np
from timeit import default_timer
class Minesweeper:
"""class represents the game & associated metadata"""
def __init__(self, rows=10, cols=8, mines=None):
self.rows = rows
self.cols = cols
# board is rows * cols;... |
import fastf1 as ff1
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
from matplotlib import cm
import numpy as np
ff1.Cache.enable_cache('../doc_cache') # replace with your cache directory
session = ff1.get_session(2021, 'Austrian Grand Prix', 'Q')
laps = session.load_laps(with_tele... |
"""
Python Script for adding 1 & 2 finger multitouch gestures to implement
a right click option with Touchscreens in the Ubuntu unity environment.
This is implemented with the evdev Python library on an ELAN touchscreen.
Currently implements 2 types of right click options:
1 finger long touch: Timeout of 1.5 seconds,... |
'''OpenGL extension AMD.compressed_3DC_texture
This module customises the behaviour of the
OpenGL.raw.GLES2.AMD.compressed_3DC_texture to provide a more
Python-friendly API
Overview (from the spec)
Two compression formats are introduced:
- A compression format for two component textures. When used ... |
MOD = 10**9+7
def valueFromList(head):
value = 0
current_node = head
while current_node:
value = (value * 10) + current_node.data
current_node = current_node.next
return value
def multiplyTwoList(head1, head2):
val1 = valueFromList(head1)
val2 = valueFromList(head2)
... |
import pathlib
from aws_cdk import aws_apigatewayv2_alpha as apigatewayv2_alpha
from aws_cdk import (
aws_apigatewayv2_integrations_alpha as apigatewayv2_integrations_alpha,
)
from aws_cdk import aws_lambda as lambda_
from aws_cdk import aws_lambda_python_alpha as lambda_python_alpha
from constructs import Constru... |
# optimizer
optimizer = dict(type='SGD', lr=30, momentum=0.9, weight_decay=0.0)
# learning policy
lr_config = dict(policy='CosineAnnealing', min_lr=0.)
# runtime settings
runner = dict(type='EpochBasedRunner', max_epochs=100)
|
# -*- coding: utf-8 -*-
"""
Tested
Works
"""
import camera
import crop
import imageWorker as iW
import cv2
import math
def camCalib():
# #LIVE
# #Connect to camera
cam = camera.camera()
cam.cameraOn()
#Create image worker
imgWork = iW.ImgWorker()
print("La bordet kun inneh... |
import ns.core
import numpy as np
from src.simulator.internet.communicator import Communicator
from collections import OrderedDict
CHECK_TIME_SLOT = 0.0001
DEFAULT_TIME_SLOT = 0.1
DEFAULT_OFFLINE_NUMBER = 0
MAX_BLOCK_DURATION = 9999999999999
BASE_PORT = 5000
class DecentralizedConsensus:
def __ini... |
import tensorflow as tf
import os
##############################################################################
# Load model
##############################################################################
ROOT_DIR = os.getcwd()
# Model Directory
MODEL_DIR = "/datasets/models/mrcnn/fullstack_fullnetwork/chips20200326T... |
from django.contrib.auth import login
from django.views.decorators.csrf import csrf_exempt, ensure_csrf_cookie
from rest_framework import permissions, status
from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response
from social.apps.django_app.utils import strategy,... |
# -*- coding: utf-8 -*-
from formalchemy.tests import *
def test_renderer_names():
"""
Check that the input name take care of multiple primary keys::
>>> fs = FieldSet(primary1)
>>> print(fs.field.render())
<input id="PrimaryKeys-1_22-field" maxlength="10" name="PrimaryKeys-1_22-field"... |
import asyncio
class Pauser:
"""
A helper class to provide pause / resume functionality to other classes.
"""
def __init__(self) -> None:
self._paused = False
self._resumed = asyncio.Event()
@property
def is_paused(self) -> bool:
"""
Return ``True`` if the sta... |
import attr
from cortexpy.constants import EdgeTraversalOrientation
@attr.s(slots=True)
class OrientedGraphFuncs(object):
graph = attr.ib()
orientation = attr.ib()
color = attr.ib(None)
edges = attr.ib(init=False)
other_edge_node = attr.ib(init=False)
def __attrs_post_init__(self):
a... |
"""Policy package"""
from KID.policy.base_policy import BasePolicy
from KID.policy.kid_policy import KIDPolicy
__all__ = [
'BasePolicy',
'KIDPolicy',
]
|
from vtkplotter import Cube, Text, show, collection
from vtkplotter.settings import fonts
Text("List of available fonts:")
Cube().c('white').rotateX(20).rotateZ(20)
for i, f in enumerate(fonts):
Text(f+': The quick fox jumps over the lazy dog.',
pos=(5,i*40+20), font=f, c=i%3)
show(collection(), axes=... |
class Solution:
def solve(self, n, m):
if n%2==0:
return m*(n//2)
if m%2==0:
return n*(m//2)
return ((n-1)//2)*m + (m-1)//2 |
import os
import xgcm
import dask
import numpy as np
import xarray as xr
import pop_tools
import tqdm.notebook as tqdm_notebook
import matplotlib.pyplot as plt
from grid import create_tdepth, find_array_idx
from paths import file_ex_ocn_ctrl, path_prace
from xr_DataArrays import xr_DZ, xr_DXU, xr_DZ_xgcm
from xhistogr... |
import logging
from django.db import transaction
from wikidata import wikidata
from tkapi.util import queries
from tkapi.zaak import ZaakSoort
from tkapi.besluit import Besluit as TKBesluit
from person.util import parse_name_surname_initials
from person.models import Person
from parliament.models import ParliamentM... |
import pygame
class Ant:
def __init__(self):
self.nodes = {}
self.node_size = 10
self.width = 1001
self.height = 1001
self.backg_color = (145,73,48)
self.pixel_color = (207,148,110)
self.ant_color = (0,0,0)
self.ant_start_x = 501/self.node_size
... |
import unittest
from unittest.mock import patch
import fs.path
from moban.core.mobanfile.templates import handle_template
class TestHandleTemplateFunction(unittest.TestCase):
def setUp(self):
self.base_dir = [fs.path.join("tests", "fixtures")]
def test_copy_files(self):
results = list(
... |
#!/usr/bin/env python3
from .baseController import *
"""
#################
# The Functions #
######################################
## Global file with all the functions.
######################################
"""
class BUFFALO(BaseController):
def defineController(self):
self.name = 'Buffalo controller'
|
# Generated by Django 3.0.5 on 2020-06-01 22:25
from decimal import Decimal
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Order',
... |
# Copyright 2015 The Switch Authors. All rights reserved.
# Licensed under the Apache License, Version 2, which is in the LICENSE file.
"""
Defines timescales for investment and dispatch for the SWITCH-Pyomo model.
SYNOPSIS
>>> from switch_mod.utilities import define_AbstractModel
>>> model = define_AbstractModel('ti... |
# Copyright 2021 Huawei Technologies Co., Ltd
#
# 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... |
import time
import logging
logger = logging.getLogger(__name__)
class Steps:
fstep = 0
lstep = -1
times = []
tags = []
def __init__(self, fs = 0, ls=1000):
self.fstep = fs
self.lstep = ls
def isstep(self, step, tag=""):
if self.lstep >= step >= self.fstep:
... |
# -*- coding: utf-8 -*-
"""
Created by zejiran.
"""
def cargar_tablero_goles(ruta_archivo: str) -> list:
"""
Esta función carga la información de un tablero de goles
a partir de un archivo CSV.
La primera fila del archivo contiene la dimensión del tablero (cuadrado).
Parámetros:
ruta_arch... |
#!/usr/bin/env python3
#****************************************************************************************************************************************************
# Copyright (c) 2014 Freescale Semiconductor, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
#... |
#!/usr/bin/python
# Copyright 2020 Amazon.com, Inc. or its affiliates. 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.
# A copy of the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "LIC... |
from docopt import docopt
from os.path import isfile
from datetime import datetime
import locale
import asyncio
import json
from colorama import Fore, ansi
from .bandcamp import Bandcamp
DOC = """
Camp Collective.
Usage:
camp-collective -c=<cookie>... [options] download-collection [<target-directory>]
Option... |
"""
Toggles for the Agreements app
"""
from opaque_keys.edx.keys import CourseKey
from openedx.core.djangoapps.waffle_utils import CourseWaffleFlag
# .. toggle_name: agreements.enable_integrity_signature
# .. toggle_implementation: CourseWaffleFlag
# .. toggle_default: False
# .. toggle_description: Supports rollou... |
#!/usr/bin/env python
import argparse
import logging
import csv
import json
import sys
import gzip
import bz2
import os
logging.basicConfig(
format='%(message)s',
level=logging.INFO)
log = logging.getLogger(__name__)
# Handle py2 and py3 file differences
if sys.version_info[0] == 3:
from io import IOBa... |
from numpy import random
import pytest
@pytest.fixture
def generator(request):
seed_string = request.node.nodeid
seed = [ord(character) for character in seed_string]
return random.default_rng(seed)
|
import tornado.web
from tornado.options import define, options
import tornado.ioloop
import os
from handlers import *
from storage import *
define("db_connstr", help="PostgreSQL connection string")
define("port", default="44321", help="Port for hosting service")
settings = {
"debug" : True,
"gzip" ... |
#!/usr/bin/env python3
#
# This is a small script that intercepts the build command, and
# applies it to multiple directories, in parallel.
#
import multiprocessing.dummy
import pathlib
import subprocess
import sys
sys.path.insert(0, "development-support")
import _install_tool
jobs = int(sys.argv[1])
cmd = sys.argv... |
#
# 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... |
from collections import Counter
class Solution:
def numSplits(self, s: str) -> int:
left = Counter()
right = Counter(s)
count = 0
for i in range(len(s)):
left[s[i]] += 1
right[s[i]] -= 1
if right[s[i]] == 0:
del right[s[i]]
... |
from collections import OrderedDict
import click
import trisicell as tsc
from trisicell.commands._bnb import bnb
from trisicell.commands._booster import booster
from trisicell.commands._consensus import consensus
from trisicell.commands._grmt import grmt
from trisicell.commands._huntress import huntress
from trisicel... |
import scipy.io.wavfile as sio
import scipy.signal as sis
from scipy import interpolate
import numpy as np
import math
import matplotlib.pyplot as plt
import mylib as myl
import sys
import copy as cp
import re
import scipy.fftpack as sf
# NOTE: int2float might be removed after scipy update/check
# (check defaul... |
TIME_REGION = [350, 1035, 140, 40] # left, top, width, height
FPS_REGION = [2100, 950, 400, 150] # left, top, width, height
SIMULATION_SPEED = 1.4 # Slower = .6, Slow = .8, Normal = 1, Fast = 1.2, Faster = 1.4
THREADS = 6 # Use as many CPU threads as you have |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
#
from dataclasses import dataclass
@dataclass
class Options:
"""Class for defining... |
from src.csv_parser import CSVParser
import logging
from src.config import cfg
import src.logger
from itertools import islice
from src.db import Database
import os
import json
from typing import List
from psycopg2.extras import execute_values
import psycopg2
def insert_to_db(rows):
cursor = Database.database_conn... |
import argparse
import logging
import os
import tensorflow as tf
from nlpvocab import Vocabulary
from .input import RESERVED, vocab_dataset
from .model import _unit_embedder
from .config import VectModel, build_config
def extract_vocab(data_path, config):
dataset = vocab_dataset(data_path, config)
label_voca... |
# -*- coding: utf-8 -*-
"""Meta-transformers for building composite transformers."""
# copyright: sktime developers, BSD-3-Clause License (see LICENSE file)
from sklearn.base import clone
from sktime.base import _HeterogenousMetaEstimator
from sktime.transformations.base import BaseTransformer
__author__ = ["fkiraly... |
from oslo_config import cfg
from hsm import flags
from hsm import utils
db_opts = [
cfg.StrOpt('db_backend',
default='sqlalchemy',
help='The backend to use for db'),
cfg.BoolOpt('enable_new_services',
default=True,
help='Services to be added to th... |
import Config
import http.server
import json
import os
import time
import urllib.parse
from pymongo import cursor
class REST(http.server.BaseHTTPRequestHandler):
"""
The RequestHandler-class gets instantiated once per HTTP-request and handles it.
Every HTTP-request is passed to the related HTTP Method h... |
import cv2
import numpy as np
face_cascade = cv2.CascadeClassifier('/users/shreykhandelwal/opencv/haarcascade_frontalface_default.xml')
cap = cv2.VideoCapture(0)
while True:
ret, frame= cap.read()
frame = cv2.resize(frame, None, fx= 0.5, fy= 0.5, interpolation= cv2.INTER_AREA)
gray = cv2.cvtColor(frame, cv2.COLOR_BG... |
f = open('a.txt')
f.read()
print(f) |
# Generated by Django 2.1.5 on 2019-04-16 08:51
import CRM.models
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('CRM', '0006_auto_20190319_0815'),
]
operations = [
migrations.AlterField(
model_name='client',
nam... |
from typing import List
from requests.auth import HTTPBasicAuth
from shared.logger.logging_config import logger
from shared.models.feature_store_models import Feature, FeatureSet
from ...rest_api import crud
from ..fixtures.conftest import APP, get_my_session, override_get_db, test_app
from ..fixtures.feature import... |
'''
双足机器人的配置文件
'''
#############################
## 树莓派版本号
##
#############################
RASP_VERSION = 4
#############################
## DBSP参数
##
#############################
# DBSP树莓派拓展版对应的端口号
DBSP_PORT_NAME = '/dev/ttyAMA0' if RASP_VERSION == 3 else '/dev/ttyS0'
# DBSP串口连接的波特率
DBSP_BAUDRATE = 57600
########... |
# coding: utf-8
# In[2]:
# A script to calculate tolerance factors of ABX3 perovskites using bond valences from 2016
# Data from the International Union of Crystallography
# Author: Nick Wagner
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import pymatgen as mg
from pymatgen.analysis.bond_va... |
import os
import sys
from numpy import random
import math
import re
import time
import numpy as np
import cv2
import matplotlib
import matplotlib.pyplot as plt
import json
from PIL import Image, ImageDraw
from tensorflow.python.framework.versions import VERSION as __version__
import tensorflow as tf
from imgaug import ... |
from uuid import uuid4
class AbstractStorage(object):
def __init__(self, manager, **config):
self.manager = manager
self.init(**config)
def begin(self):
transaction = uuid4().hex
self.initialize_transaction(transaction)
return transaction
def initialize_transactio... |
from motion_detector import df
from bokeh.plotting import figure, show, output_file
from bokeh.models import HoverTool, ColumnDataSource
df["Start_string"]=df["Start"].dt.strftime("%Y-%m-%d %H:%M:%S")
df["End_string"]=df["End"].dt.strftime("%Y-%m-%d %H:%M:%S")
plot=figure(x_axis_type='datetime',height=200, w... |
import rospy
import os
from sensor_msgs.msg import CameraInfo, Image
__all__ = ('ImagePublisher')
class ImagePublisher:
"""Wrapper to publish images to a topic."""
def __init__(self, topic, frame_id, camera_info, queue_size=None):
"""[summary]
Arguments:
topic {str} -- image top... |
import sys
sys.path.append('../')
import config as cf
from word_feature.utils import get_unique_word, read_caption_clean_file, map_w2id
import numpy as np
def load_glove(path):
"""
Give you the dict of word and its coefficent
"""
f = open(path, encoding='utf-8')
print("Loading the /{}/ vector"... |
"""instagram URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-bas... |
from django import forms
from .models import Procedure,Profile
class ProcedureForm(forms.ModelForm):
class Meta:
model = Procedure
exclude = ['user','user_procedure_id']
class ProfileForm(forms.ModelForm):
class Meta:
model = Profile
exclude = ['prof_user','profile_Id']
class... |
#!/usr/bin/evn python
import threading
from scapy.all import *
import subprocess as sp
import Queue
import time
class Sniffer(threading.Thread):
def __init__(self, queue, *args, **kwargs):
threading.Thread.__init__(self, *args, **kwargs)
self.__queue = queue
sp.Popen(['hostapd', '/etc/host... |
# ------------------------------------------------------------------------------
# Created by Tyler Stegmaier
# Copyright (c) 2020.
#
# ------------------------------------------------------------------------------
from typing import List, Tuple
from ..Widgets.base import *
__all__ = ['Style']
class Style(ttk.... |
import sys
import pytest
if __name__ == "__main__":
repeat_times = 3
for index, arg in enumerate(sys.argv):
if arg == '-n':
repeat_times = int(sys.argv[index + 1])
pytest.main(['--repeat-count=%s' % repeat_times, 'test_hilauncher_gfx.py'])
|
#!/usr/bin/env python
#
# Exploit Title : Allok AVI DivX MPEG to DVD Converter - Buffer Overflow (SEH)
# Date : 3/27/18
# Exploit Author : wetw0rk
# Vulnerable Software : Allok AVI DivX MPEG to DVD Converter
# Vendor Homepage : http://alloksoft.com/
# Version : 2.6.... |
from API_operaciones.mysql_connection import app
from API_operaciones.mysql_connection import mysql2 as mysql
from API_operaciones.bd_descripcion import pimcBD
import MySQLdb
def eliminarElemento(elementoRelacional, parametrosJSON):
cur = mysql.cursor()
if (not pimcBD.tablaExiste(elementoRelacional)):
raise V... |
import json
import logging
import re
import unicodedata
import backoff
import dateutil.parser
from bs4 import BeautifulSoup, NavigableString
from urllib import request, parse, error
logger = logging.getLogger(__name__)
class ConfluenceAPI(object):
"""Confluence API Class
This class acts as an API bridge ... |
import setuptools
setuptools.setup(
name="pycef",
version="1.0",
author="Bubba",
author_email="[email protected]",
description="A py wrapper for close ended fund connect portal",
long_description='Rough API around cefconnect.com via web scraping',
long_description_content_type="text/mar... |
# _*_ coding: utf-8 _*_
"""
Time: 2021/7/22 17:29
Author: WANG Bingchen
Version: V 0.1
File: model.py
Describe:
"""
from .lossFunc import *
from .initialParams import *
import pandas as pd
from .optimize import CVOptimize, FanoOptimize, CCVOptimize
from . import utiles
from .cell_circle import CellCircle
i... |
""" Utilities for parsing settings """
def asdict(setting, value_type=lambda x: x):
"""
Parses config values from .ini file and returns a dictionary
Parameters
----------
setting : str
The setting from the config.ini file
value_type : callable
Run this function on the values o... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: app_health_config_variable.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from ... |
import json
from mock import MagicMock
from pyramid.security import ALL_PERMISSIONS
class TestNestedMutationDict:
def test_dictwrapper_comparison(self):
from kotti.sqla import NestedMutationDict
assert NestedMutationDict({}) == NestedMutationDict({})
assert (
NestedMutationDi... |
"""
List of Linux distributions that get packaging
https://wiki.ubuntu.com/Releases
https://www.debian.org/releases/
https://fedoraproject.org/wiki/Releases
https://fedoraproject.org/wiki/End_of_life
"""
ubuntu_deps = ["torsocks", "python3", "openssh-client", "sshfs", "conntrack"]
ubuntu_deps_2 = ubuntu_deps + ["py... |
import pandas as pd
# Create a Pandas dataframe from some data.
data = [10, 20, 30, 40, 50, 60]
df = pd.DataFrame({'Heading': data,
'Longer heading that should be wrapped' : data})
out_path = r'C:\Users\Gael\Desktop\export_dataframe.xlsx'
# Create a Pandas Excel writer using XlsxWriter as the... |
#
# LGE Advanced Robotics Laboratory
# Copyright (c) 2020 LG Electronics Inc., LTD., Seoul, Korea
# All Rights are Reserved.
#
# SPDX-License-Identifier: MIT
#
import os
import sys
import launch.actions
import launch_ros.actions
from ament_index_python.packages import get_package_share_directory
from launch import La... |
import tkinter as tk
from tkinter import messagebox
root = tk.Tk()
root.withdraw()
__all__ = ['universal'] |
import collections
import itertools
import re
import sys
import typing
from copy import deepcopy
class Point(typing.NamedTuple):
x: int
y: int
Grid = list[list[str]]
def main():
with open(sys.argv[1]) as f:
grid: Grid = [list(line.strip()) for line in f.readlines()]
height = len(grid)
... |
"""Run a discrete-event simulation of an asynchronous evolutionary
algorithm with only cloning and selection, so we can track the
takeover times of particular genomes."""
import inspect
import os
import sys
from matplotlib import pyplot as plt
import numpy as np
import toolz
from leap_ec import ops, probe
from leap_e... |
#!/usr/bin/python3 -u
# Example to set profile on NOLA-12 testbed:
# ./sdk_set_profile.py --testrail-user-id NONE --model ecw5410 --ap-jumphost-address localhost --ap-jumphost-port 8823 --ap-jumphost-password pumpkin77 \
# --ap-jumphost-tty /dev/ttyAP1 --testbed "NOLA-12" --lanforge-ip-address loca... |
from collections import deque
import random
class Queue:
def __init__ (self):
self._init ()
self._req_id = 0
self._consumed = 0
def qsize (self):
return len (self.q)
@property
def req_id (self):
req_id = self._req_id
self._req_id += 1
return req_id
def add (self, req):
self._add (req) ... |
# Generated by Django 2.2 on 2020-11-05 01:23
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('user', '0052_auto_20201105_0026'),
]
operations = [
migrations.AddField(
model_name='user',
name='country_code',
... |
from rdflib import Literal, URIRef
from rdflib.namespace import OWL, RDF, XSD
from client.model import (
Concept,
RDFDataset,
FeatureOfInterest,
Value,
Observation,
)
from client.model._TERN import TERN
# TODO: Confirm this testing is sufficient
def test_basic_rdf():
rdfdataset1 = RDFDataset(... |
import unittest
import uuid
from requests import PreparedRequest, Response, Session
from unittest.mock import patch, Mock
from identixone.http.client import IdentixOneHttpClient
class TestHttpClientRequest(unittest.TestCase):
def setUp(self):
self.session_patch = patch('identixone.http.client.Session')... |
def fcn_model(inputs, num_classes):
# Add Encoder Blocks.
# Remember that with each encoder layer, the depth of your model (the number of filters) increases.
print("Inputs shape:", inputs.shape, " \tImage Size in Pixels")
encoder01 = encoder_block(inputs, filters=32, strides=2)
print("encoder01 s... |
import os
import app
import json
def real_path(file_name):
return os.path.dirname(os.path.abspath(__file__)) + file_name
def main():
try:
config_file = real_path('/config/config.json')
config = json.loads(open(config_file).read())
tunnel_type = str(config['tunnel_type'])
... |
from enum import Enum
from concrete_class.hi_active_cooling import HighActiveCooling
from concrete_class.med_active_cooling import MedActiveCooling
from concrete_class.passive_cooling import PassiveCooling
class CoolingType(Enum):
PASSIVE = PassiveCooling()
HIGH_ACTIVE = HighActiveCooling()
MED_ACTIVE = ... |
import os
from compas.geometry.transformations import translation
os.system("cls")
import os
import numpy as np
import compas.geometry as cg
from compas.geometry import Point
from compas.geometry import Vector
from compas.geometry import Plane
from compas.geometry import Line
from compas.geometry import Polyline
fr... |
#!/usr/bin/env python3
# Yes, I am aware that I just switched from 2 spaces to 4 spaces. I installed linux on my desktop and this
# is the default formatting from vim, and also I remembered that it's the preferred tab-width for python.
# I am truly and deeply sorry if this has offended you. If you would like to seek fi... |
import os
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
import argparse
import schedule
import time
import datetime
import glob
# function to create directories
def create_dir(target_dir):
if not os.path.exists... |
# coding=utf-8
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import torch
import os
import pickle
import torchvision.models as models
import math
import numpy as np
import cv2
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.au... |
# container-service-extension
# Copyright (c) 2019 VMware, Inc. All Rights Reserved.
# SPDX-License-Identifier: BSD-2-Clause
from container_service_extension.exceptions import ClusterNotFoundError
from container_service_extension.exceptions import CseDuplicateClusterError
from container_service_extension.exceptions im... |
"""
A tool to extract hourly time series of salinity and volume in the segments.
Now also gets parts of a variance budget.
Performance: takes 1.5 sec per save (3.6 hours per year) on my mac. This relies
on creating i_dict and j_dict of indices used for fancy indexing in the segment loop.
The alternate version takes a... |
import os
import sqlite3
from flask import g, current_app
from collections import namedtuple
import logging
UserEntry = namedtuple('UserEntry', 'user_id,user_name,password')
def init_db():
db = get_db()
try:
with open(os.path.join(os.path.dirname(os.path.realpath(__file__)),
... |
import argparse
import os
from meshica import migp
from niio import loaded
import numpy as np
import scipy.io as sio
parser = argparse.ArgumentParser()
parser.add_argument('-files',
'--file-list',
help='List of resting-state files to aggregate.',
required... |
# Generated by Django 2.1.4 on 2019-09-05 23:07
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0002_card'),
]
operations = [
migrations.AlterField(
model_name='card',
name='binNum',
field=mode... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.