content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
# ------------------------------------------------------------------------------------------------------ # Copyright (c) Leo Hanisch. All rights reserved. # Licensed under the BSD 3-Clause License. See LICENSE.txt in the project root for license information. # ------------------------------------------------------------------------------------------------------ #pylint: disable=invalid-name import inspect from functools import wraps import landscapes.single_objective import numpy as np # Wrapper for landscapes.single_objective functions for inputs > 1d # Add all functions from landscapes.single_objective FUNCTIONS = { name: wrap_landscapes_func(func) for (name, func) in inspect.getmembers( landscapes.single_objective, inspect.isfunction ) if name not in ['colville', 'wolfe'] # Don't include 3D and 4D functions }
[ 2, 16529, 3880, 23031, 198, 2, 220, 15069, 357, 66, 8, 19632, 9530, 25308, 13, 1439, 2489, 10395, 13, 198, 2, 220, 49962, 739, 262, 347, 10305, 513, 12, 2601, 682, 13789, 13, 4091, 38559, 24290, 13, 14116, 287, 262, 1628, 6808, 329,...
4.028169
213
# -*- coding: UTF-8 -*- from collections import deque # def set_use_nat_port(self, use_or_not): # self._use_nat_port = use_or_not # # def get_use_nat_port(self): # return self._use_nat_port # # def set_dut_nat_port(self, port): # self._nat_port = port # # def get_dut_nat_port(self): # return self._nat_port # # def get_nat_magic_number(self): # return self._nat_magic_number #
[ 2, 532, 9, 12, 19617, 25, 41002, 12, 23, 532, 9, 12, 198, 6738, 17268, 1330, 390, 4188, 628, 198, 2, 220, 220, 220, 825, 900, 62, 1904, 62, 32353, 62, 634, 7, 944, 11, 779, 62, 273, 62, 1662, 2599, 198, 2, 220, 220, 220, 220...
2.077295
207
#!/usr/bin/env python """interp_spline_interest.py: Demonstrate spline interpolation. """ from scipy.interpolate import splrep, splev import numpy as np import matplotlib.pyplot as plt # pylint: disable=invalid-name # Interest rates of Jan, Feb, Mar, Jun, Dec. x = np.array([1, 2, 3, 6, 12]) y = np.array([0.080, 0.100, 0.112, 0.144, 0.266]) # Interpolate the rates. tck = splrep(x, y) # Print the spline curve. np.set_printoptions(formatter={'float': '{:.3f}'.format}) print("knot vector:\n", tck[0]) print("control points:\n", tck[1]) print("degree:\n", tck[2]) # Evaluate interest rates for each month. for i in range(1, 13): print(f"month[{i:02d}]: {float(splev(i, tck)):.3f}%") # Plot the interest curve. time = np.linspace(1, 12, 1000, endpoint=True) rate = splev(time, tck) plt.figure() plt.plot(time, rate, color='deeppink') plt.xlabel("Month") plt.ylabel("Rate (%)") plt.show()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 37811, 3849, 79, 62, 22018, 500, 62, 9446, 13, 9078, 25, 7814, 23104, 4328, 500, 39555, 341, 13, 198, 37811, 198, 6738, 629, 541, 88, 13, 3849, 16104, 378, 1330, 4328, 7856, 11, 599,...
2.427027
370
import unittest import numpy as np from optimizer import SGD from modules import ConvNet from .utils import *
[ 11748, 555, 715, 395, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 6436, 7509, 1330, 26147, 35, 198, 6738, 13103, 1330, 34872, 7934, 198, 6738, 764, 26791, 1330, 1635, 628, 628 ]
3.645161
31
# uncompyle6 version 3.7.4 # Python bytecode 3.7 (3394) # Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)] # Embedded file name: T:\InGame\Gameplay\Scripts\Server\tunable_utils\create_object.py # Compiled at: 2020-05-07 00:26:47 # Size of source mod 2**32: 4106 bytes from crafting.crafting_tunable import CraftingTuning from objects.components.state import TunableStateValueReference, CommodityBasedObjectStateValue from objects.system import create_object from sims4.random import weighted_random_item from sims4.tuning.tunable import TunableReference, TunableTuple, TunableList, TunableRange, AutoFactoryInit, HasTunableSingletonFactory, TunableFactory import crafting, services, sims4 logger = sims4.log.Logger('CreateObject')
[ 2, 34318, 2349, 21, 2196, 513, 13, 22, 13, 19, 198, 2, 11361, 18022, 8189, 513, 13, 22, 357, 2091, 5824, 8, 198, 2, 4280, 3361, 3902, 422, 25, 11361, 513, 13, 22, 13, 24, 357, 31499, 14, 85, 18, 13, 22, 13, 24, 25, 1485, 66,...
3.034615
260
# # @lc app=leetcode.cn id=47 lang=python3 # # [47] II # # https://leetcode-cn.com/problems/permutations-ii/description/ # # algorithms # Medium (59.58%) # Likes: 371 # Dislikes: 0 # Total Accepted: 78.7K # Total Submissions: 132.1K # Testcase Example: '[1,1,2]' # # # # : # # : [1,1,2] # : # [ # [1,1,2], # [1,2,1], # [2,1,1] # ] # # # @lc code=start # @lc code=end # def permuteUnique(self, nums: List[int]) -> List[List[int]]: # def helper(nums,res,path): # if not nums and path not in res: # res.append(path) # for i in range(len(nums)): # helper(nums[:i]+nums[i+1:],res,path+[nums[i]]) # res = [] # helper(nums,res,[]) # return res
[ 2, 198, 2, 2488, 44601, 598, 28, 293, 316, 8189, 13, 31522, 4686, 28, 2857, 42392, 28, 29412, 18, 198, 2, 198, 2, 685, 2857, 60, 220, 2873, 198, 2, 198, 2, 3740, 1378, 293, 316, 8189, 12, 31522, 13, 785, 14, 1676, 22143, 14, 1...
1.798578
422
import subprocess as sp import sys sp.run(["pip", "install", "-e", "."], check=True) sp.run(["pytest", "blobfile"] + sys.argv[1:], check=True)
[ 11748, 850, 14681, 355, 599, 201, 198, 11748, 25064, 201, 198, 201, 198, 2777, 13, 5143, 7, 14692, 79, 541, 1600, 366, 17350, 1600, 27444, 68, 1600, 366, 526, 4357, 2198, 28, 17821, 8, 201, 198, 2777, 13, 5143, 7, 14692, 9078, 9288,...
2.328125
64
import Sofa import random from cmath import * ############################################################################################ # this is a PythonScriptController example script ############################################################################################ ############################################################################################ # following defs are used later in the script ############################################################################################ # utility methods falling_speed = 0 capsule_height = 5 capsule_chain_height = 5
[ 11748, 1406, 13331, 198, 11748, 4738, 198, 6738, 269, 11018, 1330, 1635, 198, 29113, 29113, 14468, 7804, 4242, 198, 2, 428, 318, 257, 11361, 7391, 22130, 1672, 4226, 198, 29113, 29113, 14468, 7804, 4242, 628, 198, 198, 29113, 29113, 14468...
6.537634
93
import tensorboardX with tensorboardX.SummaryWriter("foo") as w: w.add_scalar("a", 1.0, 1) w.add_scalar("a", 2.0, 2) with tensorboardX.SummaryWriter("foo/bar") as w: w.add_scalar("a", 3.0, 3) w.add_scalar("a", 4.0, 4) with tensorboardX.SummaryWriter("foo/bar/baz") as w: w.add_scalar("a", 5.0, 5) w.add_scalar("a", 6.0, 6)
[ 11748, 11192, 273, 3526, 55, 198, 198, 4480, 11192, 273, 3526, 55, 13, 22093, 34379, 7203, 21943, 4943, 355, 266, 25, 198, 220, 220, 220, 266, 13, 2860, 62, 1416, 282, 283, 7203, 64, 1600, 352, 13, 15, 11, 352, 8, 198, 220, 220, ...
1.933702
181
############################################################################### # Copyright 2020 UChicago Argonne, LLC. # (c.f. AUTHORS, LICENSE) # For more info, see https://xgitlab.cels.anl.gov/argo/cobalt-python-wrapper # SPDX-License-Identifier: BSD-3-Clause ############################################################################## import subprocess from cobalt.cobalt import Cobalt, UserPolicy __all__ = [ 'Cobalt', 'UserPolicy' ]
[ 29113, 29113, 7804, 4242, 21017, 198, 2, 15069, 12131, 471, 25705, 49974, 710, 11, 11419, 13, 198, 2, 357, 66, 13, 69, 13, 37195, 20673, 11, 38559, 24290, 8, 198, 2, 1114, 517, 7508, 11, 766, 3740, 1378, 87, 18300, 23912, 13, 5276, ...
3.731092
119
#!/usr/bin/env python3 import os orderNumbers = open("orders.txt", "r") #Order numbers to match #Network path to a directory of files that has full details of the order directoryEntries = os.scandir("") outputFile = open("matchedData.dat", "w") for entry in directoryEntries: print("Currently parsing file ", entry.path) fullOrderData = open(entry.path, "r") #loop through each order from the ordernumber file for orderNo in OrderNumbers: for row in fullOrderData: if orderNo.strip() in row: outputFile.write(row) #go back to start of orderdetails data to match on next order number fullOrderData.seek(0) #go back to order numbers again to match on the next order details file orderNumbers.seek(0) fullOrderData.close() OrderNumbers.close() outputFile.close() print("done")
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 11748, 28686, 198, 198, 2875, 49601, 796, 1280, 7203, 6361, 13, 14116, 1600, 366, 81, 4943, 220, 1303, 18743, 3146, 284, 2872, 198, 198, 2, 26245, 3108, 284, 257, 8619, 286, ...
2.892256
297
import pytest import rasterio as rio from rasterio.io import DatasetWriter from cog_worker import Manager from rasterio import MemoryFile, crs TEST_COG = "tests/roads_cog.tif" def test_preview(molleweide_manager, sample_function): arr, bbox = molleweide_manager.preview(sample_function, max_size=123) assert max(arr.shape) == 123, "Expected maximum array dimension to be 123px" def test_tile(molleweide_manager, sample_function): arr, bbox = molleweide_manager.tile(sample_function, x=1, y=2, z=3) assert arr.shape == (1, 256, 256), "Expected 256x256 tile" def test_chunk_execute(molleweide_manager, sample_function): chunks = list(molleweide_manager.chunk_execute(sample_function, chunksize=123)) for arr, bbox in chunks: assert max(arr.shape) <= 123, "Max chunk size should be 123px"
[ 11748, 12972, 9288, 198, 11748, 374, 1603, 952, 355, 374, 952, 198, 6738, 374, 1603, 952, 13, 952, 1330, 16092, 292, 316, 34379, 198, 6738, 43072, 62, 28816, 1330, 9142, 198, 6738, 374, 1603, 952, 1330, 14059, 8979, 11, 1067, 82, 198,...
2.758278
302
from train import train_model from utils import * import os import sys pwd = os.environ.get('CLIP_DIR') DATA_DIR = "%s/data/processed/" % pwd exp_name = "non_multilabel" run_name = "sentence_structurel_with_crf" train_file_name = "MIMIC_train_binary.csv" dev_file_name = "MIMIC_val_binary.csv" test_file_name = "test_binary.csv" exp_name = "outputs_binary" train = read_sentence_structure(os.path.join(DATA_DIR, train_file_name)) dev = read_sentence_structure(os.path.join(DATA_DIR, dev_file_name)) test = read_sentence_structure(os.path.join(DATA_DIR, test_file_name)) run_name = "binary" if __name__ == "__main__": main(sys.argv[1:])
[ 6738, 4512, 1330, 4512, 62, 19849, 198, 6738, 3384, 4487, 1330, 1635, 198, 11748, 28686, 198, 11748, 25064, 198, 198, 79, 16993, 796, 28686, 13, 268, 2268, 13, 1136, 10786, 5097, 4061, 62, 34720, 11537, 198, 26947, 62, 34720, 796, 36521...
2.480769
260
from django.urls import path from . import views app_name = 'persons' urlpatterns = [ path('', views.PersonsTableView.as_view(),name='persons_list'), path('persons_details/<int:pk>',views.PersonsUpdateView.as_view(),name='persons_details_edit'), path('persons_details/create',views.PersonsCreateView.as_view(),name='persons_details_add'), path('persons_details/<int:pk>/delete',views.PersonsDeleteView.as_view(),name="persons_details_delete"), path('persons_details/sort',views.event_gate, name='sort'), ]
[ 6738, 42625, 14208, 13, 6371, 82, 1330, 3108, 198, 6738, 764, 1330, 5009, 628, 198, 1324, 62, 3672, 796, 705, 19276, 684, 6, 198, 6371, 33279, 82, 796, 685, 198, 220, 220, 220, 3108, 10786, 3256, 5009, 13, 30946, 684, 10962, 7680, 1...
2.764398
191
__title__ = 'logxs' __description__ = 'Replacing with build-in `print` with nice formatting.' __url__ = 'https://github.com/minlaxz/logxs' __version__ = '0.3.2' __author__ = 'Min Latt' __author_email__ = 'minminlaxz@gmail.com' __license__ = 'MIT'
[ 834, 7839, 834, 796, 705, 6404, 34223, 6, 198, 834, 11213, 834, 796, 705, 39232, 4092, 351, 1382, 12, 259, 4600, 4798, 63, 351, 3621, 33313, 2637, 198, 834, 6371, 834, 796, 705, 5450, 1378, 12567, 13, 785, 14, 1084, 75, 897, 89, 1...
2.589474
95
import time
[ 11748, 640, 628, 198 ]
3.5
4
from hytra.pluginsystem import transition_feature_vector_construction_plugin import numpy as np from compiler.ast import flatten
[ 6738, 2537, 9535, 13, 37390, 6781, 1330, 6801, 62, 30053, 62, 31364, 62, 9979, 2762, 62, 33803, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 17050, 13, 459, 1330, 27172, 268, 628 ]
4.0625
32
from matplotlib.style import available import pygame as pg from sprites.character import Character from pygame.math import Vector2 from settings import * from math import cos, pi from control import Controler from sprites.gun import MachineGun, Pistol, Rifle from managers.resourcemanager import ResourceManager as GR from utils.observable import Observable
[ 6738, 2603, 29487, 8019, 13, 7635, 1330, 1695, 198, 11748, 12972, 6057, 355, 23241, 198, 6738, 42866, 13, 22769, 1330, 15684, 198, 6738, 12972, 6057, 13, 11018, 1330, 20650, 17, 198, 6738, 6460, 1330, 1635, 198, 6738, 10688, 1330, 8615, ...
3.98913
92
# # Gtk+ UI pieces for BitBake # # Copyright (C) 2006-2007 Richard Purdie # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
[ 2, 198, 2, 402, 30488, 10, 12454, 5207, 329, 4722, 33, 539, 198, 2, 198, 2, 15069, 357, 34, 8, 4793, 12, 12726, 6219, 350, 2799, 494, 198, 2, 198, 2, 770, 1430, 318, 1479, 3788, 26, 345, 460, 17678, 4163, 340, 290, 14, 273, 13...
3.808511
188
# -*- coding: utf-8 -*- from django.db import migrations from tardis.tardis_portal.models import ( Schema, ParameterName, DatafileParameter, DatafileParameterSet ) from mytardisbf.apps import ( OMESCHEMA, BFSCHEMA ) def forward_func(apps, schema_editor): """Create mytardisbf schemas and parameternames""" db_alias = schema_editor.connection.alias ome_schema, _ = Schema.objects\ .using(db_alias)\ .update_or_create( name="OME Metadata", namespace="http://tardis.edu.au/schemas/bioformats/1", subtype=None, hidden=True, type=3, immutable=True, defaults={ 'namespace': OMESCHEMA } ) ParameterName.objects\ .using(db_alias)\ .update_or_create( name="ome", data_type=5, is_searchable=False, choices="", comparison_type=1, full_name="OME Metadata", units="xml", order=1, immutable=True, schema=ome_schema, defaults={ "full_name": "OMEXML Metadata" } ) series_schema, _ = Schema.objects\ .using(db_alias)\ .update_or_create( name="Series Metadata", namespace=BFSCHEMA, subtype="", hidden=False, type=3, immutable=True ) ParameterName.objects\ .using(db_alias)\ .update_or_create( name="id", data_type=2, is_searchable=True, choices="", comparison_type=8, full_name="ID", units="", order=9999, immutable=True, schema=series_schema, defaults={ "is_searchable": False } ) ParameterName.objects\ .using(db_alias)\ .update_or_create( name="name", data_type=2, is_searchable=True, choices="", comparison_type=8, full_name="Name", units="", order=9999, immutable=True, schema=series_schema ) ParameterName.objects\ .using(db_alias)\ .update_or_create( name="type", data_type=2, is_searchable=True, choices="", comparison_type=8, full_name="Pixel Type", units="", order=9999, immutable=True, schema=series_schema, defaults={ "name": "pixel_type" } ) ParameterName.objects\ .using(db_alias)\ .update_or_create( name="dimensionorder", data_type=2, is_searchable=True, choices="", comparison_type=8, full_name="Dimension Order", units="", order=9999, immutable=True, schema=series_schema ) ParameterName.objects\ .using(db_alias)\ .update_or_create( name="sizex", data_type=1, is_searchable=True, choices="", comparison_type=1, full_name="SizeX", units="", order=9999, immutable=True, schema=series_schema ) ParameterName.objects\ .using(db_alias)\ .update_or_create( name="sizey", data_type=1, is_searchable=True, choices="", comparison_type=1, full_name="SizeY", units="", order=9999, immutable=True, schema=series_schema ) ParameterName.objects\ .using(db_alias)\ .update_or_create( name="sizeZ", data_type=1, is_searchable=True, choices="", comparison_type=1, full_name="SizeZ", units="", order=9999, immutable=True, schema=series_schema ) ParameterName.objects\ .using(db_alias)\ .update_or_create( name="sizec", data_type=1, is_searchable=True, choices="", comparison_type=1, full_name="SizeC", units="", order=9999, immutable=True, schema=series_schema ) ParameterName.objects\ .using(db_alias)\ .update_or_create( name="sizet", data_type=1, is_searchable=True, choices="", comparison_type=1, full_name="SizeT", units="", order=9999, immutable=True, schema=series_schema ) ParameterName.objects\ .using(db_alias)\ .update_or_create( name="physicalsizex", data_type=1, is_searchable=True, choices="", comparison_type=1, full_name="Voxel Size X", units="", order=9999, immutable=True, schema=series_schema ) ParameterName.objects\ .using(db_alias)\ .update_or_create( name="physicalsizey", data_type=1, is_searchable=True, choices="", comparison_type=1, full_name="Voxel Size Y", units="", order=9999, immutable=True, schema=series_schema ) ParameterName.objects\ .using(db_alias)\ .update_or_create( name="physicalsizez", data_type=1, is_searchable=True, choices="", comparison_type=1, full_name="Voxel Size Z", units="", order=9999, immutable=True, schema=series_schema ) ParameterName.objects\ .using(db_alias)\ .update_or_create( name="timeincrement", data_type=1, is_searchable=True, choices="", comparison_type=1, full_name="Time Increment", units="", order=9999, immutable=True, schema=series_schema ) ParameterName.objects\ .using(db_alias)\ .update_or_create( name="excitationwavelength", data_type=2, is_searchable=True, choices="", comparison_type=1, full_name="Excitation Wavelength", units="", order=9999, immutable=True, schema=series_schema ) ParameterName.objects\ .using(db_alias)\ .update_or_create( name="samplesperpixel", data_type=2, is_searchable=True, choices="", comparison_type=1, full_name="Samples per Pixel", units="", order=9999, immutable=True, schema=series_schema ) ParameterName.objects\ .using(db_alias)\ .update_or_create( name="emissionwavelength", data_type=2, is_searchable=True, choices="", comparison_type=1, full_name="Emission Wavelength", units="", order=9999, immutable=True, schema=series_schema ) ParameterName.objects\ .using(db_alias)\ .update_or_create( name="pinholesize", data_type=2, is_searchable=True, choices="", comparison_type=1, full_name="Pinhole Size", units="", order=9999, immutable=True, schema=series_schema ) ParameterName.objects\ .using(db_alias)\ .update_or_create( name="previewImage", data_type=5, is_searchable=False, choices="", comparison_type=1, full_name="Preview", units="image", order=1, immutable=True, schema=series_schema, defaults={ "name": "preview_image" } )
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 198, 6738, 256, 446, 271, 13, 83, 446, 271, 62, 634, 282, 13, 27530, 1330, 357, 198, 220, 220, 220, 10011, 2611, ...
1.716132
4,953
# -*- coding: utf-8 -*- from django.db import models from datetime import datetime # Create your models here.
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 2, 13610, 534, 4981, 994, 13 ]
3.114286
35
#!/usr/bin/env python3 # # Copyright (c) 2021, The OpenThread Authors. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # 3. Neither the name of the copyright holder nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # import logging import unittest import pktverify from pktverify import packet_verifier, packet_filter, consts from pktverify.consts import MA1, PBBR_ALOC import config import thread_cert # Test description: # The purpose of this test case is to verify that a Primary BBR (DUT) can manage # a re-registration of a device on its network to remain receiving multicasts. # The test also verifies the usage of UDP multicast packets across backbone and # internal Thread network. # # Topology: # ----------------(eth)------------------ # | | | # BR_1 (Leader) ---- BR_2 HOST # | | # | | # Router_1 -----------+ # BR_1 = 1 BR_2 = 2 ROUTER_1 = 3 HOST = 4 REG_DELAY = 10 UDP_HEADER_LENGTH = 8 if __name__ == '__main__': unittest.main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 198, 2, 220, 15069, 357, 66, 8, 33448, 11, 383, 4946, 16818, 46665, 13, 198, 2, 220, 1439, 2489, 10395, 13, 198, 2, 198, 2, 220, 2297, 396, 3890, 290, 779, 287, 2723, 290,...
2.968485
825
import time import logging try: from pypylon import pylon except: pylon = None from . input import Input log = logging.getLogger(__name__) # writes the framenumber to the 8-11 bytes of the image as a big-endian set of octets # converts time from a float in seconds to an int64 in microseconds # writes the time to the first 7 bytes of the image as a big-endian set of octets
[ 11748, 640, 198, 11748, 18931, 198, 28311, 25, 198, 220, 220, 220, 422, 279, 4464, 15158, 1330, 279, 15158, 198, 16341, 25, 198, 220, 220, 220, 279, 15158, 796, 6045, 198, 198, 6738, 764, 5128, 1330, 23412, 198, 198, 6404, 796, 18931,...
3.252101
119
# -*- coding: utf-8 -*- # Copyright (c) 2021. Distributed under the terms of the MIT License. from phonopy.interface.calculator import read_crystal_structure from phonopy.structure.atoms import PhonopyAtoms from vise.util.phonopy.phonopy_input import structure_to_phonopy_atoms import numpy as np # # def test_make_phonopy_input(mc_structure, mc_structure_conv): # actual = make_phonopy_input(unitcell=mc_structure, # supercell_matrix=np.eye(3).tolist(), # conventional_base=True) # supercell_matrix = [[ 1., 1., 0.], # [-1., 1., 0.], # [ 0., 0., 1.]] # supercell = mc_structure * supercell_matrix # expected = PhonopyInput(unitcell=mc_structure, # supercell=supercell, # supercell_matrix=supercell_matrix) # assert actual == expected # # # def test_make_phonopy_input_default(mc_structure, mc_structure_conv): # actual = make_phonopy_input(unitcell=mc_structure) # supercell_matrix = [[ 2., 2., 0.], # [-2., 2., 0.], # [ 0., 0., 2.]] # supercell = mc_structure * supercell_matrix # expected = PhonopyInput(unitcell=mc_structure, # supercell=supercell, # supercell_matrix=supercell_matrix) # assert actual == expected # # # def test_make_phonopy_input_default_hexa(): # structure = Structure(Lattice.hexagonal(1.0, 2.0), species=["H"], # coords=[[0.0]*3]) # actual = make_phonopy_input(unitcell=structure) # supercell_matrix = [[2, -1, 0], [2, 1, 0], [0, 0, 2]] # supercell = structure * supercell_matrix # expected = PhonopyInput(unitcell=structure, # supercell=supercell, # supercell_matrix=supercell_matrix) # assert actual == expected
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 220, 15069, 357, 66, 8, 33448, 13, 4307, 6169, 739, 262, 2846, 286, 262, 17168, 13789, 13, 198, 6738, 32896, 11081, 13, 39994, 13, 9948, 3129, 1352, 1330, 1100, 62,...
1.962
1,000
""" 2020 Day 15 https://adventofcode.com/2020/day/15 """ from collections import deque from typing import Dict, Iterable, Optional import aocd # type: ignore def main() -> None: """ Calculate and output the solutions based on the real puzzle input. """ data = aocd.get_data(year=2020, day=15) emg = ElfMemoryGame(map(int, data.split(","))) emg.extend(2020) print(f"Part 1: {emg.latest}") emg.extend(30_000_000) print(f"Part 2: {emg.latest}") if __name__ == "__main__": main()
[ 37811, 198, 42334, 3596, 1315, 198, 5450, 1378, 324, 1151, 1659, 8189, 13, 785, 14, 42334, 14, 820, 14, 1314, 198, 37811, 198, 198, 6738, 17268, 1330, 390, 4188, 198, 6738, 19720, 1330, 360, 713, 11, 40806, 540, 11, 32233, 198, 11748,...
2.476415
212
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- # pylint: disable=too-few-public-methods, unused-argument, redefined-builtin from azure.cli.core.azclierror import ClientRequestError from ._util_enterprise import is_enterprise_tier
[ 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, 4091, 13789, 13, 14116, 287, 262, 1628, 6808, 329, 5964, 1321, 13, 198, 2, 16529, 1783, 10541, 198,...
5.165049
103
from typing import Any, TypeVar, Union from types import MethodType, FunctionType from .base_types import BooleanType, Constant, StringType, Collection, Referenceable from .type_checking import TypeChecker AnyArgs = TypeVar("AnyArgs") NoArgs = TypeVar("NoArgs") VarArgs = TypeVar("VarArgs") T = TypeVar("T") class ArithmeticF(WithOperatorSupport, F):
[ 6738, 19720, 1330, 4377, 11, 5994, 19852, 11, 4479, 198, 6738, 3858, 1330, 11789, 6030, 11, 15553, 6030, 198, 198, 6738, 764, 8692, 62, 19199, 1330, 41146, 6030, 11, 20217, 11, 10903, 6030, 11, 12251, 11, 20984, 540, 198, 6738, 764, 4...
3.307692
117
"""This script is for training and evaluating a model.""" import sys import os import traceback import numpy as np from functools import partial from utils import * from punctuator import Punctuator from bidirectional_gru_with_gru import BidirectionalGruWithGru from keras.callbacks import ModelCheckpoint from keras.models import Model, load_model, Sequential from keras.layers import Dense, Activation, Dropout, Input, Masking, TimeDistributed, LSTM, Conv1D, Embedding, RepeatVector, Lambda, Dot, Multiply, Concatenate, Permute from keras.layers import GRU, Bidirectional, BatchNormalization, Reshape, Flatten, ThresholdedReLU from keras.optimizers import Adam EMBEDDING_FILE = 'data/glove.6B.50d.txt' MODEL_FILE = 'data/model.json' WEIGHTS_FILE = 'data/model.h5' TEXT_FILE = 'data/utterances.txt' BATCH = 128 EPOCH = 1000 DEV_SIZE = 100 def load_text_data(textfile): """Read a text file containing lines of text. Args: textfile: string representing a path name to a file Returns: list of words """ words = [] with open(textfile, 'r') as lines: for line in lines: words.extend(line.split()) return words def main(): """Train a model using lines of text contained in a file and evaluates the model. """ #read golve vecs #words, word_to_index, index_to_word, word_to_vec_map = read_glove_vecs(EMBEDDING_FILE) #create word embedding matrix #embedding_matrix = create_emb_matrix(word_to_index, word_to_vec_map) embedding_matrix = None #print('shape of embedding_matrix:', embedding_matrix.shape) #load trainig text from a file utterances = load_text_data(TEXT_FILE) punctuator = Punctuator(None, None) X, Y = punctuator.create_training_data(utterances[:3], False) print(X.shape) print(X.shape[1]) print(Y.shape) #if a model already exists, load the model if os.path.isfile(MODEL_FILE) and False: punctuator.load_model(MODEL_FILE) else: model = BidirectionalGruWithGru.create_model( input_shape=(X.shape[1], X.shape[2], ), embedding_matrix=None, vocab_len=0, n_d1=128, n_d2=128, n_c=len(punctuator.labels)) print(model.summary()) punctuator.__model__ = model #if the model has been already trained, use the pre-trained weights if os.path.isfile(WEIGHTS_FILE): punctuator.load_weights(WEIGHTS_FILE) for i in range(100): shuffle(utterances) print(utterances[0]) #create an instance of Punctutor and create training data X, Y = punctuator.create_training_data(utterances[:300000], False) #shuffle the training data shuffle(X,Y) denom_Y = Y.swapaxes(0,1).sum((0,1)) print ('Summary of Y:', denom_Y) print('shape of X:', X.shape) print(X[0:10]) print('shape of Y:', Y.shape) print(Y[0:10]) #define optimizer and compile the model opt = Adam(lr=0.007, beta_1=0.9, beta_2=0.999, decay=0.01) punctuator.compile(opt, loss='categorical_crossentropy', metrics=['accuracy']) #split the training data into training set, test set, and dev set t_size = int(X.shape[0] * 0.9) train_X, train_Y = X[:t_size], Y[:t_size] test_X, test_Y = X[t_size:-DEV_SIZE], Y[t_size:-DEV_SIZE] dev_X, dev_Y = X[-DEV_SIZE:], Y[-DEV_SIZE:] print (train_Y.swapaxes(0,1).sum((0,1))) print (test_Y.swapaxes(0,1).sum((0,1))) #train the model punctuator.fit([train_X], train_Y, batch_size = BATCH, epochs=EPOCH) punctuator.save_model(MODEL_FILE) punctuator.save_weights(WEIGHTS_FILE) #evaluate the model on the dev set (or the test set) for i,example in enumerate(dev_X): prediction = punctuator.predict(example) punctuator.check_result(prediction, dev_Y[i]) #manually evaluate the model on an example examples = ["good morning chairman who I saw and members of the committee it's my pleasure to be here today I'm Elizabeth Ackles director of the office of rate payer advocates and I appreciate the chance to present on oris key activities from 2017 I have a short presentation and I'm going to move through it really quickly because you've had a long morning already and be happy to answer any questions that you have", "this was a measure that first was introduced back in 1979 known as the International bill of rights for women it is the first and only international instrument that comprehensively addresses women's rights within political cultural economic social and family life", "I'm Elizabeth Neumann from the San Francisco Department on the status of women Sita is not just about naming equal rights for women and girls it provides a framework to identify and address inequality", "we have monitored the demographics of commissioners and board members in San Francisco to assess the equality of political opportunities and after a decade of reports women are now half of appointees but white men are still over-represented and Asian and Latina men and women are underrepresented", "when the city and county faced a 300 million dollar budget deficit in 2003 a gender analysis of budget cuts by city departments identified the disproportionate effect on women and particularly women of color in the proposed layoffs and reduction of services"] for example in examples: words = example.split() x = punctuator.create_live_data(words) print x for s in x: print s prediction = punctuator.predict(s) result = punctuator.add_punctuation(prediction, words) print(result) if __name__ == "__main__": main()
[ 37811, 1212, 4226, 318, 329, 3047, 290, 22232, 257, 2746, 526, 15931, 198, 198, 11748, 25064, 198, 11748, 28686, 198, 11748, 12854, 1891, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 1257, 310, 10141, 1330, 13027, 198, 6738, 3384, 4487,...
2.728612
2,104
""" Contains a canned predictor for a GQN. """ import os import json import numpy as np import tensorflow as tf from .gqn_graph import gqn_draw from .gqn_params import create_gqn_config def _normalize_pose(pose): """ Converts a camera pose into the GQN format. Args: pose: [x, y, z, yaw, pitch]; x, y, z in [-1, 1]; yaw, pitch in euler degree Returns: [x, y, z, cos(yaw), sin(yaw), cos(pitch), sin(pitch)] """ norm_pose = np.zeros((7, )) norm_pose[0:3] = pose[0:3] norm_pose[3] = np.cos(np.deg2rad(pose[3])) norm_pose[4] = np.sin(np.deg2rad(pose[3])) norm_pose[5] = np.cos(np.deg2rad(pose[4])) norm_pose[6] = np.sin(np.deg2rad(pose[4])) # print("Normalized pose: %s -> %s" % (pose, norm_pose)) # DEBUG return norm_pose def clear_context(self): """Clears the current context.""" self._context_frames.clear() self._context_poses.clear() def render_query_view(self, pose: np.ndarray): """ Renders the scene from the given camera pose. Args: pose: [x, y, z, yaw, pitch]; x, y, z in [-1, 1]; yaw, pitch in euler degree """ assert len(self._context_frames) >= self._ctx_size \ and len(self._context_poses) >= self._ctx_size, \ "Not enough context points available. Required %d. Given: %d" % \ (self._ctx_size, np.min(len(self._context_frames), len(self._context_poses))) assert pose.shape == (self._dim_pose, ) or pose.shape == (5, ), \ "The pose's shape %s does not match the specification (either %s or %s)." % \ (pose.shape, self._dim_pose, (5, )) if pose.shape == (5, ): # assume un-normalized pose pose = _normalize_pose(pose) ctx_frames = np.expand_dims( np.stack(self._context_frames[-self._ctx_size:]), axis=0) ctx_poses = np.expand_dims( np.stack(self._context_poses[-self._ctx_size:]), axis=0) query_pose = np.expand_dims(pose, axis=0) feed_dict = { self._ph_query_pose : query_pose, self._ph_ctx_frames : ctx_frames, self._ph_ctx_poses : ctx_poses } [pred_frame] = self._sess.run([self._net], feed_dict=feed_dict) pred_frame = np.clip(pred_frame, a_min=0.0, a_max=1.0) return pred_frame
[ 37811, 198, 4264, 1299, 257, 32530, 41568, 329, 257, 402, 48, 45, 13, 198, 37811, 198, 198, 11748, 28686, 198, 11748, 33918, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 11192, 273, 11125, 355, 48700, 198, 198, 6738, 764, 70, ...
2.329087
942
# -*- coding: utf-8 -*- # Copyright (C) 2019, QuantStack # SPDX-License-Identifier: BSD-3-Clause from conda.base.constants import DepsModifier, UpdateModifier from conda._vendor.boltons.setutils import IndexedSet from conda.core.prefix_data import PrefixData from conda.models.prefix_graph import PrefixGraph from conda._vendor.toolz import concatv from conda.models.match_spec import MatchSpec
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 15069, 357, 34, 8, 13130, 11, 16972, 25896, 198, 2, 30628, 55, 12, 34156, 12, 33234, 7483, 25, 347, 10305, 12, 18, 12, 2601, 682, 198, 198, 6738, 1779, 64, 13, ...
3.007576
132
num = input() lucky = 0 for i in num: if i == '4' or i == '7': lucky += 1 counter = 0 for c in str(lucky): if c == '4' or c == '7': counter += 1 if counter == len(str(lucky)): print("YES") else: print("NO")
[ 22510, 796, 5128, 3419, 198, 75, 5309, 796, 657, 198, 220, 198, 1640, 1312, 287, 997, 25, 198, 220, 220, 220, 611, 1312, 6624, 705, 19, 6, 393, 1312, 6624, 705, 22, 10354, 198, 220, 220, 220, 220, 220, 220, 220, 9670, 15853, 352, ...
1.941176
136
from snakebids.utils.output import ( Mode, get_time_hash, prepare_output, retrofit_output, write_config_file, write_output_mode, ) from snakebids.utils.snakemake_io import ( glob_wildcards, regex, update_wildcard_constraints, ) __all__ = [ "Mode", "get_time_hash", "glob_wildcards", "prepare_output", "regex", "retrofit_output", "update_wildcard_constraints", "write_config_file", "write_output_mode", ]
[ 6738, 17522, 65, 2340, 13, 26791, 13, 22915, 1330, 357, 198, 220, 220, 220, 10363, 11, 198, 220, 220, 220, 651, 62, 2435, 62, 17831, 11, 198, 220, 220, 220, 8335, 62, 22915, 11, 198, 220, 220, 220, 12175, 11147, 62, 22915, 11, 198...
2.228972
214
import pydantic from vizno.renderers import ContentConfiguration, render from vizno.report import Report r = Report() r.widget(CustomObject(parameter=10)) r.render("./output") r.widget( CustomObject(parameter=1000), name="It works with a name", description="and a description", ) r.render("./output")
[ 11748, 279, 5173, 5109, 198, 198, 6738, 48569, 3919, 13, 10920, 19288, 1330, 14041, 38149, 11, 8543, 198, 6738, 48569, 3919, 13, 13116, 1330, 6358, 628, 628, 198, 198, 81, 796, 6358, 3419, 198, 81, 13, 42655, 7, 15022, 10267, 7, 17143...
3.009434
106
import abc import collections.abc import socket __all__ = ['get_socket_type', 'get_server_socket', 'get_client_socket', 'SocketReader', 'SocketWriter', 'JSONReader', 'JSONWriter']
[ 11748, 450, 66, 198, 11748, 17268, 13, 39305, 198, 11748, 17802, 628, 198, 834, 439, 834, 796, 37250, 1136, 62, 44971, 62, 4906, 3256, 705, 1136, 62, 15388, 62, 44971, 3256, 705, 1136, 62, 16366, 62, 44971, 3256, 198, 220, 220, 220, ...
2.897059
68
from django.urls import path, include from django.contrib import admin import hackdayproject.main.urls as main_urls import hackdayproject.repo.urls as repo_urls urlpatterns = [ path('admin/', admin.site.urls), path('oauth/', include('social_django.urls', namespace='social')), path('', include(main_urls)), path('repo/', include(repo_urls)) ]
[ 6738, 42625, 14208, 13, 6371, 82, 1330, 3108, 11, 2291, 198, 6738, 42625, 14208, 13, 3642, 822, 1330, 13169, 198, 11748, 8156, 820, 16302, 13, 12417, 13, 6371, 82, 355, 1388, 62, 6371, 82, 198, 11748, 8156, 820, 16302, 13, 260, 7501, ...
2.706767
133
#!/usr/bin/env python import unittest import logging import importlib import copy import os from mock import patch from nose.tools import raises logging.disable(logging.CRITICAL) ciftify_recon_all = importlib.import_module('ciftify.bin.ciftify_recon_all')
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 11748, 555, 715, 395, 198, 11748, 18931, 198, 11748, 1330, 8019, 198, 11748, 4866, 198, 11748, 28686, 198, 198, 6738, 15290, 1330, 8529, 198, 6738, 9686, 13, 31391, 1330, 12073, 198, 198...
2.977011
87
# -*- coding: utf-8 -*- ''' Created on Tue Jan 17 16:19:36 2017 @author: Boykai ''' #!/usr/bin/env python # -*- coding: utf-8 -*- import xml.etree.cElementTree as ET # Use cElementTree or lxml if too slow from collections import defaultdict import re import pprint import string import codecs import json import os from pymongo import MongoClient def mongoAggregate(cursor): ''' Takes in pymongo aggregate cursor object, iterates through each element within the aggregation, then returns the list of elements cursor: pymongo aggreate cursor object, which is iterated (a cursor object) @return: List of aggregation elements (a list) ''' results_list = [] [results_list.append(result) for result in cursor] return results_list if __name__ == '__main__': # Get OSM File, which is Brooklyn OpenStreetMap # https://mapzen.com/data/metro-extracts/metro/brooklyn_new-york/ xml_original_file = 'brooklyn_new-york.osm' # Original OSM File input name xml_sample_file = 'sample.osm' # Sample OSM File output name xml_cleaned_file = 'output.osm' sample_size = 1 # Initialize and create OSM original file and sample file if sample_size == 1: xml_sample_file = xml_original_file osm = OSMFile(xml_original_file, xml_sample_file, sample_size) if sample_size != 1: osm.createSampleFile() # Initialize and clean street type tag attributes print('\nInitialzing and getting street type tag attributes...') cleanSt = CleanStreets(xml_sample_file) # Audit street tag attributes and store vales in unexpected_street dict # returns street type keys with street name values dict print('\nPerforming audit on street types...') audit_results = cleanSt.audit(xml_sample_file) unexpected_streets = audit_results[0] unexpected_zips = audit_results[1] print('There are ' + str(len(unexpected_streets.values())) + ' unique unexpected streets.') print('Dictionary of unexpected street name types with street names: ') pprint.pprint(unexpected_streets) print('\nThere are ' + str(len(unexpected_zips.values())) + ' unique unexpected zip codes.') print('Dictionary of unexpected zip code types with street names: ') pprint.pprint(unexpected_zips) # Clean street values and store cleaned streets in clean_street_dict print('\nCleaning street type values...') clean_streets_dict = cleanSt.clean(unexpected_streets) print('There are ' + str(len(cleanSt.getCleanStreetsDict().values())) + ' street names to be replaced.') print('Dictionary of dirty street keys and clean street values: ') pprint.pprint(clean_streets_dict) # Find and write clean street names to XML file, save updated XML file print('\nCreating new output.osm file with cleaned street types...') cleanSt.writeClean(clean_streets_dict) clean_audit_results = cleanSt.audit(xml_sample_file) clean_unexpected_streets = clean_audit_results[0] print('There are ' + str(len(clean_unexpected_streets.values())) + ' unique unexpected streets.') print('New audit after street names have been replaced with clean street names: ') pprint.pprint(clean_unexpected_streets) if sample_size != 1: print('\nDeleting XML sample file...') #os.remove(xml_sample_file) # Initialize and create JSON file from cleaned XML output.osm file print('\nCreating new JSON file from cleaned XML file...') js = JsonFile(xml_cleaned_file) data = js.processMap() print('\nDeleting XML cleaned file...') os.remove(xml_cleaned_file) # Initialize and create MongoDB database from JSON document list 'data' print('\nCreating new MongoDB database \'brooklyn\' from cleaned JSON file...') client = MongoClient('mongodb://localhost:27017') db = client.osm_results db.brooklyn.insert_many(data, bypass_document_validation=True) del data[:] # Run and output MongoDB querires and results print('\nRunning MongoDB queries...') print('\nTotal number of documents: ') print('db.brooklyn.find().count()') print(str(db.brooklyn.find().count())) print('\nNumber of \'way\' type documents: ') print('db.brooklyn.find({\'type\' :\'way\'}).count()') print(str(db.brooklyn.find({'type' :'way'}).count())) print('\nNumber of \'node\' type documents: ') print('db.brooklyn.find({\'type\' :\'node\'}).count()') print(str(db.brooklyn.find({'type' :'node'}).count())) print('\nNumber of unique users: ') print('len(db.brooklyn.distinct(\'created.user\'))') print(str(len(db.brooklyn.distinct('created.user')))) print('\nTop 1 contributing user: ') top_contributor_pipeline = [{'$group': {'_id':'$created.user', 'count':{'$sum':1}}}, {'$sort': {'count':1}}, {'$limit':1}] print('db.brooklyn.aggregate(' + str(top_contributor_pipeline) + ')') top_contributor = mongoAggregate(db.brooklyn.aggregate(top_contributor_pipeline)) print(str(top_contributor[0])) print('\nNumber of users appearing only once (having 1 post): ') unique_user_count_pipeline =[{'$group': {'_id':'$created.user', 'count':{'$sum':1}}}, {'$group': {'_id':'$count', 'num_users':{'$sum':1}}}, {'$sort': {'_id':1}}, {'$limit':1}] print('db.brooklyn.aggregate(' + str(unique_user_count_pipeline) + ')') unique_user_count = mongoAggregate(db.brooklyn.aggregate(unique_user_count_pipeline)) print(str(unique_user_count[0])) print('\nTop 10 appearing amenities: ') top_10_amenities_pipeline = [{'$match': {'amenity':{'$exists':1}}}, {'$group': {'_id':'$amenity', 'count':{'$sum':1}}}, {'$sort': {'count':1}}, {"$limit":10}] print('db.brooklyn.aggregate(' + str(top_10_amenities_pipeline) + ')') top_10_amenities = mongoAggregate(db.brooklyn.aggregate(top_10_amenities_pipeline)) print(str(top_10_amenities)) print('\nHighest population religion: ') most_pop_religion_pipeline = [{'$match': {'amenity':{'$exists':1}, 'amenity':'place_of_worship'}}, {'$group': {'_id':'$religion', 'count':{'$sum':1}}}, {'$sort': {'count':1}}, {'$limit':1}] print('db.brooklyn.aggregate(' + str(most_pop_religion_pipeline) + ')') most_pop_religion = mongoAggregate(db.brooklyn.aggregate(most_pop_religion_pipeline)) print(str(most_pop_religion[0])) print('\nMost popular cuisines: ') most_pop_cuisine_pipeline = [{'$match': {'amenity':{'$exists':1}, 'amenity':'restaurant'}}, {'$group': {'_id':'$cuisine', 'count':{'$sum':1}}}, {'$sort': {'count':1}}, {'$limit':2}] print('db.brooklyn.aggregate(' + str(most_pop_cuisine_pipeline) + ')') most_pop_cuisine = mongoAggregate(db.brooklyn.aggregate(most_pop_cuisine_pipeline)) print(str(most_pop_cuisine[0])) print('\nPostal Codes: ') postal_codes_pipeline = [{'$match': {'address.postcode':{'$exists':1}, 'address.postcode':'NaN'}}, {'$group': {'_id':'$address.postcode', 'count':{'$sum':1}}}, {'$sort':{'count':1}}] print('db.brooklyn.aggregate(' + str(postal_codes_pipeline) + ')') postal_codes = mongoAggregate(db.brooklyn.aggregate(postal_codes_pipeline)) print(str(postal_codes[0]))
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 7061, 6, 198, 41972, 319, 30030, 2365, 1596, 1467, 25, 1129, 25, 2623, 2177, 198, 198, 31, 9800, 25, 6387, 32765, 198, 7061, 6, 198, 198, 2, 48443, 14629, 14, 8800, ...
1.964262
4,589
r""" Currently, this package is experimental and may change in the future. """ from __future__ import absolute_import #------------------------------------------------------------------------------ # this little trick is for static builds of VTK. In such builds, if # the user imports this Python package in a non-statically linked Python # interpreter i.e. not of the of the VTK-python executables, then we import the # static components importer module. try: from . import vtkCommonCore except ImportError: from . import _vtkpythonmodules_importer #------------------------------------------------------------------------------
[ 81, 37811, 198, 21327, 11, 428, 5301, 318, 11992, 290, 743, 1487, 287, 262, 2003, 13, 198, 37811, 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 628, 198, 2, 10097, 26171, 198, 2, 428, 1310, 6908, 318, 329, 9037, 12188, 286, 3...
4.705882
136
from django.db import models from django.contrib.auth.models import User # Create your models here.
[ 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 27530, 1330, 11787, 198, 2, 13610, 534, 4981, 994, 13, 198 ]
3.571429
28
from django.db import models """ ShipmentModels have a one to many relationship with boxes and aliquot Aliquot and Box foreign keys to a ShipmentModel determine manifest contents for shipping purposes (resolved in schema return for manifest view) """
[ 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 198, 37811, 198, 220, 220, 220, 911, 4667, 5841, 1424, 423, 257, 530, 284, 867, 2776, 351, 10559, 290, 435, 1557, 313, 198, 220, 220, 220, 978, 1557, 313, 290, 8315, 3215, 8251, 284, 25...
3.760563
71
""" Consuming Iterator manually """ from collections import namedtuple def cast(data_type, value): """Cast the value into a correct data type""" if data_type == 'DOUBLE': return float(value) elif data_type == 'STRING': return str(value) elif data_type == 'INT': return int(value) # cars = [] # with open('cars.csv') as file: # row_index = 0 # for line in file: # if row_index == 0: # # Header row # headers = line.strip('\n').split(';') # Car = namedtuple('Car', headers) # elif row_index == 1: # data_types = line.strip('\n').split(';') # # print('types', data_types) # else: # # data row # data = line.strip('\n').split(';') # data = cast_row(data_types, data) # car = Car(*data) # cars.append(car) # # print(data) # row_index += 1 # with open('cars.csv') as file: # file_iter = iter(file) # headers = next(file_iter).strip('\n').split(';') # Car = namedtuple('Car', headers) # data_types = next(file_iter).strip('\n').split(';') # for line in file_iter: # data = line.strip('\n').split(';') # data = cast_row(data_types, data) # car = Car(*data) # cars.append(car) with open('cars.csv') as file: file_iter = iter(file) headers = next(file_iter).strip('\n').split(';') Car = namedtuple('Car', headers) data_types = next(file_iter).strip('\n').split(';') cars = [Car(*cast_row( data_types, line.strip('\n').split(';') )) for line in file_iter] print(cars)
[ 37811, 198, 9444, 12595, 40806, 1352, 14500, 198, 37811, 198, 6738, 17268, 1330, 3706, 83, 29291, 628, 198, 4299, 3350, 7, 7890, 62, 4906, 11, 1988, 2599, 198, 220, 220, 220, 37227, 19248, 262, 1988, 656, 257, 3376, 1366, 2099, 37811, ...
2.035714
840
#! Copyright (C) 2017 Christian Stransky #! #! This software may be modified and distributed under the terms #! of the MIT license. See the LICENSE file for details. from flask import Flask, redirect, request, make_response from shutil import copyfile import json import requests import os.path import uuid import urllib app = Flask(__name__) remote_task_file = "%landingURL%/get_ipynb/" target_file = "/home/jupyter/tasks.ipynb" user_data_file = "/home/jupyter/.instanceInfo" if __name__ == '__main__': #app.debug = True app.run(host='127.0.0.1', port=60000)
[ 2, 0, 15069, 357, 34, 8, 2177, 4302, 4285, 49792, 201, 198, 2, 0, 201, 198, 2, 0, 770, 3788, 743, 307, 9518, 290, 9387, 739, 262, 2846, 201, 198, 2, 0, 286, 262, 17168, 5964, 13, 220, 4091, 262, 38559, 24290, 2393, 329, 3307, ...
2.704545
220
import numpy as np import math import logging from termcolor import colored # Check a matrix for: negative eigenvalues, asymmetry and negative diagonal values
[ 11748, 299, 32152, 355, 45941, 198, 11748, 10688, 198, 11748, 18931, 198, 6738, 3381, 8043, 1330, 16396, 198, 198, 2, 6822, 257, 17593, 329, 25, 4633, 304, 9324, 27160, 11, 30372, 11973, 290, 4633, 40039, 3815, 198 ]
4.324324
37
""" * * Author: Juarez Paulino(coderemite) * Email: juarez.paulino@gmail.com * """ I=lambda:map(int,input().split()) f=abs n,_,a,b,k=I() while k: p,q,u,v=I() P=[a,b] if a<=q<=b:P+=[q] if a<=v<=b:P+=[v] print([min(f(q-x)+f(v-x)for x in P)+f(p-u),f(q-v)][p==u]) k-=1
[ 37811, 198, 1635, 198, 1635, 6434, 25, 220, 12585, 19655, 3362, 2879, 7, 19815, 567, 32937, 8, 198, 1635, 9570, 25, 7544, 19655, 13, 79, 2518, 2879, 31, 14816, 13, 785, 198, 1635, 198, 37227, 198, 40, 28, 50033, 25, 8899, 7, 600, ...
1.688623
167
import json import sys import pandas args = sys.argv if len(args) == 1 : import main as settings else : import sub as settings from requests_oauthlib import OAuth1Session CK = settings.CONSUMER_KEY CS = settings.CONSUMER_SECRET AT = settings.ACCESS_TOKEN ATS = settings.ACCESS_TOKEN_SECRET twitter = OAuth1Session(CK, CS, AT, ATS) tweetlist = [] url = "https://api.twitter.com/1.1/statuses/user_timeline.json" params = {"count" : 200} for i range(5): res = twitter.get(url, params = params) if res.status_code == 200: timelines = json.loads(res.text) for tweet in timelines: tweetlist.append(tweet["text"]) else: print("(%d)" % res.status_code) datafile = pandas.DataFrame(tweetlist) datafile.to_csv("tweetlist.csv", encoding='utf_8_sig')
[ 11748, 33918, 201, 198, 11748, 25064, 201, 198, 11748, 19798, 292, 201, 198, 201, 198, 22046, 796, 25064, 13, 853, 85, 201, 198, 201, 198, 361, 18896, 7, 22046, 8, 6624, 352, 1058, 201, 198, 220, 220, 220, 1330, 1388, 355, 6460, 201...
2.298913
368
"""This module contains a function for validating a scratch config entry.""" import re from idact.detail.config.validation.validation_error_message import \ validation_error_message VALID_SCRATCH_DESCRIPTION = 'Non-empty absolute path, or environment' \ ' variable name.' VALID_SCRATCH_REGEX = r"^(/.*)|(\$[A-Za-z][A-Za-z0-9]*)$" # noqa, pylint: disable=line-too-long __COMPILED = re.compile(pattern=VALID_SCRATCH_REGEX) def validate_scratch(scratch) -> str: """Returns the parameter if it's a valid scratch config entry, otherwise raises an exception. Key path is optional, non-empty string. :param scratch: Object to validate. :raises TypeError: On wrong type. :raises ValueError: On regex mismatch. """ if not isinstance(scratch, str): raise TypeError(validation_error_message( label='scratch', value=scratch, expected=VALID_SCRATCH_DESCRIPTION, regex=VALID_SCRATCH_REGEX)) if not __COMPILED.match(scratch): raise ValueError(validation_error_message( label='scratch', value=scratch, expected=VALID_SCRATCH_DESCRIPTION, regex=VALID_SCRATCH_REGEX)) return scratch
[ 37811, 1212, 8265, 4909, 257, 2163, 329, 4938, 803, 257, 12692, 4566, 5726, 526, 15931, 198, 198, 11748, 302, 198, 198, 6738, 4686, 529, 13, 49170, 13, 11250, 13, 12102, 341, 13, 12102, 341, 62, 18224, 62, 20500, 1330, 3467, 198, 220,...
2.351648
546
import warnings from typing import Callable, List, Optional, Union import mpmath import numpy as np import paramak import sympy as sp from paramak import RotateMixedShape, diff_between_angles from paramak.parametric_components.tokamak_plasma_plasmaboundaries import \ PlasmaBoundaries from scipy.interpolate import interp1d def create_offset_points(self, thetas, offset): """generates a list of points following parametric equations with an offset Args: thetas (np.array): the angles in degrees. offset (callable): offset value (cm). offset=0 will follow the parametric equations. Returns: list: list of points [[R1, Z1, connection1], [R2, Z2, connection2], ...] """ # create sympy objects and derivatives theta_sp = sp.Symbol("theta") R_sp, Z_sp = self.distribution(theta_sp, pkg=sp) R_derivative = sp.diff(R_sp, theta_sp) Z_derivative = sp.diff(Z_sp, theta_sp) points = [] for theta in thetas: # get local value of derivatives val_R_derivative = float(R_derivative.subs("theta", theta)) val_Z_derivative = float(Z_derivative.subs("theta", theta)) # get normal vector components nx = val_Z_derivative ny = -val_R_derivative # normalise normal vector normal_vector_norm = (nx ** 2 + ny ** 2) ** 0.5 nx /= normal_vector_norm ny /= normal_vector_norm # calculate outer points val_R_outer = self.distribution(theta)[0] + offset(theta) * nx val_Z_outer = self.distribution(theta)[1] + offset(theta) * ny if float(val_R_outer) > 0: points.append( [float(val_R_outer), float(val_Z_outer), "spline"]) else: self._overlapping_shape = True return points def distribution(self, theta, pkg=np): """Plasma distribution theta in degrees Args: theta (float or np.array or sp.Symbol): the angle(s) in degrees. pkg (module, optional): Module to use in the funciton. If sp, as sympy object will be returned. If np, a np.array or a float will be returned. Defaults to np. Returns: (float, float) or (sympy.Add, sympy.Mul) or (numpy.array, numpy.array): The R and Z coordinates of the point with angle theta """ if pkg == np: theta = np.radians(theta) else: theta = mpmath.radians(theta) R = self.major_radius + self.minor_radius * pkg.cos( theta + self.triangularity * pkg.sin(theta) ) Z = ( self.elongation * self.minor_radius * pkg.sin(theta) + self.vertical_displacement ) return R, Z
[ 198, 11748, 14601, 198, 6738, 19720, 1330, 4889, 540, 11, 7343, 11, 32233, 11, 4479, 198, 198, 11748, 285, 4426, 776, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 5772, 461, 198, 11748, 10558, 88, 355, 599, 198, 6738, 5772, 461, 13...
2.073239
1,420
s=str(input()) a=[] for i in range(len(s)): si=s[i] a.append(si) b=[] n=str(input()) for j in range(len(n)): sj=n[j] b.append(sj) p={} for pi in range(len(s)): key=s[pi] p[key]=0 j1=0 for i in range(0,len(a)): key=a[i] while j1<len(b): bj=b[0] if key in p: p[key]=bj b.remove(bj) break c=[] si=str(input()) for si1 in range(0,len(si)): ci=si[si1] c.append(ci) co=[] for ci in range(0,len(c)): if c[ci] in p: cco=c[ci] pco=p[cco] co.append(pco) d=[] di=str(input()) for sj1 in range(0,len(di)): dj=di[sj1] d.append(dj) do=[] for di in range(0,len(d)): for key in p: pkey=key if p.get(key) == d[di]: ddo=pkey do.append(ddo) for i in range (0,len(co)): print(co[i],end='') print() for j in range (0,len(do)): print(do[j],end='')
[ 82, 28, 2536, 7, 15414, 28955, 198, 64, 28, 21737, 198, 1640, 1312, 287, 2837, 7, 11925, 7, 82, 8, 2599, 198, 220, 220, 220, 33721, 28, 82, 58, 72, 60, 198, 220, 220, 220, 257, 13, 33295, 7, 13396, 8, 198, 65, 28, 21737, 198, ...
1.62254
559
# # Copyright (c) 2021 Airbyte, Inc., all rights reserved. # import datetime import json from typing import Any, Iterable, List, Mapping, MutableMapping, Optional, Tuple, Union import plaid from airbyte_cdk.logger import AirbyteLogger from airbyte_cdk.models import SyncMode from airbyte_cdk.sources import AbstractSource from airbyte_cdk.sources.streams import Stream from plaid.api import plaid_api from plaid.model.accounts_balance_get_request import AccountsBalanceGetRequest from plaid.model.transactions_get_request import TransactionsGetRequest SPEC_ENV_TO_PLAID_ENV = { "production": plaid.Environment.Production, "development": plaid.Environment.Development, "sandbox": plaid.Environment.Sandbox, } class IncrementalTransactionStream(PlaidStream): def get_updated_state(self, current_stream_state: MutableMapping[str, Any], latest_record: Mapping[str, Any]): return {"date": latest_record.get("date")} def read_records( self, sync_mode: SyncMode, cursor_field: List[str] = None, stream_slice: Mapping[str, Any] = None, stream_state: Mapping[str, Any] = None, ) -> Iterable[Mapping[str, Any]]: stream_state = stream_state or {} date = stream_state.get("date") if not date: date = datetime.date.fromtimestamp(0) else: date = datetime.date.fromisoformat(date) if date >= datetime.datetime.utcnow().date(): return transaction_response = self.client.transactions_get( TransactionsGetRequest(access_token=self.access_token, start_date=date, end_date=datetime.datetime.utcnow().date()) ) yield from map(lambda x: x.to_dict(), sorted(transaction_response["transactions"], key=lambda t: t["date"])) class SourcePlaid(AbstractSource):
[ 2, 198, 2, 15069, 357, 66, 8, 33448, 3701, 26327, 11, 3457, 1539, 477, 2489, 10395, 13, 198, 2, 198, 198, 11748, 4818, 8079, 198, 11748, 33918, 198, 6738, 19720, 1330, 4377, 11, 40806, 540, 11, 7343, 11, 337, 5912, 11, 13859, 540, ...
2.676901
684
from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import csv import os import shutil from PIL import Image import torch import torch.nn.parallel import torch.backends.cudnn as cudnn import torch.optim import torch.utils.data import torch.utils.data.distributed import torchvision.transforms as transforms import torchvision import cv2 import numpy as np import time import math import _init_paths import models from config import cfg from config import update_config from core.function import get_final_preds from utils.transforms import get_affine_transform COCO_KEYPOINT_INDEXES = { 0: 'nose', 1: 'left_eye', 2: 'right_eye', 3: 'left_ear', 4: 'right_ear', 5: 'left_shoulder', 6: 'right_shoulder', 7: 'left_elbow', 8: 'right_elbow', 9: 'left_wrist', 10: 'right_wrist', 11: 'left_hip', 12: 'right_hip', 13: 'left_knee', 14: 'right_knee', 15: 'left_ankle', 16: 'right_ankle' } COCO_INSTANCE_CATEGORY_NAMES = [ '__background__', 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light', 'fire hydrant', 'N/A', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow', 'elephant', 'bear', 'zebra', 'giraffe', 'N/A', 'backpack', 'umbrella', 'N/A', 'N/A', 'handbag', 'tie', 'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard', 'tennis racket', 'bottle', 'N/A', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple', 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed', 'N/A', 'dining table', 'N/A', 'N/A', 'toilet', 'N/A', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone', 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'N/A', 'book', 'clock', 'vase', 'scissors', 'teddy bear', 'hair drier', 'toothbrush' ] SKELETON = [ [5, 7], [7, 9],[5, 6],[6, 8], [8, 10] ] ## : # SKELETON = [ # [1, 3], [1, 0], [2, 4], [2, 0], [0, 5], [0, 6], [5, 7], [7, 9], [6, 8], [8, 10], [5, 11], [6, 12], [11, 12], # [11, 13], [13, 15], [12, 14], [14, 16] #] CocoColors = [[255, 0, 0], [255, 85, 0], [255, 170, 0], [255, 255, 0], [170, 255, 0], [85, 255, 0], [0, 255, 0], [0, 255, 85], [0, 255, 170], [0, 255, 255], [0, 170, 255], [0, 85, 255], [0, 0, 255], [85, 0, 255], [170, 0, 255], [255, 0, 255], [255, 0, 170], [255, 0, 85]] NUM_KPTS = 17 CTX = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu') def draw_pose(keypoints, img): """draw the keypoints and the skeletons. :params keypoints: the shape should be equal to [17,2] :params img: """ # # assert keypoints.shape == (NUM_KPTS, 2) # for i in range(len(SKELETON)): # kpt_a, kpt_b = SKELETON[i][0], SKELETON[i][1] # x_a, y_a = keypoints[kpt_a][0], keypoints[kpt_a][1] # x_b, y_b = keypoints[kpt_b][0], keypoints[kpt_b][1] # cv2.circle(img, (int(x_a), int(y_a)), 6, CocoColors[i], -1) # cv2.circle(img, (int(x_b), int(y_b)), 6, CocoColors[i], -1) # cv2.line(img, (int(x_a), int(y_a)), (int(x_b), int(y_b)), CocoColors[i], 2) for i in range(len(SKELETON)): kpt_a, kpt_b = SKELETON[i][0], SKELETON[i][1] x_a, y_a = keypoints[kpt_a][0], keypoints[kpt_a][1] x_b, y_b = keypoints[kpt_b][0], keypoints[kpt_b][1] cv2.circle(img, (int(x_a), int(y_a)), 10, CocoColors[i], -1) cv2.circle(img, (int(x_b), int(y_b)), 10, CocoColors[i], -1) cv2.line(img, (int(x_a), int(y_a)), (int(x_b), int(y_b)), CocoColors[i], 7) def draw_bbox(box, img): """draw the detected bounding box on the image. :param img: """ cv2.rectangle(img, box[0], box[1], color=(0, 255, 0), thickness=3) def box_to_center_scale(box, model_image_width, model_image_height): """convert a box to center,scale information required for pose transformation Parameters ---------- box : list of tuple list of length 2 with two tuples of floats representing bottom left and top right corner of a box model_image_width : int model_image_height : int Returns ------- (numpy array, numpy array) Two numpy arrays, coordinates for the center of the box and the scale of the box """ center = np.zeros((2), dtype=np.float32) bottom_left_corner = box[0] top_right_corner = box[1] box_width = top_right_corner[0] - bottom_left_corner[0] box_height = top_right_corner[1] - bottom_left_corner[1] bottom_left_x = bottom_left_corner[0] bottom_left_y = bottom_left_corner[1] center[0] = bottom_left_x + box_width * 0.5 center[1] = bottom_left_y + box_height * 0.5 aspect_ratio = model_image_width * 1.0 / model_image_height pixel_std = 200 if box_width > aspect_ratio * box_height: box_height = box_width * 1.0 / aspect_ratio elif box_width < aspect_ratio * box_height: box_width = box_height * aspect_ratio scale = np.array( [box_width * 1.0 / pixel_std, box_height * 1.0 / pixel_std], dtype=np.float32) if center[0] != -1: scale = scale * 1.25 return center, scale if __name__ == '__main__': main()
[ 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 6738, 11593, 37443, 834, 1330, 7297, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 198, 11748, 1822, 29572, 198, 11748, 269, 21370, 198, 11748, 28686, 198, 11748, 4423, 346, ...
2.223819
2,435
from __future__ import division import sqlite3 from bisect import bisect_left import plotly.plotly as py from plotly.graph_objs import Scatter, Figure, Layout, Data, YAxis, XAxis from feemodel.util import DataSample from feemodel.app.predict import PVALS_DBFILE from feemodeldata.plotting.plotrrd import BASEDIR def get_txgroups(txs, feerates=(10000, 15000, 20000, 50000)): """Sort the txs by feerate.""" txs.sort() txfeerates, _dum = zip(*txs) idxs = [bisect_left(txfeerates, feerate) for feerate in feerates] idxs.insert(0, 0) print("idxs are {}.".format(idxs)) txgroups = [txs[idxs[i]:idxs[i+1]] for i in range(len(idxs)-1)] return txgroups
[ 6738, 11593, 37443, 834, 1330, 7297, 198, 198, 11748, 44161, 578, 18, 198, 6738, 47457, 478, 1330, 47457, 478, 62, 9464, 198, 198, 11748, 7110, 306, 13, 29487, 306, 355, 12972, 198, 6738, 7110, 306, 13, 34960, 62, 672, 8457, 1330, 144...
2.480144
277
import torch import torch.nn.functional as F from torch.autograd import Variable import numpy as np import os import math from utils import logger use_cuda = torch.cuda.is_available() # utility # optimization # reference: http://pytorch.org/docs/master/_modules/torch/optim/lr_scheduler.html#ReduceLROnPlateau # model save and loading # class weighted_BCELoss(Module): # def __init__(self, mode): # self.mode = mode # # def forward(self, input, target, weight=10): # if not (input.size() == target.size()): # raise ValueError("Target and input must have the same size. target size ({}) " # "!= input size ({})".format(target.size(), input.size())) # loss_matrix = - (torch.mul(target, input.log()) + torch.mul(1 - target, (1 - input).log())) # one_matrix = Variable(torch.ones(input.size())) # if use_cuda: # one_matrix = one_matrix.cuda() # if self.mode == 'one': # weight_matrix = (weight - 1) * target + one_matrix # elif self.mode == 'pitch': # # weighted_loss_matrix = torch.mul(loss_matrix, weight_matrix) # return torch.mean(weighted_loss_matrix) # loss
[ 198, 11748, 28034, 198, 11748, 28034, 13, 20471, 13, 45124, 355, 376, 198, 6738, 28034, 13, 2306, 519, 6335, 1330, 35748, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 28686, 198, 11748, 10688, 198, 6738, 3384, 4487, 1330, 49706, 198, ...
2.318786
527
from dataclasses import field from marshmallow import Schema, ValidationError, post_load, schema from marshmallow.validate import OneOf, Length from marshmallow.fields import Bool, Str, List, Nested, Email from flask_rebar import ResponseSchema, RequestSchema, errors from ecosante.inscription.models import Inscription from ecosante.utils.custom_fields import TempList from ecosante.api.schemas.commune import CommuneSchema from ecosante.extensions import celery from indice_pollution.history.models import Commune as CommuneModel from flask import request
[ 6738, 4818, 330, 28958, 1330, 2214, 198, 6738, 22397, 42725, 1330, 10011, 2611, 11, 3254, 24765, 12331, 11, 1281, 62, 2220, 11, 32815, 198, 6738, 22397, 42725, 13, 12102, 378, 1330, 1881, 5189, 11, 22313, 198, 6738, 22397, 42725, 13, 25...
3.63871
155
import math # Exercise 017: Right Triangle """Write a program that reads the length of the opposite side and the adjacent side of a right triangle. Calculate and display the length of the hypotenuse.""" # To do this we will use the Pythagorean theorem: a^2 = b^2 + c^2 # Method 01, without the module Math: # First we ask for the leg values leg_a = float(input("Enter the value of leg a: ")) leg_b = float(input("Enter the value of leg b: ")) # Then we do the Pythagorean theorem: sqrt((leg_a^2)+(leg_b^2)) hyp = ((leg_a**2) + (leg_b**2)) ** 0.5 print(f"The triangle hypotenuse measures {hyp:.2f} m.u. ") # Method 02, with the module using pow function: hypo = math.sqrt(math.pow(leg_a, 2) + math.pow(leg_b, 2)) print(f"The triangle hypotenuse measures {hypo:.2f} m.u. ") # Method 03 using the module with the hypotenuse function u.u hypot = math.hypot(leg_a, leg_b) print(f"The triangle hypotenuse measures {hypot:.2f} m.u. ")
[ 11748, 10688, 198, 198, 2, 32900, 5534, 22, 25, 6498, 33233, 198, 37811, 16594, 257, 1430, 326, 9743, 262, 4129, 286, 262, 6697, 1735, 290, 262, 15909, 1735, 286, 257, 826, 22950, 13, 198, 9771, 3129, 378, 290, 3359, 262, 4129, 286, ...
2.801802
333
"""Package groups the different commands modules.""" from annuaire.commands import download, import_lawyers __all__ = [download, import_lawyers]
[ 37811, 27813, 2628, 262, 1180, 9729, 13103, 526, 15931, 198, 6738, 1529, 6413, 557, 13, 9503, 1746, 1330, 4321, 11, 1330, 62, 6270, 21200, 198, 198, 834, 439, 834, 796, 685, 15002, 11, 1330, 62, 6270, 21200, 60, 198 ]
3.74359
39
import logging from thespian.actors import * from eventsourcing.application.process import ProcessApplication, Prompt from eventsourcing.application.system import System, SystemRunner from eventsourcing.domain.model.events import subscribe, unsubscribe from eventsourcing.interface.notificationlog import RecordManagerNotificationLog logger = logging.getLogger() # Todo: Send timer message to run slave every so often (in master or slave?). DEFAULT_ACTORS_LOGCFG = { 'version': 1, 'formatters': { 'normal': { 'format': '%(levelname)-8s %(message)s' } }, 'handlers': { # 'h': { # 'class': 'logging.FileHandler', # 'filename': 'hello.log', # 'formatter': 'normal', # 'level': logging.INFO # } }, 'loggers': { # '': {'handlers': ['h'], 'level': logging.DEBUG} } } # def start_multiproc_udp_base_system(): # start_actor_system(system_base='multiprocUDPBase') # # # def start_multiproc_queue_base_system(): # start_actor_system(system_base='multiprocQueueBase')
[ 11748, 18931, 198, 198, 6738, 262, 2777, 666, 13, 529, 669, 1330, 1635, 198, 198, 6738, 2995, 29985, 13, 31438, 13, 14681, 1330, 10854, 23416, 11, 45965, 198, 6738, 2995, 29985, 13, 31438, 13, 10057, 1330, 4482, 11, 4482, 49493, 198, ...
2.528345
441
"""This module implements backtracking algorithm to solve sudoku."""
[ 37811, 1212, 8265, 23986, 736, 36280, 11862, 284, 8494, 424, 67, 11601, 526, 15931, 198 ]
4.6
15
# Copyright (C) 2020-2021 Intel Corporation # SPDX-License-Identifier: Apache-2.0 """Aggregator module.""" import base64 import json import os import platform import shutil import signal import subprocess import time import urllib.request from logging import getLogger from pathlib import Path from subprocess import call import requests from click import confirm logger = getLogger(__name__) TOKEN_DELIMITER = '.' CA_STEP_CONFIG_DIR = Path('step_config') CA_PKI_DIR = Path('cert') CA_PASSWORD_FILE = Path('pass_file') CA_CONFIG_JSON = Path('config/ca.json') def get_system_and_architecture(): """Get system and architecture of machine.""" uname_res = platform.uname() system = uname_res.system.lower() architecture_aliases = { 'x86_64': 'amd64', 'armv6l': 'armv6', 'armv7l': 'armv7', 'aarch64': 'arm64' } architecture = uname_res.machine.lower() for alias in architecture_aliases: if architecture == alias: architecture = architecture_aliases[alias] break return system, architecture def download_step_bin(url, grep_name, architecture, prefix='.', confirmation=True): """ Donwload step binaries from github. Args: url: address of latest release grep_name: name to grep over github assets architecture: architecture type to grep prefix: folder path to download confirmation: request user confirmation or not """ if confirmation: confirm('CA binaries from github will be downloaded now', default=True, abort=True) result = requests.get(url) if result.status_code != 200: logger.warning('Can\'t download binaries from github. Please try lately.') return assets = result.json().get('assets', []) archive_urls = [ a['browser_download_url'] for a in assets if (grep_name in a['name'] and architecture in a['name'] and 'application/gzip' in a['content_type']) ] if len(archive_urls) == 0: raise Exception('Applicable CA binaries from github were not found ' f'(name: {grep_name}, architecture: {architecture})') archive_url = archive_urls[-1] archive_url = archive_url.replace('https', 'http') name = archive_url.split('/')[-1] logger.info(f'Downloading {name}') urllib.request.urlretrieve(archive_url, f'{prefix}/{name}') shutil.unpack_archive(f'{prefix}/{name}', f'{prefix}/step') def get_token(name, ca_url, ca_path='.'): """ Create authentication token. Args: name: common name for following certificate (aggregator fqdn or collaborator name) ca_url: full url of CA server ca_path: path to ca folder """ ca_path = Path(ca_path) step_config_dir = ca_path / CA_STEP_CONFIG_DIR pki_dir = ca_path / CA_PKI_DIR step_path, _ = get_ca_bin_paths(ca_path) if not step_path: raise Exception('Step-CA is not installed!\nRun `fx pki install` first') priv_json = step_config_dir / 'secrets' / 'priv.json' pass_file = pki_dir / CA_PASSWORD_FILE root_crt = step_config_dir / 'certs' / 'root_ca.crt' try: token = subprocess.check_output( f'{step_path} ca token {name} ' f'--key {priv_json} --root {root_crt} ' f'--password-file {pass_file} 'f'--ca-url {ca_url}', shell=True) except subprocess.CalledProcessError as exc: logger.error(f'Error code {exc.returncode}: {exc.output}') return token = token.strip() token_b64 = base64.b64encode(token) with open(root_crt, mode='rb') as file: root_certificate_b = file.read() root_ca_b64 = base64.b64encode(root_certificate_b) return TOKEN_DELIMITER.join([ token_b64.decode('utf-8'), root_ca_b64.decode('utf-8'), ]) def get_ca_bin_paths(ca_path): """Get paths of step binaries.""" ca_path = Path(ca_path) step = None step_ca = None if (ca_path / 'step').exists(): dirs = os.listdir(ca_path / 'step') for dir_ in dirs: if 'step_' in dir_: step = ca_path / 'step' / dir_ / 'bin' / 'step' if 'step-ca' in dir_: step_ca = ca_path / 'step' / dir_ / 'bin' / 'step-ca' return step, step_ca def certify(name, cert_path: Path, token_with_cert, ca_path: Path): """Create an envoy workspace.""" os.makedirs(cert_path, exist_ok=True) token, root_certificate = token_with_cert.split(TOKEN_DELIMITER) token = base64.b64decode(token).decode('utf-8') root_certificate = base64.b64decode(root_certificate) step_path, _ = get_ca_bin_paths(ca_path) if not step_path: url = 'http://api.github.com/repos/smallstep/cli/releases/latest' system, arch = get_system_and_architecture() download_step_bin(url, f'step_{system}', arch, prefix=ca_path) step_path, _ = get_ca_bin_paths(ca_path) if not step_path: raise Exception('Step-CA is not installed!\nRun `fx pki install` first') with open(f'{cert_path}/root_ca.crt', mode='wb') as file: file.write(root_certificate) call(f'{step_path} ca certificate {name} {cert_path}/{name}.crt ' f'{cert_path}/{name}.key --kty EC --curve P-384 -f --token {token}', shell=True) def remove_ca(ca_path): """Kill step-ca process and rm ca directory.""" _check_kill_process('step-ca') shutil.rmtree(ca_path, ignore_errors=True) def install(ca_path, ca_url, password): """ Create certificate authority for federation. Args: ca_path: path to ca directory ca_url: url for ca server like: 'host:port' password: Simple password for encrypting root private keys """ logger.info('Creating CA') ca_path = Path(ca_path) ca_path.mkdir(parents=True, exist_ok=True) step_config_dir = ca_path / CA_STEP_CONFIG_DIR os.environ['STEPPATH'] = str(step_config_dir) step_path, step_ca_path = get_ca_bin_paths(ca_path) if not (step_path and step_ca_path and step_path.exists() and step_ca_path.exists()): confirm('CA binaries from github will be downloaded now', default=True, abort=True) system, arch = get_system_and_architecture() url = 'http://api.github.com/repos/smallstep/certificates/releases/latest' download_step_bin(url, f'step-ca_{system}', arch, prefix=ca_path, confirmation=False) url = 'http://api.github.com/repos/smallstep/cli/releases/latest' download_step_bin(url, f'step_{system}', arch, prefix=ca_path, confirmation=False) step_config_dir = ca_path / CA_STEP_CONFIG_DIR if (not step_config_dir.exists() or confirm('CA exists, do you want to recreate it?', default=True)): _create_ca(ca_path, ca_url, password) _configure(step_config_dir) def run_ca(step_ca, pass_file, ca_json): """Run CA server.""" if _check_kill_process('step-ca', confirmation=True): logger.info('Up CA server') call(f'{step_ca} --password-file {pass_file} {ca_json}', shell=True) def _check_kill_process(pstring, confirmation=False): """Kill process by name.""" pids = [] proc = subprocess.Popen(f'ps ax | grep {pstring} | grep -v grep', shell=True, stdout=subprocess.PIPE) text = proc.communicate()[0].decode('utf-8') for line in text.splitlines(): fields = line.split() pids.append(fields[0]) if len(pids): if confirmation and not confirm('CA server is already running. Stop him?', default=True): return False for pid in pids: os.kill(int(pid), signal.SIGKILL) time.sleep(2) return True def _create_ca(ca_path: Path, ca_url: str, password: str): """Create a ca workspace.""" import os pki_dir = ca_path / CA_PKI_DIR step_config_dir = ca_path / CA_STEP_CONFIG_DIR pki_dir.mkdir(parents=True, exist_ok=True) step_config_dir.mkdir(parents=True, exist_ok=True) with open(f'{pki_dir}/pass_file', 'w') as f: f.write(password) os.chmod(f'{pki_dir}/pass_file', 0o600) step_path, step_ca_path = get_ca_bin_paths(ca_path) assert (step_path and step_ca_path and step_path.exists() and step_ca_path.exists()) logger.info('Create CA Config') os.environ['STEPPATH'] = str(step_config_dir) shutil.rmtree(step_config_dir, ignore_errors=True) name = ca_url.split(':')[0] call(f'{step_path} ca init --name name --dns {name} ' f'--address {ca_url} --provisioner prov ' f'--password-file {pki_dir}/pass_file', shell=True) call(f'{step_path} ca provisioner remove prov --all', shell=True) call(f'{step_path} crypto jwk create {step_config_dir}/certs/pub.json ' f'{step_config_dir}/secrets/priv.json --password-file={pki_dir}/pass_file', shell=True) call( f'{step_path} ca provisioner add provisioner {step_config_dir}/certs/pub.json', shell=True )
[ 2, 15069, 357, 34, 8, 12131, 12, 1238, 2481, 8180, 10501, 198, 2, 30628, 55, 12, 34156, 12, 33234, 7483, 25, 24843, 12, 17, 13, 15, 198, 198, 37811, 46384, 2301, 1352, 8265, 526, 15931, 198, 198, 11748, 2779, 2414, 198, 11748, 33918...
2.361184
3,818
from pearce.emulator import OriginalRecipe, ExtraCrispy import numpy as np training_file = '/home/users/swmclau2/scratch/PearceRedMagicWpCosmo.hdf5' em_method = 'gp' split_method = 'random' a = 1.0 z = 1.0/a - 1.0 fixed_params = {'z':z, 'cosmo': 1}#, 'r':0.18477483} n_leaves, n_overlap = 5, 2 emu = ExtraCrispy(training_file,n_leaves, n_overlap, split_method, method = em_method, fixed_params=fixed_params,\ custom_mean_function = None) results = emu.train_metric() print results print print dict(zip(emu.get_param_names(), np.exp(results.x)))
[ 6738, 25286, 344, 13, 368, 8927, 1330, 13745, 37523, 11, 17221, 34, 2442, 9078, 198, 11748, 299, 32152, 355, 45941, 198, 198, 34409, 62, 7753, 796, 31051, 11195, 14, 18417, 14, 2032, 76, 565, 559, 17, 14, 1416, 36722, 14, 46262, 344, ...
2.333333
246
# -*- coding: utf-8 -*- # pylint: disable=missing-docstring,unused-import,reimported import json import pytest # type: ignore import xmllint_map_html.xmllint_map_html as xmh
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 279, 2645, 600, 25, 15560, 28, 45688, 12, 15390, 8841, 11, 403, 1484, 12, 11748, 11, 260, 320, 9213, 198, 11748, 33918, 198, 11748, 12972, 9288, 220, 1303, 2099, 25...
2.492958
71
from rest_framework import mixins, viewsets, status from rest_framework.permissions import ( AllowAny, IsAuthenticated ) from apps.transmissions.models import Transmission from apps.transmissions.serializers import TransmissionModelSerializer, CommentModelserializer from django_filters import rest_framework as filters
[ 6738, 1334, 62, 30604, 1330, 5022, 1040, 11, 5009, 1039, 11, 3722, 198, 198, 6738, 1334, 62, 30604, 13, 525, 8481, 1330, 357, 198, 220, 220, 220, 22507, 7149, 11, 198, 220, 220, 220, 1148, 47649, 3474, 198, 8, 198, 198, 6738, 6725, ...
3.940476
84
from amstramdam import app, socketio, timers, manager from flask import session from flask_socketio import emit from .types import GameEndNotification, GameEndPayload from .utils import safe_cancel, wait_and_run from ..game.types import GameName, Coordinates
[ 6738, 716, 301, 859, 11043, 1330, 598, 11, 17802, 952, 11, 48085, 11, 4706, 198, 6738, 42903, 1330, 6246, 198, 6738, 42903, 62, 44971, 952, 1330, 27588, 198, 198, 6738, 764, 19199, 1330, 3776, 12915, 3673, 2649, 11, 3776, 12915, 19197, ...
3.680556
72
__copyright__ = 'Copyright(c) Gordon Elliott 2017' """ """ from datetime import date from decimal import Decimal from io import StringIO from unittest import TestCase from glod.model.statement_item import StatementItem from glod.model.account import Account from glod.in_out.statement_item import statement_item_csv
[ 198, 834, 22163, 4766, 834, 796, 705, 15269, 7, 66, 8, 11646, 22386, 2177, 6, 198, 198, 37811, 220, 198, 37811, 198, 198, 6738, 4818, 8079, 1330, 3128, 198, 6738, 32465, 1330, 4280, 4402, 198, 6738, 33245, 1330, 10903, 9399, 198, 6738...
3.538462
91
# Tested with Python 3.6 # Install Pillow: pip install pillow """ This script extracts exif data from JPEG images """ from PIL import Image from PIL.ExifTags import TAGS import sys main()
[ 2, 6208, 276, 351, 11361, 513, 13, 21, 201, 198, 2, 15545, 19770, 322, 25, 7347, 2721, 28774, 201, 198, 37811, 770, 4226, 32139, 409, 361, 1366, 422, 48561, 4263, 37227, 201, 198, 6738, 350, 4146, 1330, 7412, 201, 198, 6738, 350, 41...
3.177419
62
SCHEMA_VERSION = 2 from .common import ValidationError, SchemaMismatchError from .v2 import MetadataValidatorV2 as MetadataValidator from .v2 import read_v2 as read, write_v2 as write from .v2 import reads_v2 as reads, writes_v2 as writes
[ 50, 3398, 27630, 62, 43717, 796, 362, 198, 198, 6738, 764, 11321, 1330, 3254, 24765, 12331, 11, 10011, 2611, 44, 1042, 963, 12331, 198, 6738, 764, 85, 17, 1330, 3395, 14706, 47139, 1352, 53, 17, 355, 3395, 14706, 47139, 1352, 198, 673...
3.037975
79
import h5py from ont_fast5_api.conversion_tools import multi_to_single_fast5 from ont_fast5_api import fast5_interface import SequenceGenerator.align as align import SignalExtractor.Nanopolish as events from testFiles.test_commands import * import os, sys import subprocess #todo get basecall data #test to check if required files are created #create event info file for machine learning models
[ 11748, 289, 20, 9078, 201, 198, 6738, 39585, 62, 7217, 20, 62, 15042, 13, 1102, 9641, 62, 31391, 1330, 5021, 62, 1462, 62, 29762, 62, 7217, 20, 201, 198, 6738, 39585, 62, 7217, 20, 62, 15042, 1330, 3049, 20, 62, 39994, 201, 198, 1...
2.869281
153
# -*- coding: utf-8 -*- # ------------------------------------------------------------ # streamondemand-pureita.- XBMC Plugin # Canale italiaserie # http://www.mimediacenter.info/foro/viewtopic.php?f=36&t=7808 # ------------------------------------------------------------ import re from core import httptools from core import logger from core import config from core import servertools from core import scrapertools from core.item import Item from core.tmdb import infoSod __channel__ = "italiaserie" host = "https://italiaserie.org" headers = [['Referer', host]] # ================================================================================================================================================== # ================================================================================================================================================== # ================================================================================================================================================== # ================================================================================================================================================== # ==================================================================================================================================================
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 20368, 1783, 10541, 198, 2, 4269, 623, 368, 392, 12, 37424, 5350, 7874, 1395, 33, 9655, 42636, 198, 2, 1680, 1000, 340, 26011, 18287, 198, 2, 2638, 1378, 2503, 13, ...
6.695431
197
from setuptools import setup setup( name='potnanny-api', version='0.2.6', packages=['potnanny_api'], include_package_data=True, description='Part of the Potnanny greenhouse controller application. Contains Flask REST API and basic web interface.', author='Jeff Leary', author_email='potnanny@gmail.com', url='https://github.com/jeffleary00/potnanny-api', install_requires=[ 'requests', 'passlib', 'sqlalchemy', 'marshmallow', 'flask', 'flask-restful', 'flask-jwt-extended', 'flask-wtf', 'potnanny-core==0.2.9', ], )
[ 6738, 900, 37623, 10141, 1330, 9058, 198, 198, 40406, 7, 198, 220, 220, 220, 1438, 11639, 13059, 77, 7737, 12, 15042, 3256, 198, 220, 220, 220, 2196, 11639, 15, 13, 17, 13, 21, 3256, 198, 220, 220, 220, 10392, 28, 17816, 13059, 77, ...
2.222615
283
# This file was automatically generated by SWIG (http://www.swig.org). # Version 4.0.0 # # Do not make changes to this file unless you know what you are doing--modify # the SWIG interface file instead. from sys import version_info as _swig_python_version_info if _swig_python_version_info < (2, 7, 0): raise RuntimeError('Python 2.7 or later required') # Import the low-level C/C++ module if __package__ or '.' in __name__: from . import _envcpp else: import _envcpp try: import builtins as __builtin__ except ImportError: import __builtin__ def _swig_add_metaclass(metaclass): """Class decorator for adding a metaclass to a SWIG wrapped class - a slimmed down version of six.add_metaclass""" return wrapper # Register SwigPyIterator in _envcpp: _envcpp.SwigPyIterator_swigregister(SwigPyIterator) # Register vectori in _envcpp: _envcpp.vectori_swigregister(vectori) # Register vectord in _envcpp: _envcpp.vectord_swigregister(vectord) # Register vectors in _envcpp: _envcpp.vectors_swigregister(vectors) # Register Environment in _envcpp: _envcpp.Environment_swigregister(Environment)
[ 2, 770, 2393, 373, 6338, 7560, 416, 12672, 3528, 357, 4023, 1378, 2503, 13, 2032, 328, 13, 2398, 737, 198, 2, 10628, 604, 13, 15, 13, 15, 198, 2, 198, 2, 2141, 407, 787, 2458, 284, 428, 2393, 4556, 345, 760, 644, 345, 389, 1804,...
2.937824
386
""" Final Project EDA """ import pandas as pd import matplotlib.pyplot as plt from mlxtend.plotting import scatterplotmatrix import numpy as np import seaborn as sns from imblearn.over_sampling import SMOTE from sklearn.utils import resample from mlxtend.plotting import heatmap from sklearn.ensemble import RandomForestClassifier from sklearn.preprocessing import StandardScaler, MinMaxScaler from sklearn.feature_selection import SelectFromModel import sys from sklearn.model_selection import train_test_split from collections import Counter df = pd.read_csv('student-mat-edited.csv') df['school'] = df['school'].replace(['GP', 'MS'], [1, 0]) df['sex'] = df['sex'].replace(['M', 'F'], [1, 0]) df['address'] = df['address'].replace(['U', 'R'], [1, 0]) df['famsize'] = df['famsize'].replace(['GT3', 'LE3'], [1, 0]) df['Pstatus'] = df['Pstatus'].replace(['T', 'A'], [1, 0]) df = df.replace(to_replace={'yes':1, 'no':0}) df = pd.get_dummies(df, prefix= ['Mjob', 'Fjob', 'reason', 'guardian']) #code from: https://stackoverflow.com/questions/46168450/replace-a-specific-range-of-values-in-a-pandas-dataframe #convert the scores to integers representing the letter grade range specified in the paper. higher the number, the higher the grade df['scores'] = df[['G1', 'G2', 'G3']].mean(axis=1) df['scores'] = np.where(df['scores'].between(0, 10), 0, df['scores']) df['scores'] = np.where(df['scores'].between(10, 12), 1, df['scores']) df['scores'] = np.where(df['scores'].between(12, 14), 2, df['scores']) df['scores'] = np.where(df['scores'].between(14, 16), 3, df['scores']) df['scores'] = np.where(df['scores'].between(16, 21), 4, df['scores']) df['scores'] = df['scores'].astype(np.int) df = df.drop(index=1, columns=['G1', 'G2', 'G3']) #separate into features and target X = df[[i for i in list(df.columns) if i != 'scores']] y = df['scores'] # fixing class imbalance #https://machinelearningmastery.com/multi-class-imbalanced-classification/ oversample = SMOTE(random_state=0) X, y = oversample.fit_resample(X, y) # splitting training and test data X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0, stratify=y) # min-max scaling mms = MinMaxScaler() X_train_norm = mms.fit_transform(X_train) X_test_norm = mms.transform(X_test) # standardizing the data stdsc = StandardScaler() X_train_std = stdsc.fit_transform(X_train) X_test_std = stdsc.transform(X_test) # Random Forest Feature Selection feat_labels = X.columns forest = RandomForestClassifier(n_estimators=500, random_state=0) forest.fit(X_train, y_train) importances = forest.feature_importances_ indices = np.argsort(importances)[::-1] for f in range(X_train.shape[1]): print("%2d) %-*s %f" % (f + 1, 30, feat_labels[indices[f]], importances[indices[f]])) plt.title('Feature Importance') plt.bar(range(X_train.shape[1]), importances[indices], align='center') plt.xticks(range(X_train.shape[1]), feat_labels[indices], rotation=90) plt.xlim([-1, X_train.shape[1]]) plt.tight_layout() plt.savefig("rf_selection.png") plt.show() sfm = SelectFromModel(forest, threshold=0.04, prefit=True) X_selected = sfm.transform(X_train) print('Number of features that meet this threshold', 'criterion:', X_selected.shape[1]) # # Now, let's print the features that met the threshold criterion for feature selection that we set earlier (note that this code snippet does not appear in the actual book but was added to this notebook later for illustrative purposes): cols = [] for f in range(X_selected.shape[1]): cols.append(feat_labels[indices[f]]) print("%2d) %-*s %f" % (f + 1, 30, feat_labels[indices[f]], importances[indices[f]])) # Correlation heatmap cols.append("scores") cm = np.corrcoef(df[cols].values.T) hm = heatmap(cm, row_names=cols, column_names=cols, figsize=(10, 8)) plt.savefig("corr_matrix.png") plt.show()
[ 37811, 198, 19006, 4935, 198, 1961, 32, 198, 37811, 628, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 6738, 25962, 742, 437, 13, 29487, 889, 1330, 41058, 29487, 6759, 8609, 1...
2.589014
1,511
import numpy as np def gauss_points(el_type, n): """Returns the Gaussian weights and locations for *n* point Gaussian integration of a finite element. Refer to xxx for a list of the element types. :param string el_type: String describing the element type :param int n: Number of Gauss points :returns: The integration weights *(n x 1)* and an *(n x i)* matrix consisting of the values of the *i* shape functions for *n* Gauss points :rtype: tuple(list[float], :class:`numpy.ndarray`) """ if el_type == 'Tri6': # one point gaussian integration if n == 1: weights = [1] gps = np.array([[1.0 / 3, 1.0 / 3, 1.0 / 3]]) # three point gaussian integration elif n == 3: weights = [1.0 / 3, 1.0 / 3, 1.0 / 3] gps = np.array([ [2.0 / 3, 1.0 / 6, 1.0 / 6], [1.0 / 6, 2.0 / 3, 1.0 / 6], [1.0 / 6, 1.0 / 6, 2.0 / 3] ]) # six point gaussian integration elif n == 6: g1 = 1.0 / 18 * (8 - np.sqrt(10) + np.sqrt(38 - 44 * np.sqrt(2.0 / 5))) g2 = 1.0 / 18 * (8 - np.sqrt(10) - np.sqrt(38 - 44 * np.sqrt(2.0 / 5))) w1 = (620 + np.sqrt(213125 - 53320 * np.sqrt(10))) / 3720 w2 = (620 - np.sqrt(213125 - 53320 * np.sqrt(10))) / 3720 weights = [w2, w2, w2, w1, w1, w1] gps = np.array([ [1 - 2 * g2, g2, g2], [g2, 1 - 2 * g2, g2], [g2, g2, 1 - 2 * g2], [g1, g1, 1 - 2 * g1], [1 - 2 * g1, g1, g1], [g1, 1 - 2 * g1, g1] ]) return (weights, gps) def shape_function(el_type, coords, gp): """Computes shape functions, shape function derivatives and the determinant of the Jacobian matrix for a number of different finite elements at a given Gauss point. Refer to xxx for a list of the element types. :param string el_type: String describing the element type :param coords: Global coordinates of the element nodes *(n x 3)*, where *n* is the number of nodes :type coords: :class:`numpy.ndarray` :param gp: Isoparametric location of the Gauss point :type gp: :class:`numpy.ndarray` :returns: The value of the shape functions *N(i)* at the given Gauss point *(1 x n)*, the derivative of the shape functions in the j-th global direction *B(i,j)* *(3 x n)* and the determinant of the Jacobian matrix *j* :rtype: tuple(:class:`numpy.ndarray`, :class:`numpy.ndarray`, float) """ if el_type == 'Tri6': # location of isoparametric co-ordinates for each Gauss point eta = gp[0] xi = gp[1] zeta = gp[2] # value of the shape functions N = np.array([ eta * (2 * eta - 1), xi * (2 * xi - 1), zeta * (2 * zeta - 1), 4 * eta * xi, 4 * xi * zeta, 4 * eta * zeta ]) # derivatives of the sf wrt the isoparametric co-ordinates B_iso = np.array([ [4 * eta - 1, 0, 0, 4 * xi, 0, 4 * zeta], [0, 4 * xi - 1, 0, 4 * eta, 4 * zeta, 0], [0, 0, 4 * zeta - 1, 0, 4 * xi, 4 * eta] ]) # form Jacobian matrix J_upper = np.array([[1, 1, 1]]) J_lower = np.dot(coords, np.transpose(B_iso)) J = np.vstack((J_upper, J_lower)) # calculate the jacobian j = 0.5 * np.linalg.det(J) # cacluate the P matrix P = np.dot(np.linalg.inv(J), np.array([[0, 0], [1, 0], [0, 1]])) # calculate the B matrix in terms of cartesian co-ordinates B = np.transpose(np.dot(np.transpose(B_iso), P)) return (N, B, j)
[ 11748, 299, 32152, 355, 45941, 628, 198, 4299, 31986, 1046, 62, 13033, 7, 417, 62, 4906, 11, 299, 2599, 198, 220, 220, 220, 37227, 35561, 262, 12822, 31562, 19590, 290, 7064, 329, 1635, 77, 9, 966, 12822, 31562, 11812, 286, 257, 27454...
1.989974
1,895
import requests import time import argparse import sys import os from bs4 import BeautifulSoup from urllib.parse import urlparse # Instantiate the parser parser = argparse.ArgumentParser(description='URL scrapper') parser.add_argument('--url', help='Root URL page') parser.add_argument('--limit', type=int, default=1000, help='Limit urls to scrape') parser.add_argument('--output', default='output.csv', help='Path to output file') args = parser.parse_args() urls = [] urls_visited = [] if is_url(args.url) != True: print('Invalid root URL [--url]') sys.exit(1) fetch_urls(args.url) urls_visited.append(args.url); for url in urls: if len(urls) > args.limit: break print_progress(len(urls), args.limit) if url not in urls_visited: urls_visited.append(url); fetch_urls(url) # Save output os.remove(args.output) with open(args.output, 'a') as output: for url in urls: output.write(url + '\n')
[ 11748, 7007, 198, 11748, 640, 198, 11748, 1822, 29572, 198, 11748, 25064, 198, 11748, 28686, 198, 6738, 275, 82, 19, 1330, 23762, 50, 10486, 198, 6738, 2956, 297, 571, 13, 29572, 1330, 19016, 29572, 198, 198, 2, 24470, 9386, 262, 30751,...
2.756024
332
from shift_oelint_parser.cls_item import Variable from shift_oelint_adv.cls_rule import Rule from shift_oelint_parser.helper_files import get_scr_components from shift_oelint_parser.parser import INLINE_BLOCK
[ 6738, 6482, 62, 78, 417, 600, 62, 48610, 13, 565, 82, 62, 9186, 1330, 35748, 198, 6738, 6482, 62, 78, 417, 600, 62, 32225, 13, 565, 82, 62, 25135, 1330, 14330, 198, 6738, 6482, 62, 78, 417, 600, 62, 48610, 13, 2978, 525, 62, 166...
2.957746
71
from github import User as GitHubUser from github.auth import get_token from github.exceptions import AuthValidationError from . import get_user_model
[ 6738, 33084, 1330, 11787, 355, 21722, 12982, 198, 6738, 33084, 13, 18439, 1330, 651, 62, 30001, 198, 6738, 33084, 13, 1069, 11755, 1330, 26828, 7762, 24765, 12331, 198, 198, 6738, 764, 1330, 651, 62, 7220, 62, 19849, 628 ]
4.026316
38
import time import board import busio import digitalio from adafruit_apds9960.apds9960 import APDS9960 from adafruit_apds9960 import colorutility i2c = busio.I2C(board.SCL, board.SDA) int_pin = digitalio.DigitalInOut(board.A2) apds = APDS9960(i2c) apds.enable_color = True while True: #create some variables to store the color data in #wait for color data to be ready while not apds.color_data_ready: time.sleep(0.005) #get the data and print the different channels r, g, b, c = apds.color_data print("red: ", r) print("green: ", g) print("blue: ", b) print("clear: ", c) print("color temp {}".format(colorutility.calculate_color_temperature(r, g, b))) print("light lux {}".format(colorutility.calculate_lux(r, g, b))) time.sleep(0.5)
[ 11748, 640, 198, 11748, 3096, 198, 11748, 1323, 952, 198, 11748, 4875, 952, 198, 6738, 512, 1878, 4872, 62, 499, 9310, 2079, 1899, 13, 499, 9310, 2079, 1899, 1330, 3486, 5258, 2079, 1899, 198, 6738, 512, 1878, 4872, 62, 499, 9310, 207...
2.501567
319
N, *A = map(int, open(0).read().split()) A.sort() for i in range(N): if i == A[i] - 1: continue print('No') break else: print('Yes')
[ 45, 11, 1635, 32, 796, 3975, 7, 600, 11, 1280, 7, 15, 737, 961, 22446, 35312, 28955, 198, 198, 32, 13, 30619, 3419, 198, 1640, 1312, 287, 2837, 7, 45, 2599, 198, 220, 220, 220, 611, 1312, 6624, 317, 58, 72, 60, 532, 352, 25, 1...
2
79
from behave import * from hamcrest import assert_that, is_not, greater_than import numpy as np import nibabel as nib import rpy2.robjects as robjects from rpy2.robjects.numpy2ri import numpy2ri from rpy2.robjects.packages import importr robjects.conversion.py2ri = numpy2ri from os import path as op import sys curfile = op.abspath(__file__) testpath = op.dirname(op.dirname(op.dirname(curfile))) rpath = op.join(testpath, "R") pypath = op.dirname(testpath) sys.path.append(pypath) from cwas import * from utils import * def custom_corrcoef(X, Y=None): """Each of the columns in X will be correlated with each of the columns in Y. Each column represents a variable, with the rows containing the observations.""" if Y is None: Y = X if X.shape[0] != Y.shape[0]: raise Exception("X and Y must have the same number of rows.") X = X.astype(float) Y = Y.astype(float) X -= X.mean(axis=0)[np.newaxis,...] Y -= Y.mean(axis=0) xx = np.sum(X**2, axis=0) yy = np.sum(Y**2, axis=0) r = np.dot(X.T, Y)/np.sqrt(np.multiply.outer(xx,yy)) return r
[ 6738, 17438, 1330, 1635, 198, 6738, 8891, 66, 2118, 1330, 6818, 62, 5562, 11, 318, 62, 1662, 11, 3744, 62, 14813, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 33272, 9608, 355, 33272, 198, 11748, 374, 9078, 17, 13, 22609, 752,...
2.453744
454
import sys sys.path.append('..') from Analyzer.TransitionProperties import ProcessTransitionProperties from tkinter import * from tkinter import messagebox, ttk, filedialog # from tkFileDialog import * import uniaxanalysis.getproperties as getprops from uniaxanalysis.plotdata import DataPlotter from uniaxanalysis.saveproperties import write_props_csv from exvivoframes import * from matplotlib import pyplot as plt import time ''' The GUI for uniax data analysis of soft tissue. inputs: - Dimensions file - a file with format: sample name, width, thickness and initial distance - directory - Folder with raw uniax data files in csv format with format: time, distance, force To Do: - polymorphic method for handling input data (variable names to get) <done> - control when line for manual control shows up <done> - test rdp for finding linear region - done (check implementation) - fix point picking on plot so that can work in desceding order of x value - <done> - tick boxes for properties <done> - config file - scroll bar for large data sets <done> Bugs: - work out bug in the 2nd order gaussian - done - work out bug in the display for automatic linear find - destroy instance of toolbar on graph create - destroy instance of plot everytime ''' if __name__ == '__main__': main()
[ 11748, 25064, 198, 17597, 13, 6978, 13, 33295, 10786, 492, 11537, 198, 198, 6738, 16213, 9107, 13, 8291, 653, 2964, 18200, 1330, 10854, 8291, 653, 2964, 18200, 198, 198, 6738, 256, 74, 3849, 1330, 1635, 198, 6738, 256, 74, 3849, 1330, ...
3.3825
400
import click import aiohttp import asyncio import re import json from typing import Optional, Tuple, Iterable, Union, List from blspy import G2Element, AugSchemeMPL from chia.cmds.wallet_funcs import get_wallet from chia.rpc.wallet_rpc_client import WalletRpcClient from chia.util.default_root import DEFAULT_ROOT_PATH from chia.util.config import load_config from chia.util.ints import uint16 from chia.util.byte_types import hexstr_to_bytes from chia.types.blockchain_format.program import Program from clvm_tools.clvmc import compile_clvm_text from clvm_tools.binutils import assemble from chia.types.spend_bundle import SpendBundle from chia.wallet.cc_wallet.cc_utils import ( construct_cc_puzzle, CC_MOD, SpendableCC, unsigned_spend_bundle_for_spendable_ccs, ) from chia.util.bech32m import decode_puzzle_hash # Loading the client requires the standard chia root directory configuration that all of the chia commands rely on # The clvm loaders in this library automatically search for includable files in the directory './include' def append_include(search_paths: Iterable[str]) -> List[str]: if search_paths: search_list = list(search_paths) search_list.append("./include") return search_list else: return ["./include"] def parse_program(program: Union[str, Program], include: Iterable = []) -> Program: if isinstance(program, Program): return program else: if "(" in program: # If it's raw clvm prog = Program.to(assemble(program)) elif "." not in program: # If it's a byte string prog = Program.from_bytes(hexstr_to_bytes(program)) else: # If it's a file with open(program, "r") as file: filestring: str = file.read() if "(" in filestring: # If it's not compiled # TODO: This should probably be more robust if re.compile(r"\(mod\s").search(filestring): # If it's Chialisp prog = Program.to( compile_clvm_text(filestring, append_include(include)) ) else: # If it's CLVM prog = Program.to(assemble(filestring)) else: # If it's serialized CLVM prog = Program.from_bytes(hexstr_to_bytes(filestring)) return prog CONTEXT_SETTINGS = dict(help_option_names=["-h", "--help"]) if __name__ == "__main__": main()
[ 11748, 3904, 198, 11748, 257, 952, 4023, 198, 11748, 30351, 952, 198, 11748, 302, 198, 11748, 33918, 198, 198, 6738, 19720, 1330, 32233, 11, 309, 29291, 11, 40806, 540, 11, 4479, 11, 7343, 198, 6738, 698, 2777, 88, 1330, 402, 17, 2018...
2.391013
1,046
# -*- coding: utf-8 -*- # Author: Haoran Chen # Date: 2019-4-28 import tensorflow as tf from tensorflow import placeholder, glorot_normal_initializer, zeros_initializer from tensorflow.nn import dropout import numpy as np n_z = 3584 n_y = 300 MSVD_PATH = None MSRVTT_PATH = None MSVD_GT_PATH = None MSRVTT_GT_PATH = None max_epochs = 1000 lr = 0.0002 batch_size = 128 keep_prob = 1.0 batch_size = 64
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 6434, 25, 9398, 31884, 12555, 198, 2, 7536, 25, 13130, 12, 19, 12, 2078, 198, 198, 11748, 11192, 273, 11125, 355, 48700, 198, 6738, 11192, 273, 11125, 1330, 46076, ...
2.5
164
import pandas as pd from cloudmesh import mongo from flask import request from flask_pymongo import PyMongo from sklearn.feature_selection import SelectKBest, chi2 from sklearn.linear_model import LogisticRegression from sklearn.metrics import accuracy_score from .file import upload
[ 11748, 19798, 292, 355, 279, 67, 198, 6738, 6279, 76, 5069, 1330, 285, 25162, 198, 6738, 42903, 1330, 2581, 198, 6738, 42903, 62, 79, 4948, 25162, 1330, 9485, 44, 25162, 198, 6738, 1341, 35720, 13, 30053, 62, 49283, 1330, 9683, 42, 13...
3.75
76
""" Explore raw composites based on indices from predicted testing data and showing all the difference OHC levels for OBSERVATIONS Author : Zachary M. Labe Date : 21 September 2021 Version : 2 (mostly for testing) """ ### Import packages import sys import matplotlib.pyplot as plt import numpy as np import calc_Utilities as UT from mpl_toolkits.basemap import Basemap, addcyclic, shiftgrid import palettable.cubehelix as cm import cmocean as cmocean import calc_dataFunctions as df import calc_Stats as dSS from netCDF4 import Dataset ### Plotting defaults plt.rc('text',usetex=True) plt.rc('font',**{'family':'sans-serif','sans-serif':['Avant Garde']}) ############################################################################### ############################################################################### ############################################################################### ### Data preliminaries modelGCMs = ['CESM2le'] dataset_obs = 'ERA5' allDataLabels = modelGCMs monthlychoiceq = ['annual'] variables = ['T2M'] vari_predict = ['SST','OHC100','OHC300','OHC700'] reg_name = 'SMILEGlobe' level = 'surface' ############################################################################### ############################################################################### randomalso = False timeper = 'hiatus' shuffletype = 'GAUSS' ############################################################################### ############################################################################### land_only = False ocean_only = False ############################################################################### ############################################################################### baseline = np.arange(1951,1980+1,1) ############################################################################### ############################################################################### window = 0 if window == 0: rm_standard_dev = False ravel_modelens = False ravelmodeltime = False else: rm_standard_dev = True ravelmodeltime = False ravel_modelens = True yearsall = np.arange(1979+window,2099+1,1) yearsobs = np.arange(1979+window,2020+1,1) ############################################################################### ############################################################################### numOfEns = 40 lentime = len(yearsall) ############################################################################### ############################################################################### lat_bounds,lon_bounds = UT.regions(reg_name) ############################################################################### ############################################################################### ravelyearsbinary = False ravelbinary = False lensalso = True ############################################################################### ############################################################################### ### Remove ensemble mean rm_ensemble_mean = True ############################################################################### ############################################################################### ### Accuracy for composites accurate = True if accurate == True: typemodel = 'correcthiatus_obs' elif accurate == False: typemodel = 'extrahiatus_obs' elif accurate == 'WRONG': typemodel = 'wronghiatus_obs' elif accurate == 'HIATUS': typemodel = 'allhiatus_obs' ############################################################################### ############################################################################### ### Call functions trendlength = 10 AGWstart = 1990 years_newmodel = np.arange(AGWstart,yearsall[-1]-8,1) years_newobs = np.arange(AGWstart,yearsobs[-1]-8,1) vv = 0 mo = 0 variq = variables[vv] monthlychoice = monthlychoiceq[mo] directoryfigure = '/Users/zlabe/Desktop/GmstTrendPrediction/ANN_v2/Obs/' saveData = monthlychoice + '_' + variq + '_' + reg_name + '_' + dataset_obs print('*Filename == < %s >' % saveData) ############################################################################### ############################################################################### ### Function to read in predictor variables (SST/OHC) ############################################################################### ############################################################################### ### Loop through to read all the variables ohcHIATUS = np.empty((len(vari_predict),92,144)) for vvv in range(len(vari_predict)): ### Function to read in predictor variables (SST/OHC) models_var = [] for i in range(len(modelGCMs)): if vari_predict[vvv][:3] == 'OHC': obs_predict = 'OHC' else: obs_predict = 'ERA5' obsq_var,lats,lons = read_obs_dataset(vari_predict[vvv],obs_predict,numOfEns,lensalso,randomalso,ravelyearsbinary,ravelbinary,shuffletype,lat_bounds=lat_bounds,lon_bounds=lon_bounds) ### Save predictor models_var.append(obsq_var) models_var = np.asarray(models_var).squeeze() ### Remove ensemble mean if rm_ensemble_mean == True: models_var = dSS.remove_trend_obs(models_var,'surface') print('\n*Removed observational linear trend*') ### Standardize models_varravel = models_var.squeeze().reshape(yearsobs.shape[0],lats.shape[0]*lons.shape[0]) meanvar = np.nanmean(models_varravel,axis=0) stdvar = np.nanstd(models_varravel,axis=0) modelsstd_varravel = (models_varravel-meanvar)/stdvar models_var = modelsstd_varravel.reshape(yearsobs.shape[0],lats.shape[0],lons.shape[0]) ### Slice for number of years yearsq_m = np.where((yearsobs >= AGWstart))[0] models_slice = models_var[yearsq_m,:,:] if rm_ensemble_mean == False: variq = 'T2M' fac = 0.7 random_segment_seed = int(np.genfromtxt('/Users/zlabe/Documents/Research/GmstTrendPrediction/Data/SelectedSegmentSeed.txt',unpack=True)) random_network_seed = 87750 hidden = [20,20] n_epochs = 500 batch_size = 128 lr_here = 0.001 ridgePenalty = 0.05 actFun = 'relu' fractWeight = 0.5 elif rm_ensemble_mean == True: variq = 'T2M' fac = 0.7 random_segment_seed = int(np.genfromtxt('/Users/zlabe/Documents/Research/GmstTrendPrediction/Data/SelectedSegmentSeed.txt',unpack=True)) random_network_seed = 87750 hidden = [30,30] n_epochs = 500 batch_size = 128 lr_here = 0.001 ridgePenalty = 0.5 actFun = 'relu' fractWeight = 0.5 else: print(ValueError('SOMETHING IS WRONG WITH DATA PROCESSING!')) sys.exit() ### Naming conventions for files directorymodel = '/Users/zlabe/Documents/Research/GmstTrendPrediction/SavedModels/' savename = 'ANNv2_'+'OHC100'+'_hiatus_' + actFun + '_L2_'+ str(ridgePenalty)+ '_LR_' + str(lr_here)+ '_Batch'+ str(batch_size)+ '_Iters' + str(n_epochs) + '_' + str(len(hidden)) + 'x' + str(hidden[0]) + '_SegSeed' + str(random_segment_seed) + '_NetSeed'+ str(random_network_seed) if(rm_ensemble_mean==True): savename = savename + '_EnsembleMeanRemoved' ### Directories to save files directorydata = '/Users/zlabe/Documents/Research/GmstTrendPrediction/Data/' ############################################################################### ############################################################################### ############################################################################### ### Read in data for testing predictions and actual hiatuses actual_test = np.genfromtxt(directorydata + 'obsActualLabels_' + savename + '.txt') predict_test = np.genfromtxt(directorydata + 'obsLabels_' + savename+ '.txt') ### Reshape arrays for [ensemble,year] act_re = actual_test pre_re = predict_test ### Slice ensembles for testing data ohcready = models_slice[:,:,:].squeeze() ### Pick all hiatuses if accurate == True: ### correct predictions ohc_allenscomp = [] for yr in range(ohcready.shape[0]): if (pre_re[yr]) == 1 and (act_re[yr] == 1): ohc_allenscomp.append(ohcready[yr,:,:]) elif accurate == False: ### picks all hiatus predictions ohc_allenscomp = [] for yr in range(ohcready.shape[0]): if pre_re[yr] == 1: ohc_allenscomp.append(ohcready[yr,:,:]) elif accurate == 'WRONG': ### picks hiatus but is wrong ohc_allenscomp = [] for yr in range(ohcready.shape[0]): if (pre_re[yr]) == 1 and (act_re[yr] == 0): ohc_allenscomp.append(ohcready[yr,:,:]) elif accurate == 'HIATUS': ### accurate climate change ohc_allenscomp = [] for yr in range(ohcready.shape[0]): if (act_re[yr] == 1): ohc_allenscomp.append(ohcready[yr,:,:]) else: print(ValueError('SOMETHING IS WRONG WITH ACCURACY COMPOSITES!')) sys.exit() ### Composite across all years to get hiatuses ohcHIATUS[vvv,:,:] = np.nanmean(np.asarray(ohc_allenscomp),axis=0) ############################################################################### ############################################################################### ### Loop through to read all the variables lag1 = 3 lag2 = 7 lag = lag2-lag1 ohcHIATUSlag = np.empty((len(vari_predict),92,144)) for vvv in range(len(vari_predict)): ### Function to read in predictor variables (SST/OHC) models_var = [] for i in range(len(modelGCMs)): if vari_predict[vvv][:3] == 'OHC': obs_predict = 'OHC' else: obs_predict = 'ERA5' obsq_var,lats,lons = read_obs_dataset(vari_predict[vvv],obs_predict,numOfEns,lensalso,randomalso,ravelyearsbinary,ravelbinary,shuffletype,lat_bounds=lat_bounds,lon_bounds=lon_bounds) ### Save predictor models_var.append(obsq_var) models_var = np.asarray(models_var).squeeze() ### Remove ensemble mean if rm_ensemble_mean == True: models_var = dSS.remove_trend_obs(models_var,'surface') print('\n*Removed observational linear trend*') ### Standardize models_varravel = models_var.squeeze().reshape(yearsobs.shape[0],lats.shape[0]*lons.shape[0]) meanvar = np.nanmean(models_varravel,axis=0) stdvar = np.nanstd(models_varravel,axis=0) modelsstd_varravel = (models_varravel-meanvar)/stdvar models_var = modelsstd_varravel.reshape(yearsobs.shape[0],lats.shape[0],lons.shape[0]) ### Slice for number of years yearsq_m = np.where((yearsobs >= AGWstart))[0] models_slice = models_var[yearsq_m,:,:] if rm_ensemble_mean == False: variq = 'T2M' fac = 0.7 random_segment_seed = int(np.genfromtxt('/Users/zlabe/Documents/Research/GmstTrendPrediction/Data/SelectedSegmentSeed.txt',unpack=True)) random_network_seed = 87750 hidden = [20,20] n_epochs = 500 batch_size = 128 lr_here = 0.001 ridgePenalty = 0.05 actFun = 'relu' fractWeight = 0.5 elif rm_ensemble_mean == True: variq = 'T2M' fac = 0.7 random_segment_seed = int(np.genfromtxt('/Users/zlabe/Documents/Research/GmstTrendPrediction/Data/SelectedSegmentSeed.txt',unpack=True)) random_network_seed = 87750 hidden = [30,30] n_epochs = 500 batch_size = 128 lr_here = 0.001 ridgePenalty = 0.5 actFun = 'relu' fractWeight = 0.5 else: print(ValueError('SOMETHING IS WRONG WITH DATA PROCESSING!')) sys.exit() ### Naming conventions for files directorymodel = '/Users/zlabe/Documents/Research/GmstTrendPrediction/SavedModels/' savename = 'ANNv2_'+'OHC100'+'_hiatus_' + actFun + '_L2_'+ str(ridgePenalty)+ '_LR_' + str(lr_here)+ '_Batch'+ str(batch_size)+ '_Iters' + str(n_epochs) + '_' + str(len(hidden)) + 'x' + str(hidden[0]) + '_SegSeed' + str(random_segment_seed) + '_NetSeed'+ str(random_network_seed) if(rm_ensemble_mean==True): savename = savename + '_EnsembleMeanRemoved' ### Directories to save files directorydata = '/Users/zlabe/Documents/Research/GmstTrendPrediction/Data/' ############################################################################### ############################################################################### ############################################################################### ### Read in data for testing predictions and actual hiatuses actual_test = np.genfromtxt(directorydata + 'obsActualLabels_' + savename + '.txt') predict_test = np.genfromtxt(directorydata + 'obsLabels_' + savename+ '.txt') ### Reshape arrays for [ensemble,year] act_re = actual_test pre_re = predict_test ### Slice ensembles for testing data ohcready = models_slice[:,:,:].squeeze() ### Pick all hiatuses if accurate == True: ### correct predictions ohc_allenscomp = [] for yr in range(ohcready.shape[0]): if (pre_re[yr]) == 1 and (act_re[yr] == 1): ohc_allenscomp.append(np.nanmean(ohcready[yr+lag1:yr+lag2,:,:],axis=0)) elif accurate == False: ### picks all hiatus predictions ohc_allenscomp = [] for yr in range(ohcready.shape[0]): if pre_re[yr] == 1: ohc_allenscomp.append(np.nanmean(ohcready[yr+lag1:yr+lag2,:,:],axis=0)) elif accurate == 'WRONG': ### picks hiatus but is wrong ohc_allenscomp = [] for yr in range(ohcready.shape[0]): if (pre_re[yr]) == 1 and (act_re[yr] == 0): ohc_allenscomp.append(np.nanmean(ohcready[yr+lag1:yr+lag2,:,:],axis=0)) elif accurate == 'HIATUS': ### accurate climate change ohc_allenscomp = [] for yr in range(ohcready.shape[0]): if (act_re[yr] == 1): ohc_allenscomp.append(np.nanmean(ohcready[yr+lag1:yr+lag2,:,:],axis=0)) else: print(ValueError('SOMETHING IS WRONG WITH ACCURACY COMPOSITES!')) sys.exit() ### Composite across all years to get hiatuses ohcHIATUSlag[vvv,:,:] = np.nanmean(np.asarray(ohc_allenscomp),axis=0) ### Composite all for plotting ohc_allcomp = np.append(ohcHIATUS,ohcHIATUSlag,axis=0) ############################################################################### ############################################################################### ### Plot subplot of obser+++++++++++++++vations letters = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n"] plotloc = [1,3,5,7,2,4,6,8] if rm_ensemble_mean == False: limit = np.arange(-1.5,1.51,0.02) barlim = np.round(np.arange(-1.5,1.6,0.5),2) elif rm_ensemble_mean == True: limit = np.arange(-1.5,1.6,0.02) barlim = np.round(np.arange(-1.5,1.6,0.5),2) cmap = cmocean.cm.balance label = r'\textbf{[ HIATUS COMPOSITE ]}' fig = plt.figure(figsize=(8,10)) ############################################################################### for ppp in range(ohc_allcomp.shape[0]): ax1 = plt.subplot(ohc_allcomp.shape[0]//2,2,plotloc[ppp]) m = Basemap(projection='robin',lon_0=-180,resolution='l',area_thresh=10000) m.drawcoastlines(color='darkgrey',linewidth=0.27) ### Variable varn = ohc_allcomp[ppp] if ppp == 0: lons = np.where(lons >180,lons-360,lons) x, y = np.meshgrid(lons,lats) circle = m.drawmapboundary(fill_color='dimgrey',color='dimgray', linewidth=0.7) circle.set_clip_on(False) cs1 = m.contourf(x,y,varn,limit,extend='both',latlon=True) cs1.set_cmap(cmap) m.fillcontinents(color='dimgrey',lake_color='dimgrey') ax1.annotate(r'\textbf{[%s]}' % letters[ppp],xy=(0,0),xytext=(0.95,0.93), textcoords='axes fraction',color='k',fontsize=10, rotation=0,ha='center',va='center') if ppp < 4: ax1.annotate(r'\textbf{%s}' % vari_predict[ppp],xy=(0,0),xytext=(-0.08,0.5), textcoords='axes fraction',color='dimgrey',fontsize=20, rotation=90,ha='center',va='center') if ppp == 0: plt.title(r'\textbf{Onset}',fontsize=15,color='k') if ppp == 4: plt.title(r'\textbf{%s-Year Composite}' % lag,fontsize=15,color='k') ############################################################################### cbar_ax1 = fig.add_axes([0.38,0.05,0.3,0.02]) cbar1 = fig.colorbar(cs1,cax=cbar_ax1,orientation='horizontal', extend='both',extendfrac=0.07,drawedges=False) cbar1.set_label(label,fontsize=6,color='dimgrey',labelpad=1.4) cbar1.set_ticks(barlim) cbar1.set_ticklabels(list(map(str,barlim))) cbar1.ax.tick_params(axis='x', size=.01,labelsize=4) cbar1.outline.set_edgecolor('dimgrey') plt.tight_layout() plt.subplots_adjust(bottom=0.08,wspace=0.01) if rm_ensemble_mean == True: plt.savefig(directoryfigure + 'RawCompositesHiatus_OBSERVATIONS_OHClevels-lag%s_v2_AccH-%s_AccR-%s_rmENSEMBLEmean.png' % (lag,accurate,accurate),dpi=300) else: plt.savefig(directoryfigure + 'RawCompositesHiatus_OBSERVATIONS_OHClevels-lag%s_v2_AccH-%s_AccR-%s.png' % (lag,accurate,accurate),dpi=300)
[ 37811, 198, 35433, 8246, 18882, 2737, 1912, 319, 36525, 422, 11001, 4856, 1366, 290, 198, 1477, 7855, 477, 262, 3580, 440, 16045, 2974, 329, 440, 4462, 1137, 53, 18421, 198, 198, 13838, 220, 220, 220, 220, 1058, 18825, 560, 337, 13, 3...
2.551704
6,837
# Copyright 2016 OSNEXUS Corporation """ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import socket from zope.interface import implementer from flocker.node.agents.blockdevice import ( AlreadyAttachedVolume, IBlockDeviceAPI, IProfiledBlockDeviceAPI, BlockDeviceVolume, UnknownVolume, UnattachedVolume ) from osnexusutil import osnexusAPI import logging from eliot import Message, Logger #_logger = Logger()
[ 2, 15069, 1584, 7294, 45, 6369, 2937, 10501, 198, 198, 37811, 198, 26656, 15385, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 5832, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13,...
3.773109
238
#! /usr/bin/python3 from configparser import ConfigParser, NoSectionError, NoOptionError from electrumpersonalserver.jsonrpc import JsonRpc, JsonRpcError from datetime import datetime import server main()
[ 2, 0, 1220, 14629, 14, 8800, 14, 29412, 18, 198, 198, 6738, 4566, 48610, 1330, 17056, 46677, 11, 1400, 16375, 12331, 11, 1400, 19722, 12331, 198, 6738, 30880, 931, 882, 874, 18497, 13, 17752, 81, 14751, 1330, 449, 1559, 49, 14751, 11,...
3.179104
67
from bs4 import BeautifulSoup from flask import url_for from application.utils import generate_token from application.auth.models import TypeOfUser from tests.models import UserFactory
[ 6738, 275, 82, 19, 1330, 23762, 50, 10486, 198, 198, 6738, 42903, 1330, 19016, 62, 1640, 198, 198, 6738, 3586, 13, 26791, 1330, 7716, 62, 30001, 198, 6738, 3586, 13, 18439, 13, 27530, 1330, 5994, 5189, 12982, 198, 198, 6738, 5254, 13,...
4.021277
47
from setuptools import setup, find_packages from os import path from time import time here = path.abspath(path.dirname(__file__)) if path.exists("VERSION.txt"): # this file can be written by CI tools (e.g. Travis) with open("VERSION.txt") as version_file: version = version_file.read().strip().strip("v") else: version = str(time()) setup( name='ckan_cloud_operator', version=version, description='''CKAN Cloud Kubernetes operator''', url='https://github.com/datopian/ckan-cloud-operator', author='''Viderum''', license='MIT', packages=find_packages(exclude=['examples', 'tests', '.tox']), install_requires=[ 'httpagentparser', 'boto3', 'coverage', 'psycopg2', # 'pyyaml<5.2,>=3.10', 'kubernetes', 'click', 'toml', # 'dataflows>=0.0.37', # 'dataflows-shell>=0.0.8', # 'jupyterlab', 'awscli', 'urllib3<1.25', 'ruamel.yaml<1', 'requests==2.21', # 'python-dateutil<2.8.1', 'botocore', ], entry_points={ 'console_scripts': [ 'ckan-cloud-operator = ckan_cloud_operator.cli:main', ] }, )
[ 6738, 900, 37623, 10141, 1330, 9058, 11, 1064, 62, 43789, 198, 6738, 28686, 1330, 3108, 198, 6738, 640, 1330, 640, 198, 198, 1456, 796, 3108, 13, 397, 2777, 776, 7, 6978, 13, 15908, 3672, 7, 834, 7753, 834, 4008, 198, 198, 361, 3108...
2.084775
578
import os import os.path def activate(ipython, venv): """ Shortcut to run execfile() on `venv`/bin/activate_this.py """ venv = os.path.abspath(venv) venv_activate = os.path.join(venv, 'bin', 'activate_this.py') if not os.path.exists(venv_activate): print('Not a virtualenv: {}'.format(venv)) return # activate_this.py doesn't set VIRTUAL_ENV, so we must set it here os.environ['VIRTUAL_ENV'] = venv os.putenv('VIRTUAL_ENV', venv) execfile(venv_activate, {'__file__': venv_activate}) print('Activated: {}'.format(venv))
[ 11748, 28686, 198, 11748, 28686, 13, 6978, 628, 198, 4299, 15155, 7, 541, 7535, 11, 8710, 85, 2599, 198, 220, 220, 220, 37227, 198, 220, 220, 220, 10073, 8968, 284, 1057, 2452, 7753, 3419, 319, 4600, 574, 85, 63, 14, 8800, 14, 39022...
2.330677
251
import base64 import os import threading from pathlib import Path #from sqlitedict import SqliteDict from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker, scoped_session from daqbrokerServer.web.utils import hash_password from daqbrokerServer.storage.server_schema import ServerBase, User, Connection from daqbrokerServer.storage.contextual_session import session_open # ###### THIS CREATES THE LOCAL STRUCTURE NECESSARY TO HOLD LOCAL DATABASES ####### # if not os.path.isdir(db_folder): # os.mkdir(db_folder) # # Initialise the local settings database # local_url = "sqlite+pysqlite:///" + str(db_folder / "settings.sqlite") # local_engine = create_engine(local_url) # ################################################################################# # # This should create the mappings necessary on the local database # Base.metadata.reflect(local_engine, extend_existing= True, autoload_replace= False) # Base.metadata.create_all(local_engine, checkfirst= True) # #This starts a session - probably not ideal, should consider using scoped session # #LocalSession = scoped_session(sessionmaker(bind=local_engine)) # Session = sessionmaker(bind=local_engine) # session = Session() # Experimenting a class that will handle the folder definition of the session for the server class # ######## THIS IS VERY DANGEROUS - IT SHOULD BE A PROMPT CREATED WHEN INSTALLING THE LIBRARY # query = session.query(User).filter(User.id == 0) # if not query.count() > 0: # pwd = "admin" # password = hash_password(pwd) # user = User(id= 0, type= 3, email= "mail", username= "admin", password= password) # ########################################################################################## # ##### THIS SHOULD LOOK FOR RECORDS OF LOCAL DATABASE, CREATES IF IT DOES NOT EXIST ####### # query2 = session.query(Connection).filter(Connection.id == 0) # if not query2.count() > 0: # connection = Connection(id= 0, type= "sqlite+pysqlite", hostname= "local", username= "admin", password= base64.b64encode(b"admin"), port=0) # ########################################################################################## # #Actually adding the objects - if one does not exist the other will most likely not exist too # if (not query.count() > 0) or (not query2.count() > 0): # connection.users.append(user) # session.add(user) # session.add(connection) # session.commit()
[ 11748, 2779, 2414, 198, 11748, 28686, 198, 11748, 4704, 278, 198, 198, 6738, 3108, 8019, 1330, 10644, 198, 2, 6738, 44161, 863, 713, 1330, 311, 13976, 578, 35, 713, 198, 6738, 44161, 282, 26599, 1330, 2251, 62, 18392, 198, 6738, 44161, ...
3.465318
692
# Copyright (c) 2014 Rackspace, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, 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 logging from tempest.api.queuing import base from tempest.common.utils import data_utils from tempest import test LOG = logging.getLogger(__name__)
[ 2, 15069, 357, 66, 8, 1946, 37927, 13200, 11, 3457, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789,...
3.651961
204
from django.test import TestCase from django_hosts import reverse from util.test_utils import Get, assert_requesting_paths_succeeds
[ 6738, 42625, 14208, 13, 9288, 1330, 6208, 20448, 198, 6738, 42625, 14208, 62, 4774, 82, 1330, 9575, 198, 198, 6738, 7736, 13, 9288, 62, 26791, 1330, 3497, 11, 6818, 62, 25927, 278, 62, 6978, 82, 62, 82, 1229, 2707, 82, 628 ]
3.268293
41
#!/usr/bin/env python # # Copyright (C) 2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, 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. # This module is used for version 2 of the Google Data APIs. # These tests attempt to connect to Google servers. __author__ = 'j.s@google.com (Jeff Scudder)' import os import unittest import gdata.gauth import gdata.client import atom.http_core import atom.mock_http_core import atom.core import gdata.data # TODO: switch to using v2 atom data once it is available. import atom import gdata.test_config as conf conf.options.register_option(conf.BLOG_ID_OPTION) # Utility methods. # The Atom XML namespace. ATOM = 'http://www.w3.org/2005/Atom' # URL used as the scheme for a blog post tag. TAG = 'http://www.blogger.com/atom/ns#' # Namespace for Google Data API elements. GD = 'http://schemas.google.com/g/2005' WORK_REL = 'http://schemas.google.com/g/2005#work' if __name__ == '__main__': unittest.TextTestRunner().run(suite())
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 198, 2, 15069, 357, 34, 8, 3717, 3012, 3457, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 77...
3.198238
454
from django.contrib import admin # Register your models here. from .models import WorkOrder admin.site.register(WorkOrder)
[ 6738, 42625, 14208, 13, 3642, 822, 1330, 13169, 198, 198, 2, 17296, 534, 4981, 994, 13, 198, 6738, 764, 27530, 1330, 5521, 18743, 198, 198, 28482, 13, 15654, 13, 30238, 7, 12468, 18743, 8, 198 ]
3.571429
35
import torch import numpy as np import torch.nn.functional as F from torch.nn.utils.clip_grad import clip_grad_norm_ from mpi_utils.mpi_utils import sync_grads
[ 11748, 28034, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 28034, 13, 20471, 13, 45124, 355, 376, 198, 6738, 28034, 13, 20471, 13, 26791, 13, 15036, 62, 9744, 1330, 10651, 62, 9744, 62, 27237, 62, 198, 6738, 285, 14415, 62, 26791, ...
3.075472
53
from collections import defaultdict, OrderedDict from itertools import islice import copy, os, pickle, warnings import esda import numpy from .analysis import GlobalAutoK from . import util from libpysal import cg, examples, weights from libpysal.common import requires try: from libpysal import open except ImportError: import libpysal open = libpysal.io.open __all__ = ["Network", "PointPattern", "GlobalAutoK"] SAME_SEGMENT = (-0.1, -0.1) dep_msg = ( "The next major release of pysal/spaghetti (2.0.0) will " "drop support for all ``libpysal.cg`` geometries. This change " "is a first step in refactoring ``spaghetti`` that is " "expected to result in dramatically reduced runtimes for " "network instantiation and operations. Users currently " "requiring network and point pattern input as ``libpysal.cg`` " "geometries should prepare for this simply by converting " "to ``shapely`` geometries." ) warnings.warn(f"{dep_msg}", FutureWarning) def extract_component(net, component_id, weightings=None): """Extract a single component from a network object. Parameters ---------- net : spaghetti.Network Full network object. component_id : int The ID of the desired network component. weightings : {dict, bool} See the ``weightings`` keyword argument in ``spaghetti.Network``. Returns ------- cnet : spaghetti.Network The pruned network containing the component specified in ``component_id``. Notes ----- Point patterns are not reassigned when extracting a component. Therefore, component extraction should be performed prior to snapping any point sets onto the network. Also, if the ``spaghetti.Network`` object has ``distance_matrix`` or ``network_trees`` attributes, they are deleted and must be computed again on the single component. Examples -------- Instantiate a network object. >>> from libpysal import examples >>> import spaghetti >>> snow_net = examples.get_path("Soho_Network.shp") >>> ntw = spaghetti.Network(in_data=snow_net, extractgraph=False) The network is not fully connected. >>> ntw.network_fully_connected False Examine the number of network components. >>> ntw.network_n_components 45 Extract the longest component. >>> longest = spaghetti.extract_component(ntw, ntw.network_longest_component) >>> longest.network_n_components 1 >>> longest.network_component_lengths {0: 13508.169276875526} """ def _reassign(attr, cid): """Helper for reassigning attributes.""" # set for each attribute(s) if attr == "_fully_connected": _val = [True for objt in obj_type] attr = [objt + attr for objt in obj_type] elif attr == "_n_components": _val = [1 for objt in obj_type] attr = [objt + attr for objt in obj_type] elif attr in ["_longest_component", "_largest_component"]: _val = [cid for objt in obj_type] attr = [objt + attr for objt in obj_type] elif attr == "vertex_list": # reassigns vertex list + network, graph component vertices supp = [objt + "_component_vertices" for objt in obj_type] _val = [getattr(cnet, supp[0])[cid]] _val += [{cid: getattr(cnet, s)[cid]} for s in supp] attr = [attr] + supp elif attr == "vertex_coords": # reassigns both vertex_coords and vertices supp = getattr(cnet, "vertex_list") _val = [{k: v for k, v in getattr(cnet, attr).items() if k in supp}] _val += [{v: k for k, v in _val[0].items()}] attr = [attr, "vertices"] elif attr == "_component_vertex_count": # reassigns both network and graph _component_vertex_count supp = len(getattr(cnet, "vertex_list")) _val = [{cid: supp} for objt in obj_type] attr = [objt + attr for objt in obj_type] elif attr == "adjacencylist": supp_adj = copy.deepcopy(list(getattr(cnet, attr).keys())) supp_vtx = getattr(cnet, "vertex_list") supp_rmv = [v for v in supp_adj if v not in supp_vtx] [getattr(cnet, attr).pop(s) for s in supp_rmv] return elif attr == "_component_is_ring": # reassigns both network and graph _component_is_ring supp = [getattr(cnet, objt + attr) for objt in obj_type] _val = [{cid: s[cid]} for s in supp] attr = [objt + attr for objt in obj_type] elif attr == "non_articulation_points": supp_vtx = getattr(cnet, "vertex_list") _val = [[s for s in getattr(cnet, attr) if s in supp_vtx]] attr = [attr] elif attr == "_component2": # reassigns both network and graph _component2 attributes supp = [_n + "_component2" + _a] if hasgraph: supp += [_g + "_component2" + _e] _val = [{cid: getattr(cnet, s)[cid]} for s in supp] attr = supp elif attr == "arcs": # reassigns both arcs and edges c2 = "_component2" supp = [_n + c2 + _a] if hasgraph: supp += [_g + c2 + _e] _val = [getattr(cnet, s)[cid] for s in supp] attr = [attr] if hasgraph: attr += ["edges"] elif attr == "_component_labels": # reassigns both network and graph _component_labels supp = [len(getattr(cnet, o + "s")) for o in obj] _val = [numpy.array([cid] * s) for s in supp] attr = [objt + attr for objt in obj_type] elif attr == "_component_lengths": # reassigns both network and graph _component_lengths supp = [objt + attr for objt in obj_type] _val = [{cid: getattr(cnet, s)[cid]} for s in supp] attr = supp elif attr == "_lengths": # reassigns both arc and edge _lengths supp_name = [o + attr for o in obj] supp_lens = [getattr(cnet, s) for s in supp_name] supp_link = [getattr(cnet, o + "s") for o in obj] supp_ll = list(zip(supp_lens, supp_link)) _val = [{k: v for k, v in l1.items() if k in l2} for l1, l2 in supp_ll] attr = supp_name # reassign attributes for a, av in zip(attr, _val): setattr(cnet, a, av) # provide warning (for now) if the network contains a point pattern if getattr(net, "pointpatterns"): msg = "There is a least one point pattern associated with the network." msg += " Component extraction should be performed prior to snapping" msg += " point patterns to the network object; failing to do so may" msg += " lead to unexpected results." warnings.warn(msg) # provide warning (for now) if the network contains a point pattern dm, nt = "distance_matrix", "network_trees" if hasattr(net, dm) or hasattr(net, nt): msg = "Either one or both (%s, %s) attributes" % (dm, nt) msg += " are present and will be deleted. These must be" msg += " recalculated following component extraction." warnings.warn(msg) for attr in [dm, nt]: if hasattr(net, attr): _attr = getattr(net, attr) del _attr # make initial copy of the network cnet = copy.deepcopy(net) # set labels _n, _a, _g, _e = "network", "arc", "graph", "edge" obj_type = [_n] obj = [_a] hasgraph = False if hasattr(cnet, "w_graph"): obj_type += [_g] obj += [_e] hasgraph = True # attributes to reassign update_attributes = [ "_fully_connected", "_n_components", "_longest_component", "_largest_component", "vertex_list", "vertex_coords", "_component_vertex_count", "adjacencylist", "_component_is_ring", "_component2", "arcs", "_component_lengths", "_lengths", "_component_labels", ] if hasgraph: update_attributes.append("non_articulation_points") # reassign attributes for attribute in update_attributes: _reassign(attribute, component_id) # recreate spatial weights cnet.w_network = cnet.contiguityweights(graph=False, weightings=weightings) if hasgraph: cnet.w_graph = cnet.contiguityweights(graph=True, weightings=weightings) return cnet def spanning_tree(net, method="sort", maximum=False, silence_warnings=True): """Extract a minimum or maximum spanning tree from a network. Parameters ---------- net : spaghetti.Network Instance of a network object. method : str Method for determining spanning tree. Currently, the only supported method is 'sort', which sorts the network arcs by length prior to building intermediary networks and checking for cycles within the tree/subtrees. Future methods may include linear programming approachs, etc. maximum : bool When ``True`` a maximum spanning tree is created. When ``False`` a minimum spanning tree is created. Default is ``False``. silence_warnings : bool Warn if there is more than one connected component. Default is ``False`` due to the nature of constructing a minimum spanning tree. Returns ------- net : spaghetti.Network Pruned instance of the network object. Notes ----- For in-depth background and details see :cite:`GrahamHell_1985`, :cite:`AhujaRavindraK`, and :cite:`Okabe2012`. See also -------- networkx.algorithms.tree.mst scipy.sparse.csgraph.minimum_spanning_tree Examples -------- Create a network instance. >>> from libpysal import cg >>> import spaghetti >>> p00 = cg.Point((0,0)) >>> lines = [cg.Chain([p00, cg.Point((0,3)), cg.Point((4,0)), p00])] >>> ntw = spaghetti.Network(in_data=lines) Extract the minimum spanning tree. >>> minst_net = spaghetti.spanning_tree(ntw) >>> min_len = sum(minst_net.arc_lengths.values()) >>> min_len 7.0 Extract the maximum spanning tree. >>> maxst_net = spaghetti.spanning_tree(ntw, maximum=True) >>> max_len = sum(maxst_net.arc_lengths.values()) >>> max_len 9.0 >>> max_len > min_len True """ # (un)silence warning weights_kws = {"silence_warnings": silence_warnings} # do not extract graph object while testing for cycles net_kws = {"extractgraph": False, "weights_kws": weights_kws} # if the network has no cycles, it is already a spanning tree if util.network_has_cycle(net.adjacencylist): if method.lower() == "sort": spanning_tree = mst_weighted_sort(net, maximum, net_kws) else: msg = "'%s' not a valid method for minimum spanning tree creation" raise ValueError(msg % method) # instantiate the spanning tree as a network object net = Network(in_data=spanning_tree, weights_kws=weights_kws) return net def mst_weighted_sort(net, maximum, net_kws): """Extract a minimum or maximum spanning tree from a network used the length-weighted sort method. Parameters ---------- net : spaghetti.Network See ``spanning_tree()``. maximum : bool See ``spanning_tree()``. net_kws : dict Keywords arguments for instaniating a ``spaghetti.Network``. Returns ------- spanning_tree : list All networks arcs that are members of the spanning tree. Notes ----- This function is based on the method found in Chapter 3 Section 4.3 of :cite:`Okabe2012`. """ # network arcs dictionary sorted by arc length sort_kws = {"key": net.arc_lengths.get, "reverse": maximum} sorted_lengths = sorted(net.arc_lengths, **sort_kws) # the spanning tree is initially empty spanning_tree = [] # iterate over each lengths of network arc while sorted_lengths: _arc = sorted_lengths.pop(0) # make a spatial representation of an arc chain_rep = util.chain_constr(net.vertex_coords, [_arc]) # current set of network arcs as libpysal.cg.Chain _chains = spanning_tree + chain_rep # current network iteration _ntw = Network(in_data=_chains, **net_kws) # determine if the network contains a cycle if not util.network_has_cycle(_ntw.adjacencylist): # If no cycle is present, add the arc to the spanning tree spanning_tree.extend(chain_rep) return spanning_tree def regular_lattice(bounds, nh, nv=None, exterior=False): """Generate a regular lattice of line segments (`libpysal.cg.Chain objects <https://pysal.org/libpysal/generated/libpysal.cg.Chain.html#libpysal.cg.Chain>`_). Parameters ---------- bounds : {tuple, list} Area bounds in the form - <minx,miny,maxx,maxy>. nh : int The number of internal horizontal lines of the lattice. nv : int The number of internal vertical lines of the lattice. Defaults to ``nh`` if left as None. exterior : bool Flag for including the outer bounding box segments. Default is False. Returns ------- lattice : list The ``libpysal.cg.Chain`` objects forming a regular lattice. Notes ----- The ``nh`` and ``nv`` parameters do not include the external line segments. For example, setting ``nh=3, nv=2, exterior=True`` will result in 5 horizontal line sets and 4 vertical line sets. Examples -------- Create a 5x5 regular lattice with an exterior >>> import spaghetti >>> lattice = spaghetti.regular_lattice((0,0,4,4), 3, exterior=True) >>> lattice[0].vertices [(0.0, 0.0), (1.0, 0.0)] Create a 5x5 regular lattice without an exterior >>> lattice = spaghetti.regular_lattice((0,0,5,5), 3, exterior=False) >>> lattice[-1].vertices [(3.75, 3.75), (3.75, 5.0)] Create a 7x9 regular lattice with an exterior from the bounds of ``streets.shp``. >>> path = libpysal.examples.get_path("streets.shp") >>> shp = libpysal.io.open(path) >>> lattice = spaghetti.regular_lattice(shp.bbox, 5, nv=7, exterior=True) >>> lattice[0].vertices [(723414.3683108028, 875929.0396895551), (724286.1381211297, 875929.0396895551)] """ # check for bounds validity if len(bounds) != 4: bounds_len = len(bounds) msg = "The 'bounds' parameter is %s elements " % bounds_len msg += "but should be exactly 4 - <minx,miny,maxx,maxy>." raise RuntimeError(msg) # check for bounds validity if not nv: nv = nh try: nh, nv = int(nh), int(nv) except TypeError: nlines_types = type(nh), type(nv) msg = "The 'nh' and 'nv' parameters (%s, %s) " % nlines_types msg += "could not be converted to integers." raise TypeError(msg) # bounding box line lengths len_h, len_v = bounds[2] - bounds[0], bounds[3] - bounds[1] # horizontal and vertical increments incr_h, incr_v = len_h / float(nh + 1), len_v / float(nv + 1) # define the horizontal and vertical space space_h = [incr_h * slot for slot in range(nv + 2)] space_v = [incr_v * slot for slot in range(nh + 2)] # create vertical and horizontal lines lines_h = util.build_chains(space_h, space_v, exterior, bounds) lines_v = util.build_chains(space_h, space_v, exterior, bounds, h=False) # combine into one list lattice = lines_h + lines_v return lattice
[ 6738, 17268, 1330, 4277, 11600, 11, 14230, 1068, 35, 713, 198, 6738, 340, 861, 10141, 1330, 318, 75, 501, 198, 11748, 4866, 11, 28686, 11, 2298, 293, 11, 14601, 198, 198, 11748, 1658, 6814, 198, 11748, 299, 32152, 198, 198, 6738, 764,...
2.407937
6,577
from mlflow.tracking.default_experiment.abstract_context import DefaultExperimentProvider
[ 6738, 285, 1652, 9319, 13, 36280, 13, 12286, 62, 23100, 3681, 13, 397, 8709, 62, 22866, 1330, 15161, 20468, 3681, 29495, 628 ]
4.136364
22
# -*- coding: utf-8 -*- """ plot acc loss @author: atpandey """ #%% import matplotlib.pyplot as plt #%% ff='./to_laptop/trg_file.txt' with open(ff,'r') as trgf: listidx=[] listloss=[] listacc=[] ctr=0 for line in trgf: if(ctr>0): ll=line.split(',') listidx.append(ll[0]) listloss.append(ll[1]) listacc.append(ll[2]) #listf.append(line) ctr +=1 #for i in range(len(listidx)): # print("idx: {}, loss: {}, acc: {}".format(listidx[i],listloss[i],listacc[i])) # Make a figure fig = plt.figure() plt.subplots_adjust(top = 0.99, bottom=0.05, hspace=0.5, wspace=0.4) # The axes ax1 = fig.add_subplot(2, 1, 1) ax2 = fig.add_subplot(2, 1, 2) #plots ax1.plot(listloss,'bo-',label='loss') ax2.plot(listacc,'go-',label='accuracy') ax1.set_xlabel('training idx') ax1.set_ylabel('Loss') ax1.set_title('loss data set') ax1.legend() ax2.set_xlabel('training idx') ax2.set_ylabel('accuracy') ax2.set_title('accuracydata set') ax2.legend() plt.show() plt.savefig('./outputs/loss_accuracy.png')
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 29487, 697, 2994, 198, 198, 31, 9800, 25, 379, 79, 392, 2959, 198, 37811, 198, 198, 2, 16626, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83,...
1.951957
562
##--------------------------------Main file------------------------------------ ## ## Copyright (C) 2020 by Belinda Brown Ramrez (belindabrownr04@gmail.com) ## June, 2020 ## timna.brown@ucr.ac.cr ##----------------------------------------------------------------------------- # Variables aleatorias mltiples # Se consideran dos bases de datos las cuales contienen los descrito # a continuacin: # 1. ****** Registro de la frecuencia relativa de dos variables aleatorias # conjuntas en forma de tabla: xy.csv # 2. ****** Pares (x, y) y su probabilidad asociada: xyp.csv # Recordando que variable aleatoria es una funcin determinista. #### **************** Algoritmo **************** #### #****************************************************** # IMPORTANDO PAQUETES #****************************************************** # Es importante considerar que notas son necesarias pero si # fueron usadas durante el desarrollo de la tarea por diversas # razones por lo cual se mantiene dentro del algortimo en forma # comentario. # from __future__ import division # from pylab import * # from sklearn import * # from sklearn.preprocessing import PolynomialFeatures # import math # import decimal # import pandas as pd # from scipy.stats import norm # from scipy.stats import rayleigh # import csv import pandas as pd from collections import OrderedDict import matplotlib.pyplot as plt import matplotlib.mlab as mlab from mpl_toolkits.mplot3d import axes3d from numpy import * import numpy as np from matplotlib import cm import scipy.stats as stats from scipy.optimize import curve_fit #****************************************************** # DEFINICIONES #****************************************************** #****************************************************** # OBTENIENDO VALORES # DE LOS CSV #****************************************************** data = pd.read_csv("/Users/belindabrown/Desktop/VA_multiples/data_base/xy.csv", index_col=0) data_xyp = pd.read_csv("/Users/belindabrown/Desktop/VA_multiples/data_base/xyp.csv") #****************************************************** # CURVA DE MEJOR AJUSTE # DE LAS FUNCIONES DE # DENSIDAD MARGINALES X & Y #****************************************************** # Se requieren los valores marginales tanto de x como de y # Columna con la sumatoria de todas las columnas es la probabilidad marginal de X marg_value_x = [n for n in data.sum(axis=1, numeric_only=True)] # Fila con la sumatoria de todas las filas es la probabilidad marginal de Y marg_value_y = [n for n in data.sum(axis=0, numeric_only=True)] print("\nValor marginal de X: ", marg_value_x) print("\nValor marginal de Y: ", marg_value_y) x_curva_modelo, x_mu, x_sigma = ajuste_curva(marg_value_x, 5, 15, distribucion_normal, "Datos que pertenencen a X","Datos_de_X", "Modelos de X(x)", "Modelado_X(x)") y_curva_modelo, y_mu, y_sigma = ajuste_curva(marg_value_y, 5, 25, distribucion_normal, "Datos que pertenencen a Y","Datos_de_Y", "Modelos de Y(y)", "Modelado_Y(y)") #****************************************************** # FUNCION DE DENSIDAD # CONJUNTA DE # X & Y #****************************************************** probabi_conjuntaX = distribucion_normal(x_curva_modelo,x_mu,x_sigma) probabi_conjuntaY = distribucion_normal(y_curva_modelo,y_mu,y_sigma) #****************************************************** # VALORES DE CORRELACION, COVARIANZA # COEFICIENTE DE CORRELACION (PEARSON) # Y SIGNIFICADO #****************************************************** ###### OBTENIDOS CON XY.CSV # Se requieren los valores anteriormente calculados. Para calcular # E[X] & E[Y] lo que se conoce como los valores. # Valores inicializados de los valores de X y Y (E[X] y E[Y]) # Este rango es de [x0, x1], es decir, incluye los limites e_x = valor_esperado(marg_value_x,5,15, "X") e_y = valor_esperado(marg_value_y,5,25, "Y") multi_valor_esperados = e_x*e_y # Se calcula E[X]*E[Y] print("\n\nEl valor de E[X]E[Y] es de: ", multi_valor_esperados) ###### OBTENIDOS CON XYP.CSV # Dado que la primera fila contiene las etiquetas de x, y, p todos_mu_sum = data_xyp.x * data_xyp.y * data_xyp.p # La sumatoria de E[XY] nos brinda su correlacin correlacion = todos_mu_sum.sum() # Ahora para la covarianza, de acuerdo a lo visto en clase la # covarianza es la correlacion menos la multiplicacion de los # valores. covarianza = correlacion - multi_valor_esperados # Se requiere calcular el coeficiente de correlacion de # Pearson en el cual se utilizan los valores de la data brindada de # obtenidos entonces ... # De acuerdo a los resultados obtenidos al correr el programa # se ve que: # SigmaDatos_de_X = 3.2994428707078436 # SigmaDatos_de_Y = 6.0269377486808775 # Para el coeficiente pearson se calcula como la covarianza # divida entre la multiplicacion de los sigmas coef_pearson = covarianza/(3.2994428707078436*6.0269377486808775) print("\nEl resultado de la correlacin es de: ", correlacion) print("\nEl resultado de la covarianza es de: ",covarianza) print("\nDe acuerdo a los datos obtenidos y considerando todo sus decimales se tiene que el coeficiente de Pearson es de: ", coef_pearson) #****************************************************** # GRAFICA EN 2D DE LAS FUNCIONES # DE DENSIDAD MARGINALES # & # GRAFICA EN 3D DE LA FUNCION # DE DENSIDAD CONJUNTA #****************************************************** # Dado que se requiere redondear los valores para la grfica se toma en # cuenta que los parmetros completos para el modelo seran los ya calculados distribucion_de_x = grafica_en2d(x_mu, x_sigma, 100,"Distribucion_de_X") distribucion_de_y = grafica_en2d(y_mu, y_sigma, 100,"Distribucion_de_Y") dis_cojun3d = grafica_en3d(x_curva_modelo, y_curva_modelo, probabi_conjuntaX, probabi_conjuntaY, "Distribucion_en_3D")
[ 2235, 3880, 13383, 2393, 3880, 650, 198, 2235, 198, 2235, 15069, 357, 34, 8, 12131, 416, 3944, 22261, 4373, 7431, 21107, 357, 6667, 521, 397, 2053, 81, 3023, 31, 14816, 13, 785, 8, 198, 2235, 197, 197, 197, 15749, 11, 12131, 198, 22...
2.714416
2,192
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by 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. """Convolutional Neural Network Estimator for MNIST, built with tf.layers.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import os import sys import tensorflow as tf import dataset def model_fn(features, labels, mode, params): """The model_fn argument for creating an Estimator.""" model = Model(params['data_format']) image = features if isinstance(image, dict): image = features['image'] if mode == tf.estimator.ModeKeys.PREDICT: logits = model(image, training=False) predictions = { 'classes': tf.argmax(logits, axis=1), 'probabilities': tf.nn.softmax(logits), } return tf.estimator.EstimatorSpec( mode=tf.estimator.ModeKeys.PREDICT, predictions=predictions, export_outputs={ 'classify': tf.estimator.export.PredictOutput(predictions) }) if mode == tf.estimator.ModeKeys.TRAIN: optimizer = tf.train.AdamOptimizer(learning_rate=1e-4) logits = model(image, training=True) loss = tf.losses.softmax_cross_entropy(onehot_labels=labels, logits=logits) accuracy = tf.metrics.accuracy( labels=tf.argmax(labels, axis=1), predictions=tf.argmax(logits, axis=1)) # Name the accuracy tensor 'train_accuracy' to demonstrate the # LoggingTensorHook. tf.identity(accuracy[1], name='train_accuracy') tf.summary.scalar('train_accuracy', accuracy[1]) return tf.estimator.EstimatorSpec( mode=tf.estimator.ModeKeys.TRAIN, loss=loss, train_op=optimizer.minimize(loss, tf.train.get_or_create_global_step())) if mode == tf.estimator.ModeKeys.EVAL: logits = model(image, training=False) loss = tf.losses.softmax_cross_entropy(onehot_labels=labels, logits=logits) return tf.estimator.EstimatorSpec( mode=tf.estimator.ModeKeys.EVAL, loss=loss, eval_metric_ops={ 'accuracy': tf.metrics.accuracy( labels=tf.argmax(labels, axis=1), predictions=tf.argmax(logits, axis=1)), }) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument( '--batch_size', type=int, default=100, help='Number of images to process in a batch') parser.add_argument( '--data_dir', type=str, default='/tmp/mnist_data', help='Path to directory containing the MNIST dataset') parser.add_argument( '--model_dir', type=str, default='/tmp/mnist_model', help='The directory where the model will be stored.') parser.add_argument( '--train_epochs', type=int, default=40, help='Number of epochs to train.') parser.add_argument( '--data_format', type=str, default=None, choices=['channels_first', 'channels_last'], help='A flag to override the data format used in the model. channels_first ' 'provides a performance boost on GPU but is not always compatible ' 'with CPU. If left unspecified, the data format will be chosen ' 'automatically based on whether TensorFlow was built for CPU or GPU.') parser.add_argument( '--export_dir', type=str, help='The directory where the exported SavedModel will be stored.') tf.logging.set_verbosity(tf.logging.INFO) FLAGS, unparsed = parser.parse_known_args() tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)
[ 2, 220, 15069, 2177, 383, 309, 22854, 37535, 46665, 13, 1439, 6923, 33876, 13, 198, 2, 198, 2, 220, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 220, 345, 743, 407, 779, 428, 2393, 2...
2.596671
1,562
#!/usr/bin/env python3 TERMINALS = (1, 89) sq_sum = [sum(int(c)**2 for c in str(i)) for i in range(1000)] if __name__ == "__main__": print(calculate())
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 5781, 44, 17961, 50, 796, 357, 16, 11, 9919, 8, 198, 198, 31166, 62, 16345, 796, 685, 16345, 7, 600, 7, 66, 8, 1174, 17, 329, 269, 287, 965, 7, 72, 4008, 329, 1312, 28...
2.191781
73
from PyQt5.QtCore import *
[ 6738, 9485, 48, 83, 20, 13, 48, 83, 14055, 1330, 1635 ]
2.363636
11