content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
#!/usr/bin/env python # -*- python -*- #BEGIN_LEGAL # #Copyright (c) 2019 Intel Corporation # # 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. # #END_LEGAL from __future__ import print_function import re import genutil import codegen
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 21015, 532, 9, 12, 198, 2, 33, 43312, 62, 2538, 38, 1847, 198, 2, 198, 2, 15269, 357, 66, 8, 13130, 8180, 10501, 198, 2, 198, 2, 220, 49962, 739, 262, 24843, 137...
3.366516
221
import pytest from tenable_io.api.target_groups import TargetListEditRequest from tenable_io.api.models import TargetGroup, TargetGroupList
[ 11748, 12972, 9288, 198, 198, 6738, 3478, 540, 62, 952, 13, 15042, 13, 16793, 62, 24432, 1330, 12744, 8053, 18378, 18453, 198, 6738, 3478, 540, 62, 952, 13, 15042, 13, 27530, 1330, 12744, 13247, 11, 12744, 13247, 8053, 628, 628, 628 ]
3.560976
41
""" Module containing all the spectrogram classes """ # 0.2.0 import torch import torch.nn as nn from torch.nn.functional import conv1d, conv2d, fold import numpy as np from time import time from nnAudio.librosa_functions import * from nnAudio.utils import * sz_float = 4 # size of a float epsilon = 10e-8 # fudge factor for normalization ### --------------------------- Spectrogram Classes ---------------------------### # The section below is for developing purpose # Please don't use the following classes #
[ 37811, 198, 26796, 7268, 477, 262, 5444, 39529, 6097, 198, 37811, 198, 198, 2, 657, 13, 17, 13, 15, 198, 198, 11748, 28034, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 6738, 28034, 13, 20471, 13, 45124, 1330, 3063, 16, 67, 11, ...
3.389937
159
import argparse import logging import os import numpy as np import pandas as pd import pytorch_lightning as pl import torch from pytorch_lightning import loggers as pl_loggers from torch.utils.data import DataLoader, Dataset from dataset import KoBARTSummaryDataset from transformers import BartForConditionalGeneration, PreTrainedTokenizerFast from transformers.optimization import AdamW, get_cosine_schedule_with_warmup from kobart import get_pytorch_kobart_model, get_kobart_tokenizer parser = argparse.ArgumentParser(description='KoBART translation') parser.add_argument('--checkpoint_path', type=str, help='checkpoint path') logger = logging.getLogger() logger.setLevel(logging.INFO) def train_dataloader(self): train = DataLoader(self.train, batch_size=self.batch_size, num_workers=self.num_workers, shuffle=True) return train def val_dataloader(self): val = DataLoader(self.test, batch_size=self.batch_size, num_workers=self.num_workers, shuffle=False) return val def test_dataloader(self): test = DataLoader(self.test, batch_size=self.batch_size, num_workers=self.num_workers, shuffle=False) return test class Base(pl.LightningModule): class KoBARTConditionalGeneration(Base): if __name__ == '__main__': parser = Base.add_model_specific_args(parser) parser = ArgsBase.add_model_specific_args(parser) parser = KobartSummaryModule.add_model_specific_args(parser) parser = pl.Trainer.add_argparse_args(parser) args = parser.parse_args() logging.info(args) model = KoBARTConditionalGeneration(args) dm = KobartSummaryModule(args.train_file, args.test_file, None, max_len=args.max_len, batch_size=args.batch_size, num_workers=args.num_workers) checkpoint_callback = pl.callbacks.ModelCheckpoint(monitor='val_loss', dirpath=args.default_root_dir, filename='model_chp/{epoch:02d}-{val_loss:.3f}', verbose=True, save_last=True, mode='min', save_top_k=-1, prefix='kobart_translation') tb_logger = pl_loggers.TensorBoardLogger(os.path.join(args.default_root_dir, 'tb_logs')) lr_logger = pl.callbacks.LearningRateMonitor() trainer = pl.Trainer.from_argparse_args(args, logger=tb_logger, callbacks=[checkpoint_callback, lr_logger]) trainer.fit(model, dm)
[ 11748, 1822, 29572, 198, 11748, 18931, 198, 11748, 28686, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 12972, 13165, 354, 62, 2971, 768, 355, 458, 198, 11748, 28034, 198, 6738, 12972, 13165, 354, ...
1.92254
1,575
"""Sensor for Shelly.""" from __future__ import annotations from datetime import timedelta import logging from typing import Final, cast import aioshelly from homeassistant.components import sensor from homeassistant.components.sensor import SensorEntity from homeassistant.config_entries import ConfigEntry from homeassistant.const import ( CONCENTRATION_PARTS_PER_MILLION, DEGREE, ELECTRIC_CURRENT_AMPERE, ELECTRIC_POTENTIAL_VOLT, ENERGY_KILO_WATT_HOUR, LIGHT_LUX, PERCENTAGE, POWER_WATT, SIGNAL_STRENGTH_DECIBELS_MILLIWATT, ) from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.typing import StateType from homeassistant.util import dt from . import ShellyDeviceWrapper from .const import LAST_RESET_NEVER, LAST_RESET_UPTIME, SHAIR_MAX_WORK_HOURS from .entity import ( BlockAttributeDescription, RestAttributeDescription, ShellyBlockAttributeEntity, ShellyRestAttributeEntity, ShellySleepingBlockAttributeEntity, async_setup_entry_attribute_entities, async_setup_entry_rest, ) from .utils import get_device_uptime, temperature_unit _LOGGER: Final = logging.getLogger(__name__) SENSORS: Final = { ("device", "battery"): BlockAttributeDescription( name="Battery", unit=PERCENTAGE, device_class=sensor.DEVICE_CLASS_BATTERY, state_class=sensor.STATE_CLASS_MEASUREMENT, removal_condition=lambda settings, _: settings.get("external_power") == 1, ), ("device", "deviceTemp"): BlockAttributeDescription( name="Device Temperature", unit=temperature_unit, value=lambda value: round(value, 1), device_class=sensor.DEVICE_CLASS_TEMPERATURE, state_class=sensor.STATE_CLASS_MEASUREMENT, default_enabled=False, ), ("emeter", "current"): BlockAttributeDescription( name="Current", unit=ELECTRIC_CURRENT_AMPERE, value=lambda value: value, device_class=sensor.DEVICE_CLASS_CURRENT, state_class=sensor.STATE_CLASS_MEASUREMENT, ), ("light", "power"): BlockAttributeDescription( name="Power", unit=POWER_WATT, value=lambda value: round(value, 1), device_class=sensor.DEVICE_CLASS_POWER, state_class=sensor.STATE_CLASS_MEASUREMENT, default_enabled=False, ), ("device", "power"): BlockAttributeDescription( name="Power", unit=POWER_WATT, value=lambda value: round(value, 1), device_class=sensor.DEVICE_CLASS_POWER, state_class=sensor.STATE_CLASS_MEASUREMENT, ), ("emeter", "power"): BlockAttributeDescription( name="Power", unit=POWER_WATT, value=lambda value: round(value, 1), device_class=sensor.DEVICE_CLASS_POWER, state_class=sensor.STATE_CLASS_MEASUREMENT, ), ("emeter", "voltage"): BlockAttributeDescription( name="Voltage", unit=ELECTRIC_POTENTIAL_VOLT, value=lambda value: round(value, 1), device_class=sensor.DEVICE_CLASS_VOLTAGE, state_class=sensor.STATE_CLASS_MEASUREMENT, ), ("emeter", "powerFactor"): BlockAttributeDescription( name="Power Factor", unit=PERCENTAGE, value=lambda value: round(value * 100, 1), device_class=sensor.DEVICE_CLASS_POWER_FACTOR, state_class=sensor.STATE_CLASS_MEASUREMENT, ), ("relay", "power"): BlockAttributeDescription( name="Power", unit=POWER_WATT, value=lambda value: round(value, 1), device_class=sensor.DEVICE_CLASS_POWER, state_class=sensor.STATE_CLASS_MEASUREMENT, ), ("roller", "rollerPower"): BlockAttributeDescription( name="Power", unit=POWER_WATT, value=lambda value: round(value, 1), device_class=sensor.DEVICE_CLASS_POWER, state_class=sensor.STATE_CLASS_MEASUREMENT, ), ("device", "energy"): BlockAttributeDescription( name="Energy", unit=ENERGY_KILO_WATT_HOUR, value=lambda value: round(value / 60 / 1000, 2), device_class=sensor.DEVICE_CLASS_ENERGY, state_class=sensor.STATE_CLASS_MEASUREMENT, last_reset=LAST_RESET_UPTIME, ), ("emeter", "energy"): BlockAttributeDescription( name="Energy", unit=ENERGY_KILO_WATT_HOUR, value=lambda value: round(value / 1000, 2), device_class=sensor.DEVICE_CLASS_ENERGY, state_class=sensor.STATE_CLASS_MEASUREMENT, last_reset=LAST_RESET_NEVER, ), ("emeter", "energyReturned"): BlockAttributeDescription( name="Energy Returned", unit=ENERGY_KILO_WATT_HOUR, value=lambda value: round(value / 1000, 2), device_class=sensor.DEVICE_CLASS_ENERGY, state_class=sensor.STATE_CLASS_MEASUREMENT, last_reset=LAST_RESET_NEVER, ), ("light", "energy"): BlockAttributeDescription( name="Energy", unit=ENERGY_KILO_WATT_HOUR, value=lambda value: round(value / 60 / 1000, 2), device_class=sensor.DEVICE_CLASS_ENERGY, state_class=sensor.STATE_CLASS_MEASUREMENT, default_enabled=False, last_reset=LAST_RESET_UPTIME, ), ("relay", "energy"): BlockAttributeDescription( name="Energy", unit=ENERGY_KILO_WATT_HOUR, value=lambda value: round(value / 60 / 1000, 2), device_class=sensor.DEVICE_CLASS_ENERGY, state_class=sensor.STATE_CLASS_MEASUREMENT, last_reset=LAST_RESET_UPTIME, ), ("roller", "rollerEnergy"): BlockAttributeDescription( name="Energy", unit=ENERGY_KILO_WATT_HOUR, value=lambda value: round(value / 60 / 1000, 2), device_class=sensor.DEVICE_CLASS_ENERGY, state_class=sensor.STATE_CLASS_MEASUREMENT, last_reset=LAST_RESET_UPTIME, ), ("sensor", "concentration"): BlockAttributeDescription( name="Gas Concentration", unit=CONCENTRATION_PARTS_PER_MILLION, icon="mdi:gauge", state_class=sensor.STATE_CLASS_MEASUREMENT, ), ("sensor", "extTemp"): BlockAttributeDescription( name="Temperature", unit=temperature_unit, value=lambda value: round(value, 1), device_class=sensor.DEVICE_CLASS_TEMPERATURE, state_class=sensor.STATE_CLASS_MEASUREMENT, available=lambda block: cast(bool, block.extTemp != 999), ), ("sensor", "humidity"): BlockAttributeDescription( name="Humidity", unit=PERCENTAGE, value=lambda value: round(value, 1), device_class=sensor.DEVICE_CLASS_HUMIDITY, state_class=sensor.STATE_CLASS_MEASUREMENT, available=lambda block: cast(bool, block.extTemp != 999), ), ("sensor", "luminosity"): BlockAttributeDescription( name="Luminosity", unit=LIGHT_LUX, device_class=sensor.DEVICE_CLASS_ILLUMINANCE, state_class=sensor.STATE_CLASS_MEASUREMENT, ), ("sensor", "tilt"): BlockAttributeDescription( name="Tilt", unit=DEGREE, icon="mdi:angle-acute", state_class=sensor.STATE_CLASS_MEASUREMENT, ), ("relay", "totalWorkTime"): BlockAttributeDescription( name="Lamp Life", unit=PERCENTAGE, icon="mdi:progress-wrench", value=lambda value: round(100 - (value / 3600 / SHAIR_MAX_WORK_HOURS), 1), extra_state_attributes=lambda block: { "Operational hours": round(block.totalWorkTime / 3600, 1) }, ), ("adc", "adc"): BlockAttributeDescription( name="ADC", unit=ELECTRIC_POTENTIAL_VOLT, value=lambda value: round(value, 1), device_class=sensor.DEVICE_CLASS_VOLTAGE, state_class=sensor.STATE_CLASS_MEASUREMENT, ), ("sensor", "sensorOp"): BlockAttributeDescription( name="Operation", icon="mdi:cog-transfer", value=lambda value: value, extra_state_attributes=lambda block: {"self_test": block.selfTest}, ), } REST_SENSORS: Final = { "rssi": RestAttributeDescription( name="RSSI", unit=SIGNAL_STRENGTH_DECIBELS_MILLIWATT, value=lambda status, _: status["wifi_sta"]["rssi"], device_class=sensor.DEVICE_CLASS_SIGNAL_STRENGTH, state_class=sensor.STATE_CLASS_MEASUREMENT, default_enabled=False, ), "uptime": RestAttributeDescription( name="Uptime", value=get_device_uptime, device_class=sensor.DEVICE_CLASS_TIMESTAMP, default_enabled=False, ), }
[ 37811, 47864, 329, 1375, 12810, 526, 15931, 198, 6738, 11593, 37443, 834, 1330, 37647, 198, 198, 6738, 4818, 8079, 1330, 28805, 12514, 198, 11748, 18931, 198, 6738, 19720, 1330, 8125, 11, 3350, 198, 198, 11748, 257, 4267, 12758, 88, 198, ...
2.289987
3,745
""" Web settings to override for testing. """ import os from biothings.web.settings.default import QUERY_KWARGS # ***************************************************************************** # Elasticsearch Variables # ***************************************************************************** ES_INDEX = 'bts_test' ES_DOC_TYPE = 'gene' ES_SCROLL_SIZE = 60 # ***************************************************************************** # User Input Control # ***************************************************************************** # use a smaller size for testing QUERY_KWARGS['GET']['facet_size']['default'] = 3 QUERY_KWARGS['GET']['facet_size']['max'] = 5 QUERY_KWARGS['POST']['q']['jsoninput'] = True # ***************************************************************************** # Elasticsearch Query Builder # ***************************************************************************** ALLOW_RANDOM_QUERY = True ALLOW_NESTED_AGGS = True USERQUERY_DIR = os.path.join(os.path.dirname(__file__), 'userquery') # ***************************************************************************** # Endpoints Specifics # ***************************************************************************** STATUS_CHECK = { 'id': '1017', 'index': 'bts_test', 'doc_type': '_all' }
[ 37811, 198, 220, 220, 220, 5313, 6460, 284, 20957, 329, 4856, 13, 198, 37811, 198, 11748, 28686, 198, 198, 6738, 3182, 849, 654, 13, 12384, 13, 33692, 13, 12286, 1330, 19604, 19664, 62, 42, 16279, 14313, 198, 198, 2, 41906, 17174, 455...
4.091195
318
""" Custom management command to rebuild thumbnail images - May be required after importing a new dataset, for example """ import os import logging from PIL import UnidentifiedImageError from django.core.management.base import BaseCommand from django.conf import settings from django.db.utils import OperationalError, ProgrammingError from company.models import Company from part.models import Part logger = logging.getLogger("inventree-thumbnails")
[ 37811, 198, 15022, 4542, 3141, 284, 17884, 40901, 4263, 198, 198, 12, 1737, 307, 2672, 706, 33332, 257, 649, 27039, 11, 329, 1672, 198, 37811, 198, 198, 11748, 28686, 198, 11748, 18931, 198, 198, 6738, 350, 4146, 1330, 791, 19107, 5159,...
4.089286
112
import discord from discord.ext import commands import urllib.parse from .constants import themes, controls, languages, fonts, escales import os from pathlib import Path from typing import Any # from pyppeteer import launch from io import * import requests def hex_to_rgb(hex: str) -> tuple: """ Args: hex (str): """ return tuple(int(hex.lstrip("#")[i : i + 2], 16) for i in (0, 2, 4)) _carbon_url = "https://carbonnowsh.herokuapp.com/"
[ 11748, 36446, 198, 6738, 36446, 13, 2302, 1330, 9729, 198, 11748, 2956, 297, 571, 13, 29572, 198, 6738, 764, 9979, 1187, 1330, 13460, 11, 6973, 11, 8950, 11, 26806, 11, 3671, 2040, 198, 11748, 28686, 198, 6738, 3108, 8019, 1330, 10644, ...
2.788235
170
# shows artist info for a URN or URL import spotipy_twisted import sys import pprint if len(sys.argv) > 1: urn = sys.argv[1] else: urn = 'spotify:artist:3jOstUTkEu2JkjvRdBA5Gu' sp = spotipy_twisted.Spotify() artist = sp.artist(urn) pprint.pprint(artist)
[ 2, 2523, 6802, 7508, 329, 257, 37902, 45, 393, 10289, 198, 198, 11748, 4136, 541, 88, 62, 4246, 6347, 198, 11748, 25064, 198, 11748, 279, 4798, 198, 198, 361, 18896, 7, 17597, 13, 853, 85, 8, 1875, 352, 25, 198, 220, 220, 220, 220...
2.188525
122
import busio import digitalio import board import adafruit_mcp3xxx.mcp3002 as MCP from adafruit_mcp3xxx.analog_in import AnalogIn # create the spi bus spi = busio.SPI(clock=board.SCK, MISO=board.MISO, MOSI=board.MOSI) # create the cs (chip select) cs = digitalio.DigitalInOut(board.D5) # create the mcp object mcp = MCP.MCP3002(spi, cs) # create an analog input channel on pin 0 chan = AnalogIn(mcp, MCP.P0) print("Raw ADC Value: ", chan.value) print("ADC Voltage: " + str(chan.voltage) + "V")
[ 11748, 1323, 952, 198, 11748, 4875, 952, 198, 11748, 3096, 198, 11748, 512, 1878, 4872, 62, 76, 13155, 18, 31811, 13, 76, 13155, 6200, 17, 355, 337, 8697, 198, 6738, 512, 1878, 4872, 62, 76, 13155, 18, 31811, 13, 272, 11794, 62, 259...
2.495
200
from glue.core.data_factories.helpers import has_extension from glue.config import data_factory __all__ = ['tabular_data']
[ 6738, 22749, 13, 7295, 13, 7890, 62, 22584, 1749, 13, 16794, 364, 1330, 468, 62, 2302, 3004, 198, 6738, 22749, 13, 11250, 1330, 1366, 62, 69, 9548, 628, 198, 834, 439, 834, 796, 37250, 8658, 934, 62, 7890, 20520, 628 ]
3.15
40
from django.shortcuts import render from django.http import Http404 from django.views.generic.edit import UpdateView from django.views.generic import ListView, View from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.utils.decorators import method_decorator import logging from ..models.projects import Project from ..models.authors import Author from ..forms import AuthorForm from .permission_helpers import PermissionOnObjectViewMixin # logger for this file logger = logging.getLogger(__name__)
[ 6738, 42625, 14208, 13, 19509, 23779, 1330, 8543, 198, 6738, 42625, 14208, 13, 4023, 1330, 367, 29281, 26429, 198, 198, 6738, 42625, 14208, 13, 33571, 13, 41357, 13, 19312, 1330, 10133, 7680, 198, 6738, 42625, 14208, 13, 33571, 13, 41357,...
3.578616
159
# External deps import os, sys, json from pathlib import Path from typing import Dict, List # Internal deps os.chdir(sys.path[0]) sys.path.append("..") import df_common as dfc import analyses_common as ac # Generated files directory GEN_FILE_DIR = str(Path(__file__).resolve().parent.parent) + os.sep + "generated_files" # TODO: ugly parent.parent pathing if os.path.exists(GEN_FILE_DIR): sys.path.append(GEN_FILE_DIR) if os.path.exists(os.path.join(GEN_FILE_DIR, "sloc_cnt.py")): from sloc_cnt import DRIVER_NAME_TO_SLOC else: print("Error: no SLOC file! Run \'df_analyze.py\' with \'--linux-src-dir\'") sys.exit(1) if __name__ == "__main__": json_files = ac.argparse_and_get_files("Graph SLOC/SoC data") soc_sloc_by_arch: Dict[str, List[int]] = {} print("Gathering SLOC average by arch...") from graph_dd_sloc_by_arch import get_sloc_avg_and_list_by_arch cmp_by_arch = ac.build_dict_two_lvl_cnt(json_files, dfc.JSON_ARC, dfc.JSON_CMP_STR) avg_sloc_by_arch, sloc_list_by_arch = get_sloc_avg_and_list_by_arch(cmp_by_arch, verbose = False) # Collection print("Iterating DTBs/SoCs...") for dtb_json in json_files: with open(dtb_json) as json_file: data = json.load(json_file) soc_sloc = 0 arch = data[dfc.JSON_ARC] cmp_strs = data[dfc.JSON_CMP_STR] # Total SLOC for this SoC for cmp_str in cmp_strs: driver_sloc = dfc.cmp_str_to_sloc(cmp_str) if not driver_sloc: # Closed-source driver driver_sloc = avg_sloc_by_arch[arch] soc_sloc += driver_sloc #print("{}: {}".format(cmp_str, driver_sloc)) if arch not in soc_sloc_by_arch: soc_sloc_by_arch[arch] = [] else: soc_sloc_by_arch[arch].append(soc_sloc) print("{} ({}): {}".format(dtb_json.split(os.sep)[-1], arch, soc_sloc)) # Final stats ac.print_mean_median_std_dev_for_dict_of_lists(soc_sloc_by_arch, "\nSloc Per Soc, format: [arch : (mean, median, std_dev)]\n")
[ 2, 34579, 390, 862, 198, 11748, 28686, 11, 25064, 11, 33918, 198, 6738, 3108, 8019, 1330, 10644, 198, 6738, 19720, 1330, 360, 713, 11, 7343, 198, 198, 2, 18628, 390, 862, 198, 418, 13, 354, 15908, 7, 17597, 13, 6978, 58, 15, 12962, ...
2.134912
971
import math import pytorch_lightning as pl
[ 11748, 10688, 198, 11748, 12972, 13165, 354, 62, 2971, 768, 355, 458, 198 ]
3.307692
13
# -*- coding: utf-8 -*- # # Copyright (C) 2020 Chris Caron <lead2gold@gmail.com> # All rights reserved. # # This code is licensed under the MIT License. # # 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. import os import re import six import yaml import time from .. import plugins from ..AppriseAsset import AppriseAsset from ..URLBase import URLBase from ..common import ConfigFormat from ..common import CONFIG_FORMATS from ..common import ContentIncludeMode from ..utils import GET_SCHEMA_RE from ..utils import parse_list from ..utils import parse_bool from ..utils import parse_urls from . import SCHEMA_MAP # Test whether token is valid or not VALID_TOKEN = re.compile( r'(?P<token>[a-z0-9][a-z0-9_]+)', re.I) def __getitem__(self, index): """ Returns the indexed server entry associated with the loaded notification servers """ if not isinstance(self._cached_servers, list): # Generate ourselves a list of content we can pull from self.servers() return self._cached_servers[index] def __iter__(self): """ Returns an iterator to our server list """ if not isinstance(self._cached_servers, list): # Generate ourselves a list of content we can pull from self.servers() return iter(self._cached_servers) def __len__(self): """ Returns the total number of servers loaded """ if not isinstance(self._cached_servers, list): # Generate ourselves a list of content we can pull from self.servers() return len(self._cached_servers) def __bool__(self): """ Allows the Apprise object to be wrapped in an Python 3.x based 'if statement'. True is returned if our content was downloaded correctly. """ if not isinstance(self._cached_servers, list): # Generate ourselves a list of content we can pull from self.servers() return True if self._cached_servers else False def __nonzero__(self): """ Allows the Apprise object to be wrapped in an Python 2.x based 'if statement'. True is returned if our content was downloaded correctly. """ if not isinstance(self._cached_servers, list): # Generate ourselves a list of content we can pull from self.servers() return True if self._cached_servers else False
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 2, 15069, 357, 34, 8, 12131, 5180, 1879, 261, 1279, 28230, 17, 24267, 31, 14816, 13, 785, 29, 198, 2, 1439, 2489, 10395, 13, 198, 2, 198, 2, 770, 2438, 318...
2.883278
1,208
import sys import subprocess from subprocess import Popen, PIPE AV_LOG_QUIET = "quiet" AV_LOG_PANIC = "panic" AV_LOG_FATAL = "fatal" AV_LOG_ERROR = "error" AV_LOG_WARNING = "warning" AV_LOG_INFO = "info" AV_LOG_VERBOSE = "verbose" AV_LOG_DEBUG = "debug" ffmpeg_loglevel = AV_LOG_ERROR IS_WIN32 = 'win32' in str(sys.platform).lower() SUBPROCESS_ARGS = {} if IS_WIN32: startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags = subprocess.CREATE_NEW_CONSOLE | subprocess.STARTF_USESHOWWINDOW startupinfo.wShowWindow = subprocess.SW_HIDE SUBPROCESS_ARGS['startupinfo'] = startupinfo
[ 11748, 25064, 198, 11748, 850, 14681, 198, 6738, 850, 14681, 1330, 8099, 268, 11, 350, 4061, 36, 198, 198, 10116, 62, 25294, 62, 43702, 2767, 220, 220, 796, 366, 39624, 1, 198, 10116, 62, 25294, 62, 47, 1565, 2149, 220, 220, 796, 36...
2.361538
260
from setuptools import setup setup( name="nmn-iwp", version="0.1", keywords="", packages=["vr", "vr.models"] )
[ 6738, 900, 37623, 10141, 1330, 9058, 198, 198, 40406, 7, 198, 220, 220, 220, 1438, 2625, 77, 10295, 12, 14246, 79, 1600, 198, 220, 220, 220, 2196, 2625, 15, 13, 16, 1600, 198, 220, 220, 220, 26286, 2625, 1600, 198, 220, 220, 220, ...
2.285714
56
""" Represent a triangulated surface using a 3D boolean grid""" import logging import numpy as np from rpl.tools.ray_tracing.bsp_tree_poly import BSP_Element from rpl.tools.geometry import geom_utils import data_io def make_grid(veh_surfs, settings): """ Make coordinates of voxelated grid based on overall list of vehicle surfaces """ ## Find overall bounding box x_min, x_max = 1e30, -1e30 y_min, y_max = 1e30, -1e30 z_min, z_max = 1e30, -1e30 for key, veh_surf in veh_surfs.items(): x_min, x_max = min(x_min, np.min(veh_surf["x"])), max(x_max, np.max(veh_surf["x"])) y_min, y_max = min(y_min, np.min(veh_surf["y"])), max(y_max, np.max(veh_surf["y"])) z_min, z_max = min(z_min, np.min(veh_surf["z"])), max(z_max, np.max(veh_surf["z"])) x_min, x_max = x_min - settings["voxel_size"], x_max + settings["voxel_size"] y_min, y_max = y_min - settings["voxel_size"], y_max + settings["voxel_size"] z_min, z_max = z_min - settings["voxel_size"], z_max + settings["voxel_size"] ########################################### # Create the uniformly spaced grid points x_grid = np.arange(x_min, x_max + settings["voxel_size"], settings["voxel_size"]) y_grid = np.arange(y_min, y_max + settings["voxel_size"], settings["voxel_size"]) z_grid = np.arange(z_min, z_max + settings["voxel_size"], settings["voxel_size"]) return x_grid, y_grid, z_grid def convert_geom(veh_surf, tr_mat): """ Rotate nodes using provided transformation matrix; convert xyz node dict to nodes array """ veh_surf["nodes"] = np.vstack((veh_surf["x"], veh_surf["y"], veh_surf["z"])).T veh_surf['nodes'] = np.dot(veh_surf['nodes'], tr_mat[:3, :3]) veh_surf["x"] = veh_surf['nodes'][:, 0] veh_surf["y"] = veh_surf['nodes'][:, 1] veh_surf["z"] = veh_surf['nodes'][:, 2] return veh_surf def find_occupied_voxels(surf, surf_mask, voxel_data): """ Voxels with any triangle from ``surf`` are considered occupied and or'ed with ``group_mask``. If the supplied ``occupied_voxels`` is None a voxel array is created and returned. """ nodes = surf["nodes"] tris = surf["tris"] x_pts, y_pts, z_pts = [voxel_data[k] for k in ("x_grid", "y_grid", "z_grid")] vox_size = voxel_data["vox_size"] ## Find the local extents of this part min_x, max_x = np.min(surf["x"]) - vox_size, np.max(surf["x"]) + vox_size min_y, max_y = np.min(surf["y"]) - vox_size, np.max(surf["y"]) + vox_size min_z, max_z = np.min(surf["z"]) - vox_size, np.max(surf["z"]) + vox_size b_tree = BSP_Grid(nodes, tris) # Create BSP tree elements- we're not using a tree, but we are using some of the functions b_x_root = BSP_Element(b_tree.tris, b_tree) size_i, size_j, size_k = len(x_pts), len(y_pts), len(z_pts) ## Create the occupied voxels if none were supplied if voxel_data["value"] is None: voxel_data["value"] = np.zeros((size_i - 1, size_j - 1, size_k - 1), dtype=np.uint32) occupied_voxels = voxel_data["value"] ## The [1:] is because to make n voxels in a given direction we need n-1 splits for i, x_pos in enumerate(x_pts[1:]): if x_pos < min_x: continue if x_pos > max_x: break b_above_x, b_below_x = b_x_root.split_at(0, x_pos) b_y_root = b_below_x for j, y_pos in enumerate(y_pts[1:]): if b_y_root is None: break if y_pos < min_y: continue if y_pos > max_y: break b_above_y, b_below_y = b_y_root.split_at(1, y_pos) b_z_root = b_below_y for k, z_pos in enumerate(z_pts[1:]): if b_z_root is None: break if z_pos < min_z: continue if z_pos > max_z: break b_above_z, b_below_z = b_z_root.split_at(2, z_pos) if not (b_below_z and (len(b_below_z.tris) == 0)): ## There is at least part of triangle here so mark as occupied occupied_voxels[i, j, k] |= surf_mask b_z_root = b_above_z b_y_root = b_above_y b_x_root = b_above_x return voxel_data ############# # Main code def main(vehicle_comp_coords, tr_mat, voxel_masks, settings): """ Perform voxelization for all vehicle geometries in a list of parts. Combine on a uniform grid. """ for key, veh_surf in vehicle_comp_coords.items(): # Convert coordinates and find overall best bounding box veh_surf = convert_geom(veh_surf, tr_mat) x_grid, y_grid, z_grid = make_grid(vehicle_comp_coords, settings) voxel_data = {"x_grid": x_grid, "y_grid": y_grid, "z_grid": z_grid, "vox_size": settings["voxel_size"], "csys_trans": tr_mat, "value": None} for key, veh_surf in vehicle_comp_coords.items(): # Build up the voxel_data logging.debug("Sampling component: {}".format(key)) ## Default mask is 1 for anything not in an identified set surf_mask = 1 for mask, geo_set in voxel_masks.items(): if veh_surf['part_class'] in geo_set: surf_mask |= mask voxel_data = find_occupied_voxels(veh_surf, surf_mask, voxel_data) return voxel_data if __name__ == "__main__": from rpl.tools.api import test_bench_api as tb_api SETTINGS = tb_api.load_settings("settings.js") DOORS = {'Hatch_Assembly_Rear_Ramp', 'Hatch_Assembly_Personnel_Door'} HATCHES = {'Hatch_Assembly_Driver_Commander', 'Hatch_Assembly_Cargo'} HULLS = {"Hull_Assembly_Parametric", 'Hull_Assembly_Example_With_Connector'} MANIKINS = {"Manikin"} # Special labels applied to specific types of voxels VOXEL_LABELS = {2: HULLS, 4: DOORS, 8: HATCHES, 16: MANIKINS} vehicle_surfs = tb_api.load_geometry(tb_api.get_all_geom_set() - MANIKINS, single_file=False) # Modify node coords so object aligns with cartesian axes of occ voxel grid, +z=up # Vector to rotate around is cross product of current z axis and sfc normal veh_up = np.array([0., 1., 0.]) rot_around = np.cross(veh_up, np.array([0, 0, 1])) rot_ang = -np.arccos(veh_up[2]) tr_mat = geom_utils.rotation_about_vector(rot_around, rot_ang) # voxel_data = main(vehicle_surfs, tr_mat, VOXEL_LABELS, SETTINGS) vox_veh_folder = r"voxelated_models/vehicles/{}/{}".format(SETTINGS["run_id"], SETTINGS["voxel_size"]) vox_veh_file = "voxels_{}_vox{}_hacked".format(SETTINGS["run_id"], SETTINGS["voxel_size"]) try: voxel_data = data_io.load_array(vox_veh_folder, vox_veh_file, True) except: voxel_data = main(vehicle_surfs, tr_mat, VOXEL_LABELS, SETTINGS) from mayavi import mlab xo, yo, zo = np.where(voxel_data["value"] == 1) plot_vehicle = mlab.points3d(voxel_data["x_grid"][xo], voxel_data["y_grid"][yo], voxel_data["z_grid"][zo], color=(0.9, 0.9, 0.9), scale_mode="none", scale_factor=voxel_data["vox_size"], mode='cube', opacity=1) xo, yo, zo = np.where(voxel_data["value"] & 2) plot_vehicle = mlab.points3d(voxel_data["x_grid"][xo], voxel_data["y_grid"][yo], voxel_data["z_grid"][zo], color=(1, 1, 1), scale_mode="none", scale_factor=voxel_data["vox_size"], mode='cube', opacity=0.05) xo, yo, zo = np.where(voxel_data["value"] & 4) plot_vehicle = mlab.points3d(voxel_data["x_grid"][xo], voxel_data["y_grid"][yo], voxel_data["z_grid"][zo], color=(1.0, 0.5, 0.5), scale_mode="none", scale_factor=voxel_data["vox_size"], mode='cube', opacity=1) xo, yo, zo = np.where(voxel_data["value"] & 8) plot_vehicle = mlab.points3d(voxel_data["x_grid"][xo], voxel_data["y_grid"][yo], voxel_data["z_grid"][zo], color=(0.6, 0.6, 1.0), scale_mode="none", scale_factor=voxel_data["vox_size"], mode='cube', opacity=1) # No manikins included, no need to plot them # xo, yo, zo = np.where(voxel_data["value"] & 16) # plot_vehicle = mlab.points3d(voxel_data["x_grid"][xo], # voxel_data["y_grid"][yo], # voxel_data["z_grid"][zo], # color=(0.5, 1.0, 0.8), # scale_mode="none", scale_factor=voxel_data["vox_size"], # mode='cube', opacity=1.0) mlab.show() # Save the voxelated model of the vehicle (sans door and other excluded parts) data_io.save_multi_array(vox_veh_folder, vox_veh_file, voxel_data)
[ 37811, 10858, 257, 1333, 648, 4817, 4417, 1262, 257, 513, 35, 25131, 10706, 37811, 201, 198, 11748, 18931, 201, 198, 11748, 299, 32152, 355, 45941, 201, 198, 201, 198, 6738, 374, 489, 13, 31391, 13, 2433, 62, 2213, 4092, 13, 24145, 62...
1.857749
5,188
''' >List of functions 1. encrypt(user_input,passphrase) - Encrypt the given string with the given passphrase. Returns cipher text and locked pad. 2. decrypt(cipher_text,locked_pad,passphrase) - Decrypt the cipher text encrypted with SBET. It requires cipher text, locked pad, and passphrase. ''' # CODE ======================================================================== import zlib import random from hashlib import sha1 from silver_bullet.TRNG import trlist from silver_bullet.contain_value import contain ascii_value=256
[ 7061, 6, 198, 29, 8053, 286, 5499, 198, 197, 16, 13, 34117, 7, 7220, 62, 15414, 11, 6603, 34675, 8, 197, 12, 197, 27195, 6012, 262, 1813, 4731, 351, 262, 1813, 1208, 34675, 13, 16409, 38012, 2420, 290, 8970, 14841, 13, 198, 197, 1...
3.69863
146
# -*- coding: utf-8 -*- """ pyfire.errors ~~~~~~~~~~~~~~~~~~~~~~ Holds the global used base errors :copyright: 2011 by the pyfire Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ import xml.etree.ElementTree as ET
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 220, 220, 220, 12972, 6495, 13, 48277, 198, 220, 220, 220, 220, 27156, 8728, 4907, 628, 220, 220, 220, 9340, 82, 262, 3298, 973, 2779, 8563, 628, 220, 220,...
2.854167
96
import random
[ 11748, 4738, 628, 628, 197, 197, 220, 628, 628, 628 ]
2.6
10
from dataclasses import dataclass import math import chess import chess.engine from model import EngineMove, NextMovePair from chess import Color, Board from chess.pgn import GameNode from chess.engine import SimpleEngine, Score nps = [] def win_chances(score: Score) -> float: """ winning chances from -1 to 1 https://graphsketch.com/?eqn1_color=1&eqn1_eqn=100+*+%282+%2F+%281+%2B+exp%28-0.004+*+x%29%29+-+1%29&eqn2_color=2&eqn2_eqn=&eqn3_color=3&eqn3_eqn=&eqn4_color=4&eqn4_eqn=&eqn5_color=5&eqn5_eqn=&eqn6_color=6&eqn6_eqn=&x_min=-1000&x_max=1000&y_min=-100&y_max=100&x_tick=100&y_tick=10&x_label_freq=2&y_label_freq=2&do_grid=0&do_grid=1&bold_labeled_lines=0&bold_labeled_lines=1&line_width=4&image_w=850&image_h=525 """ mate = score.mate() if mate is not None: return 1 if mate > 0 else -1 cp = score.score() return 2 / (1 + math.exp(-0.004 * cp)) - 1 if cp is not None else 0 CORRESP_TIME = 999999
[ 6738, 4818, 330, 28958, 1330, 4818, 330, 31172, 198, 11748, 10688, 198, 11748, 19780, 198, 11748, 19780, 13, 18392, 198, 6738, 2746, 1330, 7117, 21774, 11, 7406, 21774, 47, 958, 198, 6738, 19780, 1330, 5315, 11, 5926, 198, 6738, 19780, ...
2.202797
429
import time, morning from datetime import datetime
[ 11748, 640, 11, 3329, 201, 198, 6738, 4818, 8079, 1330, 4818, 8079, 201 ]
4
13
from unittest import TestCase from mock import patch, Mock from samcli.commands.local.start_lambda.cli import do_cli as start_lambda_cli from samcli.commands.local.cli_common.user_exceptions import UserException from samcli.commands.validate.lib.exceptions import InvalidSamDocumentException from samcli.commands.local.lib.exceptions import OverridesNotWellDefinedError
[ 6738, 555, 715, 395, 1330, 6208, 20448, 198, 6738, 15290, 1330, 8529, 11, 44123, 198, 198, 6738, 6072, 44506, 13, 9503, 1746, 13, 12001, 13, 9688, 62, 50033, 13, 44506, 1330, 466, 62, 44506, 355, 923, 62, 50033, 62, 44506, 198, 6738, ...
3.542857
105
from django.test import TestCase import pandas as pd from .getters import Getter from .converter import Converter from strategies.models import Company from strategies.models import IndicatorType
[ 6738, 42625, 14208, 13, 9288, 1330, 6208, 20448, 198, 198, 11748, 19798, 292, 355, 279, 67, 198, 198, 6738, 764, 1136, 1010, 1330, 3497, 353, 198, 6738, 764, 1102, 332, 353, 1330, 35602, 353, 198, 198, 6738, 10064, 13, 27530, 1330, 58...
3.846154
52
""" Copyright (c) 2020 Intel Corporation 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 json import logging import subprocess import tempfile from ote import MMDETECTION_TOOLS from .base import BaseTrainer from ..registry import TRAINERS
[ 37811, 198, 15069, 357, 66, 8, 12131, 8180, 10501, 628, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 198, 921, 743, 7...
3.967914
187
import sys import json import subprocess import re import statistics # Main service body if __name__ == "__main__": complexity = get_complexity() duplicate_const_strings = get_duplicate_const_strings() files = set() files.update(complexity.keys()) files.update(duplicate_const_strings.keys()) result = [] for f in files: result.append({ 'filename': f, 'cyclomaticComplexity': complexity[f] if f in complexity else 0, 'duplicateConstStrings': duplicate_const_strings[f] if f in duplicate_const_strings else 0 }) print(json.dumps(result))
[ 11748, 25064, 198, 11748, 33918, 198, 11748, 850, 14681, 198, 11748, 302, 198, 11748, 7869, 198, 198, 2, 8774, 2139, 1767, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 220, 220, 628, 220, 220, 220, 13357, 796, 651, 62...
2.627615
239
""" Testing if parso finds syntax errors and indentation errors. """ import sys import warnings import pytest import parso from parso._compatibility import is_pypy from .failing_examples import FAILING_EXAMPLES, indent, build_nested if is_pypy: # The errors in PyPy might be different. Just skip the module for now. pytestmark = pytest.mark.skip() def test_non_async_in_async(): """ This example doesn't work with FAILING_EXAMPLES, because the line numbers are not always the same / incorrect in Python 3.8. """ if sys.version_info[:2] < (3, 5): pytest.skip() # Raises multiple errors in previous versions. code = 'async def foo():\n def nofoo():[x async for x in []]' wanted, line_nr = _get_actual_exception(code) errors = _get_error_list(code) if errors: error, = errors actual = error.message assert actual in wanted if sys.version_info[:2] < (3, 8): assert line_nr == error.start_pos[0] else: assert line_nr == 0 # For whatever reason this is zero in Python 3.8+ def _get_actual_exception(code): with warnings.catch_warnings(): # We don't care about warnings where locals/globals misbehave here. # It's as simple as either an error or not. warnings.filterwarnings('ignore', category=SyntaxWarning) try: compile(code, '<unknown>', 'exec') except (SyntaxError, IndentationError) as e: wanted = e.__class__.__name__ + ': ' + e.msg line_nr = e.lineno except ValueError as e: # The ValueError comes from byte literals in Python 2 like '\x' # that are oddly enough not SyntaxErrors. wanted = 'SyntaxError: (value error) ' + str(e) line_nr = None else: assert False, "The piece of code should raise an exception." # SyntaxError # Python 2.6 has a bit different error messages here, so skip it. if sys.version_info[:2] == (2, 6) and wanted == 'SyntaxError: unexpected EOF while parsing': wanted = 'SyntaxError: invalid syntax' if wanted == 'SyntaxError: non-keyword arg after keyword arg': # The python 3.5+ way, a bit nicer. wanted = 'SyntaxError: positional argument follows keyword argument' elif wanted == 'SyntaxError: assignment to keyword': return [wanted, "SyntaxError: can't assign to keyword", 'SyntaxError: cannot assign to __debug__'], line_nr elif wanted == 'SyntaxError: assignment to None': # Python 2.6 does has a slightly different error. wanted = 'SyntaxError: cannot assign to None' elif wanted == 'SyntaxError: can not assign to __debug__': # Python 2.6 does has a slightly different error. wanted = 'SyntaxError: cannot assign to __debug__' elif wanted == 'SyntaxError: can use starred expression only as assignment target': # Python 3.4/3.4 have a bit of a different warning than 3.5/3.6 in # certain places. But in others this error makes sense. return [wanted, "SyntaxError: can't use starred expression here"], line_nr elif wanted == 'SyntaxError: f-string: unterminated string': wanted = 'SyntaxError: EOL while scanning string literal' elif wanted == 'SyntaxError: f-string expression part cannot include a backslash': return [ wanted, "SyntaxError: EOL while scanning string literal", "SyntaxError: unexpected character after line continuation character", ], line_nr elif wanted == "SyntaxError: f-string: expecting '}'": wanted = 'SyntaxError: EOL while scanning string literal' elif wanted == 'SyntaxError: f-string: empty expression not allowed': wanted = 'SyntaxError: invalid syntax' elif wanted == "SyntaxError: f-string expression part cannot include '#'": wanted = 'SyntaxError: invalid syntax' elif wanted == "SyntaxError: f-string: single '}' is not allowed": wanted = 'SyntaxError: invalid syntax' return [wanted], line_nr def test_default_except_error_postition(): # For this error the position seemed to be one line off, but that doesn't # really matter. code = 'try: pass\nexcept: pass\nexcept X: pass' wanted, line_nr = _get_actual_exception(code) error, = _get_error_list(code) assert error.message in wanted assert line_nr != error.start_pos[0] # I think this is the better position. assert error.start_pos[0] == 2 def test_statically_nested_blocks(): assert get_error(19) is None assert get_error(19, add_func=True) is None assert get_error(20) assert get_error(20, add_func=True) def test_future_import_first(): i1 = 'from __future__ import division' i2 = 'from __future__ import absolute_import' assert not is_issue(i1) assert not is_issue(i1 + ';' + i2) assert not is_issue(i1 + '\n' + i2) assert not is_issue('"";' + i1) assert not is_issue('"";' + i1) assert not is_issue('""\n' + i1) assert not is_issue('""\n%s\n%s', i1, i2) assert not is_issue('""\n%s;%s', i1, i2) assert not is_issue('"";%s;%s ', i1, i2) assert not is_issue('"";%s\n%s ', i1, i2) assert is_issue('1;' + i1) assert is_issue('1\n' + i1) assert is_issue('"";1\n' + i1) assert is_issue('""\n%s\nfrom x import a\n%s', i1, i2) assert is_issue('%s\n""\n%s', i1, i2) def test_named_argument_issues(works_not_in_py): message = works_not_in_py.get_error_message('def foo(*, **dict): pass') message = works_not_in_py.get_error_message('def foo(*): pass') if works_not_in_py.version.startswith('2'): assert message == 'SyntaxError: invalid syntax' else: assert message == 'SyntaxError: named arguments must follow bare *' works_not_in_py.assert_no_error_in_passing('def foo(*, name): pass') works_not_in_py.assert_no_error_in_passing('def foo(bar, *, name=1): pass') works_not_in_py.assert_no_error_in_passing('def foo(bar, *, name=1, **dct): pass') def test_escape_decode_literals(each_version): """ We are using internal functions to assure that unicode/bytes escaping is without syntax errors. Here we make a bit of quality assurance that this works through versions, because the internal function might change over time. """ error, = _get_error_list(r'u"\x"', version=each_version) assert error.message in get_msgs(r'\xXX') error, = _get_error_list(r'u"\u"', version=each_version) assert error.message in get_msgs(r'\uXXXX') error, = _get_error_list(r'u"\U"', version=each_version) assert error.message in get_msgs(r'\UXXXXXXXX') error, = _get_error_list(r'u"\N{}"', version=each_version) assert error.message == get_msg(r'malformed \N character escape', to=2) error, = _get_error_list(r'u"\N{foo}"', version=each_version) assert error.message == get_msg(r'unknown Unicode character name', to=6) # Finally bytes. error, = _get_error_list(r'b"\x"', version=each_version) wanted = r'SyntaxError: (value error) invalid \x escape' if sys.version_info >= (3, 0): # The positioning information is only available in Python 3. wanted += ' at position 0' assert error.message == wanted def test_too_many_levels_of_indentation(): assert not _get_error_list(build_nested('pass', 99)) assert _get_error_list(build_nested('pass', 100)) base = 'def x():\n if x:\n' assert not _get_error_list(build_nested('pass', 49, base=base)) assert _get_error_list(build_nested('pass', 50, base=base))
[ 37811, 198, 44154, 611, 1582, 568, 7228, 15582, 8563, 290, 33793, 341, 8563, 13, 198, 37811, 198, 11748, 25064, 198, 11748, 14601, 198, 198, 11748, 12972, 9288, 198, 198, 11748, 1582, 568, 198, 6738, 1582, 568, 13557, 5589, 25901, 1330, ...
2.583474
2,953
# -*- coding: utf-8 -*- from __future__ import unicode_literals from shogitk.shogi import Coords, Move, BLACK, WHITE, DROP, PROMOTE RANKNUM = { 'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9 }
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 6738, 427, 519, 270, 74, 13, 1477, 44381, 1330, 1766, 3669, 11, 10028, 11, 31963, 11, 44925, 11, ...
1.653409
176
import click from . import utils if __name__ == '__main__': main()
[ 11748, 3904, 198, 6738, 764, 1330, 3384, 4487, 628, 628, 628, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 1388, 3419, 198 ]
2.655172
29
import getpass from plumbum import local from plumbum.machines.paramiko_machine import ParamikoMachine from plumbum.path.utils import copy def get_local_machine(): return local def with_machine_rule(cls): old_init = cls.__init__ cls.__init__ = new_init old_apply = cls.apply cls.apply = new_apply return cls
[ 11748, 651, 6603, 198, 6738, 458, 2178, 388, 1330, 1957, 198, 6738, 458, 2178, 388, 13, 76, 620, 1127, 13, 17143, 12125, 62, 30243, 1330, 25139, 12125, 37573, 198, 6738, 458, 2178, 388, 13, 6978, 13, 26791, 1330, 4866, 628, 198, 198, ...
2.558824
136
salario = float(input('digite o seu salario: ')) aumento = (salario + (salario * 15)/100 if salario <= 1250 else salario + (salario * 10)/100) print(aumento)
[ 21680, 4982, 796, 12178, 7, 15414, 10786, 12894, 578, 267, 384, 84, 3664, 4982, 25, 705, 4008, 198, 64, 1713, 78, 796, 357, 21680, 4982, 1343, 357, 21680, 4982, 1635, 1315, 20679, 3064, 611, 3664, 4982, 19841, 1105, 1120, 2073, 3664, ...
2.706897
58
#!/usr/bin/env python import os import os.path import airflow import airflow.plugins_manager from airflow import configuration from flask import Flask from unittest import TestCase, main from airflow_code_editor.commons import PLUGIN_NAME from airflow_code_editor.tree import ( get_tree, ) assert airflow.plugins_manager app = Flask(__name__) if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 11748, 28686, 198, 11748, 28686, 13, 6978, 198, 11748, 45771, 198, 11748, 45771, 13, 37390, 62, 37153, 198, 6738, 45771, 1330, 8398, 198, 6738, 42903, 1330, 46947, 198, 6738, 555, 7...
3.231405
121
from quart import Quart, jsonify, request from quart_jwt_extended import ( JWTManager, jwt_required, create_access_token, jwt_refresh_token_required, create_refresh_token, get_jwt_identity, fresh_jwt_required, ) app = Quart(__name__) app.config["JWT_SECRET_KEY"] = "super-secret" # Change this! jwt = JWTManager(app) # Standard login endpoint. Will return a fresh access token and # a refresh token # Refresh token endpoint. This will generate a new access token from # the refresh token, but will mark that access token as non-fresh, # as we do not actually verify a password in this endpoint. # Fresh login endpoint. This is designed to be used if we need to # make a fresh token for a user (by verifying they have the # correct username and password). Unlike the standard login endpoint, # this will only return a new access token, so that we don't keep # generating new refresh tokens, which entirely defeats their point. # Any valid JWT can access this endpoint # Only fresh JWTs can access this endpoint if __name__ == "__main__": app.run()
[ 6738, 28176, 1330, 48748, 11, 33918, 1958, 11, 2581, 198, 6738, 28176, 62, 73, 46569, 62, 2302, 1631, 1330, 357, 198, 220, 220, 220, 449, 39386, 13511, 11, 198, 220, 220, 220, 474, 46569, 62, 35827, 11, 198, 220, 220, 220, 2251, 62,...
3.355828
326
from datetime import datetime from typing import Any, Dict, Union __all__ = 'AnyDict' AnyDict = Dict[str, Any] # pragma: no mutate datetime_or_str = Union[datetime, str] # pragma: no mutate
[ 6738, 4818, 8079, 1330, 4818, 8079, 198, 6738, 19720, 1330, 4377, 11, 360, 713, 11, 4479, 198, 198, 834, 439, 834, 796, 705, 7149, 35, 713, 6, 198, 198, 7149, 35, 713, 796, 360, 713, 58, 2536, 11, 4377, 60, 220, 1303, 23864, 2611,...
2.671233
73
import os os.environ['KERAS_BACKEND'] = 'theano' os.environ['THEANO_FLAGS'] = 'floatX=float32,device=cpu' import cloudpickle as pickle import pipeline_invoke import pandas as pd import numpy as np import keras from keras.layers import Input, Dense from keras.models import Model from keras.models import save_model, load_model from sklearn.preprocessing import StandardScaler, MinMaxScaler, Normalizer if __name__ == '__main__': df = pd.read_csv("../input/training/training.csv") df["People per Television"] = pd.to_numeric(df["People per Television"],errors='coerce') df = df.dropna() x = df["People per Television"].values.reshape(-1,1).astype(np.float64) y = df["People per Physician"].values.reshape(-1,1).astype(np.float64) # min-max -1,1 sc = MinMaxScaler(feature_range=(-1,1)) x_ = sc.fit_transform(x) y_ = sc.fit_transform(y) inputs = Input(shape=(1,)) preds = Dense(1,activation='linear')(inputs) model = Model(inputs=inputs,outputs=preds) sgd = keras.optimizers.SGD() model.compile(optimizer=sgd ,loss='mse') model.fit(x_,y_, batch_size=1, verbose=1, epochs=10, shuffle=False) save_model(model, 'state/keras_theano_linear_model_state.h5') # model_pkl_path = 'model.pkl' # with open(model_pkl_path, 'wb') as fh: # pickle.dump(pipeline_invoke, fh)
[ 11748, 28686, 198, 418, 13, 268, 2268, 17816, 42839, 1921, 62, 31098, 10619, 20520, 796, 705, 1169, 5733, 6, 198, 418, 13, 268, 2268, 17816, 10970, 1565, 46, 62, 38948, 50, 20520, 796, 705, 22468, 55, 28, 22468, 2624, 11, 25202, 28, ...
2.46337
546
from unittest import TestCase from unittest.mock import Mock, patch import sys sys.modules['smbus'] = Mock() # Mock the hardware layer to avoid errors. from ledshimdemo.canvas import Canvas from ledshimdemo.effects.cheerlights import CheerLightsEffect
[ 6738, 555, 715, 395, 1330, 6208, 20448, 198, 6738, 555, 715, 395, 13, 76, 735, 1330, 44123, 11, 8529, 198, 11748, 25064, 198, 198, 17597, 13, 18170, 17816, 82, 2022, 385, 20520, 796, 44123, 3419, 220, 1303, 44123, 262, 6890, 7679, 284...
3.240506
79
from colicoords.synthetic_data import add_readout_noise, draw_poisson from colicoords import load import numpy as np import mahotas as mh from tqdm import tqdm import os import tifffile def gen_im(data_dir): """Generate microscopy images from a list of cell objects by placing them randomly oriented in the image.""" cell_list = load(os.path.join(data_dir, 'cell_obj', 'cells_final_selected.hdf5')) out_dict = generate_images(cell_list, 1000, 10, 3, (512, 512)) if not os.path.exists(os.path.join(data_dir, 'images')): os.mkdir(os.path.join(data_dir, 'images')) np.save(os.path.join(data_dir, 'images', 'binary.npy'), out_dict['binary']) np.save(os.path.join(data_dir, 'images', 'brightfield.npy'), out_dict['brightfield']) np.save(os.path.join(data_dir, 'images', 'foci_inner.npy'), out_dict['foci_inner']) np.save(os.path.join(data_dir, 'images', 'foci_outer.npy'), out_dict['foci_outer']) np.save(os.path.join(data_dir, 'images', 'storm_inner.npy'), out_dict['storm_inner']) np.save(os.path.join(data_dir, 'images', 'storm_outer.npy'), out_dict['storm_outer']) tifffile.imsave(os.path.join(data_dir, 'images', 'binary.tif'), out_dict['binary']) tifffile.imsave(os.path.join(data_dir, 'images', 'brightfield.tif'), out_dict['brightfield']) tifffile.imsave(os.path.join(data_dir, 'images', 'foci_inner.tif'), out_dict['foci_inner']) tifffile.imsave(os.path.join(data_dir, 'images', 'foci_outer.tif'), out_dict['foci_outer']) np.savetxt(os.path.join(data_dir, 'images', 'storm_inner.txt'), out_dict['storm_inner']) np.savetxt(os.path.join(data_dir, 'images', 'storm_outer.txt'), out_dict['storm_inner']) def noise_bf(data_dir): """add poissonian and readout noise to brightfield images""" noise = 20 img_stack = np.load(os.path.join(data_dir, 'images', 'brightfield.npy')) for photons in [10000, 1000, 500]: ratio = 1.0453 # ratio between 'background' (no cells) and cell wall img = (photons*(ratio-1))*img_stack + photons img = draw_poisson(img) img = add_readout_noise(img, noise) tifffile.imsave(os.path.join(data_dir, 'images', 'bf_noise_{}_photons.tif'.format(photons)), img) np.save(os.path.join(data_dir, 'images', 'bf_noise_{}_photons.npy'.format(photons)), img) if __name__ == '__main__': np.random.seed(42) data_dir = r'.' if not os.path.exists(os.path.join(data_dir, 'images')): os.mkdir(os.path.join(data_dir, 'images')) gen_im(data_dir) noise_bf(data_dir)
[ 6738, 951, 3713, 3669, 13, 1837, 429, 6587, 62, 7890, 1330, 751, 62, 961, 448, 62, 3919, 786, 11, 3197, 62, 7501, 30927, 198, 6738, 951, 3713, 3669, 1330, 3440, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 42768, 313, 292, 355, 2...
2.385768
1,068
word = input("Enter a word: ") if word == "a": print("one; any") elif word == "apple": print("familiar, round fleshy fruit") elif word == "rhinoceros": print("large thick-skinned animal with one or two horns on its nose") else: print("That word must not exist. This dictionary is very comprehensive.")
[ 4775, 796, 5128, 7203, 17469, 257, 1573, 25, 366, 8, 198, 198, 361, 1573, 6624, 366, 64, 1298, 198, 220, 220, 220, 3601, 7203, 505, 26, 597, 4943, 198, 417, 361, 1573, 6624, 366, 18040, 1298, 198, 220, 220, 220, 3601, 7203, 69, 19...
3.097087
103
cnt = int(input()) num = list(map(int, input())) sum = 0 for i in range(len(num)): sum = sum + num[i] print(sum)
[ 66, 429, 796, 493, 7, 15414, 28955, 198, 22510, 796, 1351, 7, 8899, 7, 600, 11, 5128, 3419, 4008, 198, 16345, 796, 657, 198, 1640, 1312, 287, 2837, 7, 11925, 7, 22510, 8, 2599, 198, 220, 220, 220, 2160, 796, 2160, 1343, 997, 58, ...
2.27451
51
from distutils.core import setup setup( name = 'kube_navi', packages = ['kube_navi'], # this must be the same as the name above version = '0.1', description = 'Kubernetes resource discovery toolkit', author = 'Srini Seetharaman', author_email = 'srini.seetharaman@gmail.com', url = 'https://github.com/sdnhub/kube-navi', # use the URL to the github repo download_url = 'https://github.com/sdnhub/kube-navi/archive/0.1.tar.gz', # I'll explain this in a second keywords = ['testing', 'logging', 'example'], # arbitrary keywords classifiers = [], )
[ 6738, 1233, 26791, 13, 7295, 1330, 9058, 198, 40406, 7, 198, 220, 1438, 796, 705, 74, 3266, 62, 77, 15820, 3256, 198, 220, 10392, 796, 37250, 74, 3266, 62, 77, 15820, 6, 4357, 1303, 428, 1276, 307, 262, 976, 355, 262, 1438, 2029, ...
2.887755
196
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use 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 ast from typing import Text, Optional, Union, List from ai_flow.rest_endpoint.protobuf.metric_service_pb2 import MetricMetaResponse, ListMetricMetaResponse, \ MetricSummaryResponse, ListMetricSummaryResponse from ai_flow.rest_endpoint.service import int64Value, stringValue from ai_flow.common.properties import Properties from ai_flow.meta.metric_meta import MetricMeta, MetricType, MetricSummary from ai_flow.rest_endpoint.protobuf.message_pb2 import MetricMetaProto, MetricSummaryProto, MetricTypeProto, ReturnCode, \ SUCCESS, RESOURCE_DOES_NOT_EXIST from ai_flow.store.db.db_model import SqlMetricMeta, SqlMetricSummary from ai_flow.store.db.db_model import MongoMetricSummary, MongoMetricMeta
[ 2, 198, 2, 49962, 284, 262, 24843, 10442, 5693, 357, 1921, 37, 8, 739, 530, 198, 2, 393, 517, 18920, 5964, 11704, 13, 220, 4091, 262, 28536, 2393, 198, 2, 9387, 351, 428, 670, 329, 3224, 1321, 198, 2, 5115, 6634, 9238, 13, 220, ...
3.488479
434
# -*- coding: UTF-8 -*- from PySide2.QtWidgets import QWidget, QPushButton, QVBoxLayout from PySide2.QtCore import Signal from moduels.component.NormalValue import from moduels.component.SponsorDialog import SponsorDialog import os, webbrowser def initElement(self): self. = QPushButton(self.tr('')) self.ffmpegMannualNoteButton = QPushButton(self.tr(' FFmpeg ')) self.openVideoHelpButtone = QPushButton(self.tr('')) self.openGiteePage = QPushButton(self.tr(f' v{.} Gitee ')) self.openGithubPage = QPushButton(self.tr(f' v{.} Github ')) self.linkToDiscussPage = QPushButton(self.tr(' QQ ')) self.tipButton = QPushButton(self.tr('')) self.masterLayout = QVBoxLayout() def initSlots(self): self..clicked.connect(self.openHelpDocument) self.ffmpegMannualNoteButton.clicked.connect(lambda: webbrowser.open(self.tr(r'https://hacpai.com/article/1595480295489'))) self.openVideoHelpButtone.clicked.connect(lambda: webbrowser.open(self.tr(r'https://www.bilibili.com/video/BV12A411p73r/'))) self.openGiteePage.clicked.connect(lambda: webbrowser.open(self.tr(r'https://gitee.com/haujet/CapsWriter/releases'))) self.openGithubPage.clicked.connect(lambda: webbrowser.open(self.tr(r'https://github.com/HaujetZhao/CapsWriter/releases'))) self.linkToDiscussPage.clicked.connect(lambda: webbrowser.open( self.tr(r'https://qm.qq.com/cgi-bin/qm/qr?k=DgiFh5cclAElnELH4mOxqWUBxReyEVpm&jump_from=webapi'))) self.tipButton.clicked.connect(lambda: SponsorDialog(self)) def initLayout(self): self.setLayout(self.masterLayout) # self.masterLayout.addWidget(self.) # self.masterLayout.addWidget(self.ffmpegMannualNoteButton) self.masterLayout.addWidget(self.openVideoHelpButtone) self.masterLayout.addWidget(self.openGiteePage) self.masterLayout.addWidget(self.openGithubPage) self.masterLayout.addWidget(self.linkToDiscussPage) self.masterLayout.addWidget(self.tipButton) def initValue(self): self..setMaximumHeight(100) self.ffmpegMannualNoteButton.setMaximumHeight(100) self.openVideoHelpButtone.setMaximumHeight(100) self.openGiteePage.setMaximumHeight(100) self.openGithubPage.setMaximumHeight(100) self.linkToDiscussPage.setMaximumHeight(100) self.tipButton.setMaximumHeight(100) def openHelpDocument(self): try: if . == 'Darwin': import shlex os.system("open " + shlex.quote(self.tr("./misc/Docs/README_zh.html"))) elif . == 'Windows': os.startfile(os.path.realpath(self.tr('./misc/Docs/README_zh.html'))) except: print('')
[ 2, 532, 9, 12, 19617, 25, 41002, 12, 23, 532, 9, 12, 198, 198, 6738, 9485, 24819, 17, 13, 48, 83, 54, 312, 11407, 1330, 1195, 38300, 11, 1195, 49222, 21864, 11, 1195, 53, 14253, 32517, 198, 6738, 9485, 24819, 17, 13, 48, 83, 140...
2.291941
1,216
from typing import Callable, Optional, Type, cast from fastapi import APIRouter, HTTPException, Request, status from app.models import users from app.common.user import ErrorCode, run_handler from app.users.user import ( CreateUserProtocol, InvalidPasswordException, UserAlreadyExists, ValidatePasswordProtocol, ) def get_register_router( create_user: CreateUserProtocol, user_model: Type[users.BaseUser], user_create_model: Type[users.BaseUserCreate], after_register: Optional[Callable[[users.UD, Request], None]] = None, validate_password: Optional[ValidatePasswordProtocol] = None, ) -> APIRouter: """Generate a router with the register route.""" router = APIRouter() return router
[ 6738, 19720, 1330, 4889, 540, 11, 32233, 11, 5994, 11, 3350, 198, 198, 6738, 3049, 15042, 1330, 3486, 4663, 39605, 11, 14626, 16922, 11, 19390, 11, 3722, 198, 198, 6738, 598, 13, 27530, 1330, 2985, 198, 6738, 598, 13, 11321, 13, 7220,...
3.153846
234
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import cv2 import numpy as np def flow_to_img(flow, normalize=True): """Convert flow to viewable image, using color hue to encode flow vector orientation, and color saturation to encode vector length. This is similar to the OpenCV tutorial on dense optical flow, except that they map vector length to the value plane of the HSV color model, instead of the saturation plane, as we do here. Args: flow: optical flow normalize: Normalize flow to 0..255 Returns: img: viewable representation of the dense optical flow in RGB format Ref: https://github.com/philferriere/tfoptflow/blob/33e8a701e34c8ce061f17297d40619afbd459ade/tfoptflow/optflow.py """ hsv = np.zeros((flow.shape[0], flow.shape[1], 3), dtype=np.uint8) flow_magnitude, flow_angle = cv2.cartToPolar(flow[..., 0].astype(np.float32), flow[..., 1].astype(np.float32)) # A couple times, we've gotten NaNs out of the above... nans = np.isnan(flow_magnitude) if np.any(nans): nans = np.where(nans) flow_magnitude[nans] = 0. # Normalize hsv[..., 0] = flow_angle * 180 / np.pi / 2 if normalize is True: hsv[..., 1] = cv2.normalize(flow_magnitude, None, 0, 255, cv2.NORM_MINMAX) else: hsv[..., 1] = flow_magnitude hsv[..., 2] = 255 img = cv2.cvtColor(hsv, cv2.COLOR_HSV2RGB) return img
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 269, 85, 17, 198, 11748, 299, 32152, 355, 45941, 198, 198, 4299, 5202, 62, 1462, 62, 9600, 7, 11125, 11, ...
2.407095
592
import argparse from PIL import Image, ImageStat import math parser = argparse.ArgumentParser() parser.add_argument('fname') parser.add_argument('pref', default="", nargs="?") args = parser.parse_args() im = Image.open(args.fname) RGB = im.convert('RGB') imWidth, imHeight = im.size ratg = 1.2 ratgb = 1.66 ming = 10 ratr = 2 speed = 8 leafcount = 0 total = 0 for i in range(0, int(imWidth/speed)): for j in range(0, int(imHeight/speed)): R,G,B = RGB.getpixel((i*speed,j*speed)) if R*ratg < G and B*ratgb < G and B*ratr < R: leafcount = leafcount + 1 total = total+1 print("LAI="+str(float(leafcount)/total))
[ 11748, 1822, 29572, 198, 6738, 350, 4146, 1330, 7412, 11, 7412, 17126, 198, 11748, 10688, 198, 198, 48610, 796, 1822, 29572, 13, 28100, 1713, 46677, 3419, 198, 48610, 13, 2860, 62, 49140, 10786, 69, 3672, 11537, 198, 48610, 13, 2860, 62...
2.486056
251
#!/usr/bin/env python """cluster storage stats for python""" # import pyhesity wrapper module from pyhesity import * from datetime import datetime import codecs # command line arguments import argparse parser = argparse.ArgumentParser() parser.add_argument('-v', '--vip', type=str, default='helios.cohesity.com') # cluster to connect to parser.add_argument('-u', '--username', type=str, required=True) # username parser.add_argument('-d', '--domain', type=str, default='local') # (optional) domain - defaults to local parser.add_argument('-pwd', '--password', type=str, default=None) # optional password parser.add_argument('-n', '--unit', type=str, choices=['GiB', 'TiB', 'gib', 'tib'], default='TiB') args = parser.parse_args() vip = args.vip username = args.username domain = args.domain password = args.password unit = args.unit if unit.lower() == 'tib': multiplier = 1024 * 1024 * 1024 * 1024 unit = 'TiB' else: multiplier = 1024 * 1024 * 1024 unit = 'GiB' # authenticate apiauth(vip=vip, username=username, domain=domain, password=password, useApiKey=True, noretry=True) # outfile now = datetime.now() # cluster = api('get', 'cluster') dateString = now.strftime("%Y-%m-%d") outfile = 'heliosStorageStats-%s.csv' % dateString f = codecs.open(outfile, 'w') # headings f.write('Date,Capacity (%s),Consumed (%s),Free (%s),Used %%,Data In (%s),Data Written (%s),Storage Reduction,Data Reduction\n' % (unit, unit, unit, unit, unit)) stats = {} endMsecs = dateToUsecs(now.strftime("%Y-%m-%d %H:%M:%S")) / 1000 startMsecs = (timeAgo(2, 'days')) / 1000 print('\nGathering cluster stats:\n') for cluster in heliosClusters(): heliosCluster(cluster) print(' %s' % cluster['name']) capacityStats = api('get', 'statistics/timeSeriesStats?endTimeMsecs=%s&entityId=%s&metricName=kCapacityBytes&metricUnitType=0&range=day&rollupFunction=average&rollupIntervalSecs=86400&schemaName=kBridgeClusterStats&startTimeMsecs=%s' % (endMsecs, cluster['clusterId'], startMsecs)) consumedStats = api('get', 'statistics/timeSeriesStats?startTimeMsecs=%s&schemaName=kBridgeClusterTierPhysicalStats&metricName=kMorphedUsageBytes&rollupIntervalSecs=86400&rollupFunction=latest&entityIdList=%s:Local&endTimeMsecs=%s' % (startMsecs, cluster['clusterId'], endMsecs)) dataInStats = api('get', 'statistics/timeSeriesStats?startTimeMsecs=%s&schemaName=ApolloV2ClusterStats&metricName=BrickBytesLogical&rollupIntervalSecs=86400&rollupFunction=latest&entityIdList=%s (ID %s)&endTimeMsecs=%s' % (startMsecs, cluster['name'], cluster['clusterId'], endMsecs)) dataWrittenStats = api('get', 'statistics/timeSeriesStats?startTimeMsecs=%s&schemaName=ApolloV2ClusterStats&metricName=ChunkBytesMorphed&rollupIntervalSecs=86400&rollupFunction=latest&entityIdList=%s (ID %s)&endTimeMsecs=%s' % (startMsecs, cluster['name'], cluster['clusterId'], endMsecs)) logicalSizeStats = api('get', 'statistics/timeSeriesStats?startTimeMsecs=%s&schemaName=kBridgeClusterLogicalStats&metricName=kUnmorphedUsageBytes&rollupIntervalSecs=86400&rollupFunction=latest&entityIdList=%s&endTimeMsecs=%s' % (startMsecs, cluster['clusterId'], endMsecs)) parseStats(cluster['name'], capacityStats['dataPointVec'][0], 'capacity') parseStats(cluster['name'], consumedStats['dataPointVec'][0], 'consumed') parseStats(cluster['name'], dataInStats['dataPointVec'][0], 'dataIn') parseStats(cluster['name'], dataWrittenStats['dataPointVec'][0], 'dataWritten') parseStats(cluster['name'], logicalSizeStats['dataPointVec'][0], 'logicalSize') for clusterName in sorted(stats.keys()): capacity = stats[clusterName]['capacity'] consumed = stats[clusterName]['consumed'] dataIn = stats[clusterName]['dataIn'] dataWritten = stats[clusterName]['dataWritten'] logicalSize = stats[clusterName]['logicalSize'] free = capacity - consumed pctUsed = round(100 * consumed / capacity, 0) storageReduction = round(float(logicalSize) / consumed, 1) dataReduction = round(float(dataIn) / dataWritten, 1) f.write('"%s","%s","%s","%s","%s","%s","%s","%s","%s"\n' % (clusterName, toUnits(capacity), toUnits(consumed), toUnits(free), pctUsed, toUnits(dataIn), toUnits(dataWritten), storageReduction, dataReduction)) f.close() print('\nOutput saved to %s\n' % outfile)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 37811, 565, 5819, 6143, 9756, 329, 21015, 37811, 198, 198, 2, 1330, 12972, 956, 414, 29908, 8265, 198, 6738, 12972, 956, 414, 1330, 1635, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, ...
2.713115
1,586
#coding=utf-8 from PyQt4 import QtCore import os, glob, numpy, sys from PIL import Image from sklearn.cross_validation import StratifiedKFold from sklearn.metrics import confusion_matrix from sklearn.neighbors import KNeighborsClassifier from sklearn.neighbors import BallTree from sklearn import cross_validation from sklearn.utils import shuffle import sklearn import leargist import cPickle import random import sys reload(sys) sys.setdefaultencoding( "utf-8" )
[ 2, 66, 7656, 28, 40477, 12, 23, 198, 198, 6738, 9485, 48, 83, 19, 1330, 33734, 14055, 198, 11748, 28686, 11, 15095, 11, 299, 32152, 11, 25064, 198, 6738, 350, 4146, 1330, 7412, 198, 6738, 1341, 35720, 13, 19692, 62, 12102, 341, 1330...
3.243056
144
# coding: utf-8 """test_find_fork.""" # pylint: disable=no-self-use from __future__ import absolute_import, division, print_function, unicode_literals from os import path import unittest from six import PY3 from find_forks.__init__ import CONFIG from find_forks.find_forks import add_forks, determine_names, find_forks, main from .__init__ import BASEPATH if PY3: from unittest.mock import patch, MagicMock, Mock # pylint: disable=no-name-in-module else: from mock import patch, MagicMock, Mock
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 37811, 9288, 62, 19796, 62, 32523, 526, 15931, 198, 2, 279, 2645, 600, 25, 15560, 28, 3919, 12, 944, 12, 1904, 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 11, 7297, 11, 3601, 62, 8818,...
2.838889
180
# Copyright (c) 2015 Openstack Foundation # # 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 binascii import netaddr from oslo_log import log as logging from oslo_utils import excutils from neutron.agent.l3 import dvr_fip_ns from neutron.agent.l3 import dvr_snat_ns from neutron.agent.l3 import router_info as router from neutron.agent.linux import ip_lib from neutron.common import constants as l3_constants from neutron.common import utils as common_utils from neutron.i18n import _LE LOG = logging.getLogger(__name__) # xor-folding mask used for IPv6 rule index MASK_30 = 0x3fffffff
[ 2, 15069, 357, 66, 8, 1853, 4946, 25558, 5693, 198, 2, 198, 2, 220, 220, 220, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 345, 743, 198, 2, 220, 220, 220, 407, 779, 428, 2393, 2845, 287, ...
3.268222
343
""":mod:`sider.warnings` --- Warning categories ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This module defines several custom warning category classes. """
[ 15931, 1298, 4666, 25, 63, 82, 1304, 13, 40539, 654, 63, 11420, 15932, 9376, 198, 27156, 27156, 15116, 8728, 4907, 93, 198, 198, 1212, 8265, 15738, 1811, 2183, 6509, 6536, 6097, 13, 198, 198, 37811, 628, 628, 198 ]
4.394737
38
MEDIA_SEARCH = """ query ($search: String, $type: MediaType, $exclude: MediaFormat, $isAdult: Boolean) { Media(search: $search, type: $type, format_not: $exclude, isAdult: $isAdult) { id type format title { english romaji native } synonyms status description startDate { year month day } endDate { year month day } episodes chapters volumes coverImage { large color } bannerImage genres averageScore siteUrl isAdult nextAiringEpisode { timeUntilAiring episode } } } """ MEDIA_BY_ID = """ query ($id: Int, $type: MediaType) { Media(id: $id, type: $type) { id type format title { english romaji native } synonyms status description startDate { year month day } endDate { year month day } episodes chapters coverImage { large color } bannerImage genres averageScore siteUrl isAdult nextAiringEpisode { timeUntilAiring episode } } } """ MEDIA_PAGED = """ query ( $id: Int, $page: Int, $perPage: Int, $search: String, $type: MediaType, $sort: [MediaSort] = [SEARCH_MATCH], $exclude: MediaFormat, $isAdult: Boolean ) { Page(page: $page, perPage: $perPage) { media(id: $id, search: $search, type: $type, sort: $sort, format_not: $exclude, isAdult: $isAdult) { id type format title { english romaji native } synonyms status description startDate { year month day } endDate { year month day } episodes chapters volumes coverImage { large color } bannerImage genres averageScore siteUrl isAdult popularity } } } """ USER_SEARCH = """ query ($search: String) { User(search: $search) { id name html_about: about(asHtml: true) about avatar { large } bannerImage siteUrl stats { watchedTime chaptersRead } } } """ USER_BY_ID = """ query ($id: Int) { User(id: $id) { id name html_about: about(asHtml: true) about avatar { large } bannerImage siteUrl stats { watchedTime chaptersRead } } } """
[ 30733, 3539, 62, 5188, 31315, 796, 37227, 198, 22766, 7198, 12947, 25, 10903, 11, 720, 4906, 25, 6343, 6030, 11, 720, 1069, 9152, 25, 6343, 26227, 11, 720, 271, 42995, 25, 41146, 8, 1391, 198, 220, 6343, 7, 12947, 25, 720, 12947, 11...
2.012821
1,248
import unittest import operator import sandbox.chainop as chainop def suite(suffix="Test"): suite = unittest.TestSuite() all_names = globals() for name in all_names: if name.endswith(suffix): suite.addTest(unittest.makeSuite(all_names[name], "test")) return suite if __name__ == '__main__': runner = unittest.TextTestRunner() runner.run(suite())
[ 11748, 555, 715, 395, 198, 11748, 10088, 198, 11748, 35204, 13, 7983, 404, 355, 6333, 404, 628, 628, 198, 4299, 18389, 7, 37333, 844, 2625, 14402, 1, 2599, 198, 220, 220, 220, 18389, 796, 555, 715, 395, 13, 14402, 5606, 578, 3419, 1...
2.46875
160
#!/usr/bin/env python import chainer from algs import trpo from env_makers import EnvMaker from models import GaussianMLPPolicy, MLPBaseline from utils import SnapshotSaver import numpy as np import os import logger log_dir = "data/local/trpo-pendulum" np.random.seed(42) # Clean up existing logs os.system("rm -rf {}".format(log_dir)) with logger.session(log_dir): env_maker = EnvMaker('Pendulum-v0') env = env_maker.make() policy = GaussianMLPPolicy( observation_space=env.observation_space, action_space=env.action_space, env_spec=env.spec, hidden_sizes=(64, 64), hidden_nonlinearity=chainer.functions.tanh, ) baseline = MLPBaseline( observation_space=env.observation_space, action_space=env.action_space, env_spec=env.spec, hidden_sizes=(64, 64), hidden_nonlinearity=chainer.functions.tanh, ) trpo( env=env, env_maker=env_maker, n_envs=16, policy=policy, baseline=baseline, batch_size=10000, n_iters=100, snapshot_saver=SnapshotSaver(log_dir), )
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 11748, 6333, 263, 198, 198, 6738, 435, 14542, 1330, 491, 7501, 198, 6738, 17365, 62, 6620, 1330, 2039, 85, 48890, 198, 6738, 4981, 1330, 12822, 31562, 5805, 10246, 21424, 11, 10373, 47, ...
2.222004
509
#!/usr/bin/python3.7 # -*- coding: utf-8 -*- # @Time : 2019/12/2 10:17 # @Author: Jtyoui@qq.com """ """ try: import xml.etree.cElementTree as et except ModuleNotFoundError: import xml.etree.ElementTree as et import re
[ 2, 48443, 14629, 14, 8800, 14, 29412, 18, 13, 22, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2488, 7575, 220, 1058, 13130, 14, 1065, 14, 17, 838, 25, 1558, 198, 2, 2488, 13838, 25, 449, 774, 280, 72...
2.3
100
""" Main Author: Will LeVine Corresponding Email: levinewill@icloud.com """ import keras import numpy as np from sklearn.tree import DecisionTreeClassifier from sklearn.utils.validation import check_array, check_is_fitted, check_X_y from .base import BaseTransformer
[ 37811, 198, 13383, 6434, 25, 2561, 1004, 53, 500, 198, 10606, 5546, 278, 9570, 25, 443, 7114, 413, 359, 31, 291, 75, 2778, 13, 785, 198, 37811, 198, 11748, 41927, 292, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 1341, 35720, 13, ...
3.214286
84
import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.collections as mcoll from matplotlib.ticker import MaxNLocator plt.style.use('seaborn-darkgrid') def colorline(x, y, z=None, cmap=plt.get_cmap('copper'), norm=plt.Normalize(0.0, 1.0), linewidth=3, alpha=1.0, zorder=1): """ Plot a colored line with coordinates x and y Optionally specify colors in the array z Optionally specify a colormap, a norm function and a line width """ # Default colors equally spaced on [0,1]: if z is None: z = np.linspace(0.0, 1.0, len(x)) # Special case if a single number: if not hasattr(z, "__iter__"): # to check for numerical input -- this is a hack z = np.array([z]) z = np.asarray(z) segments = make_segments(x, y) lc = mcoll.LineCollection(segments, array=z, cmap=cmap, norm=norm, linewidth=linewidth, alpha=alpha, zorder=zorder) ax = plt.gca() ax.add_collection(lc) return lc def make_segments(x, y): """ Create list of line segments from x and y coordinates, in the correct format for LineCollection: an array of the form numlines x (points per line) x 2 (x and y) array """ points = np.array([x, y]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) return segments def truncate_colormap(cmap, minval=0.0, maxval=1.0, n=100): ''' https://stackoverflow.com/a/18926541 ''' if isinstance(cmap, str): cmap = plt.get_cmap(cmap) new_cmap = mpl.colors.LinearSegmentedColormap.from_list( 'trunc({n},{a:.2f},{b:.2f})'.format(n=cmap.name, a=minval, b=maxval), cmap(np.linspace(minval, maxval, n))) return new_cmap
[ 11748, 299, 32152, 355, 45941, 198, 11748, 2603, 29487, 8019, 355, 285, 489, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 2603, 29487, 8019, 13, 4033, 26448, 355, 285, 26000, 198, 6738, 2603, 29487, 8019, 13...
2.31039
770
import imp from venv import create from django.shortcuts import render, redirect from django.views import View from django.views.generic import ( ListView, ) from account.models import * from account.forms import * from data.models import * from django.contrib.auth import login as auth_login from django.contrib.auth.models import auth from django.contrib import messages from django.contrib.auth.mixins import PermissionRequiredMixin, LoginRequiredMixin # Create your views here. def deleteUser(request, event_id): event = Account.objects.get(pk=event_id) event.delete() return redirect('userlist')
[ 11748, 848, 198, 6738, 8710, 85, 1330, 2251, 198, 6738, 42625, 14208, 13, 19509, 23779, 1330, 8543, 11, 18941, 198, 6738, 42625, 14208, 13, 33571, 1330, 3582, 198, 6738, 42625, 14208, 13, 33571, 13, 41357, 1330, 357, 198, 220, 220, 220,...
3.326203
187
import cv2 import aiohttp import asyncio import concurrent.futures import argparse import numpy as np def main(): parser = argparse.ArgumentParser('fpds.client') parser.add_argument('url', type=str, help='WebSocket endpoint of fpds.server e.g. http://localhost:8181/fpds') args = parser.parse_args() loop = asyncio.get_event_loop() task = loop.create_task(amain(args.url)) try: loop.run_until_complete(task) except KeyboardInterrupt: task.cancel() loop.run_until_complete(asyncio.wait_for(task, timeout=None)) finally: loop.close() if __name__ == '__main__': main()
[ 11748, 269, 85, 17, 198, 11748, 257, 952, 4023, 198, 11748, 30351, 952, 198, 11748, 24580, 13, 69, 315, 942, 198, 11748, 1822, 29572, 198, 11748, 299, 32152, 355, 45941, 628, 198, 4299, 1388, 33529, 198, 220, 220, 220, 30751, 796, 182...
2.517787
253
import logging import os import pickle import sys import threading import time from typing import List from Giveme5W1H.extractor.root import path from Giveme5W1H.extractor.tools.util import bytes_2_human_readable
[ 11748, 18931, 198, 11748, 28686, 198, 11748, 2298, 293, 198, 11748, 25064, 198, 11748, 4704, 278, 198, 11748, 640, 198, 6738, 19720, 1330, 7343, 198, 198, 6738, 13786, 1326, 20, 54, 16, 39, 13, 2302, 40450, 13, 15763, 1330, 3108, 198, ...
3.359375
64
from argparse import ArgumentParser from tqdm import tqdm import NSST from nsst_translate import best_transition_sequence if __name__ == '__main__': parser = ArgumentParser() parser.add_argument("--nsst_file", default="output/nsst_tss20_th4_nSt100_Q0.pkl", help="nsst file") parser.add_argument("--src_lang", default="output/europarl-v7.de-en.de.clean") parser.add_argument("--tgt_lang", default="output/europarl-v7.de-en.en.clean") parser.add_argument("--enforce_n_reg", default=True) parser.add_argument("--output", default=f"output/nsst_stat_nreg_100Q0.csv") args = parser.parse_args() args.enforce_n_final_reg = False # load NSST nsst = NSST.NSST() nsst.load(args.nsst_file) args.nsst = nsst # open files src_file = open(args.src_lang, 'r') tgt_file = open(args.tgt_lang, 'r') output_file = open(args.output, 'w') # iterate over sentences, first 4096 -> test sentences for src, tgt, _ in tqdm(list(zip(src_file, tgt_file, range(4096))), desc="Processing sentences"): # remove line breaks src = src[:-1] tgt = tgt[:-1] # try to translate try: # prepare tokenisations token_src = [nsst.tokenization_src[word] if word in nsst.tokenization_src else 0 for word in src.split(" ") if len(word)] token_tgt = [nsst.tokenization_tgt[word] if word in nsst.tokenization_tgt else 0 for word in tgt.split(" ") if len(word)] # run nsst args.input = src args.token_src = token_src result = best_transition_sequence(args) # get best result pred = sorted((k for k in result if ('Qf' in args.nsst_file or not args.enforce_n_final_reg or len(k[1]) == 1) and ('Q0' in args.nsst_file or k[0] == -1) ), key=lambda x: x[2], reverse=True)[0] n_res = len(result) q, reg, prob = pred # write to csv if not len(reg): # catch empty registers continue token_pred = [w for w in reg[0].split(' ') if len(w)] pred_str = "" for t in token_pred: pred_str += f"{nsst.tokenization_tgt_lut[int(t)]} " token_src_str = "" for t in token_src: token_src_str += f"{t} " token_tgt_str = "" for t in token_tgt: token_tgt_str += f"{t} " token_pred_str = "" for t in token_pred: token_pred_str += f"{t} " print(f"{src};{token_src_str[:-1]};" f"{tgt};{token_tgt_str[:-1]};" f"{pred_str};{token_pred_str[:-1]};" f"{prob};{len(reg)};{n_res}", file=output_file) output_file.flush() except RuntimeError: pass # close files src_file.close() tgt_file.close() output_file.close()
[ 6738, 1822, 29572, 1330, 45751, 46677, 198, 198, 6738, 256, 80, 36020, 1330, 256, 80, 36020, 198, 198, 11748, 10896, 2257, 198, 6738, 36545, 301, 62, 7645, 17660, 1330, 1266, 62, 7645, 653, 62, 43167, 198, 198, 361, 11593, 3672, 834, ...
1.905372
1,638
# Import library import math # Define functionts # Set data size = int(input()) numbers = list(map(int, input().split())) # Get standard deviation print(round(stddev(numbers, size), 1))
[ 2, 17267, 5888, 198, 11748, 10688, 198, 198, 2, 2896, 500, 2163, 912, 198, 198, 2, 5345, 1366, 198, 7857, 796, 493, 7, 15414, 28955, 198, 77, 17024, 796, 1351, 7, 8899, 7, 600, 11, 5128, 22446, 35312, 3419, 4008, 198, 198, 2, 3497...
3
63
Alice='Ti rga eoe esg o h ore"ermetsCmuainls' Bob='hspormdcdsamsaefrtecus Hraina optcoae"' print(decode(Alice,Bob,''))
[ 198, 44484, 11639, 40533, 374, 4908, 304, 2577, 220, 1658, 70, 267, 289, 23751, 1, 7780, 1039, 34, 30300, 391, 7278, 6, 198, 18861, 11639, 71, 2777, 579, 17896, 9310, 4105, 64, 891, 81, 660, 9042, 367, 3201, 64, 2172, 1073, 3609, 30...
2.1
60
# =============================================================================== # Copyright 2012 Jake Ross # # 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. # =============================================================================== # ============= enthought library imports ======================= from __future__ import absolute_import from traits.api import HasTraits, Instance, DelegatesTo, Button, List, Any, Float from traitsui.api import View, Item, VGroup, HGroup, Group, spring, TabularEditor # ============= standard library imports ======================== import pickle import os from numpy import polyval # ============= local library imports ========================== from pychron.managers.manager import Manager from pychron.database.selectors.power_calibration_selector import ( PowerCalibrationSelector, ) from pychron.database.adapters.power_calibration_adapter import PowerCalibrationAdapter from pychron.paths import paths from pychron.graph.graph import Graph from pychron.hardware.meter_calibration import MeterCalibration """ use a dbselector to select data """ if __name__ == "__main__": ccm = CompositeCalibrationManager() ccm.configure_traits() # ============= EOF =============================================
[ 2, 38093, 25609, 855, 198, 2, 15069, 2321, 14757, 9847, 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, ...
4.114486
428
# refactored from make_play to simplify # by Russell on 3/5/21 #from ttt_package.libs.move_utils import get_open_cells from ttt_package.libs.compare import get_transposed_games, reorient_games from ttt_package.libs.calc_game_bound import calc_game_bound from ttt_package.libs.maxi_min import maximin # find the best move for this agent, based on prior games in the game_history
[ 2, 1006, 529, 1850, 422, 787, 62, 1759, 284, 30276, 198, 2, 416, 11563, 319, 513, 14, 20, 14, 2481, 198, 198, 2, 6738, 256, 926, 62, 26495, 13, 8019, 82, 13, 21084, 62, 26791, 1330, 651, 62, 9654, 62, 46342, 198, 6738, 256, 926,...
3.04
125
#!/usr/bin/env python3 # python import _thread import time from yvhai.demo.base import YHDemo if __name__ == '__main__': RawThreadDemo.demo()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 21015, 220, 628, 198, 11748, 4808, 16663, 198, 11748, 640, 198, 198, 6738, 331, 85, 44488, 13, 9536, 78, 13, 8692, 1330, 575, 10227, 41903, 628, 628, 198, 361, 11593, 3672, 83...
2.483871
62
# constants for configuration parameters of our tensorflow models LABEL = "label" IDS = "ids" # LABEL_PAD_ID is used to pad multi-label training examples. # It should be < 0 to avoid index out of bounds errors by tf.one_hot. LABEL_PAD_ID = -1 HIDDEN_LAYERS_SIZES = "hidden_layers_sizes" SHARE_HIDDEN_LAYERS = "share_hidden_layers" TRANSFORMER_SIZE = "transformer_size" NUM_TRANSFORMER_LAYERS = "number_of_transformer_layers" NUM_HEADS = "number_of_attention_heads" UNIDIRECTIONAL_ENCODER = "unidirectional_encoder" KEY_RELATIVE_ATTENTION = "use_key_relative_attention" VALUE_RELATIVE_ATTENTION = "use_value_relative_attention" MAX_RELATIVE_POSITION = "max_relative_position" BATCH_SIZES = "batch_size" BATCH_STRATEGY = "batch_strategy" EPOCHS = "epochs" RANDOM_SEED = "random_seed" LEARNING_RATE = "learning_rate" DENSE_DIMENSION = "dense_dimension" CONCAT_DIMENSION = "concat_dimension" EMBEDDING_DIMENSION = "embedding_dimension" ENCODING_DIMENSION = "encoding_dimension" SIMILARITY_TYPE = "similarity_type" LOSS_TYPE = "loss_type" NUM_NEG = "number_of_negative_examples" MAX_POS_SIM = "maximum_positive_similarity" MAX_NEG_SIM = "maximum_negative_similarity" USE_MAX_NEG_SIM = "use_maximum_negative_similarity" SCALE_LOSS = "scale_loss" REGULARIZATION_CONSTANT = "regularization_constant" NEGATIVE_MARGIN_SCALE = "negative_margin_scale" DROP_RATE = "drop_rate" DROP_RATE_ATTENTION = "drop_rate_attention" DROP_RATE_DIALOGUE = "drop_rate_dialogue" DROP_RATE_LABEL = "drop_rate_label" CONSTRAIN_SIMILARITIES = "constrain_similarities" WEIGHT_SPARSITY = "weight_sparsity" # Deprecated and superseeded by CONNECTION_DENSITY CONNECTION_DENSITY = "connection_density" EVAL_NUM_EPOCHS = "evaluate_every_number_of_epochs" EVAL_NUM_EXAMPLES = "evaluate_on_number_of_examples" INTENT_CLASSIFICATION = "intent_classification" ENTITY_RECOGNITION = "entity_recognition" MASKED_LM = "use_masked_language_model" SPARSE_INPUT_DROPOUT = "use_sparse_input_dropout" DENSE_INPUT_DROPOUT = "use_dense_input_dropout" RANKING_LENGTH = "ranking_length" MODEL_CONFIDENCE = "model_confidence" BILOU_FLAG = "BILOU_flag" RETRIEVAL_INTENT = "retrieval_intent" USE_TEXT_AS_LABEL = "use_text_as_label" SOFTMAX = "softmax" MARGIN = "margin" AUTO = "auto" INNER = "inner" LINEAR_NORM = "linear_norm" COSINE = "cosine" CROSS_ENTROPY = "cross_entropy" BALANCED = "balanced" SEQUENCE = "sequence" SEQUENCE_LENGTH = f"{SEQUENCE}_lengths" SENTENCE = "sentence" POOLING = "pooling" MAX_POOLING = "max" MEAN_POOLING = "mean" TENSORBOARD_LOG_DIR = "tensorboard_log_directory" TENSORBOARD_LOG_LEVEL = "tensorboard_log_level" SEQUENCE_FEATURES = "sequence_features" SENTENCE_FEATURES = "sentence_features" FEATURIZERS = "featurizers" CHECKPOINT_MODEL = "checkpoint_model" MASK = "mask" IGNORE_INTENTS_LIST = "ignore_intents_list" TOLERANCE = "tolerance" POSITIVE_SCORES_KEY = "positive_scores" NEGATIVE_SCORES_KEY = "negative_scores" RANKING_KEY = "label_ranking" QUERY_INTENT_KEY = "query_intent" SCORE_KEY = "score" THRESHOLD_KEY = "threshold" SEVERITY_KEY = "severity" NAME = "name" EPOCH_OVERRIDE = "epoch_override"
[ 2, 38491, 329, 8398, 10007, 286, 674, 11192, 273, 11125, 4981, 198, 198, 48780, 3698, 796, 366, 18242, 1, 198, 14255, 796, 366, 2340, 1, 198, 2, 406, 6242, 3698, 62, 47, 2885, 62, 2389, 318, 973, 284, 14841, 5021, 12, 18242, 3047, ...
2.451104
1,268
# # Copyright 2016-2019 Games Creators Club # # MIT License # import math import pyroslib import pyroslib.logging import time from pyroslib.logging import log, LOG_LEVEL_ALWAYS, LOG_LEVEL_INFO, LOG_LEVEL_DEBUG from rover import WheelOdos, WHEEL_NAMES from rover import normaiseAngle, angleDiference from challenge_utils import Action, PID SQRT2 = math.sqrt(2) PIhalf = math.pi / 2 if __name__ == "__main__": from rover import Radar, RoverState radar_values = {0: 10, 45: SQRT2 * 10, 90: 10, 135: SQRT2 * 10, 180: 10, 225: SQRT2 * 10, 270: 10, 315: SQRT2 * 10} radar_last_values = {0: 10, 45: SQRT2 * 10, 90: 10, 135: SQRT2 * 10, 180: 10, 225: SQRT2 * 10, 270: 10, 315: SQRT2 * 10} radar_status = {0: 0, 45: 0, 90: 0, 135: 0, 180: 0, 225: 0, 270: 0, 315: 0} attitude = MazeAttitude() radar = Radar(0, radar_values, radar_status, Radar(0, radar_last_values, radar_status)) state = RoverState(None, None, None, radar, None, None) # attitude.calculate(state) # printWalls() # # state.radar.radar[0] = 5 # state.radar.radar[45] = SQRT2 * 5 * 0.9 # state.radar.radar[315] = SQRT2 * 17 # state.radar.radar[270] = SQRT2 * 13 # state.radar.radar[225] = SQRT2 * 12 # attitude.calculate(state) # printWalls() state.radar.radar[180] = 50 state.radar.radar[315] = 30 attitude.calculate(state) printWalls()
[ 198, 2, 198, 2, 15069, 1584, 12, 23344, 5776, 7921, 669, 6289, 198, 2, 198, 2, 17168, 13789, 198, 2, 198, 198, 11748, 10688, 198, 11748, 12972, 4951, 8019, 198, 11748, 12972, 4951, 8019, 13, 6404, 2667, 198, 11748, 640, 198, 198, 67...
2.378194
587
PROTO = { 'spaceone.monitoring.interface.grpc.v1.data_source': ['DataSource'], 'spaceone.monitoring.interface.grpc.v1.metric': ['Metric'], 'spaceone.monitoring.interface.grpc.v1.project_alert_config': ['ProjectAlertConfig'], 'spaceone.monitoring.interface.grpc.v1.escalation_policy': ['EscalationPolicy'], 'spaceone.monitoring.interface.grpc.v1.event_rule': ['EventRule'], 'spaceone.monitoring.interface.grpc.v1.webhook': ['Webhook'], 'spaceone.monitoring.interface.grpc.v1.maintenance_window': ['MaintenanceWindow'], 'spaceone.monitoring.interface.grpc.v1.alert': ['Alert'], 'spaceone.monitoring.interface.grpc.v1.note': ['Note'], 'spaceone.monitoring.interface.grpc.v1.event': ['Event'], }
[ 4805, 26631, 796, 1391, 198, 220, 220, 220, 705, 13200, 505, 13, 41143, 278, 13, 39994, 13, 2164, 14751, 13, 85, 16, 13, 7890, 62, 10459, 10354, 37250, 6601, 7416, 6, 4357, 198, 220, 220, 220, 705, 13200, 505, 13, 41143, 278, 13, ...
2.577465
284
from django.contrib.contenttypes.fields import ( GenericForeignKey, GenericRelation ) from django.contrib.contenttypes.models import ContentType from django.db import models # Models for #15776 # Models for #16128
[ 6738, 42625, 14208, 13, 3642, 822, 13, 11299, 19199, 13, 25747, 1330, 357, 198, 220, 220, 220, 42044, 33616, 9218, 11, 42044, 6892, 341, 198, 8, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 11299, 19199, 13, 27530, 1330, 14041, 6030, 1...
3.1125
80
import cv2 from cv2 import * import numpy as np from matplotlib import pyplot as plt ###############################SIFT MATCH Function################################# ################################################################################################### #################################Function######################### ############################################################ ###########################MAIN############################# MIN_MATCH_COUNT = 10 e1 = cv2.getTickCount() # # initialize the camera # cam = VideoCapture(0) # 0 -> index of camera # s, img1 = cam.read() # ret = cam.set(3,1920); # ret = cam.set(4,1080); # if s: # frame captured without any errors # cv2.namedWindow("output", cv2.WINDOW_NORMAL) # cv2.imshow("cam-test",img1) # waitKey(0) # destroyWindow("cam-test") # imwrite("Scene.jpg",img1) #save image # del(cam) # Scene image in Grayscale # imgray = cv2.cvtColor(img1,cv2.COLOR_BGR2GRAY) imgray = cv2.imread('Scene.jpg', 0) # queryImage # Reference Piece Image img1 = cv2.imread('img3.jpg',0) # queryImage # SIFT Algorithm fore Object Detection SIFTMATCH(img1, imgray) # image de reference cX, cY = CercleDetection('img3.jpg') print('cX = %.3f , cY =%.3f' % (cX, cY)) # Image Webcam cX2, cY2 = CercleDetection('img3.jpg') print('cX2 = %.3f , cY2 =%.3f' % (cX2, cY2)) deltaX = (cX2-cX) deltaY = -(CY2-cY) # Write X and Y values to File file = open("values.txt", "w") file.write("%.3f \n" % deltaX) file.write("%.3f \n" % deltaY) file.close() #Calculate time of execution e2 = cv2.getTickCount() time = (e2 - e1)/ cv2.getTickFrequency() print('time needed to execute') print(time)
[ 11748, 269, 85, 17, 201, 198, 6738, 269, 85, 17, 1330, 1635, 201, 198, 11748, 299, 32152, 355, 45941, 201, 198, 6738, 2603, 29487, 8019, 1330, 12972, 29487, 355, 458, 83, 201, 198, 201, 198, 201, 198, 201, 198, 201, 198, 14468, 7804...
2.443537
735
import dash from dash.exceptions import PreventUpdate import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output, State import dash_bootstrap_components as dbc import dash_table import plotly.express as ex import plotly.graph_objects as go import pandas as pd import numpy as np data = pd.read_csv("./data/Phone_dataset_new.csv", header=0) details = pd.read_csv("./data/Phone_details.csv", header=0) names = details.loc[0] data = data.rename(columns=names) details = details.rename(columns=names) maxi = details.loc[1].astype(int) details_on_card = details.loc[2].astype(int) details_on_card = details.columns[details_on_card == 1] fitness_columns = { "Memory": -1, "RAM": -1, "Camera (MP)": -1, "Price (Euros)": 1, } fitness_data = data[fitness_columns] * maxi[fitness_columns].values external_stylesheets = ["https://codepen.io/chriddyp/pen/bWLwgP.css"] app = dash.Dash( __name__, external_stylesheets=[dbc.themes.LITERA], eager_loading=True, suppress_callback_exceptions=True, ) app.layout = html.Div( children=[ # .container class is fixed, .container.scalable is scalable dbc.Row( [ dbc.Col( html.H1( children="What is your optimal phone?", className="text-center mt-4", ) ) ] ), dbc.Row( [ dbc.Col( children=[ # Top card with details(?) dbc.Card( children=[ dbc.CardBody( [ html.H4( "Researcher's Night Event", className="card-title text-center", ), html.P( ( "This app uses decision support tools to " "quickly and easily find phones which reflect " "the user's desires. Input your preferences " "below. The box on top right shows the phone " "which matches the preferences the best. " "The box on bottom right provides some " "close alternatives." ), className="card-text", ), ] ) ], className="mr-3 ml-3 mb-2 mt-2", ), dbc.Form( [ dbc.FormGroup( children=[ dbc.Label( "Choose desired operating system", html_for="os-choice", ), dbc.RadioItems( options=[ { "label": "Android", "value": "Android", }, {"label": "iOS", "value": "IOS"}, { "label": "No preference", "value": "both", }, ], id="os-choice", value="both", inline=True, # className="text-center mt-4", ), ], className="mr-3 ml-3 mb-2 mt-2", ), dbc.FormGroup( children=[ dbc.Label( "Choose desired Memory capacity (GB)", html_for="memory-choice", ), dcc.Slider( id="memory-choice", min=16, max=256, step=None, included=False, value=256, marks={ 16: "16", 32: "32", 64: "64", 128: "128", 256: "256", }, # className="text-center mt-5", ), ], className="mr-3 ml-3 mb-2 mt-2", ), dbc.FormGroup( children=[ dbc.Label( "Choose desired RAM capacity (GB)", html_for="ram-choice", ), dcc.Slider( id="ram-choice", min=2, max=12, step=1, value=12, included=False, marks={ 2: "2", 3: "3", 4: "4", 5: "5", 6: "6", 7: "7", 8: "8", 9: "9", 10: "10", 11: "11", 12: "12", }, className="text-center mt-5", ), ], className="mr-3 ml-3 mb-2 mt-2", ), dbc.FormGroup( children=[ dbc.Label( "Choose desired camera resolution (MP)", html_for="cam-choice", ), dcc.Slider( id="cam-choice", min=0, max=130, step=1, included=False, value=70, marks={ 0: "0", 10: "10", 30: "30", 50: "50", 70: "70", 90: "90", 110: "110", 130: "130", }, className="text-center mt-5", ), ], className="mr-3 ml-3 mb-2 mt-2", ), dbc.FormGroup( children=[ dbc.Label( "Choose desired budget (Euros)", html_for="cost-choice", ), dcc.Slider( id="cost-choice", min=0, max=1400, step=1, included=False, value=100, marks={ 0: "0", 200: "200", 400: "400", 600: "600", 800: "800", 1000: "1000", 1200: "1200", 1400: "1400", }, className="text-center mt-5", ), ], className="mr-3 ml-3 mb-2 mt-2", ), ], style={"maxHeight": "560px", "overflow": "auto"}, ), ], width={"size": 5, "offset": 1}, ), dbc.Col( children=[ dbc.Card( children=[ dbc.CardHeader("The best phone for you is:"), dbc.CardBody(id="results"), ], className="mb-4", ), dbc.Card( children=[ dbc.CardHeader("Other great phones:"), dbc.CardBody( id="other-results", children=( [ html.P( html.Span( f"{i}. ", id=f"other-results-list-{i}", ) ) for i in range(2, 6) ] + [ dbc.Tooltip( id=f"other-results-tooltip-{i}", target=f"other-results-list-{i}", placement="right", style={ "maxWidth": 700, "background-color": "white", "color": "white", "border-style": "solid", "border-color": "black", }, ) for i in range(2, 6) ] ), ), ], className="mt-4", ), html.Div(id="tooltips"), ], width={"size": 5, "offset": 0}, className="mb-2 mt-2", ), ] ), dbc.Row([html.Div(id="callback-dump")]), ], ) """@app.callback(Output("tooltips", "children"), [Input("callback-dump", "children")]) def tooltips(tooldict): num = len(tooldict["ids"]) content = [] for i in range(num): content.append(dbc.Tooltip(tooldict["tables"][i], target=tooldict["ids"][i])) return content""" if __name__ == "__main__": app.run_server(debug=False)
[ 11748, 14470, 198, 6738, 14470, 13, 1069, 11755, 1330, 31572, 10260, 198, 11748, 14470, 62, 7295, 62, 5589, 3906, 355, 288, 535, 198, 11748, 14470, 62, 6494, 62, 5589, 3906, 355, 27711, 198, 6738, 14470, 13, 45841, 3976, 1330, 23412, 11...
1.278417
10,944
import pyxon.decode as pd def unobjectify(obj): """ Turns a python object (must be a class instance) into the corresponding JSON data. Example: >>> @sprop.a # sprop annotations are needed to tell the >>> @sprop.b # unobjectify function what parameter need >>> @sprop.c # to be written out. >>> class Baz(object): pass >>> def __init__(self, a, b, c): >>> self.a = a >>> self.b = b >>> self.c = c >>> >>> baz = Baz(a=1, b=2, c='three') >>> unobjectify(baz) { 'a':1, 'b':2, 'c':'three' } """ cls = obj.__class__ # Create empty data data = {} sprops,cprops = _get_registered_props(cls) # Add simple properties for p in sprops: data[p]=getattr(obj,p) # Add calculated data for p in cprops: f2 = cprops[p][1] data[p]=f2(getattr(obj,p)) data = pd.add_type_property(data, cls) return data def _get_registered_props(cls): """ Returns all of the registered properties for a given class. Recursively calls up to parent classes that are inherited from. """ sprops = pd.class_sprops.get(cls,{}) # [name] cprops = pd.class_cprops.get(cls,{}) # {name:(fn, inv_fn)} if cls in pd.conc_to_abstract: # {ConcreteClass: (AbstractClass, _)} parent_cls = pd.conc_to_abstract[cls][0] parent_sprops, parent_cprops = _get_registered_props(parent_cls) sprops = list(set(sprops).union(set(parent_sprops))) cprops2 = parent_cprops.copy() cprops2.update(cprops) cprops = cprops2 return sprops,cprops def obj(cls): """ Helper function returns a closure turning objectify into a single argument function. This cuts down the amount of code needed in class annotations by removing the need to write lambda functions. """ return lambda d: objectify(d, cls) def objectify(data, cls): """ Function takes JSON data and a target class as arguments and returns an instance of the class created using the JSON data. I'm not sure whether it is a great idea to keep (un)objectify separate from the decode module, since they need to access some of the module-level parameters. """ # Create empty class concrete_cls = pd.conc2(data, cls) obj = concrete_cls() sprops,cprops = _get_registered_props(cls) # Add simple properties from data for p in sprops: setattr(obj, p, data[p]) # Add calculated properties from data for p in cprops: f1 = cprops[p][0] setattr(obj, p, f1(data[p])) return obj def transform_map(kfun=lambda x: x, vfun=lambda x: x): """ Function that takes two functions as arguments and returns a function that applies those functions over all of the keys and values in a map and returns the transformed version of the map. kfun: function applied to all keys (default identity) vfun: function applied to all values (default identity) (k -> k') -> (v -> v') -> ((k, v) -> (k', v')) """ return lambda dct: dict([(kfun(k),vfun(v)) for k,v in dct.items()]) def identity(x): """ Identity function is needed when performing transformations on maps where some operation is needed on either the keys or values, but not both. """ return x
[ 11748, 12972, 23813, 13, 12501, 1098, 355, 279, 67, 198, 198, 4299, 555, 15252, 1958, 7, 26801, 2599, 198, 220, 220, 220, 37227, 198, 220, 220, 220, 30875, 257, 21015, 2134, 357, 27238, 307, 257, 1398, 4554, 8, 198, 220, 220, 220, 6...
2.448301
1,383
# Segmentation script # ------------------- # This script lets the user segment automatically one or many images based on the default segmentation models: SEM or # TEM. # # Maxime Wabartha - 2017-08-30 # Imports import sys from pathlib import Path import json import argparse from argparse import RawTextHelpFormatter from tqdm import tqdm import pkg_resources import AxonDeepSeg import AxonDeepSeg.ads_utils as ads from AxonDeepSeg.apply_model import axon_segmentation from AxonDeepSeg.ads_utils import convert_path # Global variables SEM_DEFAULT_MODEL_NAME = "default_SEM_model_v1" TEM_DEFAULT_MODEL_NAME = "default_TEM_model_v1" MODELS_PATH = pkg_resources.resource_filename('AxonDeepSeg', 'models') MODELS_PATH = Path(MODELS_PATH) default_SEM_path = MODELS_PATH / SEM_DEFAULT_MODEL_NAME default_TEM_path = MODELS_PATH / TEM_DEFAULT_MODEL_NAME default_overlap = 25 # Definition of the functions def segment_image(path_testing_image, path_model, overlap_value, config, resolution_model, acquired_resolution = None, verbosity_level=0): ''' Segment the image located at the path_testing_image location. :param path_testing_image: the path of the image to segment. :param path_model: where to access the model :param overlap_value: the number of pixels to be used for overlap when doing prediction. Higher value means less border effects but more time to perform the segmentation. :param config: dict containing the configuration of the network :param resolution_model: the resolution the model was trained on. :param verbosity_level: Level of verbosity. The higher, the more information is given about the segmentation process. :return: Nothing. ''' # If string, convert to Path objects path_testing_image = convert_path(path_testing_image) path_model = convert_path(path_model) if path_testing_image.exists(): # Extracting the image name and its folder path from the total path. path_parts = path_testing_image.parts acquisition_name = Path(path_parts[-1]) path_acquisition = Path(*path_parts[:-1]) # Get type of model we are using selected_model = path_model.name # Read image img = ads.imread(str(path_testing_image)) # Generate tmp file fp = open(path_acquisition / '__tmp_segment__.png', 'wb+') img_name_original = acquisition_name.stem if selected_model == "default_TEM_model_v1": ads.imwrite(fp,255-img, format='png') else: ads.imwrite(fp, img, format='png') acquisition_name = Path(fp.name).name segmented_image_name = img_name_original + '_seg-axonmyelin' + '.png' # Performing the segmentation axon_segmentation(path_acquisitions_folders=path_acquisition, acquisitions_filenames=[acquisition_name], path_model_folder=path_model, config_dict=config, ckpt_name='model', inference_batch_size=1, overlap_value=overlap_value, segmentations_filenames=segmented_image_name, resampled_resolutions=resolution_model, verbosity_level=verbosity_level, acquired_resolution=acquired_resolution, prediction_proba_activate=False, write_mode=True) if verbosity_level >= 1: print(("Image {0} segmented.".format(path_testing_image))) # Remove temporary file used for the segmentation fp.close() (path_acquisition / '__tmp_segment__.png').unlink() else: print(("The path {0} does not exist.".format(path_testing_image))) return None def segment_folders(path_testing_images_folder, path_model, overlap_value, config, resolution_model, acquired_resolution = None, verbosity_level=0): ''' Segments the images contained in the image folders located in the path_testing_images_folder. :param path_testing_images_folder: the folder where all image folders are located (the images to segment are located in those image folders) :param path_model: where to access the model. :param overlap_value: the number of pixels to be used for overlap when doing prediction. Higher value means less border effects but more time to perform the segmentation. :param config: dict containing the configuration of the network :param resolution_model: the resolution the model was trained on. :param verbosity_level: Level of verbosity. The higher, the more information is given about the segmentation process. :return: Nothing. ''' # If string, convert to Path objects path_testing_images_folder = convert_path(path_testing_images_folder) path_model = convert_path(path_model) # Update list of images to segment by selecting only image files (not already segmented or not masks) img_files = [file for file in path_testing_images_folder.iterdir() if (file.suffix.lower() in ('.png','.jpg','.jpeg','.tif','.tiff')) and (not str(file).endswith(('_seg-axonmyelin.png','_seg-axon.png','_seg-myelin.png','mask.png')))] # Pre-processing: convert to png if not already done and adapt to model contrast for file_ in tqdm(img_files, desc="Segmentation..."): print(path_testing_images_folder / file_) try: height, width, _ = ads.imread(str(path_testing_images_folder / file_)).shape except: try: height, width = ads.imread(str(path_testing_images_folder / file_)).shape except Exception as e: raise e image_size = [height, width] minimum_resolution = config["trainingset_patchsize"] * resolution_model / min(image_size) if acquired_resolution < minimum_resolution: print("EXCEPTION: The size of one of the images ({0}x{1}) is too small for the provided pixel size ({2}).\n".format(height, width, acquired_resolution), "The image size must be at least {0}x{0} after resampling to a resolution of {1} to create standard sized patches.\n".format(config["trainingset_patchsize"], resolution_model), "One of the dimensions of the image has a size of {0} after resampling to that resolution.\n".format(round(acquired_resolution * min(image_size) / resolution_model)), "Image file location: {0}".format(str(path_testing_images_folder / file_)) ) sys.exit(2) selected_model = path_model.name # Read image for conversion img = ads.imread(str(path_testing_images_folder / file_)) # Generate tmpfile for segmentation pipeline fp = open(path_testing_images_folder / '__tmp_segment__.png', 'wb+') img_name_original = file_.stem if selected_model == "default_TEM_model_v1": ads.imwrite(fp,255-img, format='png') else: ads.imwrite(fp,img, format='png') acquisition_name = Path(fp.name).name segmented_image_name = img_name_original + '_seg-axonmyelin' + '.png' axon_segmentation(path_acquisitions_folders=path_testing_images_folder, acquisitions_filenames=[acquisition_name], path_model_folder=path_model, config_dict=config, ckpt_name='model', inference_batch_size=1, overlap_value=overlap_value, segmentations_filenames=[segmented_image_name], acquired_resolution=acquired_resolution, verbosity_level=verbosity_level, resampled_resolutions=resolution_model, prediction_proba_activate=False, write_mode=True) if verbosity_level >= 1: tqdm.write("Image {0} segmented.".format(str(path_testing_images_folder / file_))) # Remove temporary file used for the segmentation fp.close() (path_testing_images_folder / '__tmp_segment__.png').unlink() return None def generate_default_parameters(type_acquisition, new_path): ''' Generates the parameters used for segmentation for the default model corresponding to the type_model acquisition. :param type_model: String, the type of model to get the parameters from. :param new_path: Path to the model to use. :return: the config dictionary. ''' # If string, convert to Path objects new_path = convert_path(new_path) # Building the path of the requested model if it exists and was supplied, else we load the default model. if type_acquisition == 'SEM': if (new_path is not None) and new_path.exists(): path_model = new_path else: path_model = MODELS_PATH / SEM_DEFAULT_MODEL_NAME elif type_acquisition == 'TEM': if (new_path is not None) and new_path.exists(): path_model = new_path else: path_model = MODELS_PATH / TEM_DEFAULT_MODEL_NAME path_config_file = path_model / 'config_network.json' config = generate_config_dict(path_config_file) return path_model, config def generate_config_dict(path_to_config_file): ''' Generates the dictionary version of the configuration file from the path where it is located. :param path_to_config: relative path where the file config_network.json is located. :return: dict containing the configuration of the network, or None if no configuration file was found at the mentioned path. ''' # If string, convert to Path objects path_to_config_file = convert_path(path_to_config_file) try: with open(path_to_config_file, 'r') as fd: config_network = json.loads(fd.read()) except: raise ValueError("No configuration file available at this path.") return config_network def generate_resolution(type_acquisition, model_input_size): ''' Generates the resolution to use related to the trained modeL. :param type_acquisition: String, "SEM" or "TEM" :param model_input_size: String or Int, the size of the input. :return: Float, the resolution of the model. ''' dict_size = { "SEM":{ "512":0.1, "256":0.2 }, "TEM":{ "512":0.01 } } return dict_size[str(type_acquisition)][str(model_input_size)] # Main loop def main(argv=None): ''' Main loop. :return: Exit code. 0: Success 2: Invalid argument value 3: Missing value or file ''' print(('AxonDeepSeg v.{}'.format(AxonDeepSeg.__version__))) ap = argparse.ArgumentParser(formatter_class=RawTextHelpFormatter) requiredName = ap.add_argument_group('required arguments') # Setting the arguments of the segmentation requiredName.add_argument('-t', '--type', required=True, choices=['SEM','TEM'], help='Type of acquisition to segment. \n'+ 'SEM: scanning electron microscopy samples. \n'+ 'TEM: transmission electron microscopy samples. ') requiredName.add_argument('-i', '--imgpath', required=True, nargs='+', help='Path to the image to segment or path to the folder \n'+ 'where the image(s) to segment is/are located.') ap.add_argument("-m", "--model", required=False, help='Folder where the model is located. \n'+ 'The default SEM model path is: \n'+str(default_SEM_path)+'\n'+ 'The default TEM model path is: \n'+str(default_TEM_path)+'\n') ap.add_argument('-s', '--sizepixel', required=False, help='Pixel size of the image(s) to segment, in micrometers. \n'+ 'If no pixel size is specified, a pixel_size_in_micrometer.txt \n'+ 'file needs to be added to the image folder path. The pixel size \n'+ 'in that file will be used for the segmentation.', default=None) ap.add_argument('-v', '--verbose', required=False, type=int, choices=list(range(0,4)), help='Verbosity level. \n'+ '0 (default) : Displays the progress bar for the segmentation. \n'+ '1: Also displays the path of the image(s) being segmented. \n'+ '2: Also displays the information about the prediction step \n'+ ' for the segmentation of current sample. \n'+ '3: Also displays the patch number being processed in the current sample.', default=0) ap.add_argument('-o', '--overlap', required=False, type=int, help='Overlap value (in pixels) of the patches when doing the segmentation. \n'+ 'Higher values of overlap can improve the segmentation at patch borders, \n'+ 'but also increase the segmentation time. \n'+ 'Default value: '+str(default_overlap)+'\n'+ 'Recommended range of values: [10-100]. \n', default=25) ap._action_groups.reverse() # Processing the arguments args = vars(ap.parse_args(argv)) type_ = str(args["type"]) verbosity_level = int(args["verbose"]) overlap_value = int(args["overlap"]) if args["sizepixel"] is not None: psm = float(args["sizepixel"]) else: psm = None path_target_list = [Path(p) for p in args["imgpath"]] new_path = Path(args["model"]) if args["model"] else None # Preparing the arguments to axon_segmentation function path_model, config = generate_default_parameters(type_, new_path) resolution_model = generate_resolution(type_, config["trainingset_patchsize"]) # Tuple of valid file extensions validExtensions = ( ".jpeg", ".jpg", ".tif", ".tiff", ".png" ) # Going through all paths passed into arguments for current_path_target in path_target_list: if not current_path_target.is_dir(): if current_path_target.suffix.lower() in validExtensions: # Handle cases if no resolution is provided on the CLI if psm == None: # Check if a pixel size file exists, if so read it. if (current_path_target.parent / 'pixel_size_in_micrometer.txt').exists(): resolution_file = open(current_path_target.parent / 'pixel_size_in_micrometer.txt', 'r') psm = float(resolution_file.read()) else: print("ERROR: No pixel size is provided, and there is no pixel_size_in_micrometer.txt file in image folder. ", "Please provide a pixel size (using argument -s), or add a pixel_size_in_micrometer.txt file ", "containing the pixel size value." ) sys.exit(3) # Check that image size is large enough for given resolution to reach minimum patch size after resizing. try: height, width, _ = ads.imread(str(current_path_target)).shape except: try: height, width = ads.imread(str(current_path_target)).shape except Exception as e: raise e image_size = [height, width] minimum_resolution = config["trainingset_patchsize"] * resolution_model / min(image_size) if psm < minimum_resolution: print("EXCEPTION: The size of one of the images ({0}x{1}) is too small for the provided pixel size ({2}).\n".format(height, width, psm), "The image size must be at least {0}x{0} after resampling to a resolution of {1} to create standard sized patches.\n".format(config["trainingset_patchsize"], resolution_model), "One of the dimensions of the image has a size of {0} after resampling to that resolution.\n".format(round(psm * min(image_size) / resolution_model)), "Image file location: {0}".format(current_path_target) ) sys.exit(2) # Performing the segmentation over the image segment_image(current_path_target, path_model, overlap_value, config, resolution_model, acquired_resolution=psm, verbosity_level=verbosity_level) print("Segmentation finished.") else: print("The path(s) specified is/are not image(s). Please update the input path(s) and try again.") break else: # Handle cases if no resolution is provided on the CLI if psm == None: # Check if a pixel size file exists, if so read it. if (current_path_target / 'pixel_size_in_micrometer.txt').exists(): resolution_file = open(current_path_target / 'pixel_size_in_micrometer.txt', 'r') psm = float(resolution_file.read()) else: print("ERROR: No pixel size is provided, and there is no pixel_size_in_micrometer.txt file in image folder. ", "Please provide a pixel size (using argument -s), or add a pixel_size_in_micrometer.txt file ", "containing the pixel size value." ) sys.exit(3) # Performing the segmentation over all folders in the specified folder containing acquisitions to segment. segment_folders(current_path_target, path_model, overlap_value, config, resolution_model, acquired_resolution=psm, verbosity_level=verbosity_level) print("Segmentation finished.") sys.exit(0) # Calling the script if __name__ == '__main__': main()
[ 2, 1001, 5154, 341, 4226, 198, 2, 34400, 6329, 198, 2, 770, 4226, 8781, 262, 2836, 10618, 6338, 530, 393, 867, 4263, 1912, 319, 262, 4277, 10618, 341, 4981, 25, 48603, 393, 198, 2, 309, 3620, 13, 198, 2, 198, 2, 5436, 524, 370, ...
2.219229
8,612
from dcstats.hedges import Hedges_d from dcstats.statistics_EJ import simple_stats as mean_SD import random import math ###tests
[ 6738, 30736, 34242, 13, 704, 3212, 1330, 30920, 3212, 62, 67, 198, 6738, 30736, 34242, 13, 14269, 3969, 62, 36, 41, 1330, 2829, 62, 34242, 355, 1612, 62, 10305, 198, 11748, 4738, 198, 11748, 10688, 198, 198, 21017, 41989, 628, 628 ]
3.243902
41
from django.urls import path from . import views urlpatterns = [ path('', views.Records, name ="fRec"), ]
[ 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, 6690, 3669, 11, 1438, 796, 1, 69, 6690, 12340, 198, 60 ]
2.75
40
import pytest from spacy.training.example import Example from spacy.util import make_tempdir from spacy import util from thinc.api import Config TRAIN_DATA = [ ("I'm so happy.", {"cats": {"POSITIVE": 1.0, "NEGATIVE": 0.0}}), ("I'm so angry", {"cats": {"POSITIVE": 0.0, "NEGATIVE": 1.0}}), ] cfg_string = """ [nlp] lang = "en" pipeline = ["transformer","textcat"] [components] [components.textcat] factory = "textcat" [components.textcat.model] @architectures = "spacy.TextCatEnsemble.v2" [components.textcat.model.tok2vec] @architectures = "spacy-transformers.TransformerListener.v1" grad_factor = 1.0 [components.textcat.model.tok2vec.pooling] @layers = "reduce_mean.v1" [components.transformer] factory = "transformer" """ # Xfail this until the new spaCy rc is up.
[ 11748, 12972, 9288, 198, 6738, 599, 1590, 13, 34409, 13, 20688, 1330, 17934, 198, 6738, 599, 1590, 13, 22602, 1330, 787, 62, 29510, 15908, 198, 6738, 599, 1590, 1330, 7736, 198, 6738, 294, 1939, 13, 15042, 1330, 17056, 628, 198, 51, 3...
2.469565
345
import asyncio from ..core.common.io import input from .action_creator import ActionCreator
[ 11748, 30351, 952, 198, 198, 6738, 11485, 7295, 13, 11321, 13, 952, 1330, 5128, 198, 6738, 764, 2673, 62, 45382, 1330, 7561, 16719, 273, 628 ]
3.76
25
"""Trainining script for seq2seq text-to-speech synthesis model. usage: train.py [options] options: --data-root=<dir> Directory contains preprocessed features. --checkpoint-dir=<dir> Directory where to save model checkpoints [default: checkpoints]. --hparams=<parmas> Hyper parameters [default: ]. --checkpoint=<path> Restore model from checkpoint path if given. --checkpoint-seq2seq=<path> Restore seq2seq model from checkpoint path. --checkpoint-postnet=<path> Restore postnet model from checkpoint path. --train-seq2seq-only Train only seq2seq model. --train-postnet-only Train only postnet model. --restore-parts=<path> Restore part of the model. --log-event-path=<name> Log event path. --reset-optimizer Reset optimizer. --load-embedding=<path> Load embedding from checkpoint. --speaker-id=<N> Use specific speaker of data in case for multi-speaker datasets. -h, --help Show this help message and exit """ from docopt import docopt import sys from os.path import dirname, join from tqdm import tqdm, trange from datetime import datetime # The deepvoice3 model from dv3.deepvoice3_pytorch import frontend, builder import dv3.audio import dv3.lrschedule import torch from torch.utils import data as data_utils from torch.autograd import Variable from torch import nn from torch import optim import torch.backends.cudnn as cudnn from torch.utils import data as data_utils from torch.utils.data.sampler import Sampler import numpy as np from numba import jit from nnmnkwii.datasets import FileSourceDataset, FileDataSource from os.path import join, expanduser import random import librosa.display from matplotlib import pyplot as plt import sys import os from tensorboardX import SummaryWriter from matplotlib import cm from warnings import warn from dv3.hparams import hparams, hparams_debug_string fs = hparams.sample_rate global_step = 0 global_epoch = 0 use_cuda = torch.cuda.is_available() if use_cuda: cudnn.benchmark = False _frontend = None # to be set later def sequence_mask(sequence_length, max_len=None): if max_len is None: max_len = sequence_length.data.max() batch_size = sequence_length.size(0) seq_range = torch.arange(0, max_len).long() seq_range_expand = seq_range.unsqueeze(0).expand(batch_size, max_len) seq_range_expand = Variable(seq_range_expand) if sequence_length.is_cuda: seq_range_expand = seq_range_expand.cuda() seq_length_expand = sequence_length.unsqueeze(1) \ .expand_as(seq_range_expand) return (seq_range_expand < seq_length_expand).float() def collate_fn(batch): """Create batch""" r = hparams.outputs_per_step downsample_step = hparams.downsample_step multi_speaker = len(batch[0]) == 4 # Lengths input_lengths = [len(x[0]) for x in batch] max_input_len = max(input_lengths) target_lengths = [len(x[1]) for x in batch] max_target_len = max(target_lengths) if max_target_len % r != 0: max_target_len += r - max_target_len % r assert max_target_len % r == 0 if max_target_len % downsample_step != 0: max_target_len += downsample_step - max_target_len % downsample_step assert max_target_len % downsample_step == 0 # Set 0 for zero beginning padding # imitates initial decoder states b_pad = r max_target_len += b_pad * downsample_step a = np.array([_pad(x[0], max_input_len) for x in batch], dtype=np.int) x_batch = torch.LongTensor(a) input_lengths = torch.LongTensor(input_lengths) target_lengths = torch.LongTensor(target_lengths) b = np.array([_pad_2d(x[1], max_target_len, b_pad=b_pad) for x in batch], dtype=np.float32) mel_batch = torch.FloatTensor(b) c = np.array([_pad_2d(x[2], max_target_len, b_pad=b_pad) for x in batch], dtype=np.float32) y_batch = torch.FloatTensor(c) # text positions text_positions = np.array([_pad(np.arange(1, len(x[0]) + 1), max_input_len) for x in batch], dtype=np.int) text_positions = torch.LongTensor(text_positions) max_decoder_target_len = max_target_len // r // downsample_step # frame positions s, e = 1, max_decoder_target_len + 1 # if b_pad > 0: # s, e = s - 1, e - 1 frame_positions = torch.arange(s, e).long().unsqueeze(0).expand( len(batch), max_decoder_target_len) # done flags done = np.array([_pad(np.zeros(len(x[1]) // r // downsample_step - 1), max_decoder_target_len, constant_values=1) for x in batch]) done = torch.FloatTensor(done).unsqueeze(-1) if multi_speaker: speaker_ids = torch.LongTensor([x[3] for x in batch]) else: speaker_ids = None return x_batch, input_lengths, mel_batch, y_batch, \ (text_positions, frame_positions), done, target_lengths, speaker_ids # https://discuss.pytorch.org/t/how-to-load-part-of-pre-trained-model/1113/3 if __name__ == "__main__": args = docopt(__doc__) print("Command line args:\n", args) checkpoint_dir = args["--checkpoint-dir"] checkpoint_path = args["--checkpoint"] checkpoint_seq2seq_path = args["--checkpoint-seq2seq"] checkpoint_postnet_path = args["--checkpoint-postnet"] load_embedding = args["--load-embedding"] checkpoint_restore_parts = args["--restore-parts"] speaker_id = args["--speaker-id"] speaker_id = int(speaker_id) if speaker_id is not None else None data_root = args["--data-root"] if data_root is None: data_root = join(dirname(__file__), "data", "ljspeech") log_event_path = args["--log-event-path"] reset_optimizer = args["--reset-optimizer"] # Which model to be trained train_seq2seq = args["--train-seq2seq-only"] train_postnet = args["--train-postnet-only"] # train both if not specified if not train_seq2seq and not train_postnet: print("Training whole model") train_seq2seq, train_postnet = True, True if train_seq2seq: print("Training seq2seq model") elif train_postnet: print("Training postnet model") else: assert False, "must be specified wrong args" # Override hyper parameters hparams.parse(args["--hparams"]) print(hparams_debug_string()) assert hparams.name == "deepvoice3" # Presets if hparams.preset is not None and hparams.preset != "": preset = hparams.presets[hparams.preset] import json hparams.parse_json(json.dumps(preset)) print("Override hyper parameters with preset \"{}\": {}".format( hparams.preset, json.dumps(preset, indent=4))) _frontend = getattr(frontend, hparams.frontend) os.makedirs(checkpoint_dir, exist_ok=True) # Input dataset definitions X = FileSourceDataset(TextDataSource(data_root, speaker_id)) Mel = FileSourceDataset(MelSpecDataSource(data_root, speaker_id)) Y = FileSourceDataset(LinearSpecDataSource(data_root, speaker_id)) # Prepare sampler frame_lengths = Mel.file_data_source.frame_lengths sampler = PartialyRandomizedSimilarTimeLengthSampler( frame_lengths, batch_size=hparams.batch_size) # Dataset and Dataloader setup dataset = PyTorchDataset(X, Mel, Y) data_loader = data_utils.DataLoader( dataset, batch_size=hparams.batch_size, num_workers=hparams.num_workers, sampler=sampler, collate_fn=collate_fn, pin_memory=hparams.pin_memory) print("dataloader_prepared") # Model model = build_model() if use_cuda: model = model.cuda() optimizer = optim.Adam(model.get_trainable_parameters(), lr=hparams.initial_learning_rate, betas=( hparams.adam_beta1, hparams.adam_beta2), eps=hparams.adam_eps, weight_decay=hparams.weight_decay) if checkpoint_restore_parts is not None: restore_parts(checkpoint_restore_parts, model) # Load checkpoints if checkpoint_postnet_path is not None: load_checkpoint(checkpoint_postnet_path, model.postnet, optimizer, reset_optimizer) if checkpoint_seq2seq_path is not None: load_checkpoint(checkpoint_seq2seq_path, model.seq2seq, optimizer, reset_optimizer) if checkpoint_path is not None: load_checkpoint(checkpoint_path, model, optimizer, reset_optimizer) # Load embedding if load_embedding is not None: print("Loading embedding from {}".format(load_embedding)) _load_embedding(load_embedding, model) # Setup summary writer for tensorboard if log_event_path is None: log_event_path = "log/run-test" + str(datetime.now()).replace(" ", "_") print("Los event path: {}".format(log_event_path)) writer = SummaryWriter(log_dir=log_event_path) # Train! try: train(model, data_loader, optimizer, writer, init_lr=hparams.initial_learning_rate, checkpoint_dir=checkpoint_dir, checkpoint_interval=hparams.checkpoint_interval, nepochs=hparams.nepochs, clip_thresh=hparams.clip_thresh, train_seq2seq=train_seq2seq, train_postnet=train_postnet) except KeyboardInterrupt: save_checkpoint( model, optimizer, global_step, checkpoint_dir, global_epoch, train_seq2seq, train_postnet) print("Finished") sys.exit(0)
[ 37811, 44077, 3191, 4226, 329, 33756, 17, 41068, 2420, 12, 1462, 12, 45862, 21263, 2746, 13, 198, 198, 26060, 25, 4512, 13, 9078, 685, 25811, 60, 198, 198, 25811, 25, 198, 220, 220, 220, 1377, 7890, 12, 15763, 28, 27, 15908, 29, 220...
2.453939
3,897
#! /usr/bin/python2 import time start = time.time() import pygame, numpy import pygame.camera # Init display screen = pygame.display.set_mode((0,0), pygame.FULLSCREEN) pygame.display.set_caption("Magic Mirror") #pygame.mouse.set_visible(False) # Init font pygame.font.init() font_colour = 16, 117, 186 fonts = {40: pygame.font.Font("Futura.ttc", 40)} # Init AI import recognition import sys, os index = recognition.MultiBinaryTree() imgdir = sys.argv[1] if len(sys.argv) > 1 else "images" photo_samples = [] screen.blit(write("Loading index... %fs" % (time.time() - start)), (0,0)) pygame.display.flip() with open(os.path.join(imgdir, "index.tsv")) as f: for line in f: line = line.strip().split("\t") img = os.path.join(imgdir, line[0]) description = numpy.array([float(n) for n in line[1:]]) index.insert(description, img) screen.blit(write("Loading images... %fs" % (time.time() - start)), (0,50)) pygame.display.flip() for img in os.listdir(os.path.join(imgdir, "thumbnails")): photo_samples.append(pygame.image.load(os.path.join(imgdir, "thumbnails", img))) # Init clock clock = pygame.time.Clock() # Init camera pygame.camera.init() cameras = pygame.camera.list_cameras() if not cameras: pygame.quit() print "No cameras found, exiting!" sys.exit(1) camera = pygame.camera.Camera(cameras[0]) camera.start() # Mainloop if __name__ == "__main__": main()
[ 2, 0, 1220, 14629, 14, 8800, 14, 29412, 17, 198, 11748, 640, 198, 9688, 796, 640, 13, 2435, 3419, 198, 198, 11748, 12972, 6057, 11, 299, 32152, 198, 11748, 12972, 6057, 13, 25695, 198, 198, 2, 44707, 3359, 198, 9612, 796, 12972, 605...
2.516755
567
""".. Ignore pydocstyle D400. ======= Resolwe ======= Open source enterprise dataflow engine in Django. """ from resolwe.__about__ import ( # noqa: F401 __author__, __copyright__, __email__, __license__, __summary__, __title__, __url__, __version__, )
[ 37811, 492, 41032, 279, 5173, 420, 7635, 360, 7029, 13, 198, 198, 1421, 18604, 198, 4965, 349, 732, 198, 1421, 18604, 198, 198, 11505, 2723, 13953, 1366, 11125, 3113, 287, 37770, 13, 198, 198, 37811, 198, 6738, 581, 349, 732, 13, 834,...
2.380165
121
# %% [markdown] # # Testing python-som with audio dataset # %% [markdown] # # Imports # %% import matplotlib.pyplot as plt # import librosa as lr # import librosa.display as lrdisp import numpy as np import pandas as pd import pickle import seaborn as sns import sklearn.preprocessing from python_som import SOM FILE_PREFIX = 'som64_u_grupo1' # %% [markdown] # # Loading dataset # %% df = pd.read_csv('features_means.csv', index_col=0, verbose=True) df.index = pd.to_datetime(df.index) df['rac'] = False df.loc['2020-09-22':, 'rac'] = True # type: ignore df.sort_index(inplace=True) # %% [markdown] # ## Checking for and dropping duplicates # %% # Resetting index for duplicate analysis df.reset_index(inplace=True) print("Duplicates by filename:", df.duplicated(subset=['file_name']).value_counts(), sep='\n') df.drop_duplicates(subset=['file_name'], inplace=True) print("Duplicates by (datetime, ala, grupo):", df.duplicated(subset=['datetime', 'ala', 'grupo']).value_counts(), sep='\n') df.drop_duplicates(subset=['datetime', 'ala', 'grupo'], inplace=True) # Rebuilding dataframe index df.set_index('datetime', inplace=True) # %% # Filtering dataset by 'group' df = df[df['grupo'] == 1] # %% # Dropping tail of dataset for class balancing # tail_size = abs( # len(df[df['rac'].astype(int) == 1]) - len(df[df['rac'].astype(int) == 0])) # df.drop(df.tail(tail_size).index, inplace=True) # %% [markdown] # ## Visualizing distribution of sample dates # %% df_tmp = pd.DataFrame(df['file_name'].resample('1D').count()) df_tmp['count'] = df_tmp['file_name'] del df_tmp['file_name'] df_tmp['rac'] = False df_tmp.loc['2020-09-22':, 'rac'] = True # type: ignore plt.figure(figsize=(10, 10)) sns.set(style="whitegrid", palette=sns.color_palette("muted", n_colors=6, desat=1.0)) sns.barplot(y=df_tmp.index, x=df_tmp['count'], hue=df_tmp['rac']) plt.draw() df_tmp = pd.DataFrame(df['file_name'].resample('1H').count()) df_tmp['count'] = df_tmp['file_name'] del df_tmp['file_name'] df_tmp['rac'] = False df_tmp.loc['2020-09-22':, 'rac'] = True # type: ignore df_tmp = df_tmp.reset_index() df_tmp['hour'] = df_tmp['datetime'].dt.hour plt.figure(figsize=(10, 10)) sns.set(style="whitegrid", palette=sns.color_palette("muted", n_colors=6, desat=1.0)) sns.barplot(y=df_tmp['hour'], x=df_tmp['count'], hue=df_tmp['rac'], orient='h') plt.draw() # %% df_melt = pd.melt(df, value_vars=['rac'], value_name='ractopamine') plt.figure(figsize=(10, 10)) sns.set(style="whitegrid", palette=sns.color_palette("muted", n_colors=6, desat=1.0)) ax = sns.countplot(data=df_melt, x='ractopamine', hue='ractopamine') for p in ax.patches: ax.annotate(f'\n{p.get_height()}', (p.get_x() + 0.2, p.get_height()), ha='center', va='top', color='white', size=18) plt.draw() # %% # using sklearn's MinMaxScaler scaler = sklearn.preprocessing.MinMaxScaler(feature_range=(0, 1)) df_train = df.iloc[:, 3:-1].copy() df_train = scaler.fit_transform(df_train) # %% # Defining first element of SOM shape # Second element will be assigned based on the ratio between the # first two principal components of the train dataset som_x: int = 64 try: with open(f'./{FILE_PREFIX}.obj', 'rb') as f: som = pickle.load(f) except FileNotFoundError: som = SOM(x=som_x, y=None, input_len=df_train.shape[1], learning_rate=0.5, neighborhood_radius=1.0, neighborhood_function='gaussian', cyclic_x=True, cyclic_y=True, data=df_train) # Training SOM som.weight_initialization(mode='linear', data=df_train) som.train(data=df_train, mode='random', verbose=True) with open(f'./{FILE_PREFIX}.obj', 'wb') as f: pickle.dump(som, f) # %% som_x, som_y = som.get_shape() print('SOM shape:', (som_x, som_y)) # %% # Visualizing distance matrix and activation matrix umatrix = som.distance_matrix() fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(16, 9)) sns.heatmap(umatrix.T, cmap='bone_r', ax=ax1, robust=True) sns.heatmap(som.activation_matrix(data=df_train).T, cmap='mako', ax=ax2, robust=True) ax1.invert_yaxis() ax2.invert_yaxis() fig.savefig(f'./output_{FILE_PREFIX}/{FILE_PREFIX}_umatrix_activation.png', bbox_inches='tight', transparent=True) plt.draw() # %% # Visualizing distance matrix anc activation matrix separately fig = plt.figure(figsize=(16, 9)) ax = sns.heatmap(umatrix.T, cmap='bone_r', robust=True) ax.invert_yaxis() fig.savefig(f'./output_{FILE_PREFIX}/{FILE_PREFIX}_umatrix.png', bbox_inches='tight', transparent=True) fig = plt.figure(figsize=(16, 9)) ax = sns.heatmap(som.activation_matrix(data=df_train).T, cmap='mako', robust=True) ax.invert_yaxis() fig.savefig(f'./output_{FILE_PREFIX}/{FILE_PREFIX}_activation_matrix.png', bbox_inches='tight', transparent=True) # %% [markdown] # ## Visualizing distribution of features # %% for column in df.iloc[:, 3:-1].columns: hmap = som.get_weights()[:, :, df.iloc[:, 3:-1].columns.get_loc(column)].T fig = plt.figure(figsize=(16, 9)) ax = sns.heatmap(hmap, robust=True, cmap='BrBG') ax.invert_yaxis() fig.savefig(f'./output_{FILE_PREFIX}/{FILE_PREFIX}_{column}.png', bbox_inches='tight', transparent=True) plt.close(fig=fig) # %% [markdown] # ## Visualizing distribution of audios by metadata (day, hour, ...) # Each node is colorized according to its most frequent label # %% df['days'] = df.index.date df['days'] = (df['days'] - df['days'][0]) df['days'] = df['days'].apply(lambda x: x.days) df['hour'] = df.index.hour # %% # Visualizing 'rac' distribution class_assignments = som.label_map(np.array(df_train), np.array(df['rac'])) hmap = np.zeros((som_x, som_y)) for i, j in sorted(class_assignments.keys()): try: hmap[i][j] = class_assignments[(i, j)].most_common()[0][0] + 1 except Exception: continue hmap = hmap.T fig = plt.figure(figsize=(16, 9)) ax = sns.heatmap(hmap, cmap=sns.color_palette(palette=["#000000", "blue", "orange"], n_colors=3), cbar_kws={'ticks': [0, 1, 2]}) ax.invert_yaxis() fig.savefig(f'./output_{FILE_PREFIX}/{FILE_PREFIX}_rac.png', bbox_inches='tight', transparent=True) plt.show() # %% # Visualizing by 'grupo' print(df.groupby('grupo')['rac'].count()) column = 'grupo' class_assignments = som.label_map(np.array(df_train), np.array(df[column])) hmap = np.zeros((som_x, som_y)) for i, j in sorted(class_assignments.keys()): try: hmap[i][j] = class_assignments[(i, j)].most_common()[0][0] except Exception: hmap[i][j] = 0 hmap = hmap.T fig = plt.figure(figsize=(16, 9)) ax = sns.heatmap(hmap, cmap=sns.color_palette(palette=["#000000", "blue", "orange"], n_colors=3), cbar_kws={'ticks': [0, 1, 2]}) ax.invert_yaxis() fig.savefig(f'./output_{FILE_PREFIX}/{FILE_PREFIX}_{column}.png', bbox_inches='tight', transparent=True) plt.show() # %% # Visualizing by 'days' print(df.groupby('days')['rac'].count()) column = 'days' class_assignments = som.label_map(np.array(df_train), np.array(df[column])) hmap = np.zeros((som_x, som_y)) for i, j in sorted(class_assignments.keys()): try: hmap[i][j] = class_assignments[(i, j)].most_common()[0][0] except Exception: hmap[i][j] = -1 hmap = hmap.T fig = plt.figure(figsize=(16, 9)) ax = sns.heatmap(hmap, cmap='viridis') ax.invert_yaxis() fig.savefig(f'./output_{FILE_PREFIX}/{FILE_PREFIX}_{column}.png', bbox_inches='tight', transparent=True) plt.show() # %% # Visualizing by 'hour' print(df.groupby('hour')['rac'].count()) column = 'hour' class_assignments = som.label_map(np.array(df_train), np.array(df[column])) hmap = np.zeros((som_x, som_y)) for i, j in sorted(class_assignments.keys()): try: hmap[i][j] = class_assignments[(i, j)].most_common()[0][0] except Exception: hmap[i][j] = -1 hmap = hmap.T fig = plt.figure(figsize=(16, 9)) ax = sns.heatmap(hmap, cmap=sns.diverging_palette(150, 250, s=100, l=20, sep=1, n=26, center='light'), center=12) ax.invert_yaxis() fig.savefig(f'./output_{FILE_PREFIX}/{FILE_PREFIX}_{column}.png', bbox_inches='tight', transparent=True) plt.show() # %%
[ 2, 43313, 685, 4102, 2902, 60, 198, 2, 1303, 23983, 21015, 12, 82, 296, 351, 6597, 27039, 198, 198, 2, 43313, 685, 4102, 2902, 60, 198, 2, 1303, 1846, 3742, 198, 198, 2, 43313, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, ...
2.073159
4,292
"""Prediction Engine - Update the data model with the most resent fixtures and results.""" from footy.domain import Competition
[ 37811, 39156, 2867, 7117, 532, 10133, 262, 1366, 2746, 351, 262, 749, 20315, 34609, 290, 2482, 526, 15931, 198, 198, 6738, 2366, 88, 13, 27830, 1330, 27348, 628 ]
4.642857
28
"""Script to embed pydeck examples into .rst pages with code These populate the files you see once you click into a grid cell on the pydeck gallery page """ from multiprocessing import Pool import os import subprocess import sys from const import DECKGL_URL_BASE, EXAMPLE_GLOB, GALLERY_DIR, HTML_DIR, HOSTED_STATIC_PATH from utils import to_presentation_name, to_snake_case_string from templates import DOC_TEMPLATE if not os.environ.get("MAPBOX_API_KEY"): # If running for rtfd.io, set this variable from the Admin panel raise Exception("MAPBOX_API_KEY not set") if __name__ == "__main__": main()
[ 37811, 7391, 284, 11525, 12972, 35875, 6096, 656, 764, 81, 301, 5468, 351, 2438, 198, 198, 4711, 48040, 262, 3696, 345, 766, 1752, 345, 3904, 656, 257, 10706, 2685, 198, 261, 262, 12972, 35875, 15604, 2443, 198, 37811, 198, 6738, 18540,...
3.064356
202
import numpy as np import sympy as sp import re import os ###################### # # # 17 16 21 # # 18 15 22 # # 19 14 23 # # 20 01 24 # # 02 08 # # 03 09 # # 04 10 # # 05 11 # # 06 12 # # 07 13 # # # ###################### # # origin: in the waist, middle point between the two pitch hip rotations # inertial frame: located at the origin (waist), but aligned with the ground (info from IMU) # # Di : position vector from the anchor point of the previous body to the current body i # (previous body is not always body i-1), expressed in the relative # frame of the previous body # DGi : position vector from the anchor point of body i to its COM (center of mass) G_i, # expressed in the relative frame of the current body i # Omi : rotational vector from the previous body to the current body i # (previous body is not always body i-1), expressed in the relative # frame of the previous body # Rdi : rotational matrix between body i and its predecessor # si : sine of the relative angle before body i # ci : cosine of the relative angle before body i # # xi : absolute position vector (from origin, expressed in the inertial frame) # of the anchor point of body i # xgi : absolute position vector of the COM G_i of body i # xpi : derivative of xi # xgpi : derivative of xgi # omi : absolute rotational vector of body i # Ri : absolute rotational matrix # Rti : transpose matrix of Ri # xji : jacobian of 'xi' # xgji : jacobian of 'xgi' # Rji : jacobian of 'Ri' # return true if it is a float # return true if it has a shape 'R%a_%b%c' (indexes %a, %b, %c also returned) # return true if it has a shape 'x%a_%b' (indexes %a, %b also returned) # count the number of 'elem' in the file # print the declaration of an element # print all declarations # get tilde matrix # get rotation matrix # get vector axis # compute the derivative of an element (for jacobian) # compute the derivative of an expression (for jacobian) # write the beginning of the file # compute the center of mass position and velocity # from an orientation matrix, compute the roll, pitch, yaw angles (and derivative) # compute the time derivatives of 'yaw_pitch_roll_angles' # angles (position and derivative) of the waist and the torso # compute the feet position, velocity and orientation # compute the wrists position, velocity and orientation # get a string for the enumeration of joints # write the end of the file # print matrix components declaration # print variables declaration # variables initialization # write symbolic vector and replace symbolic variable by its name # write symbolic matrix and replace symbolic variable by its name # save the symbolic vector for print # save the symbolic matrix for print # write symbolic jacobian of a rotation matrix # write symbolic jacobian of an anchor point # write symbolic jacobian of a com point # symbolic computation # generate the symbolic output file # main script # rotation axis for each joint before body i (1:x, 2:y, 3:z) rot_axis = np.array([0, # waist 2, 1, 3, 2, 1, 2, # right leg 2, 1, 3, 2, 1, 2, # left leg 1, 2, 3, # trunk 2, 1, 3, 2, # right arm 2, 1, 3, 2 # left arm ]) # parent index parent_body_index = np.array([ -1, # waist 0, 1, 2, 3, 4, 5, # right leg 0, 7, 8, 9, 10, 11, # left leg 0, 13, 14, # trunk 15, 16, 17, 18, # right arm 15, 20, 21, 22 # left arm ]) nb_bodies = len(parent_body_index) ## anchor point positions Dpt = nb_bodies*[None] # waist Dpt[0] = sp.Matrix([0.0, 0.0, 0.0]) # right leg Dpt[1] = sp.Matrix([0.0, sp.Symbol('DPT_2_2'), 0.0]) Dpt[2] = sp.Matrix([0.0, sp.Symbol('DPT_2_6'), 0.0]) Dpt[3] = sp.Matrix([0.0, 0.0, sp.Symbol('DPT_3_8')]) Dpt[4] = sp.Matrix([0.0, 0.0, sp.Symbol('DPT_3_10')]) Dpt[5] = sp.Matrix([0.0, 0.0, sp.Symbol('DPT_3_12')]) Dpt[6] = sp.Matrix([0.0, 0.0, 0.0]) # left leg Dpt[7] = sp.Matrix([0.0, sp.Symbol('DPT_2_3'), 0.0]) Dpt[8] = sp.Matrix([0.0, sp.Symbol('DPT_2_18'), 0.0]) Dpt[9] = sp.Matrix([0.0, 0.0, sp.Symbol('DPT_3_20')]) Dpt[10] = sp.Matrix([0.0, 0.0, sp.Symbol('DPT_3_22')]) Dpt[11] = sp.Matrix([0.0, 0.0, sp.Symbol('DPT_3_24')]) Dpt[12] = sp.Matrix([0.0, 0.0, 0.0]) # trunk Dpt[13] = sp.Matrix([sp.Symbol('DPT_1_4'), 0.0, sp.Symbol('DPT_3_4')]) Dpt[14] = sp.Matrix([0.0, 0.0, 0.0]) Dpt[15] = sp.Matrix([0.0, 0.0, sp.Symbol('DPT_3_32')]) # right arm Dpt[16] = sp.Matrix([sp.Symbol('DPT_1_36'), sp.Symbol('DPT_2_36'), sp.Symbol('DPT_3_36')]) Dpt[17] = sp.Matrix([0.0, sp.Symbol('DPT_2_39'), 0.0]) Dpt[18] = sp.Matrix([0.0, 0.0, sp.Symbol('DPT_3_41')]) Dpt[19] = sp.Matrix([0.0, 0.0, sp.Symbol('DPT_3_43')]) # left arm Dpt[20] = sp.Matrix([sp.Symbol('DPT_1_37'), sp.Symbol('DPT_2_37'), sp.Symbol('DPT_3_37')]) Dpt[21] = sp.Matrix([0.0, sp.Symbol('DPT_2_46'), 0.0]) Dpt[22] = sp.Matrix([0.0, 0.0, sp.Symbol('DPT_3_48')]) Dpt[23] = sp.Matrix([0.0, 0.0, sp.Symbol('DPT_3_50')]) ## COM positions Dg = nb_bodies*[None] # waist Dg[0] = sp.Matrix([sp.Symbol('L_1_6'), sp.Symbol('L_2_6'), sp.Symbol('L_3_6')]) # right leg Dg[1] = sp.Matrix([sp.Symbol('L_1_7') , sp.Symbol('L_2_7') , sp.Symbol('L_3_7')]) Dg[2] = sp.Matrix([sp.Symbol('L_1_8') , sp.Symbol('L_2_8') , sp.Symbol('L_3_8')]) Dg[3] = sp.Matrix([sp.Symbol('L_1_9') , sp.Symbol('L_2_9') , sp.Symbol('L_3_9')]) Dg[4] = sp.Matrix([sp.Symbol('L_1_10'), sp.Symbol('L_2_10'), sp.Symbol('L_3_10')]) Dg[5] = sp.Matrix([sp.Symbol('L_1_11'), sp.Symbol('L_2_11'), sp.Symbol('L_3_11')]) Dg[6] = sp.Matrix([sp.Symbol('L_1_12'), 0.0 , sp.Symbol('L_3_12')]) # left leg Dg[7] = sp.Matrix([sp.Symbol('L_1_13'), sp.Symbol('L_2_13'), sp.Symbol('L_3_13')]) Dg[8] = sp.Matrix([sp.Symbol('L_1_14'), sp.Symbol('L_2_14'), sp.Symbol('L_3_14')]) Dg[9] = sp.Matrix([sp.Symbol('L_1_15'), sp.Symbol('L_2_15'), sp.Symbol('L_3_15')]) Dg[10] = sp.Matrix([sp.Symbol('L_1_16'), sp.Symbol('L_2_16'), sp.Symbol('L_3_16')]) Dg[11] = sp.Matrix([sp.Symbol('L_1_17'), sp.Symbol('L_2_17'), sp.Symbol('L_3_17')]) Dg[12] = sp.Matrix([sp.Symbol('L_1_18'), 0.0 , sp.Symbol('L_3_18')]) # trunk Dg[13] = sp.Matrix([sp.Symbol('L_1_19'), sp.Symbol('L_2_19'), sp.Symbol('L_3_19')]) Dg[14] = sp.Matrix([sp.Symbol('L_1_20'), sp.Symbol('L_2_20'), sp.Symbol('L_3_20')]) Dg[15] = sp.Matrix([sp.Symbol('L_1_21'), sp.Symbol('L_2_21'), sp.Symbol('L_3_21')]) # right arm Dg[16] = sp.Matrix([sp.Symbol('L_1_22'), sp.Symbol('L_2_22'), sp.Symbol('L_3_22')]) Dg[17] = sp.Matrix([sp.Symbol('L_1_23'), sp.Symbol('L_2_23'), sp.Symbol('L_3_23')]) Dg[18] = sp.Matrix([sp.Symbol('L_1_24'), sp.Symbol('L_2_24'), sp.Symbol('L_3_24')]) Dg[19] = sp.Matrix([sp.Symbol('L_1_25'), sp.Symbol('L_2_25'), sp.Symbol('L_3_25')]) # left arm Dg[20] = sp.Matrix([sp.Symbol('L_1_26'), sp.Symbol('L_2_26'), sp.Symbol('L_3_26')]) Dg[21] = sp.Matrix([sp.Symbol('L_1_27'), sp.Symbol('L_2_27'), sp.Symbol('L_3_27')]) Dg[22] = sp.Matrix([sp.Symbol('L_1_28'), sp.Symbol('L_2_28'), sp.Symbol('L_3_28')]) Dg[23] = sp.Matrix([sp.Symbol('L_1_29'), sp.Symbol('L_2_29'), sp.Symbol('L_3_29')]) # masses M = np.array([ 'M_6', # waist 'M_7' , 'M_8' , 'M_9' , 'M_10', 'M_11', 'M_12', # right leg 'M_13', 'M_14', 'M_15', 'M_16', 'M_17', 'M_18', # left leg 'M_19', 'M_20', 'M_21', # trunk 'M_22', 'M_23', 'M_24', 'M_25', # right arm 'M_26', 'M_27', 'M_28', 'M_29' # left arm ]) # joint names joint_id_names = np.array(['0', # waist 'RightHipPitch_id', 'RightHipRoll_id', 'RightHipYaw_id', 'RightKneePitch_id', 'RightFootRoll_id', 'RightFootPitch_id', # right leg 'LeftHipPitch_id' , 'LeftHipRoll_id' , 'LeftHipYaw_id' , 'LeftKneePitch_id' , 'LeftFootRoll_id' , 'LeftFootPitch_id' , # left leg 'TorsoRoll_id' , 'TorsoPitch_id' , 'TorsoYaw_id' , # trunk 'RightShPitch_id' , 'RightShRoll_id' , 'RightShYaw_id' , 'RightElbPitch_id', # right arm 'LeftShPitch_id' , 'LeftShRoll_id' , 'LeftShYaw_id' , 'LeftElbPitch_id' # left arm ]) out_file_name = 'forward_kinematics' gen_symbolic_out(out_file_name, nb_bodies, rot_axis, parent_body_index, joint_id_names, Dpt, Dg, M)
[ 11748, 299, 32152, 355, 45941, 198, 11748, 10558, 88, 355, 599, 198, 11748, 302, 198, 11748, 28686, 198, 198, 14468, 4242, 2235, 198, 2, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, ...
2.156689
3,842
#!/usr/bin/env python # -*- coding: utf-8 -*- from pymisp import PyMISP from keys import misp_url, misp_key, misp_verifycert import argparse import os import json # Usage for pipe masters: ./last.py -l 5h | jq . if __name__ == '__main__': parser = argparse.ArgumentParser(description='Download latest events from a MISP instance.') parser.add_argument("-l", "--last", required=True, help="can be defined in days, hours, minutes (for example 5d or 12h or 30m).") parser.add_argument("-o", "--output", help="Output file") args = parser.parse_args() if args.output is not None and os.path.exists(args.output): print('Output file already exists, abord.') exit(0) misp = init(misp_url, misp_key) download_last(misp, args.last, args.output)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 6738, 279, 4948, 8802, 1330, 9485, 44, 1797, 47, 198, 6738, 8251, 1330, 2984, 79, 62, 6371, 11, 2984, 79, 62, ...
2.692833
293
from django.conf.urls import include, url from django.views.generic.base import TemplateView from . import views as core_views from .category.urls import urlpatterns as category_urls from .collection.urls import urlpatterns as collection_urls from .customer.urls import urlpatterns as customer_urls from .discount.urls import urlpatterns as discount_urls from .menu.urls import urlpatterns as menu_urls from .order.urls import urlpatterns as order_urls from .page.urls import urlpatterns as page_urls from .product.urls import urlpatterns as product_urls from .search.urls import urlpatterns as search_urls from .shipping.urls import urlpatterns as shipping_urls from .sites.urls import urlpatterns as site_urls from .staff.urls import urlpatterns as staff_urls from .taxes.urls import urlpatterns as taxes_urls # BEGIN :: SoftButterfly Extensions -------------------------------------------- from .brand.urls import urlpatterns as brand_urls from .widget.slider.urls import urlpatterns as slider_urls from .widget.banner.urls import urlpatterns as banner_urls from .widget.scene.urls import urlpatterns as scene_urls from .widget.benefit.urls import urlpatterns as benefit_urls from .store.physical_store.urls import urlpatterns as store_urls from .store.social_network.urls import urlpatterns as social_network_urls from .store.special_page.urls import urlpatterns as special_page_urls from .store.bank_account.urls import urlpatterns as bank_account_urls from .store.footer_item.urls import urlpatterns as footer_item_urls # END :: SoftButterfly Extensions ---------------------------------------------- urlpatterns = [ url(r'^$', core_views.index, name='index'), url(r'^categories/', include(category_urls)), url(r'^collections/', include(collection_urls)), url(r'^orders/', include(order_urls)), url(r'^page/', include(page_urls)), url(r'^products/', include(product_urls)), url(r'^customers/', include(customer_urls)), url(r'^staff/', include(staff_urls)), url(r'^discounts/', include(discount_urls)), url(r'^settings/', include( site_urls + social_network_urls + special_page_urls + bank_account_urls + footer_item_urls)), # Extensions url(r'^menu/', include(menu_urls)), url(r'^shipping/', include(shipping_urls)), url(r'^style-guide/', core_views.styleguide, name='styleguide'), url(r'^search/', include(search_urls)), url(r'^taxes/', include(taxes_urls)), url(r'^next/', TemplateView.as_view(template_name='dashboard/next.html')), # BEGIN :: SoftButterfly Extensions ---------------------------------------- url(r'^brand/', include(brand_urls)), url(r'^slider/', include(slider_urls)), url(r'^banner/', include(banner_urls)), url(r'^scene/', include(scene_urls)), url(r'^store/', include(store_urls)), url(r'^benefit/', include(benefit_urls)), # END :: SoftButterfly Extensions ------------------------------------------ ]
[ 6738, 42625, 14208, 13, 10414, 13, 6371, 82, 1330, 2291, 11, 19016, 198, 6738, 42625, 14208, 13, 33571, 13, 41357, 13, 8692, 1330, 37350, 7680, 198, 198, 6738, 764, 1330, 5009, 355, 4755, 62, 33571, 198, 6738, 764, 22872, 13, 6371, 82...
2.905419
1,015
import os import sys import torch import yaml from functools import partial sys.path.append('../../../../') from trainers import trainer, frn_train from datasets import dataloaders from models.FRN import FRN args = trainer.train_parser() with open('../../../../config.yml', 'r') as f: temp = yaml.safe_load(f) data_path = os.path.abspath(temp['data_path']) fewshot_path = os.path.join(data_path,'CUB_fewshot_raw') pm = trainer.Path_Manager(fewshot_path=fewshot_path,args=args) train_way = args.train_way shots = [args.train_shot, args.train_query_shot] train_loader = dataloaders.meta_train_dataloader(data_path=pm.train, way=train_way, shots=shots, transform_type=args.train_transform_type) model = FRN(way=train_way, shots=[args.train_shot, args.train_query_shot], resnet=args.resnet) train_func = partial(frn_train.default_train,train_loader=train_loader) tm = trainer.Train_Manager(args,path_manager=pm,train_func=train_func) tm.train(model) tm.evaluate(model)
[ 11748, 28686, 198, 11748, 25064, 198, 11748, 28034, 198, 11748, 331, 43695, 198, 6738, 1257, 310, 10141, 1330, 13027, 198, 17597, 13, 6978, 13, 33295, 10786, 40720, 40720, 40720, 40720, 11537, 198, 6738, 28514, 1330, 21997, 11, 1216, 77, ...
2.199616
521
import argparse import argparse import os import numpy as np import torch from dataloaders.LoaderBase import LoaderBase import exp.feature.feature_utils as feature_utils if __name__ == '__main__': args = parse_args() if 'other_ranks' in args.rank_func: args.rank_func.remove('other_ranks') args.rank_func += ['marginal_rank', 'rf_rank', 'zero_rank', 'shuffle_rank', 'random_rank', 'enet_rank', 'lasso_rank'] for mode in args.modes: run(mode, args)
[ 11748, 1822, 29572, 198, 11748, 1822, 29572, 198, 11748, 28686, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 28034, 198, 198, 6738, 4818, 282, 1170, 364, 13, 17401, 14881, 1330, 8778, 263, 14881, 198, 11748, 1033, 13, 30053, 13, ...
2.398148
216
from gym_pcgrl.envs.reps.representation3D import Representation3D from PIL import Image from gym import spaces import numpy as np from gym_pcgrl.envs.probs.minecraft.mc_render import reps_3D_render """ The wide representation where the agent can pick the tile position and tile value at each update. """
[ 6738, 11550, 62, 14751, 2164, 75, 13, 268, 14259, 13, 260, 862, 13, 15603, 341, 18, 35, 1330, 10858, 341, 18, 35, 198, 6738, 350, 4146, 1330, 7412, 198, 6738, 11550, 1330, 9029, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 11550, ...
3.388889
90
"""This module contains the general information for AdaptorMenloQStats ManagedObject.""" from ...ucsmo import ManagedObject from ...ucscoremeta import MoPropertyMeta, MoMeta from ...ucsmeta import VersionMeta
[ 37811, 1212, 8265, 4909, 262, 2276, 1321, 329, 30019, 273, 10418, 5439, 48, 29668, 1869, 1886, 10267, 526, 15931, 198, 198, 6738, 2644, 1229, 5796, 78, 1330, 1869, 1886, 10267, 198, 6738, 2644, 1229, 26675, 28961, 1330, 4270, 21746, 48526...
3.925926
54
import unittest import pytest from old_password import old_password import csv import re def test_password_with_space(): """ spaces in password are skipped """ assert old_password("pass word") == old_password("password") def test_password_with_tab(): """ tabs in password are skipped """ assert old_password("pass\tword") == old_password("password")
[ 11748, 555, 715, 395, 198, 11748, 12972, 9288, 198, 6738, 1468, 62, 28712, 1330, 1468, 62, 28712, 198, 198, 11748, 269, 21370, 198, 11748, 302, 628, 198, 198, 4299, 1332, 62, 28712, 62, 4480, 62, 13200, 33529, 198, 220, 220, 220, 3722...
3.07874
127
# -*- coding: utf-8 -*- """ ------------------------------------------------- Description : Author : cmy date 2020/1/2 ------------------------------------------------- """ import datetime import heapq import numpy as np import tensorflow as tf import time from metrics import ndcg_at_k from train import get_user_record from DMF import DMF import os os.environ["CUDA_VISIBLE_DEVICES"] = "1" config = tf.ConfigProto() config.gpu_options.per_process_gpu_memory_fraction = 0.5 # maximun alloc gpu50% of MEM config.gpu_options.allow_growth = True #allocate dynamically
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 47232, 12, 198, 220, 220, 12489, 1058, 198, 220, 220, 6434, 1058, 220, 220, 220, 220, 220, 220, 269, 1820, 198, 220, 220, 3128, 220, 220, 220, 220, 220, ...
3.098958
192
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Aug 28 19:28:17 2019 @author: Wanling Song """ import mdtraj as md import numpy as np import pandas as pd import argparse import sys from collections import defaultdict import pickle import os import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import networkx as nx import seaborn as sns from matplotlib.ticker import MultipleLocator from scipy.optimize import curve_fit from scipy.sparse import coo_matrix from scipy import sparse from statsmodels.nonparametric.kernel_density import KDEMultivariate import community import warnings from shutil import copyfile import datetime from itertools import product import logomaker import re warnings.simplefilter(action='ignore', category=FutureWarning) warnings.filterwarnings('ignore') np.seterr(all='ignore') ################################### ###### Parameter settings ####### ################################### parser = argparse.ArgumentParser() parser.add_argument("-f", nargs="+", metavar="./run/md.xtc", help="List of trajectories, seperated by space, \ Supports xtc, gro format. Used by mdtraj.load()") parser.add_argument("-c", nargs="+", metavar="./run/system.gro", \ help="List of coordinates of trajectory, in the same order as -f, required when inputs of -f are xtc trajectories, \ Supported format: gro, pdb, etc., Used by mdtraj.load()") parser.add_argument("-stride", default=1, metavar=1, help="Striding through trajectories. Only every stride-th will be analized." ) parser.add_argument("-dt", default=None, metavar="None", help="The time interval between two adjacent frames in the trajectories. \ If not specified, the mdtraj will deduce from the trajectories. This works for trajectories in format of e.g. xtc which \ include timestep information. For trajectories in dcd format, users have to provide the time interval manually, \ in a time unite consistent with -tu") parser.add_argument("-tu", default="us", choices=["ns", "us"], metavar="us", \ help="Time unit for interaction duration calculation. Available options: ns, us. This will affect the unit of koff as well.") parser.add_argument("-save_dir", default=None, metavar="None", help="The directory where all the generated results will be put in. \ The directory will be created if not existing. Using the current working directory if not specified.") parser.add_argument("-cutoffs", nargs=2, default=(0.55, 1.0), metavar=(0.55, 1.0), \ help="Double cutoff seperated by space. In unit of nm. Default is 0.55 1.0. The double cutoffs are used to define lipid \ interactions. A continuous lipid contact with a given residue starts when the lipid moves to the given residue \ closer than the smaller cutoff; and ends when the lipid moves farther than the larger cutoff. The standard single \ cutoff can be acheived by setting the same value for both cutoffs.") parser.add_argument("-lipids", nargs="+", metavar="POPC", default="POPC CHOL POP2", \ help="Lipid species to check, seperated by space. Should be consistent with residue names in your trajectories.") parser.add_argument("-lipid_atoms", nargs="+", metavar="PO4", default=None, \ help="Lipid atoms to check, seperated by space. Should be consistent with the atom names in your trajectories.") parser.add_argument("-radii", nargs="+", default=None, metavar="BB:0.26 SC1:0.23", help="Change/Define the radius of atoms/beads \ that is used for the calculation of binding site surface area. Values need to be in the unit of nm. Supported syntax is \ BB:0.26, which defines the radius of bead BB as 0.26 nm, or CA:0.12 which defines the radius of atom CA as 0.12 nm. For \ atomistic simulations, the default radii are taken from \ mdtraj https://github.com/mdtraj/mdtraj/blob/master/mdtraj/geometry/sasa.py#L56. For coarse-grained \ simulations, this script defines the radius of the MARTINI 2 beads of BB as 0.26 nm and SC1/2/3 as 0.23 nm.") parser.add_argument("-nprot", default=1, metavar="1", \ help="num. of proteins (or chains) in the simulation system. The calculated results will be averaged among these proteins \ (or chains). The proteins (or chains) need to be identical, otherwise the averaging will fail.") parser.add_argument("-resi_offset", default=0, metavar="0", help="Shifting the residue index. It is useful if you need to change the residue \ index in your trajectories. For example, to change the residue indeces from 5,6,7,..., to 10,11,12,..., use -resi_offset 4. \ All the outputs, including plotted figures and saved coordinates, will be changed by this.") parser.add_argument("-resi_list", nargs="+", default=[], metavar="1-10 20-30", help="The indices of residues on which the calculations are done. \ This option is useful for those proteins with large regions that don't require calculation. Skipping those calculations could \ save time and memory. Accepted syntax include 1/ defining a range, like 1-10 (both ends included); 2/ single residue index, \ like 25 26 17. All the selections are seperated by space. For example, -resi_list 1-10 20-30 40 45 46 means selecting \ residues 1-10, 20-30, 40, 45 and 46 for calculation. The residue indices are not affected by -resi_offset, i.e. they \ should be consistent with the indices in your trajectories.") parser.add_argument("-chain_breaks", nargs="+", default=[], metavar="100 281 420", help="Start a new chain at the X-th residue (starting at 1) in \ the trajectory topology. This identifier is independent of the residue index but checks the residue order in the topology. \ Multiple chain breaks are supported. This option is useful when the simulation system contains \ multiple differnt chains, or users want to see the difference between chains even if these chains are identical. Using this flag \ will generate seperate figures for each of the chains. But the binding site detection will still treat the proteins in the \ system collectively, i.e. those binding sites that cover at multiple chains will be identified.") parser.add_argument("-nbootstrap", default=10, metavar=10, help="The number of samples for bootstrapping the calcultion of koff. \ The default is 10. The larger the number, the more time-consuming the calculation will be. The closer the bootstrapped \ residence time/koffs are to the original values, the more reliable those original values are. The bootstrapped results \ are ploted in each of the koff plots and plotted apposed to the original values in the figure showing residence time. ") parser.add_argument("-save_dataset", nargs="?", default=True, const=True, metavar="True", help="Save dataset in Pickle. Default is True") parser.add_argument("-gen_binding_poses", default=5, metavar=5, help="The num. of top-scored lipid binding poses to be generated for each binding \ site. The default is 5. A scoring function is generated for each binding site based on the sum of the probability density function of each atom/bead \ the lipid molecule. Score = sum(PDF(atom_i) * Weight(atom_i)) for atom_i in the lipid molecule. The weight function Weight(atom_i) \ is specified by the flag -score_weights.") parser.add_argument("-save_pose_format", default="gro", metavar="gro", help="The format the generated lipid binding poses are written into. This function \ is carried out by mdtraj.save(), hence supports the formats that are included by mdtraj. ") parser.add_argument("-score_weights", nargs="+", default=None, metavar="PO4:1 C1:1", help="The weight of each of the lipid atom/bead contributes to the scoring function. \ Top-rated lipid binding poses can be generated based on users' specification. The bounds poses of each binding site are scored based \ on the scoring function Score = sum(PDF(atom_i) * Weight(atom_i)) for atom_i in the lipid molecule.") parser.add_argument("-letter_map", nargs="+", default=None, metavar="ARG:K GLY:G", help="Map the three-letter amino acids to one letter. This map is \ used in making logomaker figures (https://logomaker.readthedocs.io/en/latest/). The common 20 amino acids are defined \ by this script. Users need to use this flag to define maps for uncommon amino acids in their systems.") parser.add_argument("-pdb", default=None, metavar="None", help="Provide a PDB structure onto which the binding site information will be mapped. \ Using this flag will generate a 'show_binding_site_info.py' file in the -save_dir directory, which allows users to check the \ mapped binding site information in PyMol. Users can run the generated script by 'python show_binding_site_info.py' \ to open such a PyMol session.") parser.add_argument("-pymol_gui", nargs="?", default=True, const=True, metavar="True", help="Show the PyMol session of binding site information \ at the end of the calcution. Need to be used in conjuction with -pdb.") args = parser.parse_args(sys.argv[1:]) ########################################## ########## assisting functions ########### ########################################## def cal_interaction_intensity(contact_residues_high): """ The probablily of finding the lipids around the selected residue plus the number of lipids found around the selected residue, the average number of lipid per contact """ contact_counts = [len(item) for item in contact_residues_high] mask = np.array(contact_counts) > 0 contact_counts_nonzero = np.array(contact_counts)[mask] return 100 * len(contact_counts_nonzero)/len(contact_residues_high), np.nan_to_num(contact_counts_nonzero.mean()) def cal_restime_koff(sigma, initial_guess): """ fit the exponential curve y=A*e^(-k1*x)+B*e^(-k2*x) """ delta_t_range = list(sigma.keys()) delta_t_range.sort() # x hist_values = np.nan_to_num([sigma[delta_t] for delta_t in delta_t_range]) # y try: popt, pcov = curve_fit(bi_expo, np.array(delta_t_range, dtype=np.float128), np.array(hist_values, dtype=np.float128), p0=initial_guess, maxfev=100000) n_fitted = bi_expo(np.array(delta_t_range, dtype=np.float128), *popt) r_squared = 1 - np.sum((np.nan_to_num(n_fitted) - np.nan_to_num(hist_values))**2)/np.sum((hist_values - np.mean(hist_values))**2) ks = [abs(k) for k in popt[:2]] koff = np.min(ks) restime = 1/koff except RuntimeError: koff = 0 restime = 0 r_squared = 0 popt = [0, 0, 0, 0] return restime, koff, r_squared, popt ##################################### ####### Main Class object ########### ##################################### ###################################################### ########### Load params and do calculation ########### ###################################################### if __name__ == '__main__': trajfile_list = args.f grofile_list = args.c lipid_set = args.lipids cutoff = [float(data) for data in args.cutoffs] save_dir = check_dir(args.save_dir) ####################################################################### ######## write a backup file of params for reproducibility ############ fn = os.path.join(save_dir, "pylipid_backup_{}.txt".format(datetime.datetime.now().strftime("%Y_%m_%d_%H%M"))) with open(fn, "w") as f: f.write("##### Record params for reproducibility #####\n") f.write("python {}\n".format(" ".join(sys.argv))) ###################################################################### ######################### process resi_list ########################## resi_list = [] if len(args.resi_list) > 0: for item in args.resi_list: if "-" in item: item_list = item.split("-") resi_list.append(np.arange(int(item_list[0]), int(item_list[-1])+1)) else: resi_list.append(int(item)) resi_list = np.hstack(resi_list) ####################################################################### ############################ change of radii ########################## ##### mdtraj default radii: ##### https://github.com/mdtraj/mdtraj/blob/b28df2cd6e5c35fa006fe3c24728857880793abb/mdtraj/geometry/sasa.py#L56 if args.radii == None: radii_book = None else: radii_book = {} for item in args.radii: radius = item.split(":") radii_book[radius[0]] = float(radius[1]) ####################################################################### ################# score weight for kde calculation #################### if args.score_weights == None: score_weights = None else: score_weights = {} for item in args.score_weights: weight = item.split(":") score_weights[weight[0]] = float(weight[1]) ####################################################################### ################# map three letter to single letter ################### letter_map = None if args.letter_map != None: letter_map = {} for item in args.letter_map: letter_map[item.split(":")[0]] = item.split(":")[1] ####################################################################### ################# process chain breaks ################################ chain_breaks = [] if len(args.chain_breaks) == 0 else [int(num)-1 for num in args.chain_breaks] ####################################################################### for lipid in lipid_set: li = LipidInteraction(trajfile_list, grofile_list, stride=int(args.stride), dt=args.dt, cutoff=cutoff, lipid=lipid, \ lipid_atoms=args.lipid_atoms, nprot=args.nprot, timeunit=args.tu, resi_offset=int(args.resi_offset), \ resi_list=resi_list, save_dir=args.save_dir) li.cal_interactions(save_dataset=args.save_dataset, nbootstrap=int(args.nbootstrap)) li.plot_interactions(item="Duration", letter_map=letter_map, chain_breaks=chain_breaks) li.plot_interactions(item="Residence Time", letter_map=letter_map, chain_breaks=chain_breaks) li.plot_interactions(item="Occupancy", letter_map=letter_map, chain_breaks=chain_breaks) li.plot_interactions(item="LipidCount", letter_map=letter_map, chain_breaks=chain_breaks) li.write_to_pdb(item="Duration") li.write_to_pdb(item="Residence Time") li.write_to_pdb(item="Occupancy") li.write_to_pdb(item="LipidCount") li.cal_interaction_network(pdb=args.pdb, save_dataset=args.save_dataset, \ pymol_gui=args.pymol_gui, radii=radii_book, gen_binding_poses=int(args.gen_binding_poses), \ score_weights=score_weights, save_pose_format=args.save_pose_format)
[ 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, 3300, 2447, 2579, 678, 25, 2078, 25, 1558, 13130, 198, 198, 31, 9800, 25, 33242, 1359, 10...
2.756399
5,665
# RT by Rext from asyncio import run from discord import Intents, Status, Game, AllowedMentions from core.bot import RT from data import SECRET try: from uvloop import install except ModuleNotFoundError: ... else: install() intents = Intents.default() intents.message_content = True intents.members = True bot = RT( allowed_mentions=AllowedMentions(everyone=False), intents=intents, status=Status.dnd, activity=Game("") ) bot.print("Now loading...") try: run(bot.start(SECRET["token"])) except KeyboardInterrupt: bot.print("Bye")
[ 2, 11923, 416, 797, 742, 198, 198, 6738, 30351, 952, 1330, 1057, 198, 198, 6738, 36446, 1330, 2558, 658, 11, 12678, 11, 3776, 11, 1439, 6972, 44, 298, 507, 198, 198, 6738, 4755, 13, 13645, 1330, 11923, 198, 6738, 1366, 1330, 10729, ...
3.061798
178
# Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import uuid import random import math import time import typing as t from . import experiment as hip # Demos from the README. If one of those is modified, please modify the readme as well README_DEMOS: t.Dict[str, t.Callable[[], hip.Experiment]] = { "demo": demo, "demo_3xcols": demo_3xcols, "demo_big": lambda: demo(1000), "demo_change_column_properties": demo_change_column_properties, "demo_basic_usage": demo_basic_usage, "demo_line_xy": demo_line_xy, "demo_bug_uid": demo_bug_uid, "demo_force_scale": demo_force_scale, "demo_distribution_cat": lambda: demo_distribution(axis="cat"), "demo_distribution_num": lambda: demo_distribution(axis="numeric"), "demo_distribution_num_100bins": lambda: demo_distribution(axis="numeric", nbins=100), "demo_bool": demo_bool, "demo_color_interpolate": demo_color_interpolate, "demo_color_scheme_ylrd": demo_color_scheme_ylrd, "demo_color_scheme_accent": demo_color_scheme_accent, "demo_axis_style": demo_axis_style, "demo_categorical": demo_categorical, "demo_customize": demo_customize, "demo_long_names": demo_long_names, "demo_force_constant_pplot": demo_force_constant_pplot, "demo_color_interpolate_inverse": demo_color_interpolate_inverse, "demo_first_value_nan": demo_first_value_nan, "demo_weighted_rows": demo_weighted_rows, "demo_col_html": demo_col_html, "demo_disable_table": demo_disable_table, "demo_big_floats": demo_big_floats, }
[ 2, 15069, 357, 66, 8, 3203, 11, 3457, 13, 290, 663, 29116, 13, 198, 2, 770, 2723, 2438, 318, 11971, 739, 262, 17168, 5964, 1043, 287, 262, 198, 2, 38559, 24290, 2393, 287, 262, 6808, 8619, 286, 428, 2723, 5509, 13, 198, 198, 11748...
2.532138
669
"""Ingredient dto. """
[ 37811, 27682, 445, 1153, 288, 1462, 13, 198, 37811, 198 ]
2.3
10
import logging import groceries.api as groceries import barcodescanner.scan as barcode if __name__ == "__main__": logging.basicConfig(level=logging.DEBUG) main()
[ 11748, 18931, 198, 11748, 38464, 13, 15042, 355, 38464, 198, 11748, 2318, 19815, 3798, 272, 1008, 13, 35836, 355, 2318, 8189, 628, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 18931, 13, 35487, ...
3.035088
57
import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="easy-icm-runner", version="1.0.6", author="Bachir El Koussa", author_email="bgkoussa@gmail.com", description="A wrapper for IBM ICMs Scheduler API Calls", long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/equinoxfitness/easy-icm-runner/", #packages=setuptools.find_packages(exclude=["*.tests", "*.tests.*", "tests.*", "tests"]), py_modules = ['icm_runner'], install_requires=[ 'requests', ], classifiers=[ "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ], )
[ 11748, 900, 37623, 10141, 198, 198, 4480, 1280, 7203, 15675, 11682, 13, 9132, 1600, 366, 81, 4943, 355, 277, 71, 25, 198, 220, 220, 220, 890, 62, 11213, 796, 277, 71, 13, 961, 3419, 198, 198, 2617, 37623, 10141, 13, 40406, 7, 198, ...
2.5
316
import unittest from molecule import onize_formula, update_equation_with_multiplier, flaten_formula, parse_molecule if __name__ == '__main__': unittest.main()
[ 11748, 555, 715, 395, 198, 198, 6738, 27756, 1330, 319, 1096, 62, 687, 4712, 11, 4296, 62, 4853, 341, 62, 4480, 62, 47945, 959, 11, 6228, 268, 62, 687, 4712, 11, 21136, 62, 76, 2305, 23172, 628, 198, 361, 11593, 3672, 834, 6624, 7...
2.813559
59