content
stringlengths
5
1.05M
import re #regular expression library import def __checkPassword(password): checker = 0 while True: if (len(password)<8): checker = -1 break elif not re.search("[a-z]", password): checker = -1 break elif not re.search("[A-Z...
# Copyright 2015 Leon Sixt # # 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...
"""InstanceFile and InstanceFileManager.""" import os import re import itertools from pathlib import Path from schema_enforcer.utils import find_files, load_file SCHEMA_TAG = "jsonschema" class InstanceFileManager: # pylint: disable=too-few-public-methods """InstanceFileManager.""" def __init__(self, confi...
#!/usr/bin/env python # # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: MIT-0 # # 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 restric...
#!/usr/bin/env python3 with open("hello.txt", "w") as f: f.write("Hello world.\n")
import pygame def collide(s1: pygame.Surface, x1: float, y1: float, s2: pygame.Surface, x2: float, y2: float) -> bool: l1, t1 = int(x1), int(y1) l2, t2 = int(x2), int(y2) w, h = s1.get_size() r1, b1 = l1 + w, t1 + h w, h = s2.get_size() r2, b2 = l2 + w, t2 + h if (((l2 < l1 < r2) or (l2 <...
# -*- coding: utf-8 -*- # Generated by Django 1.11.9 on 2018-03-03 16:41 from __future__ import unicode_literals from django.db import migrations, models def set_position(apps, schema_editor): Question = apps.get_model('pretixbase', 'Question') for q in Question.objects.all(): for i, option in enumer...
# # -*- coding: utf-8 -*- # Copyright 2019 Red Hat # GNU General Public License v3.0+ # (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) """ The junos l3_interfaces fact class It is in this file the configuration is collected from the device for a given resource, parsed, and the facts tree is populated based o...
# /////////////////////////////////////////////////////////////// # # BY: WANDERSON M.PIMENTA # PROJECT MADE WITH: Qt Designer and PySide6 # V: 1.0.0 # # This project can be used freely for all uses, as long as they maintain the # respective credits only in the Python scripts, any information in the visual # interface ...
""" Input the account's username and password here. """ USERNAME = "USERNAME" PASSWORD = "PASSWORD"
import asyncio import commands class ConsoleInterface: def __init__(self, guild=None): self.guild = guild # Unused async def send_text_to_channel(self, msg, channel_name): print(f"#{channel_name}: {msg}") return True async def send_embed_to_channel(self, embed_msg, channel_name)...
from typing import List import torch from torch.sparse import FloatTensor from . import BaseSparseNdArray if False: import numpy as np __all__ = ['SparseNdArray'] class SparseNdArray(BaseSparseNdArray): """Pytorch powered sparse ndarray, i.e. FloatTensor .. seealso:: https://pytorch.org/docs/...
# -*- coding: utf-8 -*- #!/usr/bin/python from math import exp,log,sqrt from random import random import numpy as np import pylab as P X=lambda: log(random()*(exp(1)-1)+1 ) av=lambda o: float(sum(o))/len(o) m=10000 print "\n\nEjercicio 1 pag 81" print "Se puede obtener la función de acumulación para esta distribuci...
# This file is part of sequencing. # # Copyright (c) 2021, The Sequencing Authors. # 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. import copy import numpy as np from tqdm import tqdm import qutip f...
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Implementation of SS-QCCN algorithm ------------- Based on paper: Steganalysis of QIM Steganography in Low-Bit-Rate Speech Signals ------------- Author: Zinan Lin Email: zinanl@andrew.cmu.edu ''' import os, random, pickle, csv, sys import numpy as np from sklearn...
#!/usr/bin/env python3 print("Print alphabets ") lastNumber = 6 asciiNumber = 65 for i in range(0, lastNumber): for j in range(0, i+1): character = chr(asciiNumber) print(character, end=' ') asciiNumber+=1 print(" ")
import torch import argparse from utils import * from models import * from mode_validation import * from train_and_eval import * from torch.optim import lr_scheduler from torchvision import datasets, transforms import numpy as np import time import pandas as pd RESULTS_PATH = "Results/" """ The parameters to use when...
from graphviz import Digraph import numpy as np import xlrd import openpyxl import pandas as pd def build_dot(): dot = Digraph() dot.attr(label='服务调用热点监控 Service HotSpot Monitor', labelloc="t") sheet = pd.read_excel("data/services.xlsx", sheet_name='services') print(sheet) for index, row in sheet....
# -*- coding: utf-8 -*- from __future__ import unicode_literals from conf import load_config from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() engine = create_engine(load_config().DB_ENGINE) DBSession = sess...
""" @brief Base robot class @author Josip Delic (delijati.net) @author Rowland O'Flaherty (rowlandoflaherty.com) @date 04/23/2014 @version: 1.0 @copyright: Copyright (C) 2014, see the LICENSE file """ import sys import time import re import socket import threading import Adafruit_BBIO.GPIO as GPIO import Adafruit_BB...
import sys import atexit import traceback import threading def wait_exit(): #Wait for shutdown signal if running in service mode print("Press Ctrl-C to quit...") if sys.platform == "win32": _win32_wait_exit() else: import signal signal.sigwait([signal.SIGTERM,signal.SIGINT]) ...
# Parse the input from the input file input_file = 'example_input.txt' polymer_template = '' rules = {} with open(input_file) as input: # Template line polymer_template = input.readline().rstrip() # Empty line input.readline() # Rest is rules for line in input.readlines(): pair, insert = line....
# Create a function called kwargs_length() that can receive some keyword arguments and return their length. # Submit only the function in the judge system. def kwargs_length(**kwargs): return len(kwargs)
class Node: def __init__(self, data=None, labels=None, is_leaf=False, split_feature=None, split_kind=None, split_criteria=None, left=None, right=None, depth=0): """ :param pandas.Dataframe data: features :param pandas.Dataframe labels: label...
# same imports as earlier. from vtkmodules.util.vtkAlgorithm import VTKPythonAlgorithmBase # new module for ParaView-specific decorators. from paraview.util.vtkAlgorithm import smproxy, smproperty, smhint, smdomain @smproxy.source(name="MagnetovisPlane", label="MagnetovisPlane") @smhint.xml('<ShowInMenu category="Mag...
# Generated by Django 2.2 on 2019-04-08 05:06 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Assignment', fields=[ ...
import click from sgp30_exporter import app @click.command() @click.option( "--listen-address", default="0.0.0.0", help="The address on which to listen for HTTP requests.", show_default=True, ) @click.option( "--listen-port", default=9895, help="The port on which to listen for HTTP reques...
#!/usr/bin/python from gi.repository import Gtk, WebKit, Notify import json import traceback from pickle import Pickler, Unpickler import os import sys from os.path import expanduser home = expanduser("~") gskype_settings_file = os.path.join(home, ".gskype", "settings") gskype_state_file = os.path.join(home, ".gskype"...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Script to generate the ASAP7 dummy SRAM cache. # # See LICENSE for licence details. import sys import re from typing import List def main(args: List[str]) -> int: if len(args) != 3: print("Usage: ./sram-cache-gen.py list-of-srams-1-per-line.txt output-...
#!/usr/bin/env python import os import sys from setuptools import setup from pip.download import PipSession from pip.req import parse_requirements # work around the combination of http://bugs.python.org/issue8876 and # https://www.virtualbox.org/ticket/818 since it doesn't really have ill # effects and there will be ...
""" Copyright 2015 Rackspace 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, software dist...
# Copyright 2020 Google 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 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, ...
# (C) Datadog, Inc. 2020-present # All rights reserved # Licensed under a 3-clause BSD style license (see LICENSE) import copy import mock import pytest from datadog_checks.snowflake import SnowflakeCheck, queries from .conftest import CHECK_NAME PROXY_CONFIG = {'http': 'http_host', 'https': 'https_host', 'no_proxy...
def paint_fill(image, target_color, location, init_color=None): dims = image.shape if location[0] >= dims[0] or location[1] >= dims[1] or location[0] < 0 or location[1] < 0: return # end recursion (1) if the location is invalid if init_color is None: init_color = image[location[0], location...
# coding=utf-8 import re import sys import pkuseg def split(filename): new_f = filename + '.new' c = [] pattern = re.compile(r'[!?。\.\!\?]') with open(filename) as f1, open(new_f, 'w') as f2: for line in f1: m = re.findall(pattern, line) cc = re.split(pattern, line.st...
s = 'azcbobobegghakl' count = 0 threeCharStringCount = len(s)-2 for i in range(0, threeCharStringCount): print i print s[i:i+3] if s[i:i+3] == "bob": count += 1 print "yep" else: print "nope" print "Number of times bob occurs is: " + str(count)
#!/usr/bin/python3 """Simple Flask app, with additional route""" from flask import Flask, abort, render_template from models import storage from models.state import State from models.amenity import Amenity from models.place import Place from uuid import uuid4 app = Flask(__name__) app.url_map.strict_slashes = False ...
# -*- coding: utf-8 -*- from flask import Blueprint, render_template, abort, g, request, redirect, \ url_for, jsonify from .models import Group, Member, GameLog from fossil.fb import Graph from fossil.auth.decorators import login_required, LoginRequired from google.appengine.ext import db import random import json ...
import numpy as np def tau(pv: float, compr_total: float, pi: float): """ Time Constant Parameters --- pv : float pore volume compr_total : float total compressibility pi : float productivity index """ return pv*compr_total/pi def pvct(pv: float, compr_total: f...
#!/usr/bin/env python3 """ Push file to robot """ import argparse import requests address = 'http://192.168.49.1:8080/' javafilesave = 'java/file/save?f=' def main(args): with open(args.file, 'r') as f: code = f.read() cookieReq = requests.get(address) # TODO: cache this cookie ...
# -*- coding: utf-8 -*- """ Main module. """ import os import sys from .util import click_funcs from .util import shell_funcs def run_conda_create(name): """ The program's main routine. """ # Defaults env_path = shell_funcs.get_default_conda_env_path() py_version = '3.6' libs = {'pylint':...
from datetime import datetime import json import unittest from elasticsearch.helpers import bulk from elasticsearch_dsl import Index from elasticsearch_dsl.connections import connections from elasticsearch_dsl.document import DocType from elasticsearch_dsl.field import String from pyspark.conf import SparkConf from py...
""" ============================================= Processess PPG Cycles (:mod:`pypg.cycles`) ============================================= Identify characteristics and extract features from PPG Cycles. """ import numpy as np import pandas as pd from scipy import signal from .plots import marks_plot def find_onset...
import unittest import os import cProfile import celescope.snp.variant_calling as vc from tests.unittests.__init__ import TEST_DIR_ROOT class Test_snp(unittest.TestCase): def setUp(self): os.chdir(f'{TEST_DIR_ROOT}/snp/') self.sample = 'test1' self.vcf_file = f'{self.sample}/07.variant_ca...
""" app.recipe_users.tests.test_recipe_users_admin ---------------------------------------------- Tests cases for recipe_users admin functionality """ from django.test import TestCase, Client from django.contrib.auth import get_user_model from django.urls import reverse class TestRecipeUsersAdmin(TestCase): """ ...
from django.db import models from django_extensions.db.fields.json import JSONField from django_extensions.tests.fields import FieldTestCase class TestModel(models.Model): a = models.IntegerField() j_field = JSONField() class JsonFieldTest(FieldTestCase): def testCharFieldCreate(self): j = Test...
from sklearn.ensemble import ExtraTreesClassifier from sklearn.ensemble import ExtraTreesRegressor from sklearn.ensemble import RandomForestClassifier from sklearn.ensemble import RandomForestRegressor from sklearn.metrics import mean_squared_error, make_scorer from data_helper import DataHelper import numpy as np impo...
import torch.nn as nn import torch.nn.functional as F from layers.autogcn_layer import AUTOGCNLayer class AUTOGCNNet(nn.Module): def __init__(self, net_params): super().__init__() in_dim = net_params['in_dim'] hidden_dim = net_params['hidden_dim'] n_classes = net_params['n_classes']...
from code-katas import array_plus_array import unittest """ Test.assert_equals(array_plus_array([1, 2, 3], [4, 5, 6]), 21) Test.assert_equals(array_plus_array([-1, -2, -3], [-4, -5, -6]), -21) Test.assert_equals(array_plus_array([0, 0, 0], [4, 5, 6]), 15) Test.assert_equals(array_plus_array([100, 200, 300], [400, 500,...
# coding=utf-8 from OTLMOW.OTLModel.Classes.VerlichtingstoestelConnector import VerlichtingstoestelConnector from OTLMOW.OTLModel.Classes.Verlichtingstoestel import Verlichtingstoestel # Generated with OTLClassCreator. To modify: extend, do not edit class VerlichtingstoestelHgLP(VerlichtingstoestelConnector, Verlicht...
''' Dataset and DataLoader adapted from https://www.kaggle.com/pinocookie/pytorch-dataset-and-dataloader ''' import pickle import torch import torchvision import torchvision.transforms as transforms from PIL import Image from sklearn.model_selection import train_test_split from torch.utils.data import Dataset from to...
import itertools import numpy as np from typing import Dict, Optional from autoconf import cached_property from autoarray.inversion.mappers.abstract import AbstractMapper from autoarray.structures.arrays.two_d.array_2d import Array2D from autoarray.numba_util import profile_func from autoarray.structures.a...
import logging import os from .utils import load_checkpoint, save_checkpoint logger = logging.getLogger(__name__) def train_loop(model, mutator, criterion, optimizer, scheduler, train_loader, sanitize_loader, valid_loader, train_fn, valid_fn, writer, args): last_epoch = 0 auto...
import serial #From pyserial package https://anaconda.org/anaconda/pyserial import sqlite3 #From sqlite3 package https://anaconda.org/anaconda/sqlite3 from sqlite3 import Error from datetime import datetime import numpy as np import matplotlib.pyplot as plt import collections from drawnow import drawnow, figure #Syste...
""" This module produces the outputs/plots. Marina von Steinkirch, spring/2013 """ import pylab import numpy from matplotlib import pyplot def plotPhaseSpace( b, aTheta, aOmega, t, power, k): pylab.clf() pylab.cla() label = str(b) pylab.subplot(221) pylab.plot( aTheta, aOmeg...
""" Common ====== Expressions common to both :mod:`stream` and :mod:`sequence`. """ import numpy as np from scipy.special import erf from scipy.fftpack import dct def saturation_distance(mean_mu_squared, wavenumber, scale): """Saturation distance according to Wenzel. :param mean_mu_squared: Mean mu squared...
# -*- coding: utf-8 -*- from datetime import timedelta from copy import deepcopy from openprocurement.api.utils import get_now # ContractNoItemsChangeTest def no_items_contract_change(self): data = deepcopy(self.initial_data) del data['items'] response = self.app.post_json('/contracts', {"data": data}) ...
import sqlite3 from datetime import datetime, timedelta import dateutil.relativedelta def initialize(): '''Inicializa la base de datos con tabla 'registros' ''' try: con = sqlite3.connect('facemask.db') cur = con.cursor() cur.execute('''CREATE TABLE IF NOT EXISTS registros ...
#!/usr/bin/env python import os from collections import deque def find_mismatch(xmas: list, preamble: int = 25) -> tuple: running_list = deque(xmas[:preamble]) mismatch = None i = preamble while mismatch is None: next_number = xmas[i] for number in running_list: if next_n...
from django.test import TestCase, Client from django.core.cache import cache from apps.accounts.models import Account class AccountTest(TestCase): """General Tests for Accounts Verification""" def setUp(self): """Fixtures""" self.username = 'new_user' self.username2 = 'new_user2' ...
from collections import deque from typing import List # DP - Bottom up def updateMatrix(self, mat: List[List[int]]) -> List[List[int]]: m, n = len(mat), len(mat[0]) for r in range(m): for c in range(n): if mat[r][c] > 0: top = mat[r - 1][c] if r > 0 else float('inf') ...
import json def generate_dict_from_json(file_path: str) -> dict: """ Returns a dictionary filled with JSON data loaded from the file provided. :param file_path: Path to file containing JSON to load :return: Dictionary with JSON retrieved from file """ with open(file_path) as file: dat...
# coding: utf-8 from oslo_config import cfg CONF = cfg.CONF def base(request): namespace = request.resolver_match.namespace view_name = request.resolver_match.view_name livereload_js = 'http://{0}:35729/livereload.js'.format( CONF.web.node_public_host) chat_socketio_js = 'http://{0}:{1}/sock...
from pathlib import Path from typing import Dict from typing import List import pandas as pd import drem def _convert_dataframe_to_dict_of_lists( vo_cibse_link: pd.DataFrame, category_col: str, uses_col: str, ) -> Dict[str, str]: """Convert pandas DataFrame into a Dictionary of Lists. Args: vo_...
#! /usr/bin/env python import numpy as np import numpy.linalg as LA # test passed def allocate_time(path, max_vel, max_acc): pathlength = path.shape[0] distance = path[1:pathlength, :] - path[0:pathlength-1, :] distance = np.transpose(LA.norm(distance, axis=1)) time_segment = np.multiply(3.0 * (dis...
from arm.logicnode.arm_nodes import * class SetTraitPausedNode(ArmLogicTreeNode): """Sets the paused state of the given trait.""" bl_idname = 'LNSetTraitPausedNode' bl_label = 'Set Trait Paused' arm_version = 1 def init(self, context): super(SetTraitPausedNode, self).init(context) ...
import os import sys from setuptools import setup, find_packages if sys.argv[-1] == "publish": os.system("python setup.py sdist upload") sys.exit() setup_args = dict( name="dlgr.demos", version="6.5.0", description="Demonstration experiments for Dallinger", url="http://github.com/Dallinger/D...
from nonebot import on_command from nonebot.adapters.cqhttp import Message from io import BytesIO from nonebot.typing import T_State from nonebot.adapters.cqhttp.permission import GROUP, PRIVATE from nonebot.adapters.cqhttp.event import Event from nonebot.adapters.cqhttp.bot import Bot from nonebot.adapters.cqhttp.mess...
import logging import sys import argparse # pylint: disable=import-error from .upstream.server.entrypoint import configure_parser as server_parser from .upstream.util.cli import * from .upstream.__init__ import __version__ from .upstream.util.log import * # # setting up custom trace debug level LOGGER = logging.getLog...
import requests import postageapp from ostruct import OpenStruct import json from json import JSONEncoder class RequestEncoder(JSONEncoder): def default(self, o): return o.__dict__ class Request: def __init__(self, method = None): self._method = method or 'send_message' self._argum...
# coding=utf-8 """Annotate python syntax trees with formatting from the source file.""" # Copyright 2021 Google 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 obtain a copy of the License at # # https://www.apache....
#!/usr/bin/python3 # Download the latest KaoriYa Vim from the GitHub release import argparse import calendar import io import json import os import sys import time import urllib.request, urllib.error # Repository Name repo_name = 'koron/vim-kaoriya' gh_release_url = 'https://api.github.com/repos/' + repo_name + '/re...
from flask import Flask, render_template, request, jsonify import pymongo from cassandra.cluster import Cluster from cassandra.auth import PlainTextAuthProvider ''' Objective: - Create a UI to connect to cloud DBs (MongoDb and Cassandra) - Create APIs to do CRUD operations to these DBs ''' app = Flask(__nam...
# -*- python -*- """@file @brief I2C-serial transport for pato Copyright (c) 2014-2015 Dimitry Kloper <kloper@users.sf.net>. All rights reserved. @page License Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistrib...
""" Tests gen3.file.Gen3File for calls """ from unittest.mock import patch import json import pytest from requests import HTTPError NO_UPLOAD_ACCESS_MESSAGE = """ You do not have access to upload data. You either need general file uploader permissions or create and write-storage permissions on the ...
"""urbanpiper URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class...
#!/usr/bin/env python3 import sys, subprocess, time, os, getopt, copy, signal from datetime import datetime from ast import literal_eval from ctypes import * import numpy as np # ================================================================================= reproduceFile = "" memInfoFile = "" TaskReproduce = 0 Lo...
#!/usr/bin/env python # a stacked bar plot with errorbars import numpy as np import matplotlib.pyplot as plt import sys import math import collections from matplotlib.backends.backend_pdf import PdfPages if __name__ == '__main__': ''' Need an argument with the data file where each row has the format "'...
""" Generating data from the CarRacing gym environment. !!! DOES NOT WORK ON TITANIC, DO IT AT HOME, THEN SCP !!! """ import argparse from os.path import join, exists import gym import numpy as np from utils.misc import sample_continuous_policy def generate_data(rollouts, data_dir, noise_type): # pylint: disable=R0914...
from sqlalchemy.orm.attributes import InstrumentedAttribute from sqlalchemy.ext.hybrid import hybrid_property from logic_bank.rule_type.abstractrule import AbstractRule class Derivation(AbstractRule): def __init__(self, derive: InstrumentedAttribute): # names = derive.split('.') if not isinstance...
from django.contrib.auth.models import Group, User from django.db import models class Draft(models.Model): title = models.CharField(max_length=100) text = models.TextField() owner = models.ForeignKey(User, on_delete=models.CASCADE)
from tkinter import * from tkinter.ttk import Style import cv2 from PokikiAPI import Pokiki from PIL import Image, ImageTk from tkinter import filedialog as fd from threading import Thread root = Tk() root.title("Pokiki - Mosaic Video Maker") root.resizable(False, False) style = Style(root) style.theme_use('clam') #...
# encoding: UTF-8 """ 双均线策略 注意事项: 1. 作者不对交易盈利做任何保证,策略代码仅供参考 2. 本策略需要用到talib,没有安装的用户请先参考www.vnpy.org上的教程安装 """ from __future__ import division from ctaBase import * from ctaTemplate import * ######################################################################## class DMAStrategy(CtaTemplate): """双均线交易策略""" ...
from prolog.interpreter.signature import Signature, SignatureFactory def test_eq(): sig1 = Signature("a", 0) assert sig1.eq(sig1) sig2 = Signature("a", 0) assert sig1.eq(sig2) sig3 = Signature("a", 1) assert not sig1.eq(sig3) sig4 = Signature("b", 0) assert not sig1.eq(sig4) def tes...
## Evaluator for evaluating net accuracy against test data import numpy as np import os import LabPicsMaterialInstanceReader as LabPicsInstanceReader import torch CatName={} CatName[0]='Empty' CatName[1]='Vessel' CatName[2]='V Label' CatName[3]='V Cork' CatName[4]='V Parts GENERAL' CatName[5]='Ignore' CatName[6]='Liq...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import requests from flask import current_app from flod_common.session.utils import (unsign_auth_token, verify_superuser_auth_token) USERS_URL = os.environ.get('USERS_URL', 'http://localhost:4000') USERS_VERSION = os.envir...
with open('answer.data', 'rb') as a: answer = a.read(8192) with open('cloud.data', 'ab') as c: while answer: c.write(answer) answer = a.read(8192)
import os from os import path import sys import subprocess import requests def inHDInsightClusterNode(): if path.exists('/usr/hdp/current') : print('Please don\'t run this script on your existing cluster node, yet!') sys.exit() return True else: #print('Running on an Azure L...
# a heap structure designed for external sort import random import sys import collections item = collections.namedtuple('item', ['listname', 'index', 'value']) class Heap: def __init__(self): self.h = [] self.currsize = 0 def leftChild(self,i): if 2*i+1 < self.currsize: return 2*i+1 return None ...
#python train.py --solver SFD/solver.prototxt --gpu 0,1,2,3 from __future__ import print_function import argparse import os import time import torch import torch.nn as nn import torch.optim as optim from torch.autograd import Variable from caffenet import CaffeNet from prototxt import parse_solver import caffe class P...
#!/usr/bin/env python3 # Written by Ivan Anishchuk (anishchuk.ia@gmail.com) in 2015 """ Solution for APU: Init Phase. It's actually too complex because I've down all the wrong way: I just copy-pasted the beginning of my solution for APU: Improvement. During contest I obviously did something much simpler but I lost it ...
# -*- coding: utf-8 -* from copy import deepcopy from typing import Dict from videoanalyst.utils import Registry TRACK_MONITORS = Registry('TRACK_MONITOR') VOS_MONITORS = Registry('VOS_MONITOR') TASK_MONITORS = dict( track=TRACK_MONITORS, vos=VOS_MONITORS, ) class MonitorBase: r""" Monitor base cla...
# ref: https://github.com/waymo-research/waymo-open-dataset/blob/master/waymo_open_dataset/utils/frame_utils.py from __future__ import absolute_import from pathlib import Path import os import time from glob import glob from __future__ import division from __future__ import print_function import numpy as np import te...
# -*-coding:utf-8-*- """Main application script""" import os import click from flask_migrate import Migrate from app import create_app, db from app.models import User app = create_app(os.getenv('APP_CONFIG') or 'default') migrate = Migrate(app, db) # set up code coverage COV = None if os.environ.get('APP_COVERAGE...
""" 08-function-calls.py - Using custom algorithms with python function calls. **EventCall** :: EventCall(function, *args, occurrences=inf, stopEventsWhenDone=True) EventCall calls a function, with any number of arguments (\*args) and uses its return value for the given parameter. The example below use a functio...
""" Read/write JSON formatted data """ import os import json def read_test(file_path): """ Read data from a file having JSON formatted data. """ if os.path.exists(file_path): with open(file_path, "r") as file: json_data = json.load(file) print('Value of key_1: ', j...
from enum import Enum from typing import Any, Dict, Final, List, Optional, Sequence, Set, Union import torch from numpy import typing as nptyping from embeddings.evaluator.metrics_evaluator import MetricsEvaluator from embeddings.metric.hugging_face_metric import HuggingFaceMetric from embeddings.metric.metric import...
# -*- coding: utf-8 -*- """Validation machine file IPMSM TOYOTA Prius 2004 interior magnet (V shape) with distributed winding 50 kW peak, 400 Nm peak at 1500 rpm from publication Z. Yang, M. Krishnamurthy and I. P. Brown, "Electromagnetic and vibrational characteristic of IPM over full torque-speed range," Electric Ma...
# Copyright 2018/2019 The RLgraph 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 appli...
pri=[{'Bachelor of Science in Mathematics<br>\n(General Mathematics Option)': [{'': []}, {'Required Subjects': [{'Departmental Program': '18.03', 'type': 'required'}]}, {'Restricted Electives': [{'Departmental Program': 'Select eight 12-unit subjects of essentially different content, including at least six advanced sub...