content
stringlengths
5
1.05M
class double_buffer: def __init__(self, cls): self.__name__ = cls.__name__ self.__doc__ = cls.__doc__ try: self._transition_hook = getattr(cls, 'on_transition') except AttributeError: self._transition_hook = lambda self: None try: self._c...
# -*- coding: utf-8 -*- """ SMART_2011 Assignment Includes Conversion from Scilab to Python3 Brunston Poon begun 2014.09.22 - completed 2014.09.25 """ import numpy as np from matplotlib import pyplot as plt file = r"C:\ast\SMART_data.txt" numberOfColumns = 7 data = np.loadtxt(file) radii = data[:,0] # Distance colu...
from django.views.generic import * from wikis.mixins import * import json from commons.markdown import markdown_tools from commons import file_name_tools from commons.file import file_utils from .forms import PageCreateForm, PageUpdateForm, PageCopyForm from django.urls import reverse import datetime from django.http i...
import os import subprocess from ctypes import RTLD_LOCAL, RTLD_GLOBAL class LibraryMeta(type): def __call__(cls, name, mode=RTLD_LOCAL, nm="nm"): if os.name == "nt": from ctypes import WinDLL # WinDLL does demangle the __stdcall names, so use that. return WinDLL(name...
import torch import torchtestcase import unittest from survae.tests.nn import ModuleTest from survae.nn.layers.encoding import PositionalEncodingImage class PositionalEncodingImageTest(ModuleTest): def test_layer_is_well_behaved(self): batch_size = 10 shape = (3,8,8) x = torch.rand(batch_...
import importlib def get_project_settings(): modele = importlib.import_module("setting") return modele if __name__ == '__main__': get_project_settings()
#!/usr/bin/python """ --- Day 11: Hex Ed --- Crossing the bridge, you've barely reached the other side of the stream when a program comes up to you, clearly in distress. "It's my child process," she says, "he's gotten lost in an infinite grid!" Fortunately for her, you have plenty of experience with infinite ...
import time from pgdrive.envs.pgdrive_env import PGDriveEnv from pgdrive.utils import setup_logger def vis_highway_render_with_panda_render(): setup_logger(True) env = PGDriveEnv( { "environment_num": 1, "manual_control": True, "use_render": True, "use...
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
import mido import json import keyboard import sys # load macro mappings from config file #TODO: command line option for filename macros = json.load((open("config.json", "r"))) # { "channel": "1", "onpress": "", "onchange": "", "onincrease": "", "ondecrease": "", "granularity": 8 }, # configure the behavior for ea...
from django.db import models from django.contrib.auth.models import User # Create your models here. class Location(models.Model): name = models.CharField(max_length = 30) def __str__(self): return self.name class Neighbourhood(models.Model): name = models.CharFi...
''' StaticRoute Genie Ops Object Outputs for NXOS. ''' class StaticRouteOutput(object): # 'show ipv4 static route' output showIpv4StaticRoute = { 'vrf': { 'default': { 'address_family': { 'ipv4': { 'routes': { ...
import os import sys if not os.path.isdir(os.path.join(sys.path[0], "data_pipeline", "tests")): raise Exception("Tests must be run from base dir of repo")
from .topology import Topology from .elements import Atom, Bond, Angle, Dihedral, Proper, Improper from .molecule import Molecule from .zmatrix import ZMatrix from .rotamer import RotamerLibrary from .conformer import BCEConformations
from email.mime.multipart import MIMEMultipart from email.mime.base import MIMEBase from email.mime.text import MIMEText from email.Utils import formatdate from os.path import basename from smtplib import SMTP class CustomSMTP(SMTP): def __init__(self, *args, **kwargs): self.host = kwargs.pop('host', 'lo...
# Ok, lets collect data from preprogrammed pick import gym import roboticsPlayroomPybullet import numpy as np import os import shutil from tqdm import tqdm env = gym.make('pandaPlay1Obj-v0') env.render(mode='human') env.reset() open_gripper = np.array([0.04]) closed_gripper = np.array([0.01]) p = env.panda.bullet_cl...
import requests from bs4 import BeautifulSoup import re def solr(request,title,author): r = requests.get("http://katalog.stbib-koeln.de:8983/solr/select?rows=1&q="+title+"+"+author) soup = BeautifulSoup(r.text) PublicationDate = soup.find("arr", {"name": "DateOfPublication"}).find("str") Author = soup.find("arr"...
import json import os # formats songs for the app # note - translate uses python3 syntax, so run this with python3! # note - needs work on getting rid of [] from genius things_to_remove = dict.fromkeys(map(ord, '()[]"'), None) output = "" if (os.path.isfile("input.txt")): with open("input.txt") as f: word...
from typing import List, Any, Union import matplotlib.pyplot as plt import numpy as np import pandas as pd from sklearn.metrics import adjusted_rand_score from ML import DBscan_step_positions, DBscan_step_positions_and_velocity, build_ground_truth, \ DBscan_step_intuition_dist_multistep_1, DBscan_step_intuition_d...
import asyncio from dataclasses import dataclass from enum import Enum import functools import heapq from dataclasses_json import dataclass_json import numpy as np from runstats import Statistics from typing import Callable, List, Optional from knn import utils from knn.utils import JSONType from .base import Reduc...
import json from nose.tools import assert_equal, assert_not_equal from tests.fixtures import WebTest class TestMetricsController(WebTest): def test_index(self): response = self.app.get('/metrics/', follow_redirects=True) assert_equal( response.status_code, 200, ...
# -*- coding: utf-8 -*- """Crop_data_prep.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1jhfMRdq6na9JiUmcqqZsQAWpknZjvRpY ## Notebook for transforming raw cpdata to Mergable data ### Filter cpdata.csv to MergeFileCrop.cv ### Filter fertilizer....
import sys import os.path as op from pathlib import Path from databases import Database sys.path.append(op.abspath(op.join(op.dirname(__file__), '..'))) import create_db # noqa: import not at top of file projects = {'icepap-ipassign': {'README': ('tests/test_data/ipa/README.md', ...
# # PySNMP MIB module TPT-HIGH-AVAIL-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TPT-HIGH-AVAIL-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:26:19 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, ...
#!/usr/bin/env python # -*- encoding: utf-8 -*- """ """ from __future__ import absolute_import, division, print_function from builtins import (bytes, open, str, super, range, zip, round, input, int, pow, object, map, zip) import os import argparse import multiprocessing import gunicorn.app....
from buildings import * from soldiers import SoldierClass class Player(object): def __init__(self, name, money, army, buildings): self.name = name self.money = money self.army = army self.buildings = buildings def buyArmy(self, economy, army): iCost = economy.cost(army) print "Buying ...
#!/usr/bin/env python3 """ Export CLA information from bugs.python.org to a JSON file. """ from __future__ import annotations from datetime import datetime import json import os import xmlrpc.client from dotenv import load_dotenv from rich.progress import track try: import certifi except ModuleNotFoundError: ...
from django.utils.functional import lazy from drf_spectacular.utils import extend_schema_field from drf_spectacular.openapi import OpenApiTypes from rest_framework import serializers from baserow.api.groups.serializers import GroupSerializer from baserow.core.registries import application_type_registry from baserow....
NONE = 0 HALT = 1 << 0 FAULT = 1 << 1 BREAK = 1 << 2
"""General utility functions.""" import contextlib import random import inspect from asyncio import ensure_future from functools import partial import datetime from util.commands.errors import PassException def bdel(s, r): return (s[len(r):] if s.startswith(r) else s) class DiscordFuncs(): def __init__(self, bot):...
import os import pandas as pd import click from flask import Flask from flask.cli import FlaskGroup from flask.cli import run_command from .config import update_config from .routing import register_blueprints from .routing import register_routes_to_pbo from .jinja_env import create_jinja_env from .utils.excel impor...
# copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve. # # 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 applica...
# Copyright 2017 Great Software Laboratory Pvt. Ltd. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
import nni import GPUtil from UCTB.dataset import GridTrafficLoader from UCTB.model import ST_ResNet from UCTB.evaluation import metric args = { 'dataset': 'DiDi', 'city': 'Xian', 'num_residual_unit': 4, 'conv_filters': 64, 'kernel_size': 3, 'lr': 1e-5, 'batch_size': 32, 'MergeIndex': ...
"""Print all tasks. Usage: # Print all tasks python3 print_all_tasks.py # Print a specific task python3 print_all_tasks.py --idx 10 """ import argparse from common import load_and_register_tasks def print_task(index, task): print("=" * 60) print(f"Index: {index}") print(f"flop_ct: {task.compute_dag.flop_...
import pytest from jsonschema import ValidationError from babbage.validation import validate_model class TestValidation(object): def test_simple_model(self, simple_model_data): validate_model(simple_model_data) def test_invalid_fact_table(self, simple_model_data): with pytest.raises(Validat...
class Solution(object): def getRow(self, rowIndex): """ :type rowIndex: int :rtype: List[int] """ row = [1] for _ in range(rowIndex): # pad 0, perform element-wise addition row = [x + y for x, y in zip([0] + row, row + [0])] return row ...
from typing import Tuple, Union from axelrod import Action C, D = Action.C, Action.D Score = Union[int, float] class Game(object): """Container for the game matrix and scoring logic. Attributes ---------- scores: dict The numerical score attribute to all combinations of action pairs. "...
import inspect import sys from pathlib import Path import kts.ui.settings from kts.core.backend.ray_middleware import setup_ray from kts.core.cache import frame_cache, obj_cache from kts.core.lists import feature_list, helper_list from kts.settings import cfg from kts.util.debug import logger def find_scope(): f...
import argparse import os import sys import pickle import time import pandas as pd import re from src.utils import np from src.problem import Problem from src.controller import Parallel_Controller from src.MMAS_solver import MMAS_Solver from pathlib import Path def parse_arguments(): parser = argparse.ArgumentPars...
# -*- coding: utf-8 -*- """ eng : import library tr : kรผtรผphaneleri yรผklรผyoruz """ import numpy as np import matplotlib.pyplot as plt import seaborn as sns from scipy import stats from keras.datasets import imdb from keras.preprocessing.sequence import pad_sequences from keras.models import Sequential f...
from __future__ import with_statement import inspect, logging log = logging.getLogger(__name__) import math, threading from warnings import warn import otp.ai.passlib.exc as exc, otp.ai.passlib.ifc as ifc from otp.ai.passlib.exc import MissingBackendError, PasslibConfigWarning, PasslibHashWarning from otp.ai.passlib.if...
''' โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–„โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–„โ–‘โ–‘โ–‘โ–‘ โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–Œโ–’โ–ˆโ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–„โ–€โ–’โ–Œโ–‘โ–‘โ–‘ โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–Œโ–’โ–’โ–ˆโ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–„โ–€โ–’โ–’โ–’โ–โ–‘โ–‘โ–‘ โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–โ–„โ–€โ–’โ–’โ–€โ–€โ–€โ–€โ–„โ–„โ–„โ–€โ–’โ–’โ–’โ–’โ–’โ–โ–‘โ–‘โ–‘ โ–‘โ–‘โ–‘โ–‘โ–‘โ–„โ–„โ–€โ–’โ–‘โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–ˆโ–’โ–’โ–„โ–ˆโ–’โ–โ–‘โ–‘โ–‘ โ–‘โ–‘โ–‘โ–„โ–€โ–’โ–’โ–’โ–‘โ–‘โ–‘โ–’โ–’โ–’โ–‘โ–‘โ–‘โ–’โ–’โ–’โ–€โ–ˆโ–ˆโ–€โ–’โ–Œโ–‘โ–‘โ–‘ โ–‘โ–‘โ–โ–’โ–’โ–’โ–„โ–„โ–’โ–’โ–’โ–’โ–‘โ–‘โ–‘โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–€โ–„โ–’โ–’โ–Œโ–‘โ–‘ โ–‘โ–‘โ–Œโ–‘โ–‘โ–Œโ–ˆโ–€โ–’โ–’โ–’โ–’โ–’โ–„โ–€โ–ˆโ–„โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–ˆโ–’โ–โ–‘โ–‘ โ–‘โ–โ–‘โ–‘โ–‘โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–Œโ–ˆโ–ˆโ–€โ–’โ–’โ–‘โ–‘โ–‘โ–’โ–’โ–’โ–€โ–„โ–Œโ–‘ โ–‘โ–Œโ–‘โ–’โ–„โ–ˆโ–ˆโ–„โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–’โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–’โ–’โ–’โ–’โ–Œโ–‘ โ–€โ–’โ–€โ–โ–„โ–ˆโ–„โ–ˆโ–Œโ–„โ–‘โ–€โ–’...
#!/usr/bin/env python import pytest TEST_DATA = [ 143845, 86139, 53043, 124340, 73213, 108435, 126874, 131397, 85618, 107774, 66872, 94293, 51015, 51903, 147655, 112891, 100993, 143374, 83737, 145868, 144768, 89793, 124127, ...
""" Manipulation with the YANG schemas. File: schemas.py Author: Radek Krejci <rkrejci@cesnet.cz> """ import json import os import errno import time from subprocess import check_output from shutil import copy from liberouterapi import auth from flask import request import yang from .inventory import INVENTORY, inven...
import os as _os import sys as _sys import json import dash as _dash from dash_uploader.configure_upload import configure_upload from dash_uploader.callbacks import callback from dash_uploader.httprequesthandler import HttpRequestHandler from dash_uploader.upload import Upload # noinspection PyUnresolvedR...
import unittest from .. import lmparser from .. import tokenstream from .. import lexertokens from .. import lmast from .. import lamarksyntaxerror class TestLmParser(unittest.TestCase): def setUp(self): self.parser = lmparser.LmParser({}) def test_empty(self): "Parse empty token stream" ...
from __future__ import division from scitbx.linalg import eigensystem from scitbx.array_family import flex from libtbx.utils import null_out from math import acos,pi from scitbx import matrix from iotbx import pdb import os class fab_elbow_angle(object): def __init__(self, pdb_hierarchy, ...
import os import glob import cc3d import numpy as np from skimage import io, transform from torch.utils.data import Dataset from copy import copy from graphics import Voxelgrid from graphics.transform import compute_tsdf import h5py # from graphics.utils import extract_mesh_marching_cubes # from graphics.visualizatio...
import setuptools setuptools.setup( name="windows-path-adder", version="1.0.4", license='MIT', author="oneofthezombies", author_email="hunhoekim@gmail.com", description="add environment path in windows.", long_description=open('README.md').read(), long_description_content_type = 'text/...
#!/usr/bin/env python import json import os import urllib.request from pprint import pprint job_status = os.environ["JOB_STATUS"] github = json.loads(os.environ["GITHUB_ENVIRONMENT"]) actor = github["actor"] workflow = github["workflow"] repository = github["repository"] run_id = github["run_id"] html_url = f"https://...
from typing import Dict import pandas as pd import plotly.graph_objects as go import mlrun from mlrun.artifacts import Artifact, PlotlyArtifact from ..._common import ModelType from ..plan import MLPlanStages, MLPlotPlan from ..utils import DatasetType, to_dataframe class FeatureImportancePlan(MLPlotPlan): """...
import requests import pandas as pd import datetime as dt import matplotlib.pyplot as plt #my_api_key = "" Input your AlphaVenture API key as a str() var here my_stock = "GME" my_timeframe = "TIME_SERIES_DAILY" response = requests.get("https://www.alphavantage.co/query?function="+my_timeframe+"&symbol="...
"""Bot starts a telegram bot.""" import os from github import Github import requests from datetime import datetime, timedelta from collections import defaultdict import logging g = Github(os.getenv('GITHUB_USER', ''), os.getenv('GITHUB_PASSWORD', '')) BASE_URL = 'https://api.github.com' log = logging.getLogger(__name...
import string, re from subprocess import Popen, PIPE enc_flag = 'JcOCLQgPJEjwNAZHgVFzAoMVHOiCRVAVKkvFidUvzmUSSnqJzO' flag = [] pat = re.compile('Flag: (\w+)\n') candidates = string.ascii_lowercase+string.ascii_uppercase+string.digits+'_'+'-' for k in range(len(enc_flag)): for c in candidates: with open('f...
#! /usr/bin/env python DESCRIPTION = "Intensive Care Unit (ICU) Simulation" LONG_DESCRIPTION = """\ ICUSIM simplifies the process of simulating ICU burden scenarios based on rich set of input variables. """ DISTNAME = 'ICUSIM' MAINTAINER = 'Mikko Kotila' MAINTAINER_EMAIL = 'mailme@mikkokotila.com' URL = 'http://auton...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from .. import _utilitie...
from __future__ import print_function import Pyro4 import sys import time if sys.version_info<(3,0): input=raw_input host=input("enter the hostname of the itunescontroller: ") itunes=Pyro4.Proxy("PYRO:itunescontroller@{0}:39001".format(host)) print("setting Playlist 'Music'...") itunes.playlist("Music") itunes.play...
import abc class InstallationStrategy( abc.ABC ): @classmethod @abc.abstractmethod def execute(cls): """ abstract method definingthe rules for the installation bla bvla """ class DmgInstallationStrategy( InstallationStrategy ): @classmethod def execute(cls): """ abstract method d...
revision = '4160ccb58402' down_revision = None branch_labels = None depends_on = None import json import os from alembic import op import sqlalchemy as sa from sqlalchemy.sql import table, column sections = { 'update_authorized_keys': 'local', 'authorized_keys_file': 'local', 'githome_executable': 'loca...
# Copyright 2017 reinforce.io. 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 law or...
import pyglet from pyglet.window import key import cocos from cocos import actions, layer, sprite, scene from cocos.director import director import cocos.euclid as eu import cocos.collision_model as cm import math import paho.mqtt.client as mqtt import json MAP_SIZE = (600, 600) VELOCITY_MAX = 400 VELOCITY_INERTIA = ...
""" Problem: The function even_squares takes in a number. If the number is: * even - print out the number squared * odd - print out the number Tests: >>> even_squares(20) 400 >>> even_squares(9) 9 >>> even_squares(8) 64 >>> even_squares(73) 73 """ # Use this to test your ...
from ytree.frontends.treefarm import \ TreeFarmArbor from ytree.utilities.testing import \ ArborTest, \ TempDirTest class TreeFarmArborDescendentsTest(TempDirTest, ArborTest): arbor_type = TreeFarmArbor test_filename = "tree_farm/tree_farm_descendents/fof_subhalo_tab_000.0.h5" num_data_files = ...
# -*- encoding: utf-8 -*- import argparse import logging import multiprocessing from math import floor import django from django.core.management import BaseCommand import miniblog from bpp.util import partition_count, disable_multithreading_by_monkeypatching_pool from import_dbf.models import B_A, Bib from import_dbf...
#!/usr/bin/env python # Copyright Contributors to the Open Shading Language project. # SPDX-License-Identifier: BSD-3-Clause # https://github.com/AcademySoftwareFoundation/OpenShadingLanguage # max(float,float) includes masking command += testshade("-t 1 -g 64 64 -od uint8 -o Cout out_max_u_float_u_float.tif test_max...
from collections import Counter def solve(input): twos = 0 threes = 0 for line in input: c = Counter(line) has2 = False has3 = False for k, v in c.items(): if not has2 and v == 2: twos += 1 has2 = True elif not has3 an...
from euler import * n = 144 while True: a = n * ( 2 * n - 1) if check_penta(a) and check_triangle(a) == True: print(a) break else: n += 1
import numpy as np from sklearn.linear_model import LogisticRegression from sklearn.model_selection import GridSearchCV from sklearn.multiclass import OneVsRestClassifier from sklearn import metrics import random import tensorflow as tf from tensorflow.keras.layers import Conv2D, Flatten, Dense, Activation import torch...
import functools import os.path as osp import numpy as np import rlf.rl.utils as rutils import torch from rlf.algos.base_net_algo import BaseNetAlgo from rlf.il.transition_dataset import TransitionDataset from rlf.rl import utils class ExperienceGenerator(object): def init(self, policy, args, exp_gen_num_trans):...
#!/usr/bin/env python # -*- coding: utf-8 -*- import cv2 # ArUcoใฎใƒฉใ‚คใƒ–ใƒฉใƒชใ‚’ๅฐŽๅ…ฅ aruco = cv2.aruco # 4x4ใฎใƒžใƒผใ‚ซใƒผ๏ผŒID็•ชๅทใฏ50ใพใงใฎ่พžๆ›ธใ‚’ไฝฟใ† dictionary = aruco.getPredefinedDictionary(aruco.DICT_4X4_50) def main(): # 10ๆžšใฎใƒžใƒผใ‚ซใƒผใ‚’ไฝœใ‚‹ใŸใ‚ใซ10ๅ›ž็นฐใ‚Š่ฟ”ใ™ for i in range(10): ar_image = aruco.drawMarker(dictionary, i, 150) # i: ID็•ชๅท๏ผŒ150x1...
""" Abstract asyncio synchronization primitive """ from __future__ import annotations from abc import ABC class SyncPrimitive(ABC): """ Abstract asyncio synchronization primitive """ def __init__(self, key: str): """ :param key: key """ self.key = key
import cv2 import time import numpy as np cap=cv2.VideoCapture(0) time.sleep(3) background=0 for i in range(60): capture,background=cap.read() background = np.flip(background,axis=1) ## Read every frame from the webcam, until the camera is open while(cap.isOpened()): res,img=cap.read() ...
"""This is a dummy module for the reflection test.""" from .reflection_test import ImportedClass # pylint: disable=unused-import class DuplicateClass: # pylint: disable=missing-docstring pass
import os # be careful with this one def disable_fan_control(): cmd="""ssh root@shm-smrf-sp01 \"clia setfanpolicy 20 4 disable; clia setfanpolicy 20 3 disable\"""" os.system(cmd) def enable_fan_control(): cmd="""ssh root@shm-smrf-sp01 \"clia setfanpolicy 20 4 enable; clia setfanpolicy 20 3 enable\"""" ...
import streamlit as st # from stqdm import stqdm import io from PIL import Image import requests import time import logging import json import os from requests_toolbelt.multipart.encoder import MultipartEncoder backend = "http://fastapi:8000" def detect_image(data, server): m = MultipartEncoder(fields={"file":...
class Solution: def sortedSquares(self, A: 'List[int]') -> 'List[int]': B = [] for elem in A: B.append(elem * elem) B.sort() return B
from kendo_base import KendoComponent # test urls get_list = 'http://127.0.0.1:3000/posts/' class DataSource(KendoComponent): ''' http://docs.telerik.com/kendo-ui/api/javascript/ui/datepicker#fields-options ''' _k_cls = kendo.data.DataSource data = None transport = None _functions = ['read...
from kaneda import Metrics from . import mark_benchmark @mark_benchmark class TestBenchmarksBackends(object): def test_benchmark_elasticsearch(self, elasticsearch_backend, benchmark): metrics = Metrics(backend=elasticsearch_backend) benchmark(metrics.gauge, 'benchmark_elasticsearch', 1) def...
from .client import Method, Request, HTTPClient from .gateway import GatewayKeepAlive, Gateway, GatewayEvent from .events import * from .session import Session from .bot import Bot from .exceptions import ClosedSocketException from .structs.user import Relationship, Presence, Status, BotUser, User from .structs.channel...
# -*- coding: utf-8 -*- # @Author: JanKinCai # @Date: 2019-12-24 12:55:30 # @Last Modified by: JanKinCai # @Last Modified time: 2020-01-06 22:41:34 from interact.when import When test_items = { "a": True, "b": "ssss", "c": 22, "d": { "dd": 23 }, } def test_true(): """ Test wh...
# Colors yellow = (255, 255, 0) red = (255, 0, 0) blue = (0, 0, 255) white = (255, 255, 255) black = (0, 0, 0) green = (0,255,0)
import sys import os.path def main(files): nfiles = len(files) if nfiles < 2: sys.exit("Usage: %s file1 file2 ... " % sys.argv[0]) # Check files for filename in files: if( os.path.isfile(filename) == False ): sys.exit("File %s not found" % filename) # read files n = 0 ...
### TUPLE print("\n\n### TUPLE") x = (1,2,"Three",4) print(x) x = 1,2,"Three",4 print(x) # Index x = (1,2,"Three",4) print(x[1]) print(x[1:-1]) # Mutate Tuple? x = (1,2) print(x*4) y = ("Three",4) print(x+y) print(x+y) print(1 in x) for i in x: print(i) # Following will not work # del x[1] # ...
import optuna import pandas as pd from lightgbm import LGBMClassifier from sklearn.ensemble import RandomForestClassifier from xgboost import XGBClassifier from zenml.logger import get_logger logging = get_logger(__name__) class Hyperparameter_Optimization: """ Class for doing hyperparameter optimization. ...
from __future__ import division import cv2 import matplotlib.pyplot as plt import numpy as np from scipy import ndimage # calculate the scale that should be aplied to make the image # fit into the window def display_image(window_name, image): screen_res = 720, 480 scale_width = screen_res[0] / image.shape[1]...
import fv3gfs.wrapper # May need to run 'ulimit -s unlimited' before running this example # If you're running in our prepared docker container, you definitely need to do this # sets the stack size to unlimited # Run using mpirun -n 6 python3 basic_model.py # mpirun flags that may be useful if using openmpi rather tha...
from datetime import datetime # PLAYER ID ALIASES FAZY_ID = 67712324 GRUMPY_ID = 100117588 KESKOO_ID = 119653426 SHIFTY_ID = 171566175 WARELIC_ID = 211310297 class DotaPatch: def __init__(self, name, release_time): self.name = name self.release_time = release_time def __str__(self): ...
# -*- coding: utf-8 -*- """Login middleware.""" from django.contrib.auth import authenticate from django.middleware.csrf import get_token as get_csrf_token from account.accounts import Account class LoginMiddleware(object): """Login middleware.""" def process_view(self, request, view, args, kwargs): ...
def for_closed_bracket(): for row in range(5): for col in range(5): if col==3 or col==2 and(row==0 or row==4): print("*",end=" ") else: print(" ",end=" ") print() def while_closed_bracket(): row=0 while row<5: col=0 ...
import pytest from aries_cloudcontroller import ( AcaPyClient, CredentialsApi, IssueCredentialV10Api, IssueCredentialV20Api, LedgerApi, PresentProofV10Api, PresentProofV20Api, WalletApi, ) from mockito import mock from app.tests.util.client_fixtures import ( member_admin_acapy_clien...
from typing import Any from utils.dp.observer import ConcreteSubject class AppStatus(dict, ConcreteSubject): def __init__(self, **kwargs: Any) -> None: super().__init__(**kwargs) def setv(self, name, value): name_parts = list(name.split(".")) obj = self for name_part in name_...
#!/usr/bin/python2.5 # Copyright (C) 2009 Google 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 applicable la...
# vim: set fenc=utf8 ts=4 sw=4 et : import xml.sax import functools from .autovivification import AutoVivification from .utils import autoconvert, call_plugin from .conf import Conf from .flow import Flow from .logging import * class PdmlHandler(xml.sax.ContentHandler): def __init__(self): self.__frame =...
from RivetDetect import RivetDetect import threading import numpy as np import cv2 import time # 3๊ฐœ์˜ ์นด๋ฉ”๋ผ๋ฅผ ๋ฉ€ํ‹ฐ์Šค๋ ˆ๋“œ๋กœ ๋™์‹œ์— ์‹คํ–‰ def camera1(): RivetDetect.execute(0) def camera2(): RivetDetect.execute(1) def camera3(): RivetDetect.execute(2) # ์Šค๋ ˆ๋“œ๋ฅผ ์‹คํ–‰ํ•˜๊ธฐ ์œ„ํ•ด ๊ฐ์ฒด(t1, t2, t3)๋ฅผ ํ• ๋‹นํ•˜๊ณ  ์ธ์ž๋ฅผ ๋Œ€์ž…ํ•จ(์ธ์ž ์—†์Œ) # target = ํ•จ์ˆ˜์ด๋ฆ„, args...
import smart_imports smart_imports.all() class MatchmakerClient(tt_api_matchmaker.Client): def protobuf_to_battle_request(self, pb_battle_request): return objects.BattleRequest(id=pb_battle_request.id, initiator_id=pb_battle_request.initiator_id, ...
""" main runner for all sims Args: - type of sim - num points in sim - save name - other parameters? """ #main packages import argparse import numpy as np import os #special packages import model_runner as mr #Read in supplied arguments. parser = argparse.ArgumentParser(description="Run a single vas...
#!/usr/bin/env python __author__ = "Richard Clubb" __copyrights__ = "Copyright 2018, the python-uds project" __credits__ = ["Richard Clubb"] __license__ = "MIT" __maintainer__ = "Richard Clubb" __email__ = "richard.clubb@embeduk.com" __status__ = "Development" from uds.uds_config_tool import DecodeFunctions import ...
# -*- coding: utf-8 -*- ## @file testsuite/python/thresholdTest.py ## @date jan. 2017 ## @author PhRG - opticalp.fr ## ## Test the threshold img proc modules # # Copyright (c) 2017 Ph. Renaud-Goud / Opticalp # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and as...
"""Created by sgoswami on 9/1/17.""" """Given a binary tree struct TreeLinkNode { TreeLinkNode *left; TreeLinkNode *right; TreeLinkNode *next; } Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL. Initially, all ...