content
stringlengths
5
1.05M
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import json import stac import click @click.group() def cli(): """ :return: """ pass @cli.command(name="stac2json", help="Save a STAC Collection return in a JSON file") @click.option('--bdc-stac-search-bbox', required=True, help='BDC STAC Search bbox'...
import re import sys from datetime import date from PySide2.QtCore import Qt from qtpy import QtSql from PySide2.QtSql import QSqlDatabase, QSqlQueryModel, QSqlQuery from PySide2.QtWidgets import QTableView, QApplication import sys command_category = 'FirewallChecks' # self.commandcategorydropdown def replace(stri...
import os import tempfile import json import webbrowser from netCDF4 import Dataset import click from pyproj import Proj from rasterio.crs import CRS from rasterio.warp import calculate_default_transform from rasterio.enums import Resampling from jinja2 import Environment, PackageLoader from trefoil.netcdf...
import pytest from petisco import ValueObject, InvalidValueObject @pytest.mark.unit @pytest.mark.parametrize("expected_value", ["any", 1, 0.3, ["1", ["2"]], {"any": 1}]) def test_value_object_should_construct_and_serialize_with_inner_value(expected_value): value_object = ValueObject(value=expected_value) as...
from pwn import * # sh:tube = process("./sctf_2019_one_heap") context.update(arch="amd64", os="linux", endian="little") sh = remote("node3.buuoj.cn", 26663) cur_elf = ELF("./sctf_2019_one_heap") libc = cur_elf.libc def LOG_ADDR(*args): pass context.update(arch="amd64", os="linux", endian="little") def new_note(...
#!/usr/bin/env python #coding=utf-8 import numpy class Task(object): def __init__(self, cpu, mem): self.cpu = cpu self.mem = mem def __repr__(self): return ("%d,%d") % (self.cpu, self.mem) def get_task_list(): task_list = [] for i in range(0,30): cpu = numpy.random.r...
import lldb from lldbsuite.test.lldbtest import * from lldbsuite.test.decorators import * import lldbsuite.test.lldbutil as lldbutil import unittest2 class TestSwiftLetConstants(TestBase): mydir = TestBase.compute_mydir(__file__) @swiftTest def test_let_constants(self): """Test that let constants...
############################################################################## # # Copyright (c) 2001, 2002 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # TH...
from cqupt import PIPER_HOME from cqupt.log import Log from cqupt.fs import b64_fwrite, b64_fread from time import time from getpass import getpass from os import mkdir, path from shutil import rmtree PATH_PIPER_COOKIE = f'{PIPER_HOME}/cookie' PATH_PIPER_USER = f'{PIPER_HOME}/user' MAX_COOKIE_LIVE = 60 * 15 # 15mins...
# # MIT License # # Copyright (c) 2020 Keisuke Sehara # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, me...
# -*- coding: utf-8 -*- """ Defines unit tests for :mod:`colour.models.rgb.transfer_functions.cineon` module. """ from __future__ import division, unicode_literals import numpy as np import unittest from colour.models.rgb.transfer_functions import (log_encoding_Cineon, ...
"""Use this for combining rollouts together. For individual runs, see `scripts/plot_rollouts.py`. For the 'DAgger improvement over BC phase', I just used this: In [9]: e1 Out[9]: [88.45, 94.84] In [10]: e2 Out[10]: [89.43, 89.56] In [11]: e3 Out[11]: [84.26, 91.24] In [12]: e4 Out[12]: [76.69, 84....
import sys from pygments import styles from pygments.token import Error from friendly_styles import friendly_light, friendly_dark # When friendly is imported in environments that have previously # imported Pygments, the styles defined in friendly_styles do not # get automatically added to the list of available styles...
""" # -- --------------------------------------------------------------------------------------------------- -- # # -- project: -- # # -- script: visualizations.py : python script with data visualization functions ...
# This file is generated automatically through: # d2lbook build lib # Don't edit it directly # Defined in file: ./chapter_preface/index.md import collections from collections import defaultdict from IPython import display import math from matplotlib import pyplot as plt import os import pandas as pd import random i...
# # Based on Second Library (MIT license): # https://github.com/traveller59/second.pytorch # # Copyright (c) 2018 Yan Yan # 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 wi...
from os import listdir, path from datetime import date import re def load(): nameList = [] dowList = [] for name in listdir('datasets'): f = open(path.join('datasets', name), 'r') firstLine = f.readline() day, month, year = firstLine[0:2], firstLine[2:4], firstLine[4:8] day...
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) class PyLifelines(PythonPackage): """Survival analysis was originally developed and applied heavily by the actuar...
import pathlib import setuptools docs_requires = ["sphinx"] tests_requires = ['pytest>=3.0.0', 'pytest-asyncio', 'pytest-tornasync'] aiohttp_requires = ["aiohttp"] treq_requires = ["treq", "twisted[tls]"] tornado_requires = ["tornado"] long_description = pathlib.Path("README.rst").read_text("utf-8") setuptools.set...
import os import re import shutil from graph4nlp.pytorch.modules.evaluation.base import EvaluationMetricBase import pyrouge class SummarizationRouge(EvaluationMetricBase): def __init__(self): super(SummarizationRouge, self).__init__() self.rouge = pyrouge.Rouge155() def calculate_scores(sel...
##################################################################################### # # Copyright (c) Microsoft Corporation. All rights reserved. # # This source code is subject to terms and conditions of the Apache License, Version 2.0. A # copy of the license can be found in the License.html file at the root of th...
import re from django.db import models from django.template.defaultfilters import slugify from django.utils.translation import gettext_lazy as _ from django.core.exceptions import ValidationError from django.dispatch import receiver from django.db.models.signals import pre_save, post_save """ @receiver(pre_save) def p...
import argparse import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt from rlo import experiment_result from rlo import plotting from rlo import utils import numpy as np def average_of_counter(ctr): return sum([float(k) * v for k, v in ctr.items()]) / sum(ctr.values()) def plot_search_summar...
# 문제 번호: 14583 문제 이름: 이음줄 # 문제 최초 시도: 2019_05_18 # 문제 풀이 완료: 2019_05_18 # 이 코드의 접근법: 구현, 수학 import math as m H,V=map(float,input().split()) a= H*V/(H+m.sqrt(H**2+V**2)) row=m.sqrt(H**2+a**2)/2 S=H*(V-a) column=S/2/row print("%.2f %.2f" %(row,column))
# -*- coding: utf-8 -*- ''' Created on Sun Mar 14 00:09:39 2021 @author: Ayrton M and jmatailov11 This function returns the indices where the '1' values are found. ''' import numpy as np def location(loc_matrix): location = np.where(loc_matrix == 1) # return indices of the values that are '1' locat...
from images_to_video import * from rat_maskrcnn import * # load the test dataset train_set = RatDataset() train_set.load_dataset('rat') train_set.prepare() print('Test: %d' % len(train_set.image_ids)) test_set = RatDataset() test_set.load_dataset('rattest') test_set.prepare() print('Test: %d' % len(test_set.image_id...
# -*- coding: utf-8 -*- """ Colour Models Plotting ====================== Defines the colour models plotting objects: - :func:`colour.plotting.\ plot_RGB_colourspaces_in_chromaticity_diagram_CIE1931` - :func:`colour.plotting.\ plot_RGB_colourspaces_in_chromaticity_diagram_CIE1960UCS` - :func:`colour.plotting.\ ...
""" Config Class """ import json class Config: """ Config class containing data, train and model hyperparameters """ def __init__(self, data, train): self.data = data self.train = train @classmethod def from_json(cls, cfg): """ Creates config from json ...
import PikaStdLib import pikaRTThread import SmartLoong thread = pikaRTThread.Thread() mem = PikaStdLib.MemChecker() print('mem use max(byte): ') print(int(mem.getMax() * 1000)) led1 = SmartLoong.LED() led1.setId(1) led1.enable() led1.on() key1 = SmartLoong.KEY() key1.setId(1) key1.enable() i = 0 while i < 3: i ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Utilities for real-time processing """ from collections import OrderedDict from threading import Thread, Event import numpy as np from scipy import signal BAND_FREQS = OrderedDict() BAND_FREQS['delta'] = (1, 4) BAND_FREQS['theta'] = (4, 8) BAND_FREQS['alpha'] = (7....
from mapswipe_workers import auth from mapswipe_workers.definitions import logger, sentry def get_project_ids_from_postgres(): """Get project ids.""" p_con = auth.postgresDB() query = """ SELECT project_id FROM projects; """ data = p_con.retr_query(query) project_ids = [item[0] for i...
import torch.nn as nn from .attention import MultiHeadedAttention from .utils import SublayerConnection, PositionwiseFeedForward, clones, LayerNorm class TransformerEncoderBlock(nn.Module): def __init__(self, hidden, attn_heads, feed_forward_hidden, dropout): super().__init__() self.attentio...
from neater.strategies.strategy import Strategy from numpy.core.defchararray import equal import torch from tqdm import trange import numpy as np import pickle import matplotlib.pyplot as plt class Agent(): def __init__(self, env, strategy, input_shape: int, output_shape: int, discrete=True): self.input...
# -*- coding: utf-8 -*- # Generated by Django 1.11.20 on 2019-06-11 12:53 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('great_international', '0033_auto_20190611_1057'), ('great_international', '0037_correct_pag...
# -*- coding: utf-8 -*- import os import re import gzip import struct import hashlib import xlsxwriter import np import time import shutil import mimetypes import pb from . import STDR from . import utils from . import DTO ''' WARNING!!! This class was comment out in the utils.py. After the clean-up it was placed in s...
number = int(input()) salaperhour = int(input()) valorperhour = float(input()) print("NUMBER = {}".format(number)) print('SALARY = U$ {:.2f}'.format(salaperhour * valorperhour))
from .vgg import * def get_model_conv_block(name, **kwargs): """Returns base_model's convolution part by name :param name: str Name of the base_model :return: HybridBlock The base_model convolution part """ models = { 'vgg16': VGGConvBlock } name = name.lower() ...
import logging import os import errno class CreateHierarchyFileHandler(logging.FileHandler): """ Custom file handler that creates the path of the log file if it's not exists """ def __init__(self, filename, mode='a', encoding=None, delay=0): self._create_path_hierarchy(os.path.dirname(filename)) ...
""" Script for performing validation for the Attentive Neural Process. """ import argparse import numpy as np import torch from sklearn.model_selection import train_test_split from sklearn.metrics import r2_score, mean_squared_error, mean_absolute_error from data_utils import transform_data, TaskDataLoader, featuris...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jan 8 15:36:15 2020 preproc using a color adjustment for the dataset also save gain_rgb for this image @author: minjie """ from pathlib import Path import os import cv2 from tqdm import tqdm from color_enh import sod_minkowski import pandas as pd ...
def max_point(strA, left, right): if right < left: return -1 mid = (left + right) // 2 if strA[mid] > strA[mid -1] and strA[mid] > strA[mid + 1]: return strA[mid] elif strA[mid] > strA[mid -1] and strA[mid] < strA[mid + 1]: return max_point(strA, mid, right) elif strA[mid] < strA[mid -1] and strA[mid] >...
from setuptools import setup with open("README.md", "r") as fh: long_description = fh.read() setup( name="ubtbr", version="1.0", packages=['ubtbr'], description="Ubtbr firmware control library", long_description=long_description, long_description_content_type="text/markdown", install_requires=['libusb1'], ...
"""Fake 'charset_normalizer' for Python 2 to raise ImportError. Needed for 'requests' module which first checks for existence of 'charset_normalizer' (Python 3) but does not raise 'ImportError' but 'SyntaxError'. """ raise ImportError("charset_normalizer not available")
import scapy.all as scapy import threading from time import sleep import os import logging logging.basicConfig(format='%(levelname)s - %(asctime)s - %(message)s', datefmt='%d-%b-%y %H:%M:%S', level=logging.INFO) class ArpPoison(threading.Thread): """ Arp spoofing MiTM ...
import os import random def getSubsetName(file, n): return file.split(".txt")[0] + str(n) + ".txt" def saveRandomSubset(file, n): print("Generating new subset of size " + str(n) + " of file " + file) f = open(file, "r") words = f.read().splitlines() random.shuffle(words) filename = getSubse...
from django.views.generic import ListView from samhlida.models import Entry from samhlida.filters import EntityFilterSet class FilteredListView(ListView): filterset_class = None def get_queryset(self): # Get the queryset however you usually would. For example: queryset = super().get_queryset(...
# -*- coding: utf-8 -*- """ Created on Fri Feb 5 22:53:34 2021 @author: lsong4 """ import os import csv # path = 'dataset/1_enhanced/' # fileList = os.listdir(path) # n=0 # for i in fileList: # oldname=path+ os.sep + fileList[n] # newname=path + os.sep + 'real' + str(n+1)+'.jpg...
# Main entrance of GAIL import numpy as np import torch import torch.nn.functional as F import gym import safety_gym import time import os.path as osp from torch.distributions.categorical import Categorical from neural_nets import Discriminator, ActorCritic, ValorDiscriminator, count_vars from utils import BufferS, ...
import re import sys import yaml import json import logging import unittest import datetime from Database import Database class Test(unittest.TestCase): def setUp(self): with open('conf/config_test.yaml', "r") as yamlfile: data = yaml.load(yamlfile, Loader=yaml.FullLoader) username = data[0]['database']['user...
# SecretPlots # Copyright (c) 2019. SecretBiology # # Author: Rohit Suratekar # Organisation: SecretBiology # Website: https://github.com/secretBiology/SecretPlots # Licence: MIT License # Creation: 05/10/19, 7:55 PM # # # # # Author: Rohit Suratekar # Organisation: SecretBiology # Website: https://github.co...
import torch import numpy as np import json from torch.autograd import Variable ''' Dataloader are based on dataloder from https://github.com/thunlp/VERNet ''' INCORRECT_ID =0 CORRECT_ID = 1 SUB_ID = 2 PAD_ID = 3 def convert_label(string): lab_list = string.strip().split() new_labs = list() for lab in la...
# # Copyright 2021 Ocean Protocol Foundation # SPDX-License-Identifier: Apache-2.0 # """ Test did_lib """ from ocean_lib.common.agreements.service_types import ServiceTypes from ocean_lib.common.ddo.ddo import DDO from ocean_lib.common.did import DID from tests.resources.ddo_helpers import get_resource_path, get_sa...
# -*- coding: utf-8 -*- def is2DData(Data):% # Purpose : Tests if the input argument represents valid 2D homogeneous # coordinates. # # Uses (syntax) : # is2DData( Data ) # # Input Parameters : # Data := the variable to be tested (should be 3xn, n greater than 0) # # Return P...
# Library imports. from flask import Flask from json import dumps from re import escape # Reactive imports. import database # Because we need an app. app = Flask(__name__) # All routes are defined here. # User Routes @app.route("/add_user/<username>") def add_user(username): # escape username username = es...
""" 539. Minimum Time Difference Given a list of 24-hour clock time points in "Hour:Minutes" format, find the minimum minutes difference between any two time points in the list. Example 1: Input: ["23:59","00:00"] Output: 1 Note: The number of time points in the given list is at least 2 and won't exceed 20000. The inpu...
import traceback from db_adapter.logger import logger from db_adapter.exceptions import DatabaseAdapterError """ Variable JSON Object would looks like this e.g.: { 'variable' : 'mm', } """ def get_variable_by_id(pool, id_): """ Retrieve variable by id :param pool: database connection...
from textwrap import dedent from click.testing import CliRunner import pytest from dennis.cmdline import cli from tests import build_po_string, nix_header @pytest.fixture def runner(): """Creates a CliRunner""" return CliRunner() def build_key_val(text): pairs = {} for line in text.splitlines(): ...
class Host: def __init__(self, ip): self.ip = ip
# -*- coding: utf-8 -*- from django.conf import settings from django.template import RequestContext from django.template.loader import render_to_string from djangorestframework.response import Response, ErrorResponse from djangorestframework import status from ionyweb.website.rendering import HTMLRendering from iony...
import sphinx_rtd_theme extensions = [ "jupyter_sphinx", ] templates_path = ["_templates"] def setup(app): app.add_css_file("main_stylesheet.css") master_doc = "index" source_suffix = ".rst" # General information about the project. project = "HERE Map Widget for Jupyter" copyright = "Copyright (C) 2019-2...
import dotenv import os from pathlib import Path current_dir = Path(__file__).parent.absolute() env_file = os.getenv("SCWEET_ENV_FILE", current_dir.parent.joinpath(".env")) dotenv.load_dotenv(env_file, verbose=True)
from flask import Flask, request, render_template app = Flask(__name__) @app.route('/') def home(): thing = request.values.get('thing') height = request.values.get('height') color = request.values.get('color') return render_template('home.html',thing=thing, height=height, color=color) app.run(host='192.168.56.10...
# Copyright 2021 The casbin Authors. 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...
# Carlos Morato, PhD. # cwmorato@wpi.edu # Deep Learning for Advanced Robot Perception # # Example of Theano library import theano from theano import tensor # declare two symbolic floating-point scalars a = tensor.dscalar() b = tensor.dscalar() # create a simple symbolic expression c = a + b # convert the expression in...
"""Make some columns not nullable Revision ID: dc5428c022bd Revises: 53ed37276d53 Create Date: 2019-01-19 22:54:19.528454 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'dc5428c022bd' down_revision = '53ed37276d53' branch_labels = None depends_on = None def ...
import geopandas as gpd import pandas as pd from geoalchemy2 import WKTElement from shapely.geometry.multipolygon import MultiPolygon from shapely.geometry.polygon import Polygon def clean_taxi_zones(**kwargs): '''Make geometry column consistent for writing to postgres''' ti = kwargs['ti'] taxi_zones = ti...
"""A MQTT interface adapter.""" import json import logging import paho.mqtt.client as mqtt import paho.mqtt.publish as publish from ..settings import identify from ..domain.ports import QueueSender from ..domain.messages import RegisterBookCommand LOGGER = logging.getLogger('sample') @identify('mqtt', 'interface...
# coding=utf-8 # Copyright 2020 RigL 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 agree...
import random import time import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from tqdm.auto import tqdm from gensim.models import Word2Vec from torch.optim import Adam from torchtext.vocab import Vectors from torchtext.data import TabularDataset, Field, LabelField, BucketIterator from...
import numpy as np import matplotlib.pyplot as plt import torch import torch.nn as nn import torch.nn.functional as F import torchvision import torchvision.transforms as transforms from torch.autograd import Variable num_rotations = 16 batch_size = 6 device = torch.device("cpu") transform = transforms.Compose( [...
import os environment = os.environ #ASSETS = environment['ASSETSFOLDER'] if 'ASSETSFOLDER' in environment else "asset" JSON_FILES = "eurekaClientShare/asset/file/json"#.format(ASSETS)
from scipy.sparse import lil_matrix from scipy.optimize import differential_evolution import numpy as np import copy import psycopg2 from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT __author__ = 'willmcginnis' class BaseGraph(object): """ Base object for a graph, contains most interfaces with a gr...
#!/usr/bin/env python import sys import subprocess class Safer(object): def __init__(self, name): self.name = name def __call__(self): sp = subprocess.Popen( [self.name] + sys.argv[1:], stdout=subprocess.PIPE, stderr=subprocess.PIPE) (stdout, stderr) = sp.commu...
from typing import ( Tuple, ) from eth2.beacon.types.blocks import BaseBeaconBlock from trinity.protocol.common.normalizers import BaseNormalizer from trinity.protocol.bcc.commands import ( BeaconBlocksMessage, ) class BeaconBlocksNormalizer(BaseNormalizer[BeaconBlocksMessage, Tuple[BaseBeaconBlock, ...]])...
from threading import Thread from time import sleep class Filter: def __init__(self): self._alive = True @property def alive(self): return self.receiving_thread.is_alive() and self.sending_thread.is_alive() and self._alive def kill(self): self._alive = False ...
#! /usr/bin/python import sys, csv, numpy import networkx as nx BW_FILENAME="aggregate_mean_netspeeds.csv" PLOSS_FILENAME="aggregate_mean_netquality.csv" MAP_FILENAME="full_tor_map.xml" GEO_FILENAME="geoip" OUTPUT_FILENAME="topology.full.graphml.xml" def main(): bwdown, bwup = get_bandwidth() # KiB/s loss = ...
''' Created on Oct 9, 2013 @author: yonch ''' import random import networkx as nx from networkx.generators import bipartite class graph_util(object): ''' Generates different bipartite graphs ''' def generate_random_regular_bipartite(self, n, d): ''' Generates a regular bipartite graph of...
import time import RPi.GPIO as GPIO class Buzzer: def __init__(self): GPIO.setwarnings(False) self.Buzzer_Pin = 17 GPIO.setmode(GPIO.BCM) GPIO.setup(self.Buzzer_Pin,GPIO.OUT) def run(self,command): if command!="0": GPIO.output(self.Buzzer_Pin,True) els...
# Copyright 2019 IBM Corp. # # 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, sof...
#!/usr/bin/env python ############################################################################### # Copyright 2017 The Apollo Authors. 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 ...
import sys global _PyQtAvailable,_PyQt5Available,_PyQt4Available,_GLUTAvailable,_GLBackend _PyQtAvailable = False _PyQt5Available = False _PyQt4Available = False _GLUTAvailable = False _GLBackend = None if not _PyQtAvailable and not _GLUTAvailable: try: from PyQt5.QtCore import * from PyQt5.QtGui i...
# Vamos chamar o script em shell a partir desse script python import subprocess p = subprocess.Popen(args=['/bin/bash', 'script_shell.sh']) # O wait aguardará o processo filho rodar totalmente e armazenará o return code return_code = p.wait() if return_code == 0: print('Script shell rodado com sucesso') else: ...
# -*- coding: utf-8 -*- # -------------------------------------------------------------------- # The MIT License (MIT) # # Copyright (c) 2016 Jonathan Labéjof <jonathan.labejof@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation fi...
from evennia import Command as BaseCommand class Command(BaseCommand): """ Inherit from this if you want to create your own command styles from scratch. Note that Evennia's default commands inherits from MuxCommand instead. Note that the class's `__doc__` string (this text) is used by Evennia...
import datetime from decimal import Decimal import django_filters import pytz from django.db import transaction from django.db.models import F, Prefetch, Q from django.db.models.functions import Coalesce, Concat from django.http import FileResponse, HttpResponse from django.shortcuts import get_object_or_404 from djan...
import sys import traceback from io import TextIOWrapper from pathlib import Path from typing import BinaryIO, Iterable, Iterator, Set, Tuple, Union from .ast_node import GherkinDocument from .errors import ( BaseError, EmptySources, EquivalentError, InternalError, NothingChanged, StableError, ...
""" configservice module: This module is responsible for "poking" the proper host OS services to change the host OS config. This would include things like changing the networking, DHCP server settings, wifi, etc.. """ import json from paradrop.confd import client from paradrop.base.output ...
#!/usr/bin/env python import math import sys, argparse import time import numpy as np import owl from owl.net.trainer import FeatureExtractor if __name__ == "__main__": # parse command line arguments parser = argparse.ArgumentParser() parser.add_argument('solver_file', help='caffe solver configure file') ...
import sys import requests from st2common.runners.base_action import Action class Dbgetes(Action): def run(self): url="http://dummy.restapiexample.com/api/v1/employees" response = requests.get('http://dummy.restapiexample.com/api/v1/employees') if response.status_code == 200: ...
from setuptools import setup setup( name = 'depfetch' , version = '0.0.2' , packages = [ 'depfetch' , 'depfetch.lang' , 'depfetch.pm' ] , scripts = [ 'bin/depfetch' ] )
from alias.src.surface_parameters import SurfaceParameters from .fixtures import amber_trajectory, amber_topology class ProbeSurfaceParameters(SurfaceParameters): def __init__(self, molecule='TRP'): super().__init__(molecule) self.load_traj_parameters( amber_trajectory, amber_topolo...
from astrometry.util.pyfits_utils import * from pyfits import * # Returns "gain", "dark_variance", and "skyErr" def sdss_psfield_noise(psfieldfn, band=None): p = table_fields(pyfits.open(psfieldfn)[6].data) p = p[0] if band is not None: return (p.gain[band], p.dark_variance[band], p.sky[band], p.skyerr[band]) re...
from fractions import Fraction class Ratio: def __init__(self,n,d): self.n = n self.d = d # mul and rmul should take integer o def __mul__(self,o): return (self.n*o) // self.d def __rmul__(self,o): return (o*self.n) // self.d def mkFraction(a): ...
import argparse import logging import asyncio import sys import binascii import os from . import config from . import glob class Error(Exception): pass def _setup_logging(args): if args.debug: level = logging.DEBUG elif args.verbose: level = logging.INFO else: level = loggin...
#!/usr/bin/python # # Copyright 2013 Zynga 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 applicabl...
#!/usr/bin/env python3 # 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 # "...
import requests import json import time url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=38db01c7-1d8b-47db-aee0-ae9a6f43772b' url2 = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=819eb666-8bc3-4f66-a6a7-173ce9a61a93' # 半佛,朱一旦,大骚,罗翔说刑法,毕导THU,何同学,科技美学, 局座, 手工耿, 敬汉卿 bili_ids = ['37663924','437316738',...
import pandas as pd import pygmt import numpy as np def read_EQT(eqt_dir): with open(eqt_dir, 'r') as eqt_file: lines = eqt_file.readlines() my_dates = [] longitude = [] latitude = [] magnitude = [] name = [] for i in lines: my_dates.append(i[0:14].strip()) try: ...
import sys from sample_factory.algorithms.appo.enjoy_appo import enjoy from sample_factory_examples.train_custom_vizdoom_env import register_custom_doom_env, custom_parse_args def main(): """Script entry point.""" cfg = custom_parse_args(evaluation=True) register_custom_doom_env(custom_timeout=cfg.my_cus...
"""Miscellaneous small classes""" from operator import xor from functools import reduce import numpy as np from .units import Quantity, qty # pylint: disable=unused-import Strings = (str,) Numbers = (int, float, np.number, Quantity) class FixedScalarMeta(type): "Metaclass to implement instance checking for fixe...