text
stringlengths
2
999k
import sys # Has a write() method you can use, nothing else. LOG = sys.stderr
# coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. import platform import re import unittest import warnings import random import sys from pymatgen import SETTINGS, __version__ as pmg_version from pymatgen.ext.matproj import MPRester, MPRestError, TaskType from ...
# coding: utf-8 """ MgmtClientRecordDeleteDescriptor.py The Clear BSD License Copyright (c) – 2016, NetApp, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted (subject to the limitations in the disclaimer below) provided that the following con...
# Copyright 2016 VMware 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 by a...
import os import numpy as np import pickle import xml.etree.ElementTree as ET import time import sys import torch from torch.autograd import Variable import data from . import helpers def eval(test_dataset, args, net, al_iteration, eval_ensemble_idx = 99999, epochs_test = False, train_iters = None, use_dataset_imag...
import ctypes as ct import sys import matplotlib.pyplot as plt import matplotlib.patches as patches import numpy as np import os # Setup for individual channels, these are default values class channel_setup: def __init__(self, channel): # Set channel self.channel = channel # Set bit correspon...
import re test_case = "penta(2,\ \ \ \ 3,4)\ tri(1,\ 2, 3)\ tri(2,3,4)line(7,8,9,10)\ ngon(2,3,4,5)hexa(1,2,3)penta(1,2,3)\ line(1,2,3,4)ngon(1,2,3)penta(7,8,9)hexa(7,8,9)" test_case2 = "hexa(1,2,3,4)hexa(1,2,3,4)" def changgetongon(input_str): input_str = re.sub(r'\s*','',input_str) nglist= re.findall(r'ngon\s*?\...
# # Copyright (C) 2018 The Android Open Source Project # Copyright (c) 2020 Samsung Electronics Co., Ltd. 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://w...
from collections import OrderedDict from torch import nn from torchvision.ops.feature_pyramid_network import FeaturePyramidNetwork, LastLevelMaxPool from torchvision.ops import misc as misc_nn_ops from .._utils import IntermediateLayerGetter from .. import resnet class BackboneWithFPN(nn.Sequential): """ Add...
import inspect from tornado import gen from tornado_json.constants import TORNADO_MAJOR def coroutine(func, replace_callback=True): """Tornado-JSON compatible wrapper for ``tornado.gen.coroutine`` Annotates original argspec.args of ``func`` as attribute ``__argspec_args`` """ # gen.coroutine in tor...
from collections import defaultdict import re from lk_utils import read_and_write from blueprint.typehint import * def main(file_i, file_o): """ Args: file_i: '../resources/no5_all_qml_widgets.json' see `no3_all_qml_widgets.py` file_o: '../resources/no6_all_pyml_widgets.json' ...
from django.test import TestCase, Client from django.contrib.auth import get_user_model from django.urls import reverse class AdminSiteTests(TestCase): def setUp(self): self.client = Client() self.admin_user = get_user_model().objects.create_superuser( email='admin@gmail.com', ...
import numpy as np def StationaryBootstrap(data: np.ndarray, m, sampleLength)-> np.ndarray: """ Returns a bootstraped sample of the time-series "data" of length "sampleLength. The algorithm used is stationary bootstrap from 1994 Politis & Romano. Args: data ... ndarray array....
# flake8: noqa # Except when otherwise stated (look at the beginning of each file) the # software and the documentation in this project are copyrighted by: # # Denis Bilenko and the contributors, http://www.gevent.org # # and licensed under the MIT license: # # Permission is hereby granted, free of charge, to any pers...
import subprocess if __name__ == '__main__': commbatch = "python ../StressTest.py --bw_factor=1.0 --lat_factor=1.0 --res_factor=1.0 --vnf_sharing=0.0 --vnf_sharing_same_sg=0.0 --shareable_sg_count=4 --batch_length=8 --request_seed=" for i in xrange(0,500): batched = commbatch + str(i) + " 2>> 8batched...
lista=[] while True: valor=int(input('Digite um numero: ')) if lista.count(valor) == 0: lista.append(valor) print('Valor adicionado com sucesso!') else: print('Valor duplicado, não será adicionado.') saida=str(input('Você deseja sair? [S/N]? ')).strip().upper() while saida !=...
#!/bin/env python # # Copyright 2008 # by # The Board of Trustees of the # Leland Stanford Junior University. # All rights reserved. # __facility__ = "Online" __abstract__ = "Cal conf...
# -*- coding: utf-8 -*- import unittest from copy import deepcopy from openregistry.lots.core.tests.base import snitch from openregistry.lots.bargain.tests.base import ( LotContentWebTest ) from openregistry.lots.core.tests.blanks.json_data import test_loki_item_data from openregistry.lots.bargain.tests.blanks.it...
"""Support for Homekit device discovery.""" from __future__ import annotations import asyncio from typing import Any import aiohomekit from aiohomekit.model import Accessory from aiohomekit.model.characteristics import ( Characteristic, CharacteristicPermissions, CharacteristicsTypes, ) from aiohomekit.mo...
import tensorflow as tf from filterflow.base import State from filterflow.resampling.differentiable.loss.regularized import SinkhornLoss from filterflow.resampling.differentiable.optimized import OptimizedPointCloud from filterflow.resampling.differentiable.optimizer.sgd import SGD from filterflow.resampling.standard....
# Generated by Django 2.1.9 on 2019-07-03 11:43 from django.db import migrations, models import wagtail.core.fields def copy_description_to_catalog_details(apps, schema_editor): """ Copy the existing page description to the new `catalog_details` field. """ CoursePage = apps.get_model("cms", "Cour...
# %matplotlib inline import os import numpy as np import pandas as pd import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt from sklearn.ensemble import RandomForestClassifier from keras.models import Sequential, Model from keras.layers import Dense, Input from keras import optimizers import keras...
from __future__ import print_function, division import numpy as np def linear_regression(data, weights, pattern1, pattern2): c1 = np.sum(data * pattern1 * weights, axis=1) c2 = np.sum(data * pattern2 * weights, axis=1) m11 = np.sum(pattern1 * pattern1 * weights) m12 = np.sum(pattern1 * pattern2 * we...
import pytest from pytest import raises import numpy as np import netket as nk from .. import common pytestmark = common.skipif_mpi SEED = 214748364 def _setup_system(): L = 3 hi = nk.hilbert.Spin(s=0.5) ** L ha = nk.operator.LocalOperator(hi) j_ops = [] for i in range(L): ha += (0.3...
# generated from catkin/cmake/template/pkg.context.pc.in CATKIN_PACKAGE_PREFIX = "" PROJECT_PKG_CONFIG_INCLUDE_DIRS = "".split(';') if "" != "" else [] PROJECT_CATKIN_DEPENDS = "".replace(';', ' ') PKG_CONFIG_LIBRARIES_WITH_PREFIX = "".split(';') if "" != "" else [] PROJECT_NAME = "grapebot_sim_launch" PROJECT_SPACE_DI...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'acq4/analysis/modules/Photostim/MapCtrlTemplate.ui' # # Created by: PyQt5 UI code generator 5.8.2 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Form(object): def setupUi(se...
"""Collection of generic functions""" import os from typing import List def split(path: str) -> List[str]: """ Split a path into all of its parts :param path: path to file or directory :return: parts of the path """ parts = [] head, tail = os.path.split(path) parts.append(tail) ...
# Copyright 1999-2021 Alibaba Group Holding 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 a...
# TurtleDrawing # Reading a text file line by line. # # Project: TurtleDrawing # By: Angelo Goduto # Email: angeloagoduto@lewisu.edu # # All rights reserved import turtle import math SPECIFICFILENAME = 'turtle-draw.txt' with open(input('Enter file name: '), 'rU') as input_file: print(input_file) turtleBoarder...
#!/usr/bin/python """ Looks through network state files to find the ports that both the most and fewest exits allow. If SCANALLPORTS, then every possible port is scanned for each relay, but only for the first consensus of each day. Otherwise, a common subset is scanned for all relays for every consensus. Status for ea...
import os import numpy as np import xml.etree.ElementTree as ET import torch from torch.utils.data import Dataset import cv2 from pycocotools.coco import COCO from utils.utils import * class VOCDataset(Dataset): """ COCO dataset class. """ def __init__(self, model_type, data_dir, nam...
import asyncio import os import subprocess import sys from pathlib import Path from typing import Optional from rolls.cmds.passphrase_funcs import get_current_passphrase from rolls.daemon.client import DaemonProxy, connect_to_daemon_and_validate from rolls.util.keychain import KeyringMaxUnlockAttempts from rolls.util...
import unittest from pywsitest import WSResponse, WSMessage class WSResponseTests(unittest.TestCase): # noqa: pylint - too-many-public-methods def test_create_ws_response(self): ws_response = WSResponse() self.assertDictEqual({}, ws_response.attributes) def test_with_attribute(self): ...
import os import logging from typing import ( List, Any, Dict, Union, Optional, Tuple, TypeVar, TYPE_CHECKING, ) import numpy as np if TYPE_CHECKING: import pyarrow import pandas import dask import mars import modin import pyspark import datasets import ray...
# Calculadora... #funções das operações: import math def soma(a, b): return a + b def resta(a, b): return a - b def multiplicacao(a, b): return a * b def divisao(a, b): return a / b def potencia(a, b): return a**b def raizquadrada(a): return math.sqrt(a) while True: ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import boto3 import csv import json import logging from budget_retrieval import get_budget from budget_placement import place_budget def respond(err, res=None): return { 'statusCode': '400' if err else '200', 'body': err.message if err else json.dumps...
from typing import Any, Dict, Optional import jsonschema from hypothesis import strategies as st from hypothesis_jsonschema import from_schema from .mutations import MutationContext from .types import Draw, Schema _VALIDATORS_CACHE = {} def get_validator(schema: Schema, operation_name: str, location: str) -> jsons...
# Copyright 2012 by Wibowo Arindrarto. All rights reserved. # This code is part of the Biopython distribution and governed by its # license. Please see the LICENSE file that should have been included # as part of this package. """Bio.SearchIO base classes for HMMER-related code.""" from anarci.Bio._py3k import _as_...
# -*- coding: utf-8 -*- from oauthlib.common import Request from oauthlib.oauth1 import ( SIGNATURE_HMAC_SHA1, SIGNATURE_HMAC_SHA256, SIGNATURE_PLAINTEXT, SIGNATURE_RSA, SIGNATURE_TYPE_BODY, SIGNATURE_TYPE_QUERY, ) from oauthlib.oauth1.rfc5849 import Client from tests.unittest import TestCase class ClientRea...
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def rotateRight(self, head: ListNode, k: int) -> ListNode: """Linked list Running Time: O(n) where n is the length of linked list. """ ...
#coding=utf-8 import md5 import os from sampler import * from PIL import Image def md5_img ( im ): width,height = im.size hashed = md5.new() for ih in xrange(height): for iw in xrange(width): r,g,b = im.getpixel((iw,ih)) hashed.update('-'.join(map(str,[r,g,b]))) return hashed.hexdigest() def ...
from datetime import datetime def utils_datetime(): """Wrapper for datetime.today""" return datetime.today()
print('single quote') print("double quote") print("don\'t") print('"double quotes" are in single qoute') print(r'C:\Users\BIT200164\Downloads') multiline = """\ Happy bird day jaaaaa Developer.\ """ print(multiline) c = "a"+"b" print(c*3) twoliterals = 'py' 'thon' print(twoliterals) text = ('Put several strin...
# -*- coding: utf-8 -*- r"""Test structure factor calculations """ import numpy as np import pytest from matplotlib import use use('Agg') from mock import patch from neutronpy import Material from neutronpy.crystal.structure_factors import MagneticFormFactor input = {'name': 'FeTe', 'composition': [{'ion'...
""" Dummy UE program written for DIKUE Authors: Imtiaz Karim, Syed Rafiul Hussain Contact: karim7@purdue.edu, hussain1@psu.edu """ import socket DEVICE_PORT = 58888 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(("localhost", DEVICE_PORT)) s.listen(1) (client, address) = s.accept() print "Adapter con...
# DO NOT MODIFY THIS FILE DIRECTLY. THIS FILE MUST BE CREATED BY # mf6/utils/createpackages.py # FILE created on August 06, 2021 20:57:00 UTC from .. import mfpackage class ModflowGwtadv(mfpackage.MFPackage): """ ModflowGwtadv defines a adv package within a gwt6 model. Parameters ---------- mode...
import base64 def main(req, res): return 404, [(b'Content-Type', b'image/png')], base64.decodebytes(b"iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAAhSURBVDhPY3wro/KfgQLABKXJBqMGjBoAAqMGDLwBDAwAEsoCTFWunmQAAAAASUVORK5CYII=")
"""passlib.tests.test_handlers_django - tests for passlib hash algorithms""" #============================================================================= # imports #============================================================================= from __future__ import with_statement # core import logging; log = logging....
from team29.analizer.abstract.expression import Expression, TYPE from team29.analizer.abstract import expression from team29.analizer.reports import Nodo from team29.analizer.statement.expressions.primitive import Primitive class InRelationalOperation(Expression): def __init__(self, colData, optNot, subquery, row...
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.7.1 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # %% import pandas as pd from tasrif.processing_pipe...
def merge_dicts(dict_a, dict_b): """Return dict issue from merge from dict_a and dict_b, dict_a having precedence""" # inspired from https://stackoverflow.com/questions/7204805/dictionaries-of-dictionaries-merge/7205107#7205107 if not dict_a: return dict_b if not dict_b: return dict_a ...
''' Create a program that asks the user to enter their name and their age. Print out a message addressed to them that tells them the year that they will turn 100 years old. Extras: -Add on to the previous program by asking the user for another number and printing out that many copies of the previous message. (Hint: o...
#!/usr/bin/env python import pika # Host in which RabbitMQ is running. HOST = 'localhost' # Name of the queue. QUEUE = 'pages' # Specifies what to do after consuming messages from RabbitMQ. def handler(channel, method, properties, body): print '-> Handled: [%s]' % body # Getting the connection using pika. # Cr...
# coding=utf-8 r""" This code was generated by \ / _ _ _| _ _ | (_)\/(_)(_|\/| |(/_ v1.0.0 / / """ from twilio.base import deserialize from twilio.base import serialize from twilio.base import values from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import L...
""" WSGI config for acatto_web project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION...
import tensorflow.compat.v1 as tf import numpy as np import argparse import socket import importlib import time import os import scipy.misc import sys BASE_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.append(BASE_DIR) sys.path.append(os.path.join(BASE_DIR, 'models')) sys.path.append(os.path.join(BASE_DIR, ...
from setuptools import setup, find_packages setup( name="tnef", version="2.0.0", author="Marcus LaFerrera (@mlaferrera)", url="https://github.com/PUNCH-Cyber/stoq-plugins-public/v2", license="Apache License 2.0", description="TNEF File Extractor", packages=find_packages(), include_packa...
from copy import deepcopy import numpy as np from .base_quantum import BaseQuantum from .qobj import Qobj from .routines import _SIGMA_I, _SIGMA_X, _SIGMA_Y, _SIGMA_Z, _vec2mat class Operator(BaseQuantum): """Class for representing quantum operators Parameters ---------- data : array-like M...
#!/usr/bin/env python import argparse import chainer import chainer.functions as F import chainer.links as L from chainer import training from chainer.training import extensions import os import sys import time sys.path.insert(0, os.path.abspath('.')) from watchdog import WatchDog from watchdog.estimators import Sim...
# -*- coding: utf-8 -*- # Generated by Django 1.9.8 on 2017-03-14 19:21 from __future__ import unicode_literals import django.db.models.deletion from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('talk', '0012_auto_20170304_1517'), ] operations = [...
"""Estimate reasonable bin sizes from BAM read counts or depths.""" from __future__ import absolute_import, division, print_function import logging import os import tempfile import numpy as np import pandas as pd from skgenome import tabio, GenomicArray as GA from . import coverage, samutil from .antitarget import co...
from enum import Enum import os import sys from dataclasses import dataclass from logging import error, getLogger from typing import Union from eit_ai.default.set_default_dir import AI_DIRS, AiDirs, set_ai_default_dir from eit_ai.train_utils.lists import (ListDatasetHandlers, ListModels, ListWorkspaces, ListLosses, ...
import pysam import readtagger.bam_io TEST_BAM = 'dm6.bam' TEST_SAM = 'testsam_a.sam' TEST_SAM_B = 'testsam_b.sam' EXTENDED = 'extended_annotated_updated_all_reads.bam' def test_bamreader_samtools(datadir_copy): # noqa: D103 _test_bamreader(datadir_copy, 'samtools') def test_bamreader_internal(datadir_copy):...
from django.core.mail import send_mail from django.shortcuts import get_object_or_404, redirect, render from django.template.loader import render_to_string from django.urls import reverse, reverse_lazy from django.utils.translation import ugettext_lazy as _ from django.views.generic import DeleteView, FormView, Templat...
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import unittest from pathlib import Path from unittest.mock import MagicMock, patch from ... import commands from ...analysis_directory impor...
"""" Re-entrancy detection Based on heuristics, it may lead to FP and FN Iterate over all the nodes of the graph until reaching a fixpoint """ from collections import namedtuple, defaultdict from slither.detectors.abstract_detector import DetectorClassification from .reentrancy import Reentrancy, to_hasha...
""" sphinx.ext.imgmath ~~~~~~~~~~~~~~~~~~ Render math in HTML via dvipng or dvisvgm. :copyright: Copyright 2007-2019 by the Sphinx team, see AUTHORS. :license: BSD, see LICENSE for details. """ import posixpath import re import shutil import tempfile from hashlib import sha1 from os import path f...
import logging import pathlib from multiprocessing import freeze_support from typing import Dict from beer.consensus.constants import ConsensusConstants from beer.consensus.default_constants import DEFAULT_CONSTANTS from beer.full_node.full_node import FullNode from beer.full_node.full_node_api import FullNodeAPI from...
import subprocess from briefcase.commands import ( BuildCommand, CreateCommand, PackageCommand, PublishCommand, RunCommand, UpdateCommand ) from briefcase.config import BaseConfig, parsed_version from briefcase.exceptions import BriefcaseCommandError from briefcase.integrations.android_sdk impo...
# # 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 us...
# Copyright 2018-2020 Streamlit 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 law or agreed to in wr...
# coding: utf-8 """ Vericred API Vericred's API allows you to search for Health Plans that a specific doctor accepts. ## Getting Started Visit our [Developer Portal](https://developers.vericred.com) to create an account. Once you have created an account, you can create one Application for Production and an...
import sys sys.path.append('/TabPy') from geocode import geocodeReverse def prepGeo(input): prepData = geocodeReverse(input,"token") return prepData def get_output_schema(): return pd.DataFrame( { "InitialQuery": prep_string(), "ReturnAddress": prep_string(), "A...
from setuptools import setup from io import open from enzyme_sphinx_theme import __version__ setup( name = 'enzyme_sphinx_theme', version =__version__, author = 'Shift Lab', author_email= 'info@shiftlabny.com', url="https://github.com/enzymead/enzyme_sphinx_theme", docs_url="https://github.com/...
"""Simpletest example using Adafruit PyPortal. Uses the touchscreen to advance between examples.""" import board import adafruit_touchscreen from adafruit_pybadger import pybadger # pylint: disable=invalid-name # These pins are used as both analog and digital! XL, XR and YU must be analog # and digital capabl...
import asyncio import tempfile from decimal import Decimal import os from contextlib import contextmanager from collections import defaultdict import logging import concurrent from concurrent import futures import unittest from typing import Iterable, NamedTuple, Tuple from aiorpcx import TaskGroup from electrum impo...
""" thinly wrapped MongoDB backend for the sample storage """ from pymongo import MongoClient from bioflow.configs.main_configs import mongo_db_url, pymongo_prefix, pymongo_suffix # Original module ported from main_configs client = MongoClient(mongo_db_url) db = client.BioFlow_database # REFACTOR: [Better database]: ...
from flask import request from flask.views import MethodView from airview_api.blueprint import Blueprint, Roles from airview_api.schemas import SearchResultSchema, SearchQueryArgsSchema from airview_api.search import init_search_backend blp = Blueprint( "search", __name__, url_prefix="/search", descri...
# Copyright 2021 The Tekton Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wr...
# generated from catkin/cmake/template/pkg.context.pc.in CATKIN_PACKAGE_PREFIX = "" PROJECT_PKG_CONFIG_INCLUDE_DIRS = "".split(';') if "" != "" else [] PROJECT_CATKIN_DEPENDS = "".replace(';', ' ') PKG_CONFIG_LIBRARIES_WITH_PREFIX = "".split(';') if "" != "" else [] PROJECT_NAME = "visual_odometry_line" PROJECT_SPACE_D...
from eth2spec.test.context import ( spec_state_test, spec_test, with_all_phases, single_phase, with_phases, PHASE0, PHASE1, with_custom_state, zero_activation_threshold, misc_balances, low_single_balance, is_post_altair, ) from eth2spec.test.helpers.state import ( next_epoch, next_sl...
# -*- coding: utf8 -*- # Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. 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...
import os from os import listdir, makedirs from os.path import join import pickle import sys import cv2 import matplotlib.pyplot as plt from PIL import Image import numpy as np from time import time from skimage import filters # threshold_yen, frangi from skimage.exposure import rescale_intensity import src.data.cons...
#!/usr/bin/python # Copyright (c) 2014 Wladimir J. van der Laan # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. ''' Script to generate list of seed nodes for chainparams.cpp. This script expects two text files in the directory tha...
""" @brief test log(time=10s) """ import os import sys import unittest from pyquickhelper.loghelper import fLOG from pyquickhelper.pycode import get_temp_folder try: import src except ImportError: path = os.path.normpath( os.path.abspath( os.path.join( os.path.split(__...
"""Portfolio site views.""" from django.views.generic import TemplateView class HomeView(TemplateView): """Home view class based view.""" template_name = 'portfolio/home.html'
#!/usr/bin/env python3 import logging import re from telegram import InlineKeyboardButton, InlineKeyboardMarkup, Update from telegram.ext import (CallbackQueryHandler, CommandHandler, ConversationHandler, Filters, MessageHandler, Updater) from commons import checkI...
import cv2 from dbr import DynamsoftBarcodeReader dbr = DynamsoftBarcodeReader() import time import os import sys sys.path.append('../') import config def get_time(): localtime = time.localtime() capturetime = time.strftime("%Y%m%d%H%M%S", localtime) return capturetime def read_barcode(): vc = cv2...
split()正序分割列;rsplit()逆序分割列 Series.str.split(pat=None, n=-1, expand=False) 参数: pat : 字符串,默认使用空白分割. n : 整型,默认为-1,既使用所有的分割点分割 expand : 布尔值,默认为False.如果为真返回数据框(DataFrame)或复杂索引(MultiIndex);如果为假,返回序列(Series)或者索引(Index). return_type : 弃用,使用spand参数代替 返回值: split : 参考expand参数
from threading import Thread from django.http import HttpResponse from django.shortcuts import render from Vizard.models import User, Task, TaskScheduler from Vizard.settings import RESPONSE from Analyzer.execution import execute_jmeter, execute_locust, execute_regressiontest from source.util import dump scheduler =...
from nipype import Workflow from .nodedefs import definednodes from p3.base import workflowgenerator class fieldmapcorrectionworkflow(workflowgenerator): """ Defines the field map correction workflow TODO """ def __new__(cls,name,settings): # call base constructor super().__new__...
from contextualized_topic_models.models.ctm import CTM from contextualized_topic_models.utils.data_preparation import TextHandler from contextualized_topic_models.utils.data_preparation import bert_embeddings_from_list from contextualized_topic_models.datasets.dataset import CTMDataset import pandas as pd import numpy ...
from typing import Optional # Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def rotateRight(self, head: Optional[ListNode], k: int) -> Optional[ListNode]: # the idea is to split the last (k % le...
"""Fixes for GFDL CM2p1 model.""" from copy import deepcopy import cftime import numpy as np from esmvalcore.iris_helpers import date2num from ..cmip5.gfdl_esm2g import AllVars as BaseAllVars from ..fix import Fix from .cesm1_cam5 import Cl as BaseCl Cl = BaseCl class AllVars(BaseAllVars): """Fixes for all va...
#! /usr/bin/env python # -*- coding: iso-8859-15 -*- ############################################################################## # Copyright 2003 & onward LASMEA UMR 6602 CNRS/Univ. Clermont II # Copyright 2009 & onward LRI UMR 8623 CNRS/Univ Paris Sud XI # # Distributed under the Boost ...
from pymongo import MongoClient import pandas as pd from bson.json_util import dumps from flask import make_response def db_init(): """ Initialize database connection and clear data in collection :return: MongoDB reference object """ client = MongoClient("mongodb+srv://admin:semantive@semantive-lt...
# Labelbox json file to COCO json files # Based on the LBExporters 0.1.1 file (https://pypi.org/project/LBExporters/), but heavily modified # Import libraries import json import datetime as dt import logging import requests from PIL import Image import numpy as np import os import rasterio import shapely import time...
""" collection of add-ons for QM calculations. contains: - gCP """ import os import sys from ase.io import read, write import numpy as np from ase.units import mol, kcal from ase.units import Hartree, Bohr def run_command(command): """ execute <command> in a subprocess and check error code """ from s...
import Queue import threading import os import urllib2 threads = 10 target = "http://xperblueray.com" directory = "/usr/blueray/Downloads" filters = [".jpg",".gif","png",".css"] os.chdir(directory) web_paths = Queue.Queue() for r,d,f in os.walk("."): for files in f: remote_path = "%s/%s" % (r,files) ...
import re import json import pickle import textwrap import unittest import warnings import importlib import importlib_metadata import pyfakefs.fake_filesystem_unittest as ffs from . import fixtures from importlib_metadata import ( Distribution, EntryPoint, MetadataPathFinder, PackageNotFoundError, ...