text
stringlengths
1
927k
# -*- coding: utf-8 -*- # Copyright 2018 Novo Nordisk Foundation Center for Biosustainability, # Technical University of Denmark. # # 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...
''' Build the pipeline workflow by plumbing the stages together. ''' from ruffus import Pipeline, suffix, formatter, add_inputs, output_from from stages import Stages def make_pipeline(state): '''Build the pipeline by constructing stages and connecting them together''' # Build an empty pipeline pipeline ...
import time from web_scraper import checkIfExsits from fast import degree_distance from db import get_db from flask import session def wikicheat(start_link, end_link): start_link = start_link.lower() end_link = end_link.lower() start_time = time.time() path_length = degree_distance(start_link, end_li...
#!/usr/bin/env python3 #Copyright (C) 2013 by Glenn Hickey # Copyright (C) 2012-2019 by UCSC Computational Genomics Lab # #Released under the MIT license, see LICENSE.txt #!/usr/bin/env python3 """Compute constraint turnover stats over entire tree """ import argparse import os import sys import copy import subprocess...
from typing import Tuple from functools import lru_cache from pulumi import ResourceOptions, Alias from pulumi_azure import appservice, storage @lru_cache(maxsize=1) def get_consumption_plan( resource_group_name: str, ) -> Tuple[appservice.Plan, storage.Account]: plan = appservice.Plan( "nvd-funcs-con...
import tempfile import logging import traceback from rest_framework.response import Response from rest_framework import status from django.http import response from ..models import State from ..renderers import PngRenderer from ..renderers import JpegRenderer from ..renderers import GifRenderer from ..renderers impor...
import os import time from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint from absl import app from absl import flags from albumentations import ( Compose, HorizontalFlip, RandomBrightness,RandomContrast, ShiftScaleRotate, ToFloat, VerticalFlip) from models import build_seg_model, build_pixel...
from typing import List from ....source_shared.base import Base from ....utilities.byte_io_mdl import ByteIO class MaterialReplacementList(Base): def __init__(self): self.replacements = [] # type: List[MaterialReplacement] def read(self, reader: ByteIO): entry = reader.tell() repl...
import os import flopy import numpy as np tpth = os.path.abspath(os.path.join('temp', 't016')) if not os.path.isdir(tpth): os.makedirs(tpth) exe_name = 'mfusg' v = flopy.which(exe_name) run = True if v is None: run = False def test_usg_disu_load(): pthusgtest = os.path.join('..', 'examples', 'data',...
# -*- coding: utf-8 -*- # flake8: noqa from app.views import common from app.views import user from app.views import webhook from app.views import server from app.views import history from app.views import collaborator from app.views import api from app.views import socket
# ------------------------------------------------------------------------- # # Part of the CodeChecker project, under the Apache License v2.0 with # LLVM Exceptions. See LICENSE for license information. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception # # ---------------------------------------------------...
import array as ar # F1 myarray = ar.array("i", [] ) # F2 myarrlen = int(input("Kindly enter the array length: ")) # F3 for loop in range(myarrlen): myarray.append(int(input("Enter element number: "))) # F4 for loop in range(len(myarray)): print(myarray[loop]) # F5
# coding: utf-8 """ Argo Server API You can get examples of requests and responses by using the CLI with `--gloglevel=9`, e.g. `argo list --gloglevel=9` # noqa: E501 The version of the OpenAPI document: v2.11.8 Generated by: https://openapi-generator.tech """ import pprint import re # noqa: F401 ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # 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-...
import paddle.fluid as fluid import paddle import paddorch.cuda import paddorch.nn import os import paddorch.nn.functional from paddle.fluid import dygraph import numpy as np def constant_(x, val): x=fluid.layers.fill_constant(x.shape,x.dtype,val,out=x) return x def normal_(x,m=0,std=1): y=paddle.randn(x...
# Generated by Django 2.2.4 on 2019-08-27 16:40 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] ope...
import urllib from xml.dom import minidom import time def nextbus(a, r, c="vehicleLocations", e=0): """Returns the most recent latitude and longitude of the selected bus line using the NextBus API (nbapi)""" nbapi = "http://webservices.nextbus.com" nbapi += "/service/publicXMLFeed?" nbapi += "command=%s&a...
from hypothesis import given from rene.exact import Point from tests.utils import (equivalence, implication) from . import strategies @given(strategies.points) def test_reflexivity(point: Point) -> None: assert point == point @given(strategies.points, strategies.points) def test_symmet...
import requests import json import os content_type = "application/vnd.netbackup+json; version=2.0" testPolicyName = "VMware_test_policy" testClientName = "MEDIA_SERVER" testScheduleName = "VMware_test_schedule" def post_rbac_object_group_for_VMware_policy(jwt, base_url): global object_group_id url = base_url + "/rb...
def up(config, database, semester, course): database.execute('ALTER TABLE users ADD COLUMN IF NOT EXISTS registration_subsection character varying(255)')
''' URL: https://leetcode.com/problems/day-of-the-week/ Difficulty: Easy Description: Day of the Week Given a date, return the corresponding day of the week for that date. The input is given as three integers representing the day, month and year respectively. Return the answer as one of the following values {"Sund...
import os import sys from datetime import datetime import logging import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.utils.data import DataLoader, random_split from torch.utils.tensorboard import SummaryWriter import torchvision.transforms as transforms from models...
from django.core.urlresolvers import reverse from django.db.models.query import QuerySet as DjangoQuerySet from modularodm import Q from modularodm.exceptions import NoResultsFound from modularodm.query.query import RawQuery from framework.mongo.storage import MongoQuerySet class AffiliatedInstitutionsList(list): ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 2012-2018 Matt Martz # 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.or...
""" """ class Game: """A scrabble game"""
#!/bin/env python # encoding:utf-8 # # # __Author__ = "CORDEA" __date__ = "2014-10-13" import sys arg = sys.argv[1] arg2 = sys.argv[2] infile = open(arg, "r") lines = infile.readlines() infile.close() idDict = {} for line in lines: tmp = [r.rstrip("\r\n") for r in line.split("\t")] idDict[tmp[0]] = tmp[...
import argparse import gym import numpy as np import os import tensorflow as tf import tempfile import time import sys cwd = os.getcwd() cwd = '/'.join(cwd.split('/')[:-4]) temp = sys.path temp.append('') temp[1:] = temp[0:-1] temp[0] = cwd print(sys.path) from baselines.deepq.dqn_utils import * import baselines.com...
# Copyright (c) 2021 - present / Neuralmagic, 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...
import logging import discord from discord.ext import commands from discord_slash import cog_ext from discord_slash.context import SlashContext from config import CONSTANTS, cmds, database import lonir_funcs discord.Permissions.advanced() log = logging.getLogger('logger') class Information(commands.Cog): def __...
class DNode: def __init__(self, data): self.data=data self.next=None self.prev=None class Doublylinkedlist(): def __init__(self): self.head=None def print_list(self): cur_node=self.head while cur_node: print(cur_node.dat...
# Copyright The ANGLE Project Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # # Generates an Android.bp file from the json output of a 'gn desc' command. # Example usage: # gn desc out/Android --format=json "*" > desc.json # py...
# coding=utf-8 # Copyright (c) Facebook, Inc. and its affiliates. # Copyright (c) HuggingFace Inc. team. # # 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 math from calculate_grades import calculate_stat def test_calculate_grades(): mean_answer = 69.5 sd_answer = 22.299 grades = [88, 34, 67, 89] mean, sd = calculate_stat(grades) assert math.isclose(mean, mean_answer, abs_tol=0.05) assert math.isclose(sd, sd_answer, abs_tol=0.05)
# -*- coding: utf-8 -*- import datetime from decimal import Decimal from south.db import db from south.v2 import DataMigration from django.db import models class Migration(DataMigration): def forwards(self, orm): for rec in orm['fund.RecurringDirectDebitPayment'].objects.all(): donor = orm['re...
''' /****************************************************************** * * Copyright 2018 Samsung Electronics 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 * * htt...
#This file contain and will update with all the programs i used ... #Empty line remover sed -e '/^[[:blank:]]*$/d' source_file > newfile #Frequency word count. files = list_of_files fd = nltk.FreqDist() for file in files: with open(file) as f: for sent in nltk.sent_tokenize(f.lower()): for word...
#===----------------------------------------------------------------------===## # # The LLVM Compiler Infrastructure # # This file is dual licensed under the MIT and the University of Illinois Open # Source Licenses. See LICENSE.TXT for details. # #===------------------------------------------------...
""" DCA class performs Discriminant Correlation Analysis (DCA). It can be used as a dimensionality reduction algorithm. Usage is similar to sklearn's preprocessing classes such as PCA. (Code from Thee Chanyaswad (tc7@princeton.edu)) """ import numpy as np import scipy from sklearn.metrics import pairwise from sklearn ...
#!/usr/bin/env python # # Copyright (C) 2016 The Android Open Source Project # # 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 req...
### importing libraries import matplotlib.pyplot as plt import numpy as np n = np.linspace(-5, 5, 11) delta = 1*(n==0) u = 1*(n>=0) plt.stem(n, delta, use_line_collection = True) # naming the x axis plt.xlabel('n') plt.ylabel('x[n] = delta[n]') # giving a title to my graph plt.title('Unit Impulse Sequence') plt.show()...
import hashlib class Plugin: def __init__(self, parser, sqlitecur): parser.registerCommand([("hash", "Calculates all hashes", self._allHash)]) for h in hashlib.algorithms_available: parser.registerCommand([("hash",), (h, "Calculates the %s" % h, self._hashCurry(h))]) def _allHash(...
"""Implement an API wrapper for accessing a TP-Link EAP.""" from pathlib import Path from .client import Client from .eap import Eap from .error import CommunicationError, PytleapError __all__ = [ "Eap", "Client", "PytleapError", "CommunicationError", ] __version__ = (Path(__file__).parent / "VERSION...
# # PySNMP MIB module HH3C-DOT11-ACMT-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HH3C-DOT11-ACMT-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 19:13:08 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default...
"""Upload the contents of your Downloads folder to Dropbox. This is an example app for API v2. """ from __future__ import print_function import argparse import contextlib import datetime import os import six import sys import time import unicodedata if sys.version.startswith('2'): input = raw_input # noqa: E501...
# -*- coding: utf-8 -*- from starlette.applications import Starlette from starlette.responses import JSONResponse from starlette.routing import Route, WebSocketRoute import math_func import scheduled_tasks async def homepage(request): result: dict = { "status": "hello world", "method": request.me...
# ---------------------------------------------------------------------------- # Copyright (c) 2013--, scikit-bio development team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. # --------------------------------------------...
import pandas as pd import numpy as np from dplypy.dplyframe import DplyFrame from dplypy.pipeline import arrange def test_arrange(): pandas_df = pd.DataFrame( data=[[5, 1, 0], [20, 2, 2], [0, 8, 8], [np.nan, 7, 9], [10, 7, 5], [15, 4, 3]], columns=["col1", "col2", "col3"], index=[1, 3, 5...
# ============================================================================= # Tool Directory # # A program to prepare an HTML table listing softwares available on # a file system. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. #...
# Copyright 2013-2019 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class PyPint(PythonPackage): """Pint is a Python package to define, operate and manipulate physi...
"""Jade Tree Email Support. Jade Tree Personal Budgeting Application | jadetree.io Copyright (c) 2020 Asymworks, LLC. All Rights Reserved. """ from flask import current_app from flask_mail import Mail, Message from jadetree.exc import ConfigError mail = Mail() __all__ = ('init_mail', 'mail', 'send_email') def i...
from flask import Response, request from flask_jwt_extended import create_access_token from database.models import User from database.db import db from flask_restful import Resource from mongoengine.errors import FieldDoesNotExist, NotUniqueError, DoesNotExist, ValidationError from resources.errors import SchemaValidat...
"""Whatnext """ from __future__ import print_function import os from setuptools import find_packages, setup # --- import your package --- import whatnext as package PLATFORMS = [ "Windows", "MacOS", "Unix", ] CLASSIFIERS = [ "Development Status :: 3 - Alpha", "Intended Audience :: Developers",...
# Copyright 2015 The TensorFlow 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 applica...
from django.views import generic from django.shortcuts import render, redirect from django.db.models import Q from django.contrib import messages from .models import Alumnus from .forms import AlumniForm import operator from functools import reduce from hknweb.utils import method_login_and_permission, login_and_permi...
import math class Math: @staticmethod def add(x,y): return x+y @staticmethod def remove(x,y): return x-y @staticmethod def mulitiply(x,y): return x*y @staticmethod def divide(x,y): return x/y def calculate(): var = ("+","-","*","/") take = input...
# 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.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
# model settings model = dict( type='MaskRCNN', pretrained=None, backbone=dict( type='LIT', embed_dim=96, depths=[2, 2, 6, 2], num_heads=[3, 6, 12, 24], window_size=7, mlp_ratio=4., qkv_bias=True, qk_scale=None, drop_rate=0., at...
import pandas as pd from sklearn.linear_model import LinearRegression from sklearn.tree import DecisionTreeRegressor from sklearn.svm import SVR from sklearn.preprocessing import PolynomialFeatures from sklearn.metrics import mean_squared_error as mse from sklearn.metrics import mean_absolute_error as mae from sklearn....
from ..base import ShopifyResource class Checkout(ShopifyResource): pass
""" Monitoring algorithms for Quicklook pipeline """ import os,sys import datetime import numpy as np import scipy.ndimage import yaml import re import astropy.io.fits as fits import desispec.qa.qa_plots_ql as plot import desispec.quicklook.qlpsf import desispec.qa.qa_plots_ql as fig from desispec.quicklook.qas impor...
# -------------- import pandas as pd from sklearn.model_selection import train_test_split data = pd.read_csv(path) X = data.drop(['customer.id','paid.back.loan'],axis=1) y = data['paid.back.loan'] X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.3,random_state=0) # -------------- #Importing header fil...
from __future__ import absolute_import, division, print_function import os import time import pandas as pd import numpy as np import seaborn as sns from collections import Counter import matplotlib.pyplot as plt from sklearn.externals import joblib from sklearn.preprocessing import Normalizer from sklearn.model_select...
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
class Produto: def __init__(self, codigo, descricao, valorUni): self.codigo = codigo self.descricao = descricao self.valorUni = valorUni class NotaFiscal: def __init__(self, nroNF, nomeCliente, itensNF): self.nroNF = nroNF self.nomeCliente = nomeCliente self.iten...
from nonebot import on_command, CommandSession from mcrcon import MCRcon __plugin_name__ = '重载MinecraftQQ' __plugin_usage__ = '重载MinecraftQQ' @on_command('qreload', aliases=('重载', 'MCQQ重载', 'MinecraftQQ重载', 'minecraftqq重载', 'mcqqreload')) async def qreload(session: CommandSession): with MCRcon(host = session.bot....
from typing import Optional import numpy as np import torch def image_to_tensor(image: np.ndarray, keepdim: bool = True) -> torch.Tensor: """Converts a numpy image to a PyTorch 4d tensor image. Args: image (numpy.ndarray): image of the form :math:`(H, W, C)`, :math:`(H, W)` or :math:`(B,...
import socket import sys import signal import serial arduino = serial.Serial('COM4', 9600) #this will change if running this on windows but this is for linux arduino.write(b'0') server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) port = None host = N...
_canvas = """ <script type="text/javascript" src="./js/canvas.js"></script> <div> <canvas id="{0}" width="{1}" height="{2}" style="background:rgba(158, 167, 184, 0.2);" onclick='click_callback(this, event, "{3}")'></canvas> </div> <script> var {0}_canvas_object = new Canvas("{0}");</script> """ # noqa class Canvas:...
from django.contrib import admin from .models import Tag, Ingredient, RecipeIngredient, Recipe, Favorite, Subscription, Purchase class TagAdmin(admin.ModelAdmin): list_display = ('pk', 'title', 'color') search_fields = ('title',) empty_value_display = '-пусто-' class IngredientAdmin(admin.ModelAdmin): ...
# Copyright 2015 The TensorFlow 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 applica...
import numpy as np import descarteslabs as dl from shapely.geometry import Polygon, MultiPolygon from PIL import Image def generate_sentinel_training_images(geometry, area, #eg. 'Jamaca' tile_size= 512, st...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** 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 _utilities, _tables from...
#Adapte o código do desafio #107, criando uma função adicional chamada moeda() # que consiga mostrar os números como um valor monetário formatado. import moeda #Programa Principal valor = float(input('Digite o preço:R$ ')) print(f' A aumentando 10% de {moeda.moeda(valor)} é igual à: R${moeda.moeda(moeda.aumentar(valo...
#!/usr/bin/python3 from functools import partial # Обычная функция принимающая 3 аргумента: def f(x, y, z): return (x + y + z) * 100 print("f(2, 3, 4) ->") print(f(2, 3, 4)) # -> 900 # Частичное применение этой же функции: funcYZ = partial(f, 2) # x = 2 print("\nfuncYZ(3, 4) ->") print(funcYZ(3, 4)) # -> 900 ...
from . import FixtureTest class BusinessAndSpurRoutes(FixtureTest): def _check_route_relation( self, rel_id, way_id, tile, shield_text, network): z, x, y = map(int, tile.split('/')) self.load_fixtures([ 'https://www.openstreetmap.org/relation/%d' % (rel_id,), ], c...
import argparse, time, sys, os sys.path.append(os.path.abspath(os.path.dirname(__file__) + '/..')) from rgbmatrix import RGBMatrix class SampleBase(argparse.ArgumentParser): def __init__(self, *args, **kwargs): super(SampleBase, self).__init__(*args, **kwargs) self.add_argument("-r", "--rows", ac...
import pickle import logging import requests import simplejson as json from django.core.cache import cache from appconf.manager import SettingManager from rmis_integration.client import get_md5 logger = logging.getLogger(__name__) BASE_URL = "https://suggestions.dadata.ru/suggestions/api/4_1/rs/suggest/{}" def s...
import mock import os import testtools from pydantic import AnyHttpUrl from shakenfist import exceptions from shakenfist import images from shakenfist import image_resolver_cirros from shakenfist import image_resolver_ubuntu from shakenfist import logutil from shakenfist.tests import test_shakenfist from shakenfist.c...
# Mostly copied and modified from torch/vision/references/segmentation to support unlabeled data # Copied functions from fmassa/vision-1 to support multi-dimensional masks loaded from numpy ndarray # Update: The current torchvision github repo now supports tensor operation for all common transformations, # you are enco...
# Copyright 2021, The TensorFlow Federated 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 o...
#!/usr/bin/env python # encoding: utf-8 name = "Baeyer-Villiger_step1_cat/groups" shortDesc = u"" longDesc = u""" """ template(reactants=["ketone", "hydroperoxide", "acid"], products=["criegee", "acid2"], ownReverse=False) reverse = "none" recipe(actions=[ ['BREAK_BOND', '*3', 1, '*4'], ['BREAK_BOND', '*7'...
"""Functionality to check that the input provided by the user is valid. Index ----- .. currentmodule:: nanoqm.workflows.input_validation .. autosummary:: process_input API --- .. autofunction:: process_input """ import os import warnings from os.path import join from pathlib import Path from typing import Any, Dict...
#!/bin/env python import sys, os, warnings, time from ncclient import manager, operations from ncenviron import * def default_unknown_host_cb(foo, bar): return True def demo(host=nc_host, port=nc_port, user=nc_user, password=nc_password): with manager.connect(host=host, port=port, username=user, password=password,...
"""Module containing the Train class and support functionality.""" __authors__ = "Ian Goodfellow" __copyright__ = "Copyright 2010-2012, Universite de Montreal" __credits__ = ["Ian Goodfellow"] __license__ = "3-clause BSD" __maintainer__ = "LISA Lab" __email__ = "pylearn-dev@googlegroups" from datetime import datetime i...
import pkg_resources try: import click except ImportError: raise Exception('Missing CLI dependencies. To use WASH from CLI, please run following command:/n' 'pip install wash-lang-prototype[cli]') @click.group() @click.option('--debug', default=False, is_flag=True, help="Debug/trace outpu...
from PyQt5.QtGui import * from PyQt5.QtWidgets import * from PyQt5.QtCore import * import pyqtgraph as pg import requests import requests_cache from collections import defaultdict from datetime import datetime, timedelta, date from itertools import cycle import sys import time import traceback requests_cache.instal...
import py, os, sys from .support import setup_make, soext from pypy.module._cppyy import interp_cppyy, executor currpath = py.path.local(__file__).dirpath() test_dct = str(currpath.join("example01Dict"))+soext def setup_module(mod): setup_make("example01") class AppTestPYTHONIFY: spaceconfig = dict(usemodu...
from abc import ABC, abstractmethod from collections import OrderedDict from typing import List, Set, Dict, Any, Union, cast import falcon from model.http_helper import HTTPBadRequestField from model.view_field import ViewField, view_field_types from model.db import LdapModlist, LdapAddlist, LdapMods, LdapFetch impo...
# -*- coding: utf-8 -*- """ /*************************************************************************** AttributeAssignment A QGIS plugin Easy to assign an attribute on QGIS ------------------- begin : 2018-03-14 git sha ...
from __future__ import annotations from dataclasses import dataclass from io import BytesIO from pathlib import Path from typing import TYPE_CHECKING, Optional, Tuple from urllib.parse import urljoin from zipfile import ZipFile import requests from more_itertools import one if TYPE_CHECKING: from _typeshed impo...
# Dummy test import numpy as np from gsea import * from numpy.testing import assert_almost_equal def test_rank_genes(): D = np.array([[-1,1],[1,-1]]) C = [0,1] L,r = rank_genes(D,C) assert_almost_equal(L, [0,1]) assert_almost_equal(r, [1,-1]) def test_enrichment_score(): L = [1,0] r = [-1,...
n=600851475143 for i in range(2,n): if n%i==0: n=int(n/i) print(f'{i}, {n}') if n==1: break
# Copyright 2020 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...
# -*- coding: utf-8 -*- ''' Production Configurations - Use djangosecure - Use mailgun to send emails ''' from django.utils import six from .common import * # noqa # SECRET CONFIGURATION # ------------------------------------------------------------------------------ # See: https://docs.djangoproject.com/en/dev/ref...
from hopex.utils.input_checker import * class MarketClient(object): def __init__(self, **kwargs): """ Create the request client instance. :param kwargs:The option of request connection. api_key: The public key applied from Hopex. secret_key: The private key applied f...
# This file is part of Scapy # See http://www.secdev.org/projects/scapy for more informations # Copyright (C) Philippe Biondi <phil@secdev.org> # This program is published under a GPLv2 license """ Generators and packet meta classes. """ ################ # Generators # ################ from __future__ import absol...
# Generated by Django 2.2.9 on 2020-10-11 10:50 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('posts', '0002_auto_20201011_1034'), ] operations = [ migrations.AlterField( model_name='group', name='title', ...
import k3redisutil import time # Using redis as a duplex cross process communication channel pool. # client and server with the same channel name "/foo" is a pair c = k3redisutil.RedisChannel(6379, '/foo', 'client') s = k3redisutil.RedisChannel(6379, '/foo', 'server') c.send_msg('c2s') s.send_msg('s2c') # list chan...
import json import shutil import os def load_coco_annotation_json(json_path, num = 'all'): anns = json.load(open(json_path)) if num == 'all': num = len(anns) return anns[:num] def copy_images(json_path, image_root, output_dir): anns = load_coco_annotation_json(json_path) # print(len(anns...
#!/usr/bin/env python import os import vtk from vtk.test import Testing from vtk.util.misc import vtkGetDataRoot VTK_DATA_ROOT = vtkGetDataRoot() # Read a field representing unstructured grid and display it (similar to blow.tcl) # create a reader and write out field data reader = vtk.vtkUnstructuredGridReader() reade...