content
stringlengths
1
1.04M
input_ids
listlengths
1
774k
ratio_char_token
float64
0.38
22.9
token_count
int64
1
774k
import logging import asyncio import os from pyrogram import Client, filters logging.basicConfig( format='%(levelname)5s - %(name)s - %(message)s', level=0 ) LOGGER = logging.getLogger("root") LOGGER.setLevel(logging._nameToLevel[os.environ.get("log_level", "NOTSET").upper()]) string_session = os.environ.get("string_session") api_id = os.environ.get("api_id") api_hash = os.environ.get("api_hash") group_a = int(os.environ.get("group_a")) group_b = int(os.environ.get("group_b")) password = os.environ.get("password", None) client = Client( string_session, int(api_id), api_hash, password=password ) basic_filters = filters.group & ~filters.edited & ~filters.service @client.on_message(filters.chat(group_a) & basic_filters) @client.on_message(filters.chat(group_b) & basic_filters) if __name__ == "__main__": try: loop = asyncio.get_running_loop() except RuntimeError: loop = asyncio.get_event_loop() loop.run_until_complete(client.run())
[ 11748, 18931, 198, 11748, 30351, 952, 198, 11748, 28686, 198, 198, 6738, 12972, 39529, 1330, 20985, 11, 16628, 628, 198, 6404, 2667, 13, 35487, 16934, 7, 198, 220, 220, 220, 5794, 11639, 4, 7, 5715, 3672, 8, 20, 82, 532, 4064, 7, 36...
2.539043
397
# Copyright 2020 Red Hat, 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 applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo_config import cfg from oslo_utils import uuidutils from octavia.image.drivers.noop_driver import driver import octavia.tests.unit.base as base CONF = cfg.CONF
[ 2, 15069, 12131, 2297, 10983, 11, 3457, 13, 1439, 2489, 10395, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 345, 743, 198, 2, 407, 779, 428, 2393, 2845, 287, 11846, 351, ...
3.674641
209
import sys, os, shutil import subprocess from osgeo import gdal from osgeo.gdalconst import * import tempfile import numpy as np sys.path.insert(1, os.path.dirname(os.path.realpath(__file__)) + '/../') from GeoRefPars import GeoRefPars # Removes vertical offset for an for a ground point cloud with uncertain georeferncing by comparing its elevation with # that from reference ground point cloud (requires that the clouds match up reasonably closely in the horizontal) # # Usage: RemoveVerticalOffset.py <options> <Input Cloud> <Reference Cloud> <Suffix> # # Input Cloud: Path to input ground point cloud # Refernce Cloud: Path to the reference ground point cloud # Suffix: suffix to be added to the outputted las file (Warning, if set to "None", will overwrite the input file!) # Options: # -a, --additional_clouds: Specfies additional clouds (separated by commas) to perform the same adjustment for (for example, # to adjust a point cloud containing canopy points using the same adjustment that is applied to the ground point cloud) # # Note that in addition to the dependencies listed above, this code assumes that the gdal and Fusion command line tools are # installed and are accessable via the command line (e.g. on the system path), as this script makes subprocess calls to them # # Created by Patrick Broxton # Updated 6/30/2020 # Read the georeferencing information and fusion parameters (crs, fusion_parameters, cellsize) = GeoRefPars() # Optional parameters def optparse_init(): """Prepare the option parser for input (argv)""" from optparse import OptionParser, OptionGroup usage = 'Usage: %prog [options] input_file(s) [output]' p = OptionParser(usage) p.add_option('-a', '--additional_clouds', dest='additional_clouds', help='Additional clouds to apply the correction to') return p if __name__ == '__main__': # Parse the command line arguments argv = gdal.GeneralCmdLineProcessor( sys.argv ) parser = optparse_init() options,args = parser.parse_args(args=argv[1:]) incloud_ground = args[0] # Input ground point cloud ref_cloud_ground = args[1] # Reference ground surface file out_suffix = args[2] # Output file suffix (for saved files) additional_clouds = options.additional_clouds # Check for the existance of the input and reference clouds path_errors = False if not os.path.exists(incloud_ground): print('Error: ' + incloud_ground + ' does not exist!') path_errors = True if not os.path.exists(ref_cloud_ground): print('Error: ' + ref_cloud_ground + ' does not exist!') path_errors = True if path_errors == True: sys.exit() # Create a temporary working directory` working_dir = tempfile.mktemp() if not os.path.exists(working_dir): os.makedirs(working_dir) # Create Surface files for the SFM ground point cloud in the temporary directory (using Fusion's GridSurfaceCreate program) cmd = 'GridSurfaceCreate "' + working_dir + '/surf_sfm.dtm" ' + str(cellsize) + ' ' + fusion_parameters + ' "' + incloud_ground + '"' print(cmd) subprocess.call(cmd, shell=True) # Convert from dtm format to asc format (so it can be read by gdal) cmd = 'DTM2ASCII "' + working_dir + '/surf_sfm.dtm" "' + working_dir + '/surf_sfm.asc"' print(cmd) subprocess.call(cmd, shell=True) # Assign georeferencing information using a gdal virtual raster layer cmd = 'gdalbuildvrt -a_srs "EPSG:' + str(crs) + '" "' + working_dir + '/surf_sfm.vrt" "' + working_dir + '/surf_sfm.asc"' print(cmd) subprocess.call(cmd, shell=True) # Open the dataset inDs = gdal.Open(working_dir + '/surf_sfm.vrt') if inDs is None: print('Could not open ' + working_dir + '/surf_sfm.vrt') sys.exit(1) # Get raster characteristics width = inDs.RasterXSize height = inDs.RasterYSize gt = inDs.GetGeoTransform() ulx = gt[0] lry = gt[3] + width*gt[4] + height*gt[5] lrx = gt[0] + width*gt[1] + height*gt[2] uly = gt[3] dx = gt[1] dy = -gt[5] # Read the ground surface file band = inDs.GetRasterBand(inDs.RasterCount) sfm_z = band.ReadAsArray() sfm_z[sfm_z == band.GetNoDataValue()] = np.nan inDs = None # Create Surface files for the reference point cloud in the temporary directory (using Fusion's GridSurfaceCreate program) cmd = 'GridSurfaceCreate "' + working_dir + '/surf_lidar.dtm" ' + str(cellsize) + ' ' + fusion_parameters + ' "' + ref_cloud_ground + '"' print(cmd) subprocess.call(cmd, shell=True) # Convert from dtm format to asc format (so it can be read by gdal) cmd = 'DTM2ASCII "' + working_dir + '/surf_lidar.dtm" "' + working_dir + '/surf_lidar.asc"' print(cmd) subprocess.call(cmd, shell=True) # Assign georeferencing information using a gdal virtual raster layer te_str = str(ulx) + ' ' + str(lry) + ' ' + str(lrx) + ' ' + str(uly) cmd = 'gdalbuildvrt -te ' + te_str + ' -a_srs "EPSG:' + str(crs) + '" "' + working_dir + '/surf_lidar.vrt" "' + working_dir + '/surf_lidar.asc"' print(cmd) subprocess.call(cmd, shell=True) # Open the dataset inDs2 = gdal.Open(working_dir + '/surf_lidar.vrt') if inDs2 is None: print('Could not open ' + working_dir + '/surf_lidar.vrt') sys.exit(1) # Read the reference cloud band = inDs2.GetRasterBand(inDs2.RasterCount) lidar_z = band.ReadAsArray() lidar_z[lidar_z == band.GetNoDataValue()] = np.nan inDs2 = None # Figure out the average difference diff = sfm_z - lidar_z vcorr = np.nanmean(diff) # Name the output file (depending on whether a suffix to be added) if out_suffix == 'None': outcloud = incloud_ground[:-4] + '.laz' else: outcloud = incloud_ground[:-4] + '_' + out_suffix + '.laz' # Apply the vertical offset to the input point cloud (using Fusion's clipdata program) cmd = 'clipdata /height /biaselev:' + str(-vcorr) + ' "' + incloud_ground + '" "' + outcloud + '" ' + str(ulx) + ' ' + str(lry) + ' ' + str(lrx) + ' ' + str(uly) print(cmd) subprocess.call(cmd, shell=True) # Apply the same vertical offset to any additional point clouds if additional_clouds != None: AdditionalClouds = additional_clouds.split(',') for incloud in AdditionalClouds: # If necissary, apply a suffix to these additional clouds if out_suffix == 'None': outcloud = incloud[:-4] + '.laz' else: outcloud = incloud[:-4] + '_' + out_suffix + '.laz' # Apply the vertical offset to each additional cloud cmd = 'clipdata /height /biaselev:' + str(-vcorr) + ' "' + incloud + '" "' + outcloud + '" ' + str(ulx) + ' ' + str(lry) + ' ' + str(lrx) + ' ' + str(uly) print(cmd) subprocess.call(cmd, shell=True) # Remove the temporary directory (including any orphaned files) if os.path.exists(working_dir): shutil.rmtree(working_dir)
[ 11748, 25064, 11, 28686, 11, 4423, 346, 201, 198, 11748, 850, 14681, 201, 198, 6738, 28686, 469, 78, 1330, 308, 31748, 201, 198, 6738, 28686, 469, 78, 13, 21287, 282, 9979, 1330, 1635, 201, 198, 11748, 20218, 7753, 201, 198, 11748, 29...
2.444887
3,012
import unittest from unittest import mock from kinto.core.testing import DummyRequest from kinto.plugins.openid import OpenIDConnectPolicy from kinto.plugins.openid.utils import fetch_openid_config from .. import support
[ 11748, 555, 715, 395, 198, 6738, 555, 715, 395, 1330, 15290, 198, 198, 6738, 479, 20424, 13, 7295, 13, 33407, 1330, 360, 13513, 18453, 198, 6738, 479, 20424, 13, 37390, 13, 9654, 312, 1330, 4946, 2389, 13313, 36727, 198, 6738, 479, 20...
3.462687
67
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition) available. Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://opensource.org/licenses/MIT Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from backend.helm.app.utils import remove_updater_creator_from_manifest FAKE_MANIFEST_YAML = """ apiVersion: apps/v1\nkind: Deployment\nmetadata:\n name: test12-redis\n labels:\n app: bk-redis\n chart: bk-redis-0.1.29\n release: test12\n heritage: Helm\n io.tencent.paas.source_type: helm\n io.tencent.paas.projectid: xxx\n io.tencent.bcs.clusterid: BCS-K8S-00000\n io.tencent.bcs.namespace: test-tes123\n io.tencent.bcs.controller.type: Deployment\n io.tencent.bcs.controller.name: test12-redis\n annotations:\n io.tencent.paas.version: 0.1.29\n io.tencent.bcs.clusterid: BCS-K8S-00000\nspec:\n replicas: 1\n selector:\n matchLabels:\n app: bk-redis\n release: test12\n template:\n metadata:\n labels:\n app: bk-redis\n release: test12\n app-name: test-db\n io.tencent.paas.source_type: helm\n io.tencent.paas.projectid: xxx\n io.tencent.bcs.clusterid: BCS-K8S-00000\n io.tencent.bcs.namespace: test-tes123\n io.tencent.bcs.controller.type: Deployment\n io.tencent.bcs.controller.name: test12-redis\n spec:\n containers:\n - name: bk-redis\n image: /paas/test/test:latest\n imagePullPolicy: IfNotPresent\n env:\n - name: test\n value: test\n - name: test\n value: test123\n - name: test\n value: ieod\n - name: test\n value: test\n - name: test\n value: \"80\"\n - name: test\n value: \"true\"\n - name: test\n value: test\n - name: io_tencent_bcs_namespace\n value: test-tes123\n - name: io_tencent_bcs_custom_labels\n value: '{}'\n command:\n - bash -c\n ports:\n - name: http\n containerPort: 80\n protocol: TCP\n livenessProbe:\n httpGet:\n path: /\n port: http\n readinessProbe:\n httpGet:\n path: /\n port: http\n resources: {}\n imagePullSecrets:\n - name: paas.image.registry.test-tes123\n---\napiVersion: batch/v1\nkind: Job\nmetadata:\n name: test12-db-migrate\n labels:\n io.tencent.paas.source_type: helm\n io.tencent.paas.projectid: xxx\n io.tencent.bcs.clusterid: BCS-K8S-00000\n io.tencent.bcs.namespace: test-tes123\n io.tencent.bcs.controller.type: Job\n io.tencent.bcs.controller.name: test12-db-migrate\n annotations:\n io.tencent.paas.version: 0.1.29\n io.tencent.bcs.clusterid: BCS-K8S-00000\nspec:\n backoffLimit: 0\n template:\n metadata:\n name: test12\n labels:\n app.kubernetes.io/managed-by: Helm\n app.kubernetes.io/instance: test12\n helm.sh/chart: bk-redis-0.1.29\n io.tencent.paas.source_type: helm\n io.tencent.paas.projectid: xxx\n io.tencent.bcs.clusterid: BCS-K8S-00000\n io.tencent.bcs.namespace: test-tes123\n io.tencent.bcs.controller.type: Job\n io.tencent.bcs.controller.name: test12-db-migrate\n spec:\n restartPolicy: Never\n containers:\n - name: pre-install-job\n image: /paas/test/test:latest\n command:\n - /bin/bash\n - -c\n args:\n - python manage.py migrate\n env:\n - name: test\n value: test\n - name: test\n value: test\n - name: test\n value: test\n - name: test\n value: \"80\"\n - name: test\n value: \"true\"\n - name: test\n value: test\n - name: io_tencent_bcs_namespace\n value: test-tes123\n - name: io_tencent_bcs_custom_labels\n value: '{}'\n imagePullPolicy: Always\n imagePullSecrets:\n - name: paas.image.registry.test-tes123\n """ # noqa EXPECTED_MANIFEST_YAML = """ apiVersion: apps/v1\nkind: Deployment\nmetadata:\n name: test12-redis\n labels:\n app: bk-redis\n chart: bk-redis-0.1.29\n release: test12\n heritage: Helm\n io.tencent.paas.source_type: helm\n io.tencent.paas.projectid: xxx\n io.tencent.bcs.clusterid: BCS-K8S-00000\n io.tencent.bcs.namespace: test-tes123\n io.tencent.bcs.controller.type: Deployment\n io.tencent.bcs.controller.name: test12-redis\n annotations:\n io.tencent.paas.version: 0.1.29\n io.tencent.bcs.clusterid: BCS-K8S-00000\nspec:\n replicas: 1\n selector:\n matchLabels:\n app: bk-redis\n release: test12\n template:\n metadata:\n labels:\n app: bk-redis\n release: test12\n app-name: test-db\n io.tencent.paas.source_type: helm\n io.tencent.paas.projectid: xxx\n io.tencent.bcs.clusterid: BCS-K8S-00000\n io.tencent.bcs.namespace: test-tes123\n io.tencent.bcs.controller.type: Deployment\n io.tencent.bcs.controller.name: test12-redis\n spec:\n containers:\n - name: bk-redis\n image: /paas/test/test:latest\n imagePullPolicy: IfNotPresent\n env:\n - name: test\n value: test\n - name: test\n value: test123\n - name: test\n value: ieod\n - name: test\n value: test\n - name: test\n value: \"80\"\n - name: test\n value: \"true\"\n - name: test\n value: test\n - name: io_tencent_bcs_namespace\n value: test-tes123\n - name: io_tencent_bcs_custom_labels\n value: '{}'\n command:\n - bash -c\n ports:\n - name: http\n containerPort: 80\n protocol: TCP\n livenessProbe:\n httpGet:\n path: /\n port: http\n readinessProbe:\n httpGet:\n path: /\n port: http\n resources: {}\n imagePullSecrets:\n - name: paas.image.registry.test-tes123\n---\napiVersion: batch/v1\nkind: Job\nmetadata:\n name: test12-db-migrate\n labels:\n io.tencent.paas.source_type: helm\n io.tencent.paas.projectid: xxx\n io.tencent.bcs.clusterid: BCS-K8S-00000\n io.tencent.bcs.namespace: test-tes123\n io.tencent.bcs.controller.type: Job\n io.tencent.bcs.controller.name: test12-db-migrate\n annotations:\n io.tencent.paas.version: 0.1.29\n io.tencent.bcs.clusterid: BCS-K8S-00000\nspec:\n backoffLimit: 0\n template:\n metadata:\n name: test12\n labels:\n app.kubernetes.io/managed-by: Helm\n app.kubernetes.io/instance: test12\n helm.sh/chart: bk-redis-0.1.29\n io.tencent.paas.source_type: helm\n io.tencent.paas.projectid: xxx\n io.tencent.bcs.clusterid: BCS-K8S-00000\n io.tencent.bcs.namespace: test-tes123\n io.tencent.bcs.controller.type: Job\n io.tencent.bcs.controller.name: test12-db-migrate\n spec:\n restartPolicy: Never\n containers:\n - name: pre-install-job\n image: /paas/test/test:latest\n command:\n - /bin/bash\n - -c\n args:\n - python manage.py migrate\n env:\n - name: test\n value: test\n - name: test\n value: test\n - name: test\n value: test\n - name: test\n value: \"80\"\n - name: test\n value: \"true\"\n - name: test\n value: test\n - name: io_tencent_bcs_namespace\n value: test-tes123\n - name: io_tencent_bcs_custom_labels\n value: '{}'\n imagePullPolicy: Always\n imagePullSecrets:\n - name: paas.image.registry.test-tes123\n """ # noqa
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 24893, 1087, 318, 10607, 284, 1104, 262, 1280, 2723, 2055, 416, 1642, 5525, 241, 251, 165, 110, 116, 162, 247, 118, 12859, 239, 47, 7252, 50, 33176, 111, 2...
1.986059
4,232
x = 1 f() print("globally, x={}".format(x))
[ 87, 796, 352, 198, 198, 69, 3419, 198, 4798, 7203, 4743, 672, 453, 11, 2124, 34758, 92, 1911, 18982, 7, 87, 4008, 198 ]
1.956522
23
import socket if __name__ == "__main__": try: echo() except KeyboardInterrupt: exit()
[ 11748, 17802, 628, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 1949, 25, 198, 220, 220, 220, 220, 220, 220, 220, 9809, 3419, 198, 220, 220, 220, 2845, 31973, 9492, 3622, 25, 198, 220, 220, 220, ...
2.265306
49
try: __import__('pkg_resources').declare_namespace(__name__) except: import pkgutil __path__ = pkgutil.extend_path(__path__, __name__)
[ 28311, 25, 198, 220, 220, 220, 11593, 11748, 834, 10786, 35339, 62, 37540, 27691, 32446, 533, 62, 14933, 10223, 7, 834, 3672, 834, 8, 198, 16341, 25, 198, 220, 220, 220, 1330, 279, 10025, 22602, 198, 220, 220, 220, 11593, 6978, 834, ...
2.409836
61
import os.path import ConfigFile from Constants import * BLOCK = 'block' SLOPE = 'slope' CORNER = 'corner' EXTERIOR_DEFAULT = "Light Armor" EXTERIOR_CONFIG = { TYPE_SM: { BLOCK: "1 2", SLOPE: "1 2", CORNER: "1 2", }, TYPE_LG: { BLOCK: "1 2", SLOPE: "1 2", CORNER: "1 2", }, } INTERIOR_DEFAULT = "Interior Wall" INTERIOR_CONFIG = { TYPE_LG: { BLOCK: "1 1", }, } initialized = False materials = {}
[ 11748, 28686, 13, 6978, 198, 198, 11748, 17056, 8979, 198, 198, 6738, 4757, 1187, 1330, 1635, 198, 198, 9148, 11290, 796, 705, 9967, 6, 198, 8634, 32135, 796, 705, 6649, 3008, 6, 198, 44879, 21479, 796, 705, 10215, 1008, 6, 198, 198, ...
2.063107
206
from os import environ from typing import ContextManager, Optional, Union from aiohttp import request from discord.ext.commands.core import guild_only from src.data_clusters.configuration.server_vars import server from discord import Member, Reaction, Embed, channel, colour from discord.ext.commands import Cog, bot, command, cooldown, BucketType from DiscordUtils.Pagination import CustomEmbedPaginator
[ 6738, 28686, 1330, 551, 2268, 198, 6738, 19720, 1330, 30532, 13511, 11, 32233, 11, 4479, 198, 6738, 257, 952, 4023, 1330, 2581, 198, 6738, 36446, 13, 2302, 13, 9503, 1746, 13, 7295, 1330, 19806, 62, 8807, 198, 198, 6738, 12351, 13, 78...
3.805556
108
# http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html from __future__ import absolute_import # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery import app as celery_app
[ 2, 2638, 1378, 31628, 13, 7015, 88, 16302, 13, 2398, 14, 268, 14, 42861, 14, 28241, 14208, 14, 11085, 12, 20214, 12, 4480, 12, 28241, 14208, 13, 6494, 201, 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 201, 198, 201, 198, 2, ...
3.320988
81
import logging import time import torch from typing import Optional from chatty_goose.settings import NtrSettings from spacy.lang.en import English from transformers import T5ForConditionalGeneration, T5Tokenizer from .cqr import ConversationalQueryRewriter __all__ = ["Ntr"] class Ntr(ConversationalQueryRewriter): """Neural Transfer Reformulation using a trained T5 model"""
[ 11748, 18931, 198, 11748, 640, 198, 11748, 28034, 198, 6738, 19720, 1330, 32233, 198, 198, 6738, 8537, 774, 62, 2188, 577, 13, 33692, 1330, 399, 2213, 26232, 198, 6738, 599, 1590, 13, 17204, 13, 268, 1330, 3594, 198, 6738, 6121, 364, ...
3.574074
108
import collections import torch import PIL import pytorch_lightning as pl import numpy as np import torchvision.transforms.functional as F import webdataset as wds from pathlib import Path from torchvision import transforms as T from random import randint, choice from torch.utils.data import DataLoader from PIL import Image from io import BytesIO def web_dataset_helper(path): """ https://github.com/tgisaturday/dalle-lightning/blob/master/pl_dalle/loader.py """ if Path(path).is_dir(): DATASET = [ str(p) for p in Path(path).glob("**/*") if ".tar" in str(p).lower() ] # .name assert ( len(DATASET) > 0 ), "The directory ({}) does not contain any WebDataset/.tar files.".format(path) print( "Found {} WebDataset .tar(.gz) file(s) under given path {}!".format( len(DATASET), path ) ) elif ("http://" in path.lower()) | ("https://" in path.lower()): DATASET = f"pipe:curl -L -s {path} || true" print("Found {} http(s) link under given path!".format(len(DATASET), path)) elif "gs://" in path.lower(): DATASET = f"pipe:gsutil cat {path} || true" print("Found {} GCS link under given path!".format(len(DATASET), path)) elif ".tar" in path: DATASET = path print("Found WebDataset .tar(.gz) file under given path {}!".format(path)) else: raise Exception( "No folder, no .tar(.gz) and no url pointing to tar files provided under {}.".format( path ) ) return DATASET def build_table( x, perceiver, tokenize, indices, indices_data, device, knn, y=None, ctx=None, is_image=True, return_images=False, ): """im2txt table.""" table = [" || "] * len(x) x = perceiver.encode_image(x).float() x /= x.norm(dim=-1, keepdim=True) for (index, index_data) in zip(indices, indices_data): top_ind = index.search(x.cpu().numpy(), knn)[1] for idx in range(len(x)): results = [index_data[i] for i in top_ind[idx]] for r in results: table[idx] += r + " | " table = [r[:-1] + "|| " for r in table] if y: table = [table[idx] + y[idx] for idx in range(len(x))] if return_images: return table, x return table
[ 11748, 17268, 198, 11748, 28034, 198, 11748, 350, 4146, 198, 11748, 12972, 13165, 354, 62, 2971, 768, 355, 458, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 28034, 10178, 13, 7645, 23914, 13, 45124, 355, 376, 198, 11748, 3992, 19608, ...
2.193578
1,090
#! /usr/bin/env python """Londiste launcher. """ import sys, os, optparse, signal, skytools # python 2.3 will try londiste.py first... import sys, os.path if os.path.exists(os.path.join(sys.path[0], 'londiste.py')) \ and not os.path.isdir(os.path.join(sys.path[0], 'londiste')): del sys.path[0] from londiste import * __all__ = ['Londiste'] command_usage = """ %prog [options] INI CMD [subcmd args] commands: replay replay events to subscriber provider install installs modules, creates queue provider add TBL ... add table to queue provider remove TBL ... remove table from queue provider tables show all tables on provider provider add-seq SEQ ... add sequence to provider provider remove-seq SEQ ... remove sequence from provider provider seqs show all sequences on provider subscriber install installs schema subscriber add TBL ... add table to subscriber subscriber remove TBL ... remove table from subscriber subscriber add-seq SEQ ... add table to subscriber subscriber remove-seq SEQ ... remove table from subscriber subscriber tables list tables subscriber has attached to subscriber seqs list sequences subscriber is interested subscriber missing list tables subscriber has not yet attached to subscriber check compare table structure on both sides subscriber resync TBL ... do full copy again subscriber fkeys [pending|active] show fkeys on tables subscriber triggers [pending|active] show triggers on tables subscriber restore-triggers TBL [TGNAME ..] restore pending triggers subscriber register register consumer on provider's queue subscriber unregister unregister consumer on provider's queue compare [TBL ...] compare table contents on both sides repair [TBL ...] repair data on subscriber copy [internal command - copy table logic] """ if __name__ == '__main__': script = Londiste(sys.argv[1:]) script.start()
[ 2, 0, 1220, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 37811, 43, 623, 40833, 24008, 13, 198, 37811, 198, 198, 11748, 25064, 11, 28686, 11, 2172, 29572, 11, 6737, 11, 6766, 31391, 198, 198, 2, 21015, 362, 13, 18, 481, 1949, 300, ...
2.778061
784
# python3 import json import socket import sys from email.parser import Parser from functools import lru_cache from urllib.parse import parse_qs, urlparse, urlencode, quote import re # for regulars MAX_LINE = 64 * 1024 MAX_HEADERS = 100 if __name__ == '__main__': serv = Server() try: serv.serve_forever() except KeyboardInterrupt: pass
[ 2, 21015, 18, 198, 198, 11748, 33918, 198, 11748, 17802, 198, 11748, 25064, 198, 6738, 3053, 13, 48610, 1330, 23042, 263, 198, 6738, 1257, 310, 10141, 1330, 300, 622, 62, 23870, 198, 6738, 2956, 297, 571, 13, 29572, 1330, 21136, 62, 4...
2.717391
138
#!/usr/bin/env python3 import json import urllib3 import boto3 from botocore.exceptions import ClientError from boto3 import Session f = open("config.json", "r+") configObj = json.loads(f.read()) f.close() headers = { "Content-Type": "application/json", "api-secret-key": configObj["c1wsApiKey"], "api-version": "v1" } if __name__ == "__main__": main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 11748, 33918, 198, 11748, 2956, 297, 571, 18, 198, 11748, 275, 2069, 18, 198, 6738, 10214, 420, 382, 13, 1069, 11755, 1330, 20985, 12331, 198, 6738, 275, 2069, 18, 1330, 23575, 198...
2.554795
146
#!/usr/bin/env python3 # Note: This file became necessary as a workaround # since pyttsx3 is not thread-safe. # See https://github.com/nateshmbhat/pyttsx3/issues/8 # for further details. import pyttsx3 # id: 3 is french, 4 is german, 10 & 28 is english import sys text = str(sys.argv[1]) try: language = str(sys.argv[2]) except: language = "en" if language == "de": language_code = 4 elif language == "fr": language_code = 3 else: language_code = 10 engine = init_engine(language_code) say(text)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 2, 5740, 25, 770, 2393, 2627, 3306, 355, 257, 46513, 198, 2, 1201, 12972, 83, 912, 87, 18, 318, 407, 4704, 12, 21230, 13, 198, 2, 4091, 3740, 1378, 12567, 13, 785, 14, 7...
2.586207
203
# -*- coding: utf-8 -*- # Generated by Django 1.11.2 on 2017-11-22 17:13 from __future__ import unicode_literals import django.db.models.deletion from django.db import migrations, models
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2980, 515, 416, 37770, 352, 13, 1157, 13, 17, 319, 2177, 12, 1157, 12, 1828, 1596, 25, 1485, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, ...
2.73913
69
from rest_framework import generics from .serializers import TweetModelSerializer from ..models import Tweet from django.db.models import Q from rest_framework import permissions from .pagination import TweetsSetPagination from rest_framework.views import APIView from rest_framework.response import Response
[ 6738, 1334, 62, 30604, 1330, 1152, 873, 198, 6738, 764, 46911, 11341, 1330, 18752, 17633, 32634, 7509, 198, 6738, 11485, 27530, 1330, 18752, 198, 6738, 42625, 14208, 13, 9945, 13, 27530, 1330, 1195, 198, 6738, 1334, 62, 30604, 1330, 21627...
4.219178
73
from nltk.corpus import treebank from nltk.tree import Tree from nltk.stem import WordNetLemmatizer wnl = WordNetLemmatizer() from nltk.corpus import wordnet as wn import VerbMorph import PTBdata import pickle #selects first synonym import create2koriginal import copy if __name__ == "__main__": f = open('../../dictionaries/synonym.dict','rb') dict = pickle.load(f) """ for file in treebank.fileids(): for i in treebank.parsed_sents(file): print(i) ADJReplacement(i,dict) print(i) count += 1 if count == 5: break if count == 5: break """ trees = PTBdata.getalltrees('ptb-train.txt') trees.extend(PTBdata.getalltrees('ptb-test.txt')) trees.extend(PTBdata.getalltrees('ptb-valid.txt')) freqdict=makeFrequency(trees) print(freqdictselector(dict['angry'],freqdict,1)) count=0 for tree in trees: if len(tree.leaves()) < 5 or len(tree.leaves()) > 12 or not tree.label()[0] == 'S': continue j = copy.deepcopy(tree) FrequencySynonymReplacement(j,dict,freqdict,1) if tree.leaves()==j.leaves(): continue count += 1 if count < 30: pass #print(tree.leaves()) #print(j.leaves()) print(count)
[ 6738, 299, 2528, 74, 13, 10215, 79, 385, 1330, 5509, 17796, 198, 6738, 299, 2528, 74, 13, 21048, 1330, 12200, 198, 6738, 299, 2528, 74, 13, 927, 1330, 9678, 7934, 43, 368, 6759, 7509, 198, 675, 75, 796, 9678, 7934, 43, 368, 6759, ...
2.057315
663
import sys import os import json import time import post_to_server import argparse if __name__ == "__main__": main(sys.argv[1:])
[ 11748, 25064, 198, 11748, 28686, 198, 11748, 33918, 198, 11748, 640, 198, 11748, 1281, 62, 1462, 62, 15388, 198, 11748, 1822, 29572, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 1388, 7, 17597, ...
2.734694
49
import os import mysql.connector import json from jinja2 import Template config_sql = { 'host':os.environ['HOST_SQL_AZURE'], 'user':os.environ['USER_SQL_AZURE'], 'password':os.environ['PASSWORD_SQL_AZURE'], 'database':os.environ['DATABASE_SQL_AZURE'], 'client_flags': [mysql.connector.ClientFlag.SSL], 'ssl_ca': os.environ["SSL_CA_SQL_AZURE"]} conn = mysql.connector.connect(**config_sql) cursor = conn.cursor(dictionary=True)
[ 11748, 28686, 198, 11748, 48761, 13, 8443, 273, 198, 11748, 33918, 198, 6738, 474, 259, 6592, 17, 1330, 37350, 628, 198, 11250, 62, 25410, 796, 1391, 198, 220, 705, 4774, 10354, 418, 13, 268, 2268, 17816, 39, 10892, 62, 17861, 62, 227...
2.43617
188
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Tue Sep 25 08:55:11 2018 @author: gotamist """ def clean_and_move_up_poi(df): ''' Make 'poi' the first feature, remove lines having just nans ''' import pandas as pd import numpy as np f_list = list(df) x_list = f_list #I need the x_list later. Not just to move up the poi poi_series = df[ 'poi' ] poi_series = poi_series.astype('int') poi_df = poi_series.to_frame() x_list.remove('poi') x_list.remove('email_address') f_list = [ 'poi' ]+x_list df = df.loc[:, x_list] df=df.replace('NaN', np.nan) df=df.dropna( how ='all') df = poi_df.join( df, how = 'right') #if not dropping NaN here, right or left join does not matter return df
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 17, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41972, 319, 30030, 8621, 1679, 8487, 25, 2816, 25, 1157, 2864, 198, 198, 31, 9800, 25, 1392, 321, 396...
2.24058
345
import vcr from copper_sdk.activities import Activities @vcr.use_cassette('tests/vcr_cassettes/activities-list.yml', filter_headers=['X-PW-AccessToken', 'X-PW-UserEmail']) def test_activities_list(copper): '''Test list activities''' response = copper.activities().list({ 'page_size': 10, }) assert isinstance(response, list) assert isinstance(response[0], dict) assert len(response) == 10 # @vcr.use_cassette('tests/vcr_cassettes/lead-activities.yml', filter_headers=['X-PW-AccessToken', 'X-PW-UserEmail']) # def test_leads_activities(copper): # '''Test getting activities from a lead''' # # # get a lead id # response = copper.leads().list({ # 'page_size': 1, # }) # lead_id = response[0]['id'] # # # get activity for the lead # response = copper.leads().activities(lead_id) # # assert isinstance(response, list) # # # Cannot guarentee a result # # assert isinstance(response[0], dict) # # assert len(response) == 1
[ 11748, 410, 6098, 198, 6738, 15317, 62, 21282, 74, 13, 15791, 871, 1330, 36270, 198, 198, 31, 85, 6098, 13, 1904, 62, 66, 562, 5857, 10786, 41989, 14, 85, 6098, 62, 66, 562, 23014, 14, 15791, 871, 12, 4868, 13, 88, 4029, 3256, 810...
2.460784
408
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Aug 3 18:47:55 2020 @author: qwang """ import os import json import torch from torchtext import data import torchtext.vocab as vocab #%% Process for qanet only #%% # %% Instance # args = { # 'batch_size': 32, # 'max_vocab_size': 30000, # 'min_occur_freq': 0, # 'embed_path': '/media/mynewdrive/rob/wordvec/wikipedia-pubmed-and-PMC-w2v.txt', # # 'data_path': "/media/mynewdrive/bioqa/mnd/intervention/MND-Intervention-1983-06Aug20.json" # # 'data_path': "/media/mynewdrive/bioqa/PsyCIPN-II-796-factoid-20s-02112020.json" # 'data_path': "/media/mynewdrive/bioqa/PsyCIPN-II-1984-30s-20012021.json" # } # # BaseIter = BaselineIterators(args) # import helper.helper_psci as helper_psci # BaseIter.process_data(process_fn = helper_psci.process_for_baseline, model='bidaf') # 8mins # train_data, valid_data, test_data = BaseIter.create_data() # train_iter, valid_iter, test_iter = BaseIter.create_iterators(train_data, valid_data, test_data) # BaseIter.load_embedding().stoi['set'] # 347 # BaseIter.load_embedding().stoi['Set'] # 11912 # BaseIter.load_embedding().stoi['SET'] # 32073 # BaseIter.TEXT.vocab.itos[:12] # ['<unk>', '<pad>', ',', 'the', 'of', 'in', '.', 'and', ')', '(', 'to', 'a'] # BaseIter.TEXT.vocab.itos[-4:] # ['~30o', '~Ctrl', '~nd', '~uced'] # BaseIter.TEXT.pad_token # '<pad>' # BaseIter.TEXT.unk_token # '<unk>' # BaseIter.TEXT.vocab.stoi[BaseIter.TEXT.pad_token] # 1 # BaseIter.TEXT.vocab.stoi[BaseIter.TEXT.unk_token] # 0 # BaseIter.TEXT.vocab.vectors.shape # [26940, 200] / [20851, 200] # count = 0 # for batch in valid_iter: # if count < 20: # print(batch.context.shape) # [batch_size, context_len] # count += 1 # count = 0 # for batch in valid_iter: # if count < 8: # print("=======================") # print(batch.context.shape) # [batch_size, context_len] # print(batch.question.shape) # [batch_size, question_len] # # print(batch.y1s) # # print(batch.y2s) # print(len(batch.y1s)) # # print(batch.y1s.shape) # # print(batch.context[0,:].shape) # # print(batch.context[1,:].shape) # # print(batch.context[-1,:].shape) # count += 1 # b = next(iter(train_iter)) # vars(b).keys() # dict_keys(['batch_size', 'dataset', 'fields', 'input_fields', 'target_fields', 'id', 'question', 'context', 'y1s', 'y2s'])
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41972, 319, 2892, 2447, 220, 513, 1248, 25, 2857, 25, 2816, 12131, 198, 198, 31, 9800, 25, 10662, 475...
2.150927
1,186
from kivy.app import App from kivy.uix.button import Button MainApp().run()
[ 6738, 479, 452, 88, 13, 1324, 1330, 2034, 198, 6738, 479, 452, 88, 13, 84, 844, 13, 16539, 1330, 20969, 198, 220, 220, 220, 220, 198, 13383, 4677, 22446, 5143, 3419 ]
2.580645
31
import pandas as pd import numpy as np from sklearn.base import BaseEstimator, TransformerMixin __all__ = [ 'DatetimeConverter1D', 'DatetimeConverter', 'CyclicEncoder', ] class CyclicEncoder(BaseEstimator, TransformerMixin): """Cyclic Encoder Convert x to the [cos(2*pi*t), sin(2*pi*t)] pair, where t is pre-normalized x: t = (x - min[x])/(max[x] - min[x] + delta) Parameters ---------- delta : float Distance between maximum and minimum "angle" """
[ 11748, 19798, 292, 355, 279, 67, 198, 11748, 299, 32152, 355, 45941, 198, 198, 6738, 1341, 35720, 13, 8692, 1330, 7308, 22362, 320, 1352, 11, 3602, 16354, 35608, 259, 198, 198, 834, 439, 834, 796, 685, 198, 220, 220, 220, 705, 27354, ...
2.480583
206
from node import Node from random import randint from math import sqrt, pi, e import pygame as pg if __name__ == '__main__': pass
[ 6738, 10139, 1330, 19081, 198, 6738, 4738, 1330, 43720, 600, 198, 6738, 10688, 1330, 19862, 17034, 11, 31028, 11, 304, 198, 11748, 12972, 6057, 355, 23241, 628, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 22...
3.044444
45
#!/usr/bin/python # Copyright 2016 Google 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 applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Retrieve and store user provided metadata scripts.""" import re import socket import subprocess import tempfile from google_compute_engine import metadata_watcher from google_compute_engine.compat import httpclient from google_compute_engine.compat import urlerror from google_compute_engine.compat import urlretrieve class ScriptRetriever(object): """A class for retrieving and storing user provided metadata scripts.""" def __init__(self, logger, script_type): """Constructor. Args: logger: logger object, used to write to SysLog and serial port. script_type: string, the metadata script type to run. """ self.logger = logger self.script_type = script_type self.watcher = metadata_watcher.MetadataWatcher(logger=self.logger) def _DownloadGsUrl(self, url, dest_dir): """Download a Google Storage URL using gsutil. Args: url: string, the URL to download. dest_dir: string, the path to a directory for storing metadata scripts. Returns: string, the path to the file storing the metadata script. """ try: subprocess.check_call( ['which', 'gsutil'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) except subprocess.CalledProcessError: self.logger.warning( 'gsutil is not installed, cannot download items from Google Storage.') return None dest_file = tempfile.NamedTemporaryFile(dir=dest_dir, delete=False) dest_file.close() dest = dest_file.name self.logger.info('Downloading url from %s to %s using gsutil.', url, dest) try: subprocess.check_call(['gsutil', 'cp', url, dest]) return dest except subprocess.CalledProcessError as e: self.logger.warning( 'Could not download %s using gsutil. %s.', url, str(e)) except Exception as e: self.logger.warning( 'Exception downloading %s using gsutil. %s.', url, str(e)) return None def _DownloadUrl(self, url, dest_dir): """Download a script from a given URL. Args: url: string, the URL to download. dest_dir: string, the path to a directory for storing metadata scripts. Returns: string, the path to the file storing the metadata script. """ dest_file = tempfile.NamedTemporaryFile(dir=dest_dir, delete=False) dest_file.close() dest = dest_file.name self.logger.info('Downloading url from %s to %s.', url, dest) try: urlretrieve.urlretrieve(url, dest) return dest except (httpclient.HTTPException, socket.error, urlerror.URLError) as e: self.logger.warning('Could not download %s. %s.', url, str(e)) except Exception as e: self.logger.warning('Exception downloading %s. %s.', url, str(e)) return None def _DownloadScript(self, url, dest_dir): """Download the contents of the URL to the destination. Args: url: string, the URL to download. dest_dir: string, the path to a directory for storing metadata scripts. Returns: string, the path to the file storing the metadata script. """ # Check for the preferred Google Storage URL format: # gs://<bucket>/<object> if url.startswith(r'gs://'): return self._DownloadGsUrl(url, dest_dir) header = r'http[s]?://' domain = r'storage\.googleapis\.com' # Many of the Google Storage URLs are supported below. # It is prefered that customers specify their object using # its gs://<bucket>/<object> url. bucket = r'(?P<bucket>[a-z0-9][-_.a-z0-9]*[a-z0-9])' # Accept any non-empty string that doesn't contain a wildcard character # gsutil interprets some characters as wildcards. # These characters in object names make it difficult or impossible # to perform various wildcard operations using gsutil # For a complete list use "gsutil help naming". obj = r'(?P<obj>[^\*\?]+)' # Check for the Google Storage URLs: # http://<bucket>.storage.googleapis.com/<object> # https://<bucket>.storage.googleapis.com/<object> gs_regex = re.compile(r'\A%s%s\.%s/%s\Z' % (header, bucket, domain, obj)) match = gs_regex.match(url) if match: gs_url = r'gs://%s/%s' % (match.group('bucket'), match.group('obj')) # In case gsutil is not installed, continue as a normal URL. return (self._DownloadGsUrl(gs_url, dest_dir) or self._DownloadUrl(url, dest_dir)) # Check for the other possible Google Storage URLs: # http://storage.googleapis.com/<bucket>/<object> # https://storage.googleapis.com/<bucket>/<object> # # The following are deprecated but checked: # http://commondatastorage.googleapis.com/<bucket>/<object> # https://commondatastorage.googleapis.com/<bucket>/<object> gs_regex = re.compile( r'\A%s(commondata)?%s/%s/%s\Z' % (header, domain, bucket, obj)) match = gs_regex.match(url) if match: gs_url = r'gs://%s/%s' % (match.group('bucket'), match.group('obj')) # In case gsutil is not installed, continue as a normal URL. return (self._DownloadGsUrl(gs_url, dest_dir) or self._DownloadUrl(url, dest_dir)) # Unauthenticated download of the object. return self._DownloadUrl(url, dest_dir) def _GetAttributeScripts(self, attribute_data, dest_dir): """Retrieve the scripts from attribute metadata. Args: attribute_data: dict, the contents of the attributes metadata. dest_dir: string, the path to a directory for storing metadata scripts. Returns: dict, a dictionary mapping metadata keys to files storing scripts. """ script_dict = {} attribute_data = attribute_data or {} metadata_key = '%s-script' % self.script_type metadata_value = attribute_data.get(metadata_key) if metadata_value: self.logger.info('Found %s in metadata.' % metadata_key) with tempfile.NamedTemporaryFile( mode='w', dir=dest_dir, delete=False) as dest: dest.write(metadata_value.lstrip()) script_dict[metadata_key] = dest.name metadata_key = '%s-script-url' % self.script_type metadata_value = attribute_data.get(metadata_key) if metadata_value: self.logger.info('Found %s in metadata.' % metadata_key) script_dict[metadata_key] = self._DownloadScript(metadata_value, dest_dir) return script_dict def GetScripts(self, dest_dir): """Retrieve the scripts to execute. Args: dest_dir: string, the path to a directory for storing metadata scripts. Returns: dict, a dictionary mapping set metadata keys with associated scripts. """ metadata_dict = self.watcher.GetMetadata() or {} try: instance_data = metadata_dict['instance']['attributes'] except KeyError: instance_data = None self.logger.warning('Instance attributes were not found.') try: project_data = metadata_dict['project']['attributes'] except KeyError: project_data = None self.logger.warning('Project attributes were not found.') return (self._GetAttributeScripts(instance_data, dest_dir) or self._GetAttributeScripts(project_data, dest_dir))
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 2, 15069, 1584, 3012, 3457, 13, 1439, 6923, 33876, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428...
2.770111
2,797
# -*- coding: utf-8 -*- import sys sys.path.append("..") from src.seq2seq import setting import re import collections import json # 将下载得到的数据进行预处理,处理结果放置到到workdir目录中 # 获取GitHub和StackOverflow的数据,并将处理后的数据放到workdir目录下 if __name__ == '__main__': buildVocab("so","java") buildVocab("so","csharp")
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 25064, 198, 17597, 13, 6978, 13, 33295, 7203, 492, 4943, 198, 6738, 12351, 13, 41068, 17, 41068, 1330, 4634, 198, 11748, 302, 198, 11748, 17268, 198, 11748, 33918, ...
1.545455
198
# # Copyright (c) 2018 Juniper Networks, Inc. All rights reserved. # from vnc_api.gen.resource_common import PortProfile from vnc_cfg_api_server.resources._resource_base import ResourceMixin
[ 2, 198, 2, 15069, 357, 66, 8, 2864, 7653, 9346, 27862, 11, 3457, 13, 1439, 2489, 10395, 13, 198, 2, 198, 198, 6738, 410, 10782, 62, 15042, 13, 5235, 13, 31092, 62, 11321, 1330, 4347, 37046, 198, 198, 6738, 410, 10782, 62, 37581, 6...
3.344828
58
# 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, overload from .. import _utilities from . import outputs __all__ = [ 'GetThemeResult', 'AwaitableGetThemeResult', 'get_theme', 'get_theme_output', ] @pulumi.output_type # pylint: disable=using-constant-test def get_theme(app_id: Optional[str] = None, environment_name: Optional[str] = None, id: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetThemeResult: """ Definition of AWS::AmplifyUIBuilder::Theme Resource Type """ __args__ = dict() __args__['appId'] = app_id __args__['environmentName'] = environment_name __args__['id'] = id if opts is None: opts = pulumi.InvokeOptions() if opts.version is None: opts.version = _utilities.get_version() __ret__ = pulumi.runtime.invoke('aws-native:amplifyuibuilder:getTheme', __args__, opts=opts, typ=GetThemeResult).value return AwaitableGetThemeResult( app_id=__ret__.app_id, created_at=__ret__.created_at, environment_name=__ret__.environment_name, id=__ret__.id, modified_at=__ret__.modified_at, name=__ret__.name, overrides=__ret__.overrides, values=__ret__.values) @_utilities.lift_output_func(get_theme) def get_theme_output(app_id: Optional[pulumi.Input[str]] = None, environment_name: Optional[pulumi.Input[str]] = None, id: Optional[pulumi.Input[str]] = None, opts: Optional[pulumi.InvokeOptions] = None) -> pulumi.Output[GetThemeResult]: """ Definition of AWS::AmplifyUIBuilder::Theme Resource Type """ ...
[ 2, 19617, 28, 40477, 12, 23, 198, 2, 17202, 39410, 25, 428, 2393, 373, 7560, 416, 262, 21624, 12994, 26144, 35986, 13, 17202, 198, 2, 17202, 2141, 407, 4370, 416, 1021, 4556, 345, 821, 1728, 345, 760, 644, 345, 389, 1804, 0, 17202, ...
2.397783
812
import sys sys.path.insert(0,'..') import pickle import sys import copy import numpy as np from argparse import Namespace from data import Data #from acquisition_functions import acq_fn #from bo.bo.probo import ProBO #from bo.dom.list import ListDomain from bo.pp.pp_gp_my_distmat import MyGpDistmatPP #from argparse import Namespace from tqdm import tqdm from cyDPP.decompose_kernel import decompose_kernel from cyDPP.sample_dpp import sample_dpp def compute_best_test_losses(data, k, total_queries): """ Given full data from a completed nas algorithm, output the test error of the arch with the best val error after every multiple of k """ results = [] for query in range(k, total_queries + k, k): best_arch = sorted(data[:query], key=lambda i:i[3])[0] test_error = best_arch[3] results.append((query, test_error)) return results def compute_best_val_losses(data, k, total_queries): """ Given full data from a completed nas algorithm, output the test error of the arch with the best val error after every multiple of k """ results = [] for query in range(k, total_queries + k, k): best_arch = sorted(data[:query], key=lambda i:i[2])[0] test_error = best_arch[2] results.append((query, test_error)) return results def random_search(search_space, total_queries=100, k=10, allow_isomorphisms=False, deterministic=True, verbose=1): """ random search """ data = search_space.generate_random_dataset(num=total_queries, allow_isomorphisms=allow_isomorphisms, deterministic_loss=deterministic) val_losses = [d[2] for d in data] #top 10 val_losses = [np.asscalar(d[2]) for d in data] top_arches_idx = np.argsort(np.asarray(val_losses))[:10] # descending top_arches=[data[ii][0] for ii in top_arches_idx] pickle.dump([top_arches,val_losses], open( "10_best_architectures.p", "wb" ) ) print(val_losses[top_arches_idx[0]]) if verbose: top_5_loss = sorted([d[2] for d in data])[:min(5, len(data))] print('Query {}, top 5 val losses {}'.format(total_queries, top_5_loss)) return data # def GP_KDPP(myGP,xtrain,ytrain,xtest,newls,batch_size=5) : # # KDPP for sampling diverse + quality items # localGP=copy.deepcopy(myGP) # mu_test,sig_test=localGP.gp_post(xtrain,ytrain,xtest,ls=newls,alpha=1,sigma=1e-3) # #qualityK=np.zeros((N,N))+np.eye(N)*mu_test.reshape((-1,1)) # L=sig_test # # # decompose it into eigenvalues and eigenvectors # vals, vecs = decompose_kernel(L) # dpp_sample = sample_dpp(vals, vecs, k=batch_size) # x_t_all=[ xtest[ii] for ii in dpp_sample] # return x_t_all,dpp_sample def gp_batch_bayesopt_search(search_space, num_init=10, batch_size=5, total_queries=100, distance='edit_distance', algo_name='gp_bucb', deterministic=True, nppred=1000): """ Bayesian optimization with a GP prior """ num_iterations = total_queries - num_init # black-box function that bayesopt will optimize # this is GP modelp = Namespace(kernp=Namespace(ls=0.11, alpha=1, sigma=1e-5), #ls=0.11 for tw infp=Namespace(niter=num_iterations, nwarmup=5),#500 distance=distance, search_space=search_space.get_type()) modelp.distance=distance # Set up initial data init_data = search_space.generate_random_dataset(num=num_init, deterministic_loss=deterministic) xtrain = [d[0] for d in init_data] ytrain = np.array([[d[2]] for d in init_data]) # init data = Namespace() data.X = xtrain data.y = ytrain myGP=MyGpDistmatPP(data,modelp,printFlag=False) for ii in tqdm(range(num_iterations)):## ytrain_scale=(ytrain-np.mean(ytrain))/np.std(ytrain) data = Namespace() data.X = xtrain data.y = ytrain_scale myGP.set_data(data) #update new data xtest=search_space.get_candidate_xtest(xtrain,ytrain) xtest=xtest[:100] # this is to enforce to reupdate the K22 between test points myGP.K22_d=None myGP.K22_d1=None # generate xtest # check here, could be wrong #xtest = mylist.unif_rand_sample(500) if ii%5==0: newls=optimize_GP_hyper(myGP,xtrain,ytrain_scale,distance) # select a batch of candidate x_batch,idx_batch=GP_KDPP_Quality(myGP,xtrain,ytrain_scale,xtest,newls,batch_size) # evaluate the black-box function for xt in x_batch: yt=fn(xt) xtrain=np.append(xtrain,xt) ytrain=np.append(ytrain,yt) print(np.min(ytrain)) # get the validation and test loss for all architectures chosen by BayesOpt results = [] for arch in xtrain: archtuple = search_space.query_arch(arch,deterministic=deterministic) results.append(archtuple) return results
[ 11748, 25064, 198, 17597, 13, 6978, 13, 28463, 7, 15, 4032, 492, 11537, 198, 198, 11748, 2298, 293, 198, 11748, 25064, 198, 11748, 4866, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 1822, 29572, 1330, 28531, 10223, 198, 198, 6738, 136...
2.039121
2,684
"""Settings used by the tests in this submodule.""" import torch from tests.settings import SETTINGS as GLOBAL_SETTINGS from tests.utils.data import load_toy_data from tests.utils.models import load_toy_model from tests.utils.problem import make_problems_with_ids LOCAL_SETTINGS = [ { "data_fn": lambda: load_toy_data(batch_size=5), "model_fn": load_toy_model, "individual_loss_function_fn": lambda: torch.nn.CrossEntropyLoss( reduction="none" ), "loss_function_fn": lambda: torch.nn.CrossEntropyLoss(reduction="mean"), "iterations": 1, }, ] SETTINGS = GLOBAL_SETTINGS + LOCAL_SETTINGS PROBLEMS, PROBLEMS_IDS = make_problems_with_ids(SETTINGS)
[ 37811, 26232, 973, 416, 262, 5254, 287, 428, 850, 21412, 526, 15931, 198, 198, 11748, 28034, 198, 198, 6738, 5254, 13, 33692, 1330, 25823, 51, 20754, 355, 10188, 9864, 1847, 62, 28480, 51, 20754, 198, 6738, 5254, 13, 26791, 13, 7890, ...
2.427119
295
BINANCE_API_KEY = "BINANCE_API_KEY" BINANCE_MAX_WEIGHT = "BINANCE_MAX_WEIGHT" API_URL = "https://api.binance.com/api/v3" MAX_RESULTS = 1000 # Response 429, when x-mbx-used-weight-1m is 1200 MAX_WEIGHT = 1200 MIN_ELAPSED_PER_REQUEST = 0
[ 33, 1268, 19240, 62, 17614, 62, 20373, 796, 366, 33, 1268, 19240, 62, 17614, 62, 20373, 1, 198, 33, 1268, 19240, 62, 22921, 62, 8845, 9947, 796, 366, 33, 1268, 19240, 62, 22921, 62, 8845, 9947, 1, 198, 198, 17614, 62, 21886, 796, ...
2.266667
105
##This code is to prepare audio for pure kaldi prototype, it assumes audios are in wav format """ Command-line usage: python PrepareAudio.py Audio_folder wav_rspecifier spk2utt_rspecifier """ import os import re import shutil from sys import exit import sys import getopt import subprocess if __name__ == '__main__': try: opts, args = getopt.getopt(sys.argv[1:], "", [""]) scp_dict = {} if len(args) != 3 : raise ValueError("Please varify your input") Audio_folder=args[0] wav_rspecifier=args[1] spk2utt_rspecifier=args[2] wav_scp=open(wav_rspecifier,"w") spk2utt_file=open(spk2utt_rspecifier,"w") index=0 for dirpath, dirnames, filenames in os.walk(Audio_folder): for file in filenames: if "wav" in file: index+=1 utt_name=file.replace(".wav","").strip() transfer_line="sox %s --bits 16 -e signed -r 16k -c 1 -t wav - |"%os.path.join(dirpath,file) scp_dict[utt_name] = transfer_line utt_name_list = list(scp_dict.keys()) utt_name_list.sort() for utt_name in utt_name_list: wav_scp.write("%s %s\n"%(utt_name, scp_dict[utt_name])) spk2utt_file.write("%s %s\n"%(utt_name, utt_name)) wav_scp.close() spk2utt_file.close() except : print(__doc__) (type, value, traceback) = sys.exc_info() print(sys.exc_info()) sys.exit(0)
[ 2235, 1212, 2438, 318, 284, 8335, 6597, 329, 5899, 479, 37566, 14879, 11, 340, 18533, 2709, 4267, 389, 287, 266, 615, 5794, 198, 37811, 9455, 12, 1370, 8748, 25, 198, 220, 220, 220, 220, 220, 21015, 43426, 21206, 13, 9078, 13491, 62, ...
1.935404
805
""" Get the release information from a specific repository curl 'https://api.github.com/repos/sosey/testbot/releases' testbot.rel is example response for the sosey/testbot repo # used to render the markdown to HTML which can be walked # or used in the html page as-is pip install mistune # Use bs4 to walk the html tree for parsing # from bs4 import BeautifulSoup as bs # .stripped_strings on the bs4 object will remove the html tags # bs(m, "html.parser") # will return a bs object for parsing """ # SSLError: Can't connect to HTTPS URL because the SSL module is not available. # using pycurl for now as an example # import requests import json import mistune import os import pycurl from io import BytesIO def MakeSummaryPage(data=None, outpage=""): """Make a summary HTML page from a list of repos with release information. Data should be a list of dictionaries """ if not isinstance(data, list): raise TypeError("Expected data to be a list of dictionaries") if not outpage: raise TypeError("Expected outpage name") # print them to a web page we can display for ourselves, print("Checking for older html file") if os.access(outpage, os.F_OK): os.remove(outpage) html = open(outpage, 'w') # this section includes the javascript code and google calls for the # interactive features (table sorting) b = ''' <html> <head> <title>Software Status Page </title> <meta charset="utf-8"> <script type="text/javascript" src="https://www.google.com/jsapi"></script> <script type="text/javascript"> google.load("visualization", "1", {packages:["table"]}); google.setOnLoadCallback(drawTable); function drawTable() { var data = new google.visualization.DataTable(); data.addColumn("string", "Software"); data.addColumn("string", "Version"); data.addColumn("string", "Repository Link"); data.addColumn("string", "Reprocessing Information"); data.addColumn("string", "Released"); data.addColumn("string", "Author") data.addRows([ ''' html.write(b) for repo in data: # below is the google table code software = repo['name'] version = repo['version'] descrip = RenderHTML(repo['release_notes']) website = repo['website'] date = repo['published'] author = repo['author'] avatar = repo['avatar'] html.write("[\"{}\",\"{}\",\'<a href=\"{}\">{}</a>\',{}{}{},\"{}\",\'<a href=\"{}\">{}</a>\'],\n".format(software, version, website, "Code Repository", chr(96), descrip, chr(96), date, avatar, author)) ee = ''' ]); var table = new google.visualization.Table(document.getElementById("table_div")); table.draw(data, {showRowNumber: true, allowHtml: true}); } </script> </head> <body> <br>Click on the column fields to sort <div id="table_div"></div> </body> </html> ''' html.write(ee) html.close() def RenderHTML(md=""): """Turn markdown string into beautiful soup structure.""" if not md: return ValueError("Supply a string with markdown") m = mistune.markdown(md) return m def GetReleaseSpecs(data=None): """parse out the release information from the json object. This assumes data release specified in data as a dictionary """ if not isinstance(data, dict): raise TypeError("Wrong input data type, expected list") specs = {} try: specs['release_notes'] = data['body'] except KeyError: specs['release_notes'] = "None available" try: specs['name'] = data['repo_name'] except KeyError: try: specs['name'] = data['name'] except KeyError: specs['name'] = "No Name Set" try: specs['version'] = data['tag_name'] except KeyError: try: specs['version'] = data['name'] except KeyError: specs['version'] = "No versions" try: specs['published'] = data['published_at'] except KeyError: specs['published'] = "No Data" try: specs['website'] = data['html_url'] except KeyError: specs['website'] = 'No website provided' try: specs['author'] = data['author']['login'] except KeyError: specs['author'] = "STScI" try: specs['avatar'] = data['author']['avatar_url'] except KeyError: specs['avatar'] = "None Provided" return specs def ReadResponseFile(response=""): """Read a json response file.""" if not response: raise ValueError("Please specify json file to read") with open(response, 'r') as f: data = json.load(f) return data def GetAllReleases(org="", outpage=""): """Get the release information for all repositories in an organization. Returns a list of dictionaries with information on each repository The github api only returns the first 30 repos by default. At most it can return 100 repos at a time. Multiple calls need to be made for more. """ if not org: raise ValueError("Please supply github organization") orgrepo_url = "https://api.github.com/orgs/{0:s}/repos?per_page=10".format(org) repos_url = "https://api.github.com/repos/{0:s}/".format(org) print("Examinging {0:s}....".format(orgrepo_url)) # Get a list of the repositories buffer = BytesIO() c = pycurl.Curl() c.setopt(c.URL, orgrepo_url) c.setopt(c.WRITEDATA, buffer) c.perform() c.close() res = buffer.getvalue().decode('iso-8859-1') results = json.loads(res) # list of dicts repo_names = [] print(repo_names) # no account for orgs without repos for i in range(0, len(results), 1): repo_names.append(results[i]['name']) # Loop through all the repositories to get release information # Repositories may have multiple releases repo_releases = [] for name in repo_names: data = CheckForRelease(repos_url, name) # returns a list of results # expand the release information into separate dicts for d in data: relspecs = GetReleaseSpecs(d) relspecs['repo_name'] = name repo_releases.append(relspecs) MakeSummaryPage(repo_releases, outpage=outpage) def CheckForRelease(repos="", name=""): """Check for release information, not all repos may have releases. Repositories without release information may have tag information """ rel_url = repos + ("{0:s}/releases".format(name)) tags_url = repos + ("{0:s}/tags".format(name)) buffer = BytesIO() c = pycurl.Curl() c.setopt(c.URL, rel_url) c.setopt(c.WRITEDATA, buffer) c.perform() c.close() results = buffer.getvalue().decode('iso-8859-1') jdata = json.loads(results) if len(jdata) == 0: c = pycurl.Curl() buffer = BytesIO() c.setopt(c.WRITEDATA, buffer) c.setopt(c.URL, tags_url) # get info from tags c.perform() c.close() results = buffer.getvalue().decode('iso-8859-1') jdata = json.loads(results) for j in jdata: j['html_url'] = j['commit']['url'] j['tag_name'] = j['name'] j['name'] = name return jdata # def GetAllReleases(user="", repo=""): # """Get all the release information for a specific repository. # # This currently isn't working on my mac because # SSLError: Can't connect to HTTPS URL because the SSL # module is not available. # """ # # if not user: # raise ValueError("Please supply github user") # if not repo: # raise ValueError("Please supply a github repo name") # # repo_url = "https://api.github.com/repos" # req = "/".join([repo_url, user, repo, "releases"]) # return requests.get(req, verify=False).json() # make a pycurl call for now becuase of the https issue if __name__ == "__main__": """Create and example output from just the test repository.""" url = "https://api.github.com/repos/sosey/testbot/releases" page = ReadResponseFile('testbot.rel') # reads into a list of dicts specs = GetReleaseSpecs(page.pop()) # just send in the one dict specs['name'] = 'testbot' MakeSummaryPage([specs], 'testbot_release.html')
[ 37811, 198, 3855, 262, 2650, 1321, 422, 257, 2176, 16099, 198, 66, 6371, 705, 5450, 1378, 15042, 13, 12567, 13, 785, 14, 260, 1930, 14, 568, 4397, 14, 9288, 13645, 14, 260, 29329, 6, 198, 9288, 13645, 13, 2411, 318, 1672, 2882, 329,...
2.53428
3,311
# mypy: disallow-untyped-defs # mypy: disallow-any-decorated import os import re from textwrap import dedent import mypy.api from pathlib import Path from typing import List, Tuple import attr import pytest @attr.s(auto_attribs=True) class _Result: """ Encapsulates the result of a call to ``mypy.api``, providing helpful functions to check that output. """ output: Tuple[str, str, int] @property @property @property @property @attr.s(auto_attribs=True) class TypeCheckerFixture: """ Fixture to help running mypy in source code and checking for success/specific errors. This fixture is useful for libraries which provide type checking, allowing them to ensure the type support is working as intended. """ path: Path request: pytest.FixtureRequest
[ 2, 616, 9078, 25, 595, 12154, 12, 403, 774, 9124, 12, 4299, 82, 198, 2, 616, 9078, 25, 595, 12154, 12, 1092, 12, 12501, 273, 515, 198, 11748, 28686, 198, 11748, 302, 198, 6738, 2420, 37150, 1330, 4648, 298, 198, 198, 11748, 616, 9...
2.985507
276
from collections import namedtuple from numbers import Real _LayoutOptions = namedtuple( '_LayoutOptions', ['width', 'height', 'top', 'right', 'bottom', 'left']) class LayoutOptions(_LayoutOptions): """ :param LayoutOptionValue width: width spec :param LayoutOptionValue height: height spec :param LayoutOptionValue top: top spec :param LayoutOptionValue right: right spec :param LayoutOptionValue bottom: bottom spec :param LayoutOptionValue left: left spec It is possible to define values that conflict. The behavior in these cases is undefined. .. py:attribute:: width A :py:class:`LayoutOptionValue` constraining this view's width (or not). .. py:attribute:: height A :py:class:`LayoutOptionValue` constraining this view's height (or not). .. py:attribute:: top A :py:class:`LayoutOptionValue` constraining this view's distance from the top of its superview (or not). .. py:attribute:: right A :py:class:`LayoutOptionValue` constraining this view's distance from the right of its superview (or not). .. py:attribute:: bottom A :py:class:`LayoutOptionValue` constraining this view's distance from the bottom of its superview (or not). .. py:attribute:: left A :py:class:`LayoutOptionValue` constraining this view's distance from the left of its superview (or not). """ ### Convenience initializers ### @classmethod def centered(self, width, height): """ Create a :py:class:`LayoutOptions` object that positions the view in the center of the superview with a constant width and height. """ return LayoutOptions( top=None, bottom=None, left=None, right=None, width=width, height=height) @classmethod def column_left(self, width): """ Create a :py:class:`LayoutOptions` object that positions the view as a full-height left column with a constant width. """ return LayoutOptions( top=0, bottom=0, left=0, right=None, width=width, height=None) @classmethod def column_right(self, width): """ Create a :py:class:`LayoutOptions` object that positions the view as a full-height right column with a constant width. """ return LayoutOptions( top=0, bottom=0, left=None, right=0, width=width, height=None) @classmethod def row_top(self, height): """ Create a :py:class:`LayoutOptions` object that positions the view as a full-height top row with a constant height. """ return LayoutOptions( top=0, bottom=None, left=0, right=0, width=None, height=height) @classmethod def row_bottom(self, height): """ Create a :py:class:`LayoutOptions` object that positions the view as a full-height bottom row with a constant height. """ return LayoutOptions( top=None, bottom=0, left=0, right=0, width=None, height=height) ### Convenience modifiers ### def with_updates(self, **kwargs): """ Returns a new :py:class:`LayoutOptions` object with the given changes to its attributes. For example, here's a view with a constant width, on the right side of its superview, with half the height of its superview:: # "right column, but only half height" LayoutOptions.column_right(10).with_updates(bottom=0.5) """ opts = self._asdict() opts.update(kwargs) return LayoutOptions(**opts) ### Semi-internal layout API ###
[ 6738, 17268, 1330, 3706, 83, 29291, 198, 6738, 3146, 1330, 6416, 628, 198, 62, 32517, 29046, 796, 3706, 83, 29291, 7, 198, 220, 220, 220, 705, 62, 32517, 29046, 3256, 198, 220, 220, 220, 37250, 10394, 3256, 705, 17015, 3256, 705, 4852...
2.645967
1,401
from pseudo.pseudo_tree import Node class TreeTransformer: ''' visits recursively nodes of the tree with defined transform_<node_type> methods and transforms in place ''' before = None after = None whitelist = None # if a set, transform only those nodes, optimization current_class = None current_function = None # def transform_custom_exception(self, s, *w): # # input(s) # return s
[ 6738, 24543, 13, 7752, 12003, 62, 21048, 1330, 19081, 628, 198, 4871, 12200, 8291, 16354, 25, 198, 220, 220, 220, 705, 7061, 198, 220, 220, 220, 11864, 664, 1834, 2280, 13760, 286, 262, 5509, 198, 220, 220, 220, 351, 5447, 6121, 62, ...
2.883117
154
import sys if __name__ == '__main__': main(*sys.argv[1:])
[ 11748, 25064, 628, 628, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 1388, 46491, 17597, 13, 853, 85, 58, 16, 25, 12962, 198 ]
2.2
30
import matplotlib.pyplot as plt import sklearn.metrics import networkx as nx import numpy as np import pandas as pd fontsize=16 minor_size=14
[ 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 1341, 35720, 13, 4164, 10466, 198, 198, 11748, 3127, 87, 355, 299, 87, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 198, 10331, 785...
2.803922
51
from ..classes.pareto import pareto import random def Pareto(model, objectives, objdirec, runs, GetPoints=True, tol=1e-10): """ pre: objectives = [["reac"],{"reac2":x}] post: turning points of Pareto front """ state = model.GetState() rv = pareto() model.SetObjDirec(objdirec) anchor = [] for obj in objectives: model.ZeroObjective() model.SetObjective(obj) model.Solve(PrintStatus=False) anchor.append(model.GetObjVal()) print(anchor) if len(anchor) == len(objectives): for n in range(runs): model.ZeroObjective() coef = [] for b in range(len(objectives)): coef.append(random.random()) sumcoef = sum(coef) for b in range(len(objectives)): try: coef[b] = coef[b]/anchor[b]/sumcoef except ZeroDivisionError: print("Zero Division error at %s" % objectives[b]) continue objdic = {} for b in range(len(objectives)): thisobjdic = {} if isinstance(objectives[b],list): for reac in objectives[b]: thisobjdic[reac] = coef[b] elif isinstance(objectives[b],dict): for reac in objectives[b]: thisobjdic[reac] = objectives[b][reac]*coef[b] for r in thisobjdic: if r in objdic.keys(): objdic[r] += thisobjdic[r] else: objdic[r] = thisobjdic[r] print(objdic) model.SetObjective(objdic) model.Solve(PrintStatus=False) sol = model.GetSol(IncZeroes=True) for b in range(len(objectives)): sol["coef"+str(b+1)] = coef[b] if isinstance(objectives[b],list): sol["Obj"+str(b+1)] = sol[objectives[b][0]] elif isinstance(objectives[b],dict): objsol = 0 for reac in objectives[b]: objsol += sol[reac]*objectives[b][reac] sol["Obj"+str(b+1)] = objsol print(sol) rv = pareto(rv.UpdateFromDic(sol)) model.SetState(state) if len(anchor) == len(objectives) and GetPoints: return rv.GetParetoPoints(tol) else: return rv
[ 6738, 11485, 37724, 13, 79, 533, 1462, 1330, 279, 533, 1462, 198, 11748, 4738, 198, 198, 4299, 350, 533, 1462, 7, 19849, 11, 15221, 11, 26181, 67, 557, 66, 11, 4539, 11, 3497, 40710, 28, 17821, 11, 284, 75, 28, 16, 68, 12, 940, ...
1.757295
1,405
import json import numpy as np import pandas as pd import networkx as nx from texttable import Texttable def data_reader(input_path): """ Function to read a csv edge list and transform it to a networkx graph object. """ data = np.array(pd.read_csv(input_path)) return data def log_setup(args_in): """ Function to setup the logging hash table. """ log = dict() log["times"] = [] log["losses"] = [] log["new_features_added"] = [] log["params"] = vars(args_in) return log def tab_printer(log): """ Function to print the logs in a nice tabular format. """ t = Texttable() t.add_rows([["Epoch", log["losses"][-1][0]]]) print t.draw() t = Texttable() t.add_rows([["Loss", round(log["losses"][-1][1],3)]]) print t.draw() def epoch_printer(repetition): """ Function to print the epoch number. """ print("") print("Epoch " + str(repetition+1) + ". initiated.") print("") def log_updater(log, repetition, average_loss, optimization_time): """ Function to update the log object. """ index = repetition + 1 log["losses"] = log["losses"] + [[index, average_loss]] log["times"] = log["times"] + [[index, optimization_time]] return log
[ 11748, 33918, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 3127, 87, 355, 299, 87, 198, 6738, 2420, 11487, 1330, 8255, 11487, 198, 198, 4299, 1366, 62, 46862, 7, 15414, 62, 6978, 2599, 198, 220...
2.487524
521
# Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.sale_coupon.tests.test_program_numbers import TestSaleCouponProgramNumbers from odoo.addons.website.tools import MockRequest from odoo.exceptions import UserError from odoo.tests import tagged @tagged('-at_install', 'post_install')
[ 2, 2142, 286, 10529, 2238, 13, 4091, 38559, 24290, 2393, 329, 1336, 6634, 290, 15665, 3307, 13, 198, 198, 6738, 16298, 2238, 13, 39996, 13, 21378, 62, 66, 10486, 261, 13, 41989, 13, 9288, 62, 23065, 62, 77, 17024, 1330, 6208, 50, 10...
3.371134
97
import json import redis from celery import Celery import pandas as pd import math import pymysql app = Celery( 'get_key_words', backend='redis://localhost:6379/8' ) @app.task def get_key(user_api_key, api_key): """ :param user_api_key: :param api_key: :return: """ conn = pymysql.connect( # 链接MYSQL host='localhost', user='root', passwd='963369', db='wisreccloud', port=3306, charset='utf8' ) # 到数据库查询所需要的数据 _temp = pd.read_sql("select data_id, key_digest from jie_card_data where client_id_id = %s" % user_api_key, conn) _id = _temp["data_id"].to_list() _digest = _temp["key_digest"].to_list() _result = {temp_id: temp_digest for temp_id, temp_digest in zip(_id, _digest)} news_cor_list = list() # 计算相似度 for new_id1 in _result.keys(): id1_tags = set(_result[new_id1].split(",")) for new_id2 in _result.keys(): id2_tags = set(_result[new_id2].split(",")) if new_id1 != new_id2: cor = (len(id1_tags & id2_tags)) / len(id1_tags | id2_tags) if cor > 0.1: news_cor_list.append([new_id1, new_id2, format(cor, ".2f")]) # 替换redis中推荐数据 pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True, db=8) conn = redis.StrictRedis(connection_pool=pool) try: # 如何未查询到数据,则是因为第一次创建则新建数据 for redis_name in conn.keys(): if api_key == json.loads(conn.get(redis_name))["result"]["api_key"]: conn.delete(redis_name) except KeyError: pass result = { "api_key": api_key, "result": news_cor_list } return result def load_data(user_api_key): """ 加载数据库中的数据集 :param user_api_key: :return: """ conn = pymysql.connect( # 链接MYSQL host='localhost', user='root', passwd='963369', db='wisreccloud', port=3306, charset='utf8' ) _temp = pd.read_sql("select user_id, movie_id, ratting from movie_cf_data where client_id_id = %s" % user_api_key, conn) data, new_data = list(), dict() for user_id, item_id, record in zip(_temp["user_id"], _temp["movie_id"], _temp["ratting"]): data.append((user_id, item_id, record)) for user, item, record in data: new_data.setdefault(user, {}) new_data[user][item] = record return new_data @app.task def UserSimilarityBest(user_api_key, api_key): """ 计算用户之间的相似度 :return: """ data = load_data(user_api_key) item_users = dict() # 存储哪些item被用户评价过 for u, items in data.items(): # user_id {item_id: rating} for i in items.keys(): # 得到每个item被哪些user评价过 item_users.setdefault(i, set()) if data[u][i] > 0: item_users[i].add(u) # {'1193': {'1', '15', '2', '28', '18', '19', '24', '12', '33', '17'}} count, user_item_count = dict(), dict() for i, users in item_users.items(): # item_id, set(user_id1, user_id2) for u in users: # user_id user_item_count.setdefault(u, 0) # user_id: 0 user_item_count[u] += 1 count.setdefault(u, {}) # user_id: {} for v in users: # user_id count[u].setdefault(v, 0) if u == v: continue count[u][v] += 1 / math.log(1 + len(users)) # {'33': 391, '19': 255, '28': 107, '12': 23} userSim = dict() for u, related_users in count.items(): userSim.setdefault(u, {}) for v, cuv in related_users.items(): if u == v: continue userSim[u].setdefault(v, 0.0) userSim[u][v] = cuv / math.sqrt(user_item_count[u] * user_item_count[v]) # 替换redis中推荐数据 pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True, db=8) conn = redis.StrictRedis(connection_pool=pool) try: # 如何未查询到数据,则是因为第一次创建则新建数据 for redis_name in conn.keys(): if api_key == json.loads(conn.get(redis_name))["result"]["api_key"]: conn.delete(redis_name) except KeyError: pass result = { "api_key": api_key, "result": userSim } return result @app.task
[ 11748, 33918, 198, 11748, 2266, 271, 198, 6738, 18725, 1924, 1330, 15248, 1924, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 10688, 198, 11748, 279, 4948, 893, 13976, 198, 198, 1324, 796, 15248, 1924, 7, 198, 220, 220, 220, 705, ...
1.813738
2,373
#%% [markdown] # # Matching when including the contralateral connections #%% [markdown] # ## Preliminaries #%% import datetime import os import time from pathlib import Path import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns from giskard.plot import adjplot, matched_stripplot, matrixplot from numba import jit from pkg.data import load_maggot_graph, load_matched from pkg.io import OUT_PATH from pkg.io import glue as default_glue from pkg.io import savefig from pkg.match import BisectedGraphMatchSolver, GraphMatchSolver from pkg.plot import method_palette, set_theme from pkg.utils import get_paired_inds, get_paired_subgraphs, get_seeds from scipy.optimize import linear_sum_assignment from scipy.stats import wilcoxon FILENAME = "larva_brain" DISPLAY_FIGS = True OUT_PATH = OUT_PATH / FILENAME t0 = time.time() set_theme() rng = np.random.default_rng(8888) #%% [markdown] # ### Load the data #%% left_adj, left_nodes = load_matched("left") right_adj, right_nodes = load_matched("right") left_nodes["inds"] = range(len(left_nodes)) right_nodes["inds"] = range(len(right_nodes)) seeds = get_seeds(left_nodes, right_nodes) all_nodes = pd.concat((left_nodes, right_nodes)) all_nodes["inds"] = range(len(all_nodes)) left_nodes.iloc[seeds[0]]["pair_id"] assert len(left_nodes) == len(right_nodes) #%% mg = load_maggot_graph() mg = mg.node_subgraph(all_nodes.index) adj = mg.sum.adj n = len(left_nodes) left_inds = np.arange(n) right_inds = np.arange(n) + n glue("n_nodes", n) #%% [markdown] # ### Run the graph matching experiment n_sims = 25 glue("n_initializations", n_sims) RERUN_SIMS = False if RERUN_SIMS: seeds = rng.integers(np.iinfo(np.int32).max, size=n_sims) rows = [] for sim, seed in enumerate(seeds): for Solver, method in zip( [BisectedGraphMatchSolver, GraphMatchSolver], ["BGM", "GM"] ): run_start = time.time() solver = Solver(adj, left_inds, right_inds, rng=seed) solver.solve() match_ratio = (solver.permutation_ == np.arange(n)).mean() elapsed = time.time() - run_start print(f"{elapsed:.3f} seconds elapsed.") rows.append( { "match_ratio": match_ratio, "sim": sim, "method": method, "seed": seed, "elapsed": elapsed, "converged": solver.converged, "n_iter": solver.n_iter, "score": solver.score_, } ) results = pd.DataFrame(rows) results.to_csv(OUT_PATH / "larva_comparison.csv") else: results = pd.read_csv(OUT_PATH / "larva_comparison.csv", index_col=0) results.head() #%% fig, ax = plt.subplots(1, 1, figsize=(6, 6)) matched_stripplot( data=results, x="method", y="match_ratio", match="sim", order=["GM", "BGM"], hue="method", palette=method_palette, ax=ax, jitter=0.25, ) sns.move_legend(ax, "upper left", title="Method") mean1 = results[results["method"] == "GM"]["match_ratio"].mean() mean2 = results[results["method"] == "BGM"]["match_ratio"].mean() ax.set_yticks([mean1, mean2]) ax.set_yticklabels([f"{mean1:.2f}", f"{mean2:.2f}"]) ax.tick_params(which="both", length=7) ax.set_ylabel("Match ratio") ax.set_xlabel("Method") gluefig("match_ratio_larva", fig) # %% bgm_results = results[results["method"] == "BGM"] gm_results = results[results["method"] == "GM"] stat, pvalue = wilcoxon( bgm_results["match_ratio"].values, gm_results["match_ratio"].values ) glue("match_ratio_pvalue", pvalue, form="pvalue") mean_bgm = bgm_results["match_ratio"].mean() glue("mean_match_ratio_bgm", mean_bgm) mean_gm = gm_results["match_ratio"].mean() glue("mean_match_ratio_gm", mean_gm)
[ 2, 16626, 685, 4102, 2902, 60, 198, 2, 1303, 13225, 278, 618, 1390, 262, 542, 1373, 10534, 8787, 198, 2, 16626, 685, 4102, 2902, 60, 198, 2, 22492, 28887, 320, 259, 3166, 198, 2, 16626, 198, 11748, 4818, 8079, 198, 11748, 28686, 198...
2.204571
1,750
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from datetime import timedelta from dateutil.relativedelta import relativedelta from odoo import api, fields, models
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2142, 286, 10529, 2238, 13, 4091, 38559, 24290, 2393, 329, 1336, 6634, 290, 15665, 3307, 13, 198, 198, 6738, 4818, 8079, 1330, 28805, 12514, 198, 6738, 3128, 22602, 1...
3.460317
63
v1 = int(input('Digite o primeiro valor: ')) v2 = int(input('Digite o segundo valor: ')) v3 = int(input('Digite o terceiro valor: ')) v4 = int(input('Digite o quarto valor: ')) v5 = int(input('Digite o quinto valor: ')) lista = (v1, v2, v3, v4, v5) print(f'O 9 apareceu {lista.count(9)} vezes.') if lista.count(3) > 0: print(f'O primeiro 3 esta na {lista.index(3) + 1} posição.') else: print('Não tem nenhum 3') print('Os números pares são: ', end='') for n in lista: if n % 2 == 0: print(n, end=' ')
[ 85, 16, 796, 493, 7, 15414, 10786, 19511, 578, 267, 6994, 7058, 1188, 273, 25, 705, 4008, 198, 85, 17, 796, 493, 7, 15414, 10786, 19511, 578, 267, 384, 70, 41204, 1188, 273, 25, 705, 4008, 198, 85, 18, 796, 493, 7, 15414, 10786, ...
2.100806
248
import os import cv2 import paddle from tqdm import tqdm # from paddle.io import DataLoader from ppcd.datasets import DataLoader from ppcd.tools import splicing_list, save_tif # 进行滑框预测
[ 11748, 28686, 198, 11748, 269, 85, 17, 198, 11748, 39517, 198, 6738, 256, 80, 36020, 1330, 256, 80, 36020, 198, 2, 422, 39517, 13, 952, 1330, 6060, 17401, 198, 6738, 9788, 10210, 13, 19608, 292, 1039, 1330, 6060, 17401, 198, 6738, 978...
2.527027
74
from models import Admin, UserProxy, Customer from db_models import db, db_session, UserDB, AppointmentsDB, InsurancePlanDB from insurance_plan import BasicHealthPlan, CancerCare, CardiacCare, BasicLifePlan, ULIPBenefits, ComboPlan if __name__ == "__main__": # Add new user new_user = add_user() # Fetch existing user new_user = get_user('leja@ic.com') # View current plan for a user # view_current_plan(new_user) # Customer buys a new plan buy_plan(new_user) # Schedule a call # schedule_call(new_user)
[ 6738, 4981, 1330, 32053, 11, 11787, 44148, 11, 22092, 198, 6738, 20613, 62, 27530, 1330, 20613, 11, 20613, 62, 29891, 11, 11787, 11012, 11, 2034, 1563, 902, 11012, 11, 17541, 20854, 11012, 198, 6738, 5096, 62, 11578, 1330, 14392, 18081, ...
2.875648
193
#!/usr/bin/env python """Python-Pinboard Python script for downloading your saved stories and saved comments on Hacker News. """ __version__ = "1.1" __license__ = "BSD" __copyright__ = "Copyright 2013-2014, Luciano Fiandesio" __author__ = "Luciano Fiandesio <http://fiandes.io/> & John David Pressman <http://jdpressman.com>" import argparse import json import os import sys import time import urllib import pdfkit import requests import tqdm from bs4 import BeautifulSoup from lxml import html HACKERNEWS = 'https://news.ycombinator.com' parser = argparse.ArgumentParser() parser.add_argument("username", help="The Hacker News username to grab the stories from.") parser.add_argument("password", help="The password to login with using the username.") parser.add_argument("-f", "--file", help="Filepath to store the JSON document at.") parser.add_argument("-n", "--number", default=1, type=int, help="Number of pages to grab, default 1. 0 grabs all pages.") parser.add_argument("-s", "--stories", action="store_true", help="Grab stories only.") parser.add_argument("-c", "--comments", action="store_true", help="Grab comments only.") parser.add_argument("-pdf", "--pdf", default=1, type=bool, help="Save to PDF") parser.add_argument("-o", "--output_folder", default="output/", type=str, help="Output Folder for PDF") arguments = parser.parse_args() def getSavedStories(session, hnuser, page_range): """Return a list of story IDs representing your saved stories. This function does not return the actual metadata associated, just the IDs. This list is traversed and each item inside is grabbed using the Hacker News API by story ID.""" story_ids = [] for page_index in page_range: saved = session.get(HACKERNEWS + '/upvoted?id=' + hnuser + "&p=" + str(page_index)) soup = BeautifulSoup(saved.content, features="lxml") for tag in soup.findAll('td', attrs={'class': 'subtext'}): if tag.a is not type(None): a_tags = tag.find_all('a') for a_tag in a_tags: if a_tag['href'][:5] == 'item?': story_id = a_tag['href'].split('id=')[1] story_ids.append(story_id) break return story_ids def getSavedComments(session, hnuser, page_range): """Return a list of IDs representing your saved comments. This function does not return the actual metadata associated, just the IDs. This list is traversed and each item inside is grabbed using the Hacker News API by ID.""" comment_ids = [] for page_index in page_range: saved = session.get(HACKERNEWS + '/upvoted?id=' + hnuser + "&comments=t" + "&p=" + str(page_index)) soup = BeautifulSoup(saved.content, features="lxml") for tag in soup.findAll('td', attrs={'class': 'default'}): if tag.a is not type(None): a_tags = tag.find_all('a') for a_tag in a_tags: if a_tag['href'][:5] == 'item?': comment_id = a_tag['href'].split('id=')[1] comment_ids.append(comment_id) break return comment_ids def getHackerNewsItem(item_id): """Get an 'item' as specified in the HackerNews v0 API.""" time.sleep(0.2) item_json_link = "https://hacker-news.firebaseio.com/v0/item/" + item_id + ".json" try: with urllib.request.urlopen(item_json_link) as item_json: current_story = json.loads(item_json.read().decode('utf-8')) if "kids" in current_story: del current_story["kids"] # Escape / in name for a later use current_story["title"] = current_story["title"].replace("/", "-") return current_story except urllib.error.URLError: return {"title": "Item " + item_id + " could not be retrieved", "id": item_id} if __name__ == "__main__": main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 37811, 37906, 12, 28348, 3526, 198, 37906, 4226, 329, 22023, 534, 7448, 3923, 290, 7448, 3651, 319, 34399, 3000, 13, 198, 37811, 198, 198, 834, 9641, 834, 796, 366, 16, 13, 16, 1, 19...
2.420611
1,669
# Copyright 2020 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Data Commons static content routes.""" from flask import Blueprint, render_template from lib.gcs import list_blobs _SA_FEED_BUCKET = 'datacommons-frog-feed' _MAX_BLOBS = 1 bp = Blueprint( 'static', __name__ ) @bp.route('/') @bp.route('/about') @bp.route('/faq') @bp.route('/disclaimers') @bp.route('/datasets') @bp.route('/getinvolved') @bp.route('/special_announcement') @bp.route('/special_announcement/faq')
[ 2, 15069, 12131, 3012, 11419, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 198, 2, 921, 743, 733...
3.123457
324
import functools import collections # ---------------------------------------------------------------------------- # Memoization/Caching # ---------------------------------------------------------------------------- class cached(object): """Last 100 value memoization for functions of any arguments""" def __init__(self, func): """Cache the function/method of any arguments""" self.func = func self.cache = collections.OrderedDict() def __repr__(self): """Return the original function's docstring""" return self.func.__doc__ def __get__(self, obj, cls): """Support instance methods""" return functools.partial(self.__call__, obj)
[ 11748, 1257, 310, 10141, 198, 11748, 17268, 198, 198, 2, 16529, 10541, 198, 2, 4942, 78, 1634, 14, 34, 8103, 198, 2, 16529, 10541, 198, 4871, 39986, 7, 15252, 2599, 198, 220, 220, 220, 37227, 5956, 1802, 1988, 16155, 1634, 329, 5499, ...
3.410628
207
import wheel import pandas as pd import nltk import numpy import sklearn as skl import pickle f = open('./mypkg/bananoulli_20k.pickle', 'rb') classifier = pickle.load(f) f.close df = pd.DataFrame(pd.read_csv('./mypkg/testingdataset.csv')) sentiment_column = (df.iloc[:, [1]]) sentiment_array = sentiment_column.values text_column = (df.iloc[:, [6]]) text_array = text_column.values text = [] for words in text_array: words_filtered = [e.lower() for e in words[0].split() if len(e) >= 3] text.append((words_filtered)) testing_tweets = [] count = 0 for words in text: tweet = (words, sentiment_array[count][0]) count += 1 testing_tweets.append(tweet) # print (get_words_in_tweets(tweets)) word_features = get_word_features(get_words_in_tweets(testing_tweets)) # print(word_features) # ---------------------------------------------------------------------- # Final classification methods # ---------------------------------------------------------------------- # ---------------------------------------------------------------------- # Testing the ML model # ---------------------------------------------------------------------- # test_tweet = 'lovely happy beautiful joy' # # print(classify_tweet(test_tweet)) # # print(probability_positive(test_tweet)) # # # ---------------------------------------------------------------------- # # Accuracy of the ML model # # ---------------------------------------------------------------------- # # testing_set = nltk.classify.apply_features(extract_features, testing_tweets) # # print("MultinomialNB accuracy percent:", nltk.classify.accuracy(classifier, testing_set))
[ 11748, 7825, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 299, 2528, 74, 198, 11748, 299, 32152, 198, 11748, 1341, 35720, 355, 1341, 75, 198, 11748, 2298, 293, 198, 198, 69, 796, 1280, 7, 4458, 14, 1820, 35339, 14, 3820, 272, 2...
3.384774
486
# -*- coding: utf-8 -*- from django import forms
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 6738, 42625, 14208, 1330, 5107, 198 ]
2.380952
21
""" Exceptions that are specific to the dynamodb module. """ from boto.exception import BotoServerError, BotoClientError class DynamoDBExpiredTokenError(BotoServerError): """ Raised when a DynamoDB security token expires. This is generally boto's (or the user's) notice to renew their DynamoDB security tokens. """ pass class DynamoDBKeyNotFoundError(BotoClientError): """ Raised when attempting to retrieve or interact with an item whose key can't be found. """ pass class DynamoDBItemError(BotoClientError): """ Raised when invalid parameters are passed when creating a new Item in DynamoDB. """ pass
[ 37811, 198, 3109, 11755, 326, 389, 2176, 284, 262, 6382, 375, 65, 8265, 13, 198, 37811, 198, 6738, 275, 2069, 13, 1069, 4516, 1330, 347, 2069, 10697, 12331, 11, 347, 2069, 11792, 12331, 628, 198, 4871, 41542, 11012, 3109, 6474, 30642, ...
3.170616
211
# Count-Min Sketch - вероятностная структура данных для быстрого примерного подсчёта частоты встречаемости элементов import random from collections import Counter if __name__ == '__main__': data = [random.randint(0, 5) for i in range(100)] print(Counter(data)) cms = CountMinSketch(top_k=3) for i in range(len(data)): # key = data[random.randint(0, random.randint(0, len(data) - 1))] cms.increment_value(key=data[i]) print(cms.get_minimum(0)) print(cms.get_minimum(1)) print(cms.get_minimum(2)) print(cms.get_minimum(3)) print(cms.get_minimum(4)) print(cms.get_minimum(5))
[ 2, 2764, 12, 9452, 17001, 532, 12466, 110, 16843, 21169, 15166, 40623, 20375, 22177, 15166, 21727, 20375, 22177, 16142, 40623, 220, 21727, 20375, 21169, 35072, 31583, 20375, 35072, 21169, 16142, 12466, 112, 16142, 22177, 22177, 45035, 141, 22...
1.822222
360
""" Generate spatial gratings ========================= Stimulus presentation based on gratings of different spatial frequencies for generating ERPs, high frequency oscillations, and alpha reset. Inspired from: > Hermes, Dora, K. J. Miller, B. A. Wandell, and Jonathan Winawer. "Stimulus dependence of gamma oscillations in human visual cortex." Cerebral Cortex 25, no. 9 (2015): 2951-2959. """ from time import time from optparse import OptionParser import numpy as np import pandas as pd from psychopy import visual, core, event from pylsl import StreamInfo, StreamOutlet, local_clock parser = OptionParser() parser.add_option("-d", "--duration", dest="duration", type='int', default=400, help="duration of the recording in seconds.") (options, args) = parser.parse_args() # Create markers stream outlet info = StreamInfo('Markers', 'Markers', 3, 0, 'float32', 'myuidw43536') channels = info.desc().append_child("channels") for c in ['Frequency', 'Contrast', 'Orientation']: channels.append_child("channel") \ .append_child_value("label", c) outlet = StreamOutlet(info) start = time() # Set up trial parameters n_trials = 2010 iti = 1.0 soa = 1.5 jitter = 0.5 record_duration = np.float32(options.duration) # Setup trial list frequency = np.random.binomial(1, 0.5, n_trials) contrast = np.ones(n_trials, dtype=int) orientation = np.random.randint(0, 4, n_trials) * 45 trials = pd.DataFrame(dict(frequency=frequency, contrast=contrast, orientation=orientation)) # graphics mywin = visual.Window([1920, 1080], monitor="testMonitor", units="deg", fullscr=True) grating = visual.GratingStim(win=mywin, mask='circle', size=40, sf=4) fixation = visual.GratingStim(win=mywin, size=0.2, pos=[0, 0], sf=0, rgb=[1, 0, 0]) rs = np.random.RandomState(42) core.wait(2) for ii, trial in trials.iterrows(): # onset fre = trials['frequency'].iloc[ii] contrast = trials['contrast'].iloc[ii] ori = trials['orientation'].iloc[ii] grating.sf = 4 * fre + 0.1 grating.ori = ori grating.contrast = contrast grating.draw() fixation.draw() # Send marker outlet.push_sample([fre + 1, contrast, ori], local_clock()) mywin.flip() # offset core.wait(soa) fixation.draw() outlet.push_sample([fre + 3, contrast, ori], local_clock()) mywin.flip() if len(event.getKeys()) > 0 or (time() - start) > record_duration: break event.clearEvents() # Intertrial interval core.wait(iti + np.random.rand() * jitter) # Cleanup mywin.close()
[ 37811, 198, 8645, 378, 21739, 14586, 654, 198, 4770, 2559, 28, 198, 198, 1273, 320, 23515, 10470, 1912, 319, 14586, 654, 286, 1180, 21739, 19998, 198, 1640, 15453, 13793, 12016, 11, 1029, 8373, 24969, 602, 11, 290, 17130, 13259, 13, 198...
2.555981
1,045
#!/usr/bin/env python # EQUAL PARTS VINEGAR AND WATER # # https://www.goodhousekeeping.com/home/cleaning/tips/a26565/cleaning-coffee-maker/ # # Fill the reservoir with equal parts vinegar and water, and place a paper filter # into the machine's empty basket. Position the pot in place, and "brew" the solution # halfway. Turn off the machine, and let it sit for 30 minutes. Then, turn the # coffee maker back on, finish the brewing, and dump the full pot of vinegar and water. # Rinse everything out by putting in a new paper filter and brewing a full pot # of clean water. Repeat once. import time import argparse import collections import math # from settings.automation_settings import AUTOMATION_EXECUTABLES_PATH from remote_frequency_outlets import rfoutlets as rfo from settings import automation_settings # schedule_brew(args.outlet_group, schedule_time, settings.brew_time,) settings = automation_settings.coffee_settings["default"] cleaning_instructions = "Add vinegar and water 1 : 1 in coffeemaker. Fill MrCoffee to 12 cups when using default settings." try: parser = argparse.ArgumentParser( description="Mr Coffee 12 cup coffeemaker programmer using a remote frequency outlet.") parser.add_argument("outlet_group") parser.add_argument('--delay', '-d', help='delay start of brewing in minutes', type=float, default=automation_settings.coffee_default_delay, metavar='min') maintenance_group = parser.add_mutually_exclusive_group() maintenance_group.add_argument('--clean', '-c', action='store_true', help='cleaning cycle for full 12 cup MrCoffee 1/2 vinegar 1/2 water') maintenance_group.add_argument('--rinse', '-r', action='store_true', help='rinse the coffeepot after the cleaning cycle') maintenance_group.add_argument('--test', action="store_true", help='used by pytest, to run a quicker test' ) args = parser.parse_args() if args.test: settings = automation_settings.coffee_settings["test"] elif args.clean: settings = automation_settings.coffee_settings["clean"] elif args.rinse: settings = automation_settings.coffee_settings["rinse"] args_dict = vars(args) for key in args_dict: print(key + ' -> ' + str(args_dict[key])) total_hours = ( args.delay * 60 + (settings.pause * (settings.cycles - 1) + settings.brew_time * settings.cycles) / (60.0 * 60.0) ) print print(cleaning_instructions) print print("The brewing process will start in {:3d} minutes, and will be finished {:.2f} hours from now...".format( args.delay, total_hours)) rv = '' schedule_time = args.delay * 60 for i in range(settings.cycles): # PAUSE if i > 0: schedule_time += settings.pause # BREW: minutes_from_now = int(math.ceil(schedule_time / 60)) if settings.brew_time < 3 * 60: # schedule once and use 1 blink for length of brew schedule_brew(args.outlet_group, minutes_from_now, settings.brew_time) else: # schedule twice: turn on and turn off rfo.rfo_schedule_in_minutes( args.outlet_group, 'on', minutes_from_now, 3, 1) minutes_from_now = int(math.ceil( (schedule_time + settings.brew_time) / 60)) rfo.rfo_schedule_in_minutes( args.outlet_group, 'off', minutes_from_now, 3, 1) schedule_time += settings.brew_time except KeyboardInterrupt: rfo.switch_outlet_group(args.outlet_group, 'off') print print("KeyboardInterrupt") print except Exception as error: rfo.switch_outlet_group(args.outlet_group, 'off') print print("An error occured. I'm super sorry: ") print("error: ") print(error) print else: print print("DONE, no exceptions")
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 2, 46886, 1847, 29463, 4694, 569, 1268, 7156, 1503, 5357, 370, 23261, 198, 2, 198, 2, 3740, 1378, 2503, 13, 11274, 4803, 19934, 13, 785, 14, 11195, 14, 2375, 7574, 14, 41315, 14...
2.369553
1,767
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import unittest from hmalib.common.actioner_models import Label
[ 2, 15069, 357, 66, 8, 3203, 11, 3457, 13, 290, 663, 29116, 13, 1439, 6923, 33876, 198, 198, 11748, 555, 715, 395, 198, 6738, 289, 7617, 571, 13, 11321, 13, 2673, 263, 62, 27530, 1330, 36052, 628 ]
3.702703
37
from __future__ import print_function import tensorflow as tf import sys
[ 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 198, 11748, 11192, 273, 11125, 355, 48700, 198, 11748, 25064, 628 ]
3.75
20
from django.shortcuts import render # Create your views here. from oosc.absence.models import Absence from oosc.absence.serializers import AbsenceSerializer from rest_framework import generics from oosc.attendance.models import Attendance from django.db.models import Count,Case,When,IntegerField,Q,Value,CharField,TextField from datetime import datetime,timedelta from oosc.absence.models import Absence from oosc.students.models import Students from oosc.config.settings import DROPOUT_MIN_COUNT from oosc.schools.models import Schools from rest_framework import generics # # class GetTheDropOuts() #from oosc.absence.views import GenerateReport as d #Calculating the droupouts weekly
[ 6738, 42625, 14208, 13, 19509, 23779, 1330, 8543, 198, 198, 2, 13610, 534, 5009, 994, 13, 198, 6738, 267, 17500, 13, 8937, 594, 13, 27530, 1330, 13051, 594, 198, 6738, 267, 17500, 13, 8937, 594, 13, 46911, 11341, 1330, 13051, 594, 326...
3.418719
203
# References: # http://developer.download.nvidia.com/books/HTML/gpugems/gpugems_ch38.html # https://github.com/PavelDoGreat/WebGL-Fluid-Simulation # https://www.bilibili.com/video/BV1ZK411H7Hc?p=4 # https://github.com/ShaneFX/GAMES201/tree/master/HW01 import argparse import numpy as np import taichi as ti ti.init(arch=ti.vulkan) res = 512 dt = 0.03 p_jacobi_iters = 500 # 40 for a quicker but less accurate result f_strength = 10000.0 curl_strength = 0 time_c = 2 maxfps = 60 dye_decay = 1 - 1 / (maxfps * time_c) force_radius = res / 2.0 gravity = True paused = False @ti.func @ti.func @ti.func # 3rd order Runge-Kutta @ti.func @ti.kernel @ti.kernel @ti.kernel @ti.kernel @ti.kernel mouse_data_ti = ti.ndarray(ti.f32, shape=(8, )) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument( '--baseline', action='store_true') args, unknown = parser.parse_known_args() gui = ti.GUI('Stable Fluid', (res, res)) md_gen = MouseDataGen() _velocities = ti.Vector.ndarray(2, float, shape=(res, res)) _new_velocities = ti.Vector.ndarray(2, float, shape=(res, res)) _velocity_divs = ti.ndarray(float, shape=(res, res)) velocity_curls = ti.ndarray(float, shape=(res, res)) _pressures = ti.ndarray(float, shape=(res, res)) _new_pressures = ti.ndarray(float, shape=(res, res)) _dye_buffer = ti.Vector.ndarray(3, float, shape=(res, res)) _new_dye_buffer = ti.Vector.ndarray(3, float, shape=(res, res)) if args.baseline: velocities_pair = TexPair(_velocities, _new_velocities) pressures_pair = TexPair(_pressures, _new_pressures) dyes_pair = TexPair(_dye_buffer, _new_dye_buffer) else: print('running in graph mode') velocities_pair_cur = ti.graph.Arg(ti.graph.ArgKind.NDARRAY, 'velocities_pair_cur', ti.f32, element_shape=(2, )) velocities_pair_nxt = ti.graph.Arg(ti.graph.ArgKind.NDARRAY, 'velocities_pair_nxt', ti.f32, element_shape=(2, )) dyes_pair_cur = ti.graph.Arg(ti.graph.ArgKind.NDARRAY, 'dyes_pair_cur', ti.f32, element_shape=(3, )) dyes_pair_nxt = ti.graph.Arg(ti.graph.ArgKind.NDARRAY, 'dyes_pair_nxt', ti.f32, element_shape=(3, )) pressures_pair_cur = ti.graph.Arg(ti.graph.ArgKind.NDARRAY, 'pressures_pair_cur', ti.f32) pressures_pair_nxt = ti.graph.Arg(ti.graph.ArgKind.NDARRAY, 'pressures_pair_nxt', ti.f32) velocity_divs = ti.graph.Arg(ti.graph.ArgKind.NDARRAY, 'velocity_divs', ti.f32) mouse_data = ti.graph.Arg(ti.graph.ArgKind.NDARRAY, 'mouse_data', ti.f32) g1_builder = ti.graph.GraphBuilder() g1_builder.dispatch(advect, velocities_pair_cur, velocities_pair_cur, velocities_pair_nxt) g1_builder.dispatch(advect, velocities_pair_cur, dyes_pair_cur, dyes_pair_nxt) g1_builder.dispatch(apply_impulse, velocities_pair_nxt, dyes_pair_nxt, mouse_data) g1_builder.dispatch(divergence, velocities_pair_nxt, velocity_divs) # swap is unrolled in the loop so we only need p_jacobi_iters // 2 iterations. for _ in range(p_jacobi_iters // 2): g1_builder.dispatch(pressure_jacobi, pressures_pair_cur, pressures_pair_nxt, velocity_divs) g1_builder.dispatch(pressure_jacobi, pressures_pair_nxt, pressures_pair_cur, velocity_divs) g1_builder.dispatch(subtract_gradient, velocities_pair_nxt, pressures_pair_cur) g1 = g1_builder.compile() g2_builder = ti.graph.GraphBuilder() g2_builder.dispatch(advect, velocities_pair_nxt, velocities_pair_nxt, velocities_pair_cur) g2_builder.dispatch(advect, velocities_pair_nxt, dyes_pair_nxt, dyes_pair_cur) g2_builder.dispatch(apply_impulse, velocities_pair_cur, dyes_pair_cur, mouse_data) g2_builder.dispatch(divergence, velocities_pair_cur, velocity_divs) for _ in range(p_jacobi_iters // 2): g2_builder.dispatch(pressure_jacobi, pressures_pair_cur, pressures_pair_nxt, velocity_divs) g2_builder.dispatch(pressure_jacobi, pressures_pair_nxt, pressures_pair_cur, velocity_divs) g2_builder.dispatch(subtract_gradient, velocities_pair_cur, pressures_pair_cur) g2 = g2_builder.compile() swap = True while gui.running: if gui.get_event(ti.GUI.PRESS): e = gui.event if e.key == ti.GUI.ESCAPE: break elif e.key == 'r': paused = False reset() elif e.key == 's': if curl_strength: curl_strength = 0 else: curl_strength = 7 elif e.key == 'g': gravity = not gravity elif e.key == 'p': paused = not paused if not paused: _mouse_data = md_gen(gui) if args.baseline: step_orig(_mouse_data) gui.set_image(dyes_pair.cur.to_numpy()) else: invoke_args = { 'mouse_data': _mouse_data, 'velocities_pair_cur': _velocities, 'velocities_pair_nxt': _new_velocities, 'dyes_pair_cur': _dye_buffer, 'dyes_pair_nxt': _new_dye_buffer, 'pressures_pair_cur': _pressures, 'pressures_pair_nxt': _new_pressures, 'velocity_divs': _velocity_divs } if swap: g1.run(invoke_args) gui.set_image(_dye_buffer.to_numpy()) swap = False else: g2.run(invoke_args) gui.set_image(_new_dye_buffer.to_numpy()) swap = True gui.show()
[ 2, 31458, 25, 198, 2, 2638, 1378, 16244, 263, 13, 15002, 13, 77, 21744, 13, 785, 14, 12106, 14, 28656, 14, 31197, 1018, 5232, 14, 31197, 1018, 5232, 62, 354, 2548, 13, 6494, 198, 2, 3740, 1378, 12567, 13, 785, 14, 28875, 626, 5211...
1.811634
3,610
""" AGN spectral model generation functions Copyright: Adam Hill (2020) """ import numpy as np import pandas as pd from tqdm import tqdm from scipy.interpolate import RegularGridInterpolator def merge_dict_dfs(d, common_column): """ Main purpose: - merges all the dataframes collected in the d dictionary - Prints the duplicates in the merged dataframe and removes them NOTE: Each table must have the common_column to match on """ d_copy = d.copy() merged = d_copy[0] if 0 in d_copy: del d_copy[0] else: print("No 0 dataframe found... This shouldn't have happened.") with tqdm(total = len(d_copy), position = 0, desc = "Merging tables") as pbar: for name, df in d_copy.items(): # print(name) # print(merged.shape) merged = pd.merge(merged, df, how = "left", on = "E_keV") pbar.update(1) print(merged.shape) dupe_mask = merged.duplicated(subset = ["E_keV"], keep = "last") dupes = merged[dupe_mask] print(dupes.columns) print(str(len(dupes)) + " duplicates") print("Now removing duplicates...") merged = merged[~dupe_mask] for c in merged.columns: print(c) return merged def sed(PhoIndex, Ecut, logNHtor, CFtor, thInc, A_Fe, z, factor): """ Need to manually stitch together the spectra """ PhoIndex_str = np.array(["p3=%.5f" %par_val for par_val in PhoIndex.ravel()]) Ecut_str = np.array(["p4=%.5f" %par_val for par_val in Ecut.ravel()]) logNHtor_str = np.array(["p5=%.5f" %par_val for par_val in logNHtor.ravel()]) CFtor_str = np.array(["p6=%.5f" %par_val for par_val in CFtor.ravel()]) thInc_str = np.array(["p7=%.5f" %par_val for par_val in thInc.ravel()]) A_Fe_str = np.array(["p8=%.5f" %par_val for par_val in A_Fe.ravel()]) z_str = np.array(["p9=%.5f" %par_val for par_val in z.ravel()]) factor_str = np.array(["p17=%.5f" %par_val for par_val in factor.ravel()]) trans = np.empty(shape = [len(PhoIndex_str, len(Ecut_str), len(logNHtor_str), len(CFtor_str), len(thInc_str), len(A_Fe_str), len(z_str), len(factor_str)), 40500]) repro = np.empty(shape = [len(PhoIndex_str, len(Ecut_str), len(logNHtor_str), len(CFtor_str), len(thInc_str), len(A_Fe_str), len(z_str), len(factor_str)), 40500]) scatt = np.empty(shape = [len(PhoIndex_str, len(Ecut_str), len(logNHtor_str), len(CFtor_str), len(thInc_str), len(A_Fe_str), len(z_str), len(factor_str)), 40500]) ## note must stitch together in increasing order of length of parameter arrays for i, PhoIndex_val in enumerate(PhoIndex_str): for j, Ecut_val in enumerate(Ecut_str): for k, A_Fe_val in enumerate(A_Fe_str): for l, factor_val in enumerate(factor_str): for m, z_val in enumerate(z_str): for n, logNHtor_val in enumerate(logNHtor_str): for o, CFtor_val in enumerate(CFtor_str): for p, thInc_val in enumerate(thInc_str): df_column = "%(PhoIndex_val)s_%(Ecut_val)s_%(logNHtor_val)s_%(CFtor_val)s_%(thInc_val)s_%(A_Fe_val)s_%(z_val)s_%(factor_val)s" %locals() trans[i, j, k, l, m, n, o, p, :] = df_master["TRANS_" + df_column].values repro[i, j, k, l, m, n, o, p, :] = df_master["REPR_" + df_column].values scatt[i, j, k, l, m, n, o, p, :] = df_master["SCATT_" + df_column].values return trans, repro, scatt, temp["E_keV"].values ## load in the hefty dataset ## note -- need to figure out a more efficient way of storing this data ## Xspec uses a fits table, but unsure how we can generate the Python RegularGridInterpolator from that df_dict = {} for a, csvfile in enumerate(glob.glob("./borus_stepped/borus_step*.csv")): df_dict[a] = pd.read_csv(csvfile) df_master = merge_dict_dfs(df_dict, "E_keV") parLen = 5 PhoIndex = np.linspace(1.45, 2.55, 3) Ecut = np.logspace(2., 3., 3) logNHtor = np.linspace(22., 25.5, parLen) CFtor = np.linspace(0.15, 0.95, parLen) thInc = np.linspace(20., 85, parLen) A_Fe = np.logspace(-1., 1., 3) z = np.logspace(-3., 0., 4) factor = np.logspace(-5., -1., 3) params = np.meshgrid(PhoIndex, Ecut, logNHtor, CFtor, thInc, A_Fe, z, factor, indexing='ij', sparse=True) trans_sed, repro_sed, scatt_sed, E_keV = sed(*params) print(np.shape(SEDs)) trans_interp = RegularGridInterpolator((PhoIndex, Ecut, A_Fe, factor, z, logNHtor, CFtor, thInc), trans_sed) repro_interp = RegularGridInterpolator((PhoIndex, Ecut, A_Fe, factor, z, logNHtor, CFtor, thInc), repro_sed) scatt_interp = RegularGridInterpolator((PhoIndex, Ecut, A_Fe, factor, z, logNHtor, CFtor, thInc), scatt_sed) def generate_spectra(PhoIndex, Ecut, A_Fe, factor, z, logNHtor, CFtor, thInc): """ This is a place holder for a proper function Args: PhoIndex: float, powerlaw slope of the intrinsic spectrum (1.45--2.55) Ecut: float, high-energy exponentional cut-off of the intrinsic powerlaw (100.--1000.) A_Fe: float, abundance of iron in the obscurer (0.1--10.) factor: float, percentage of scattered emission in the warm mirror (1.e-5--1.e-1) z: float, redshift of the source (1.e-3--1.) logNHtor: float, logarithm of the column density of the obscurer (22.--22.5) CFtor: float, covering factor of the obscurer (0.15--0.95) thInc: float, inclination angle of the obscurer (20.--85.), note: edge-on = 90. Returns: dataframe: a dataframe with columns for the energy in keV, the transmitted X-ray flux, the reprocessed X-ray flux, the Thomson-scattered X-ray flux, and the total X-ray flux """ spectral_df = pd.DataFrame( { "Energy": E_keV, "Transmitted": trans_interp([PhoIndex, Ecut, A_Fe, factor, z, logNHtor, CFtor, thInc]), "Reprocessed": trans_interp([PhoIndex, Ecut, A_Fe, factor, z, logNHtor, CFtor, thInc]), "Scattered": scatt_interp([PhoIndex, Ecut, A_Fe, factor, z, logNHtor, CFtor, thInc]), } ) spectral_df.loc[:, "Total"] = spectral_df[["Transmitted", "Reprocessed", "Scattered"]].sum() return spectral_df # def generate_spectra(angle1, angle2, logNH): # """ # This is a place holder for a proper function # Args: # angle1: float, inclination angle in degrees (0-90) of the AGN view # angle2: float, torus opening angle in degrees (0-90) of the AGN # logNH: float, logarithm of the obscuring column density within the AGN environment # Returns: # dataframe: a dataframe of with columns for the energy in keV, the transmitted X-ray flux, # the reprocessed X-ray flux, and the total X-ray flux # """ # _degs_to_rads = lambda x: np.pi * x / 180.0 # degrees = np.arange(1, 1001, 1) # radians = np.array(list(map(_degs_to_rads, degrees))) # linear_component = radians * (logNH / 9.657) + 2 # transmitted_flux = (angle1 / 5) * np.cos( # _degs_to_rads(angle1) + radians * (logNH / 1.5) # ) + linear_component # reprocessed_flux = (angle2 / 10) * np.sin( # _degs_to_rads(angle2) + radians * (logNH / 5.0) # ) + 5.0 # total_flux = transmitted_flux + reprocessed_flux # spectral_df = pd.DataFrame( # { # "Energy": degrees, # "Transmitted": transmitted_flux, # "Reprocessed": reprocessed_flux, # "Summed": total_flux, # } # ) # return spectral_df
[ 37811, 198, 4760, 45, 37410, 2746, 5270, 5499, 198, 15269, 25, 7244, 3327, 357, 42334, 8, 198, 37811, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 6738, 256, 80, 36020, 1330, 256, 80, 36020, 198,...
2.193013
3,492
from django.conf.urls import patterns, include, url from django.contrib import admin from tastypie.api import Api from centros.api import * from clientes.api import * from compras.api import * from contactos.api import * from cotizaciones.api import * from equipos.api import * from familias.api import * from historiales.api import * from lugares.api import * from productos.api import * from proveedores.api import * from solicitudes.api import * from tiposequipos.api import * from usuarios.api import * from usuarios.views import * v1_api = Api(api_name="v1") v1_api.register(CentroResource()) v1_api.register(ClienteResource()) v1_api.register(CompraResource()) v1_api.register(ContactoResource()) v1_api.register(CotizacionResource()) v1_api.register(EquipoResource()) v1_api.register(FamiliaResource()) v1_api.register(HistorialResource()) v1_api.register(LugarResource()) v1_api.register(ProductoResource()) v1_api.register(NombreProductoResource()) v1_api.register(FotoProductoResource()) v1_api.register(UnidadProductoResource()) v1_api.register(PrecioMesProductoResource()) v1_api.register(ProveedorResource()) v1_api.register(SolicitudResource()) v1_api.register(ProductoSolicitudResource()) v1_api.register(TipoEquipoResource()) v1_api.register(UsuarioResource()) v1_api.register(ConsolidadorSolicitanteResource()) v1_api.register(SolicitanteCodificadorResource()) v1_api.register(AprobadorSolicitudesSolicitanteResource()) v1_api.register(AprobadorSolicitudesCompradorResource()) v1_api.register(CompradorAprobadorComprasResource()) v1_api.register(AprobadorComprasAlmacenistaResource()) urlpatterns = patterns("", (r"^api/", include(v1_api.urls)), (r"^admin/", include(admin.site.urls)) )
[ 6738, 42625, 14208, 13, 10414, 13, 6371, 82, 1330, 7572, 11, 2291, 11, 19016, 198, 6738, 42625, 14208, 13, 3642, 822, 1330, 13169, 198, 6738, 14854, 4464, 494, 13, 15042, 1330, 5949, 72, 198, 198, 6738, 1247, 4951, 13, 15042, 1330, 16...
2.862647
597
import pytest from pyntcloud.samplers import RandomMeshSampler @pytest.mark.parametrize("n", [ 1, 5, 10, 50, 100 ]) @pytest.mark.usefixtures("diamond") @pytest.mark.parametrize("rgb,normals", [ (False, False), (True, False), (True, True), (False, True) ]) @pytest.mark.usefixtures("diamond") @pytest.mark.parametrize("n", [ 1, 5, 10, 50, 100 ]) @pytest.mark.usefixtures("diamond")
[ 11748, 12972, 9288, 198, 198, 6738, 12972, 429, 17721, 13, 37687, 489, 364, 1330, 14534, 37031, 16305, 20053, 628, 198, 31, 9078, 9288, 13, 4102, 13, 17143, 316, 380, 2736, 7203, 77, 1600, 685, 198, 220, 220, 220, 352, 11, 198, 220, ...
2.089202
213
from notifications.tests.factories import SupplierEmailNotificationFactory
[ 6738, 19605, 13, 41989, 13, 22584, 1749, 1330, 8105, 2505, 15333, 3673, 2649, 22810, 628 ]
5.066667
15
# (C) Datadog, Inc. 2018 # All rights reserved # Licensed under a 3-clause BSD style license (see LICENSE) import warnings from time import time as timestamp import requests from six import string_types from urllib3.exceptions import InsecureRequestWarning from datadog_checks.checks import AgentCheck from datadog_checks.config import is_affirmative from datadog_checks.utils.containers import hash_mutable from .errors import ApiUnreachable
[ 2, 357, 34, 8, 16092, 324, 519, 11, 3457, 13, 2864, 198, 2, 1439, 2489, 10395, 198, 2, 49962, 739, 257, 513, 12, 565, 682, 347, 10305, 3918, 5964, 357, 3826, 38559, 24290, 8, 198, 11748, 14601, 198, 6738, 640, 1330, 640, 355, 4103...
3.568
125
import os from problem_3.load_data import load_data from problem_3.problem_3a import problem_3a from problem_3.problem_3b import problem_3b # Create results directory os.makedirs('results', exist_ok=True) # Problem 3a X_train, Y_train, X_test, Y_test = load_data('a') problem_3a(X_train, Y_train, X_test, Y_test) # Problem 3b X_train, Y_train, X_test, Y_test = load_data('b') problem_3b(X_train, Y_train, X_test, Y_test)
[ 11748, 28686, 198, 6738, 1917, 62, 18, 13, 2220, 62, 7890, 1330, 3440, 62, 7890, 198, 6738, 1917, 62, 18, 13, 45573, 62, 18, 64, 1330, 1917, 62, 18, 64, 198, 6738, 1917, 62, 18, 13, 45573, 62, 18, 65, 1330, 1917, 62, 18, 65, 6...
2.52381
168
import glob from setuptools import setup, find_packages try: import pypandoc long_description = pypandoc.convert("README.md", "rst") except(IOError, ImportError): long_description = open("README.md").read() setup( name="pybenzinaparse", version="0.2.2", packages=find_packages(exclude=["test_*"]), url="https://github.com/satyaog/pybenzinaparse", license="The MIT License", author="Satya Ortiz-Gagné", author_email="satya.ortiz-gagne@mila.quebec", description="MP4 / ISO base media file format (ISO/IEC 14496-12 - MPEG-4 Part 12) file parser", requires=["bitstring"], install_requires=["bitstring"], setup_requires=["pytest-runner"], tests_require=["pytest"], long_description=long_description, data_files=[("", ["README.md", ]), ("tests", glob.glob("data/*"))] )
[ 11748, 15095, 198, 6738, 900, 37623, 10141, 1330, 9058, 11, 1064, 62, 43789, 198, 198, 28311, 25, 198, 220, 220, 220, 1330, 279, 4464, 392, 420, 198, 220, 220, 220, 890, 62, 11213, 796, 279, 4464, 392, 420, 13, 1102, 1851, 7203, 156...
2.534328
335
#Author: Usama Munir Sheikh #The following code implements an LSTM recurrent neural network #for classifying tweets as positive or negative #in the sentiment140 dataset http://help.sentiment140.com/for-students/ #It was written for my Intro to Deep Learning Course #taught by Professor Qiang Ji in Spring 2017 import tensorflow as tf import numpy as np import json from sklearn.manifold import TSNE import matplotlib.pyplot as plt import time if __name__ == "__main__": main()
[ 2, 13838, 25, 4021, 1689, 12107, 343, 30843, 198, 2, 464, 1708, 2438, 23986, 281, 406, 2257, 44, 42465, 17019, 3127, 198, 197, 2, 1640, 1398, 4035, 12665, 355, 3967, 393, 4633, 198, 197, 2, 259, 262, 15598, 15187, 27039, 2638, 1378, ...
3.464286
140
# Copyright 2021 The NetKet 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 applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import jax import netket as nk import numpy as np import pytest from jax import numpy as jnp @pytest.mark.parametrize("dtype", [jnp.float64, jnp.complex128]) @pytest.mark.parametrize("s", [1 / 2, 1]) @pytest.mark.parametrize( "partial_model", [ pytest.param( lambda hilbert, dtype: nk.models.ARNNDense( hilbert=hilbert, layers=3, features=5, dtype=dtype, ), id="dense", ), pytest.param( lambda hilbert, dtype: nk.models.ARNNConv1D( hilbert=hilbert, layers=3, features=5, kernel_size=2, dtype=dtype, ), id="conv1d", ), pytest.param( lambda hilbert, dtype: nk.models.ARNNConv1D( hilbert=hilbert, layers=3, features=5, kernel_size=2, kernel_dilation=2, dtype=dtype, ), id="conv1d_dilation", ), ], )
[ 2, 15069, 33448, 383, 3433, 42, 316, 46665, 532, 1439, 2489, 10395, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, ...
2.012941
850
""" Tests for state.orchestrate """ import os import pytest pytestmark = [ pytest.mark.slow_test, ] def test_orchestrate_output(salt_run_cli, salt_minion, salt_master): """ Ensure the orchestrate runner outputs useful state data. In Issue #31330, the output only contains ['outputter:', ' highstate'], and not the full stateful return. This tests ensures we don't regress in that manner again. Also test against some sample "good" output that would be included in a correct orchestrate run. """ bad_out = ["outputter:", " highstate"] good_out = [ " Function: salt.state", " Result: True", "Succeeded: 1 (changed=1)", "Failed: 0", "Total states run: 1", ] sls_contents = """ call_sleep_state: salt.state: - tgt: {} - sls: simple-ping """.format( salt_minion.id ) simple_ping_sls = """ simple-ping: module.run: - name: test.ping """ with salt_master.state_tree.base.temp_file( "orch-test.sls", sls_contents ), salt_master.state_tree.base.temp_file("simple-ping.sls", simple_ping_sls): ret = salt_run_cli.run("--out=highstate", "state.orchestrate", "orch-test") assert ret.returncode == 0 ret_output = ret.stdout.splitlines() # First, check that we don't have the "bad" output that was displaying in # Issue #31330 where only the highstate outputter was listed assert bad_out != ret_output assert len(ret_output) > 2 # Now test that some expected good sample output is present in the return. for item in good_out: assert item in ret_output def test_orchestrate_state_output_with_salt_function( salt_run_cli, salt_minion, salt_master ): """ Ensure that orchestration produces the correct output with salt.function. A salt execution module function does not return highstate data, so we should not try to recursively output it as such. The outlier to this rule is state.apply, but that is handled by the salt.state. See https://github.com/saltstack/salt/issues/60029 for more detail. """ sls_contents = """ arg_clean_test: salt.function: - name: test.arg_clean - arg: - B flat major - has 2 flats - tgt: {minion_id} ping_test: salt.function: - name: test.ping - tgt: {minion_id} """.format( minion_id=salt_minion.id ) with salt_master.state_tree.base.temp_file("orch-function-test.sls", sls_contents): ret = salt_run_cli.run( "--out=highstate", "state.orchestrate", "orch-function-test" ) assert ret.returncode == 0 ret_output = [line.strip() for line in ret.stdout.splitlines()] assert "args:" in ret_output assert "- B flat major" in ret_output assert "- has 2 flats" in ret_output assert "True" in ret_output def test_orchestrate_nested(salt_run_cli, salt_minion, salt_master, tmp_path): """ test salt-run state.orchestrate and failhard with nested orchestration """ testfile = tmp_path / "ewu-2016-12-13" inner_sls = """ cmd.run: salt.function: - tgt: {} - arg: - {} - failhard: True """.format( salt_minion.id, pytest.helpers.shell_test_false() ) outer_sls = """ state.orchestrate: salt.runner: - mods: nested.inner - failhard: True cmd.run: salt.function: - tgt: {} - arg: - touch {} """.format( salt_minion.id, testfile ) with salt_master.state_tree.base.temp_file( "nested/inner.sls", inner_sls ), salt_master.state_tree.base.temp_file("nested/outer.sls", outer_sls): ret = salt_run_cli.run("state.orchestrate", "nested.outer") assert ret.returncode != 0 assert testfile.exists() is False def test_orchestrate_with_mine(salt_run_cli, salt_minion, salt_master): """ test salt-run state.orchestrate with mine.get call in sls """ sls_contents = ( """ {% set minion = '""" + salt_minion.id + """' %} {% set mine = salt.saltutil.runner('mine.get', tgt=minion, fun='test.ping') %} {% if mine %} test.ping: salt.function: - tgt: "{{ minion }}" {% endif %} """ ) ret = salt_run_cli.run("mine.update", salt_minion.id) assert ret.returncode == 0 with salt_master.state_tree.base.temp_file("orch/mine.sls", sls_contents): ret = salt_run_cli.run("state.orchestrate", "orch.mine") assert ret.returncode == 0 assert ret.data assert ret.data["data"][salt_master.id] for state_data in ret.data["data"][salt_master.id].values(): assert state_data["changes"]["ret"] assert state_data["changes"]["ret"][salt_minion.id] is True def test_orchestrate_state_and_function_failure(salt_run_cli, salt_master, salt_minion): """ Ensure that returns from failed minions are in the changes dict where they belong, so they can be programmatically analyzed. See https://github.com/saltstack/salt/issues/43204 """ init_sls = """ Step01: salt.state: - tgt: {minion_id} - sls: - orch.issue43204.fail_with_changes Step02: salt.function: - name: runtests_helpers.nonzero_retcode_return_false - tgt: {minion_id} - fail_function: runtests_helpers.fail_function """.format( minion_id=salt_minion.id ) fail_sls = """ test fail with changes: test.fail_with_changes """ with salt_master.state_tree.base.temp_file( "orch/issue43204/init.sls", init_sls ), salt_master.state_tree.base.temp_file( "orch/issue43204/fail_with_changes.sls", fail_sls ): ret = salt_run_cli.run("saltutil.sync_modules") assert ret.returncode == 0 ret = salt_run_cli.run("state.orchestrate", "orch.issue43204") assert ret.returncode != 0 # Drill down to the changes dict data = ret.data["data"][salt_master.id] state_ret = data["salt_|-Step01_|-Step01_|-state"]["changes"] func_ret = data[ "salt_|-Step02_|-runtests_helpers.nonzero_retcode_return_false_|-function" ]["changes"] # Remove duration and start time from the results, since they would # vary with each run and that would make it impossible to test. for item in ("duration", "start_time"): state_ret["ret"][salt_minion.id][ "test_|-test fail with changes_|-test fail with changes_|-fail_with_changes" ].pop(item) expected = { "out": "highstate", "ret": { salt_minion.id: { "test_|-test fail with changes_|-test fail with changes_|-fail_with_changes": { "__id__": "test fail with changes", "__run_num__": 0, "__sls__": "orch.issue43204.fail_with_changes", "changes": { "testing": { "new": "Something pretended to change", "old": "Unchanged", } }, "comment": "Failure!", "name": "test fail with changes", "result": False, } } }, } assert state_ret == expected assert func_ret == {"ret": {salt_minion.id: False}} def test_orchestrate_salt_function_return_false_failure( salt_run_cli, salt_minion, salt_master ): """ Ensure that functions that only return False in the return are flagged as failed when run as orchestrations. See https://github.com/saltstack/salt/issues/30367 """ sls_contents = """ deploy_check: salt.function: - name: test.false - tgt: {} """.format( salt_minion.id ) with salt_master.state_tree.base.temp_file("orch/issue30367.sls", sls_contents): ret = salt_run_cli.run("saltutil.sync_modules") assert ret.returncode == 0 ret = salt_run_cli.run("state.orchestrate", "orch.issue30367") assert ret.returncode != 0 # Drill down to the changes dict data = ret.data["data"][salt_master.id] state_result = data["salt_|-deploy_check_|-test.false_|-function"]["result"] func_ret = data["salt_|-deploy_check_|-test.false_|-function"]["changes"] assert state_result is False assert func_ret == {"ret": {salt_minion.id: False}} def test_orchestrate_target_exists(salt_run_cli, salt_minion, salt_master): """ test orchestration when target exists while using multiple states """ sls_contents = """ core: salt.state: - tgt: '{minion_id}*' - sls: - core test-state: salt.state: - tgt: '{minion_id}*' - sls: - orch.target-test cmd.run: salt.function: - tgt: '{minion_id}*' - arg: - echo test """.format( minion_id=salt_minion.id ) target_test_sls = """ always_true: test.succeed_without_changes """ with salt_master.state_tree.base.temp_file( "orch/target-exists.sls", sls_contents ), salt_master.state_tree.base.temp_file( "orch/target-test.sls", target_test_sls ), salt_master.state_tree.base.temp_file( "core.sls", target_test_sls ): ret = salt_run_cli.run("state.orchestrate", "orch.target-exists") assert ret.returncode == 0 assert ret.data data = ret.data["data"][salt_master.id] to_check = {"core", "test-state", "cmd.run"} for state_data in data.values(): if state_data["name"] == "core": to_check.remove("core") assert state_data["result"] is True if state_data["name"] == "test-state": assert state_data["result"] is True to_check.remove("test-state") if state_data["name"] == "cmd.run": assert state_data["changes"] == { "ret": {salt_minion.id: "test"}, } to_check.remove("cmd.run") assert not to_check def test_orchestrate_target_does_not_exist(salt_run_cli, salt_minion, salt_master): """ test orchestration when target does not exist while using multiple states """ sls_contents = """ core: salt.state: - tgt: 'does-not-exist*' - sls: - core test-state: salt.state: - tgt: '{minion_id}*' - sls: - orch.target-test cmd.run: salt.function: - tgt: '{minion_id}*' - arg: - echo test """.format( minion_id=salt_minion.id ) target_test_sls = """ always_true: test.succeed_without_changes """ with salt_master.state_tree.base.temp_file( "orch/target-does-not-exist.sls", sls_contents ), salt_master.state_tree.base.temp_file( "orch/target-test.sls", target_test_sls ), salt_master.state_tree.base.temp_file( "core.sls", target_test_sls ): ret = salt_run_cli.run("state.orchestrate", "orch.target-does-not-exist") assert ret.returncode != 0 assert ret.data data = ret.data["data"][salt_master.id] to_check = {"core", "test-state", "cmd.run"} for state_data in data.values(): if state_data["name"] == "core": to_check.remove("core") assert state_data["result"] is False assert state_data["comment"] == "No minions returned" if state_data["name"] == "test-state": assert state_data["result"] is True to_check.remove("test-state") if state_data["name"] == "cmd.run": assert state_data["changes"] == { "ret": {salt_minion.id: "test"}, } to_check.remove("cmd.run") assert not to_check def test_orchestrate_retcode(salt_run_cli, salt_master): """ Test orchestration with nonzero retcode set in __context__ """ sls_contents = """ test_runner_success: salt.runner: - name: runtests_helpers.success test_runner_failure: salt.runner: - name: runtests_helpers.failure test_wheel_success: salt.wheel: - name: runtests_helpers.success test_wheel_failure: salt.wheel: - name: runtests_helpers.failure """ with salt_master.state_tree.base.temp_file("orch/retcode.sls", sls_contents): ret = salt_run_cli.run("saltutil.sync_runners") assert ret.returncode == 0 ret = salt_run_cli.run("saltutil.sync_wheel") assert ret.returncode == 0 ret = salt_run_cli.run("state.orchestrate", "orch.retcode") assert ret.returncode != 0 assert ret.data data = ret.data["data"][salt_master.id] to_check = { "test_runner_success", "test_runner_failure", "test_wheel_failure", "test_wheel_success", } for state_data in data.values(): name = state_data["__id__"] to_check.remove(name) if name in ("test_runner_success", "test_wheel_success"): assert state_data["result"] is True if name in ("test_runner_failure", "test_wheel_failure"): assert state_data["result"] is False assert not to_check def test_orchestrate_batch_with_failhard_error( salt_run_cli, salt_master, salt_minion, tmp_path ): """ test orchestration properly stops with failhard and batch. """ testfile = tmp_path / "test-file" sls_contents = """ call_fail_state: salt.state: - tgt: {} - batch: 1 - failhard: True - sls: fail """.format( salt_minion.id ) fail_sls = """ {}: file.managed: - source: salt://hnlcfsdjhkzkdhynclarkhmcls """.format( testfile ) with salt_master.state_tree.base.temp_file( "orch/batch.sls", sls_contents ), salt_master.state_tree.base.temp_file("fail.sls", fail_sls): ret = salt_run_cli.run("state.orchestrate", "orch.batch") assert ret.returncode != 0 data = ret.data["data"][salt_master.id] result = data["salt_|-call_fail_state_|-call_fail_state_|-state"]["result"] changes = data["salt_|-call_fail_state_|-call_fail_state_|-state"]["changes"] assert result is False # The execution should stop after first error, so return dict should contain only one minion assert len(changes["ret"]) == 1 def test_orchestrate_subset( salt_run_cli, salt_master, salt_minion, salt_sub_minion, grains, ): """ test orchestration state using subset """ sls_contents = """ test subset: salt.state: - tgt: '*minion*' - subset: 1 - sls: test """ test_sls = """ test state: test.succeed_without_changes: - name: test """ if os.environ.get("CI_RUN", "0") == "1": if grains["os"] == "Fedora" and int(grains["osrelease"]) == 35: # This test is flaky on Fedora 35 - Don't really know why, because, # of course, this test module passes when running locally on a # Fedora 35 container. pytest.skip("Skipping flaky Fedora 35 test for now, on CI runs.") with salt_master.state_tree.base.temp_file( "orch/subset.sls", sls_contents ), salt_master.state_tree.base.temp_file("test.sls", test_sls): ret = salt_run_cli.run("state.orchestrate", "orch.subset") assert ret.returncode == 0 for state_data in ret.data["data"][salt_master.id].values(): # Should only run in one of the minions comment = state_data["comment"] if salt_minion.id in comment: assert salt_sub_minion.id not in comment elif salt_sub_minion.id in comment: assert salt_minion.id not in comment else: pytest.fail( "None of the targeted minions({}) show up in comment: '{}'".format( ", ".join([salt_minion.id, salt_sub_minion.id]), comment ) )
[ 37811, 198, 51, 3558, 329, 1181, 13, 273, 2395, 23104, 198, 37811, 198, 11748, 28686, 198, 198, 11748, 12972, 9288, 198, 198, 9078, 9288, 4102, 796, 685, 198, 220, 220, 220, 12972, 9288, 13, 4102, 13, 38246, 62, 9288, 11, 198, 60, 6...
2.173687
7,502
import numpy as np import pandas as pd import matplotlib.pyplot as plt # Local import weio def vel_bump(time, A=1, half=False): """ velocity bump, position goes from 0 to A between time[0] and time[-1] half is false: velocity 0 -> max -> 0 half is True: velocity 0 -> max """ time-=time[0] T = np.max(time) if half: # instead of going from t=0 to 1, we gofrom t=0 to 0.5 A = 2*A T = T*2 t = time/T x = A * t**3 * (6*t**2 - 15*t + 10 ) v = 1/T * A * 30*t**2 *(1-t)**2 a = 1/T**2 * A * 60*t *(2*t**2-3*t+1) return x, v, a # --- Rot Motion tMax = 10 dt = 0.1 T = 2 time = np.arange(0,tMax+dt/2,dt) Yaw = np.zeros((len(time), 3)) # angle, velocity, acc Pitch = np.zeros((len(time), 3)) # angle, velocity, acc Rot = np.zeros((len(time), 3)) # angle, velocity, acc # --- First period is one rotation of yaw I = time <= T Ip= time > T x,v,a = vel_bump(time[I], 2*np.pi) Yaw[I,0]+=x Yaw[I,1]=v Yaw[I,2]=a Yaw[Ip,0]+=Yaw[I,0][-1] # --- Second period we pitch one rotation I = np.logical_and(time >= T, time<=2*T) Ip = time>2*T x,v,a = vel_bump(time[I], 2*np.pi) Pitch[I,0]+=x Pitch[I,1]=v Pitch[I,2]=a Pitch[Ip,0]+=Pitch[I,0][-1] # --- Third period we start rotating I = np.logical_and(time >= 2*T, time<=3*T) x,v,a = vel_bump(time[I], np.pi/4, half=True) Rot[I,0]=x Rot[I,1]=v Rot[I,2]=a # --- Constant RPM for the remaining I=time>3*T Rot[I,1]=v[-1] Rot[I,0]=x[-1]+np.cumsum(dt*Rot[I,1]) # --- Fourth period we yaw with some sine motion I = np.logical_and(time >= 3*T, time<=4*T) x,v,a = sine(time[I], np.pi/4) Yaw[I,0]+=x Yaw[I,1]=v Yaw[I,2]=a # --- Fifth period we pitch with some sine motion I = np.logical_and(time >= 4*T, time<=5*T) x,v,a = sine(time[I], np.pi/6) Pitch[I,0]+=x Pitch[I,1]=v Pitch[I,2]=a # --- data = np.column_stack((time, Rot)) df = pd.DataFrame( data=data, columns=['time_[s]', 'azimuth_[rad]','omega_[rad/s]','rotacc_[rad/s^2]']) df.to_csv('RotMotion.csv', index=False, sep=',', float_format='%10.6f') data = np.column_stack((time, Yaw)) df = pd.DataFrame( data=data, columns=['time_[s]', 'yaw_[rad]','yaw_rate_[rad/s]','yaw_acc_[rad/s^2]']) df.to_csv('YawMotion.csv', index=False, sep=',', float_format='%10.6f') data = np.column_stack((time, Pitch)) df = pd.DataFrame( data=data, columns=['time_[s]', 'pitch_[rad]','pitch_rate_[rad/s]','pitch_acc_[rad/s^2]']) df.to_csv('PitchMotion.csv', index=False, sep=',', float_format='%10.6f') # fig,ax = plt.subplots(1, 1, sharey=False, figsize=(6.4,4.8)) # (6.4,4.8) # fig.subplots_adjust(left=0.12, right=0.95, top=0.95, bottom=0.11, hspace=0.20, wspace=0.20) # ax.plot(time, data[:,1] , label='x') # ax.plot(time, data[:,2] , label='v') # ax.plot(time, np.concatenate(([0],np.diff(data[:,1])/dt)),'--', label='v2') # ax.plot(time, data[:,3] , label='a') # ax.plot(time, np.concatenate(([0],np.diff(data[:,2])/dt)),'--', label='a2') # ax.set_xlabel('') # ax.set_ylabel('') # ax.legend() # plt.show() # #
[ 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 2, 10714, 220, 198, 11748, 356, 952, 628, 198, 4299, 11555, 62, 65, 931, 7, 2435, 11, 317, 28, ...
1.983596
1,524
from .batch_converter import BatchConverter from .data_reader import DataReader
[ 6738, 764, 43501, 62, 1102, 332, 353, 1330, 347, 963, 3103, 332, 353, 198, 6738, 764, 7890, 62, 46862, 1330, 6060, 33634 ]
3.590909
22
import os import re import sys import time from pysqvd import SQVD ''' Simple loading script from directory structure root/<group>/workflow/panelid+version/sample/BAM+VCF+BEDGRAPH ''' if __name__ == "__main__": # grab username and password user = os.environ.get("SQVDUSER", default="admin") passwd = os.environ.get("SQVDPASS", default="Kings123") host = os.environ.get("SQVDHOST", default="localhost:3000/sqvd") try: assert user and passwd and host root = sys.argv[1].rstrip('/') assert os.path.isdir(root) except Exception: print(""" python dirLoader.py <DIRECTORY> The directory structure must be like GROUP/WORKFLOW/TESTANDVERSION/SAMPLE/files. eg. genetics/dna_somatic/SWIFT1/ACCRO/*.(vcf.gz|bam|bed|bedgraph) Ensure SQVDUSER, SQVDPASS, SQVDHOST env variables are set! """) else: # dwell time between directories dwell = 0 try: dwell = int(sys.argv[2]) except Exception: pass main(host, user, passwd, root, dwell)
[ 11748, 28686, 198, 11748, 302, 198, 11748, 25064, 198, 11748, 640, 198, 6738, 279, 893, 80, 20306, 1330, 49747, 8898, 198, 198, 7061, 6, 198, 26437, 11046, 4226, 422, 8619, 4645, 198, 15763, 14, 27, 8094, 29, 14, 1818, 11125, 14, 3533...
2.269547
486
# THIS FILE DON'T DO ANYTHING EXCEPT GIVE ME THE PROJECT PATH (i'm listening for better ideas) if __name__ == '__main__': print("DO NOTHING")
[ 2, 12680, 45811, 23917, 6, 51, 8410, 15529, 39356, 7788, 42006, 402, 9306, 11948, 3336, 21965, 23680, 46490, 357, 72, 1101, 8680, 329, 1365, 4213, 8, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 2...
2.94
50
import airsim
[ 11748, 1633, 14323, 220, 628, 220, 220, 220, 220, 198 ]
2.1
10
# Python modules import os import io import base64 import traceback import datetime import pathlib # 3rd party modules import matplotlib matplotlib.use('Agg') import numpy as np from pydicom import Dataset, FileDataset, dcmread, read_file # Our modules import vespa.interfaces.inline.vespa_inline_engine as vie import vespa.analysis.figure_layouts as figure_layouts import vespa.analysis.fileio.util_philips as util_philips import vespa.common.util.time_ as util_time import vespa.common.util.misc as util_misc from vespa.interfaces.inline.vespa_inline_engine import VespaInlineError, VespaInlineSettings VERSION = '0.1.0' #============================================================================== def run(settings, verbose=True): """ There are 4 processing steps: 1. collate all files from specified 'datadir', and sort into 'water', 'metab' etc. 2. load file names into VIE dataset_filename and preset_filename dicts 3. run files through the Vespa-Analysis inline engine 3a. (optional) save provenance XML file and/or PNG/PDF images for debugging. 4. output 'screenshot image' gets put into a pydicom secondary capture RGB DICOM """ msg = '' # these are set here for error checking reasons fdatasets = {'metab':None, 'water':None, 'ecc':None, 'coil':None} fpresets = {'metab':None, 'water':None, 'ecc':None, 'coil':None} dcm_cur = '' try: settings.vespa_version = util_misc.get_vespa_version()+'-VIE' # not really up to the user # --------------------------------------------------------------- # 1. Get filenames from known DATADIR directory and sort # - may move to separate module in future as formats accrue if settings.dataformat == 'philips_press28_dicom': settings.import_class = 'import_philips_dicom' mrs_files = [] other_files = [] for dirpath, dirnames, filenames in os.walk(settings.data_dir): for filename in filenames: ftest = os.path.join(dirpath, filename) if vie.is_dicom(ftest): dataset = read_file(ftest, defer_size=1024) if util_philips.is_mrs_dicom(dataset): mrs_files.append(ftest) if verbose: print('Found DICOM MRS file - '+ftest) else: other_files.append(ftest) if (len(mrs_files) != 2): msg = 'Exception (do_main): Wrong number of DICOM MRS files found in - '+settings.data_dir if verbose: print(msg) raise VespaInlineError(msg) fname_metab, fname_water, fname_ecc, fname_coil = None, None, None, None fname_water = mrs_files[0] fname_metab = mrs_files[1] fname_metab_preset, fname_water_preset, fname_ecc_preset, fname_coil_preset = None, None, None, None fname_metab_preset = os.path.join(settings.preset_dir,'preset_philips_dicom_press28_metab.xml') fname_water_preset = os.path.join(settings.preset_dir,'preset_philips_dicom_press28_water.xml') fname_mmol_basis = None dcm_cur = dcmread(fname_metab) elif settings.dataformat == 'philips_slaser30_cmrr_spar': settings.import_class = 'import_philips_spar' mrs_files = [] other_files = [] for dirpath, dirnames, filenames in os.walk(settings.data_dir): for filename in filenames: ftest = os.path.join(dirpath, filename) if pathlib.Path(ftest).suffix in ['spar','sdat','.SPAR','.SDAT']: mrs_files.append(ftest) if verbose: print('Found Spar/Sdat MRS file - '+ftest) else: other_files.append(ftest) if len(mrs_files) != 4: msg = 'Exception (do_main): Wrong number of Spar/Sdat datasets found in - '+settings.data_dir if verbose: print(msg) raise VespaInlineError(msg) fname_metab, fname_water, fname_ecc, fname_coil = None, None, None, None for fname in mrs_files: if '_act.spar' in fname.lower(): fname_metab = fname if '_ref.spar' in fname.lower(): fname_water = fname if fname_metab is None: msg += '\nException (do_main): Metabolite data Spar/Sdat not found in - '+settings.data_dir if fname_water is None: msg += '\nException (do_main): Water reference Spar/Sdat not found in - '+settings.data_dir if msg: if verbose: print(msg) raise VespaInlineError(msg) fname_metab_preset, fname_water_preset, fname_ecc_preset, fname_coil_preset = None, None, None, None fname_metab_preset = os.path.join(settings.preset_dir,'preset_philips_berrington_spar_metab01.xml') fname_water_preset = os.path.join(settings.preset_dir,'preset_philips_berrington_spar_water01.xml') # fname_metab_preset = os.path.join(settings.preset_dir,'preset_philips_slaser30_cmrr_spar_metab.xml') # fname_water_preset = os.path.join(settings.preset_dir,'preset_philips_slaser30_cmrr_spar_water.xml') fname_mmol_basis = os.path.join(settings.preset_dir,'basis_mmol_simulated_from_seadMM2014_philips_128mhz_dataset.xml') dcm_cur = '' # ---------------------------------------------------------- # 2. load filenames into parameter dicts fdatasets['metab'] = fname_metab fdatasets['water'] = fname_water fdatasets['ecc'] = fname_ecc fdatasets['coil'] = fname_coil fpresets['metab'] = fname_metab_preset fpresets['water'] = fname_water_preset fpresets['ecc'] = fname_ecc_preset fpresets['coil'] = fname_coil_preset fbasis_mmol = fname_mmol_basis # None # ---------------------------------------------------------- # 3. Run the processing params = [fdatasets, fpresets, fbasis_mmol, settings] png_buf, pdf_buf, _ = vie.analysis_kernel( params, verbose=verbose ) buf_shape = 10.24*settings.png_dpi, 10.24*settings.png_dpi, 3 except VespaInlineError as e: if verbose: print('Exception: VespaInlineError - see error report ', str(e)) trace = '' # returned in the VespaInlineError msg png_buf = do_error_processing(e, fdatasets, fpresets, trace, settings) buf_shape = 10.24*settings.png_dpi, 10.24*settings.png_dpi, 3 except Exception as e: if verbose: print('Exception: GeneralException - see error report') trace = traceback.format_exc() png_buf = do_error_processing(e, fdatasets, fpresets, trace, settings) buf_shape = 10.24*settings.png_dpi, 10.24*settings.png_dpi, 3 # ---------------------------------------------------------- # 4. dump dcm_buf to a DICOM RGB file .... if settings.save_dcm: dcm_out = rgb2dcm(png_buf, dcm_cur, buf_shape) dcm_out.save_as(settings.dcm_fname) if settings.save_dcm_pdf: dcm_pdf_out = pdf2dcm(pdf_buf, dcm_cur) dcm_pdf_out.save_as(settings.dcm_pdf_fname) if verbose: print('fname_dicom = ' + settings.dcm_fname) return SSC_TEMPLATE = b'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABESUNNAgAAAFVMBACSAAAAAgABAE9CAAACAAAAAAECAAIAVUkaADEuMi44NDAuMTAwMDguNS4xLjQuMS4xLjcAAgADAFVJAAACABAAVUkUADEuMi44NDAuMTAwMDguMS4yLjEAAgASAFVJHgAxLjMuNDYuNjcwNTg5LjExLjAuMC41MS40LjU2LjECABMAU0gQAFBoaWxpcHMgTVIgNTYuMSAIAAUAQ1MKAElTT19JUiAxMDAIAAgAQ1MAAAgAEgBEQQAACAATAFRNAAAIABQAVUkWADEuMy40Ni42NzA1ODkuMTEuODkuNQAIABYAVUkaADEuMi44NDAuMTAwMDguNS4xLjQuMS4xLjcACAAYAFVJAAAIACAAREEIADIwMTcwMTAxCAAhAERBAAAIACIAREEAAAgAIwBEQQAACAAwAFRNBgAxMTIyMzQIADEAVE0AAAgAMgBUTQAACAAzAFRNAAAIAFAAU0gAAAgAYABDUwIATVIIAGQAQ1MEAFdTRCAIAHAATE8AAAgAgABMTwAACACBAFNUAAAIAJAAUE4AAAgAEBBTSAAACAAwEExPAAAIADIQU1EAAP/////+/93gAAAAAAgAPhBMTwAACABAEExPAAAIAFAQUE4AAAgAcBBQTgAACACAEExPAAAIAJAQTE8IAEluZ2VuaWEgCAAQEVNRAAD//////v8A4P////8IAFARVUkYADEuMi44NDAuMTAwMDguMy4xLjIuMy4xAAgAVRFVSTwAMS4zLjQ2LjY3MDU4OS4xMS4xMDUxNjgwOTcxLjQxNTQzOTY3NjcuMjUzMjI2MzUyOC4yOTkyNjM0MDM1/v8N4AAAAAD+/93gAAAAAAgAERFTUQAA//////7/AOD/////CAAFAENTCgBJU09fSVIgMTAwCAASAERBCAAyMDIwMDQwMQgAEwBUTQoAMDcxMzIyLjM0NggAFABVSTwAMS4zLjQ2LjY3MDU4OS4xMS43NDE3OTIyNjEuMzY5NTY2OTE5Mi40MTg2NjIxNTEzLjQwODg2Njg5NDkACABQEVVJGAAxLjIuODQwLjEwMDA4LjMuMS4yLjMuMwAIAFURVUk6ADEuMy40Ni42NzA1ODkuMTEuMjUyNjE3MjA3OS41NDUzMTgxMjEuMTUxMjgwNjcwMy4yOTEyNjY5MTIgABMASVMCADAgBSAUAExPGgBQaGlsaXBzIE1SIEltYWdpbmcgREQgMDA1IAUgBBRTUwIAAQAFIAYUU1MCAAEA/v8N4AAAAAD+/93gAAAAABAAEABQTgAAEAAgAExPAAAQADAAREEAABAAQABDUwAAEAAQEEFTBAAwMzdZEAAwEERTAAAQAAAgTE8AABAAECFMTwAAEABgIVNIAAAQAIAhU0gAABAAsCFMVAAAEADAIVVTAgAAABAAAEBMVAAAGAAQAExPAAAYABUAQ1MAABgAABBMTwYAMDAwNzEgGAASEERBAAAYABQQVE0AABgAFhBMTwgAUGhpbGlwcyAYABgQTE8IAEluZ2VuaWEgGAAZEExPBgA1LjYuMSAYACAQTE8GADUuNi4xIBgAIxBMTwAAGAAwEExPAAAgAA0AVUkAACAADgBVSQAAIAAQAFNIAAAgABEASVMAACAAEgBJUwAAIAATAElTAgAtMSAAIABDUwAAIABgAENTAAAgAABATFQAACgAAgBVUwIAAwAoAAQAQ1MEAFJHQiAoAAYAVVMCAAAAKAAQAFVTAgAVBigAEQBVUwIAxAgoAAABVVMCAAgAKAABAVVTAgAIACgAAgFVUwIABwAoAAMBVVMCAAAAKAAQIUNTAgAwMDIAMhBQTgAAMgAzEExPAAAyAGAQTE8AADIAcBBMTwAAMgAAQExUAAA4AFAATE8AADgAAAVMTwAAQAAGAFBOAABAAEECQUUOAFJBRFJFU0VBUkNIM1QgQABCAlNIAABAAEMCU0gAAEAARAJEQQgAMjAxNzAxMDFAAEUCVE0GADExMjIzNEAAUAJEQQgAMjAxNzAxMDFAAFECVE0GADExMjIzNEAAUgJDUwAAQABTAlNICgA1MzcyOTQxNTMgQABUAkxPAABAAFUCTE8AAEAAYAJTUQAA//////7/AOD/////CAAAAVNICgBVTkRFRklORUQgCAACAVNICgBVTkRFRklORUQgCAAEAUxPBgB4eHh4eCAIAAsBQ1MCAE4g/v8N4AAAAAD+/93gAAAAAEAAgAJTVAAAQAABEFNIAABAAAIQTE8AAEAAAxBTSAAAQAAEEExPAABAAAUQTE8AAEAAABRMVAAAQAABIExPAABAAAQgREEIADIwMTcwMTAxQAAFIFRNCgAxMTIyMzMuOTUxQAAJIFNIAABAABAgU0gAAEAAACRMVAAAASAQAExPFgBQaGlsaXBzIEltYWdpbmcgREQgMDAxASAdEElTAgAyIAEgThBDUwAAASBhEENTAgBOIAEgYhBDUwIATiABIGMQQ1MKAEVMU0VXSEVSRSABIHcQQ1MAAAEgehBGTAQAAAAAAAEgexBJUwIAOCABIMgQTE8IAEdvQnJhaW4gASDMEFNUAAAFIBAATE8aAFBoaWxpcHMgTVIgSW1hZ2luZyBERCAwMDEgBSARAExPGgBQaGlsaXBzIE1SIEltYWdpbmcgREQgMDAyIAUgEgBMTxoAUGhpbGlwcyBNUiBJbWFnaW5nIEREIDAwMyAFIBMATE8aAFBoaWxpcHMgTVIgSW1hZ2luZyBERCAwMDQgBSAUAExPGgBQaGlsaXBzIE1SIEltYWdpbmcgREQgMDA1IAUgFQBMTxoAUGhpbGlwcyBNUiBJbWFnaW5nIEREIDAwNiAFIDcQQ1MCAE4gBSBfEENTCABVTktOT1dOIAUgYBBJUwIALTEFIJkRVUwEAAAAAAAFIAASVUwEAAEAAAAFIAESVUwEAAAAAAAFIBMSVUwEAAEAAAAFIEUSU1MCAAEABSBJElNTAgAAAAUgURJTUwIAAAAFIFISU1MCAAAABSBTElNTAgAAAAUgVhJTUwIAAQAFIIITVUwEAAAAAAAFIJETUE4AAAUglxNMTwAABSABFFVMBAABAAAABSADFFVMBAAAAAAABSAEFFNTAgABAAUgBhRTUwIAAQAFIA8UU1EAAP/////+/wDg//////7/DeAAAAAA/v/d4AAAAAAFICoUQ1MIAElOSVRJQUwgBSArFENTCABJTklUSUFMIAUgLBRDUwgASU5JVElBTCAFIC0UQ1MKAENPTVBMRVRFRCAFIDoUTFQaAGRhdGFkZWZzICRSZXZpc2lvbjogNTYuMCAkBSB0FURTAgAwIAUgdRVEUwIAMCAFIHYVTFQAAAUgeBVDUwQATk9ORQUggRVDUwoARklSU1RMRVZFTAUgghVJUwIAMCAFIIMVTFQAAAUghRVEUwIAMCAFIIYVTFQIAEdhdXNzL2NtBSCHFURTAgAwIOB/EABPVwAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=' if __name__ == '__main__': fname_tstamp = util_time.filename_timestamp() # yyyymmdd.hhmmss.usecs # get defaults settings = VespaInlineSettings() # reset relative to 'this' filename, not to vespa_inline_engine location settings.base_path = os.path.dirname(os.path.abspath(__file__)) settings.data_dir = os.path.join(settings.base_path, 'datadir') settings.preset_dir = os.path.join(settings.base_path, 'presets') settings.output_dir = os.path.join(settings.base_path, 'output') settings.debug_dir = os.path.join(settings.base_path, 'debug') settings.dataformat = 'philips_press28_dicom' #settings.dataformat = 'philips_slaser30_cmrr_spar' settings.save_err = True settings.save_xml = True settings.save_pdf = True settings.save_png = True settings.save_dcm = True settings.save_dcm_pdf = True settings.err_fname_unique = True settings.xml_fname_unique = True settings.pdf_fname_unique = True settings.png_fname_unique = True settings.dcm_fname_unique = True settings.dcm_pdf_fname_unique = True settings.err_fname = os.path.join(settings.debug_dir, "debug_vespa_viff.png") settings.xml_fname = os.path.join(settings.debug_dir, "debug_xml_last_run.xml") settings.pdf_fname = os.path.join(settings.debug_dir, "debug_pdf_philips.pdf") settings.png_fname = os.path.join(settings.output_dir, "results_vespa_inline_philips.png") settings.dcm_fname = os.path.join(settings.output_dir, "results_vespa_inline_dicom.dcm") settings.dcm_pdf_fname = os.path.join(settings.output_dir, "results_vespa_inline_dicom_pdf.dcm") settings.pdf_plotstyle = 'lcm_multi' settings.pdf_file_label = 'Analysis- Philips PRIDE Inline' settings.pdf_minppm = 0.5 settings.pdf_maxppm = 4.2 settings.pdf_apply_phase = False settings.pdf_remove_base = False settings.pdf_fontname = 'Courier New' settings.pdf_dpi = 300 settings.pdf_pad_inches = 0.5 settings.png_plotstyle = 'lcm_square' settings.png_file_label = 'Analysis- Philips PRIDE Inline' settings.png_minppm = 0.5 settings.png_maxppm = 4.2 settings.png_apply_phase = False settings.png_remove_base = False settings.png_fontname = 'Courier New' settings.png_dpi = 100 settings.png_pad_inches = 0.5 settings.err_dpi = 100 settings.err_pad_inches = 0.5 settings.debug = False run(settings)
[ 198, 2, 11361, 13103, 198, 11748, 28686, 198, 11748, 33245, 198, 11748, 2779, 2414, 198, 11748, 12854, 1891, 198, 11748, 4818, 8079, 198, 11748, 3108, 8019, 198, 198, 2, 513, 4372, 2151, 13103, 198, 11748, 2603, 29487, 8019, 198, 6759, ...
2.019035
6,777
# -*- coding: utf-8 -*- # # Copyright 2018 Data61, CSIRO # # 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 # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import collections def is_real_iterable(x): """ Tests if x is an iterable and is not a string. Args: x: Returns: True if x is an iterable (but not a string) and False otherwise """ return isinstance(x, collections.Iterable) and not isinstance(x, (str, bytes))
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 2, 15069, 2864, 6060, 5333, 11, 9429, 43708, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345...
3.220641
281
# -*- coding: utf-8 -*- import base64 from keywordgroup import KeywordGroup from appium.webdriver.connectiontype import ConnectionType
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 2779, 2414, 198, 198, 6738, 21179, 8094, 1330, 7383, 4775, 13247, 198, 6738, 598, 1505, 13, 12384, 26230, 13, 38659, 4906, 1330, 26923, 6030, 198 ]
3.4
40
import time from owlracer.env import Env as Owlracer_Env from owlracer import owlParser @owlParser if __name__ == '__main__': main_loop()
[ 11748, 640, 198, 6738, 39610, 11510, 263, 13, 24330, 1330, 2039, 85, 355, 37007, 11510, 263, 62, 4834, 85, 198, 6738, 39610, 11510, 263, 1330, 39610, 46677, 628, 198, 31, 4883, 46677, 628, 198, 361, 11593, 3672, 834, 6624, 705, 834, 1...
2.754717
53
### channel configuration CHANNEL_NAME = 'ThreatWire' CHANNEL_PLAYLIST_ID = 'PLW5y1tjAOzI0Sx4UU2fncEwQ9BQLr5Vlu' ITEMS_TO_SCAN = 5 FG_YOUTUBE = 'https://www.youtube.com/channel/UC3s0BtrBJpwNDaflRSoiieQ' # channel link FG_AUTHOR = {'name':'Shannon Morse','email':'shannon@hak5.org'} ### data storage and history ITEMS_TO_KEEP = 25 HISTORY_JSON = 'history.json' PODCAST_FILE = 'podcast.rss' ### web hosting WEB_HOST_DIRECTORY = '/var/www/html/ytp' WEB_BASE_URL = 'http://10.0.1.25/ytp/' ### api stuff API_KEY = 'insert your api key here so you won’t get rate-limited' API_PLAYLIST_URL = 'https://www.googleapis.com/youtube/v3/playlistItems?key={}&part=snippet&contentDetails&status&maxResults={}&playlistId={}' ### other config items REFRESH_TIME = 7200 # in seconds, this is 2 hours FFMPEG_CMD = 'ffmpeg -i {} -b:a 192K -vn {}' TEMP_DIRECTORY = '/tmp/yt-podcast/'
[ 21017, 6518, 8398, 198, 198, 3398, 22846, 3698, 62, 20608, 796, 705, 817, 630, 29451, 6, 198, 3398, 22846, 3698, 62, 31519, 45849, 62, 2389, 796, 705, 6489, 54, 20, 88, 16, 83, 73, 32, 46, 89, 40, 15, 50, 87, 19, 30100, 17, 69, ...
2.311346
379
# -*- coding: utf-8 -*- ### # (C) Copyright (2012-2019) Hewlett Packard Enterprise Development LP # # 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, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. ### from pprint import pprint from hpOneView.oneview_client import OneViewClient from config_loader import try_load_from_file # This resource is only available on HPE Synergy config = { "ip": "<oneview_ip>", "credentials": { "userName": "<username>", "password": "<password>" } } # Try load config from a file (if there is a config file) config = try_load_from_file(config) oneview_client = OneViewClient(config) sas_interconnects = oneview_client.sas_interconnects # Get all, with defaults print("\nGet all SAS Interconnects") all_sas_interconnects = sas_interconnects.get_all() pprint(all_sas_interconnects) # Get the first 10 records print("\nGet the first ten SAS Interconnects") sas_interconnects_limited = sas_interconnects.get_all(0, 10) pprint(sas_interconnects_limited) if all_sas_interconnects: sas_interconnect_uri = all_sas_interconnects[0]['uri'] # Get by Uri print("\nGet a SAS Interconnect by uri") sas_interconnect_by_uri = sas_interconnects.get_by_uri(sas_interconnect_uri) pprint(sas_interconnect_by_uri.data) if sas_interconnect_by_uri.data["powerState"] == 'Off': print("\nTurn on power for SAS interconnect %s" % sas_interconnect_by_uri.data['name']) sas_interconnect_by_uri.patch( operation='replace', path='/powerState', value='On' ) print("Done!") print("\nRefresh a SAS interconnect") sas_interconnect_by_uri.refresh_state( configuration={"refreshState": "RefreshPending"} ) print("Done!") print("\nTurn 'On' UID light on SAS interconnect %s" % sas_interconnect_by_uri.data['name']) sas_interconnect_by_uri.patch( operation='replace', path='/uidState', value='On' ) print("Done!") print("\nSoft Reset SAS interconnect %s" % sas_interconnect_by_uri.data['name']) sas_interconnect_by_uri.patch( operation='replace', path='/softResetState', value='Reset' ) print("Done!") print("\nReset SAS interconnect %s" % sas_interconnect_by_uri.data['name']) sas_interconnect_by_uri.patch( operation='replace', path='/hardResetState', value='Reset' ) print("Done!") print("\nTurn off power for SAS interconnect %s" % sas_interconnect_by_uri.data['name']) sas_interconnect_by_uri.patch( operation='replace', path='/powerState', value='Off' ) print("Done!")
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 21017, 198, 2, 357, 34, 8, 15069, 357, 6999, 12, 23344, 8, 30446, 15503, 6400, 446, 14973, 7712, 18470, 198, 2, 198, 2, 2448, 3411, 318, 29376, 7520, 11, 1479, 286, ...
2.696296
1,350
from __future__ import annotations import json import logging from contextlib import AsyncExitStack, closing from datetime import datetime, timedelta, timezone from json import JSONDecodeError from typing import Any, Callable, Dict, Iterable, List, Optional, Set, Tuple, Type, Union from uuid import UUID import sniffio from anyio import TASK_STATUS_IGNORED, create_task_group, sleep from attr import asdict from sqlalchemy import ( Column, DateTime, Integer, LargeBinary, MetaData, Table, Unicode, and_, bindparam, func, or_, select) from sqlalchemy.engine import URL from sqlalchemy.exc import CompileError, IntegrityError from sqlalchemy.ext.asyncio import AsyncConnection, create_async_engine from sqlalchemy.ext.asyncio.engine import AsyncConnectable from sqlalchemy.sql.ddl import DropTable from ... import events as events_module from ...abc import AsyncDataStore, Job, Schedule, Serializer from ...events import ( AsyncEventHub, DataStoreEvent, Event, JobAdded, JobDeserializationFailed, ScheduleAdded, ScheduleDeserializationFailed, ScheduleRemoved, ScheduleUpdated, SubscriptionToken) from ...exceptions import ConflictingIdError, SerializationError from ...policies import ConflictPolicy from ...serializers.pickle import PickleSerializer from ...util import reentrant logger = logging.getLogger(__name__) @reentrant
[ 6738, 11593, 37443, 834, 1330, 37647, 198, 198, 11748, 33918, 198, 11748, 18931, 198, 6738, 4732, 8019, 1330, 1081, 13361, 30337, 25896, 11, 9605, 198, 6738, 4818, 8079, 1330, 4818, 8079, 11, 28805, 12514, 11, 640, 11340, 198, 6738, 33918...
3.520833
384
#!/usr/bin/env python # coding: utf-8 """ run consensus analysis to identify overall pattern analysis method developed by T Nichols and J Mumford """ import os import sys import glob import numpy import nibabel import nilearn.plotting import nilearn.input_data import matplotlib.pyplot as plt from statsmodels.stats.multitest import multipletests import scipy.stats from narps import Narps, hypnums, hypotheses from narps import NarpsDirs # noqa, flake8 issue from utils import log_to_file def t_corr(y, res_mean=None, res_var=None, Q=None): """ perform a one-sample t-test on correlated data y = data (n observations X n vars) res_mean = Common mean over voxels and results res_var = Common variance over voxels and results Q = "known" correlation across observations - (use empirical correlation based on maps) """ npts = y.shape[0] X = numpy.ones((npts, 1)) if res_mean is None: res_mean = 0 if res_var is None: res_var = 1 if Q is None: Q = numpy.eye(npts) VarMean = res_var * X.T.dot(Q).dot(X) / npts**2 # T = mean(y,0)/s-hat-2 # use diag to get s_hat2 for each variable T = (numpy.mean(y, 0)-res_mean )/numpy.sqrt(VarMean)*numpy.sqrt(res_var) + res_mean # Assuming variance is estimated on whole image # and assuming infinite df p = 1 - scipy.stats.norm.cdf(T) return(T, p) if __name__ == "__main__": # set an environment variable called NARPS_BASEDIR # with location of base directory if 'NARPS_BASEDIR' in os.environ: basedir = os.environ['NARPS_BASEDIR'] else: basedir = '/data' # setup main class narps = Narps(basedir) narps.load_data() narps.dirs.dirs['consensus'] = os.path.join( narps.dirs.dirs['output'], 'consensus_analysis') logfile = os.path.join( narps.dirs.dirs['logs'], '%s.txt' % sys.argv[0].split('.')[0]) log_to_file( logfile, 'running %s' % sys.argv[0].split('.')[0], flush=True) if not os.path.exists(narps.dirs.dirs['consensus']): os.mkdir(narps.dirs.dirs['consensus']) run_ttests(narps, logfile) mk_figures(narps, logfile)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 19617, 25, 3384, 69, 12, 23, 198, 37811, 198, 5143, 11529, 3781, 284, 5911, 4045, 3912, 198, 20930, 2446, 4166, 416, 309, 38403, 290, 449, 38367, 3841, 198, 37811, 628, 198, 11748, ...
2.344937
948
"""PyTest configuration.""" from __future__ import annotations from typing import Any from _pytest.assertion import truncate truncate.DEFAULT_MAX_LINES = 40 truncate.DEFAULT_MAX_CHARS = 40 * 80
[ 37811, 20519, 14402, 8398, 526, 15931, 198, 6738, 11593, 37443, 834, 1330, 37647, 198, 198, 6738, 19720, 1330, 4377, 198, 198, 6738, 4808, 9078, 9288, 13, 30493, 295, 1330, 40122, 378, 198, 198, 2213, 19524, 378, 13, 7206, 38865, 62, 22...
3.142857
63
"""Module which extends the scenepic Mesh type.""" # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import numpy as np from ._scenepic import Mesh, MeshUpdate class VertexBuffer: """Class which provides dictionary access to vertex buffer blocks. Description: The different parts of the vertex buffer can be accessed via a dictionary interface: - "pos": the vertex positions - "norm": the vertex normals - "rgb": the vertex colors (if present) - "uv": the vertex uvs (if present) Args: values (np.ndarray): The raw vertex buffer values """ def __init__(self, values: np.ndarray): """Initializer.""" self._values = values self._lookup = { "pos": slice(0, 3), "norm": slice(3, 6), "rgb": slice(6, 9), "uv": slice(6, 8) } @property def shape(self) -> tuple: """Shape of the entire vertex buffer.""" return self._values.shape def copy(self) -> "VertexBuffer": """Returns a copy of the vertex buffer.""" return VertexBuffer(self._values.copy()) def __repr__(self) -> str: """Return a string representation of the vertex buffer.""" return str(self._values) def __getitem__(self, key: str) -> np.ndarray: """Returns a sub-section of the buffer given the key. Args: key (str): one of ["pos", "norm", "rgb", "uv"] Returns: np.ndarray: a subsection of the buffer """ assert key in self._lookup, "Invalid vertex buffer key " + key return self._values[:, self._lookup[key]] def __setitem__(self, key: str, data: np.ndarray): """Sets a subsection of the buffer specified by the key. Args: key (str): one of ["pos", "norm", "rgb", "uv"] data (np.ndarray): The new values to place in the buffer """ assert key in self._lookup, "Invalid vertex buffer key " + key self._values[:, self._lookup[key]] = data def vertex_buffer(self): """VertexBuffer: a reference to the vertex buffer.""" return VertexBuffer(self.get_vertex_buffer()) def quantize(self, keyframe_index: int, fixed_point_range: float, keyframe_vertex_buffer: VertexBuffer): """Quantize the mesh update. Args: self (MeshUpdate): self reference keyframe_index (int): Index of the keyframe to use in quantizing this update fixed_point_range (float): The range to use for the fixed point representation. keyframe_vertex_buffer (VertexBuffer): The keyframe vertex buffer """ self.quantize_(keyframe_index, fixed_point_range, keyframe_vertex_buffer._values) def difference_range(self, vertex_buffer: VertexBuffer) -> float: """Returns the absolute range of values in the difference between this update and the buffer. Args: self (MeshUpdate): self reference vertex_buffer (VertexBuffer): the buffer to use in the comparison Return: float: the absolute range (from minimum to maximum) in the per-index difference between this update and the reference. """ self.difference_range_(vertex_buffer._values) Mesh.vertex_buffer = property(vertex_buffer) MeshUpdate.vertex_buffer = property(vertex_buffer) MeshUpdate.quantize = quantize MeshUpdate.difference_range = difference_range
[ 37811, 26796, 543, 14582, 262, 4408, 538, 291, 47529, 2099, 526, 15931, 198, 198, 2, 15069, 357, 66, 8, 5413, 10501, 13, 198, 2, 49962, 739, 262, 17168, 13789, 13, 198, 198, 11748, 299, 32152, 355, 45941, 198, 198, 6738, 47540, 1416, ...
2.661515
1,294
from django.contrib import admin from django.db import models from django import forms from bespeak_meal.models import Person, Person_category, Week_menu admin.site.register(Person, PersonAdmin) admin.site.register(Person_category, Person_categoryAdmin) admin.site.register(Week_menu, Week_menuAdmin)
[ 6738, 42625, 14208, 13, 3642, 822, 1330, 13169, 198, 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 6738, 42625, 14208, 1330, 5107, 198, 198, 6738, 7284, 36729, 62, 28208, 13, 27530, 1330, 7755, 11, 7755, 62, 22872, 11, 6119, 62, 26272,...
3.494253
87
from django.urls import path from . import views urlpatterns = [ path('', views.home, name='admin-home'), path('tables/', views.tables, name='tables'), path('get_tenant', views.get_tenant), ]
[ 6738, 42625, 14208, 13, 6371, 82, 1330, 3108, 198, 6738, 764, 1330, 5009, 198, 198, 6371, 33279, 82, 796, 685, 198, 220, 220, 220, 3108, 10786, 3256, 5009, 13, 11195, 11, 1438, 11639, 28482, 12, 11195, 33809, 198, 220, 220, 220, 3108,...
2.649351
77
#!/usr/bin/env python import sys import time import math import numpy from scipy import ndimage from pyami import imagefun from appionlib import apDisplay from appionlib.apImage import imagefile #========================= def classicradon(image, stepsize=2): """ computes Radon transform of image """ radonlist = [] nsteps = int(math.ceil(180/stepsize)) blackcircle = imagefun.filled_circle(image.shape, image.shape[0]/2*0.75) mask = 1 - blackcircle maskline = mask.sum(axis=0) + 1 for i in range(nsteps): rotated = ndimage.rotate(image, -i*stepsize, reshape=False, order=1) rotated = mask*rotated line = rotated.sum(axis=0) radonlist.append(line/maskline) radon = numpy.array(radonlist) radon = radon/radon.std() #radonlr = numpy.fliplr(radon) #radon = numpy.vstack((radon, radonlr)) return radon #========================= def classicradonlist(imagelist, stepsize=2, maskrad=None, msg=None): """ computes Radon transform of image list """ t0 = time.time() if msg is None and len(imagelist) > 50: msg = True elif msg is None: msg = False radonimagelist = [] if msg is True: apDisplay.printMsg("Performing Radon transforms with one processor") for imageid in range(len(imagelist)): if msg is True and imageid % 50 == 0: ### FUTURE: add time estimate sys.stderr.write(".") image = imagelist[imageid] radonimage = classicradon(image, stepsize) radonimagelist.append(radonimage) if msg is True: sys.stderr.write("\n") print "Classic Radon images complete in %s"%(apDisplay.timeString(time.time()-t0)) return radonimagelist #========================= #========================= #========================= def radonImage(image, imageid, stepsize, mask, queue): """ computes Radon transform of single image, requires multiprocessing queue """ radonlist = [] nsteps = int(math.ceil(180/float(stepsize))) maskline = mask.sum(axis=0) + 1 ### rotate image and assemble radon image for i in range(nsteps): angle = -i*stepsize rotated = ndimage.rotate(image, angle, reshape=False, order=1) rotated = mask*rotated line = rotated.sum(axis=0) radonlist.append(line/maskline) radon = numpy.array(radonlist) ### normalize standard deviation radon = radon/radon.std() ### this does not work with shifting #radonlr = numpy.fliplr(radon) #radon = numpy.vstack((radon, radonlr)) queue.put([imageid, radon]) return #========================= def radonlist(imagelist, stepsize=2, maskrad=None, msg=None): """ computes Radon transform of image list """ if msg is None and len(imagelist) > 50: msg = True elif msg is None: msg = False ### Note: multiprocessing version not compatible with python 2.4 from multiprocessing import Queue, Process t0 = time.time() ### prepare mask shape = imagelist[0].shape if maskrad is None: maskrad = shape[0]/2 blackcircle = imagefun.filled_circle(shape, maskrad) mask = 1 - blackcircle ### preform radon transform for each image queuelist = [] if msg is True: apDisplay.printMsg("Performing Radon transforms with multiprocessor") for imageid in range(len(imagelist)): if msg is True and imageid % 50 == 0: ### FUTURE: add time estimate sys.stderr.write(".") image = imagelist[imageid] queue = Queue() queuelist.append(queue) #below is equivalent to "radonImage(image, imageid, stepsize, mask, queue)" proc = Process(target=radonImage, args=(image, imageid, stepsize, mask, queue)) proc.start() proc.join() ### assemble radon image list radonimagelist = range(len(imagelist)) for queue in queuelist: imageid, radonimage = queue.get() radonimagelist[imageid] = radonimage if msg is True: sys.stderr.write("\n") print "Multi Radon images complete in %s"%(apDisplay.timeString(time.time()-t0)) return radonimagelist #========================= #========================= if __name__ == "__main__": t0 = time.time() a = numpy.zeros((512,512)) a[128:256,256:384] = 1 a += numpy.random.random((512,512)) radon(a, 0.5) radon2(a, 0.5) print "Completed in %s"%(apDisplay.timeString(time.time() - t0))
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 11748, 25064, 198, 11748, 640, 198, 11748, 10688, 198, 11748, 299, 32152, 198, 6738, 629, 541, 88, 1330, 299, 67, 9060, 198, 6738, 12972, 6277, 1330, 2939, 12543, 198, 6738, 598, ...
2.729041
1,491
# -*- coding: utf-8 -*- # Define here the models for your spider middleware # # See documentation in: # https://docs.scrapy.org/en/latest/topics/spider-middleware.html from scrapy import signals # ua_list = [ # 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0', # 'Mozilla/5.0 (Macintosh; Intel Mac OS X x.y; rv:42.0) Gecko/20100101 Firefox/42.0', # 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36', # 'Opera/9.80 (Macintosh; Intel Mac OS X; U; en) Presto/2.2.15 Version/10.00' # ] # # custom_settings = { # "COOKIES_ENABLED": False, # "DOWNLOAD_DELAY": 1, # 'DEFAULT_REQUEST_HEADERS': { # 'Accept': 'application/json, text/javascript, */*; q=0.01', # 'Accept-Encoding': 'gzip, deflate, br', # 'Accept-Language': 'zh-CN,zh;q=0.8', # 'Connection': 'keep-alive', # 'Cookie': 'user_trace_token=20171015132411-12af3b52-3a51-466f-bfae-a98fc96b4f90; LGUID=20171015132412-13eaf40f-b169-11e7-960b-525400f775ce; SEARCH_ID=070e82cdbbc04cc8b97710c2c0159ce1; ab_test_random_num=0; X_HTTP_TOKEN=d1cf855aacf760c3965ee017e0d3eb96; showExpriedIndex=1; showExpriedCompanyHome=1; showExpriedMyPublish=1; hasDeliver=0; PRE_UTM=; PRE_HOST=www.baidu.com; PRE_SITE=https%3A%2F%2Fwww.baidu.com%2Flink%3Furl%3DsXIrWUxpNGLE2g_bKzlUCXPTRJMHxfCs6L20RqgCpUq%26wd%3D%26eqid%3Dee53adaf00026e940000000559e354cc; PRE_LAND=https%3A%2F%2Fwww.lagou.com%2F; index_location_city=%E5%85%A8%E5%9B%BD; TG-TRACK-CODE=index_hotjob; login=false; unick=""; _putrc=""; JSESSIONID=ABAAABAAAFCAAEG50060B788C4EED616EB9D1BF30380575; _gat=1; _ga=GA1.2.471681568.1508045060; LGSID=20171015203008-94e1afa5-b1a4-11e7-9788-525400f775ce; LGRID=20171015204552-c792b887-b1a6-11e7-9788-525400f775ce', # 'Host': 'www.lagou.com', # 'Origin': 'https://www.lagou.com', # 'Referer': 'https://www.lagou.com/', # 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36', # } # }
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 2, 2896, 500, 994, 262, 4981, 329, 534, 19230, 3504, 1574, 198, 2, 198, 2, 4091, 10314, 287, 25, 198, 2, 3740, 1378, 31628, 13, 1416, 2416, 88, 13, 2398, 14, ...
1.940232
1,121
from ..candles_providers import CandlesProvider from ..candle_properties import CandleProperties from ..timeframes import Timeframes from .timeframe_values import TimeframeValues from .float_generator import FloatGenerator class MarketDataStorage: """ Stores historical market data that was reserved by oscillators It can be accessed by providing desired timeframe, property and size """ def get( self, timeframe: Timeframes, property: CandleProperties, max_size: int ) -> FloatGenerator: """ Return at most `max_size` of `property` values of `timeframe` candles :param timeframe: buffer will be associated with this timeframe :param property: OHLCV property to store :param size: max size of buffer """ timeframe_values = self._timeframes_values[timeframe] return timeframe_values.get(property, max_size) def reserve( self, timeframe: Timeframes, property: CandleProperties, size: int ) -> None: """ Reserves buffer to store at most `size` of `property` values of `timeframe` candles If already has one, will be resized if needed :param timeframe: buffer will be associated with this timeframe :param property: OHLCV property to store :param size: max size of buffer """ if not timeframe in self._timeframes_values: self._timeframes_values[timeframe] = TimeframeValues(timeframe, self._market_data) timeframe_values = self._timeframes_values[timeframe] if not property in timeframe_values: timeframe_values.add_property_buffer(property, size) property_buffer = timeframe_values.get_property_buffer(property) if property_buffer.capacity() < size: property_buffer.resize(size) def update(self) -> None: """ Runs each time a new candle closes Each value buffer will be updated by the new candle if needed """ for timeframe_values in self._timeframes_values.values(): timeframe_values.update()
[ 6738, 11485, 46188, 829, 62, 15234, 4157, 1330, 15518, 829, 29495, 201, 198, 6738, 11485, 46188, 293, 62, 48310, 1330, 44973, 2964, 18200, 201, 198, 6738, 11485, 2435, 37805, 1330, 3862, 37805, 201, 198, 6738, 764, 2435, 14535, 62, 27160,...
2.393661
978
import datetime from django.http import HttpResponseRedirect from django.utils.deprecation import MiddlewareMixin from users.models import UserSession
[ 11748, 4818, 8079, 198, 198, 6738, 42625, 14208, 13, 4023, 1330, 367, 29281, 31077, 7738, 1060, 198, 6738, 42625, 14208, 13, 26791, 13, 10378, 8344, 341, 1330, 6046, 1574, 35608, 259, 628, 198, 6738, 2985, 13, 27530, 1330, 11787, 36044, ...
3.780488
41
#!/usr/bin/env python # Copyright 2014-2018 The PySCF Developers. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Author: Qiming Sun <osirpt.sun@gmail.com> # ''' Effective core potential (ECP) This module exposes some ecp integration functions from the C implementation. Reference for ecp integral computation * Analytical integration J. Chem. Phys. 65, 3826 J. Chem. Phys. 111, 8778 J. Comput. Phys. 44, 289 * Numerical integration J. Comput. Chem. 27, 1009 Chem. Phys. Lett. 296, 445 ''' import ctypes import numpy from pyscf import lib from pyscf.gto import moleintor libecp = moleintor.libcgto libecp.ECPscalar_cache_size.restype = ctypes.c_int AS_ECPBAS_OFFSET= 18 AS_NECPBAS = 19 def so_by_shell(mol, shls): '''Spin-orbit coupling ECP in spinor basis i/2 <Pauli_matrix dot l U(r)> ''' li = mol.bas_angular(shls[0]) lj = mol.bas_angular(shls[1]) di = (li*4+2) * mol.bas_nctr(shls[0]) dj = (lj*4+2) * mol.bas_nctr(shls[1]) bas = numpy.vstack((mol._bas, mol._ecpbas)) mol._env[AS_ECPBAS_OFFSET] = len(mol._bas) mol._env[AS_NECPBAS] = len(mol._ecpbas) buf = numpy.empty((di,dj), order='F', dtype=numpy.complex128) cache = numpy.empty(buf.size*48) fn = libecp.ECPso_spinor fn(buf.ctypes.data_as(ctypes.c_void_p), (ctypes.c_int*2)(di, dj), (ctypes.c_int*2)(*shls), mol._atm.ctypes.data_as(ctypes.c_void_p), ctypes.c_int(mol.natm), bas.ctypes.data_as(ctypes.c_void_p), ctypes.c_int(mol.nbas), mol._env.ctypes.data_as(ctypes.c_void_p), lib.c_null_ptr(), cache.ctypes.data_as(ctypes.c_void_p)) return buf if __name__ == '__main__': from pyscf import gto, scf mol = gto.M(atom=''' Cu 0. 0. 0. H 0. 0. -1.56 H 0. 0. 1.56 ''', basis={'Cu':'lanl2dz', 'H':'sto3g'}, ecp = {'cu':'lanl2dz'}, #basis={'Cu':'crenbs', 'H':'sto3g'}, #ecp = {'cu':'crenbs'}, charge=-1, verbose=4) mf = scf.RHF(mol) print(mf.kernel(), -196.09477546034623) mol = gto.M(atom=''' Na 0. 0. 0. H 0. 0. 1. ''', basis={'Na':'lanl2dz', 'H':'sto3g'}, ecp = {'Na':'lanl2dz'}, verbose=0) mf = scf.RHF(mol) print(mf.kernel(), -0.45002315562861461)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 15069, 1946, 12, 7908, 383, 9485, 6173, 37, 34152, 13, 1439, 6923, 33876, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, ...
2.136604
1,325
from setuptools import setup, find_packages config = { 'description':'fingerid-package', 'author':'Huibin Shen', 'url':'project https://github.com/icdishb/fingerid', 'author_email':'huibin.shen@aalto.fi', 'version':'1.4', 'install_requires':['nose'], 'packages':find_packages(), 'name':'fingerid', } setup(**config)
[ 198, 198, 6738, 900, 37623, 10141, 1330, 9058, 11, 1064, 62, 43789, 198, 198, 11250, 796, 1391, 198, 220, 220, 220, 705, 11213, 10354, 6, 35461, 312, 12, 26495, 3256, 198, 220, 220, 220, 705, 9800, 10354, 6, 38202, 571, 259, 22323, ...
2.394558
147
""" Basic functions on surface meshes. """ # Author: Oualid Benkarim <oualid.benkarim@mcgill.ca> # License: BSD 3 clause import warnings import numpy as np from vtk import (vtkDataObject, vtkThreshold, vtkGeometryFilter, vtkAppendPolyData) from .array_operations import get_connected_components from ..vtk_interface import wrap_vtk, serial_connect, get_output from ..vtk_interface.pipeline import connect from ..vtk_interface.decorators import wrap_input ASSOC_CELLS = vtkDataObject.FIELD_ASSOCIATION_CELLS ASSOC_POINTS = vtkDataObject.FIELD_ASSOCIATION_POINTS @wrap_input(0) def _surface_selection(surf, array_name, low=-np.inf, upp=np.inf, use_cell=False, keep=True): """Selection of points or cells meeting some thresholding criteria. Parameters ---------- surf : vtkPolyData or BSPolyData Input surface. array_name : str or ndarray Array used to perform selection. low : float or -np.inf Lower threshold. Default is -np.inf. upp : float or np.inf Upper threshold. Default is +np.inf. use_cell : bool, optional If True, apply selection to cells. Otherwise, use points. Default is False. keep : bool, optional If True, elements within the thresholds (inclusive) are kept. Otherwise, are discarded. Default is True. Returns ------- surf_selected : BSPolyData Surface after thresholding. """ if low > upp: raise ValueError('Threshold limits are not valid: {0} -- {1}'. format(low, upp)) at = 'c' if use_cell else 'p' if isinstance(array_name, np.ndarray): drop_array = True array = array_name array_name = surf.append_array(array, at=at) else: drop_array = False array = surf.get_array(name=array_name, at=at, return_name=False) if array.ndim > 1: raise ValueError('Arrays has more than one dimension.') if low == -np.inf: low = array.min() if upp == np.inf: upp = array.max() if keep is False: raise ValueError("Don't support 'keep=False'.") # tf = wrap_vtk(vtkThreshold, invert=not keep) tf = wrap_vtk(vtkThreshold) tf.ThresholdBetween(low, upp) if use_cell: tf.SetInputArrayToProcess(0, 0, 0, ASSOC_CELLS, array_name) else: tf.SetInputArrayToProcess(0, 0, 0, ASSOC_POINTS, array_name) gf = wrap_vtk(vtkGeometryFilter(), merging=False) surf_sel = serial_connect(surf, tf, gf) # Check results mask = np.logical_and(array >= low, array <= upp) if keep: n_expected = np.count_nonzero(mask) else: n_expected = np.count_nonzero(~mask) n_sel = surf_sel.n_cells if use_cell else surf_sel.n_points if n_expected != n_sel: element = 'cells' if use_cell else 'points' warnings.warn('The number of selected {0} is different than expected. ' 'This may be due to the topology after after selection: ' 'expected={1}, selected={2}.'. format(element, n_expected, n_sel)) if drop_array: surf.remove_array(name=array_name, at=at) surf_sel.remove_array(name=array_name, at=at) return surf_sel @wrap_input(0) def _surface_mask(surf, mask, use_cell=False): """Selection fo points or cells meeting some criteria. Parameters ---------- surf : vtkPolyData or BSPolyData Input surface. mask : str or ndarray Binary boolean or integer array. Zero or False elements are discarded. use_cell : bool, optional If True, apply selection to cells. Otherwise, use points. Default is False. Returns ------- surf_masked : BSPolyData PolyData after masking. """ if isinstance(mask, np.ndarray): if np.issubdtype(mask.dtype, np.bool_): mask = mask.astype(np.uint8) else: mask = surf.get_array(name=mask, at='c' if use_cell else 'p') if np.any(np.unique(mask) > 1): raise ValueError('Cannot work with non-binary mask.') return _surface_selection(surf, mask, low=1, upp=1, use_cell=use_cell, keep=True) def drop_points(surf, array_name, low=-np.inf, upp=np.inf): """Remove surface points whose values fall within the threshold. Cells corresponding to these points are also removed. Parameters ---------- surf : vtkPolyData or BSPolyData Input surface. array_name : str or 1D ndarray Array used to perform selection. If str, it must be an array in the PointData attributes of the PolyData. low : float or -np.inf Lower threshold. Default is -np.inf. upp : float or np.inf Upper threshold. Default is np.inf. Returns ------- surf_selected : vtkPolyData or BSPolyData PolyData after thresholding. See Also -------- :func:`drop_cells` :func:`select_points` :func:`mask_points` """ return _surface_selection(surf, array_name, low=low, upp=upp, keep=False) def drop_cells(surf, array_name, low=-np.inf, upp=np.inf): """Remove surface cells whose values fall within the threshold. Points corresponding to these cells are also removed. Parameters ---------- surf : vtkPolyData or BSPolyData Input surface. array_name : str or 1D ndarray Array used to perform selection. If str, it must be an array in the CellData attributes of the PolyData. low : float or -np.inf Lower threshold. Default is -np.inf. upp : float or np.inf Upper threshold. Default is np.inf. Returns ------- surf_selected : vtkPolyData or BSPolyData PolyData after thresholding. See Also -------- :func:`drop_points` :func:`select_cells` :func:`mask_cells` """ return _surface_selection(surf, array_name, low=low, upp=upp, use_cell=True, keep=False) def select_points(surf, array_name, low=-np.inf, upp=np.inf): """Select surface points whose values fall within the threshold. Cells corresponding to these points are also kept. Parameters ---------- surf : vtkPolyData or BSPolyData Input surface. array_name : str or 1D ndarray Array used to perform selection. If str, it must be an array in the PointData attributes of the PolyData. low : float or -np.inf Lower threshold. Default is -np.inf. upp : float or np.inf Upper threshold. Default is np.inf. Returns ------- surf_selected : vtkPolyData or BSPolyData PolyData after selection. See Also -------- :func:`select_cells` :func:`drop_points` :func:`mask_points` """ return _surface_selection(surf, array_name, low=low, upp=upp, keep=True) def select_cells(surf, array_name, low=-np.inf, upp=np.inf): """Select surface cells whose values fall within the threshold. Points corresponding to these cells are also kept. Parameters ---------- surf : vtkPolyData or BSPolyData Input surface. array_name : str or 1D ndarray Array used to perform selection. If str, it must be an array in the CellData attributes of the PolyData. low : float or -np.inf Lower threshold. Default is -np.inf. upp : float or np.inf Upper threshold. Default is np.inf. Returns ------- surf_selected : vtkPolyData or BSPolyData PolyData after selection. See Also -------- :func:`select_points` :func:`drop_cells` :func:`mask_cells` """ return _surface_selection(surf, array_name, low=low, upp=upp, use_cell=True, keep=True) def mask_points(surf, mask): """Mask surface points. Cells corresponding to these points are also kept. Parameters ---------- surf : vtkPolyData or BSPolyData Input surface. mask : 1D ndarray Binary boolean array. Zero elements are discarded. Returns ------- surf_masked : vtkPolyData or BSPolyData PolyData after masking. See Also -------- :func:`mask_cells` :func:`drop_points` :func:`select_points` """ return _surface_mask(surf, mask) def mask_cells(surf, mask): """Mask surface cells. Points corresponding to these cells are also kept. Parameters ---------- surf : vtkPolyData or BSPolyData Input surface. mask : 1D ndarray Binary boolean array. Zero elements are discarded. Returns ------- surf_masked : vtkPolyData or BSPolyData PolyData after masking. See Also -------- :func:`mask_points` :func:`drop_cells` :func:`select_cells` """ return _surface_mask(surf, mask, use_cell=True) def combine_surfaces(*surfs): """ Combine surfaces. Parameters ---------- surfs : sequence of vtkPolyData and/or BSPolyData Input surfaces. Returns ------- res : BSPolyData Combination of input surfaces. See Also -------- :func:`split_surface` """ alg = vtkAppendPolyData() for s in surfs: alg = connect(s, alg, add_conn=True) return get_output(alg) @wrap_input(0) def split_surface(surf, labeling=None): """ Split surface according to the labeling. Parameters ---------- surf : vtkPolyData or BSPolyData Input surface. labeling : str, 1D ndarray or None, optional Array used to perform the splitting. If str, it must be an array in the PointData attributes of `surf`. If None, split surface in its connected components. Default is None. Returns ------- res : dict[int, BSPolyData] Dictionary of sub-surfaces for each label. See Also -------- :func:`combine_surfaces` :func:`mask_points` """ if labeling is None: labeling = get_connected_components(surf) elif isinstance(labeling, str): labeling = surf.get_array(labeling, at='p') ulab = np.unique(labeling) return {l: mask_points(surf, labeling == l) for l in ulab}
[ 37811, 198, 26416, 5499, 319, 4417, 48754, 13, 198, 37811, 198, 198, 2, 6434, 25, 440, 723, 312, 3932, 21070, 320, 1279, 280, 10751, 13, 11722, 21070, 320, 31, 23209, 70, 359, 13, 6888, 29, 198, 2, 13789, 25, 347, 10305, 513, 13444,...
2.478482
4,136
import psycopg2 import networkx import logging import math from datetime import datetime, timezone def log_info(msg): """ Print info log message. :params msg: message text. """ logging.info(' ' + msg) def log_debug(msg): """ Print debug log message. :params msg: message text. """ logging.debug(msg) def add_record(graph, record): """ Add one record to a graph. :params graph: networkx graph. :params record: record for an edge. :return: graph, as modified in place. """ graph.add_edge(record.sip, record.dip, attr_dict={'sport': record.sport, 'dport': record.dport, 'stime_epoch_secs': record.stime_epoch_secs, 'etime_epoch_secs': record.etime_epoch_secs}) return graph def start_end_epoch(graph): """ Start and end epoch of graph. :return: (start epoch, end epoch). """ start = 0 end = 0 for e in graph.edges_iter(): for _, p in graph[e[0]][e[1]].items(): end = max(end, p['etime_epoch_secs']) if start == 0: start = p['stime_epoch_secs'] else: start = min(start, p['stime_epoch_secs']) return (start, end) def epoch_utc(s): """ Convert epoch seconds to utc DateTime object. :params s: epoch seconds. :return: corresponding DateTime object. """ return datetime.fromtimestamp(s, timezone.utc) class _Frame_Iter: """ Iterator over frames in the protocol graph database. """ _db = None # ProtocolGraph _iter_start = 0 # start epoch for iterating _iter_end = -1 # end epoch of time for frames _iter_frame_secs = 0 # frame length in seconds for iterating over frames _iter_index = 0 # index of the iterator _iter_finished = False # indicates whether iterator is finished def __init__(self, db, name, seconds, start, minutes): """ Create iterator with start time over given frame length; :param db: ProtocolGraph database. :param name: name of the frame :param seconds: seconds for the frame; :param start: start epoch of iterator; start of dataset if < 0. :param minutes: minutes for the frame; whole dataset length if minutes and seconds are 0. :return: iterator. """ self._db = db frame = self._db.frame(name) if not frame: self._iter_finished = True else: self._iter_finished = False (_, start_epoch, end_epoch, sink_port) = frame self._iter_end = end_epoch if start >= 0: self._iter_start = start else: self._iter_start = start_epoch if minutes == 0 and seconds == 0: self._iter_frame_secs = math.ceil( self._iter_end - self._iter_start) # print('iter_frame_secs: {}'.format(self._iter_frame_secs)) else: self._iter_frame_secs = minutes * 60 + seconds class ProtocolGraph: """ Protocol graph obtained from a database with edges. Typical usage: db = ProtocolGraph(flow_connection) g = db.fetch_all() or for g in db.iter(sim_name, frame_secs) process g """ _database = None # connection to a database def __init__(self, flow_connection): """ Initialize with connection. :param flow_connection: FlowConnection. """ self._database = flow_connection self._database.open() def __del__(self): """ Close database if appropriate. """ if self._database: self._database.close() def fetch_all(self): """ Fetch the whole protocol graph. :return: networkx.MultiDiGraph. """ with self._database: g = networkx.MultiDiGraph() with self._database.cursor() as cur: cur.execute("select * from edges;") for rec in cur: add_record(g, rec) return g def fetch_frame(self, start, minutes=0, seconds=0): """ Fetch graph from one frame; include streams that start in the frame. :param start: epoch start time. :param minutes: minutes for the frame. :param seconds: seconds for the frame. :return: graph. """ total_secs = minutes * 60 + seconds end = start + total_secs with self._database: g = networkx.MultiDiGraph() with self._database.cursor() as cur: cur.execute('select * from edges where \ (%s<=stime_epoch_secs and stime_epoch_secs<%s);', (start, end)) for rec in cur: add_record(g, rec) return g def iter(self, name, seconds=0, start=-1, minutes=0): """ Create iterator with start time over given frame length; :param name: name of the frame :param seconds: seconds for the frame; :param start: start epoch of iterator; start of dataset if < 0. :param minutes: minutes for the frame; whole dataset length if minutes and seconds are 0. :return: iterator. """ return _Frame_Iter(self, name, seconds=seconds, start=start, minutes=minutes)
[ 11748, 17331, 22163, 70, 17, 198, 11748, 3127, 87, 198, 11748, 18931, 198, 11748, 10688, 198, 6738, 4818, 8079, 1330, 4818, 8079, 11, 640, 11340, 628, 198, 4299, 2604, 62, 10951, 7, 19662, 2599, 198, 220, 220, 220, 37227, 198, 220, 22...
2.226607
2,458
#!/usr/bin/env python3 import sys sys.path.append(r'/home/felix/git/gym-jsbsim-eee/') #TODO: Is this a good idea? Dunno! It works! import gym import numpy as np import math import random import markov_pilot.environment.properties as prp from abc import ABC, abstractmethod from markov_pilot.environment.properties import BoundedProperty from typing import Tuple, List class VarySetpointsWrapper(gym.Wrapper): """ A wrapper to vary the setpoints at the beginning of each episode This can be used during training to have bigger variance in the training data """ class SetpointVariator(ABC): """ A helper that can vary a setpoint between two extreme values following a specific pattern """ @abstractmethod def vary(self): ''' outputs the setpoint for the next step or None if there is nothing to do''' ... @abstractmethod def start_variation(self): ''' starts the setpoint variation for the first time in the upcoming interval :return: the first setpoint to be passed to the env''' ... def __init__(self, env, setpoint_property: BoundedProperty, setpoint_range: Tuple[float, float], interval_length: Tuple[float, float] = (5., 120.), ramp_time:Tuple[float, float] = (0,0), sine_frequ: Tuple[float, float] = (0,0), initial_conditions: List[Tuple] = []): """ :param setpoint_property: The property which describes the setpoint. :param setpoint_range: the range the setpoint may be chosen from (min, max) :param interval_length: the time in seconds for the interval till the next change :param ramp_time: the time, a ramp may last from current setpoint to target setpoint; (0, 0) disables ramps :param sine_frequ: the frequqcy range from which sine modulation may be chosen; (0,0) disables sine modulation :param initial_conditions: TODO: specify the initial conditions that may be varied and their ranges. """ self.env = env self.setpoint_property = setpoint_property self.setpoint_range = setpoint_range self.interval_length = interval_length self.ramp_time = ramp_time self.sine_frequ = sine_frequ self.initial_conditions = initial_conditions #don't restore the VarySetpoints wrapper automatically # #append the restore data # self.env_init_dicts.append({ # 'setpoint_property': setpoint_property, # 'setpoint_range': setpoint_range, # 'interval_length': interval_length, # 'ramp_time': ramp_time, # 'sine_frequ': sine_frequ, # 'initial_conditions': initial_conditions, # }) # self.env_classes.append(self.__class__.__name__) step_variator = self.StepVariator(setpoint_range) ramp_variator = self.RampVariator(setpoint_range, ramp_time, self.dt) sine_variator = self.SineVariator(setpoint_range, sine_frequ, self.dt) self.enabled_variators = [step_variator] if ramp_time != (0, 0): self.enabled_variators.append(ramp_variator) if sine_frequ != (0, 0): self.enabled_variators.append(sine_variator) self.envs_to_vary = [self.env] def inject_other_env(self, env): '''if the setpoint changes shall affect more than one environment synchronously; e. g. for benchmarking''' self.envs_to_vary.append(env)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 11748, 25064, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 198, 17597, 13, 6978, 13, 33295, 7, 81, 26488, 11195, 14, 69, 417, 844, 14, 18300, 14, 1360, 76, 12, ...
2.467406
1,442