content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
""" Unit Tests for Service Patch """ # Copyright (c) 2021 ipyradiant contributors. # Distributed under the terms of the Modified BSD License. import ipyradiant import rdflib LINKEDDATA_QUERY = """ SELECT DISTINCT ?s ?p ?o WHERE { SERVICE <http://linkeddata.uriburner.com/sparql> { SELECT ?s ?p ?o WHERE {?s ?p ?o} } } """ PATCHED_LINKEDDATA_QUERY = """ SELECT DISTINCT ?s ?p ?o WHERE { service <http://linkeddata.uriburner.com/sparql> { SELECT ?s ?p ?o WHERE {?s ?p ?o} } } """
[ 37811, 11801, 30307, 329, 4809, 17106, 198, 37811, 198, 2, 15069, 357, 66, 8, 33448, 20966, 2417, 324, 3014, 20420, 13, 198, 2, 4307, 6169, 739, 262, 2846, 286, 262, 40499, 347, 10305, 13789, 13, 198, 198, 11748, 20966, 2417, 324, 301...
1.840782
358
import subprocess from collections import OrderedDict import pytest from connect.cli.plugins.project import git def test_connect_version_tag_invalid_comparison(): assert not git.ConnectVersionTag(str) == 10 def test_list_tags(mocker): mock_subprocess_run = mocker.patch('connect.cli.plugins.project.git.subprocess.run') mock_subprocess_called_process_error = mocker.patch( 'connect.cli.plugins.project.git.subprocess.CompletedProcess', ) mock_subprocess_called_process_error.stdout = b"""commit1 refs/tags/21.1 commit2 refs/tags/21.10 commit3 refs/tags/21.11 commit4 refs/tags/21.9""" mock_subprocess_run.return_value = mock_subprocess_called_process_error tags = git._list_tags('dummy.repo') assert tags == {'21.1': 'commit1', '21.10': 'commit2', '21.11': 'commit3', '21.9': 'commit4'} def test_list_tags_error(mocker): mock_subprocess_run = mocker.patch('connect.cli.plugins.project.git.subprocess.run') mock_subprocess_called_process = mocker.patch( 'connect.cli.plugins.project.git.subprocess.CompletedProcess', ) mock_subprocess_called_process.check_returncode.side_effect = subprocess.CalledProcessError(1, []) mock_subprocess_run.return_value = mock_subprocess_called_process with pytest.raises(git.GitException): git._list_tags('dummy.repo')
[ 11748, 850, 14681, 198, 6738, 17268, 1330, 14230, 1068, 35, 713, 198, 198, 11748, 12972, 9288, 198, 198, 6738, 2018, 13, 44506, 13, 37390, 13, 16302, 1330, 17606, 628, 628, 198, 4299, 1332, 62, 8443, 62, 9641, 62, 12985, 62, 259, 1210...
2.532609
552
# Created by Kelvin_Clark on 3/5/2022, 6:37 PM from typing import Optional from src.models.entities.user import User from src import database as db
[ 2, 15622, 416, 46577, 62, 43250, 319, 513, 14, 20, 14, 1238, 1828, 11, 718, 25, 2718, 3122, 198, 6738, 19720, 1330, 32233, 198, 198, 6738, 12351, 13, 27530, 13, 298, 871, 13, 7220, 1330, 11787, 198, 6738, 12351, 1330, 6831, 355, 206...
3.409091
44
# Problem ID: dmpg18g1 # By Alexander Cai 2019-12-09 # Solved import sys FILLED = -1 EMPTY = 0 data = sys.stdin.read().split('\n') n, k = map(int, data[0].split()) chairs = [FILLED for _ in range(n)] for j in map(int, data[1].split()): chairs[j-1] = EMPTY for i, j in enumerate(map(int, data[2].split())): if chairs[j-1] == EMPTY: chairs[j-1] = FILLED else: chairs[j-1] = i+1 # index of student s = [] nremaining = chairs.count(EMPTY) i = 0 while nremaining > 0: if chairs[i] == FILLED: pass elif chairs[i] == EMPTY: if len(s) > 0: s.pop() chairs[i] = FILLED nremaining -= 1 else: # student at this index -- underneath them is filled s.append(chairs[i]) # add them to stack chairs[i] = FILLED i = (i+1) % n print(s[0])
[ 2, 20647, 4522, 25, 288, 3149, 70, 1507, 70, 16, 198, 2, 2750, 10009, 327, 1872, 13130, 12, 1065, 12, 2931, 198, 2, 4294, 1079, 198, 198, 11748, 25064, 198, 198, 37, 8267, 1961, 796, 532, 16, 198, 39494, 9936, 796, 657, 198, 198, ...
2.051345
409
# -*- coding: utf-8 -*- import unittest import trafaret as t from collections import Mapping as AbcMapping from trafaret import extract_error, ignore, DataError from trafaret.extras import KeysSubset # res = @guard(a=String, b=Int, c=String) # def fn(a, b, c="default"): # '''docstring''' # return (a, b, c) # res = fn.__module__ = None # res = help(fn) # self.assertEqual(res, Help on function fn: # <BLANKLINE> # fn(*args, **kwargs) # guarded with <Dict(a=<String>, b=<Int>, c=<String>)> # <BLANKLINE> # docstring # <BLANKLINE> # ********************************************************************** # File "/Users/mkrivushin/w/trafaret/trafaret/__init__.py", line 1260, in trafaret.guard # Failed example: # help(fn) # Expected: # Help on function fn: # <BLANKLINE> # fn(*args, **kwargs) # guarded with <Dict(a=<String>, b=<Int>, c=<String>)> # <BLANKLINE> # docstring # <BLANKLINE> # Got: # Help on function fn: # <BLANKLINE> # fn(a, b, c='default') # guarded with <Dict(a=<String>, b=<Int>, c=<String>)> # <BLANKLINE> # docstring # <BLANKLINE> # res = fn("foo", 1) # self.assertEqual(res, ('foo', 1, 'default') # res = extract_error(fn, "foo", 1, 2) # self.assertEqual(res, {'c': 'value is not a string'} # res = extract_error(fn, "foo") # self.assertEqual(res, {'b': 'is required'} # res = g = guard(Dict()) # res = c = Forward() # res = c << Dict(name=str, children=List[c]) # res = g = guard(c) # res = g = guard(Int()) # self.assertEqual(res, Traceback (most recent call last): # ... # RuntimeError: trafaret should be instance of Dict or Forward # res = a = Int >> ignore # res = a.check(7) # ***Test Failed*** 2 failures. # res = _dd(fold({'a__a': 4})) # self.assertEqual(res, "{'a': {'a': 4}}" # res = _dd(fold({'a__a': 4, 'a__b': 5})) # self.assertEqual(res, "{'a': {'a': 4, 'b': 5}}" # res = _dd(fold({'a__1': 2, 'a__0': 1, 'a__2': 3})) # self.assertEqual(res, "{'a': [1, 2, 3]}" # res = _dd(fold({'form__a__b': 5, 'form__a__a': 4}, 'form')) # self.assertEqual(res, "{'a': {'a': 4, 'b': 5}}" # res = _dd(fold({'form__a__b': 5, 'form__a__a__0': 4, 'form__a__a__1': 7}, 'form')) # self.assertEqual(res, "{'a': {'a': [4, 7], 'b': 5}}" # res = repr(fold({'form__1__b': 5, 'form__0__a__0': 4, 'form__0__a__1': 7}, 'form')) # self.assertEqual(res, "[{'a': [4, 7]}, {'b': 5}]" # res = _dd(unfold({'a': 4, 'b': 5})) # self.assertEqual(res, "{'a': 4, 'b': 5}" # res = _dd(unfold({'a': [1, 2, 3]})) # self.assertEqual(res, "{'a__0': 1, 'a__1': 2, 'a__2': 3}" # res = _dd(unfold({'a': {'a': 4, 'b': 5}})) # self.assertEqual(res, "{'a__a': 4, 'a__b': 5}" # res = _dd(unfold({'a': {'a': 4, 'b': 5}}, 'form')) # self.assertEqual(res, "{'form__a__a': 4, 'form__a__b': 5}" # res = from trafaret import Int # res = class A(object): # class B(object): # d = {'a': 'word'} # res = dict((DeepKey('B.d.a') >> 'B_a').pop(A)) # self.assertEqual(res, {'B_a': 'word'} # res = dict((DeepKey('c.B.d.a') >> 'B_a').pop({'c': A})) # self.assertEqual(res, {'B_a': 'word'} # res = dict((DeepKey('B.a') >> 'B_a').pop(A)) # self.assertEqual(res, {'B.a': DataError(Unexistent key)} # res = dict(DeepKey('c.B.d.a', to_name='B_a', trafaret=Int()).pop({'c': A})) # self.assertEqual(res, {'B_a': DataError(value can't be converted to int)}
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 555, 715, 395, 198, 11748, 1291, 69, 8984, 355, 256, 198, 6738, 17268, 1330, 337, 5912, 355, 2275, 66, 44, 5912, 198, 6738, 1291, 69, 8984, 1330, 7925, 62, 1822...
2.137586
1,599
# coding: utf-8 # This file is part of libdesktop # The MIT License (MIT) # # Copyright (c) 2016 Bharadwaj Raju # # 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 subprocess as sp from libdesktop import system import sys def construct(name, exec_, terminal=False, additional_opts={}): '''Construct a .desktop file and return it as a string. Create a standards-compliant .desktop file, returning it as a string. Args: name (str) : The program's name. exec\_ (str) : The command. terminal (bool): Determine if program should be run in a terminal emulator or not. Defaults to ``False``. additional_opts (dict): Any additional fields. Returns: str: The constructed .desktop file. ''' desktop_file = '[Desktop Entry]\n' desktop_file_dict = { 'Name': name, 'Exec': exec_, 'Terminal': 'true' if terminal else 'false', 'Comment': additional_opts.get('Comment', name) } desktop_file = ('[Desktop Entry]\nName={name}\nExec={exec_}\n' 'Terminal={terminal}\nComment={comment}\n') desktop_file = desktop_file.format(name=desktop_file_dict['Name'], exec_=desktop_file_dict['Exec'], terminal=desktop_file_dict['Terminal'], comment=desktop_file_dict['Comment']) if additional_opts is None: additional_opts = {} for option in additional_opts: if not option in desktop_file_dict: desktop_file += '%s=%s\n' % (option, additional_opts[option]) return desktop_file def execute(desktop_file, files=None, return_cmd=False, background=False): '''Execute a .desktop file. Executes a given .desktop file path properly. Args: desktop_file (str) : The path to the .desktop file. files (list): Any files to be launched by the .desktop. Defaults to empty list. return_cmd (bool): Return the command (as ``str``) instead of executing. Defaults to ``False``. background (bool): Run command in background. Defaults to ``False``. Returns: str: Only if ``return_cmd``. Returns command instead of running it. Else returns nothing. ''' # Attempt to manually parse and execute desktop_file_exec = parse(desktop_file)['Exec'] for i in desktop_file_exec.split(): if i.startswith('%'): desktop_file_exec = desktop_file_exec.replace(i, '') desktop_file_exec = desktop_file_exec.replace(r'%F', '') desktop_file_exec = desktop_file_exec.replace(r'%f', '') if files: for i in files: desktop_file_exec += ' ' + i if parse(desktop_file)['Terminal']: # Use eval and __import__ to bypass a circular dependency desktop_file_exec = eval( ('__import__("libdesktop").applications.terminal(exec_="%s",' ' keep_open_after_cmd_exec=True, return_cmd=True)') % desktop_file_exec) if return_cmd: return desktop_file_exec desktop_file_proc = sp.Popen([desktop_file_exec], shell=True) if not background: desktop_file_proc.wait() def locate(desktop_filename_or_name): '''Locate a .desktop from the standard locations. Find the path to the .desktop file of a given .desktop filename or application name. Standard locations: - ``~/.local/share/applications/`` - ``/usr/share/applications`` Args: desktop_filename_or_name (str): Either the filename of a .desktop file or the name of an application. Returns: list: A list of all matching .desktop files found. ''' paths = [ os.path.expanduser('~/.local/share/applications'), '/usr/share/applications'] result = [] for path in paths: for file in os.listdir(path): if desktop_filename_or_name in file.split( '.') or desktop_filename_or_name == file: # Example: org.gnome.gedit result.append(os.path.join(path, file)) else: file_parsed = parse(os.path.join(path, file)) try: if desktop_filename_or_name.lower() == file_parsed[ 'Name'].lower(): result.append(file) elif desktop_filename_or_name.lower() == file_parsed[ 'Exec'].split(' ')[0]: result.append(file) except KeyError: pass for res in result: if not res.endswith('.desktop'): result.remove(res) if not result and not result.endswith('.desktop'): result.extend(locate(desktop_filename_or_name + '.desktop')) return result def parse(desktop_file_or_string): '''Parse a .desktop file. Parse a .desktop file or a string with its contents into an easy-to-use dict, with standard values present even if not defined in file. Args: desktop_file_or_string (str): Either the path to a .desktop file or a string with a .desktop file as its contents. Returns: dict: A dictionary of the parsed file.''' if os.path.isfile(desktop_file_or_string): with open(desktop_file_or_string) as f: desktop_file = f.read() else: desktop_file = desktop_file_or_string result = {} for line in desktop_file.split('\n'): if '=' in line: result[line.split('=')[0]] = line.split('=')[1] for key, value in result.items(): if value == 'false': result[key] = False elif value == 'true': result[key] = True if not 'Terminal' in result: result['Terminal'] = False if not 'Hidden' in result: result['Hidden'] = False return result
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 198, 2, 770, 2393, 318, 636, 286, 9195, 41375, 198, 198, 2, 383, 17168, 13789, 357, 36393, 8, 198, 2, 198, 2, 15069, 357, 66, 8, 1584, 33653, 324, 86, 1228, 13308, 84, 198, 2, 198, 2, 2448,...
2.892942
2,111
import os import cv2 import keras import numpy as np import albumentations as A import tensorflow as tf from keras import backend as K def iou(y_true, y_pred, label: int): """ Return the Intersection over Union (IoU) for a given label. Args: y_true: the expected y values as a one-hot y_pred: the predicted y values as a one-hot or softmax output label: the label to return the IoU for Returns: the IoU for the given label """ # extract the label values using the argmax operator then # calculate equality of the predictions and truths to the label y_true = K.cast(K.equal(K.argmax(y_true), label), K.floatx()) y_pred = K.cast(K.equal(K.argmax(y_pred), label), K.floatx()) # calculate the |intersection| (AND) of the labels intersection = K.sum(y_true * y_pred) # calculate the |union| (OR) of the labels union = K.sum(y_true) + K.sum(y_pred) - intersection # avoid divide by zero - if the union is zero, return 1 # otherwise, return the intersection over union return K.switch(K.equal(union, 0), 1.0, intersection / union) def mean_iou(y_true, y_pred): """ Return the Intersection over Union (IoU) score. Args: y_true: the expected y values as a one-hot y_pred: the predicted y values as a one-hot or softmax output Returns: the scalar IoU value (mean over all labels) """ # get number of labels to calculate IoU for num_labels = K.int_shape(y_pred)[-1] # initialize a variable to store total IoU in total_iou = K.variable(0) # iterate over labels to calculate IoU for for label in range(num_labels): total_iou = total_iou + iou(y_true, y_pred, label) # divide total IoU by number of labels to get mean IoU return total_iou / num_labels # def iou_metric(y_true, y_pred): SMOOTH = 1e-01 def iou_coef(y_true, y_pred, smooth=SMOOTH): """ IoU = (|X &amp; Y|)/ (|X or Y|) """ intersection = K.sum(K.abs(y_true * y_pred), axis=-1) union = K.sum((y_true,-1) + K.sum(y_pred,-1)) - intersection return (intersection + smooth) / (union + smooth) # return iou_coef
[ 11748, 28686, 198, 11748, 269, 85, 17, 198, 11748, 41927, 292, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 435, 65, 1713, 602, 355, 317, 198, 11748, 11192, 273, 11125, 355, 48700, 198, 6738, 41927, 292, 1330, 30203, 355, 509, 198, ...
2.550059
849
#!/usr/bin/env python # # A minimal Python language binding for the OpsRamp REST API. # # monitoring.py # Classes related to monitoring templates and similar things. # # (c) Copyright 2019-2021 Hewlett Packard Enterprise Development LP # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from opsramp.api import ORapi
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 198, 2, 317, 10926, 11361, 3303, 12765, 329, 262, 26123, 49, 696, 30617, 7824, 13, 198, 2, 198, 2, 9904, 13, 9078, 198, 2, 38884, 3519, 284, 9904, 24019, 290, 2092, 1243, 13, 19...
3.75576
217
from client import exceptions as ex from client.sources import doctest from client.sources.doctest import models import mock import unittest import os.path
[ 6738, 5456, 1330, 13269, 355, 409, 198, 6738, 5456, 13, 82, 2203, 1330, 10412, 395, 198, 6738, 5456, 13, 82, 2203, 13, 4598, 310, 395, 1330, 4981, 198, 11748, 15290, 198, 11748, 555, 715, 395, 198, 198, 11748, 28686, 13, 6978, 198 ]
3.738095
42
#!/usr/bin/python # # Copyright (c) 2019 Zim Kalinowski, (@zikalino) # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: azure_rm_cosmosdbaccount_info short_description: Get Azure Cosmos DB Account facts description: - Get facts of Azure Cosmos DB Account. options: resource_group: description: - Name of an Azure resource group. name: description: - Cosmos DB database account name. tags: description: - Limit results by providing a list of tags. Format tags as 'key' or 'key:value'. retrieve_keys: description: - Retrieve keys and connection strings. type: str choices: - all - readonly retrieve_connection_strings: description: - Retrieve connection strings. type: bool extends_documentation_fragment: - azure.azcollection.azure author: - Zim Kalinowski (@zikalino) ''' EXAMPLES = ''' - name: Get instance of Database Account community.azure.azure_rm_cosmosdbaccount_info: resource_group: myResourceGroup name: testaccount - name: List instances of Database Account azure_rm_cosmosdbaccousnt_info: resource_group: myResourceGroup ''' RETURN = ''' accounts: description: A list of dictionaries containing facts for Database Account. returned: always type: complex contains: id: description: - The unique resource identifier of the database account. returned: always type: str sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.DocumentDB/databaseAccount s/testaccount" resource_group: description: - Name of an Azure resource group. returned: always type: str sample: myResourceGroup name: description: - The name of the database account. returned: always type: str sample: testaccount location: description: - The location of the resource group to which the resource belongs. returned: always type: str sample: westus kind: description: - Indicates the type of database account. returned: always type: str sample: global_document_db consistency_policy: description: - Consistency policy. returned: always type: complex contains: default_consistency_level: description: - Default consistency level. returned: always type: str sample: session max_interval_in_seconds: description: - Maximum interval in seconds. returned: always type: int sample: 5 max_staleness_prefix: description: - Maximum staleness prefix. returned: always type: int sample: 100 failover_policies: description: - The list of new failover policies for the failover priority change. returned: always type: complex contains: name: description: - Location name. returned: always type: str sample: eastus failover_priority: description: - Failover priority. returned: always type: int sample: 0 id: description: - Read location ID. returned: always type: str sample: testaccount-eastus read_locations: description: - Read locations. returned: always type: complex contains: name: description: - Location name. returned: always type: str sample: eastus failover_priority: description: - Failover priority. returned: always type: int sample: 0 id: description: - Read location ID. returned: always type: str sample: testaccount-eastus document_endpoint: description: - Document endpoint. returned: always type: str sample: https://testaccount-eastus.documents.azure.com:443/ provisioning_state: description: - Provisioning state. returned: always type: str sample: Succeeded write_locations: description: - Write locations. returned: always type: complex contains: name: description: - Location name. returned: always type: str sample: eastus failover_priority: description: - Failover priority. returned: always type: int sample: 0 id: description: - Read location ID. returned: always type: str sample: testaccount-eastus document_endpoint: description: - Document endpoint. returned: always type: str sample: https://testaccount-eastus.documents.azure.com:443/ provisioning_state: description: - Provisioning state. returned: always type: str sample: Succeeded database_account_offer_type: description: - Offer type. returned: always type: str sample: Standard ip_range_filter: description: - Enable IP range filter. returned: always type: str sample: 10.10.10.10 is_virtual_network_filter_enabled: description: - Enable virtual network filter. returned: always type: bool sample: true enable_automatic_failover: description: - Enable automatic failover. returned: always type: bool sample: true enable_cassandra: description: - Enable Cassandra. returned: always type: bool sample: true enable_table: description: - Enable Table. returned: always type: bool sample: true enable_gremlin: description: - Enable Gremlin. returned: always type: bool sample: true virtual_network_rules: description: - List of Virtual Network ACL rules configured for the Cosmos DB account. type: list contains: subnet: description: - Resource id of a subnet. type: str sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.Network/virtualNet works/testvnet/subnets/testsubnet1" ignore_missing_vnet_service_endpoint: description: - Create Cosmos DB account without existing virtual network service endpoint. type: bool enable_multiple_write_locations: description: - Enable multiple write locations. returned: always type: bool sample: true document_endpoint: description: - Document endpoint. returned: always type: str sample: https://testaccount.documents.azure.com:443/ provisioning_state: description: - Provisioning state of Cosmos DB. returned: always type: str sample: Succeeded primary_master_key: description: - Primary master key. returned: when requested type: str sample: UIWoYD4YaD4LxW6k3Jy69qcHDMLX4aSttECQkEcwWF1RflLd6crWSGJs0R9kJwujehtfLGeQx4ISVSJfTpJkYw== secondary_master_key: description: - Primary master key. returned: when requested type: str sample: UIWoYD4YaD4LxW6k3Jy69qcHDMLX4aSttECQkEcwWF1RflLd6crWSGJs0R9kJwujehtfLGeQx4ISVSJfTpJkYw== primary_readonly_master_key: description: - Primary master key. returned: when requested type: str sample: UIWoYD4YaD4LxW6k3Jy69qcHDMLX4aSttECQkEcwWF1RflLd6crWSGJs0R9kJwujehtfLGeQx4ISVSJfTpJkYw== secondary_readonly_master_key: description: - Primary master key. returned: when requested type: str sample: UIWoYD4YaD4LxW6k3Jy69qcHDMLX4aSttECQkEcwWF1RflLd6crWSGJs0R9kJwujehtfLGeQx4ISVSJfTpJkYw== connection_strings: description: - List of connection strings. type: list returned: when requested contains: connection_string: description: - Description of connection string. type: str returned: always sample: Primary SQL Connection String description: description: - Connection string. type: str returned: always sample: "AccountEndpoint=https://testaccount.documents.azure.com:443/;AccountKey=fSEjathnk6ZeBTrXkud9j5kfhtSEQ q3dpJxJga76h9BZkK2BJJrDzSO6DDn6yKads017OZBZ1YZWyq1cW4iuvA==" tags: description: - Tags assigned to the resource. Dictionary of "string":"string" pairs. returned: always type: dict sample: { "tag1":"abc" } ''' from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common import AzureRMModuleBase from ansible.module_utils.common.dict_transformations import _camel_to_snake try: from msrestazure.azure_exceptions import CloudError from azure.mgmt.cosmosdb import CosmosDB from msrest.serialization import Model except ImportError: # This is handled in azure_rm_common pass if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 2, 198, 2, 15069, 357, 66, 8, 13130, 1168, 320, 12612, 259, 12079, 11, 4275, 47303, 282, 2879, 8, 198, 2, 198, 2, 22961, 3611, 5094, 13789, 410, 18, 13, 15, 10, 357, 3826, 27975, 45761, ...
1.817909
6,667
from rdflib import Graph import json import glob books = {} rdf_files = glob.glob("gutindex/cache/epub/*/*.rdf") i = 1 for rdf_file in rdf_files: g = Graph() g.parse(rdf_file) for s,p,o in g: if 'title' in p: books[str(o)] = str(s) print(i, str(o)) i+=1 with open("gutindex_titles.json", "w") as f: json.dump(books, f)
[ 198, 6738, 374, 67, 2704, 571, 1330, 29681, 198, 11748, 33918, 198, 11748, 15095, 198, 12106, 796, 23884, 198, 198, 4372, 69, 62, 16624, 796, 15095, 13, 4743, 672, 7203, 70, 315, 9630, 14, 23870, 14, 538, 549, 15211, 15211, 13, 4372, ...
1.919598
199
## _____ _____ ## | __ \| __ \ AUTHOR: Pedro Rivero ## | |__) | |__) | --------------------------------- ## | ___/| _ / DATE: May 18, 2021 ## | | | | \ \ --------------------------------- ## |_| |_| \_\ https://github.com/pedrorrivero ## ## Copyright 2021 Pedro Rivero ## ## Licensed under the Apache License, Version 2.0 (the "License"); ## you may not use this file except in compliance with the License. ## You may obtain a copy of the License at ## ## http://www.apache.org/licenses/LICENSE-2.0 ## ## Unless required by applicable law or agreed to in writing, software ## distributed under the License is distributed on an "AS IS" BASIS, ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ## See the License for the specific language governing permissions and ## limitations under the License. from abc import ABC, abstractmethod ############################################################################### ## BIT CACHE INTERFACE ###############################################################################
[ 2235, 220, 220, 220, 220, 29343, 220, 220, 29343, 198, 2235, 220, 220, 930, 220, 11593, 3467, 91, 220, 11593, 3467, 220, 220, 220, 44746, 25, 28855, 5866, 78, 198, 2235, 220, 220, 930, 930, 834, 8, 930, 930, 834, 8, 930, 220, 220,...
3.665541
296
""" Log multiple instances to same file. """
[ 198, 37811, 198, 11187, 3294, 10245, 284, 976, 2393, 13, 198, 37811, 198 ]
3.538462
13
from Stream.Stream import Stream
[ 6738, 13860, 13, 12124, 1330, 13860, 628 ]
4.857143
7
""" This tool compares measured data (observed) with model outputs (predicted), used in procedures of calibration and validation """ from __future__ import division from __future__ import print_function import os from math import sqrt import pandas as pd from sklearn.metrics import mean_squared_error as calc_mean_squared_error import cea.config import cea.inputlocator from cea_calibration.global_variables import * # from cea.constants import MONTHS_IN_YEAR_NAMES # import cea.examples.global_variables as global_variables # def outputdatafolder(self): # return self._ensure_folder(self.scenario, 'outputs', 'data') # # # def get_calibrationresults(self): # """scenario/outputs/data/calibration_results/calibrationresults.csv""" # return os.path.join(self.scenario, 'outputs', 'data', 'calibration_results', 'calibrationresults.csv') # # # def get_project_calibrationresults(self): # """project/outputs/calibration_results/calibrationresults.csv""" # return os.path.join(self.project, 'outputs', 'calibration_results', 'calibrationresults.csv') # # # def get_totaloccupancy(self): # """scenario/outputs/data/totaloccupancy.csv""" # return os.path.join(self.scenario, "outputs", "data", "totaloccupancy.csv") # # # def get_measurements_folder(self): # return self._ensure_folder(self.scenario, 'inputs', 'measurements') # # # def get_annual_measurements(self): # return os.path.join(self.get_measurements_folder(), 'annual_measurements.csv') # # # def get_monthly_measurements(self): # return os.path.join(self.get_measurements_folder(), 'monthly_measurements.csv') # # # def get_global_monthly_measurements(self): # return os.path.join(self.get_measurements_folder(), 'monthly_measurements.csv') # global_validation_n_calibrated = [] # global_validation_percentage = [] MONTHS_IN_YEAR_NAMES = ['JANUARY', 'FEBRUARY', 'MARCH', 'APRIL', 'MAY', 'JUNE', 'JULY', 'AUGUST', 'SEPTEMBER', 'OCTOBER', 'NOVEMBER', 'DECEMBER'] __author__ = "Luis Santos" __copyright__ = "Copyright 2020, Architecture and Building Systems - ETH Zurich" __credits__ = ["Luis Santos, Jimeno Fonseca, Daren Thomas"] __license__ = "MIT" __version__ = "1.0" __maintainer__ = "Daren Thomas" __email__ = "cea@arch.ethz.ch" __status__ = "Production" def validation(scenario_list, locators_of_scenarios, measured_building_names_of_scenarios, monthly=True, load='GRID', ): """ This tool compares observed (real life measured data) and predicted (output of the model data) values. Monthly data is compared in terms of NMBE and CvRMSE (follwing ASHRAE Guideline 14-2014). A new input folder with measurements has to be created, with a csv each for monthly data provided as input for this tool. The input file contains: Name (CEA ID)| ZipCode (optional) | Monthly Data (JAN - DEC) | Type of equivalent variable in CEA (GRID_kWh is the default for total electricity consumption) The script prints the NBME and CvRMSE for each building. It also outputs the number of calibrated buildings and a score metric (calibrated buildings weighted by their energy consumption) """ ## monthly validation if monthly: number_of_buildings = 0 print("monthly validation") validation_output = pd.DataFrame(columns=['scenario', 'calibrated_buildings', 'score']) for scenario, locator, measured_building_names in zip(scenario_list, locators_of_scenarios, measured_building_names_of_scenarios): list_of_scores = [] number_of_calibrated = [] number_of_buildings = number_of_buildings + len(measured_building_names) # get measured data for buildings in this scenario monthly_measured_data = pd.read_csv(locator.get_monthly_measurements()) # loop in the measured buildings of this scenario for building_name in measured_building_names: # number of buildings that have real data available # extract measured data print('For building', building_name, 'the errors are') fields_to_extract = ['Name'] + MONTHS_IN_YEAR_NAMES monthly_measured_demand = monthly_measured_data[fields_to_extract].set_index('Name') monthly_measured_demand = monthly_measured_demand.loc[building_name] monthly_measured_demand = pd.DataFrame({'Month': monthly_measured_demand.index.values, 'measurements': monthly_measured_demand.values}) # extract model output hourly_modelled_data = pd.read_csv(locator.get_demand_results_file(building_name), usecols=['DATE', load + '_kWh']) hourly_modelled_data['DATE'] = pd.to_datetime(hourly_modelled_data['DATE']) look_up = {1: 'JANUARY', 2: 'FEBRUARY', 3: 'MARCH', 4: 'APRIL', 5: 'MAY', 6: 'JUNE', 7: 'JULY', 8: 'AUGUST', 9: 'SEPTEMBER', 10: 'OCTOBER', 11: 'NOVEMBER', 12: 'DECEMBER'} # this step is required to have allow the conversion from hourly to monthly data monthly_modelled_data = hourly_modelled_data.resample('M', on='DATE').sum() # because data is in kWh monthly_modelled_data['Month'] = monthly_modelled_data.index.month monthly_modelled_data['Month'] = monthly_modelled_data.apply(lambda x: look_up[x['Month']], axis=1) monthly_data = monthly_modelled_data.merge(monthly_measured_demand, on='Month') # calculate errors cv_root_mean_squared_error, normalized_mean_biased_error = calc_errors_per_building(load, monthly_data) ind_calib_building, ind_score_building = calc_building_score(cv_root_mean_squared_error, monthly_data, normalized_mean_biased_error) # appending list of variables for later use number_of_calibrated.append(ind_calib_building) list_of_scores.append(ind_score_building) n_scenario_calib = sum(number_of_calibrated) scenario_score = sum(list_of_scores) scenario_name = os.path.basename(scenario) validation_output = validation_output.append( {'scenario': scenario_name, 'calibrated_buildings': n_scenario_calib, 'score': scenario_score}, ignore_index=True) n_calib = validation_output['calibrated_buildings'].sum() score = validation_output['score'].sum() global_validation_n_calibrated.append(n_calib) global_validation_percentage.append((n_calib / number_of_buildings) * 100) print('The number of calibrated buildings is', n_calib) print('The final score is', score) return score def main(config): """ This is the main entry point to your script. Any parameters used by your script must be present in the ``config`` parameter. The CLI will call this ``main`` function passing in a ``config`` object after adjusting the configuration to reflect parameters passed on the command line - this is how the ArcGIS interface interacts with the scripts BTW. :param config: :type config: cea.config.Configuration :return: """ assert os.path.exists(config.scenario), 'Scenario not found: %s' % config.scenario locator = cea.inputlocator.InputLocator(config.scenario, config.plugins) measured_building_names = get_measured_building_names(locator) scenario_list = [config.scenario] locators_of_scenarios = [locator] measured_building_names_of_scenarios = [measured_building_names] validation(scenario_list, locators_of_scenarios, measured_building_names_of_scenarios, monthly=True, load='GRID', ) if __name__ == '__main__': main(cea.config.Configuration())
[ 37811, 198, 1212, 2891, 23008, 8630, 1366, 357, 672, 45852, 8, 351, 2746, 23862, 357, 28764, 5722, 828, 973, 287, 9021, 286, 36537, 290, 21201, 198, 37811, 198, 6738, 11593, 37443, 834, 1330, 7297, 198, 6738, 11593, 37443, 834, 1330, 36...
2.40288
3,403
try: from public_config import * except ImportError: pass HOST = '0.0.0.0' PORT = 9038 SERVICE_NAME = 'jobs' SERVER_ENV = 'prod' SQLALCHEMY_POOL_SIZE = 10 SQLALCHEMY_POOL_RECYCLE = 3600 JOBS = [ { # 10:30 # 1 'id': 'credit-check-daily', # id, 'func': 'apps.jobs.business.jobs:JobsBusiness.credit_check_daily', # 'args': None, # 'trigger': 'cron', # 'day_of_week': 'mon-fri', # 1 - 5 'hour': 11, # 11 'minute': 30, # # 'trigger': 'interval', # # 'hours': 10 # 'seconds': 10 }, { # cidata 'id': 'cijob_update', # id, 'func': 'apps.extention.business.cidata:CiJobBusiness.update_jenkins_data', # 'args': None, # 'trigger': 'interval', # 'hours': 10 # 'seconds': 10 }, { # redis 'id': 'get_statistics_route_job', # id, 'func': 'apps.public.daos.public:get_statistics_route_job', # 'args': None, # 'trigger': 'interval', # 'day_of_week': 'mon-fri', # 1 - 5 'hour': 3, # 3 # 'minute': 5, # } ]
[ 28311, 25, 198, 220, 220, 220, 422, 1171, 62, 11250, 1330, 1635, 198, 16341, 17267, 12331, 25, 198, 220, 220, 220, 1208, 198, 198, 39, 10892, 796, 705, 15, 13, 15, 13, 15, 13, 15, 6, 198, 15490, 796, 4101, 2548, 198, 35009, 27389,...
1.819018
652
import pyautogui, pygetwindow, time screen = pygetwindow.getWindowsWithTitle('Old School RuneScape')[0] centerRatio = (2.8,2.8) # while True: boxs = list(pyautogui.locateAllOnScreen("miniTree.png")) box = boxs[len(boxs)//2] if box: pyautogui.click(box) #tinder = pyautogui.locateCenterOnScreen("tinderbox.png") #pyautogui.click(tinder) time.sleep(7) move("left",1) time.sleep(3) #print("found")
[ 11748, 12972, 2306, 519, 9019, 11, 12972, 1136, 17497, 11, 640, 198, 198, 9612, 796, 12972, 1136, 17497, 13, 1136, 11209, 3152, 19160, 10786, 19620, 3961, 28228, 3351, 1758, 11537, 58, 15, 60, 198, 16159, 29665, 952, 796, 357, 17, 13, ...
2.056522
230
#!/usr/bin/python ''' Produces POSIX commands to setup the environment variables for Geant4. Required command line arguments: 1: Location of geant4.sh script. 2: Version of Geant4. ''' import os import sys import re import subprocess as subp from codecs import encode,decode geant4_sh, geant4_version = sys.argv[1:] # vars and standard directory names geant4_vars = { "G4ABLADATA" : "G4ABLA", "G4LEDATA" : "G4EMLOW", "G4LEVELGAMMADATA" : "PhotonEvaporation", "G4NEUTRONHPDATA" : "G4NDL", "G4NEUTRONXSDATA" : "G4NEUTRONXS", "G4PIIDATA" : "G4PII", "G4RADIOACTIVEDATA": "RadioactiveDecay", "G4REALSURFACEDATA": "RealSurface", "G4ENSDFSTATEDATA" : "G4ENSDFSTATE2.2", "G4SAIDXSDATA" : "G4SAIDDATA1.1" } geant4_env = {} # try to get vars from geant4.sh script if os.path.isfile(geant4_sh): p = subp.Popen("/bin/bash", stdin=subp.PIPE, stdout=subp.PIPE, cwd=os.path.dirname(geant4_sh), env={}) penv = decode(p.communicate(encode("source geant4.sh && env"))[0].strip()) for line in penv.split("\n"): sep = line.index("=") var = line[:sep] value = line[sep+1:] if var in geant4_vars: geant4_env[var] = value formatted_pairs = [] for var in geant4_vars: value = None if var in os.environ: # warn user that existing environment variables override this script, # but don't complain if we are just running inside an env-shell.sh value = os.environ[var] if not "I3_SHELL" in os.environ: sys.stderr.write(("Warning: Geant4 environment variable already set {0}={1}, " "this overrides automatic detection\n") .format(var, value)) elif var in geant4_env: value = geant4_env[var] if value is None: sys.stderr.write(("Warning: Geant4 environment variable {0} could not be set, " "g4-based modules may crash\n").format(var)) else: formatted_pairs.append("{0}={1}".format(var, value)) # extra formatting for env-shell.sh sys.stdout.write(" \\\n\t".join(formatted_pairs))
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 7061, 6, 198, 11547, 728, 28069, 10426, 9729, 284, 9058, 262, 2858, 9633, 329, 2269, 415, 19, 13, 198, 198, 37374, 3141, 1627, 7159, 25, 198, 16, 25, 13397, 286, 4903, 415, 19, 13, 1477, ...
2.044505
1,101
#! /usr/bin/env python from __future__ import absolute_import import os import sys PROJECT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir)) sys.path.append(PROJECT_DIR) sys.path.append(os.path.abspath(os.path.join(PROJECT_DIR, "app"))) if __name__ == "__main__": from app.main import Main aws_bucket_name = None if len(sys.argv) > 1: aws_bucket_name = sys.argv[1] Main().load_images(aws_bucket_name)
[ 2, 0, 1220, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 198, 11748, 28686, 198, 11748, 25064, 198, 198, 31190, 23680, 62, 34720, 796, 28686, 13, 6978, 13, 397, 2777, 776, 7, 418, ...
2.316327
196
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. # -------------------------------------------------------------------------------------------- # - Generated by tools/entrypoint_compiler.py: do not edit by hand """ PixelExtractor """ __all__ = ["PixelExtractor"] from ....entrypoints.transforms_imagepixelextractor import \ transforms_imagepixelextractor from ....utils.utils import trace from ...base_pipeline_item import BasePipelineItem, DefaultSignature
[ 2, 16529, 1783, 10541, 198, 2, 15069, 357, 66, 8, 5413, 10501, 13, 1439, 2489, 10395, 13, 198, 2, 49962, 739, 262, 17168, 13789, 13, 198, 2, 16529, 1783, 10541, 198, 2, 532, 2980, 515, 416, 4899, 14, 13000, 4122, 62, 5589, 5329, 1...
4.697674
129
# # @lc app=leetcode.cn id=17 lang=python3 # # [17] # # https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number/description/ # # algorithms # Medium (47.70%) # Total Accepted: 18K # Total Submissions: 37.5K # Testcase Example: '"23"' # # 2-9 # # 1 # # # # : # # "23" # ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. # # # : # # # from itertools import product S = Solution() print(S.letterCombinations("23"))
[ 2, 198, 2, 2488, 44601, 598, 28, 293, 316, 8189, 13, 31522, 4686, 28, 1558, 42392, 28, 29412, 18, 198, 2, 198, 2, 685, 1558, 60, 220, 198, 2, 198, 2, 3740, 1378, 293, 316, 8189, 12, 31522, 13, 785, 14, 1676, 22143, 14, 9291, 1...
2.126761
213
import random import argparse from ast import Global from dis import dis from glob import glob from itertools import count from math import dist from logger import * import json import gym from matplotlib.pyplot import axis import scipy.optimize import pdb import torch from torch.autograd import Variable from jax_rl.agents import AWACLearner, SACLearner from jax_rl.datasets import ReplayBuffer from jax_rl.evaluation import evaluate from jax_rl.utils import make_env import numpy as np import pickle import random import copy from sklearn.cluster import KMeans# import ant # import swimmer # import reacher # import walker # import halfcheetah # import inverted_double_pendulum import sys sys.path.append('../all_envs') import swimmer import walker torch.utils.backcompat.broadcast_warning.enabled = True torch.utils.backcompat.keepdim_warning.enabled = True torch.set_default_tensor_type('torch.DoubleTensor') parser = argparse.ArgumentParser(description='PyTorch actor-critic example') parser.add_argument('--env-name', default="Reacher-v1", metavar='G', help='name of the environment to run') parser.add_argument('--seed', type=int, default=543, metavar='N', help='random seed (default: 1)') parser.add_argument('--batch-size', type=int, default=256, metavar='N', help='random seed (default: 1)') parser.add_argument('--render', action='store_true', help='render the environment') parser.add_argument('--log-interval', type=int, default=1, metavar='N', help='interval between training status logs (default: 10)') parser.add_argument('--save_path', type=str, default= 'temp', metavar='N', help='path to save demonstrations on') parser.add_argument('--xml', type=str, default= None, metavar='N', help='For diffent dynamics') parser.add_argument('--demo_files', nargs='+') parser.add_argument('--test_demo_files', nargs='+') parser.add_argument('--ratio', type=float, nargs='+') parser.add_argument('--eval-interval', type=int, default=1000) parser.add_argument('--restore_model', default=None) parser.add_argument('--mode') parser.add_argument('--discount', type=float, default=0.9) parser.add_argument('--discount_train', action='store_true') parser.add_argument('--fixed_train', action='store_true') parser.add_argument('--algo', default='sac', help='the algorithm of RL') parser.add_argument('--max_steps', type=int, default=int(1e6), help='the maximum number of steps') parser.add_argument('--start_training', type=int, default=int(1e4), help='Number of training steps to start training.') args = parser.parse_args() logger = CompleteLogger('log/'+ args.env_name + '/'+ os.path.splitext(args.xml)[0] + 'resplit') # re-define datasets json.dump(vars(args), logger.get_args_file(), sort_keys=True, indent=4) target_env_name = os.path.splitext(args.xml)[0] global iters # if __name__ == '__main__': # # # # # print('') # n = 4 # G_list = [[1,1,1,0], [1,1,1,0], [1,1,1,1], [0,0,1,1]] # print('') # # for i in range(n): # # G_list.append(input().split(',')) # x = [0 for i in range(n)] # G_list = np.array(G_list) # while(not is_all_clear(G_list)): # print(G_list) # global bestn # bestn = 0 # Max_Clique(0) # print(bestx,bestn) # pdb.set_trace() # update_graph(G=G_list, nodes_to_delete=bestx) # def re_split_demos(demos_all): # size = len(demos_all) # traj_len = len(demos_all[0]) # pdb.set_trace() # dist_matrix = np.zeros((size, size)) # 200 * 200 # look_1 = np.expand_dims(np.array(demos_all), axis=0) # 1 * 200 * 1000 * 18 # look_2 = np.expand_dims(np.array(demos_all), axis=1) # 200 * 1 * 1000 * 18 # dist_matrix = np.sum(abs(look_1 - look_2), axis=-1) # 200 * 200 * 1000 # # dist_matrix = np.linalg.norm(look_1 - look_2, axis=-1) # dist_matrix = np.mean(dist_matrix, dim=-1) # # for i in range(size): # # for j in range(size): # # dist_matrix[i][j] = calculate_traj_dist(demos_all[i], demos_all[j]) # global graph_matrix # # # clique # # graph_matrix = dist_matrix < (dist_matrix.mean() * 1.1) # # independent # graph_matrix = dist_matrix > (dist_matrix.mean() * 0.9) # print("sample graph:", graph_matrix[0]) # graph_matrix = graph_matrix.astype(int) # split_done = False # split_clique=[] # while(not split_done): # global x # # print(G_list) # global bestn # global iters # x = [0 for i in range(size)] # bestn = 0 # iters = 0 # # pdb.set_trace() # Max_Clique(0, size=size) # print(bestx, bestn) # update_graph(G=graph_matrix, nodes_to_delete=bestx) # # pdb.set_trace() # clique = [i for i, x in enumerate(bestx) if x == 1] # if len(clique) > int(0.1 * size): # split_clique.append(clique) # split_done = is_all_clear(graph_matrix) # print('re_cluster id:', split_clique) # pdb.set_trace() # # save new demo clique # raw_demos = {} # for i in range(len(split_clique)): # save_demo_path = '../demo/walker2d/re_split_{}_batch_00.pkl'.format(i) # raw_demos['obs'] = [demos_all[idx] for idx in split_clique[i]] # pickle.dump(raw_demos, open(save_demo_path, 'wb')) # return a list of neigjbor of x (including self) # main if args.mode == 'pair': demos = [load_pairs(args.demo_files[i:i+1], args.ratio[i]) for i in range(len(args.test_demo_files))] elif args.mode == 'traj': # load all demos demos_all, init_obs_all = load_demos(args.demo_files, args.ratio) test_demos = [] test_init_obs = [] # clean dataset not_expert = [] for i in range(len(demos_all)): if len(demos_all[i]) < 1000: not_expert.append(i) # not expert traj? if i % 5 == 0: print("len demos {}:{}".format(i, len(demos_all[i]))) # pdb.set_trace() for i in reversed(not_expert): del demos_all[i] demos_all = np.array(demos_all) # norm demos_all_normed = (demos_all / np.expand_dims(np.linalg.norm(demos_all,axis=1), axis=1)) re_split_demos(demos_all=demos_all) # random_split_demo(demos=demos_all) # kmeans = KMeans(n_clusters=4, random_state=0).fit(demos_all) # print(kmeans.labels_) # pdb.set_trace() # for i in range(len(args.test_demo_files)): # demos_single, init_obs_single = load_demos(args.test_demo_files[i:i+1], args.ratio) # test_demos.append(demos_single) # 4 * 50 * 1000 * 18 # test_init_obs.append(init_obs_single) # 4 * 0? # pdb.set_trace()
[ 11748, 4738, 198, 11748, 1822, 29572, 198, 6738, 6468, 1330, 8060, 198, 6738, 595, 1330, 595, 198, 6738, 15095, 1330, 15095, 198, 6738, 340, 861, 10141, 1330, 954, 198, 6738, 10688, 1330, 1233, 198, 6738, 49706, 1330, 1635, 198, 11748, ...
2.272759
2,911
#!/usr/bin/env python # # tpycl.py is the python support code to allow calling of python-wrapped # vtk code from tcl scripts # # the main class is tpycl, and scripts can # import sys import os import Tkinter from __main__ import slicer import qt if __name__ == "__main__": tp = tpycl() tp.main(sys.argv[1:])
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 2, 198, 2, 256, 9078, 565, 13, 9078, 318, 262, 21015, 1104, 2438, 284, 1249, 4585, 286, 21015, 12, 29988, 1496, 198, 2, 410, 30488, 2438, 422, 256, 565, 14750, 198, 2, 198, 2,...
2.669492
118
hex_strings = [ "FF 81 BD A5 A5 BD 81 FF", "AA 55 AA 55 AA 55 AA 55", "3E 7F FC F8 F8 FC 7F 3E", "93 93 93 F3 F3 93 93 93", ] if __name__ == "__main__": for x in range(len(hex_strings)): hex_data = hex_strings[x].split(' ') hex_data_to_image(hex_data)
[ 33095, 62, 37336, 796, 685, 198, 220, 366, 5777, 9773, 28023, 317, 20, 317, 20, 28023, 9773, 18402, 1600, 198, 220, 366, 3838, 5996, 15923, 5996, 15923, 5996, 15923, 5996, 1600, 198, 220, 366, 18, 36, 767, 37, 10029, 376, 23, 376, 2...
2.150794
126
import click from kryptos.scripts import build_strategy, stress_worker, kill_strat cli.add_command(build_strategy.run, "build") cli.add_command(stress_worker.run, "stress") cli.add_command(kill_strat.run, "kill")
[ 11748, 3904, 198, 6738, 479, 6012, 418, 13, 46521, 1330, 1382, 62, 2536, 4338, 11, 5503, 62, 28816, 11, 1494, 62, 2536, 265, 628, 198, 198, 44506, 13, 2860, 62, 21812, 7, 11249, 62, 2536, 4338, 13, 5143, 11, 366, 11249, 4943, 198, ...
2.842105
76
#!/usr/bin/env python3 """Radio scheduling program. Usage: album_times.py [--host=HOST] PORT Options: --host=HOST Hostname of MPD [default: localhost] -h --help Show this text Prints out the last scheduling time of every album. """ from datetime import datetime from docopt import docopt from mpd import MPDClient def album_sticker_get(client, album, sticker): """Gets a sticker associated with an album.""" # I am pretty sure that MPD only implements stickers for songs, so # the sticker gets attached to the first song in the album. tracks = client.find("album", album) if len(tracks) == 0: return return client.sticker_get("song", tracks[0]["file"], "album_" + sticker) def list_albums(client): """Lists albums sorted by last play timestamp.""" # Get all albums albums = client.list("album") all_albums = list( filter(lambda a: a not in ["", "Lainchan Radio Transitions"], albums) ) # Group albums by when they were last scheduled albums_by_last_scheduled = {} last_scheduled_times = [] for album in all_albums: # Get the last scheduled time, defaulting to 0 try: last_scheduled = int(album_sticker_get(client, album, "last_scheduled")) except ValueError: last_scheduled = 0 # Put the album into the appropriate bucket if last_scheduled in albums_by_last_scheduled: albums_by_last_scheduled[last_scheduled].append(album) else: albums_by_last_scheduled[last_scheduled] = [album] last_scheduled_times.append(last_scheduled) # Pick the 10 oldest times last_scheduled_times.sort() for last_scheduled in last_scheduled_times: dt = datetime.utcfromtimestamp(last_scheduled) albums = albums_by_last_scheduled[last_scheduled] print("{}: {}".format(dt.strftime("%Y-%m-%d %H:%M:%S"), albums)) if __name__ == "__main__": args = docopt(__doc__) try: args["PORT"] = int(args["PORT"]) except ValueError: print("PORT must be an integer") exit(1) try: client = MPDClient() client.connect(args["--host"], args["PORT"]) except Exception as e: print(f"could not connect to MPD: {e.args[0]}") exit(2) list_albums(client)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 37811, 26093, 26925, 1430, 13, 198, 198, 28350, 25, 198, 220, 5062, 62, 22355, 13, 9078, 685, 438, 4774, 28, 39, 10892, 60, 350, 9863, 198, 198, 29046, 25, 198, 220, 1377, ...
2.46723
946
#!/usr/bin/env python3 # # Copyright (c) 2020 Raspberry Pi (Trading) Ltd. # # SPDX-License-Identifier: BSD-3-Clause # # sudo pip3 install pyusb import usb.core import usb.util # find our device dev = usb.core.find(idVendor=0x0000, idProduct=0x0001) # was it found? if dev is None: raise ValueError('Device not found') # get an endpoint instance cfg = dev.get_active_configuration() intf = cfg[(0, 0)] outep = usb.util.find_descriptor( intf, # match the first OUT endpoint custom_match= \ lambda e: \ usb.util.endpoint_direction(e.bEndpointAddress) == \ usb.util.ENDPOINT_OUT) inep = usb.util.find_descriptor( intf, # match the first IN endpoint custom_match= \ lambda e: \ usb.util.endpoint_direction(e.bEndpointAddress) == \ usb.util.ENDPOINT_IN) assert inep is not None assert outep is not None test_string = "Hello World!" outep.write(test_string) from_device = inep.read(len(test_string)) print("Device Says: {}".format(''.join([chr(x) for x in from_device])))
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 201, 198, 201, 198, 2, 201, 198, 2, 15069, 357, 66, 8, 12131, 24244, 13993, 357, 2898, 4980, 8, 12052, 13, 201, 198, 2, 201, 198, 2, 30628, 55, 12, 34156, 12, 33234, 7483, 25, 347...
2.263692
493
import ipywidgets as ipw import traitlets from IPython.display import clear_output
[ 11748, 20966, 88, 28029, 11407, 355, 20966, 86, 198, 11748, 1291, 2578, 912, 198, 6738, 6101, 7535, 13, 13812, 1330, 1598, 62, 22915, 628, 198 ]
3.4
25
# -*- coding: utf-8 -*- # # This file is part of the SKA PST LMC project # # Distributed under the terms of the BSD 3-clause new license. # See LICENSE for more info. """This module implements the PstManagement device.""" from __future__ import annotations from typing import Optional from ska_tango_base.csp.controller_device import CspSubElementController from tango.server import device_property, run # PyTango imports # from tango import AttrQuality, AttrWriteType, DebugIt, DevState, DispLevel, PipeWriteType # from tango.server import Device, attribute, command, device_property, run __all__ = ["PstManagement", "main"] # ---------- # Run server # ---------- def main(args: Optional[list] = None, **kwargs: dict) -> int: """ Entry point for module. :param args: positional arguments :param kwargs: named arguments :return: exit code :rtype: int """ return run((PstManagement,), args=args, **kwargs) if __name__ == "__main__": main()
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 2, 770, 2393, 318, 636, 286, 262, 14277, 32, 28220, 406, 9655, 1628, 198, 2, 198, 2, 4307, 6169, 739, 262, 2846, 286, 262, 347, 10305, 513, 12, 565, 682, 6...
3.074534
322
import sys,os import argparse as arg import nmap import urllib2 parser = arg.ArgumentParser() parser.add_argument("-a", "--address", help="IP address", required=True) parser.add_argument("-i", "--interface", help="Interface", required=True) argument = parser.parse_args() main()
[ 11748, 25064, 11, 418, 198, 11748, 1822, 29572, 355, 1822, 198, 11748, 299, 8899, 198, 11748, 2956, 297, 571, 17, 198, 198, 48610, 796, 1822, 13, 28100, 1713, 46677, 3419, 198, 48610, 13, 2860, 62, 49140, 7203, 12, 64, 1600, 366, 438,...
3.144444
90
import argparse from cartografo import DEFAULT_OBJECT, DEFAULT_TARGET __parser = argparse.ArgumentParser() __get_argparser() __arguments = __parser.parse_args()
[ 11748, 1822, 29572, 198, 198, 6738, 6383, 519, 430, 6513, 1330, 5550, 38865, 62, 9864, 23680, 11, 5550, 38865, 62, 51, 46095, 628, 198, 834, 48610, 796, 1822, 29572, 13, 28100, 1713, 46677, 3419, 198, 834, 1136, 62, 853, 48610, 3419, ...
3.075472
53
L = ['michael', 'sarah', 'tracy', 'bob', 'jack'] # N r = [] n = 3 for i in range(n): r.append(L[i]) print(r) # pythonslice. m = 0 print(L[m:n], L[:n], L[-n:-1]) L = list(range(100)) print(L[:10], '\r', L[-10:], '\r', L[10:20], '\r', L[:10:2], '\r', L[::5]) print((0, 1, 2, 3, 4, 5)[:3]) print('ABCDEFG'[:3], 'ABCDEFG'[::2])
[ 43, 796, 37250, 76, 40302, 3256, 705, 82, 23066, 3256, 705, 2213, 1590, 3256, 705, 65, 672, 3256, 705, 19650, 20520, 198, 2, 399, 198, 81, 796, 17635, 198, 77, 796, 513, 198, 1640, 1312, 287, 2837, 7, 77, 2599, 198, 197, 81, 13, ...
1.770053
187
''' Created on Feb 17, 2014 @author: magus0219 ''' import unittest,datetime from util.dateutil import DateUtil from core.timematcher import TimeMatcher from core.timepattern import TimePattern if __name__ == "__main__": # import sys;sys.argv = ['', 'Test.testUnvaidValue'] unittest.main()
[ 7061, 6, 198, 41972, 319, 3158, 1596, 11, 1946, 198, 198, 31, 9800, 25, 2153, 385, 2999, 1129, 198, 7061, 6, 198, 11748, 555, 715, 395, 11, 19608, 8079, 198, 6738, 7736, 13, 4475, 22602, 1330, 7536, 18274, 346, 198, 6738, 4755, 13, ...
2.820755
106
from django.conf.urls import url from api import views urlpatterns = [ url(r'^pets/$', views.ListPets.as_view(), name='list_pets'), url(r'^cities/$', views.CityList.as_view(), name='city-list'), url(r'^states/$', views.StateList.as_view(), name='state-list'), ]
[ 6738, 42625, 14208, 13, 10414, 13, 6371, 82, 1330, 19016, 198, 198, 6738, 40391, 1330, 5009, 198, 198, 6371, 33279, 82, 796, 685, 198, 220, 220, 220, 19016, 7, 81, 6, 61, 79, 1039, 32624, 3256, 5009, 13, 8053, 47, 1039, 13, 292, 6...
2.486486
111
#!/usr/bin/env python # This is not an officially supported Google product, though support # will be provided on a best-effort basis. # Copyright 2018 Google LLC # Licensed under the Apache License, Version 2.0 (the "License"); you # may not use this file except in compliance with the License. # You may obtain a copy of the License at: # https://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, 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 os import ujson import webapp2 import utilities app = webapp2.WSGIApplication([ ("/toggleIndex", main)], debug = True )
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 2, 770, 318, 407, 281, 8720, 4855, 3012, 1720, 11, 996, 1104, 198, 2, 481, 307, 2810, 319, 257, 1266, 12, 14822, 419, 4308, 13, 198, 198, 2, 15069, 2864, 3012, 11419, 198, 198...
3.65368
231
#!/usr/bin/env python # -*- coding: UTF-8 -*- """================================================= @Author @Date 2021/9/22 17:04 @Desc ==================================================""" from colors import ColorMultiImage import settings from model import training import csv if __name__ == '__main__': generate_color = ColorMultiImage() stickers = settings.module # mousecattle if settings.train: color_model_path = training(settings.color_data_path) print(":" + color_model_path) if settings.color_style == 1: f = open(settings.color_model_path, "r+", encoding="utf-8-sig") reader = csv.reader(f) colors_max = len(list(reader)) print(f"{colors_max}") for amount in range(0, settings.n): # pixel = generate_color.merges(stickers) colors_number = generate_color.colors_number generate_color.generate(pixel, settings.color_output_name,str(amount),settings.color_model_path,settings.color_style,colors_number) print(f"INFO:{str(amount)}{settings.color_output_name}")
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 41002, 12, 23, 532, 9, 12, 198, 37811, 10052, 4770, 28, 198, 31, 13838, 220, 198, 31, 10430, 220, 220, 33448, 14, 24, 14, 1828, 1596, 25, 3023, 198, 31,...
2.721519
395
#! /usr/bin/env python """ usage: demoselsim.py outfilename popn h pct """ import numpy import sys if __name__ == "__main__": main()
[ 2, 0, 1220, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 37811, 198, 26060, 25, 1357, 577, 7278, 320, 13, 9078, 503, 34345, 1461, 77, 289, 279, 310, 198, 37811, 198, 198, 11748, 299, 32152, 198, 11748, 25064, 198, 197, 198, 361, 115...
2.464286
56
import math import torch import numpy as np import torch.nn as nn
[ 11748, 10688, 198, 198, 11748, 28034, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 28034, 13, 20471, 355, 299, 77, 628, 628, 628, 628 ]
3.083333
24
""" Common CLI options for invoke command """ import click from samcli.commands._utils.options import template_click_option, docker_click_options, parameter_override_click_option try: from pathlib import Path except ImportError: from pathlib2 import Path def get_application_dir(): """ Returns ------- Path Path representing the application config directory """ # TODO: Get the config directory directly from `GlobalConfig` return Path(click.get_app_dir("AWS SAM", force_posix=True)) def get_default_layer_cache_dir(): """ Default the layer cache directory Returns ------- str String representing the layer cache directory """ layer_cache_dir = get_application_dir().joinpath("layers-pkg") return str(layer_cache_dir) def invoke_common_options(f): """ Common CLI options shared by "local invoke" and "local start-api" commands :param f: Callback passed by Click """ invoke_options = ( [ template_click_option(), click.option( "--env-vars", "-n", type=click.Path(exists=True), help="JSON file containing values for Lambda function's environment variables.", ), parameter_override_click_option(), click.option( "--debug-port", "-d", help="When specified, Lambda function container will start in debug mode and will expose this " "port on localhost.", envvar="SAM_DEBUG_PORT", ), click.option( "--debugger-path", help="Host path to a debugger that will be mounted into the Lambda container." ), click.option( "--debug-args", help="Additional arguments to be passed to the debugger.", envvar="DEBUGGER_ARGS" ), click.option( "--docker-volume-basedir", "-v", envvar="SAM_DOCKER_VOLUME_BASEDIR", help="Specifies the location basedir where the SAM file exists. If the Docker is running on " "a remote machine, you must mount the path where the SAM file exists on the docker machine " "and modify this value to match the remote machine.", ), click.option("--log-file", "-l", help="logfile to send runtime logs to."), click.option( "--layer-cache-basedir", type=click.Path(exists=False, file_okay=False), envvar="SAM_LAYER_CACHE_BASEDIR", help="Specifies the location basedir where the Layers your template uses will be downloaded to.", default=get_default_layer_cache_dir(), ), ] + docker_click_options() + [ click.option( "--force-image-build", is_flag=True, help="Specify whether CLI should rebuild the image used for invoking functions with layers.", envvar="SAM_FORCE_IMAGE_BUILD", default=False, ) ] ) # Reverse the list to maintain ordering of options in help text printed with --help for option in reversed(invoke_options): option(f) return f
[ 37811, 198, 17227, 43749, 3689, 329, 26342, 3141, 198, 37811, 198, 198, 11748, 3904, 198, 6738, 6072, 44506, 13, 9503, 1746, 13557, 26791, 13, 25811, 1330, 11055, 62, 12976, 62, 18076, 11, 36253, 62, 12976, 62, 25811, 11, 11507, 62, 250...
2.271622
1,480
import threading # _recursive_sort(arr, 0, len(arr) - 1) if __name__ == "__main__": ar = [2, 4, 1, 2, 4, 5, 8, 2, 351, 2, 0] thread1 = threading.Thread( target=_recursive_sort, args=(ar, 0, len(ar) // 2),) thread2 = threading.Thread( target=_recursive_sort, args=(ar, (len(ar) // 2) + 1, len(ar) - 1,)) thread1.start() thread2.start() thread1.join() thread2.join() _merge(ar, 0, len(ar) // 2, len(ar) - 1) print(ar)
[ 11748, 4704, 278, 628, 628, 198, 198, 2, 4808, 8344, 30753, 62, 30619, 7, 3258, 11, 657, 11, 18896, 7, 3258, 8, 532, 352, 8, 628, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 628, 220, 220, 220, 610, 796, 685, 1...
2.073913
230
""" Deploy NodeJs application https://github.com/react-boilerplate/react-boilerplate """ from py_mina import * from py_mina.subtasks import git_clone, create_shared_paths, link_shared_paths, rollback_release # Settings - shared set('verbose', True) set('shared_dirs', ['node_modules', 'tmp']) set('shared_files', []) # Tasks
[ 37811, 198, 49322, 19081, 49044, 3586, 220, 198, 5450, 1378, 12567, 13, 785, 14, 45018, 12, 2127, 5329, 6816, 14, 45018, 12, 2127, 5329, 6816, 198, 37811, 628, 198, 6738, 12972, 62, 1084, 64, 1330, 1635, 198, 6738, 12972, 62, 1084, 64...
2.864407
118
import abc import json from typing import Any, Dict, IO, Iterable, List, Optional, Union import altair as alt from altair_saver.types import Mimebundle, MimebundleContent, JSONDict from altair_saver._utils import ( extract_format, fmt_to_mimetype, infer_mode_from_spec, maybe_open, ) def save( self, fp: Optional[Union[IO, str]] = None, fmt: Optional[str] = None ) -> Optional[Union[str, bytes]]: """Save a chart to file Parameters ---------- fp : file or filename (optional) Location to save the result. For fmt in ["png", "pdf"], file must be binary. For fmt in ["svg", "vega", "vega-lite"], file must be text. If not specified, the serialized chart will be returned. fmt : string (optional) The format in which to save the chart. If not specified and fp is a string, fmt will be determined from the file extension. Returns ------- chart : string, bytes, or None If fp is None, the serialized chart is returned. If fp is specified, the return value is None. """ if fmt is None: if fp is None: raise ValueError("Must specify either `fp` or `fmt` when saving chart") fmt = extract_format(fp) if fmt not in self.valid_formats[self._mode]: raise ValueError(f"Got fmt={fmt}; expected one of {self.valid_formats}") content = self._serialize(fmt, "save") if fp is None: if isinstance(content, dict): return json.dumps(content) return content if isinstance(content, dict): with maybe_open(fp, "w") as f: json.dump(content, f, indent=2) elif isinstance(content, str): with maybe_open(fp, "w") as f: f.write(content) elif isinstance(content, bytes): with maybe_open(fp, "wb") as f: f.write(content) else: raise ValueError( f"Unrecognized content type: {type(content)} for fmt={fmt!r}" ) return None
[ 11748, 450, 66, 198, 11748, 33918, 198, 6738, 19720, 1330, 4377, 11, 360, 713, 11, 24418, 11, 40806, 540, 11, 7343, 11, 32233, 11, 4479, 198, 198, 11748, 5988, 958, 355, 5988, 198, 198, 6738, 5988, 958, 62, 82, 8770, 13, 19199, 1330...
2.204868
986
# Import our project so that our custom logging gets setup early enough from __future__ import annotations import mcookbook # noqa: F401 # pylint: disable=unused-import
[ 2, 17267, 674, 1628, 523, 326, 674, 2183, 18931, 3011, 9058, 1903, 1576, 198, 6738, 11593, 37443, 834, 1330, 37647, 198, 198, 11748, 285, 27916, 2070, 220, 1303, 645, 20402, 25, 376, 21844, 220, 1303, 279, 2645, 600, 25, 15560, 28, 40...
3.73913
46
from .exceptions import AccessDenied
[ 6738, 764, 1069, 11755, 1330, 8798, 21306, 798, 628 ]
4.222222
9
import os from bs4 import BeautifulSoup import html2text import pandas data_dir = 'co2-coalition' data_text_dir = os.path.join(data_dir, 'text') data_file_name = 'co2-coalition.csv' html_converter = html2text.HTML2Text() html_converter.body_width = 0 html_converter.ignore_images = True f = open('html/faq.html', 'r') content = f.read() f.close() faq_soup = BeautifulSoup(content, 'html.parser') entries = { 'id' : [], 'title' : [], 'text_file_name' : [], } entry_index = 0 title = html_converter.handle(str(faq_soup.find('span', 'span-title2'))).strip() content = html_converter.handle(str(faq_soup.find('p', 'p1'))) text_file_name = make_file_name(entry_index) + '.txt' save_text(data_text_dir, text_file_name, content) entries['id'].append(entry_index) entries['title'].append(title) entries['text_file_name'].append(text_file_name) entry_index += 1 faq_entries_container = faq_soup.find('div', 'vc_tta-panels-container') faq_entries = faq_entries_container.find_all('div', 'vc_tta-panel') print(f'Found {len(faq_entries)} entries') for entry in faq_entries: title = get_text(entry, 'span', 'vc_tta-title-text', do_strip = True).capitalize() print(f' Entry {entry_index} : {title}') content = get_text(entry.find('div', 'vc_tta-panel-body'), 'div', 'wpb_wrapper') text_file_name = make_file_name(entry_index) + '.txt' save_text(data_text_dir, text_file_name, content) entries['id'].append(entry_index) entries['title'].append(title) entries['text_file_name'].append(text_file_name) entry_index += 1 d = pandas.DataFrame(entries) d.to_csv(data_file_name, index = False)
[ 11748, 28686, 198, 198, 6738, 275, 82, 19, 1330, 23762, 50, 10486, 198, 11748, 27711, 17, 5239, 198, 11748, 19798, 292, 198, 198, 7890, 62, 15908, 796, 705, 1073, 17, 12, 25140, 653, 6, 198, 7890, 62, 5239, 62, 15908, 796, 28686, 13...
2.506173
648
import random
[ 11748, 4738, 198 ]
4.666667
3
"""Test functions for FOOOF analysis.""" import numpy as np from fooof.analysis import * ################################################################################################### ###################################################################################################
[ 37811, 14402, 5499, 329, 376, 6684, 19238, 3781, 526, 15931, 198, 198, 11748, 299, 32152, 355, 45941, 198, 198, 6738, 22944, 1659, 13, 20930, 1330, 1635, 198, 198, 29113, 29113, 29113, 21017, 198, 29113, 29113, 29113, 21017, 198 ]
7.684211
38
import math # The code is based on from http://www.cs.cmu.edu/~ckingsf/class/02713-s13/src/mst.py # Heap item # d-ary Heap
[ 11748, 10688, 198, 198, 2, 383, 2438, 318, 1912, 319, 422, 2638, 1378, 2503, 13, 6359, 13, 11215, 84, 13, 15532, 14, 93, 694, 654, 69, 14, 4871, 14, 44698, 1485, 12, 82, 1485, 14, 10677, 14, 76, 301, 13, 9078, 198, 198, 2, 679, ...
1.958904
73
#!/usr/bin/env python # coding: utf-8 # In[5]: import cv2 import numpy as np imagen = cv2.imread('wheel.png') gray = cv2.cvtColor(imagen,cv2.COLOR_BGR2GRAY) _,th = cv2.threshold(gray,100,255,cv2.THRESH_BINARY) #Para versiones OpenCV3: img1,contornos1,hierarchy1 = cv2.findContours(th, cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE) img2,contornos2,hierarchy2 = cv2.findContours(th, cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) cv2.drawContours(imagen, contornos1, -1, (0,0,255), 2) print ('len(contornos1[2])=',len(contornos1[2])) print ('len(contornos2[2])=',len(contornos2[2])) cv2.imshow('imagen',imagen) cv2.imshow('th',th) cv2.waitKey(0) cv2.destroyAllWindows() # In[ ]:
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 19617, 25, 3384, 69, 12, 23, 198, 198, 2, 554, 58, 20, 5974, 628, 198, 11748, 269, 85, 17, 198, 11748, 299, 32152, 355, 45941, 198, 198, 320, 11286, 796, 269, 85, 17, 13, 320,...
2.00295
339
# -*- coding: utf-8 -*- ############################################################# # Copyright (c) 2020-2021 Maurice Karrenbrock # # # # This software is open-source and is distributed under the # # BSD 3-Clause "New" or "Revised" License # ############################################################# """functions to combine bound and unbound works """ import numpy as np def combine_non_correlated_works(works_1, works_2): """combines 2 non correlated sets of work values If you have 2 set of work values (for example bound and unbound in the case of vDSSB) that are un correlated you can combine them in order to get N * M resulting works. It is equivalent to convoluting the 2 probability distributions. Parameters ------------ works_1 : numpy.array the first set of works values to combine works_2 : numpy.array the second set of works values to combine Returns ----------- numpy.array : a 1-D array N * M long containing the combined work values Notes --------- for more information check out this paper: Virtual Double-System Single-Box: A Nonequilibrium Alchemical Technique for Absolute Binding Free Energy Calculations: Application to Ligands of the SARS-CoV-2 Main Protease Marina Macchiagodena, Marco Pagliai, Maurice Karrenbrock, Guido Guarnieri, Francesco Iannone, and Piero Procacci Journal of Chemical Theory and Computation 2020 16 (11), 7160-7172 DOI: 10.1021/acs.jctc.0c00634 section 2 "THEORETICAL BACKGROUND" """ #empty array N*M long output_array = np.empty([works_1.size * works_2.size]) len_works_2 = len(works_2) i = 0 iterator_1 = np.nditer(works_1) for value_1 in iterator_1: cutoff = i * len_works_2 output_array[cutoff:cutoff + len_works_2] = value_1 + works_2[:] i += 1 return output_array
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 29113, 14468, 7804, 4242, 2, 198, 2, 15069, 357, 66, 8, 12131, 12, 1238, 2481, 32839, 9375, 918, 7957, 694, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 22...
2.696118
747
import torch import torch.nn as nn import torch.nn.functional as F import os import sys BASE_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.append(BASE_DIR) import pointnet2_utils import pytorch_utils as pt_utils from typing import List if __name__ == '__main__': radius = 1 nsamples = 4 in_channels = 128 out_channels = 256 lstm = PointLSTMCell(radius, nsamples, in_channels, out_channels).to('cuda') batch_size = 32 npoints = 1024 P1 = torch.zeros([batch_size, npoints, 3], dtype=torch.float32).to('cuda') X1 = torch.zeros([batch_size, in_channels, npoints], dtype=torch.float32).to('cuda') P2 = torch.zeros([batch_size, npoints, 3], dtype=torch.float32).to('cuda') H2 = torch.zeros([batch_size, out_channels, npoints], dtype=torch.float32).to('cuda') C2 = torch.zeros([batch_size, out_channels, npoints], dtype=torch.float32).to('cuda') P1, H1, C1 = lstm((P1, X1), (P2, H2, C2)) print(P1.shape) print(H1.shape) print(C1.shape)
[ 11748, 28034, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 11748, 28034, 13, 20471, 13, 45124, 355, 376, 198, 198, 11748, 28686, 198, 11748, 25064, 198, 33, 11159, 62, 34720, 796, 28686, 13, 6978, 13, 15908, 3672, 7, 418, 13, 6978...
2.320366
437
from django import forms ''' javascriptChoices = ((2,"Keep Javascript",),(1,"Remove Some Javascript"),(0,"Remove All Javascript")) keepJavascript = forms.ChoiceField(choices=javascriptChoices,label=" Website Javascript") '''
[ 6738, 42625, 14208, 1330, 5107, 198, 7061, 6, 198, 220, 220, 220, 44575, 22164, 1063, 796, 14808, 17, 553, 15597, 24711, 1600, 828, 7, 16, 553, 27914, 2773, 24711, 12340, 7, 15, 553, 27914, 1439, 24711, 48774, 198, 220, 220, 220, 1394...
3.492537
67
from flexmeasures.app import create as create_app application = create_app()
[ 6738, 7059, 47336, 13, 1324, 1330, 2251, 355, 2251, 62, 1324, 198, 198, 31438, 796, 2251, 62, 1324, 3419, 198 ]
3.9
20
from ctypes import Structure, Union, c_int, c_byte, c_char_p # Inner union
[ 6738, 269, 19199, 1330, 32522, 11, 4479, 11, 269, 62, 600, 11, 269, 62, 26327, 11, 269, 62, 10641, 62, 79, 628, 198, 2, 24877, 6441, 628 ]
2.888889
27
# -*- coding: utf-8 -*- # Copy this file and renamed it settings.py and change the values for your own project # The csv file containing the information about the member. # There is three columns: The name, the email and the member type: 0 regular, 1 life time CSV_FILE = "path to csv file" # The svg file for regular member. {name} and {email} are going to be replaced with the corresponding values from the # csv file SVG_FILE_REGULAR = "path to svg regular member file" # Same as SVG_FILE_REGULAR but for life time member SVG_FILE_LIFE_TIME = "path to svg life time member file" # Destination folder where the member cards will be generated. If the folder does not exist yet it will be created. DEST_GENERATED_FOLDER = "path to folder that will contain the generated files" # The message file used as the text body for the email message. UTF-8. MSG_FILE = "/Users/pierre/Documents/LPA/CA/carte_membre_msg" # SMTP configuration SMPT_HOST = "myserver.com" SMPT_PORT = 587 SMTP_USER = "user_name" SMTP_PASSWORD = "password" # Email configuration EMAIL_FROM = "some_email@something.com" EMAIL_SUBJECT = "subject" EMAIL_PDF = "name of attachment file.pdf"
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 2, 17393, 428, 2393, 290, 25121, 340, 6460, 13, 9078, 290, 1487, 262, 3815, 329, 534, 898, 1628, 198, 198, 2, 383, 269, 21370, 2393, 7268, 262, 1321, 546, 262, ...
3.183562
365
"""the names of companies which filed fields with certain words in them""" from df_wrappers import facts_stringquery def main(): """example code lives in one function""" # this one is easier in the script language query_string = """ filingsource:"Korea FSS" AND fieldname:(hedge OR (foreign AND exchange) OR (interest AND rate)) """ # send off the query resp_data = facts_stringquery(query_string, False) # keep unique list of company names from results name_list = {x['source']['companyname'] for x in resp_data['hits']} for name in name_list: print(str(name)) main() # eof
[ 37811, 1169, 3891, 286, 2706, 543, 5717, 7032, 351, 1728, 2456, 287, 606, 37811, 198, 198, 6738, 47764, 62, 29988, 11799, 1330, 6419, 62, 8841, 22766, 198, 198, 4299, 1388, 33529, 198, 220, 220, 220, 37227, 20688, 2438, 3160, 287, 530, ...
3.028708
209
DEBUG = False from typing import List, Tuple
[ 30531, 796, 10352, 198, 198, 6738, 19720, 1330, 7343, 11, 309, 29291, 198 ]
3.538462
13
""" db_triggers.py ~~~~~~~~~~~~~~ :aciklama: Veritabanina veri girisi ve gerekli triggerlar icin :yazar: github.com/serong """ import sqlite3 import db as saydb
[ 37811, 198, 220, 220, 220, 20613, 62, 2213, 328, 5355, 13, 9078, 198, 220, 220, 220, 220, 15116, 8728, 4907, 628, 220, 220, 220, 1058, 330, 1134, 75, 1689, 25, 198, 220, 220, 220, 220, 220, 220, 220, 4643, 270, 45094, 1437, 3326, ...
2.277108
83
import contextlib import os import pickle import numpy as np from itertools import product, starmap import multiprocessing import tqdm import sys if sys.platform.startswith("linux"): is_linux = True import tempfile else: is_linux = False import mmap # import pyina.launchers # from pyina.ez_map import ez_map # TODO: Convert utils.py module to use pathlib module def make_dir(path): """Makes a new directory at the provided path only if it doesn't already exist. Parameters ---------- path : str The path of the directory to make """ if not os.path.exists(path): os.makedirs(path) return os.path.abspath(path) def files_in_dir(path): """Searches a path for all files Parameters ---------- path : str The directory path to check for files Returns ------- list list of all files and subdirectories in the input path (excluding . and ..) """ return sorted(os.listdir(path)) def tifs_in_dir(path): """Searches input path for tif files Parameters ---------- path : str path of the directory to check for tif images Returns ------- tif_paths : list list of paths to tiffs in path tif_filenames : list list of tiff filenames (with the extension) in path """ abspath = os.path.abspath(path) files = files_in_dir(abspath) tif_paths = [] tif_filenames = [] for f in files: if f.endswith('.tif') or f.endswith('.tiff'): tif_paths.append(os.path.join(abspath, f)) tif_filenames.append(f) return tif_paths, tif_filenames def load_metadata(path): """Loads a metadata.pkl file within provided path Parameters ---------- path : str path of a directory containing a 'metadata.pkl' file Returns ------- dict dictionary containing the stored metadata """ return pickle_load(os.path.join(path, 'metadata.pkl')) def pickle_save(path, data): """Pickles data and saves it to provided path Parameters ---------- path : str path of the pickle file to create / overwrite data : dict dictionary with data to be pickled """ with open(path, 'wb') as f: pickle.dump(data, f, pickle.HIGHEST_PROTOCOL) def pickle_load(path): """Un-pickles a file provided at the input path Parameters ---------- path : str path of the pickle file to read Returns ------- dict data that was stored in the input pickle file """ with open(path, 'rb') as f: return pickle.load(f) def chunk_dims(img_shape, chunk_shape): """Calculate the number of chunks needed for a given image shape Parameters ---------- img_shape : tuple whole image shape chunk_shape : tuple individual chunk shape Returns ------- nb_chunks : tuple a tuple containing the number of chunks in each dimension """ return tuple(int(np.ceil(i/c)) for i, c in zip(img_shape, chunk_shape)) def chunk_coordinates(shape, chunks): """Calculate the global coordaintes for each chunk's starting position Parameters ---------- shape : tuple shape of the image to chunk chunks : tuple shape of each chunk Returns ------- start_coords : ndarray the starting indices of each chunk """ nb_chunks = chunk_dims(shape, chunks) start = [] for indices in product(*tuple(range(n) for n in nb_chunks)): start.append(tuple(i*c for i, c in zip(indices, chunks))) return np.asarray(start) def box_slice_idx(start, stop): """Creates an index tuple for a bounding box from `start` to `stop` using slices Parameters ---------- start : array-like index of box start stop : array-like index of box stop (index not included in result) Returns ------- idx : tuple index tuple for bounding box """ return tuple(np.s_[a:b] for a, b in zip(start, stop)) def extract_box(arr, start, stop): """Indexes `arr` from `start` to `stop` Parameters ---------- arr : array-like or SharedMemory input array to index start : array-like starting index of the slice stop : array-like ending index of the slice. The element at this index is not included. Returns ------- box : ndarray resulting box from `arr` """ idx = box_slice_idx(start, stop) if isinstance(arr, SharedMemory): with arr.txn() as a: box = a[idx] else: box = arr[idx] return box def insert_box(arr, start, stop, data): """Indexes `arr` from `start` to `stop` and inserts `data` Parameters ---------- arr : array-like input array to index start : array-like starting index of the slice stop : array-like ending index of the slice. The element at this index is not included. data : array-like sub-array to insert into `arr` Returns ------- box : ndarray resulting box from `arr` """ idx = box_slice_idx(start, stop) if isinstance(arr, SharedMemory): with arr.txn() as a: a[idx] = data else: arr[idx] = data return arr def pmap_chunks(f, arr, chunks=None, nb_workers=None, use_imap=False): """Maps a function over an array in parallel using chunks The function `f` should take a reference to the array, a starting index, and the chunk size. Since each subprocess is handling it's own indexing, any overlapping should be baked into `f`. Caution: `arr` may get copied if not using memmap. Use with SharedMemory or Zarr array to avoid copies. Parameters ---------- f : callable function with signature f(arr, start_coord, chunks). May need to use partial to define other args. arr : array-like an N-dimensional input array chunks : tuple, optional the shape of chunks to use. Default tries to access arr.chunks and falls back to arr.shape nb_workers : int, optional number of parallel processes to apply f with. Default, cpu_count use_imap : bool, optional whether or not to use imap instead os starmap in order to get an iterator for tqdm. Note that this requires input tuple unpacking manually inside of `f`. Returns ------- result : list list of results for each chunk """ if chunks is None: try: chunks = arr.chunks except AttributeError: chunks = arr.shape if nb_workers is None: nb_workers = multiprocessing.cpu_count() start_coords = chunk_coordinates(arr.shape, chunks) args_list = [] for i, start_coord in enumerate(start_coords): args = (arr, start_coord, chunks) args_list.append(args) if nb_workers > 1: with multiprocessing.Pool(processes=nb_workers) as pool: if use_imap: results = list(tqdm.tqdm(pool.imap(f, args_list), total=len(args_list))) else: results = list(pool.starmap(f, args_list)) else: if use_imap: results = list(tqdm.tqdm(map(f, args_list), total=len(args_list))) else: results = list(starmap(f, args_list)) return results def read_voxel_size(path, micron=True): """Reads in the voxel size stored in `path` CSV file with voxel dimensions in nanometers :param path: path to CSV file containing integer values of voxel dimensions in nanometers :param micron: Flag to return nanometers or micron :return: voxel_size tuple in same order as in CSV """ with open(path, mode='r') as f: line = f.readline().split('\n')[0] dims = line.split(',') voxel_size = tuple([int(d) / 1000 for d in dims]) return voxel_size # mapper = None # # # def parallel_map(fn, args): # """Map a function over an argument list, returning one result per arg # # Parameters # ---------- # fn : callable # the function to execute # args : list # a list of the single argument to send through the function per invocation # # Returns # ------- # list # a list of results # # Notes # ----- # The mapper is configured by two environment variables: # # PHATHOM_MAPPER - this is the name of one of the mapper classes. Typical # choices are MpiPool or MpiScatter for OpenMPI and # SlurmPool or SlurmScatter for SLURM. By default, it # uses the serial mapper which runs on a single thread. # # PHATHOM_NODES - this is the number of nodes that should be used in # parallel. # # By default, a serial mapper is returned if there is no mapper. # # Examples # -------- # myresults = parallel_map(my_function, my_inputs) # # """ # global mapper # # if mapper is None: # if "PHATHOM_MAPPER" in os.environ: # mapper_name = os.environ["PHATHOM_MAPPER"] # mapper_class = getattr(pyina.launchers, mapper_name) # if "PHATHOM_NODES" in os.environ: # nodes = os.environ["PHATHOM_NODES"] # mapper = mapper_class(nodes) # else: # mapper = mapper_class() # else: # mapper = pyina.launchers.SerialMapper() # # return mapper.map(fn, args) def shared_memory_to_zarr(memory, zarr, pool, offset, start=None, stop=None): """ Copy memory to ZARR array. Note: offset, start and stop must be on chunk boundaries of the zarr array :param memory: the memory array to copy to zarr :param zarr: the zarr array :param offset: the 3-tuple offset of the destination for the memory in the zarr array :param start: the 3-tuple start coordinates of the memory :param stop: the 3-tuple stop coordinates of the memory :param pool: the multiprocessing pool to use """ chunksize = zarr.chunks shape = memory.shape all_starts, all_stops = get_chunk_coords(chunksize, shape, start, stop) args = [(memory, zarr, offset, a, b) for a, b in zip(all_starts, all_stops)] pool.starmap(write_one_zarr, args) def get_chunk_coords(chunksize, shape, start, stop): """ Get a sequence of chunk start coordinates and stop coordinates, given a volume delimited by start and stop coordinates :param chunksize: the size of a chunk in the zarr or blockfs array :param shape: the shape of the zarr or blockfs array to handle edge case :param start: a three-tuple of start coordinates, on a chunk boundary :param stop: a three-tuple of stop coordinates, on a chunk boundary :return: a sequence/iterator of start coordinates and of stop coordinates giving the dimensions for each chunk in the volume """ if start is None: start = (0, 0, 0) if stop is None: stop = shape starts = [np.arange(a, b, c) for a, b, c in zip(start, stop, chunksize)] stops = [np.minimum(a + b, c) for a, b, c in zip(starts, chunksize, shape)] all_starts = product(*starts) all_stops = product(*stops) return all_starts, all_stops def memory_to_blockfs(memory, blockfs_dir, offset, start=None, stop=None): """ Write a block of memory to a Blockfs directory :param memory: the memory to be written :param blockfs_dir: the BlockFS directory to be written to. This must be opened and the writer processes must have been started. :param offset: the offset into the blockfs of the memory (a 3-tuple) :param start: a three-tuple of start coordinates within the memory. Default is from the start of memory. :param stop: a three-tuple of stop coordinates within the memory. Default is to the end of memory. """ chunksize = (blockfs_dir.z_block_size, blockfs_dir.y_block_size, blockfs_dir.x_block_size) shape = memory.shape for (z0, y0, x0), (z1, y1, x1) in zip(*get_chunk_coords( chunksize, shape, start, stop)): blockfs_dir.write_block(memory[z0:z1, y0:y1, x0:x1], x0 + offset[2], y0+offset[1], z0+offset[0])
[ 11748, 4732, 8019, 198, 11748, 28686, 198, 11748, 2298, 293, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 340, 861, 10141, 1330, 1720, 11, 336, 1670, 499, 198, 11748, 18540, 305, 919, 278, 198, 11748, 256, 80, 36020, 198, 11748, 25064...
2.502234
4,924
from .result import Result import numpy as np import pandas as pd
[ 6738, 764, 20274, 1330, 25414, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 628, 628, 628, 198 ]
3.272727
22
i = 0 while (i<119): print(i) i+=10
[ 72, 796, 657, 220, 198, 198, 4514, 357, 72, 27, 16315, 2599, 198, 220, 220, 220, 3601, 7, 72, 8, 198, 220, 220, 220, 1312, 47932, 940, 198, 220, 220, 198 ]
1.580645
31
import numpy as np import unittest import coremltools.models.datatypes as datatypes from coremltools.models import neural_network as neural_network from coremltools.models import MLModel from coremltools.models.neural_network.printer import print_network_spec from coremltools.converters.nnssa.coreml.graph_pass.mlmodel_passes import \ remove_disconnected_layers, transform_conv_crop, remove_redundant_transposes import copy import pytest DEBUG = False np.random.seed(100) if __name__ == '__main__': RUN_ALL_TESTS = True if RUN_ALL_TESTS: unittest.main() else: suite = unittest.TestSuite() suite.addTest(MLModelPassesTest('test_load_constant_remove')) unittest.TextTestRunner().run(suite)
[ 11748, 299, 32152, 355, 45941, 198, 11748, 555, 715, 395, 198, 11748, 4755, 76, 2528, 10141, 13, 27530, 13, 19608, 265, 9497, 355, 4818, 265, 9497, 198, 6738, 4755, 76, 2528, 10141, 13, 27530, 1330, 17019, 62, 27349, 355, 17019, 62, 2...
2.638298
282
# Generated by Django 2.1.7 on 2019-04-03 11:56 from django.db import migrations, models import django.db.models.deletion
[ 2, 2980, 515, 416, 37770, 362, 13, 16, 13, 22, 319, 13130, 12, 3023, 12, 3070, 1367, 25, 3980, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 198, 11748, 42625, 14208, 13, 9945, 13, 27530, 13, 2934, 1616, 295, ...
2.818182
44
from puretabix import get_bgzip_lines_parallel
[ 6738, 5899, 8658, 844, 1330, 651, 62, 35904, 13344, 62, 6615, 62, 1845, 29363, 628 ]
3.2
15
from setuptools import find_packages, setup setup( name="datapool_client", version="1.0", description="Designed to access the datapool software developed by ETH Zurich - SIS and Eawag. " "Find out more under https://datapool.readthedocs.io/en/latest/.", author="Christian Foerster", author_email="christian.foerster@eawag.ch", license="MIT Licence", classifiers=[ "Intended Audience :: Science/Research", "Intended Audience :: Developers", "Programming Language :: Python :: 3.9", ], install_requires=[ "pandas", "numpy", "psycopg2-binary", "matplotlib", "cufflinks", "plotly", "pyparsing==2.4.7", "sqlalchemy", "tqdm" ], keywords="datapool_client, eawag, postgres", packages=find_packages(), include_package_data=True, )
[ 6738, 900, 37623, 10141, 1330, 1064, 62, 43789, 11, 9058, 198, 198, 40406, 7, 198, 220, 220, 220, 1438, 2625, 19608, 499, 970, 62, 16366, 1600, 198, 220, 220, 220, 2196, 2625, 16, 13, 15, 1600, 198, 220, 220, 220, 6764, 2625, 5960, ...
2.256997
393
from mandaw import * mandaw = Mandaw("Window!", width = 800, height = 600, bg_color = (0, 0, 0, 255)) mandaw.loop()
[ 6738, 6855, 707, 1330, 1635, 198, 198, 22249, 707, 796, 13314, 707, 7203, 27703, 40754, 9647, 796, 10460, 11, 6001, 796, 10053, 11, 275, 70, 62, 8043, 796, 357, 15, 11, 657, 11, 657, 11, 14280, 4008, 198, 198, 22249, 707, 13, 26268,...
2.659091
44
import numpy as np with open("./dice.txt",'r') as f: input_str = f.read() input_data=list(map(int,input_str)) inf = -float('inf') N = len(input_data)-1 K = 2 trans_p = np.array([[0.95,0.1],[0.05,0.9]]) dice_p = np.array([[1/6,1/6,1/6,1/6,1/6,1/6],[1/10,1/10,1/10,1/10,1/10,1/2]]) transition_t = np.log(trans_p) dice_t = np.log(dice_p) X = np.array([[box() for l in range(K)] for k in range(N+1)]) run_viterbi(N,0) with open('./dice_result.txt','w') as f: f.write("Eyes of dice{}".format(input_str)) f.write("\n") f.write("Anticipation is following \n") trace(N,0)
[ 11748, 299, 32152, 355, 45941, 198, 198, 4480, 1280, 7, 1911, 14, 67, 501, 13, 14116, 1600, 6, 81, 11537, 355, 277, 25, 198, 220, 220, 220, 5128, 62, 2536, 796, 277, 13, 961, 3419, 198, 220, 220, 220, 5128, 62, 7890, 28, 4868, 7...
1.916129
310
from unittest import TestCase from parameterized import parameterized from scheduling.schedule_config import ScheduleConfig from utils import date_utils
[ 6738, 555, 715, 395, 1330, 6208, 20448, 198, 198, 6738, 11507, 1143, 1330, 11507, 1143, 198, 198, 6738, 26925, 13, 15952, 5950, 62, 11250, 1330, 19281, 16934, 198, 6738, 3384, 4487, 1330, 3128, 62, 26791, 628, 198 ]
4.243243
37
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import math import unittest # Generated files # pylint: disable=F0401 import sample_service_mojom import test_constants_mojom
[ 2, 15069, 1946, 383, 18255, 1505, 46665, 13, 1439, 2489, 10395, 13, 198, 2, 5765, 286, 428, 2723, 2438, 318, 21825, 416, 257, 347, 10305, 12, 7635, 5964, 326, 460, 307, 198, 2, 1043, 287, 262, 38559, 24290, 2393, 13, 198, 198, 11748...
3.372093
86
import requests, lxml.html, re import htmlentitydefs, urllib, random from lxml.cssselect import CSSSelector from StringIO import StringIO import cherrypy import requests from cachecontrol import CacheControl _PROXY_LIST = None _HEADERS = { 'accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'accept-language':'en-GB,en-US;q=0.8,en;q=0.6', 'cache-control':'max-age=0', #'user-agent':'Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36', 'user-agent':'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A356 Safari/604.1', 'Client-ID':'tq6hq1srip0i37ipzuscegt7viex9fh' # Just for Twitch API } MOVIE_RE = re.compile(r'(.*)[\(\[]?([12][90]\d\d)[^pP][\(\[]?.*$') SERIES_RE = re.compile(r'(.*)S(\d\d)E(\d\d).*$')
[ 11748, 7007, 11, 300, 19875, 13, 6494, 11, 302, 198, 11748, 27711, 26858, 4299, 82, 11, 2956, 297, 571, 11, 4738, 198, 6738, 300, 19875, 13, 25471, 19738, 1330, 17391, 17563, 273, 198, 6738, 10903, 9399, 1330, 10903, 9399, 198, 11748, ...
2.273902
387
# 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 mango import unittest
[ 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 345, 743, 407, 198, 2, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 921, 743, 7330, 257, 4866, 286, 198, 2, 262, 13789, 379, 198, 2,...
3.897959
147
from http import HTTPStatus from unittest import TestCase, mock import jwt from fastapi.testclient import TestClient from src.api.review_resource import REVIEWS from src.config import config from src.main import app from src.models.article import Article from src.models.review import Review
[ 6738, 2638, 1330, 14626, 19580, 198, 6738, 555, 715, 395, 1330, 6208, 20448, 11, 15290, 198, 198, 11748, 474, 46569, 198, 6738, 3049, 15042, 13, 9288, 16366, 1330, 6208, 11792, 198, 198, 6738, 12351, 13, 15042, 13, 19023, 62, 31092, 133...
3.78481
79
import json sequence_name_list = ['A','G','L','map2photo','S'] description_list = ['Viewpoint Appearance','Viewpoint','ViewPoint Lighting','Map to Photo','Modality'] label_list = [ ['arch', 'obama', 'vprice0', 'vprice1', 'vprice2', 'yosemite'], ['adam', 'boat','ExtremeZoomA','face','fox','graf','mag','shop','there','vin'], ['amos1','bdom','brugge_square', 'GC2','light','madrid',\ 'notredame15','paintedladies','rushmore','trevi','vatican'], ['map1', 'map2', 'map3', 'map4', 'map5', 'map6'], ['angiogram','brain1','EO-IR-2',\ 'maunaloa','mms68','mms75','treebranch'] ] #label_list = [ # ['arch', 'obama', 'vprice0', 'vprice1', 'vprice2', 'yosemite'] # ] json_data = {} json_data['Dataset Name'] = 'W1BS' json_data['Description'] = 'Baseline Stereo Benchmark' json_data['url'] = 'http://cmp.felk.cvut.cz/wbs/datasets/W1BS_with_patches.tar.gz' json_data['Sequence Number'] = len(sequence_name_list) json_data['Sequence Name List'] = sequence_name_list json_data['Sequences'] = [] for idx, sequence_name in enumerate(sequence_name_list): sequence = {} sequence['Name'] = sequence_name sequence['Description'] = sequence_name sequence['Label'] = description_list[idx] sequence['Images'] = [] sequence['Image Number'] = len(label_list[idx])*2 sequence['Link Number'] = len(label_list[idx]) sequence['Links'] = [] for image_idx, image_label in enumerate(label_list[idx]): image = {} image['file'] = '{}/1/{}.bmp'.format(sequence_name,image_label) image['id'] = str(image_label) + '_1' image['label'] = str(image_label) + '_1' sequence['Images'].append(image) image = {} image['file'] = '{}/2/{}.bmp'.format(sequence_name,image_label) image['id'] = str(image_label) + '_2' image['label'] = str(image_label) + '_2' sequence['Images'].append(image) link = {} link['source'] = str(image_label) + '_1' link['target'] = str(image_label) + '_2' link['file'] = '{}/h/{}.txt'.format(sequence_name, image_label) sequence['Links'].append(link) json_data['Sequences'].append(sequence) with open('./datasets/dataset_info/{}.json'.format('W1BS'),'w') as json_file: json.dump(json_data, json_file, indent=2)
[ 11748, 33918, 198, 198, 43167, 62, 3672, 62, 4868, 796, 37250, 32, 41707, 38, 41707, 43, 41707, 8899, 17, 23074, 41707, 50, 20520, 198, 11213, 62, 4868, 796, 37250, 7680, 4122, 43436, 41707, 7680, 4122, 41707, 7680, 12727, 43150, 41707, ...
2.301075
1,023
<html> salman.py <html/>
[ 27, 6494, 29, 3664, 805, 13, 9078, 198, 198, 27, 6494, 15913, 220, 198 ]
1.928571
14
from pyrogram import Client ,filters import os from helper.database import getid ADMIN = int(os.environ.get("ADMIN", 1696230986))
[ 6738, 12972, 39529, 1330, 20985, 837, 10379, 1010, 198, 11748, 28686, 198, 6738, 31904, 13, 48806, 1330, 651, 312, 198, 2885, 23678, 796, 493, 7, 418, 13, 268, 2268, 13, 1136, 7203, 2885, 23678, 1600, 1467, 4846, 19214, 49087, 4008, 628...
3.195122
41
# Calibration methods including Histogram Binning and Temperature Scaling import numpy as np from scipy.optimize import minimize from sklearn.metrics import log_loss import pandas as pd import time from sklearn.metrics import log_loss, brier_score_loss from tensorflow.keras.losses import categorical_crossentropy from os.path import join import sklearn.metrics as metrics # Imports to get "utility" package import sys from os import path sys.path.append( path.dirname( path.dirname( path.abspath("utility") ) ) ) from utility.unpickle_probs import unpickle_probs from utility.evaluation import ECE, MCE def softmax(x): """ Compute softmax values for each sets of scores in x. Parameters: x (numpy.ndarray): array containing m samples with n-dimensions (m,n) Returns: x_softmax (numpy.ndarray) softmaxed values for initial (m,n) array """ e_x = np.exp(x - np.max(x)) return e_x / e_x.sum(axis=1, keepdims=1) def evaluate(probs, y_true, verbose = False, normalize = False, bins = 15): """ Evaluate model using various scoring measures: Error Rate, ECE, MCE, NLL, Brier Score Params: probs: a list containing probabilities for all the classes with a shape of (samples, classes) y_true: a list containing the actual class labels verbose: (bool) are the scores printed out. (default = False) normalize: (bool) in case of 1-vs-K calibration, the probabilities need to be normalized. bins: (int) - into how many bins are probabilities divided (default = 15) Returns: (error, ece, mce, loss, brier), returns various scoring measures """ preds = np.argmax(probs, axis=1) # Take maximum confidence as prediction if normalize: confs = np.max(probs, axis=1)/np.sum(probs, axis=1) # Check if everything below or equal to 1? else: confs = np.max(probs, axis=1) # Take only maximum confidence accuracy = metrics.accuracy_score(y_true, preds) * 100 error = 100 - accuracy # Calculate ECE ece = ECE(confs, preds, y_true, bin_size = 1/bins) # Calculate MCE mce = MCE(confs, preds, y_true, bin_size = 1/bins) loss = log_loss(y_true=y_true, y_pred=probs) y_prob_true = np.array([probs[i, idx] for i, idx in enumerate(y_true)]) # Probability of positive class brier = brier_score_loss(y_true=y_true, y_prob=y_prob_true) # Brier Score (MSE) if verbose: print("Accuracy:", accuracy) print("Error:", error) print("ECE:", ece) print("MCE:", mce) print("Loss:", loss) print("brier:", brier) return (error, ece, mce, loss, brier) def cal_results(fn, path, files, m_kwargs = {}, approach = "all"): """ Calibrate models scores, using output from logits files and given function (fn). There are implemented to different approaches "all" and "1-vs-K" for calibration, the approach of calibration should match with function used for calibration. TODO: split calibration of single and all into separate functions for more use cases. Params: fn (class): class of the calibration method used. It must contain methods "fit" and "predict", where first fits the models and second outputs calibrated probabilities. path (string): path to the folder with logits files files (list of strings): pickled logits files ((logits_val, y_val), (logits_test, y_test)) m_kwargs (dictionary): keyword arguments for the calibration class initialization approach (string): "all" for multiclass calibration and "1-vs-K" for 1-vs-K approach. Returns: df (pandas.DataFrame): dataframe with calibrated and uncalibrated results for all the input files. """ df = pd.DataFrame(columns=["Name", "Error", "ECE", "MCE", "Loss", "Brier"]) total_t1 = time.time() for i, f in enumerate(files): name = "_".join(f.split("_")[1:-1]) print(name) t1 = time.time() FILE_PATH = join(path, f) (logits_val, y_val), (logits_test, y_test) = unpickle_probs(FILE_PATH) if approach == "all": y_val = y_val.flatten() model = fn(**m_kwargs) model.fit(logits_val, y_val) probs_val = model.predict(logits_val) probs_test = model.predict(logits_test) error, ece, mce, loss, brier = evaluate(softmax(logits_test), y_test, verbose=True) # Test before scaling error2, ece2, mce2, loss2, brier2 = evaluate(probs_test, y_test, verbose=False) print("Error %f; ece %f; mce %f; loss %f, brier %f" % evaluate(probs_val, y_val, verbose=False, normalize=True)) else: # 1-vs-k models probs_val = softmax(logits_val) # Softmax logits probs_test = softmax(logits_test) K = probs_test.shape[1] # Go through all the classes for k in range(K): # Prep class labels (1 fixed true class, 0 other classes) y_cal = np.array(y_val == k, dtype="int")[:, 0] # Train model model = fn(**m_kwargs) model.fit(probs_val[:, k], y_cal) # Get only one column with probs for given class "k" probs_val[:, k] = model.predict(probs_val[:, k]) # Predict new values based on the fittting probs_test[:, k] = model.predict(probs_test[:, k]) # Replace NaN with 0, as it should be close to zero # TODO is it needed? idx_nan = np.where(np.isnan(probs_test)) probs_test[idx_nan] = 0 idx_nan = np.where(np.isnan(probs_val)) probs_val[idx_nan] = 0 # Get results for test set error, ece, mce, loss, brier = evaluate(softmax(logits_test), y_test, verbose=True, normalize=False) error2, ece2, mce2, loss2, brier2 = evaluate(probs_test, y_test, verbose=False, normalize=True) print("Error %f; ece %f; mce %f; loss %f, brier %f" % evaluate(probs_val, y_val, verbose=False, normalize=True)) df.loc[i*2] = [name, error, ece, mce, loss, brier] df.loc[i*2+1] = [(name + "_calib"), error2, ece2, mce2, loss2, brier2] t2 = time.time() print("Time taken:", (t2-t1), "\n") total_t2 = time.time() print("Total time taken:", (total_t2-total_t1)) return df
[ 2, 2199, 571, 1358, 5050, 1390, 5590, 21857, 20828, 768, 290, 34467, 1446, 4272, 198, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 629, 541, 88, 13, 40085, 1096, 1330, 17775, 220, 198, 6738, 1341, 35720, 13, 4164, 10466, 1330, 2604, ...
2.217608
3,010
"""Module which implements various types of projections.""" from typing import List, Callable import tensorflow as tf from neuralmonkey.nn.utils import dropout def maxout(inputs: tf.Tensor, size: int, scope: str = "MaxoutProjection") -> tf.Tensor: """Apply a maxout operation. Implementation of Maxout layer (Goodfellow et al., 2013). http://arxiv.org/pdf/1302.4389.pdf z = Wx + b y_i = max(z_{2i-1}, z_{2i}) Arguments: inputs: A tensor or list of tensors. It should be 2D tensors with equal length in the first dimension (batch size) size: The size of dimension 1 of the output tensor. scope: The name of the scope used for the variables Returns: A tensor of shape batch x size """ with tf.variable_scope(scope): projected = tf.layers.dense(inputs, size * 2, name=scope) maxout_input = tf.reshape(projected, [-1, 1, 2, size]) maxpooled = tf.nn.max_pool( maxout_input, [1, 1, 2, 1], [1, 1, 2, 1], "SAME") reshaped = tf.reshape(maxpooled, [-1, size]) return reshaped def glu(input_: tf.Tensor, gating_fn: Callable[[tf.Tensor], tf.Tensor] = tf.sigmoid) -> tf.Tensor: """Apply a Gated Linear Unit. Gated Linear Unit - Dauphin et al. (2016). http://arxiv.org/abs/1612.08083 """ dimensions = input_.get_shape().as_list() if dimensions[-1] % 2 != 0: raise ValueError("Input size should be an even number") lin, nonlin = tf.split(input_, 2, axis=len(dimensions) - 1) return lin * gating_fn(nonlin)
[ 37811, 26796, 543, 23986, 2972, 3858, 286, 19887, 526, 15931, 198, 6738, 19720, 1330, 7343, 11, 4889, 540, 198, 11748, 11192, 273, 11125, 355, 48700, 198, 6738, 17019, 49572, 13, 20471, 13, 26791, 1330, 4268, 448, 628, 198, 4299, 3509, ...
2.400298
672
# properties detail please read \ # default_properties.py in dophon_properties module \ # inside your used dophon module package. # author: CallMeE
[ 2, 6608, 3703, 3387, 1100, 3467, 198, 2, 4277, 62, 48310, 13, 9078, 287, 288, 48982, 62, 48310, 8265, 3467, 198, 2, 2641, 534, 973, 288, 48982, 8265, 5301, 13, 198, 2, 1772, 25, 4889, 5308, 36, 198 ]
3.894737
38
from datetime import datetime from textwrap import shorten from typing import Optional, Union import discord from discord.abc import Messageable from discord.errors import Forbidden from discord.ext.commands import Bot, Cog, Context, check, command, is_owner from discord.utils import get from config import CONFIG from database import Afk as DbAfk from database import User as DbUser from database import get_user
[ 6738, 4818, 8079, 1330, 4818, 8079, 201, 198, 6738, 2420, 37150, 1330, 45381, 201, 198, 6738, 19720, 1330, 32233, 11, 4479, 201, 198, 201, 198, 11748, 36446, 201, 198, 6738, 36446, 13, 39305, 1330, 16000, 540, 201, 198, 6738, 36446, 13,...
3.581967
122
# The shape of the numbers for the dice dice = { 1: [[None, None, None], [None, "", None], [None, None, None]], 2: [["", None, None], [None, None, None], [None, None, ""]], 3: [["", None, None], [None, "", None], [None, None, ""]], 4: [["", None, ""], [None, None, None], ["", None, ""]], 5: [["", None, ""], [None, "", None], ["", None, ""]], 6: [["", None, ""], ["", None, ""], ["", None, ""]]} dice_cnt = 3
[ 2, 383, 5485, 286, 262, 3146, 329, 262, 17963, 198, 67, 501, 796, 1391, 352, 25, 16410, 14202, 11, 6045, 11, 6045, 4357, 685, 14202, 11, 366, 1600, 6045, 4357, 685, 14202, 11, 6045, 11, 6045, 60, 4357, 198, 220, 220, 220, 220, 220...
2.221675
203
from ..command.encrypt import EncryptionCommand
[ 198, 198, 6738, 11485, 21812, 13, 12685, 6012, 1330, 14711, 13168, 21575, 628 ]
3.923077
13
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2019-06-16 15:12 from __future__ import unicode_literals from django.db import migrations
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2980, 515, 416, 37770, 352, 13, 1157, 319, 13130, 12, 3312, 12, 1433, 1315, 25, 1065, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 198, 673...
2.754717
53
import time, datetime, argparse import os, sys import numpy as np np.set_printoptions(precision=2) import matplotlib.pyplot as plt import copy as cp import pickle PROJECT_PATH = '/home/nbuckman/Dropbox (MIT)/DRL/2020_01_cooperative_mpc/mpc-multiple-vehicles/' sys.path.append(PROJECT_PATH) import casadi as cas import src.MPC_Casadi as mpc import src.TrafficWorld as tw import src.IterativeBestResponseMPCMultiple as mibr import src.car_plotting_multiple as cmplot ########################################################## svo_theta = np.pi/4.0 # random_seed = args.random_seed[0] random_seed = 3 NEW = True if NEW: optional_suffix = "ellipses" subdir_name = datetime.datetime.now().strftime("%Y%m%d_%H%M%S") + optional_suffix folder = "results/" + subdir_name + "/" os.makedirs(folder) os.makedirs(folder+"imgs/") os.makedirs(folder+"data/") os.makedirs(folder+"vids/") os.makedirs(folder+"plots/") else: subdir_name = "20200224-103456_real_dim_CA" folder = "results/" + subdir_name + "/" print(folder) if random_seed > 0: np.random.seed(random_seed) ####################################################################### T = 3 # MPC Planning Horizon dt = 0.3 N = int(T/dt) #Number of control intervals in MPC n_rounds_mpc = 6 percent_mpc_executed = 0.5 ## This is the percent of MPC that is executed number_ctrl_pts_executed = int(np.floor(N*percent_mpc_executed)) XAMB_ONLY = False n_other = 2 n_rounds_ibr = 2 world = tw.TrafficWorld(2, 0, 1000) # large_world = tw.TrafficWorld(2, 0, 1000, 5.0) ######################################################################### actual_xamb = np.zeros((6, n_rounds_mpc*number_ctrl_pts_executed + 1)) actual_uamb = np.zeros((2, n_rounds_mpc*number_ctrl_pts_executed)) actual_xothers = [np.zeros((6, n_rounds_mpc*number_ctrl_pts_executed + 1)) for i in range(n_other)] actual_uothers = [np.zeros((2, n_rounds_mpc*number_ctrl_pts_executed)) for i in range(n_other)] actual_all_other_x0 = [np.zeros((6, 2*N)) for i in range(n_other)] xamb = np.zeros(shape=(6, N+1)) t_start_time = time.time() #################################################### ## Create the Cars in this Problem all_other_x0 = [] all_other_u = [] all_other_MPC = [] all_other_x = [np.zeros(shape=(6, N+1)) for i in range(n_other)] next_x0 = 0 for i in range(n_other): x1_MPC = mpc.MPC(dt) x1_MPC.n_circles = 3 x1_MPC.theta_iamb = svo_theta x1_MPC.N = N x1_MPC.k_change_u_v = 0.001 x1_MPC.max_delta_u = 50 * np.pi/180 * x1_MPC.dt x1_MPC.k_u_v = 0.01 x1_MPC.k_u_delta = .00001 x1_MPC.k_change_u_v = 0.01 x1_MPC.k_change_u_delta = 0.001 x1_MPC.k_s = 0 x1_MPC.k_x = 0 x1_MPC.k_x_dot = -1.0 / 100.0 x1_MPC.k_lat = 0.001 x1_MPC.k_lon = 0.0 x1_MPC.k_phi_error = 0.001 x1_MPC.k_phi_dot = 0.01 ####Vehicle Initial Conditions if i%2 == 0: lane_number = 0 next_x0 += x1_MPC.L + 2*x1_MPC.min_dist else: lane_number = 1 initial_speed = 0.75*x1_MPC.max_v traffic_world = world x1_MPC.fd = x1_MPC.gen_f_desired_lane(traffic_world, lane_number, True) x0 = np.array([next_x0, traffic_world.get_lane_centerline_y(lane_number), 0, 0, initial_speed, 0]).T ## Set the initial control of the other vehicles u1 = np.zeros((2,N)) # u1[0,:] = np.clip(np.pi/180 *np.random.normal(size=(1,N)), -2 * np.pi/180, 2 * np.pi/180) SAME_SIDE = False if lane_number == 1 or SAME_SIDE: u1[0,0] = 2 * np.pi/180 else: u1[0,0] = -2 * np.pi/180 u1[0,0] = 0 all_other_MPC += [x1_MPC] all_other_x0 += [x0] all_other_u += [u1] # Settings for Ambulance amb_MPC = cp.deepcopy(x1_MPC) amb_MPC.theta_iamb = 0.0 amb_MPC.k_u_v = 0.0000 amb_MPC.k_u_delta = .01 amb_MPC.k_change_u_v = 0.0000 amb_MPC.k_change_u_delta = 0 amb_MPC.k_s = 0 amb_MPC.k_x = 0 amb_MPC.k_x_dot = -1.0 / 100.0 amb_MPC.k_x = -1.0/100 amb_MPC.k_x_dot = 0 amb_MPC.k_lat = 0.00001 amb_MPC.k_lon = 0.0 # amb_MPC.min_v = 0.8*initial_speed amb_MPC.max_v = 35 * 0.447 # m/s amb_MPC.k_phi_error = 0.1 amb_MPC.k_phi_dot = 0.01 NO_GRASS = False amb_MPC.min_y = world.y_min amb_MPC.max_y = world.y_max if NO_GRASS: amb_MPC.min_y += world.grass_width amb_MPC.max_y -= world.grass_width amb_MPC.fd = amb_MPC.gen_f_desired_lane(world, 0, True) x0_amb = np.array([0, 0, 0, 0, initial_speed , 0]).T pickle.dump(x1_MPC, open(folder + "data/"+"mpc%d"%i + ".p",'wb')) pickle.dump(amb_MPC, open(folder + "data/"+"mpcamb" + ".p",'wb')) ######################################################################## #### SOLVE THE MPC ##################################################### for i_mpc in range(n_rounds_mpc): min_slack = np.infty actual_t = i_mpc * number_ctrl_pts_executed ###### Update the initial conditions for all vehicles if i_mpc > 0: x0_amb = xamb[:, number_ctrl_pts_executed] for i in range(len(all_other_x0)): all_other_x0[i] = all_other_x[i][:, number_ctrl_pts_executed] ###### Initial guess for the other u. This will be updated once the other vehicles ###### solve the best response to the ambulance. Initial guess just looks at the last solution. This could also be a lange change # Obtain a simulated trajectory from other vehicle control inputs all_other_x = [np.zeros(shape=(6, N+1)) for i in range(n_other)] all_other_x_des = [np.zeros(shape=(3, N+1)) for i in range(n_other)] for i in range(n_other): if i_mpc == 0: all_other_u[i] = np.zeros(shape=(6,N)) else: all_other_u[i] = np.concatenate((all_other_u[i][:, number_ctrl_pts_executed:], np.tile(all_other_u[i][:,-1:],(1, number_ctrl_pts_executed))),axis=1) ## x_mpci, u_all_i, x_0_i = all_other_MPC[i], all_other_u[i], all_other_x0[i] all_other_x[i], all_other_x_des[i] = x_mpci.forward_simulate_all(x_0_i, u_all_i) for i_rounds_ibr in range(n_rounds_ibr): ########## Solve the Ambulance MPC ########## response_MPC = amb_MPC response_x0 = x0_amb nonresponse_MPC_list = all_other_MPC nonresponse_x0_list = all_other_x0 nonresponse_u_list = all_other_u nonresponse_x_list = all_other_x nonresponse_xd_list = all_other_x_des ################# Generate the warm starts ############################### u_warm_profiles = mibr.generate_warm_u(N, response_MPC) ### Ambulance Warm Start if i_rounds_ibr > 0: # warm start with the solution from the last IBR round u_warm_profiles["previous"] = uamb else: # take the control inputs of the last MPC and continue the ctrl if i_mpc > 0: u_warm_profiles["previous"] = np.concatenate((uamb[:, number_ctrl_pts_executed:], np.tile(uamb[:,-1:],(1, number_ctrl_pts_executed))),axis=1) ## ####################################################################### min_response_cost = 99999999 for k_warm in u_warm_profiles.keys(): u_warm = u_warm_profiles[k_warm] x_warm, x_des_warm = response_MPC.forward_simulate_all(response_x0.reshape(6,1), u_warm) bri = mibr.IterativeBestResponseMPCMultiple(response_MPC, None, nonresponse_MPC_list ) k_slack = 10000.0 k_CA = 0.000000000000000 k_CA_power = 4 wall_CA = True bri.k_slack = k_slack bri.k_CA = k_CA bri.k_CA_power = k_CA_power bri.world = world bri.wall_CA = wall_CA # for slack_var in bri.slack_vars_list: ## Added to constrain slacks # bri.opti.subject_to(cas.vec(slack_var) <= 1.0) INFEASIBLE = True bri.generate_optimization(N, T, response_x0, None, nonresponse_x0_list, 1, slack=False) bri.opti.set_initial(bri.u_opt, u_warm) bri.opti.set_initial(bri.x_opt, x_warm) bri.opti.set_initial(bri.x_desired, x_des_warm) ### Set the trajectories of the nonresponse vehicles (as given) for i in range(n_other): bri.opti.set_value(bri.allother_x_opt[i], nonresponse_x_list[i]) bri.opti.set_value(bri.allother_x_desired[i], nonresponse_xd_list[i]) ### Solve the Optimization # Debugging # plot_range = [N] # bri.opti.callback(lambda i: bri.debug_callback(i, plot_range)) # bri.opti.callback(lambda i: print("J_i %.03f, J_j %.03f, Slack %.03f, CA %.03f"%(bri.solution.value(bri.response_svo_cost), bri.solution.value(bri.other_svo_cost), bri.solution.value(bri.k_slack*bri.slack_cost), bri.solution.value(bri.k_CA*bri.collision_cost)))) try: bri.solve(None, nonresponse_u_list) x1, u1, x1_des, _, _, _, _, _, _ = bri.get_solution() print("i_mpc %d n_round %d i %02d Cost %.02f Slack %.02f "%(i_mpc, i_rounds_ibr, i, bri.solution.value(bri.total_svo_cost), bri.solution.value(bri.slack_cost))) print("J_i %.03f, J_j %.03f, Slack %.03f, CA %.03f"%(bri.solution.value(bri.response_svo_cost), bri.solution.value(bri.other_svo_cost), bri.solution.value(bri.k_slack*bri.slack_cost), bri.solution.value(bri.k_CA*bri.collision_cost))) print("Dir:", subdir_name) print("k_warm", k_warm) INFEASIBLE = False if bri.solution.value(bri.slack_cost) < min_slack: current_cost = bri.solution.value(bri.total_svo_cost) if current_cost < min_response_cost: uamb = u1 xamb = x1 xamb_des = x1_des min_response_cost = current_cost min_response_warm = k_warm min_bri = bri # file_name = folder + "data/"+'%03d'%ibr_sub_it # mibr.save_state(file_name, xamb, uamb, xamb_des, all_other_x, all_other_u, all_other_x_des) # mibr.save_costs(file_name, bri) except RuntimeError: print("Infeasibility: k_warm %s"%k_warm) # ibr_sub_it +=1 ########### SOLVE FOR THE OTHER VEHICLES ON THE ROAD if not XAMB_ONLY: for i in range(len(all_other_MPC)): response_MPC = all_other_MPC[i] response_x0 = all_other_x0[i] nonresponse_MPC_list = all_other_MPC[:i] + all_other_MPC[i+1:] nonresponse_x0_list = all_other_x0[:i] + all_other_x0[i+1:] nonresponse_u_list = all_other_u[:i] + all_other_u[i+1:] nonresponse_x_list = all_other_x[:i] + all_other_x[i+1:] nonresponse_xd_list = all_other_x_des[:i] + all_other_x_des[i+1:] ################ Warm Start u_warm_profiles = mibr.generate_warm_u(N, response_MPC) if i_rounds_ibr > 0: # warm start with the solution from the last IBR round u_warm_profiles["previous"] = all_other_u[i] else: # take the control inputs of the last MPC and continue the ctrl if i_mpc > 0: u_warm_profiles["previous"] = np.concatenate((all_other_u[i][:, number_ctrl_pts_executed:], np.tile(all_other_u[i][:,-1:],(1, number_ctrl_pts_executed))),axis=1) ## min_response_cost = 99999999 for k_warm in u_warm_profiles.keys(): u_warm = u_warm_profiles[k_warm] x_warm, x_des_warm = response_MPC.forward_simulate_all(response_x0.reshape(6,1), u_warm) bri = mibr.IterativeBestResponseMPCMultiple(response_MPC, amb_MPC, nonresponse_MPC_list) bri.k_slack = k_slack bri.k_CA = k_CA bri.k_CA_power = k_CA_power bri.world = world bri.wall_CA = wall_CA INFEASIBLE = True bri.generate_optimization(N, T, response_x0, x0_amb, nonresponse_x0_list, 1, slack=False) # for slack_var in bri.slack_vars_list: ## Added to constrain slacks # bri.opti.subject_to(cas.vec(slack_var) <= 1.0) bri.opti.set_initial(bri.u_opt, u_warm) bri.opti.set_initial(bri.x_opt, x_warm) bri.opti.set_initial(bri.x_desired, x_des_warm) ### Set the trajectories of the nonresponse vehicles (as given) bri.opti.set_value(bri.xamb_opt, xamb) for i in range(len(nonresponse_x_list)): bri.opti.set_value(bri.allother_x_opt[i], nonresponse_x_list[i]) bri.opti.set_value(bri.allother_x_desired[i], nonresponse_xd_list[i]) # Debugging # bri.opti.callback(lambda i: bri.debug_callback(i, [N])) # bri.opti.callback(lambda i: print("J_i %.03f, J_j %.03f, Slack %.03f, CA %.03f"%(bri.solution.value(bri.response_svo_cost), bri.solution.value(bri.other_svo_cost), bri.solution.value(bri.k_slack*bri.slack_cost), bri.solution.value(bri.k_CA*bri.collision_cost)))) try: ### Solve the Optimization bri.solve(uamb, nonresponse_u_list) x1_nr, u1_nr, x1_des_nr, _, _, _, _, _, _ = bri.get_solution() print(" i_mpc %d n_round %d i %02d Cost %.02f Slack %.02f "%(i_mpc, i_rounds_ibr, i, bri.solution.value(bri.total_svo_cost), bri.solution.value(bri.slack_cost))) print(" J_i %.03f, J_j %.03f, Slack %.03f, CA %.03f"%(bri.solution.value(bri.response_svo_cost), bri.solution.value(bri.other_svo_cost), bri.solution.value(bri.k_slack*bri.slack_cost), bri.solution.value(bri.k_CA*bri.collision_cost))) print(" Dir:", subdir_name) print(" k_warm", k_warm) INFEASIBLE = False if bri.solution.value(bri.slack_cost) < min_slack: current_cost = bri.solution.value(bri.total_svo_cost) if current_cost < min_response_cost: all_other_u[i] = u1_nr all_other_x = all_other_x[:i] + [x1_nr] + all_other_x[i:] all_other_u = all_other_u[:i] + [u1_nr] + all_other_u[i:] all_other_x_des = all_other_x_des[:i] + [x1_des_nr] + all_other_x_des[i:] min_response_cost = current_cost min_response_warm = k_warm min_bri = bri # file_name = folder + "data/"+'%03d'%ibr_sub_it # mibr.save_state(file_name, xamb, uamb, xamb_des, all_other_x, all_other_u, all_other_x_des) # mibr.save_costs(file_name, bri) except RuntimeError: print(" Infeasibility: k_warm %s"%k_warm) # ibr_sub_it +=1 # print(" IBR Done: Rd %02d / %02d"%(i_rounds_ibr, n_rounds_ibr)) file_name = folder + "data/"+'r%02d%03d'%(i_mpc, i_rounds_ibr) if not INFEASIBLE: mibr.save_state(file_name, xamb, uamb, xamb_des, xothers, uothers, xothers_des) mibr.save_costs(file_name, bri) actual_t = i_mpc * number_ctrl_pts_executed actual_xamb[:,actual_t:actual_t+number_ctrl_pts_executed+1] = xamb[:,:number_ctrl_pts_executed+1] print(" MPC Done: Rd %02d / %02d"%(i_mpc, n_rounds_mpc)) print(" Full MPC Solution", xamb[0:2,:]) print(" Executed MPC", xamb[0:2,:number_ctrl_pts_executed+1]) print(" Solution Costs...") for cost in bri.car1_costs_list: print("%.04f"%bri.solution.value(cost)) print(min_bri.solution.value(min_bri.k_CA * min_bri.collision_cost), min_bri.solution.value(min_bri.collision_cost)) print(min_bri.solution.value(min_bri.k_slack * min_bri.slack_cost), min_bri.solution.value(min_bri.slack_cost)) print(" Save to...", file_name) actual_uamb[:,actual_t:actual_t+number_ctrl_pts_executed] = uamb[:,:number_ctrl_pts_executed] plot_range = range(N+1) for k in plot_range: cmplot.plot_multiple_cars( k, min_bri.responseMPC, xothers, xamb, True, None, None, None, min_bri.world, 0) plt.show() plt.plot(xamb[4,:],'--') plt.plot(xamb[4,:] * np.cos(xamb[2,:])) plt.ylabel("Velocity / Vx") plt.hlines(35*0.447,0,xamb.shape[1]) plt.show() plt.plot(uamb[1,:],'o') plt.hlines(amb_MPC.max_v_u,0,xamb.shape[1]) plt.ylabel("delta_u_v") plt.show() for i in range(len(xothers)): actual_xothers[i][:,actual_t:actual_t+number_ctrl_pts_executed+1] = xothers[i][:,:number_ctrl_pts_executed+1] actual_uothers[i][:,actual_t:actual_t+number_ctrl_pts_executed] = uothers[i][:,:number_ctrl_pts_executed] # all_other_u[i] = np.concatenate((uothers[i][:, number_ctrl_pts_executed:],uothers[i][:,:number_ctrl_pts_executed]),axis=1) else: raise Exception("Xamb is None", i_mpc, i_rounds_ibr, "slack cost", bri.solution.value(bri.slack_cost)) print("Solver Done! Runtime: %.1d"%(time.time()-t_start_time))
[ 11748, 640, 11, 4818, 8079, 11, 1822, 29572, 198, 11748, 28686, 11, 25064, 198, 11748, 299, 32152, 355, 45941, 198, 37659, 13, 2617, 62, 4798, 25811, 7, 3866, 16005, 28, 17, 8, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458,...
1.883427
9,479
import os import sys import shutil import re INPUT_PATH = "d:\\dbmaps\\test\\final\\" OUTPUT_PATH = "d:\\dbmaps\\test\\zoom17\\" for filename in os.listdir(INPUT_PATH): InputFile = INPUT_PATH + filename matchResult = re.search('([a-zA-Z]+)-([0-9]+)-([0-9]+)-([0-9]+)\.', filename) if (not matchResult): continue cellX = int(matchResult.group(2)) - 90 cellY = int(matchResult.group(3)) - 40 zoom = matchResult.group(4) newFilename = "db-" + str(cellX) + "-" + str(cellY) + "-" + str(zoom) + ".jpg" OutputFile = OUTPUT_PATH + newFilename print("Copying " + filename + " to " + newFilename + "...") shutil.copyfile(InputFile, OutputFile)
[ 11748, 28686, 201, 198, 11748, 25064, 201, 198, 11748, 4423, 346, 201, 198, 11748, 302, 201, 198, 201, 198, 1268, 30076, 62, 34219, 796, 366, 67, 25, 6852, 9945, 31803, 6852, 9288, 6852, 20311, 6852, 1, 201, 198, 2606, 7250, 3843, 62,...
2.311688
308
""" [[https://rememberthemilk.com][Remember The Milk]] tasks and notes """ REQUIRES = [ 'icalendar', ] import re from pathlib import Path from typing import Dict, List, Optional, Iterator from datetime import datetime from .common import LazyLogger, get_files, group_by_key, cproperty, make_dict from my.config import rtm as config import icalendar # type: ignore from icalendar.cal import Todo # type: ignore logger = LazyLogger(__name__) # TODO extract in a module to parse RTM's ical? # TODO tz? def is_completed(self) -> bool: return self.get_status() == 'COMPLETED' def __repr__(self): return repr(self.todo) def __str__(self): return str(self.todo) def dal(): last = get_files(config.export_path)[-1] data = last.read_text() return DAL(data=data, revision='TODO') def all_tasks() -> Iterator[MyTodo]: yield from dal().all_todos() def active_tasks() -> Iterator[MyTodo]: for t in all_tasks(): if not t.is_completed(): yield t
[ 37811, 198, 30109, 5450, 1378, 38947, 18855, 43545, 13, 785, 7131, 16676, 383, 24796, 11907, 8861, 290, 4710, 198, 37811, 198, 198, 2200, 10917, 4663, 1546, 796, 685, 198, 220, 220, 220, 705, 605, 9239, 3256, 198, 60, 198, 198, 11748, ...
2.541667
408
# def fib2(n): # n # result = [] # a, b = 0, 1 # while b < n: # result.append(b) # a, b = b, a+b # return result # # a = fib2(500) # print(a) def recur_fibo(n): """ """ if n <= 1: return n else: return(recur_fibo(n-1) + recur_fibo(n-2)) a = recur_fibo(10) print(a)
[ 2, 825, 12900, 17, 7, 77, 2599, 1303, 220, 299, 220, 198, 2, 220, 220, 220, 220, 1255, 796, 17635, 198, 2, 220, 220, 220, 220, 257, 11, 275, 796, 657, 11, 352, 198, 2, 220, 220, 220, 220, 981, 275, 1279, 299, 25, 198, 2, 220...
1.708333
192
import taco.aws_wrappers.dynamodb_wrapper.consts as dynamodb_consts from taco.boto3.boto_config import Regions DEFAULT_REGION = Regions.n_virginia.value RESPONSE_KEY_NAME = 'Responses' PRIMARY_KEY_NAME = 'KEY1' ATTRIBUTE_DEFINITIONS = [ dynamodb_consts.property_schema(PRIMARY_KEY_NAME, dynamodb_consts.AttributeTypes.string_type.value) ] PRIMARY_KEYS = [dynamodb_consts.property_schema(PRIMARY_KEY_NAME, dynamodb_consts.PrimaryKeyTypes.hash_type.value)] ITEMS_TO_PUT_WITHOUT_PRIMARY_KEY = [{'q': 'qqq'}] ITEMS_TO_PUT_WITH_MISMATCH_PRIMARY_KEY_VALUE = [{PRIMARY_KEY_NAME: 12}] DEFAULT_PRIMARY_KEY_VALUE = '123abc' VALID_ITEMS_TO_PUT = [{PRIMARY_KEY_NAME: DEFAULT_PRIMARY_KEY_VALUE}] TABLE_ALREADY_EXISTS_MESSAGE = 'Table already exists' SKIP_TABLE_DELETION_ERROR_MESSAGE = 'Table does not exists, skip deletion'
[ 11748, 47884, 13, 8356, 62, 29988, 11799, 13, 67, 4989, 375, 65, 62, 48553, 13, 1102, 6448, 355, 6382, 375, 65, 62, 1102, 6448, 198, 6738, 47884, 13, 65, 2069, 18, 13, 65, 2069, 62, 11250, 1330, 47089, 628, 198, 7206, 38865, 62, 3...
2.356322
348
import numpy as np from scipy import constants measured_species = ["HMF", "DFF", "HMFCA", "FFCA", "FDCA"] all_species = measured_species.copy() all_species.extend(["H_" + s for s in measured_species]) all_species.extend(["Hx_" + s for s in measured_species]) def derivatives(y, t, p): """ Calculates the derivatives from local values, used by scipy.integrate.solve_ivp """ c = {s:y[i] for i, s in enumerate(all_species)} dc = dict() dc["HMF"] = - (p["k11"] + p["k12"] + p["kH1"])*c["HMF"] dc["DFF"] = p["k11"]*c["HMF"] - (p["k21"] + p["kH21"])*c["DFF"] dc["HMFCA"] = p["k12"]*c["HMF"] - (p["k22"] + p["kH22"])*c["HMFCA"] dc["FFCA"] = p["k21"]*c["DFF"] + p["k22"]*c["HMFCA"] - (p["k3"] + p["kH3"])*c["FFCA"] dc["FDCA"] = p["k3"]*c["FFCA"] - p["kH4"]*c["FDCA"] dc["H_HMF"] = p["kH1"]*c["HMF"] - p["kHx"]*c["H_HMF"] dc["H_DFF"] = p["kH21"]*c["DFF"] - p["kHx"]*c["H_DFF"] dc["H_HMFCA"] = p["kH22"]*c["HMFCA"] - p["kHx"]*c["H_HMFCA"] dc["H_FFCA"] = p["kH3"]*c["FFCA"] - p["kHx"]*c["H_FFCA"] dc["H_FDCA"] = p["kH4"]*c["FDCA"] - p["kHx"]*c["H_FDCA"] dc["Hx_HMF"] = p["kHx"]*c["H_HMF"] dc["Hx_DFF"] = p["kHx"]*c["H_DFF"] dc["Hx_HMFCA"] = p["kHx"]*c["H_HMFCA"] dc["Hx_FFCA"] = p["kHx"]*c["H_FFCA"] dc["Hx_FDCA"] = p["kHx"]*c["H_FDCA"] dy = [dc[name] for name in all_species] return dy
[ 198, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 629, 541, 88, 1330, 38491, 628, 198, 1326, 34006, 62, 35448, 796, 14631, 36905, 37, 1600, 366, 35, 5777, 1600, 366, 36905, 4851, 32, 1600, 366, 37, 4851, 32, 1600, 366, 26009, 8141, ...
1.699774
886
import pytest from cayennelpp.lpp_type import LppType
[ 11748, 12972, 9288, 198, 198, 6738, 269, 323, 1697, 417, 381, 13, 75, 381, 62, 4906, 1330, 406, 381, 6030, 628, 628, 628, 198 ]
2.541667
24
from frogtips.api.Credentials import Credentials from frogtips.api.Tip import Tip from frogtips.api.Tips import Tips
[ 6738, 21264, 41315, 13, 15042, 13, 34, 445, 14817, 1330, 327, 445, 14817, 198, 6738, 21264, 41315, 13, 15042, 13, 28434, 1330, 23095, 198, 6738, 21264, 41315, 13, 15042, 13, 43368, 1330, 27558, 628 ]
3.470588
34
#!/usr/bin/env python from mission_ctrl_msgs.srv import * from studs_defines import * import rospy import time import carlos_vision as crlv from geometry_msgs.msg import PointStamped from geometry_msgs.msg import PoseArray from geometry_msgs.msg import Pose from carlos_controller.msg import StudsPoses #import geometry_msgs.msg #import std_msgs.msg # incomming handlers # publisher # timer callback for state machine update if __name__ == "__main__": init_server()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 6738, 4365, 62, 44755, 62, 907, 14542, 13, 27891, 85, 1330, 1635, 198, 6738, 941, 82, 62, 4299, 1127, 1330, 1635, 198, 11748, 686, 2777, 88, 198, 11748, 640, 198, 11748, 1097, 3...
3.037736
159
# -*- coding: utf-8 -*- """ utils.py ~~~~~~~~ Helper functions for setting up the environment and parsing args, etc. """ import os os.environ['PYTHONHASHSEED'] = '0' from numpy.random import seed import random random.seed(1) seed(1) import sys import logging import argparse import pickle import json import numpy as np import pandas as pd import smtplib import traceback import lightgbm as lgb from pprint import pformat from collections import Counter from email.mime.text import MIMEText from sklearn.preprocessing import LabelEncoder from sklearn.preprocessing import MinMaxScaler def parse_multiple_dataset_args(): """Parse the command line configuration for a particular run. Raises: ValueError: if the tree value for RandomForest is negative. Returns: argparse.Namespace -- a set of parsed arguments. """ p = argparse.ArgumentParser() p.add_argument('--task', default='binary', choices=['binary', 'multiclass'], help='Whether to perform binary classification or multi-class classification.') p.add_argument('--training-set', help='Which extra dataset to use as training. Blue Hexagon first 3 months is the default training set.') p.add_argument('--diversity', choices=['no', 'size', 'family', 'timestamp', 'timestamp_part', 'legacy', 'packed', 'family_fixed_size'], help='Which diversity metric to use in the training set: size, timestamp, family, packed. \ "no" means the original setting: use the 3 months of bluehex dataset as the training set.') p.add_argument('--setting-name', help='name for this particular setting, for saving corresponding data, model, and results') p.add_argument('-c', '--classifier', choices=['rf', 'gbdt', 'mlp'], help='The classifier used for binary classification or multi-class classification') p.add_argument('--testing-time', help='The beginning time and ending time (separated by comma) for a particular testing set (bluehex data)') p.add_argument('--quiet', default=1, type=int, choices=[0, 1], help='whether to print DEBUG logs or just INFO') p.add_argument('--retrain', type=int, choices=[0, 1], default=0, help='Whether to retrain the classifier, default NO.') p.add_argument('--seed', type=int, default=42, help='random seed for training and validation split.') # sub-arguments for the family (binary) and family_fixed_size (binary) diversity and multi-class classification p.add_argument('--families', type=int, help='add top N families from the first three months of bluehex.') # sub-arguments for the MLP classifier. p.add_argument('--mlp-hidden', help='The hidden layers of the MLP classifier, e.g.,: "2400-1200-1200", would make the architecture as 2381-2400-1200-1200-2') p.add_argument('--mlp-batch-size', default=32, type=int, help='MLP classifier batch_size.') p.add_argument('--mlp-lr', default=0.001, type=float, help='MLP classifier Adam learning rate.') p.add_argument('--mlp-epochs', default=50, type=int, help='MLP classifier epochs.') p.add_argument('--mlp-dropout', default=0.2, type=float, help='MLP classifier Droput rate.') # sub-arguments for the RandomForest classifier. p.add_argument('--tree', type=int, default=100, help='The n_estimators of RandomForest classifier when --classifier = "rf"') args = p.parse_args() if args.tree < 0: raise ValueError('invalid tree value') return args def get_model_dims(model_name, input_layer_num, hidden_layer_num, output_layer_num): """convert hidden layer arguments to the architecture of a model (list) Arguments: model_name {str} -- 'MLP' or 'Contrastive AE'. input_layer_num {int} -- The number of the features. hidden_layer_num {str} -- The '-' connected numbers indicating the number of neurons in hidden layers. output_layer_num {int} -- The number of the classes. Returns: [list] -- List represented model architecture. """ try: if '-' not in hidden_layer_num: dims = [input_layer_num, int(hidden_layer_num), output_layer_num] else: hidden_layers = [int(dim) for dim in hidden_layer_num.split('-')] dims = [input_layer_num] for dim in hidden_layers: dims.append(dim) dims.append(output_layer_num) logging.debug(f'{model_name} dims: {dims}') except: logging.error(f'get_model_dims {model_name}\n{traceback.format_exc()}') sys.exit(-1) return dims def parse_drift_args(): """Parse the command line configuration for a particular run. Raises: ValueError: if the tree value for RandomForest is negative. Returns: argparse.Namespace -- a set of parsed arguments. """ p = argparse.ArgumentParser() p.add_argument('--task', default='binary', choices=['binary', 'multiclass'], help='Whether to perform binary classification or multi-class classification.') p.add_argument('--setting-name', help='name for this particular setting, for saving corresponding data, model, and results') p.add_argument('-c', '--classifier', choices=['rf', 'gbdt', 'mlp'], help='The classifier used for binary classification or multi-class classification') p.add_argument('--testing-time', help='The beginning time and ending time (separated by comma) for a particular testing set (bluehex data)') p.add_argument('--month-interval', type=int, default=1, help='specify how many months for sampling.') # sub-arguments for the family (binary) and family_fixed_size (binary) diversity and multi-class classification p.add_argument('--families', type=int, help='add top N families from the first three months of bluehex.') p.add_argument('--quiet', default=1, type=int, choices=[0, 1], help='whether to print DEBUG logs or just INFO') p.add_argument('--retrain', type=int, choices=[0, 1], default=0, help='Whether to retrain the classifier, default NO.') p.add_argument('--sample-ratio', default=0.01, type=float, help='how many samples to add back to the training set for retraining to combat concept drift.') p.add_argument('--ember-ratio', default=0.3, type=float, help='how many Ember samples to train Transcend / CADE.') p.add_argument('--seed', default=1, type=int, help='random seed for the random experiment') args = p.parse_args() return args
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 37811, 198, 26791, 13, 9078, 198, 15116, 198, 198, 47429, 5499, 329, 4634, 510, 262, 2858, 290, 32096, 26498, 11, 3503, 13, 198, 198, 37811, 198, 198, 11748, 28686,...
2.694422
2,510
import math from functools import lru_cache class Polygons: def __init__(self, m, R): if m < 3: raise ValueError('m must be greater than 3') self._m = m self._R = R self._polygons = [Polygon(i, R) for i in range(3, m+1)]
[ 11748, 10688, 198, 6738, 1257, 310, 10141, 1330, 300, 622, 62, 23870, 198, 198, 4871, 12280, 70, 684, 25, 198, 220, 220, 220, 825, 11593, 15003, 834, 7, 944, 11, 285, 11, 371, 2599, 198, 220, 220, 220, 220, 220, 220, 220, 611, 285...
2.085271
129
""" PoW.py """ import DSA import sys import hashlib if sys.version_info < (3, 6): import sha3
[ 37811, 201, 198, 18833, 54, 13, 9078, 201, 198, 201, 198, 37811, 201, 198, 201, 198, 11748, 360, 4090, 201, 198, 11748, 25064, 201, 198, 11748, 12234, 8019, 201, 198, 201, 198, 361, 25064, 13, 9641, 62, 10951, 1279, 357, 18, 11, 718...
2
57
# ---------------------------------------------------------------------- # SubNode # ---------------------------------------------------------------------- # Copyright (C) 2007-2020 The NOC Project # See LICENSE for details # ---------------------------------------------------------------------- # Python modules from typing import Optional # NOC modules from .base import BaseCDAGNode, ValueType, Category
[ 2, 16529, 23031, 198, 2, 3834, 19667, 198, 2, 16529, 23031, 198, 2, 15069, 357, 34, 8, 4343, 12, 42334, 383, 399, 4503, 4935, 198, 2, 4091, 38559, 24290, 329, 3307, 198, 2, 16529, 23031, 198, 198, 2, 11361, 13103, 198, 6738, 19720, ...
6.227273
66
import numpy as np # softmax function # modified softmax function
[ 11748, 299, 32152, 355, 45941, 628, 198, 2, 2705, 9806, 2163, 628, 198, 2, 9518, 2705, 9806, 2163, 198 ]
3.684211
19
# example of mask inference with a pre-trained model (COCO) import sys from keras.preprocessing.image import img_to_array from keras.preprocessing.image import load_img from mrcnn.config import Config from mrcnn.model import MaskRCNN from mrcnn.visualize import display_instances from tools import load_config # load config params - labels cfg_dict = load_config('config.yaml') class_names = cfg_dict['class_names'] # config settings for model inference # replicate the model for pure inference rcnn_model = MaskRCNN(mode='inference', model_dir='models/', config=ConfigParams()) # model weights input <<<<<<< HEAD rcnn_model.load_weights('models/mask_rcnn_coco.h5', by_name=True) ======= >>>>>>> 2ffc4581f4632ec494d19a7af0f5912e7482a631 path_weights_file = 'models/mask_rcnn_coco.h5' rcnn_model.load_weights(path_weights_file, by_name=True) # single image input path_to_image = sys.argv[1] img = load_img(path_to_image) # transition to array img = img_to_array(img) print('Image shape:', img.shape) # make inference results = rcnn_model.detect([img], verbose=0) # the output is a list of dictionaries, where each dict has a single object detection # {'rois': array([[ 30, 54, 360, 586]], dtype=int32), # 'class_ids': array([21], dtype=int32), # 'scores': array([0.9999379], dtype=float32), # 'masks': huge_boolean_array_here ... result_params = results[0] # show photo with bounding boxes, masks, class labels and scores display_instances(img, result_params['rois'], result_params['masks'], result_params['class_ids'], class_names, result_params['scores'])
[ 2, 1672, 286, 9335, 32278, 351, 257, 662, 12, 35311, 2746, 357, 34, 4503, 46, 8, 198, 11748, 25064, 198, 6738, 41927, 292, 13, 3866, 36948, 13, 9060, 1330, 33705, 62, 1462, 62, 18747, 198, 6738, 41927, 292, 13, 3866, 36948, 13, 9060...
2.6528
625
import os import csv import copy import json import torch import numpy as np from os import path as osp from bootstrap.lib.logger import Logger from bootstrap.lib.options import Options from block.datasets.vqa_utils import AbstractVQA from copy import deepcopy import random import tqdm import h5py
[ 11748, 28686, 198, 11748, 269, 21370, 198, 11748, 4866, 198, 11748, 33918, 198, 11748, 28034, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 28686, 1330, 3108, 355, 267, 2777, 198, 6738, 6297, 26418, 13, 8019, 13, 6404, 1362, 1330, 5972, ...
3.397727
88
import datetime x = datetime.datetime.now() print(x) # 2021-07-13 22:55:43.029046 print(x.year) print(x.strftime("%A")) """ 2021 Tuesday """ x = datetime.datetime(2020, 5, 17) print(x) # 2020-05-17 00:00:00 x = datetime.datetime(2018, 6, 1) print(x.strftime("%B")) # June
[ 11748, 4818, 8079, 198, 198, 87, 796, 4818, 8079, 13, 19608, 8079, 13, 2197, 3419, 198, 198, 4798, 7, 87, 8, 198, 2, 33448, 12, 2998, 12, 1485, 2534, 25, 2816, 25, 3559, 13, 48891, 45438, 198, 198, 4798, 7, 87, 13, 1941, 8, 198,...
2.128788
132
# Copyright 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You # may not use this file except in compliance with the License. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompanying this file. This file is # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF # ANY KIND, either express or implied. See the License for the specific # language governing permissions and limitations under the License. from ..objects.exceptions import NotFoundError import re
[ 2, 15069, 1946, 6186, 13, 785, 11, 3457, 13, 393, 663, 29116, 13, 1439, 6923, 33876, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 11074, 921, 198, 2, 743, 407, 779, 428, 2393, ...
3.86875
160