content
stringlengths
5
1.05M
# pylint: disable=missing-docstring import hashlib import os import tempfile import crcmod from resolwe.storage.connectors.hasher import StreamHasher from resolwe.test import TestCase tmp_dir = tempfile.TemporaryDirectory() def path(filename): return os.path.join(tmp_dir.name, filename) def hashes(filename):...
# Generated by Django 3.2.5 on 2021-08-09 06:50 import api.models import api.models.app import api.models.certificate import api.models.key from django.conf import settings import django.contrib.postgres.fields from django.db import migrations, models import django.db.models.deletion import uuid class Migration(migr...
from django.db import models class Museo(models.Model): nombre = models.CharField(max_length=64) accesibilidad = models.BooleanField(default=False) via_clase = models.CharField(max_length=64) via_nombre = models.CharField(max_length=256) via_numero = models.CharField(max_length=16) postal = mo...
users = { 3346: { "first_name": "XA", "last_name": "Wick", "account_no": 6721495583, "balance": 5000000, "currency": "$" }, 9213: { "first_name": "Shailesh", "last_name": "Rubano", "account_no": 3471073995, "balance": 7000000, "...
#删除仓库文件 git pull origin master git rm "文件名" git commit -m "删除的原因" git pull origin master git push origin master #删除仓库 1.进入setting 2.滑到最后 delete repositories 3.输入要删除的仓库名称
import sys read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines sys.setrecursionlimit(10 ** 7) n = int(readline()) h = [tuple(map(int, readline().split())) for _ in range(n)] check = set(h) ans = 0 memo = 0 for x_1, y_1 in h: memo += 1 for x_2, y_2 in h[memo:...
# -*- coding: utf-8 -*- """ Created on 2021/12/20 17:12:59 @File -> _mi_dd.py @Author: luolei @Email: dreisteine262@163.com @Describe: 计算离散变量之间的互信息 """ import numpy as np from . import preprocess_values from ..entropy.entropy import Entropy class MutualInfoDD(object): """连续X和离散Y之间的互信息计算""" def __init__...
""" Generate maze layouts for 'pelita', without dead ends. Algorithm: * start with an empty grid * draw a wall with gaps, dividing the grid in 2 * repeat recursively for each sub-grid * find dead ends * remove a wall at the dead ends Players 1,3 always start in the bottom left; 2,4 in the top right Food is placed ran...
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-05-24 01:16 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='CarRecor...
# Generated by Django 4.0.3 on 2022-03-15 15:08 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('produto', '0005_alter_produto_slug'), ] operations = [ migrations.AlterField( model_name='produto', name='preco', ...
#!/usr/local/bin/python3.7 # -*- coding: utf-8 -*- import re,time,datetime,os,os.path,sys,shutil,pickle,math,random,itertools,functools,sqlite3 import subprocess,signal,threading,multiprocessing import socket,requests,urllib,django from queue import Queue, SimpleQueue, LifoQueue, PriorityQueue #实际上,Python没有独立的堆类型,而只有一个...
if __name__ == '__main__': n = int(raw_input()) arr = map(int, raw_input().split(' ')) new_list = set(arr) new_list.remove(max(new_list)) print(max(new_list))
from django.db import models # Create your models here. class scoringModel(models.Model): client = models.CharField(max_length=1000, null=True, blank=True) api_key = models.CharField(max_length=1000, null=True, blank=True) def __str__(self): return str(self.client) class submissionMod...
#!/usr/bin/env python # coding=utf-8 from flask import Flask, jsonify #from async_proxy_pool.database import RedisClient from async_proxy_pool.data_sqlite3 import SQLite3Client app = Flask(__name__) sqlite3_conn = SQLite3Client() @app.route("/") def index(): return jsonify({"Welcome": "This is a pr...
#!/usr/bin/env python # -*- coding: utf-8 -*- # This file is part of adp-api-client. # https://github.com/adplabs/adp-connection-python # Copyright © 2015-2016 ADP, LLC. # Licensed under the Apache License, Version 2.0 (the “License”); # you may not use this file except in compliance with the License. # You may obta...
L = 0.008 # thickness of glass A = 1.5*0.8 # area of the window k = 0.78 # conductivity of glass R = L/(k*A) #calculating the resistance print R print(R) # strings !!!! name = "marco" name2 = 'marco' # these two methods are the same! # concatenation name1= "marco " name2 = "sara" names = name1+name2 result = "...
# Write your solution here def who_won(game_board: list): score1 = 0 score2 = 0 for row in game_board: for square in row: if square == 1: score1 += 1 if square == 2: score2 += 1 if score1 > score2: return 1 elif score1 <score2: ...
# Copyright 2016 Quan Pan # # 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, s...
import matplotlib.pyplot as plt import pandas as pd from pipeline.modeling.data_utils import TransformDF from pipeline.modeling.datasets import TimeSeriesDataset from pipeline.common.function_utils import timeit from pipeline.common.optimize_pandas import optimize from pipeline.modeling.data_to_df import LoadDF import...
from panini.test_client import TestClient from tests.helper import Global # no need to run panini client = TestClient() global_object = Global() @client.listen("test_client_listen.foo") def foo_listener(msg): global_object.public_variable = msg.data["data"] + 1 client.start(do_always_listen=False) def test_...
# coding: utf-8 """ Campatibility layer to make python2 & 3 support easier Python 3 changes the default str type to unicode This causes issues when we need specifically a bytearray e.g. at encryption time At the same time we try to keep string remaining in the environment default mode to reduce friction and surprise ...
from rubygems_utils import RubyGemsTestUtils class RubyGemsTestrubygems_faraday_em_synchrony(RubyGemsTestUtils): def test_gem_list_rubygems_faraday_em_synchrony(self): self.gem_is_installed("faraday-em_synchrony")
#First Recurring Character in O(n) def rec(st): d={} for c in st: if c in d: return c d[c]='1' return None st=str(input()) print(rec(st))
from mock import Mock, patch import pytest from amqp.exceptions import NotFound from nameko.amqp import UndeliverableMessage from nameko.events import event_handler from nameko.standalone.events import event_dispatcher from nameko.testing.services import entrypoint_waiter handler_called = Mock() class Service(obj...
class model: ## core ############################################## def __getattribute__(self,x): v = object.__getattribute__(self,x) return v(self) if callable(v) and x not in ['copy','update'] else v ## aux ############################################## def update(self,other): for k,v in other.__dict__.item...
# This script changes Berkeley Logic Interchange Format (BLIF) to truth table # format which is easier for usage in Genetic Programming. # # Script was coded by Petr Dvoracek 2020 import re # This constant protects overfilling RAM. Truth table requires `2**len(input)` # bytes. Thus truth table memory requirements g...
# -*- coding: utf-8 -*- from ..models import EmbeddedReports from ..utilities import init_flask import pandas as pd from flask_sqlalchemy import SQLAlchemy app = init_flask() db = SQLAlchemy(app) def _iter_rows(filename): df = pd.read_csv(filename, encoding='utf8') headers = ['id', 'report_name_english', 'r...
"""Logging and reporting tools for a wmt-exe environment.""" import os import sys import threading import time import logging import subprocess import yaml import requests logger = logging.getLogger(__name__) """Logger : Instance of Logging class.""" class TaskCompleted(Exception): """Exception thrown when a ...
data_root = 'C:/Users/parisa/Desktop/csYRPCai/project/train/' import numpy as np import pandas as pd import time from sklearn import svm, datasets from sklearn.cross_validation import train_test_split from sklearn.preprocessing import label_binarize from sklearn.multiclass import OneVsRestClassifier from sklearn.mu...
from dbnd import dbnd_config from dbnd_test_scenarios.pipelines.simple_read_write_pipeline import ( write, write_dir, write_read, write_read_dir, ) from .test_s3 import _S3BaseTestCase class TestS3Sync(_S3BaseTestCase): def test_sync_execution_file_target(self): self.client.remove(self.bu...
import markdown import uuid import logging from django.db import models from django.conf import settings from django.utils.translation import ugettext_lazy as _ from .utils import AESCipher from .manager import EntryManager logger = logging.getLogger('default') IS_PUBLIC_CHOICES = ((True, 'Everyone'), (False, 'Just...
##### # creates raster files with unique values for each unique attribute # in an input shape file # # c. 2016 Christopher Anderson ##### import aei import gdal as gdal import ogr as ogr import osr as osr # set up errr handling ogr.UseExceptions() gdal.UseExceptions() class parse_args: def __init__(self, arglis...
import os import sys def square(n): return n*n if __name__ == "__main__": limit = 10 for i in range(-limit, limit+1): print('*' * square(i), i)
from grapl_common.grapl_logger import get_module_grapl_logger from mypy_boto3_dynamodb.service_resource import DynamoDBServiceResource, Table LOGGER = get_module_grapl_logger(log_to_stdout=True) def is_grapl_provisioned( dynamodb: DynamoDBServiceResource, schema_table: str, ) -> bool: """ We are doin...
# -*- coding: utf-8 -*- from __future__ import division, absolute_import # Copyright (C) 2007 Samuel Abels # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the Li...
#!/usr/bin/env python import unittest, rosunit from rostest_example.Quacker import * class QuackerTester(unittest.TestCase): def test_quacker_default_quack(self): quacker = Quacker() self.assertEqual(quacker.quack, "Quack!") def test_get_quack_string(self): quacker = Quacker("Quack!") ...
def reverse(string): string = "".join(reversed(string)) #used reversed function for reversing the String return string str = input("Enter A String:") print ("The Entered String is : ",end="") #end is used here so that output will be in same line. print (str) print ("The Reversed String is : ",end...
from rest_framework import serializers from .models import * class WarriorSerializer(serializers.ModelSerializer): class Meta: model = Warrior fields = "__all__" class SkillSerializer(serializers.ModelSerializer): class Meta: model = Skill fields = "__all__" class Professi...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ A Python implementation of the method described in [#a]_ and [#b]_ for calculating Fourier coefficients for characterizing closed contours. References ---------- .. [#a] F. P. Kuhl and C. R. Giardina, “Elliptic Fourier Features of a Closed Contour," Computer Visio...
import os import json import requests import datetime import jsonpickle import shutil import urllib import elasticsearch.helpers from elasticsearch import Elasticsearch from .interfaces import SearchEngineInterface from .utilities import configPath #from ltr.helpers.handle_resp import resp_msg def resp_msg(msg, resp...
# coding=utf-8 # Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os import re ...
from ..utils import merkle_part from tbears.libs.scoretest.score_test_case import ScoreTestCase class TestBlockHeaderMerkleParts(ScoreTestCase): def setUp(self): super().setUp() def test_get_block_header(self): data = b'' data += bytes.fromhex( "32fa694879095840619f5e4938...
#!/usr/bin/env python import argparse import sys class Atom: def __init__(self, name): self.name = name self.element = "" self.serial = 0 self.direct_neighbors = [] self.all_neighbors = [] # [[step 1 neighbors], [step 2 neighbors], ...] self.fingerprint = [] # [a...
#import pytest #import app.my_script # Dummytest which will always succeed - must be replaced by real tests def test_dummy(): assert True
from .yaml_helper import * from .ngrok_helper import * from .spark_helper import * from .html_helper import *
#! /usr/bin/env python __author__ = 's' import urllib2 import urllib import time import socket # Set some global variables proxy_list = open('proxy_list.txt', 'r') ip_check_url = 'http://automation.whatismyip.com/n09230945.asp' #ip_check_url = 'http://pr4ss.tk' user_agent = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:1...
from dataclasses import dataclass from typing import Dict, List, Optional, Tuple import numpy as np import torch import torch.nn.functional as F from torch import Tensor, nn from torch.nn import CrossEntropyLoss from transformers import PretrainedBartModel, BartModel, BartConfig from transformers.modeling_outputs imp...
from abc import ABCMeta, abstractclassmethod class Platform: __metaclass__ = ABCMeta def __init__(self): self.platform = None @abstractclassmethod def check_url(self, url): pass
# Universidade Federal de Viçosa - Campus Rio Paranaíba # Sistemas de Informação - Processamento Digital de Imagens # # Professor: Joao Mari # Autores: # - MatheusRV (3929) # - iguit0 (3902) # - ThiagoMunich (3628) # # Filtragem espacial para suavização - Filtro de máximo e mínimo # Como Exec...
import torch.nn as nn class AbstractModel(nn.Module): def __init__(self, config, data_feature): nn.Module.__init__(self) def predict(self, batch): """ Args: batch (Batch): a batch of input Returns: torch.tensor: predict result of this batch ""...
""" Not sure why, but the entry point for PyInstaller has to be a python script, and it has to lie within the main project folder. I'm probably misunderstanding how PyInstaller works, but at least this works for now. """ from broadside import run run()
#!/usr/bin/env python # Copyright 2018 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Wraps ml.exe or ml64.exe and postprocesses the output to be deterministic. Sets timestamp in .obj file to 0, hence incompatible with...
import math import numpy as np def grad(pos): u, v = pos u_grad = math.exp(u) + v*math.exp(u*v) + 2*u - 2*v -3 v_grad = 2*math.exp(2*v) + u*math.exp(u*v) - 2*u + 4*v - 2 return np.array([u_grad, v_grad]) def E(pos): u, v = pos e = math.exp(u) + math.exp(2*v) + math.exp(u*v) + u**2 - 2*u*v + 2...
''' Integration Test for Prometheus Sync in HA mode. @author: Mirabel ''' import zstackwoodpecker.test_util as test_util import zstackwoodpecker.test_lib as test_lib import test_stub import time import os vm1 = None vm2 = None node1_ip = None node2_ip = None def test(): global vm1 globa...
"""campsignup URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.0/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-ba...
class Solution: def isValid(self, s: str) -> bool: stack = [] pair = { ')': '(', ']': '[', '}': '{' } for char in s: # 栈为空时右括号先入必然不配对 if len(stack) == 0: if pair.get(char) is not None: return False ...
"""Retry plugin for Doozer. Retry is a plugin to add the ability for Doozer to automatically retry messages that fail to process. """ from __future__ import annotations import asyncio from numbers import Number import time from doozer.base import Application from doozer.exceptions import Abort from doozer.extensions...
import json import pyast from collections import OrderedDict import sys if sys.version >= '3': basestring = str else: pass def _dump_node(node, name=None, indent=0): if node is None: return None if isinstance(node, (int, bool, basestring)): return node struct = OrderedDict({'typ...
""" 学習の一時中断、再開を行う処理を提供する """ import os import tensorflow as tf from . context import Context from . colab import IS_ON_COLABOLATORY_WITH_GOOGLE_DRIVE, Colaboratory def ENABLE_SUSPEND_RESUME_TRAINING(): """ 一時中断、再開を行う学習を実施する 冒頭でリジュームを宣言してください。 Example: ENABLE_SUSPEND_RESUME_TRAINING() ...
import structlog from django.core.exceptions import ImproperlyConfigured from django.core.management.base import BaseCommand from semantic_version.base import Version from posthog.async_migrations.runner import start_async_migration from posthog.async_migrations.setup import ALL_ASYNC_MIGRATIONS, POSTHOG_VERSION, setu...
import copy import pathlib import tempfile from typing import Sequence import numpy as np from scipy import signal import torch from torch.optim.lr_scheduler import _LRScheduler from pytorch_lightning import Trainer from callbacks import PandasLogger from collections import namedtuple import yaml class LRFinder()...
from json import dumps from requests import ConnectionError import requests_mock from unittest.mock import MagicMock from mindbot.command.nasa.apod import APODCommand from mindbot.router import CommandRouter from .fixtures import fake_apod_message instance = APODCommand(CommandRouter, '', {}) APOD_TEXT = ( '[...
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. from torch.optim.optimizer import required from optimizer import OptimizerWithWeightStashing class AdamWithWeightStashing(OptimizerWithWeightStashing): """ Adam optimizer with weight stashing. """ def __init__(self, m...
"""Module for the cli usage.""" import os default_mitsuba_variant: str = os.getenv("MITSUBA_VARIANT", "packet_rgb") default_gpu_mitsuba_variant: str = "gpu_rgb"
from collections import defaultdict from dmqs.integration.utils import fetch_primary_key class Repository(object): __shared_state = {} def __init__(self): self.__dict__ = self.__shared_state self.__dict__['data'] = defaultdict(list) self.__dict__['ids'] = defaultdict(int) def get_m...
# Accuracy of NER with open("Directory/result.txt", "r") as f: sents = [line.strip() for line in f.readlines() if line.strip()] total = len(sents) print(total) count = 0 for sent in sents: words = sent.split() if words[-1] == words[-2]: count += 1 print("Accuracy: %.4f" %(count/total))
from control_layer.config.send_config import SFC def get_sfp_id(): sfc_instance = SFC("ubuntu.local", "8181") sfp_id_list = [] for path in sfc_instance.get_rendered_sfp()["rendered-service-paths"]["rendered-service-path"]: sfp_id_list.append(int(path["path-id"])) sfp_id_list.sort() return ...
import sys sys.path = ['./superfast/build'] + sys.path import superfast import dlib import timeit import random files = sys.argv[1:] start = timeit.default_timer() for i in range(1000): img = dlib.load_rgb_image(random.choice(files)) stop = timeit.default_timer() print("time to load images: ", stop-start) s...
""" Too Many Assertion """ from mock import Mock from code_resources import TestClassBase, Worker class TestSomeClass(TestClassBase): def setup_test(self): self.mocked_task = Mock() self.tester = Worker(self.mocked_task) def test_consume__pasten__pasten(self): ### self.teste...
from typing import Optional, TypeVar, Union from hamcrest.core.base_matcher import BaseMatcher from hamcrest.core.description import Description from hamcrest.core.helpers.wrap_matcher import wrap_matcher from hamcrest.core.matcher import Matcher __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" _...
""" Print an H-shaped pattern """ pattern = "" for Row in range(0, 7): for Col in range(0, 7): if (Col == 1 or Col == 5) or (Row == 3 and 1 < Col < 6): pattern += "*" else: pattern += " " pattern += "\n" print(pattern)
import geneticalgorithm ##How To setup your our GA for Cartesian # Basically your need to overwrite the eval function, the function that calculates the value for the individual class MyGACart(GeneticAlgorithm): class Individual(GeneticAlgorithm.Individual): def __cartesian_eval(self, point): re...
""" SoftLayer.tests.CLI.deprecated_tests ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :license: MIT, see LICENSE for more details. """ import mock from SoftLayer.CLI import deprecated from SoftLayer import testing from SoftLayer import utils class EnvironmentTests(testing.TestCase): def test_main(self): ...
# 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 ...
import os import tempfile from cparser import CParser from cparser.parser import preprocess_file, get_default_pp_args code = """ #include <stdio.h> #ifndef CUSTOM_PI #define CUSTOM_PI 3.14159265358979323846 #endif int main() { float a = CUSTOM_PI; return 0; } """ def main(): cparser = CParser() f ...
#! /usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright 2018 Kyoto University (Hirofumi Inaguma) # Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) """(Hierarchical) RNN encoder.""" from distutils.util import strtobool import logging import math import numpy as np import torch import torch.nn as nn fro...
#*****************************************************************************# #* Copyright (c) 2004-2008, SRI International. *# #* All rights reserved. *# #* ...
import re; from mRegistry import cRegistryHiveKey; # Cache which binaries have page heap enabled/disabled. this assumes that the user does not modify the page heap # settings while BugId is running. gdbPageHeapEnabled_by_sBinaryName = {}; guRequiredFlags = 0x02109870; def cProcess_fEnsurePageHeapIsEnabled(oProcess): ...
from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtWidgets import * import os, sys, codecs class Ui_multiInputsDialog(object): def setupUi(self, multiInputsDialog): multiInputsDialog.setObjectName("multiInputsDialog") multiInputsDialog.resize(321, 590) multiInputsDialog.setFocusPolicy(...
numbers = [1, 2, 3] number1, number2, number3 = numbers print(number1) print(number2) print(number3) print('\n') numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] number1, number2, *other_numbers = numbers print(number1) print(number2) print(other_numbers) print('\n') numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] first_number,...
from typing import List from discord import TextChannel, Message from resources.core.configure_permissions import ban from resources import client class BanMessageTemplate: def __init__(self, author, guild, channel: TextChannel): self.author = author self.guild = guild self.channel = cha...
""" Augmented B-Tree: Insertion --------------------------- This folder contains an implementation of an augmented B-tree. For this implementation, the tree only stores data in its leaf nodes. Each node also has level-set pointers defined here which access the left and right siblings of each node (or None if they do no...
# pre-req setup start import os import pandas as pd from ast import literal_eval from cdqa.utils.converters import pdf_converter from cdqa.utils.filters import filter_paragraphs from cdqa.pipeline import QAPipeline from cdqa.utils.download import download_model # Download model # download_model(model='bert-squad_1.1'...
# -*- coding: utf-8 -*- # Generated by Django 1.10 on 2018-07-06 14:33 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('blogposts', '0007_auto_20180706_1954'), ] operations = [ migrations.RenameFie...
from covidapp import app from flask import render_template,jsonify import pandas as pd from scripts.wrangle import data_wrangling,return_fig,return_data,map_fig import plotly.graph_objs as go import plotly, json @app.route('/') @app.route('/index') def index(): figs,t_case,states,cases,districtfor = return_fig(...
# type: ignore from __future__ import annotations import time from typing import TYPE_CHECKING, Any, Dict, Optional, TypeAlias from discord import Client, Guild, VoiceChannel, VoiceProtocol from discord.ext import commands from . import events from .enums import SearchType from .exceptions import FilterInvalidArgume...
"""Functions for pulling FERC Form 1 data out of the PUDL DB.""" import pandas as pd import pudl def plants_utils_ferc1(pudl_engine): """ Build a dataframe of useful FERC Plant & Utility information. Args: pudl_engine (sqlalchemy.engine.Engine): Engine for connecting to the PUDL dat...
__author__ = "Radical.Utils Development Team (Andre Merzky, Ole Weidner)" __copyright__ = "Copyright 2013, RADICAL@Rutgers" __license__ = "MIT" import radical.utils.testing as rut # ------------------------------------------------------------------------------ # class TestConfig (rut.TestConfig): #-----...
# -*- coding: utf-8 -*- # # Copyright (C) 2020 CERN. # # CDS-ILS is free software; you can redistribute it and/or modify it under # the terms of the MIT License; see LICENSE file for more details. """CDS-ILS CDS Importer ignored fields.""" CDS_IGNORE_FIELDS = { "003", "005", "020__q", "020__c", "0...
# Copyright (c) 2014, The MITRE Corporation. All rights reserved. # See LICENSE.txt for complete terms. import cybox import cybox.bindings.cybox_common as common_binding from cybox.common import PatternFieldGroup from cybox.utils import normalize_to_xml, denormalize_from_xml INVALID_XSI_TYPE = "bad_xsi_type" class ...
""" Copyright (c) 2019-2020, the Decred developers See LICENSE for details """ class DecredError(Exception): pass
#!/usr/bin/env python import functools import os.path import re import sys import traceback import docopt def checked_call( function): @functools.wraps(function) def wrapper( *args, **kwargs): result = 0 try: result = function(*args, **kwargs) ...
# Python Dictionaries # Unordered, Indexed, Mutable/Changeable collection, written with curly braces and have key:value pairs. # A pair of braces, with no elements in it, creates an empty dictionary. # They have No Duplicate Members. # They are indexed by their keys and the keys can be any immutable type (strings a...
# encoding: utf-8 """ attribute.py Created by Thomas Mangin on 2009-11-05. Copyright (c) 2009-2017 Exa Networks. All rights reserved. License: 3-clause BSD. (See the COPYRIGHT file) """ from struct import pack from exabgp.bgp.message.notification import Notify from exabgp.util.cache import Cache # ===============...
# coding: UTF-8 import time import torch import numpy as np from torchbert.train_eval import train, init_network from importlib import import_module import argparse from torchbert.utils import build_dataset, build_iterator, get_time_dif, DatasetIterater parser = argparse.ArgumentParser(description='Chinese Text Classi...
''' Integration tests for remote. TODO: Replace mock-ssh-server with some other alternatives. ''' import os import tempfile from boss.core import remote, fs def test_put(server): ''' Test put() transfers file to the remote end. ''' for uid in server.users: target_dir = tempfile.mkdtemp() sour...
# Copyright (c) Stanford University # # This source code is patent protected and being made available under the # terms explained in the ../LICENSE-Academic and ../LICENSE-GOV files. # Author: Mario J Srouji # Email: msrouji@stanford.edu import copy import os from shutil import copyfile import sys sys.path.append(".....
import os from host_py_rm_studio_internal import rm_dynamic_import _PKG_PATH = os.path.dirname(os.path.realpath(__file__)) class RM_EFR32XG14_Info(object): short_name = 'efr32xg14' val_die_name = 'EFR32XG14XFULL' arm_core_revs = [] rtl_revs = ['A0', 'A1'] di_revs = [] pte_revs = [] pkg_p...
#!/usr/bin/env python3 from cheroot.wsgi import Server, PathInfoDispatcher from flask import Flask, send_file, Response, request, abort import numpy as np import cv2 import io import platform from turbojpeg import TurboJPEG import threading import time import sys from picamera.array import PiRGBArray from picamera impo...
import numpy as np, scipy as sc from numpy.fft import fft, ifft from scipy import optimize import logging import afftc, naive, utils from utils import NEG_INF, EPS from timer import timer OPT_BOUND = 1e10 THETA_LIMIT = 1e4 def conv_power(log_pmf, L, desired_beta, desired_delta): """Compute $log(exp(log_pmf)**L)$ ...