text
stringlengths
1
927k
"""Tokens conftest""" from urllib.parse import urljoin import pytest import requests from threescale_api.resources import InvoiceState @pytest.fixture(scope="module") def api_client(testconfig): """ New and different 3scale api client is needed because the one we regularly use needs token upon creation a...
#!/usr/bin/env python map3 = {"filename": "map3.jpg", "connections": { "Underground": [[1, 9, 46], [13, 23, 22, 34, 47, 46], [13, 50, 67], [13, 14, 15, 16, 29, 55, 71, 89], [46, 45, 58, 7...
# Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from __future__ import print_function from __future__ import division from __future__ import absolute_import import json import unittest import webapp2 imp...
# beam11.py # UNITS: METRIC (meters & kN) from lib.beams import * import numpy as np # Node coordinates (modeled with 4 nodes) nodes = np.array([[0], [4], [6], [11]]) # Member/element connection matrix members = np.array([[1, 2], [2, 3], [3, 4]]) # Pre-define arrays to contain each members n = len(nodes) # nu...
from setuptools import setup setup( name='meson-cmake-wrapper', version='0.3.2', description='Build system wrapper that provides Meson integration in CMake IDE\'s', author='Niclas Moeslund Overby', author_email='noverby@prozum.dk', url='http://github.com/prozum/meson-cmake-wrapper', package...
# -*- coding: UTF-8 -*- import datetime import logging import re import time import traceback import simplejson as json from django.contrib.auth.decorators import permission_required from django.db import connection, OperationalError from django.db.models import Q from django.http import HttpResponse from common.confi...
from flask import render_template from . import main @main.app_errorhandler(404) def four_Ow_four(error): """funtion to render the 404 error page """ return render_template('fourOwfour.html'),404
# Copyright 2015 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 law or agreed to in writing, ...
# -*- coding: utf-8 -*- u""" greenCageDeformer を作成し、ターゲットとケージをバインドするスクリプト例。 ケージ(一つのmesh)、ターゲット(任意のシェイプ、部分的なポイントや複数も可) の順に選択してスクリプトを実行するとバインドされる。 """ import maya.cmds as cmds def doit(cage_tgt=None): if not cage_tgt: cage_tgt = cmds.ls(sl=True, o=True) cage = cage_tgt[0] tgt = cage_tgt[1:] cm...
from array import array from random import randint from math import log, e, ceil from itertools import izip class CountMinSketch(object): def __init__(self, w=None, d=None, delta=None, epsilon=None): """ CountMinSketch is an implementation of the count min sketch algorithm that probabilistically counts string ...
import numpy as np import pandas as pd import matplotlib.pyplot as plt data = pd.read_csv("ex1data1.txt",names = ['population','profit']) x = data.population y = data.profit "初始化,所有变量都是matrix" df = data.copy()#因为insert会改变原数组,所以先复制一份,坑1. df.insert(0,"one",1) X = df.iloc[:,0:df.shape[1]-1] y = df.iloc[:,df.shape[1]-1:df....
from collections import namedtuple from enum import Enum from iconsdk.utils.convert_type import convert_hex_str_to_bytes, convert_hex_str_to_int def addVersion(key, value, new_obj): new_obj[key] = value if value != '' else 2 def convert_data_content_to_bytes(key, value, new_obj): if new_obj["dataType"] == ...
from ConfigSpace import Configuration import numpy as np from smac.initial_design.initial_design import InitialDesign from smac.tae.execute_ta_run import ExecuteTARun, StatusType from smac.stats.stats import Stats from smac.utils.io.traj_logging import TrajLogger from smac.scenario.scenario import Scenario from smac.u...
from sqlalchemy import Column, Integer, String, ForeignKey, Table, Text, Boolean, DateTime from sqlalchemy.orm import relationship, backref from sqlalchemy.ext.declarative import declarative_base from datetime import datetime from .app import Session from .api.slack import Slack as SlackApi from .util.crypto import ran...
import uvicorn from api_f import app if __name__ == "__main__": uvicorn.run(app, host="localhost", port=8000)
# BIAS CORRECTION import numpy as np import pandas as pd from scipy.stats import gamma from scipy.stats import norm from scipy.signal import detrend ''' Scaled distribution mapping for climate data This is a excerpt from pyCAT and the method after Switanek et al. (2017) containing the functions to perform a relative ...
""" Load or save values to a file. Shelves work well for storing data, but they are slow to access repeatedly - especially for large data sets. This module allows you to store data to a file and then load it back into the workspace. When the data is stored, a python module is also created as the "namespace for the da...
from typing import TYPE_CHECKING, List, Optional, Dict, Any from dis_snek.client.const import MISSING from dis_snek.client.utils.attr_utils import define, field from dis_snek.client.utils.converters import optional from dis_snek.models.discord.asset import Asset from dis_snek.models.discord.enums import ApplicationFla...
#!/usr/bin/struture_function1 python # File: train_tp.py # Author: Yasmeen George import tensorflow as tf #from tensorflow import keras import argparse from tensorpack.tfutils.summary import * from oct_dataflow_tp import * import tensorflow.contrib.slim as slim from keras import backend as K from contextlib import con...
from django.forms import BooleanField, ModelForm, ValidationError from django.utils.translation import gettext_lazy as _ from pretalx.schedule.models import Schedule class ScheduleReleaseForm(ModelForm): notify_speakers = BooleanField( label=_('Notify speakers of changes'), required=False, initial=True ...
# Copyright 2016 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...
#----------------------------------------------------------------------------- # Copyright (c) 2012 - 2018, Anaconda, Inc. All rights reserved. # # Powered by the Bokeh Development Team. # # The full license is in the file LICENSE.txt, distributed with this software. #---------------------------------------------------...
# 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 ...
import json from django.contrib.gis.db.models.fields import BaseSpatialField from django.contrib.gis.db.models.functions import Distance from django.contrib.gis.db.models.lookups import DistanceLookupBase, GISLookup from django.contrib.gis.gdal import GDALRaster from django.contrib.gis.geos import GEOSGeometry from dj...
import numpy as np import pandas as pd from ela.textproc import EASTING_COL, NORTHING_COL, DEPTH_FROM_AHD_COL, DEPTH_FROM_COL, DEPTH_TO_AHD_COL, DEPTH_TO_COL, BORE_ID_COL KNN_WEIGHTING = 'distance' from sklearn import neighbors def read_raster_value(dem,band_1,easting,northing): """Read a value in a raster gri...
# encoding: utf-8 """ Represents a connection to the SLB service. """ import warnings import six import time import json from footmark.connection import ACSQueryConnection from footmark.slb.regioninfo import RegionInfo from footmark.slb.securitygroup import SecurityGroup from footmark.exception import SLBResponseErr...
# 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 use ...
"""empty message Revision ID: 166ae4251208 Revises: Create Date: 2020-09-10 11:25:13.286571 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '166ae4251208' down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands auto gene...
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import numpy as np import torch as T import logging import math import json from utils import print_rank from azureml.core import Run from scipy.special import betainc, betaln run = Run.get_context() def compute_LDP_noise_std(eps, max_sensitivi...
import jvcr class InputEx: def __init__(self, release_time=0.2) -> None: self.release_time = release_time self._history = {} def btnp(self, id, player_id=0): if jvcr.btn(id, player_id): time_not_pressed = self._history.get(id, self.release_time + 0.1) if time_n...
import numpy as np import xarray as xr airds = xr.tutorial.open_dataset("air_temperature").isel(time=slice(4), lon=slice(50)) airds.air.attrs["cell_measures"] = "area: cell_area" airds.air.attrs["standard_name"] = "air_temperature" airds.coords["cell_area"] = ( xr.DataArray(np.cos(airds.lat * np.pi / 180)) * x...
# coding=utf-8 import os import numpy as np import pandas as pd from sklearn.preprocessing import MaxAbsScaler class data(object): def __init__(self, workpath, label_number, features_norm=False, Standardization=False, discretization=0, run_model='Train', train_file='', validation_file='', test_fi...
# Copyright (c) 2018 Red Hat, Inc. # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) try: from botocore.exceptions import BotoCoreError, ClientError except ImportError: pass # Handled by the calling module HAS_MD5 = True try: from hashlib import md5 except Imp...
from django.conf.urls.static import static from django.contrib import admin from django.urls import path, include from django.conf import settings import api.core.views urlpatterns = [ path("healthcheck/", include("health_check.urls")), path("applications/", include("api.applications.urls")), path("audi...
# Copyright 2014 Scalyr 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 writing, so...
import gym import numpy as np from stable_baselines3.ddpg.policies import MlpPolicy from stable_baselines3.common.noise import NormalActionNoise, OrnsteinUhlenbeckActionNoise from stable_baselines3 import DDPG from stable_baselines3.common.monitor import Monitor from env import Stock from utils.callbacks import getB...
from Minigames.Minigame import Minigame from TimerHelper import TimerHelper class Sabotage3(Minigame): def __init__(self, parent,sabotagedStation): super().__init__(parent) self.parent = parent self.__target_station = sabotagedStation self.alreadyScanned = False def update(sel...
from cc3d import CompuCellSetup from .clusterMitosisSteppables import VolumeParamSteppable from .clusterMitosisSteppables import MitosisSteppableClusters CompuCellSetup.register_steppable(steppable=VolumeParamSteppable(frequency=10)) CompuCellSetup.register_steppable(steppable=MitosisSteppableClusters(frequency=10)) ...
def bf(a: bool) -> bool: return not a
## Takes Pickle Files and Exports Them to CSVs import pandas as pd source_path = "Season_pickles/" destination_path = "" filenames = [str(i) + '.pkl' for i in range(2010,2020)] seasons = ['df_' + str(i) for i in range(10,20)] season_dataframes = {} for i in list(zip(filenames, seasons)): path = source_path ...
import torch import torch.nn as nn from torch.nn import BatchNorm1d as _BatchNorm1d from torch.nn import BatchNorm2d as _BatchNorm2d from torch.nn import BatchNorm3d as _BatchNorm3d """ BatchNorm variants that can be disabled by removing all parameters and running stats """ def has_running_stats(m): return getat...
# -*- encoding: utf-8 -*- from __future__ import unicode_literals import requests from requests_oauthlib import OAuth1 from urlparse import parse_qs import json import time global m m=1 file1 = open("/Users/anandpopat/Downloads/a/syria_tr.json","a") file2 = open("/Users/anandpopat/Downloads/a/syria_tr2.json","a") REQ...
from typing import Dict from spinta import commands from spinta.components import Config from spinta.components import Node from spinta.manifests.components import Manifest @commands.get_error_context.register(Config) def get_error_context(config: Config, *, prefix='this') -> Dict[str, str]: return { 'co...
from flask import Flask, render_template, redirect import pymongo import scrape_mars app = Flask(__name__) # Set up pymongo connection and link db client = pymongo.MongoClient('mongodb://localhost:27017') db = client.mission_to_mars_2 listings = db.listings @app.route("/") def index(): listings = mongo.db.listin...
import os import pathlib import urllib.request import subprocess os.system("chcp 65001") current_directory = pathlib.Path.cwd() print("Current Directory: " + str(current_directory)) os.system("vswhere.exe -latest -property installationPath > temp.txt") file = open("temp.txt") vs_path = pathlib.Path(file.read().strip...
import unicodedata replacement_character = unicodedata.lookup('REPLACEMENT CHARACTER') spaces = list(map(unicodedata.lookup, [ 'SPACE', 'NO-BREAK SPACE', 'THIN SPACE', 'IDEOGRAPHIC SPACE', ])) def is_uppercase(codepoint): return unicodedata.category(codepoint) == 'Lu'
from .base import * from .vanilla_vae import * from .vanilla_vae_label import * from .vanilla_vae_norm import * from .gamma_vae import * from .beta_vae import * from .wae_mmd import * from .cvae import * from .hvae import * from .vampvae import * from .iwae import * from .dfcvae import * from .mssim_vae import MSSIMVAE...
from typing import List, Union import syft from syft.generic.frameworks.hook.hook_args import one from syft.generic.frameworks.hook.hook_args import register_type_rule from syft.generic.frameworks.hook.hook_args import register_forward_func from syft.generic.frameworks.hook.hook_args import register_backward_func from...
from panther_base_helpers import IN_PCI_SCOPE, deep_get def policy(resource): if not IN_PCI_SCOPE(resource): return True if not resource['TimeToLiveDescription']: return False return deep_get(resource, 'TimeToLiveDescription', 'TimeToLiveStatus') == 'ENABLED'
minConnections="10" maxConnections="80" connectionTimeout="60" unusedTimeout="300" webSphereDefaultIsolationLevel="2" statementCacheSize="100" internalds="DefaultEJBTimerDataSource,DefaultEJBTimerDataSource,OTiSDataSource" def modifyProps(ds_confid): propertySet = AdminConfig.showAttribute(ds_confid,'propertySet...
from iaso.test import APITestCase from iaso import models as m class SetupAccountApiTestCase(APITestCase): @classmethod def setUpTestData(cls): account = m.Account(name="Zelda") source = m.DataSource.objects.create(name="Korogu") cls.source = source version = m.SourceVersion.ob...
import re import sys from collections import defaultdict from typing import TYPE_CHECKING, AbstractSet, List, NamedTuple, Optional from dagster.core.definitions.dependency import DependencyStructure, Node from dagster.core.errors import DagsterExecutionStepNotFoundError, DagsterInvalidSubsetError from dagster.utils im...
class Solution: def findMin(self, nums: List[int]) -> int: left, right = 0, len(nums) - 1 while left < right: mid = (left + right) // 2 if nums[mid] < nums[right]: right = mid else: left = mid + 1 return nums[left]
#!/usr/bin/env python3 # Copyright (c) 2017-2018 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test wallet replace-by-fee capabilities in conjunction with the fallbackfee.""" from test_framework.tes...
r""" Points for products of projective spaces This class builds on the projective space class and its point and morphism classes. EXAMPLES: We construct products projective spaces of various dimensions over the same ring.:: sage: P1xP1.<x,y, u,v> = ProductProjectiveSpaces(QQ, [1, 1]) sage: P1xP1([2, 1, 3, 1...
from django.contrib.auth import get_user_model from django.urls import reverse from django.test import TestCase from rest_framework import status from rest_framework.test import APIClient from core.models import Ingredient from recette.serializers import IngredientSerializer INGREDIENT_URL = reverse('recette:ingredi...
import os import shutil from conans import ConanFile, tools, Meson, RunEnvironment, CMake from conans.errors import ConanException class TestPackageConan(ConanFile): settings = "os", "compiler", "build_type", "arch" generators = "qt", "cmake", "cmake_find_package_multi", "cmake_find_package", "pkg_config", "...
"""DO NOT EDIT - generated by make_size_report.py """ OPTIMIZED_JS_LIST = [ "//transpiler/javatests/com/google/j2cl/transpiler/integration/abstractinnerclass:optimized_js", "//transpiler/javatests/com/google/j2cl/transpiler/integration/abstractinnerclass:optimized_js.esnext", "//transpiler/javatests/com/go...
import copy import numpy import string import time import torch import tqdm from draugr.numpy_utilities import Split from draugr.python_utilities import ( rgb_drop_alpha_batch_nhwc, torch_vision_normalize_batch_nchw, ) from draugr.torch_utilities import ( TorchEvalSession, TorchTrainSession, global_...
import dataclasses import pytest from pypendency.backend.neo4j.neo import Neo4jBackend from pypendency.backend.neo4j.cypher import Credentials from pypendency.backend.neo4j.cypher import CypherDialect from pypendency.backend.neo4j.cypher import graph_storage @dataclasses.dataclass() class FakeGraph: id = "g1" ...
import pickle from typing import List import numpy as np from rdkit.Chem import Mol from rdkit.Chem.Descriptors import ExactMolWt from reinvent_chemistry import Descriptors from reinvent_scoring.scoring.component_parameters import ComponentParameters from reinvent_scoring.scoring.score_components import BaseScoreCom...
from matplotlib import pyplot as plt from ctapipe.visualization import CameraDisplay import numpy as np from matplotlib.backends.backend_pdf import PdfPages from ctapipe_io_lst import load_camera_geometry from ctapipe.coordinates import EngineeringCameraFrame # read back the monitoring containers written with the tool...
import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # Suppress TensorFlow logging (1) import pathlib import tensorflow as tf import sys tf.get_logger().setLevel('ERROR') # Suppress TensorFlow logging (2) import time from object_detection.utils import label_map_util from object_detection.utils import visual...
#!/usr/bin/env python3 # Copyright (c) 2014-2016 The Bitcoin Core developers # Copyright (c) Flo Developers 2013-2018 # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test the wallet backup features. Test case is: 4 nodes. 1 2 a...
""" Problem 1 --------- Description for problem 1. """ import unittest def foo(): pass class TestFoo(unittest.TestCase): def test_foo(self): pass if __name__ == '__main__': unittest.main()
from urllib.parse import urlparse, urlunparse result = urlparse('https://search.jd.com/Searchprint;hello?keyword=Python从菜鸟到高手&enc=utf-8#comment') print('scheme:', result.scheme) print('netloc:', result.netloc) print('path:', result.path) print('params:', result.params) print('query:', result.query) print('fragment:',...
# coding: utf-8 """ PITViewMembership.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 conditions are met...
######################## ## Author: Reinan Br. ## ## Date_init:01/07/21 ## ######################## from qfunction import q_sin,q_exp,q_cos,radian,limit import numpy as np from numpy import sqrt,array from math import atan ############ quantum equations ############# def q_rho(u,q=1,cpx=False,israd=True): u = radian(u...
import contextlib import itertools import os import pickle import shutil import sys import tempfile import warnings import dask.array as da import mock import numpy as np import pytest import rasterio import xarray as xr from affine import Affine from numpy.testing import assert_almost_equal from rasterio.errors impor...
""" You are given a tree(a simple connected graph with no cycles). The tree has N nodes numbered from 1 to N and is rooted at node 1. Find the maximum number of edges you can remove from the tree to get a forest such that each connected component of the forest contains an even number of nodes. Constraints 2 <= 2 <= 1...
# makes a string of 50 equals signs for a line break separator = "=" * 50 if True: print("hi") else: print("no") # creates a 2d list with 10 rows car_park = [[] for i in range(10)] # filling the car park for i in range(10): for j in range(6): car_park[i].append("E") # e stands for empty # creates the interfa...
# -*- coding: utf-8 -*- """Functionality for parsing IRIs.""" from typing import List, Mapping, Optional, Tuple, Union from .resolve import parse_curie from .resource_manager import prepare_prefix_list from .uri_format import get_prefix_map __all__ = [ "curie_from_iri", "parse_iri", "parse_obolibrary_pu...
# -*- coding: utf-8 -*- # import wptools # page = wptools.page('Dog') # page.get_more() # # # from wikitools import wiki # from wikitools import category # # site = wiki.Wiki("https://en.wikipedia.org/w/api.php?action=query&titles=Stack%20Overflow&prop=categories&clshow=!hidden") # site.login("username", "password") # ...
"""graph_saint dataset.""" import json import os from typing import Dict import numpy as np import scipy.sparse as sp import tensorflow as tf import tensorflow_datasets as tfds import gdown _DESCRIPTION = """\ Datasets used in/provided by [GraphSAINT](https://github.com/GraphSAINT/GraphSAINT).""" _CITATION = """\ ...
import os import scrapy from scrapy.crawler import CrawlerProcess import requests from disaster_data.sources.noaa_coast.utils import get_geoinfo, get_fgdcinfo class NoaaImageryCollections(scrapy.Spider): name = 'noaa-coast-imagery-collections' start_urls = [ 'https://coast.noaa.gov/htdata/raster2/...
'''Drawer Widget to hold the main window and the menu/hidden section that can be swiped in from the left. This Menu would be only hidden in phone mode and visible in Tablet Mode. This class is specifically in lined to save on start up speed(minimize i/o). ''' from kivy.app import App from kivy.factory import Factory ...
# Copyright 2018 Analytics Zoo 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 i...
from ..form import zope_i18n_pattern_to_jquery_pattern from datetime import datetime from icemac.addressbook.interfaces import IKeyword from icemac.addressbook.testing import WebdriverPageObjectBase, Webdriver from mock import patch, Mock from pytz import utc, timezone from selenium.webdriver.common.by import By from s...
import asyncio import aiohttp import time import sys try: from aiohttp import ClientError except: from aiohttp import ClientProxyConnectionError as ProxyConnectionError from proxypool.db import RedisClient from proxypool.setting import * class Tester(object): def __init__(self): self.redis = Redis...
#!/bin/python3 import sys import json import subprocess import random import string # for running this test make sure that you have a post with id = 1 # usage: ./test_authors.py | grep False # (should produce no input) def randomstring(length): letters = string.ascii_lowercase return ''.join(random.choice(lett...
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # This module's classes provide an interface to mojo modules. Modules are # collections of interfaces and structs to be used by mojo ipc clients and # server...
ROOT_MNIST = '/tmp2/MNIST' ROOT_CIFAR = '/tmp2/CIFAR' ROOT_EMNIST = '/tmp2/EMNIST' ROOT_CELEBA = '/tmp2/celebA/CelebA64/CelebA'
# encoding: utf-8 from __future__ import absolute_import, division, print_function, unicode_literals import copy import threading import warnings from django.core.exceptions import ImproperlyConfigured from django.utils.encoding import force_text from django.utils.six import with_metaclass from haystack import conn...
import pytest from rlo import factory @pytest.mark.parametrize("use_subtree_match_edges", [True, False]) @pytest.mark.parametrize("loss", ["pinball=0.6", "huber"]) def test_torch_model_from_config(use_subtree_match_edges, loss): # Check we can construct a Model config = { "num_embeddings": 3, ...
# # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # ...
from .core import IPFSFileSystem from .async_ipfs import AsyncIPFSFileSystem from fsspec import register_implementation from ._version import get_versions __version__ = get_versions()['version'] del get_versions # register_implementation(IPFSFileSystem.protocol, IPFSFileSystem) register_implementation(AsyncIPFSFileSy...
import os import deepchem as dc import numpy as np import pytest def load_unlabelled_data(): current_dir = os.path.dirname(os.path.abspath(__file__)) featurizer = dc.feat.CircularFingerprint(size=1024) tasks = [] input_file = os.path.join(current_dir, "../../data/tests/no_labels.csv") loader = dc.data.CSVLo...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Dec 6 15:40:14 2017 Functions needed to read the data from different databases @author: anazabal, olmosUC3M, ivaleraM """ import csv import os import torch import numpy as np from sklearn.metrics import mean_squared_error def read_data(data_file, t...
# -*- encoding: utf-8 -*- import hashlib import hmac import json import time try: # from urllib.request import urlopen from urllib.parse import quote except: # For Python 2 from urllib import quote # from urllib import urlopen import base64 import requests from Crypto.Cipher import AES from .exceptio...
import mdtraj as md import MDAnalysis as mda import numpy as np import factory from interface import TrajectoryAdapter # We made an abstract class,that both packages can be handled in the same way. Each package exported information from pdb files in different ways so we will have those be private variables. class MD...
# -*- coding: utf-8 -*- ''' export to baidu kity minder json The kityminder website : https://github.com/fex-team/kityminder from kityminder to json: In brower console type: editor.minder.exportData("json").fulfillValue from json to kityminder: type: editor.minder.importData("json","The json string"...
def maior (x,y): if x>y: print(x) else: print(y)
""" Code related to working with textures. """ import math from pathlib import Path import PIL.Image import PIL.ImageOps import PIL.ImageDraw from typing import Optional from typing import List from typing import Union from arcade import lerp from arcade import RectList from arcade import Color from arcade import c...
#! /usr/bin/python # -*- coding: utf-8 -*- """You will learn. 1. How to save data into TFRecord format file. 2. How to read data from TFRecord format file by using Queue and Thread. Reference: ----------- English : https://indico.io/blog/tensorflow-data-inputs-part1-placeholders-protobufs-queues/ https://ww...
from itertools import product import pytest import numpy as np from skimage.segmentation import slic from skimage._shared import testing from skimage._shared.testing import test_parallel, assert_equal @test_parallel() def test_color_2d(): rnd = np.random.RandomState(0) img = np.zeros((20, 21, 3)) img[:1...
#!/usr/bin/env python # Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you ma...
# Licensed under a 3-clause BSD style license - see LICENSE.rst # TODO: Test FITS parsing # STDLIB import io import re import gzip import base64 import codecs import urllib.request # THIRD-PARTY import numpy as np from numpy import ma # LOCAL from astropy.io import fits from astropy import __version__ as astropy_ver...
# -*- coding: utf-8 -*- """This code is a part of Hydra Toolkit .. module:: hydratk.translation.lib.network.ftp.client.en.messages :platform: Unix :synopsis: English language translation for FTP client messages .. moduleauthor:: Petr Rašek <bowman@hydratk.org> """ language = { 'name': 'English', 'ISO-...
# encoding: utf-8 """ @author: liaoxingyu @contact: liaoxingyu2@jd.com """ import copy import itertools from collections import defaultdict from typing import Optional import numpy as np from torch.utils.data.sampler import Sampler from fastreid.utils import comm def no_index(a, b): assert isinstance(a, list)...
import numpy as np import cv2 img = cv2.imread('exercise_images/lion.jpg') img_yuv = cv2.cvtColor(img, cv2.COLOR_BGR2YUV) # equalize the histogram of the Y channel img_yuv[:,:,1] = cv2.equalizeHist(img_yuv[:,:,0]) # convert the YUV image back to RGB format img_output = cv2.cvtColor(img_yuv, cv2.COLOR_YUV2BGR) res =...