content
stringlengths
5
1.05M
from singa_auto import Client # client = Client(admin_host='panda.d2.comp.nus.edu.sg', admin_port=3000) client = Client(admin_host='ncrs.d2.comp.nus.edu.sg', admin_port=3000) # client = Client(admin_host='localhost', admin_port=3000) client.login(email='superadmin@singaauto', password='singa_auto') print(client._use...
from dataclasses import dataclass @dataclass class Weakness: type: str value: str
class Solution(object): def validate(self, num, x, y): s = str(x + y) if num.startswith(s): n = len(s) if len(num) == n: return True return self.validate(num[n:], y, x + y) return False def isAdditiveNumber(self, num): """ ...
__source__ = 'https://leetcode.com/problems/unique-email-addresses/' # Time: O() # Space: O() # # Description: Leetcode # 929. Unique Email Addresses # # Every email consists of a local name and a domain name, separated by the @ sign. # # For example, in alice@leetcode.com, alice is the local name, and leetcode.com is...
from jnt.matching.synset_fetchers import BabelNet, SenseClusters from jnt.matching.matcher import Matcher BABELNET_KEY = "" # insert a BabelNet API key here (not required) ADAGRAM_BOW = "data/ddt-adagram-50.csv" # bow with Adagram nearest neighbours BABELNET_BOW = "data/babelnet-bow-5190.pkl" # wget http://panchen...
import logging from operator import itemgetter from anonlink._entitymatcher import ffi, lib import sys from . import bloommatcher as bm from . import util logging.basicConfig(level=logging.WARNING) def python_filter_similarity(filters1, filters2): """Pure python method for determining Bloom Filter similarity ...
# -*- coding: utf-8 -*- #!/usr/bin/env python ## last modified by Robert Liu at 6/27/2019 ## This script is used to merge DMstack output src files from two neighboring patches. And remove overlapped objects. ## Two neighbor patches have an overlap, where a same object has DIFFERENT ID in two patches. So, we need to mat...
"""Initialize mister package.""" from .mister import * # noqa: F401,F403
import io import re from setuptools import setup with io.open("README.md", "rt", encoding="utf8") as f: readme = f.read() with io.open("tefaswrapper/__init__.py", "rt", encoding="utf8") as f: version = re.search(r'__version__ = "(.*?)"', f.read()).group(1) setup( name="tefas-wrapper", version=versio...
from baby_steps import given, then, when from district42 import schema from pytest import raises from revolt import substitute from revolt.errors import SubstitutionError def test_dict_relaxed_no_keys_substitution(): with given: sch = schema.dict({...: ...}) with when: res = substitute(sch, ...
# Copyright 2022 Huawei Technologies Co., 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 or agreed to...
class TargetType(object): name = "" class Touch(TargetType): name = "Touch" class AreaOfEffect(TargetType): name = "Area Of Effect" def __init__(self, shape, radius): self.shape = shape self.radius = radius class Room(TargetType): name = "Room"
# Generated by Django 3.1.3 on 2020-11-21 20:02 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('Instagram', '0007_auto_20201121_1235'), ] operations = [ migrations.CreateModel( name='Comment'...
from pytest import raises from qsck import deserialize def test_deserialize_is_a_function(): assert hasattr(deserialize, '__call__') def test_it_returns_a_3tuple_with_identifier_timestamp_and_pairs_list(): qs_row = 'LOG,1546902289,_model=LG-M327' identifier, timestamp, key_value_pairs = deserialize(qs...
# -*- coding: utf-8 -*- """Effect with a pre-defied K kernel similiarity matrix.""" from sklearn.gaussian_process.kernels import Kernel from .effect_base import EffectBase from copy import deepcopy import numpy as np class EffectKernel(EffectBase): """ Kernel similarity effect. If active parameter is...
import os import json import sys import csv import time projectPath = os.path.normpath(os.getcwd() + os.sep + os.pardir) sys.path.append(projectPath) import ots import threading from concurrent.futures import ThreadPoolExecutor urlList = dict() finalData = dict() totalProcessed = 0 processLap = 0 class allUniver...
"""Vera tests.""" from unittest.mock import MagicMock import pyvera as pv from homeassistant.components.climate.const import ( FAN_AUTO, FAN_ON, HVAC_MODE_COOL, HVAC_MODE_HEAT, HVAC_MODE_HEAT_COOL, HVAC_MODE_OFF, ) from homeassistant.core import HomeAssistant from .common import ComponentFact...
from hamcrest import assert_that, is_ from igd import proto def describe_parse_port_mapping(): def it_extracts_fields_from_xml_response(): xml_resp = b""" <?xml version="1.0"?> <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" SOAP-ENV:encodingStyle="http://sch...
"""Bunch of small functions doing for useful stuff for flmake""" import re import sys import os import string import glob import socket import re import time import shutil import subprocess import tempfile # relative imports needed from .. import _metadata, FLASH_SRC_DIR, FLASH_CLEAN_SRC_DIR from ..utils import strip_...
from model import Maze, Cell from settings import * import multiprocessing as mp import pickle import random import time import sys import os def genMaze(maze): running = True while running: if len(maze.q)==0: break maze.genPath() with open(os.path.join(OUTPUT_DIR, f'maze_{maz...
import requests import pymongo import pandas as pd # key: fe53f97e class ImdbToMongoDB: def __init__(self, key): self.url = "http://www.omdbapi.com/?apikey=" + key + "&i=" self.client = pymongo.MongoClient("mongodb+srv://jack:jackmongodb@cluster0-uagde.mongodb.net") def readMovieFile(self, n...
# Let's be a little defensive/assertive and be sure there aren't any lower-case comments. assert not dta.violations.str.contains("comments").any() dta["comments"] = dta.violations.str.extract("(?<=Comments:)(.+)", expand=False) has_comments = dta.comments.notnull() X tfidf_vect = TfidfVectorizer( stop_words='e...
from slab_nlp.topic_bert import BertTopicSLab if __name__ == '__main__': docs = open(r'C:\Document\中共嘉兴\text.txt', encoding='UTF-8').readlines() model = BertTopicSLab('中共BERT', docs) # model.hierarchical_model() model.model() model.hierarchical_model() # model.hierarchical_compare(20, 30)
import os import sys import math import random import time from code.render.glfunctions import set_video_mode from code.menu.menu import Menu from code.controllers.intervalcontroller import IntervalController from code.tools.eventqueue import EventQueue from code.tools.xml import XMLParser from code.game.univers...
from web3 import Web3 from scripts.helpful_scripts import get_account from brownie import SimpleContract def deploy_and_create_blog(): account = get_account() simple_contract = SimpleContract.deploy({"from":account}) tx = simple_contract.changeYourNumber(61,{"from":account}) tx.wait(1) print(simple...
import numpy as np from matplotlib import pyplot as plt import torch from sklearn.svm import SVC from scipy import ndimage from scipy.interpolate import Rbf from tqdm import tqdm from time import time from . import kernel from .Obstacles import Obstacle class CollisionChecker(): def __init__(self, obstacles): ...
# -*- coding: utf-8 -*- """ Created on Tue Mar 16 10:06:17 2021 @author: Andreas Traut Problem: Assume, that we have a weighted, directed graph with a source (origin) and further nodes. Each path from one node to another node has a weight (the time-delay). The quesion is: if a signal is starting from the source ...
import logging from django.conf import settings from mkt.comm import utils_mail from mkt.constants import comm from mkt.extensions.models import Extension from mkt.users.models import UserProfile from mkt.site.storage_utils import private_storage from mkt.webapps.models import Webapp log = logging.getLogger('z.comm...
""" Code for creating the primary Flask app used by Fakebook """ from .views import add_routes, add_socketio_handlers from .settings import settings from .chat import handle_message from flask import Flask from flask_socketio import SocketIO def create_app(name): app = Flask( name, template_folde...
"""Implement Buffer type as a base class to HeavyDB Array and Column types. HeavyDB Buffer represents the following structure: template<typename T> struct Buffer { T* ptr; size_t sz; ... } that is, a structure that has at least two members where the first is a pointer to some data type and the seco...
#!/usr/bin/env python """ A collectd-python plugin for obtaining metrics from a running PgPoolII instance. """ import sys from util import CollectdPlugin from subprocess import check_output class PgPool(CollectdPlugin): """ Main plugin class """ def __init__(self, debug=False): super(PgPool, s...
#MIT License #Copyright (c) 2019 Paul Harwood #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, merge, publish...
''' Created on 27.12.2010 @author: felicitus @warning This is my first python program ever. Feel free to fix, blame or burn. ''' import usb.core import usb.util import array import random import sys import time import binascii # find our device dev = usb.core.find(idVendor=0x1235, idProduct=0x000a) # was it found? ...
from PyQt5 import QtWidgets, QtCore, QtGui from typing import Union class PolyMorphicFilterProxyModel(QtCore.QSortFilterProxyModel): """ Polymorphic Filter Proxy Model Used to filter based on SQLAlchemy types """ def __init__(self, filterClasses:set=None): super().__init__() if filte...
from plotly.graph_objs import Bar, Layout from plotly import offline from die import Die # Create three D6 die_1 = Die() die_2 = Die() die_3 = Die() # Roll die many times and store the result in the list results = [] for roll_num in range(1_000_000): result = die_1.roll() + die_2.roll() + die_3.roll() result...
# -*- coding: utf-8 -*- """Swapnil Tamrakar Lab 5.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1PQqRpMYqhrdrMVmLmH3qDD4bRzJCeOT4 #### Copyright 2017 Google LLC. """ # Licensed under the Apache License, Version 2.0 (the "License"); # you may n...
import os from configparser import ConfigParser class SimulatorConfig : config_path = None def __init__(self, sim_args): config_parser = self.get_config_parser(sim_args.config) ## start parsing self.parse_general_section(config_parser) if self.family == "LDPC": ...
""" Dataframe optimizations """ import operator import numpy as np from .. import config, core from ..blockwise import Blockwise, fuse_roots, optimize_blockwise from ..highlevelgraph import HighLevelGraph from ..optimization import cull, fuse from ..utils import ensure_dict def optimize(dsk, keys, **kwargs): if...
import unittest import numpy as np from numpy.testing import assert_equal from openmdao.utils.indexer import indexer class IndexerTestCase(unittest.TestCase): def test_int(self): ind = indexer[4] src = np.arange(10) assert_equal(ind(), 4) assert_equal(ind.as_array(), np.array([4...
"""compressor.lib High-level functions exposed as a library, that can be imported. """ from compressor.char_node import CharNode # pylint: disable=unused-import from compressor.core import (create_tree_code, parse_tree_code, process_frequencies) from compressor.core import retrieve_compr...
""" Process StackOverflow data. Some data points in this CV are specific, hence they are currently not automated (or are hard to do like top N% this year). Some statistics will probably be changed in the future. """ import sys import loguru import utils def reached(text): """Return how many people got reach...
import os from django.contrib.gis.utils import LayerMapping from .models import outpointMD outpointmd_mapping = { '경도' : '경도', '위도' : '위도', '이름' : '이름', 'geom' : 'POINT', } outpointMD_shp = os.path.abspath(os.path.join(os.path.dirname(__file__), 'data', '무등산 표주매설위치.shp'),) def run(verbose=True): l...
from __future__ import absolute_import import torch import torch.nn as nn import torchvision.models.vgg as refvgg import torch.hub as hub from torchvision.models import vgg16 from torchvision.ops import RoIPool from model.region_proposal_network import RegionProposalNetwork from model.faster_rcnn import FasterRCNN fro...
from rest_framework import serializers from .models import Menu class MenuSerializer(serializers.ModelSerializer): """ 前端视图菜单序列化类 """ class Meta: model = Menu fields = ("id", "path", "icon", "title", "show", "parent")
import cv2 import numpy as np import os import h5py from sklearn.preprocessing import LabelEncoder from sklearn.preprocessing import MinMaxScaler from sklearn.model_selection import train_test_split, cross_val_score from sklearn.ensemble import RandomForestClassifier from sklearn.decomposition import PCA as skPCA impo...
from __future__ import print_function import tensorflow as tf import numpy as np def test_blas(): with tf.Graph().as_default(): with tf.Session(config=tf.ConfigProto(log_device_placement=False)) as sess: with tf.device('/gpu:0'): tf_a = tf.placeholder(tf.float32, [None, None],...
import numpy as np import matplotlib.pyplot as plt input_data = np.array([1, 2, 3]) target = 0 weights = np.array([0, 2, 1]) updateNum = 20 mse_hist = [] def get_error(inputd, actual_target, weight): predicts = (inputd * weight).sum() error = predicts - actual_target return error def get_slope(inputd, ...
# -*- coding: utf-8 -*- import pyfits from pylab import * import Marsh import numpy import scipy """ ---------------------------------------------------------------- The P Function. Returns an array with the P[i][j] coefficients, the modeled light fractions. -----------------------------------------------------------...
from unittest.mock import MagicMock import pytest from convtools import conversion as c from convtools.columns import ColumnDef, MetaColumns from convtools.contrib.tables import CloseFileIterator, Table def test_table_base_init(): list( Table.from_rows([(1, -2), (2, -3)], ["a", "b"]) .update(c=c...
def test_updates(test_client, init_database): ''' GIVEN an instance of LibrePatron WHEN the updates page is requested THEN check to make sure updates page is protected ''' response = test_client.get('/updates') assert response.status_code != 200
""" DogFaceNet Dataset retrieving for landmarks detection Licensed under the MIT License (see LICENSE for details) Written by Guillaume Mougeot """ import numpy as np import os import skimage as sk import pandas as pd from ast import literal_eval # string to dict import matplotlib.pyplot as plt from tqdm import tqdm ...
from django.test import TestCase from console_main.models import TrackUserPageVisits from console_main.views import track_page_visit from django.db.models import F class BasicModelTest(TestCase): def setUp(self) -> None: self.did = 'modeltestDID' TrackUserPageVisits.objects.create(did=self.did, na...
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html import logging import os import sys from datetime import datetime # -- Path setup ----...
from .object_behavior import ObjectBehavior from .mocking_decorator import mock, mock_internal
""" Select features for the machine learning model """ import pandas as pd import numpy as np from util import log from sklearn.feature_selection import SelectPercentile from sklearn.feature_selection import SelectFromModel from sklearn.feature_selection import SelectFpr from sklearn.feature_selection import SelectFd...
import itertools import logging import base64 from collections import defaultdict, deque from functools import reduce from operator import mul from sqlalchemy.dialects import postgresql from raco import algebra, expression, rules, scheme from raco import types from raco.algebra import Shuffle from raco.algebra import...
import os import subprocess import tempfile import nbformat _TEST_DIR = os.path.abspath( os.path.join(os.path.dirname(__file__), "..", "notebooks") ) _EXCLUDE = [] def all_notebooks(path="."): notebooks = [] for root, _, files in os.walk(path): if ".ipynb_checkpoints" not in root: fo...
# Crie um programa que leia quanto dinheiro uma pessoa tem na carteira e mostre quantos Dólares ela podera comprar. # Considere: US$1.00 = R$3.27 real = float(input('Insira a quantidade de dinheiro R$ que você possui: R$')) dolar = real / 3.27 euro = real / 4.63 iene = real / 0.03866 print('Com {:.2f}R$ você pode comp...
# -*- coding: utf-8 -*- # Copyright (c) 2017, Softbank Robotics Europe # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, t...
"""Support for Symbology Identifiers. Symbology Identifiers is a standardized way to identify what type of barcode symbology was used to encode the following data. The Symbology Identifiers are a few extra characters that may be prefixed to the scanned data by the barcode scanning hardware. The software interpreting ...
# Copyright 2014: Mirantis Inc. # 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 b...
from typing import List, Dict import numpy as np import pandas as pd import joblib import seaborn as sns import matplotlib.pyplot as plt from matplotlib.gridspec import GridSpec from goatools.goea.go_enrichment_ns import GOEnrichmentStudyNS import larval_gonad.plotting from larval_gonad.gene_ontology import ( run...
import os from archives.scopeV2.datasets import LeftRightDataset import pytest @pytest.mark.dataset def test_dataset_creation(): ds = LeftRightDataset(os.environ.get('DATA_PATH'), os.environ.get('LABEL_PATH'), validation_size=0, neg_to_pos_ratio=1) @pytest.mark.dataset def test_dataset...
#! /usr/bin/env python import math, numpy import lhapdf import matplotlib.pyplot as plt q = math.sqrt(6400.0) pdfsets = ["cteq6ll.LHpdf"] #pdfsets = ["cteq6ll.LHpdf", "MRST2001lo.LHgrid", "MRST2007lomod.LHgrid", "MRSTMCal.LHgrid"] partons = { 0 : "gluon", 2 : "up" } NPOINTS = 1000 xs = numpy.logspace(-4, -0.001, NPO...
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * from alipay.aop.api.domain.BuyerInfo import BuyerInfo from alipay.aop.api.domain.HomeNormalApiContent import HomeNormalApiContent class AlipayIserviceItaskMerchantRecordSyncModel(object): def __init__(...
# Generated by Django 3.1.2 on 2021-06-10 10:04 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('user', '0012_emailtoken'), ] operations = [ migrations.AddField( model_name='user', name='active', field...
from sklearn.metrics import jaccard_score import numpy as np a1 = np.array([[1, 0], [1, 1]]) a2 = np.array([[0, 1], [1, 0]]) js_samples = jaccard_score(a1, a2, average='samples') js_weighted = jaccard_score(a1, a2, average='weighted') def jaccard_score_manual(y_true, y_pred): # C...
# -*- coding: utf-8 -*- import os import time from itertools import product from collections import namedtuple, OrderedDict import torch import torchvision from torch.utils.tensorboard import SummaryWriter class RunBuilder: @staticmethod def get_runs(params): Run = namedtuple('Run', params.keys()) ...
#!/usr/bin/python3 ''' Translate input text with trained model. ''' import sys import os sys.path.append('./t2t/') sys.path.append('../') import torch import argparse import dill as pickle from tqdm import tqdm import transformer.Constants as Constants from torchtext.data import Dataset from transformer.Models impor...
from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive gauth = GoogleAuth() gauth.LocalWebserverAuth() #drive = GoogleDrive(gauth)
import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatable import numpy as np import sys import os.path #from CelestePy import gen_model_image def add_colorbar_to_axis(ax, cim): """ generic helper function to throw a colorbar onto an axis """ divider = make_axes_locatable(ax) c...
''' Created on Mar 5, 2014 Copyright 2014-2015 Dario Bonino 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 ...
from ..helpers import enums, vars class UploadTypes(enums.MetaEnum): """Enum: photo, audio, video, file""" photo = vars.Var() audio = vars.Var() video = vars.Var() file = vars.Var()
# # Batchcode script # # # The Batch-code processor accepts full python modules (e.g. "batch.py") that # looks identical to normal Python files with a few exceptions that allows them # to the executed in blocks. This way of working assures a sequential execution # of the file and allows for features like stepping from ...
#!/usr/bin/env python3 # Copyright (c) Meta Platforms, Inc. and affiliates. # 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. """ Trainer App Example ============================================= This is an exampl...
# Copyright (c) 2019 PaddlePaddle 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 app...
from files import * from loaders import * import time import gc import json from test_check import check_for_test_entry class OrthoLoader: @staticmethod def get_data(mod_name, test_set, gene_master_dict): path = "tmp" filename = None filename_comp = None if test_set == True: ...
""" liquidLRU by Seung ------------------- Just a simple cache. """ from threading import Timer from time import time """ This class is the object we use to store the values inside the cache. It contains when the item expires, let's us refresh it. """ class Node: def __init__(self, value, ...
# Copyright (c) 2017, Apple Inc. All rights reserved. # # Use of this source code is governed by a BSD-3-clause license that can be # found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause import itertools import pandas as pd import os import unittest from coremltools._deps import HAS_SKLEAR...
import FWCore.ParameterSet.Config as cms # reco hit production from RecoCTPPS.TotemRPLocal.ctppsDiamondRecHits_cfi import ctppsDiamondRecHits # local track fitting from RecoCTPPS.TotemRPLocal.ctppsDiamondLocalTracks_cfi import ctppsDiamondLocalTracks ctppsDiamondLocalReconstructionTask = cms.Task( ctppsDiamondRe...
import os from pathlib import Path import pandas as pd import numpy as np from lib import parser from lib import TurnId, ActionId if not os.path.isdir('tidy_data'): os.mkdir('tidy_data') import_from = Path.cwd() / 'parsed_data' export = Path.cwd() / 'tidy_data' varnames = { 'actions': 'playeraction', 'bu...
def GCD(a, b): if b == 0: return a a1 = a % b return GCD(b, a1) a, b = list(map(int, input().split())) if b > a: a, b = b, a print(GCD(a, b))
#!/usr/bin/env python3 ''' hook for usage in pyinstaller ''' #pylint: disable=invalid-name from PyInstaller.utils.hooks import collect_submodules hiddenimports = collect_submodules('nowplaying.inputs')
# MIT License # # Copyright (c) 2017 Anders S. Christensen, Kristof T. Schutt, Stefan Chmiela # # 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 limitati...
# -*- coding: utf-8 -*- '''Chemical Engineering Design Library (ChEDL). Utilities for process modeling. Copyright (C) 2017, Caleb Bell <Caleb.Andrew.Bell@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal...
# Released under the MIT License. See LICENSE for details. # """Implements the main menu window.""" # pylint: disable=too-many-lines from __future__ import annotations from typing import TYPE_CHECKING import ba import _ba if TYPE_CHECKING: from typing import Any, Callable, Optional, Union class MainMenuWindow...
import re import socket import uuid email_regex = r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)" url_regex = (f"http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F]" f"[0-9a-fA-F]))+") email_pattern = re.compile(email_regex) url_pattern = re.compile(url_regex) def _regex_match(regex, ...
sal_info= dict () sal_info={'Austin':911985, 'Dallas': 89999, 'San Jose': 100989, 'Atlanta': 89286,'Portland':101367} #reassigns the salary for Atlanta sal_info['Atlanta']= 92340 print (sal_info) #del sal_info['Atlanta'] #print (sal_info) #print (sal_info['Atlanta']) #del sal_info #sal_info.clear() #p...
import kfp.components as comp def download_dataset(dataset_url, dataset_path: comp.OutputPath(str)): import os import tempfile import zipfile import requests os.makedirs(dataset_path + "/data", exist_ok=True) r = requests.get(dataset_url, stream=True) with tempfile.TemporaryFile() as tf:...
# Copyright (c) 2018 PaddlePaddle 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 app...
# coding=utf-8 import logging from odoo import models, fields, api from ..controllers import client from odoo.http import request from odoo.exceptions import ValidationError, UserError from ..rpc import corp_client _logger = logging.getLogger(__name__) class wx_corpuser(models.Model): _name = 'wx.corpuser' ...
import sys import json import os import io import re from logicUtils import parseFunctions def buildGate(sLogic, n=0, gateI=0): g = '' be = '' c = '' w = '' gn = '' gi = gateI s = '' i = n rg = [] bes = [] while True: c = sLogic[i:i+1] if (c == '('): ...
# Only runs code if pin 14 (D5) is high (i.e, not grounded) # Ground this pin to abort code tht will deepsleep from machine import Pin from sys import exit def sleep_check(): allow_sleep = Pin(14, Pin.IN, Pin.PULL_UP) if not allow_sleep.value(): exit()
#!/usr/bin/env python """ This module has a function that matches django fields to the corresponding random value generator. """ import base64 from django.conf import settings from django.core.files.base import ContentFile from django.db.models.fields import BigIntegerField from django.db.models.fields import BinaryFie...
from .base_mopo import mopo_params, deepcopy params = deepcopy(mopo_params) params.update({ 'domain': 'CartpoleStabilization', 'task': 'v1', 'exp_name': 'cartpole_stabilization' }) params['kwargs'].update({ 'pool_load_path': 'gym/CartpoleStabilization-v1', 'pool_load_max_size': 101000, 'rollout...
from bidict import bidict import ujson as json import time import pickle from itertools import zip_longest import datetime from collections import namedtuple, defaultdict import graph_tool import graph_tool.search from graph_tool import GraphView from typing import Iterator GlobeCoordinate = namedtuple( "GlobeCoor...
#!/usr/bin/env python """ utils/prep_ml.py Data available at: http://files.grouplens.org/datasets/movielens/ml-10m.zip """ import sys import argparse import numpy as np import pandas as pd from sklearn.model_selection import train_test_split def parse_args(): parser = argparse.ArgumentParser() p...
import matplotlib.pyplot as plt import numpy as np from mpl_toolkits.mplot3d import Axes3D import h5py import sys from lib.constants import * def plot(fig, trajectory, sensor_height): # Filter out everything above block (start of trajectory) traj_inside = trajectory[trajectory[:, 2] < sensor_height] ax =...
expected_output = { "rp": { "0": { "control_processer": { "critical_perc": 85, "dram": { "critical_perc": 95, "max_mb": 3863, "state": "H", "usage_mb": 3084, "usage...
import math class Adder(object): def add(self, x, y): # a line -- # another line # a third line return x + y def multiply(self, x, y): return x * y