content stringlengths 5 1.05M |
|---|
import torch
from torch.nn import functional as F
from torch.optim import SGD
from torchvision.models import mobilenet_v3_small
from holocron.optim import wrapper
def _test_wrapper(name: str) -> None:
lr = 1e-4
input_shape = (3, 224, 224)
num_batches = 4
# Get model, optimizer and criterion
mode... |
# Copyright 2021 DAI Foundation
#
# 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,... |
"""graph.py
A set of data strucutres and algorithms for graphs, trees, etc
Test cases:
- 107
"""
# Python Standard Library Imports
import copy
import json
class GraphEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, Tree):
return obj.as_json()
elif isinstance(obj... |
_lookup_overhead = {
'c': 0.55,
'c++': 0.63,
'cpp': 0.63,
'matlab': 10.85,
'python': 1.43}
def calculate_speedup(src_lang, dst_lang, nloops,
tinitA, t1A, t2A, t3A, tfinalA,
tinitB, t1B, t2B, t3B, tfinalB,
t_comm=None, T_overhead=Non... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
from enum import Enum
__all__ = [
'Action',
'Architecture',
'BaseImageTriggerType',
'DefaultAction',
'OS',
'PolicyStatus',
... |
"""website URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.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-based... |
#!/usr/bin/python3
import logging
import math
from simtools.model.model_parameters import MODEL_PARS
from simtools.util import names
__all__ = [
"computeTelescopeTransmission",
"getTelescopeClass",
"getCameraName",
"isTwoMirrorTelescope",
"splitSimtelParameter",
]
def splitSimtelParameter(valu... |
import threading as th
from ipywidgets_runner.utils import dprint
class Worker:
def __init__(self, supervisor):
self.supervisor = supervisor
self.consumer_thread = th.Thread(target=self.consume)
self.consumer_thread.start()
self.stale = False
def interrupt... |
fname=input('enter name of file: ')
content= input('enter content: ')
o = open("input",'w')
o.write(content)
o.close()
ip=open("input",'r')
# print(ip.read(5))
lst=ip.readlines()
# print(lst)
# print("".join(lst))
# nl=[]
# for index,data in enumerate(lst):
# nl.append(data.replace("\n"," "))
# print(nl) |
def evenodd(n):
if n%2==0:
print("even")
else:
print("odd")
def add(a,b):
c = a+b
print(c)
def hello(name):
print("Hello"+" "+name) |
import unittest
import sys
import extract_const_diff
import extract_const_same
import extract_dyn_same
import extract_dyn_diff
import test_phenomenon
import test_propertyset
if __name__ == '__main__':
suite = unittest.TestSuite()
#suite.addTest(unittest.makeSuite(extract_const_diff.TestConstDiff))
#suit... |
import discord
from discord.ext import commands
class Log(commands.cog.Cog):
def __init__(self, bot:commands.Bot):
self.bot = bot
self.logchannel = None
# ensure config file has required data
if not bot.config.has_section('log'):
bot.config.add_section('log')
if 'logchannel' not in bot.conf... |
"""
This is the proxy helps connect to another TCP server, and sends and retrieves
data from it.
"""
import asyncio
import contextlib
import logging
import threading
LOGGER = logging.getLogger(__name__)
class ATcpProxy:
"""
Proxy class.
"""
def __init__(self,
host: str = '127.0.0.1'... |
import matplotlib.pyplot as plt
import numpy as np
from keras.datasets import mnist
from keras.layers import BatchNormalization, Input, Dense, Reshape, Flatten
from keras.layers.advanced_activations import LeakyReLU
from keras.models import Sequential, Model
from keras.optimizers import Adam
def build_generator(laten... |
# encoding: utf-8
# module PySide.QtGui
# from C:\Python27\lib\site-packages\PySide\QtGui.pyd
# by generator 1.147
# no doc
# imports
import PySide.QtCore as __PySide_QtCore
import Shiboken as __Shiboken
class QGraphicsAnchor(__PySide_QtCore.QObject):
# no doc
def setSizePolicy(self, *args, **kwargs): # real... |
"""Support for Purrsong LavvieBot S"""
import asyncio
import logging
import voluptuous as vol
from lavviebot import LavvieBotApi
import homeassistant.helpers.config_validation as cv
from homeassistant import config_entries
from homeassistant.const import EVENT_HOMEASSISTANT_STOP
from homeassistant.exceptions import Co... |
from django.db import models
class Category(models.Model):
class Meta:
verbose_name_plural = "categories"
name = models.CharField(max_length=255)
def __str__(self):
return self.name
class Post(models.Model):
title = models.CharField(max_length=500)
body = models.TextFie... |
import re
import urllib2
import requests
from PIL import Image
from io import BytesIO
def print_list(list):
for i,j in enumerate(list):
print i,j
def get_base_url():
url = raw_input('Enter the base URL :')
data = urllib2.urlopen(url).read()
print url, data
return url, data
def get_hype... |
# Copyright 2016 by Raytheon BBN Technologies Corp. All Rights Reserved.
'''
Utilities for creating a basic channel configuration for testing.
'''
from QGL.ChannelLibraries import EdgeFactory, MeasFactory, QubitFactory
from QGL import ChannelLibraries
from QGL.Channels import Edge, Measurement
from QGL.PulseSequencer... |
"""Definition for methods for files resource."""
|
#!/usr/bin/python
import sys
import pathlib
import os.path
from os import path
ws_dir = 'prod'
if len(sys.argv) > 1:
ws_dir = sys.argv[1]
else:
print('Missing basepath')
sys.exit(1)
# webapp folders
webapp_log_dir = ws_dir + '/webapp/log/valentina'
webapp_output_dir = ws_dir + '/webapp/output'
webapp_set... |
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "intro.settings")
# trying this hack because of error with postgres and import psycopg2
os.environ['DYLD_LIBRARY_PATH'] = '/Library/PostgreSQL/9.3/lib'
from django.core.management ... |
import numpy as np
import operator
import matplotlib as mpl
import pyqtgraph as pg
from .tabulate import tabulate
from .Utils import *
from .Visualizer import VisualModel
from scipy.sparse import csr_matrix, vstack, hstack, lil_matrix, eye, csc_matrix, coo_matrix
from scipy.sparse.linalg import minres, spsolve, inv#,... |
#! /usr/local/bin/python
# Corinne Maufrais
# Institut Pasteur, Centre d'informatique pour les biologistes
# maufrais@pasteur.fr
#
# version 1.0
import os, sys, getopt
try:
LIB = os.environ['RANKOPTIMIZERLIB']
except:
LIB = '/usr/local/bin'
if LIB not in sys.path:
sys.path.append( LIB )
class Rank... |
i = 0
while i <= 9:
print(i)
i = i + 1 # i += 1
if i % 2 == 0:
break
print('---------')
i = 0
while i <= 9:
print(i)
i = i + 1 # i += 1
if i % 2 == 0:
continue
print('---------')
i = 0
while i <= 9:
i = i + 1 # i += 1
if i % 2 == 0:
continue
print(i)
|
import operator
lines = [l.strip().replace(' ', '') for l in open('input18').readlines()]
def parse(inp):
ops = {
'+': operator.add,
'*': operator.mul,
}
stack = []
aggr = None
for idx, item in enumerate(inp):
if item.isdigit():
if type(aggr) is tuple:
... |
import json
import os
from xml.etree import ElementTree as ET
import jinja2
import xmltodict
from bs4 import BeautifulSoup
from weasyprint import HTML
def is_xml(xml):
try:
ET.fromstring(xml)
return True
except Exception as e:
print(e)
return False
def is_html(html):
ret... |
from sling.core import config
from sling.core.g import g
import sys
import logging
class TransactionIdLogFilter(logging.Filter):
def filter(self, record):
record.transaction_id = g.transaction_id
return True
class TransactionIdLogMiddleware(object):
def process_request(self, req, res):
... |
import os
import paramiko
class SftpHandle(paramiko.SFTPHandle):
def stat(self):
try:
return paramiko.SFTPAttributes.from_stat(os.fstat(self.readfile.fileno()))
except OSError as e:
return paramiko.SFTPServer.convert_errno(e.errno)
def chattr(self, attr):
pass
|
from django.contrib.auth.models import User
from faker import Faker
from random import randint, choice
from contacts.models import Person
from django.conf import settings
import string
class DataGenerator:
fake = Faker()
@classmethod
def generate_user(cls):
user = {
'username': cls.fa... |
# Copyright (c) 2021 The Toltec Contributors
# SPDX-License-Identifier: MIT
"""Parse versions and dependency specifications."""
import re
from enum import Enum
from typing import Optional
# Characters permitted in the upstream version part of a version number
_VERSION_CHARS = re.compile("^[A-Za-z0-9.+~-]+$")
# Chara... |
import pytz
from django.db.models import Q
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.conf import settings
from django.core.exceptions import ValidationError
from django.db import transaction
from datetime import datetime, timedelta, date
from django.http.res... |
from pygame import mixer
class Audio:
def __init__(self, file, volume):
self.volume = volume
mixer.Sound(file)
mixer.Sound.set_volume(self.volume)
def play(self):
mixer.Sound.play()
def stop(self):
mixer.Sound.stop()
|
# -*- coding: utf-8 -*-
#
# Copyright (C) 2005-2009 Edgewall Software
# Copyright (C) 2005-2006 Christian Boos <cboos@edgewall.org>
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http... |
test = {
'name': 'lets-count',
'points': 1,
'suites': [
{
'cases': [
{
'code': r"""
sqlite> SELECT * from favpets;
dog|20
cat|9
turtle|4
penguin|4
dragon|4
wolf|3
tiger|3
panda|3
fox|3
... |
import binascii
import time
import os
import spotipy
from . import config
REDIRECT_URI = 'http://localhost:9090'
SCOPES = [
'playlist-read-private',
'user-read-recently-played',
]
OAUTH_TOKENS_PATH = config.STATIFY_PATH / 'oauth_tokens.json'
class Spotify:
def __init__(
self, client_id, clien... |
import threading
import socket
import time
import shutil
import getpass
import sys
import os
global count
count = 0
def main():
global count
count = count + 1
global target
global port_
global threads
global Continue
global connected
if count <= 1:
Continue = False
... |
import sys
sys.path.append("..")
from models import GCN_classification
import torch
import pickle
import numpy as np
model = GCN_classification(6, 2, [6, 256, 256], 3, [256, 256, 256, 2], 2)
model.load_state_dict(torch.load('data/E116/model_2021-06-26-at-05-46-03.pt', map_location=torch.device('cpu')))
model.eval()
... |
from django.test import RequestFactory
from nose.tools import * # flake8: noqa
from tests.base import AdminTestCase
from tests.factories import NodeFactory
from admin_tests.utilities import setup_view
from admin.nodes.views import NodeFormView
from admin.base.forms import GuidForm
class TestNodeFormView(AdminTestC... |
import math
import numpy as np
import pytest
from skspatial.objects import Circle
@pytest.mark.parametrize(
"point, radius",
[
# The point must be 2D.
([0], 1),
([0, 0, 0], 1),
([1, 2, 3], 1),
([0, 0, 0, 0], 1),
# The radius must be positive.
([0, 0], ... |
# -*- coding: utf-8 -*-
import subprocess
import excelConverse
import styling
from tkinter.filedialog import askopenfilename, asksaveasfilename
def Main():
target = askopenfilename(title="Choose spreadsheet file.")
style = askopenfilename(filetypes=(("Cascading style sheet file", "*.css"), ("All Files", "*.*... |
"""Utility functions for time-frequency analysis."""
import numpy as np
'''
TODO: Reconsider time frequency analysis terminology. I think it
might be good, for example, to use the term "record" (or maybe something
else, e.g. "vector", though "record" is my favorite at the moment) to
refer to a vector of samples tha... |
"""
please visit https://github.com/niutool/xuebao
for more detail
"""
import abc
import tempfile
import wave
import mad
from client import audioengine
class GenericPlugin(object):
def __init__(self, info, config):
self._plugin_config = config
self._plugin_info = info
@property
def pr... |
import signal
import sys
import time
from gevent import signal as gevent_signal
import lib.ai as ai
from lib.game.engine import Engine, Snake
from lib.log import get_logger
from lib.models.game import Game, GameState
from lib.models.team import Team
BATTLESNAKE_URL = 'http://www.battlesnake.io/app/games'
logger = ... |
productos =[
{"nombre":"Coca-cola 600","precio":15,"Cantidad":10},
{"nombre":"Pepsi 600","precio":15,"Cantidad":20},
{"nombre":"Cerveza ultra","precio":20,"Cantidad":5},
] |
from de0.de0mem_py import *
import led.hps_0 as hps_0
# TODO: HPS peripherals, e.g., led, button, GSensor, DMA transfers?
# TODO: GPIOs
class LEDs(object):
def __init__(self, pa_de0):
if 'LED_PIO' not in dir(hps_0):
raise RuntimeError('Cannot find "LED_PIO" in hps_0')
self.pa = pa_de0 ... |
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd.
# MIT License. See license.txt
from __future__ import unicode_literals
"""
Generate RSS feed for blog
"""
rss = u"""<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0">
<channel>
<title>%(title)s</title>
<description>%(description)s</descr... |
"""
For .py in main, use 'import xhd_source as xhds'.
If use 'from xhd_source import *', the whole folder will be imported.
Only .py files are supported in this folder.
"""
import os
# Set __all__ to be all .py files in the folder
__all__ = [
'basic_nn',
'dataset',
'helper_func',
'plot',
'recorder... |
import torch
import numpy as np
from torch import nn
from typing import Any, Dict, Tuple, Union, Optional, Sequence
from tianshou.utils.net.common import MLP
SIGMA_MIN = -20
SIGMA_MAX = 2
class Actor(nn.Module):
"""Simple actor network. Will create an actor operated in continuous \
action space with struct... |
print(*divmod(eval('+int(input())'*4),60)) |
from operator import attrgetter
import pyangbind.lib.xpathhelper as xpathhelper
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType
from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType
from pyangbind.lib.base import PybindBase
from d... |
#!/usr/bin/env python
# encoding: utf-8
"""
compute_transformation_error.py
Created by Maria Isabel Restrepo on 2012-09-24.
Copyright (c) 2012 . All rights reserved.
This script computes the distances betweeen an estimated similarity transformation and its ground truth
The transformation is used to transform a "source... |
#!/usr/bin/env python
from redis import Redis
import os
import sys
redis = Redis.from_url(
"redis://" + os.environ.get("EXECUTOR_CONSTR", "127.0.0.1:6379/0")
)
# parse last seen
tmpfile = sys.argv[1]
try:
with open(tmpfile) as fh:
jobids_last_run = [_.strip() for _ in fh.readlines()]
except:
jobid... |
""" Baseline RNN cells such as the vanilla RNN and GRU. """
import torch
import torch.nn as nn
import torch.nn.functional as F
from model.components import Gate, Linear_, Modrelu, get_activation, get_initializer
from model.orthogonalcell import OrthogonalLinear
class CellBase(nn.Module):
""" Abstract class for ... |
from __future__ import absolute_import
from warnings import warn
import numpy as np
import numpy.random as npr
from numpy.testing import *
from scipy.stats import norm
import passglm.inference as inf
npr.seed(9)
def _estimated_autocorrelation(x):
"""
http://stackoverflow.com/q/14297012/190597
http://en.... |
from helper_funcs_any import *
import numpy as np
import numpy.random as rng
from pytest import approx
import pylab as pl
import sys, pickle
import matplotlib.cm as cm
np.set_printoptions(precision=2)
#rng.seed(0)
import argparse
VERBOSE = False
parser = argparse.ArgumentParser()
parser.add_argument('-n','--nsl', met... |
"""
bdosoa - SOAP requests processing
"""
import cherrypy
import libspg
import sys
from datetime import datetime
from email.mime.text import MIMEText
from libspg.bdo import (BDRError, BDRtoBDO, BDOtoBDR, QueryBdoSVs,
SVCreateDownload, SVDeleteDownload, SVQueryReply)
from traceback import forma... |
from tkinter import *
from GtBurst.fontDefinitions import *
from GtBurst import commandDefiner
from GtBurst.EntryPoint import EntryPoint
import os
import traceback
from tkinter.messagebox import showerror, showinfo
from GtBurst.GtBurstException import GtBurstException
import GtBurst.dataHandling
class Comman... |
# Copyright 2016 Hewlett Packard Enterprise Development Company, L.P.
#
# 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 b... |
import numpy as np
import scipy.ndimage as nd
from scipy.ndimage import median_filter
def highpass_gaussian(image, sigma=2.0):
return image - nd.gaussian_filter(image, sigma=sigma)
def lowpass_gaussian(image, sigma=2.0):
return nd.gaussian_filter(image, sigma=sigma)
def homomorphic_median(image, sigma=10)... |
BILLION_TO_MILLION_RATE = 1000.0
MILLION = 1_000_000.0
def billion_to_million(v):
if isinstance(v, str):
v = float(v[:-1])
return BILLION_TO_MILLION_RATE * v
def btm(v):
return billion_to_million(v)
def to_million(v):
return v / MILLION
def from_any_to_million(v: str)... |
import time
from awrams.models.model import Model
from .clustered import build_sim_pickle, launch_sim_from_pickle
import shutil
import os
from awrams.utils import config_manager
from awrams.cluster.support import build_mpi_call_str, build_pbs_header, \
build_full_pbs_file, get_pbs_hea... |
import torch
import torchvision
from torch.utils.data.dataloader import default_collate
from torchvision import datasets
def collate_fn_bn(x):
batch = default_collate(x)
mean, std = batch.mean(1, keepdim=True), batch.std(1, keepdim=True) + 1e-5
bn_batch = (batch - mean) / std
return bn_batch
def col... |
################################# Import Libraries ################################
import os.path
from bottle import route, run, response, static_file, request, error, Bottle, template
from json import dumps, loads, load
import uuid
import urllib2
import zipfile
import thread
#################################### WebS... |
# -*- coding: utf-8 -*-
import argparse
import json
import os
# change to proper import when svg package will be modified
from sdgen.builder import Builder as SVGBuilder
from sdgen.png.png_builder import PNGBuilder
from sdgen import config as config_mod
DATA_FILE_INCORRECT = -1
CONFIG_FILE_INCORRECT = -2
CONFIG_FILE_... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# CAVEAT UTILITOR
# This file was automatically generated by Grako.
# https://bitbucket.org/apalala/grako/
# Any changes you make to it will be overwritten the
# next time the file is generated.
#
from __future__ import print_function, division, absolute_import, unico... |
import pytest
import aspen
def test_virtual_path_with_typecast(harness):
harness.fs.www.mk(('%year.int/foo.html', "Greetings, program!"),)
path = harness.hit('/1999/foo.html', want='path')
assert path == {'year': [1999]}
def test_virtual_path_raises_on_bad_typecast(harness):
harness.fs.www.mk(('%yea... |
import unittest
import solution
class TestQ(unittest.TestCase):
def test_case_0(self):
self.assertEqual(solution.time_delta('Sun 10 May 2015 13:54:36 -0700', 'Sun 10 May 2015 13:54:36 -0000'),
'25200')
self.assertEqual(solution.time_delta('Sat 02 May 2015 19:54:36 +0530',... |
# -*- coding: utf-8 -*-#
'''
# Name: NormalEquation
# Description:
# Author: super
# Date: 2020/5/13
'''
import numpy as np
from HelperClass.DataReader_1_1 import *
file_name = "../data/ch05.npz"
if __name__ == '__main__':
reader = DataReader_1_1(file_name)
reader.ReadData()
X,Y ... |
# Minimum discount that makes a book a special deal
MINIMUM_THRESHOLD = 20
PRINT_DISCOUNT = "item_in_discount"
PRINT_NORMAL = "item_not_in_discount"
PRINT_HIDE = "item_dont_display"
PRINT_CHOICE = "item_from_search"
PRINT_INIT = "welcome_text"
PRINT_FINISHED = "finished_text"
PRINT_NEXT_ELEMENT = "next_element_text"
LI... |
import os
from django.core.exceptions import ImproperlyConfigured
from pydrive2.auth import GoogleAuth
CREDENTIALS_FILE_PATH = "credentials.json"
CLIENT_SECRETS_FILE_PATH = "client_secrets.json"
def load_credentials_from_env():
CLIENT_SECRETS_FILE_CONTENT = os.environ.get('CLIENT_SECRETS_FILE_CONTENT', '')
... |
"""
Visits the following link:
"https://disclosures-clerk.house.gov/PublicDisclosure/FinancialDisclosure"
to download zip files containing text files of transaction data from congress
members. This data contains document IDs and filing dates which are parsed in
order to find the links to the PDFs that contain the actua... |
'''
Created on Jul 17, 2013
@author: Yubin Bai
'''
import time
from multiprocessing.pool import Pool
parallelSolve = False
INF = 1 << 31
def solve(par):
C, S, array = par
if S < 2 * C:
array += [0] * (2 * C - S)
array.sort()
result = []
low = 0
high = 2 * C - 1
while low < high:
... |
import logging
import requests
import json
import os
from urllib import urlretrieve
from maskgen.maskgen_loader import MaskGenLoader
def download(file_name, apitoken, directory, url, prefix='images'):
import requests
sign_url = url + ('' if url.endswith('/') else '/') + 'sign/'
headers = {"Content-Type": ... |
#
# Copyright 2017 the original author or 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 applicable law or... |
# -*- coding: utf-8 -*-
import random
import urllib
from scrapy.http.headers import Headers
from crawler.misc.spider import CommonSpider
from crawler.misc import agents
class BaseHelper(object):
PROFILE_URL = "https://mobile.qzone.qq.com/profile?hostuin=USER_QQ_NUMBER"
SHUOSHU_URL = "https://mobile.qzone.q... |
'''
Generates dumper for the SVGA 3D command stream using pygccxml.
Jose Fonseca <jfonseca@vmware.com>
'''
copyright = '''
/**********************************************************
* Copyright 2009 VMware, Inc. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person
* obtaining a c... |
from __future__ import print_function
#comment
from __future__ import absolute_import
class A:
pass
<warning descr="from __future__ imports must occur at the beginning of the file"><caret>from __future__ import with_statement</warning>
|
from pig_util import outputSchema;
@outputSchema("perc: double")
def percentage(num, total):
return num*100/total;
|
# Importem els fitxers necessaris
import Excercici1Package.ex1
import Excercici2Package.ex2
import Excercici3Package.ex3
import Excercici4Package.ex4
# Resolem l'excercici 1
print("+++++++++++ Excercici 1 ++++++++++++++")
Excercici1Package.ex1.find_count_pattern("data/covid_approval_polls.csv", ".pdf")
Excercici1Pac... |
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import JsonResponse, HttpResponse
from django.shortcuts import render, redirect
from django.urls import reverse
# Create your views here.
from django.views.generic.base import View
from accounts.models import Profile
from minloansng.mixins imp... |
import argparse
import json
from easydict import EasyDict
def get_args():
argparser = argparse.ArgumentParser(description=__doc__)
argparser.add_argument(
'-c', '--config',
metavar='C',
default=None,
help='The Configuration file')
argparser.add_argument(
'-i', '--id... |
#!/usr/bin/python
import os
import traceback
import subprocess
import json
from pprint import PrettyPrinter
def runTraceroute(ip):
outDir = "scamperTraces/"
if not os.path.exists(directory):
os.makedirs(directory)
outfileName=outDir+ip+"-paris-traceroute.warts"
#TODO: Check if host country is... |
from dal.sqlite.roi_repository_sqlite import ROIRepositorySqlite
from test.mock_ups.dal.roi_repository import ROIRepositoryMockUp
class ROIRepositorySqliteMockUp(ROIRepositorySqlite, ROIRepositoryMockUp):
pass |
import csv
from collections import defaultdict, namedtuple
import os
from urllib.request import urlretrieve
from pathlib import Path
"""
From PyBites Bite 30: https://codechalleng.es/bites/30/
"""
BASE_URL = 'https://bites-data.s3.us-east-2.amazonaws.com/'
TMP = '/tmp'
base_dir = Path(__file__).resolve().parent
fnam... |
# Copyright 2020 The TensorFlow Probability 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 applicable law o... |
'''
Useful code from Lecture 14 - Masi
'''
import image
# %% BUILD MATRIX
def create_matrix_short(rows, cols, value = 0):
'''
Create matrix with for loops and
'''
matrix = []
for row in range(rows):
matrix.append([value] * cols)
return matrix
def create_matrix_short(rows, cols, valu... |
"""
File utilities
License:
Copyright © 2018 The Climate Corporation
"""
import hashlib
import os
def length(f):
"""Get the length of a file"""
f.seek(0, os.SEEK_END)
length = f.tell()
return length
def md5(f):
"""Get the md5 of a file's contents"""
f.seek(0)
md5 = hashlib.md5()
ch... |
# enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标
map =[[".", ".", ".", "#", ".", "#", ".", ".", ".", "."],
[".", ".", "#", ".", ".", "#", ".", "#", ".", "#"],
["s", ".", "#", ".", "#", ".", "#", ".", ".", "."],
[".", "#", "#", ".", ".", ".", ".", ".", "#", "."],
[".", ".", ".", ".... |
# -*- conding:utf-8 -*-
import sys
from argparse import ArgumentParser, Namespace
from localfs import func
#
def to_opt(args: Namespace, flag: str) -> str:
opt = '-'
# charactor loop
for f in flag:
opt += f if hasattr(args, f) and getattr(args, f) is True else ''
return opt
# ls
def ls(args... |
'''
Author: Matt Bougie (mbougie@wisc.edu)
Date: June 21, 2020
Purpose: Central script to call all other scripts for processing data.
Usage: Need to set up connections to directories of scripts and to geodatabases where the output is saved.
Parameters: Parameters for all scripts are stored in the json file and referen... |
default_app_config = 'cotidia.cms.apps.CMSConfig'
|
num_1 = '100'
num_2 = '200'
num_1 = int(num_1)
num_2 = int(num_2)
print(num_1 + num_2)
|
from stge.cell_tracker import cell_tracker
import unittest
class TestCellTracker(unittest.TestCase):
def test_register_df(self):
ct = cell_tracker()
ct.register_df('../data/light_cell_df.csv')
self.assertEqual(len(ct.all_frame), 4)
def test_load(self):
ct = cell_tracker(point_... |
import doctest
from formencode.htmlgen import html
# A test value that can't be encoded as ascii:
uni_value = u'\xff'
str_value = uni_value if str is unicode else uni_value.encode('utf-8')
def test_basic():
output = '<a href="test">hey there</a>'
assert str(html.a(href='test')('hey there')) == output
a... |
######################################################################################################################
# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. #
# ... |
#
# PySNMP MIB module DGS1100-24-MGMT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DGS1100-24-MGMT-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:45:25 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default... |
from .symbolicate import symbolicate_crash
from .symbolicate import version
from .symbolicate import query_uuid
__author__ = 'jinzhao'
|
# nlantau, 2021-12-25
"""
Given an integer array nums, return the third distinct maximum number in this array.
If the third maximum does not exist, return the maximum number.
Success!
Runtime: 28ms, faster than 98.91% of Python submissions
"""
class Solution(object):
def thirdMax(self, nums):
from functoo... |
# -*- coding: utf-8 -*-
"""rackio/workers/state.py
This module implements State Machine Worker.
"""
import heapq
import logging
import time
from collections import deque
from threading import Thread
from .worker import BaseWorker
from ..utils import log_detailed
class MachineScheduler():
def __init__(self):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.