content
stringlengths
1
1.04M
input_ids
listlengths
1
774k
ratio_char_token
float64
0.38
22.9
token_count
int64
1
774k
import numpy as np import os import pickle def seqrc(string): "returns the reverse complement of a sequence" dic_rc = constant_key_dict({'a':'t','c':'g','g':'c','t':'a','A':'T','C':'G','G':'C','T':'A'}) string_rc = "".join([dic_rc[c] for c in string][::-1]) return string_rc def getFastaWeb(chrom,pos1,pos2): "For mouse genome this impots from the infojax website the chr:pos1:pos2 genomic sequence" import urllib.request, urllib.error, urllib.parse site_name = "http://www.informatics.jax.org/seqfetch/tofasta.cgi?seq1=mousegenome%21%21"+str(chrom)+"%21"+str(pos1)+"%21"+str(pos2)+"%21%21&flank1=0" html = str(urllib.request.urlopen(site_name).read()) sequence = "".join(html.split("\n")[1:-1]) return sequence def getGeneWeb(gene_id): "For mouse genome this impots from the infojax website a given gene its genomic sequence" import urllib.request, urllib.error, urllib.parse site_name = "http://useast.ensembl.org/Mus_musculus/Export/Output/Gene?db=core;flank3_display=0;flank5_display=0;g="+gene_id+";output=fasta;strand=feature;genomic=unmasked;_format=Text" html = str(urllib.request.urlopen(site_name).read()) sequence = "".join(html.split("\r\n")[2:-1]) return sequence class OTTable (dict): """ run this as: specTable = OTTable() specTableMAP = specTable.computeOTTable(gen_seq,block) specTable.Save(filename) OR: specTable = OTTable() specTable.Load(filename) specTableMAP = specTable.Map() """ def compute_pair_probes(gene_names,gene_seqs,folder_save="",blk=17,pb_len=30,map_rep=None,map_noGenes=None,maps_Genes=None,FPKM_cuttoff1=2,FPKM_cuttoff2=10,min_gc=0.30,max_gc=0.70,gene_cutoff1=3,gene_cutoff2=5): """This is intended to return to you pairs of probes for bTree Require paramaters: @gene_names : a list of names for the genes you require probes. @gene_seqs : a list of sequences (A,C,G,T,N) for the genes you require probes. For exon junctions or masking use N. @blk : word size of the maps @pb_len : desired probe length @map_noGenes : if dictionary: the OT map of FPKM excluding the genes interested in. It is not necessary to exclude the genes or to use FPKM vs just sequences, but then use the cutoffs appropriately. if None: ignore this test if string: the path of a fasta file and compute the map on the spot using blk word size @maps_Genes : if dictionary: the Index map for the gese interested in. if None: ignore this test if string: the path of a fasta file and compute the map on the spot using blk word size @map_rep : if dictionary: the OT maps of higly abundant genes. No crosstalk with these genes will be accepted if None: ignore this test if string: the path of a fasta file and compute the map on the spot using blk word size @FPKM_cuttoff1/FPKM_cuttoff2 : min/max cut for the map_noGenes @gene_cutoff1/gene_cutoff2 : min/max cut for the maps_Genes @pb_len : probe length @min_gc/max_gc Returns: @pb_names_f : names of the probe in the form "<gene name>_pb:<location>_pb-pair:[<pair index>, <index in pair>]" @pb_seqs_f : sequences of the probes """ ### Check for variable pop: if type(map_noGenes)==str: print("Computing the map for transcriptome! Please wait!") names_,seqs_ = fastaread(map_noGenes) #construct specificity table (dictionary) for all the sequences of the transcripts in MOE. specTable = OTTable() print("Warning: FPKM might not be computed correctly!") FPKM_ = [float(nm.split('_')[-3]) for nm in names_] #change this for generic FPKM map_noGenes = specTable.computeOTTable(seqs_,blk,FPKM=FPKM_) if type(maps_Genes)==str: print("Computing the maps for genes!") names_,seqs_ = fastaread(maps_Genes) maps_Genes = computeIndexTable(seqs_,blk) if type(map_rep)==str: print("Computing the map for repetitive RNA!") names_,seqs_ = fastaread(map_rep) specTable = OTTable() map_rep = specTable.computeOTTable(seqs_,blk) ###Construct the probe scoring function pb_names_f,pb_seqs_f=[],[] num_pairs_f = [] ###Iterate through genes: for current_gene in range(len(gene_seqs)): gene_seq = gene_seqs[current_gene] gene_name = gene_names[current_gene] locations_recorded = [] location,pair_ind,pb_pair_ind=0,0,0 pb_names,pb_seqs=[],[] num_pairs = 0 while True: pb1,pb2 = gene_seq[location:location+pb_len],gene_seq[location+pb_len:location+2*pb_len] #check where this probe is already in the set pb1_verified = False if locations_recorded.count(location): pb1_verified = True noNs = pb1.count('N') + pb2.count('N') == 0 if noNs: seq_cut = gc(pb1)>=min_gc and gc(pb2)>=min_gc and gc(pb1)<=max_gc and gc(pb2)<=max_gc if seq_cut: if map_rep is not None: #Deal with cross-reactivity #--To very abundant mRNA score_rep1 = map_seq(pb1,map_rep,blk) score_rep2 = map_seq(pb2,map_rep,blk) rep_cut = score_rep1==0 and score_rep2==0 else: rep_cut=True if rep_cut: if map_noGenes is not None: #--To all RNA's except the olfrs (using FPKMcuttoff) score_RNA1 = map_seq(pb1,map_noGenes,blk) score_RNA2 = map_seq(pb2,map_noGenes,blk) RNA_cut = min(score_RNA1,score_RNA2)<min(FPKM_cuttoff1,FPKM_cuttoff2) and max(score_RNA1,score_RNA2)<max(FPKM_cuttoff1,FPKM_cuttoff2) else: RNA_cut=True if RNA_cut: if maps_Genes is not None: #--To all olfrs #--To all olfrs scores_Gene1 = map_seq(pb1,maps_Genes,blk) scores_Gene1.pop(np.argmax([sc[1] for sc in scores_Gene1])) # pop the maximum scores_Gene2 = map_seq(pb2,maps_Genes,blk) scores_Gene2.pop(np.argmax([sc[1] for sc in scores_Gene2])) # pop the maximum geneIdx_offGene1 = [score[0] for score in scores_Gene1 if score[1]>gene_cutoff1] geneIdx_offGene2 = [score[0] for score in scores_Gene2 if score[1]>gene_cutoff2] geneIdx_offGene1_ = [score[0] for score in scores_Gene2 if score[1]>gene_cutoff1] geneIdx_offGene2_ = [score[0] for score in scores_Gene1 if score[1]>gene_cutoff2] gene_int = min(len(np.intersect1d(geneIdx_offGene1,geneIdx_offGene2)),len(np.intersect1d(geneIdx_offGene1_,geneIdx_offGene2_))) else: gene_int=0 if gene_int==0: # record poisitions: ## create name: if pb1_verified: pb_pair_ind+=1 pb_name = gene_name+"_pb:"+str(location+pb_len)+'_pb-pair:'+str([pair_ind,pb_pair_ind]) pb_names.append(pb_name) pb_seqs.append(pb2) locations_recorded.append(location+pb_len) num_pairs+=1 else: pair_ind+=1 pb_pair_ind=1 pb_name = gene_name+"_pb:"+str(location)+'_pb-pair:'+str([pair_ind,pb_pair_ind]) pb_names.append(pb_name) pb_seqs.append(pb1) locations_recorded.append(location) pb_pair_ind+=1 pb_name = gene_name+"_pb:"+str(location+pb_len)+'_pb-pair:'+str([pair_ind,pb_pair_ind]) pb_names.append(pb_name) pb_seqs.append(pb2) locations_recorded.append(location+pb_len) num_pairs+=1 gene_seq = gene_seq[:location]+"".join(['N' for k in range(pb_len)])+gene_seq[location+pb_len:] location+=1 if location+2*pb_len>len(gene_seq): break print(gene_name+" (pairs: "+str(num_pairs)+") done!") fastawrite(folder_save+os.sep+gene_name+'_probes.fasta',pb_names,pb_seqs) pb_names_f.append(pb_names) pb_seqs_f.append(pb_seqs) num_pairs_f+=[num_pairs] return pb_names_f,pb_seqs_f,num_pairs_f def file_to_mat(file_,sep_str=',',d_type=None,skip_first=False): """ Converts .csv files to a list of its entries Inputs: file_ - the location of a .csv file sep_str - the separator between data points d_type - the datatype in the file skip_first - an option to skip the first component (e.g. if there's a menu) Returns: lines - a list of the lines in the file, each of which itself a list of all entries in the line """ lines = [ln for ln in open(file_,'r')] start_=(1 if skip_first==True else 0) #skip first line if option selected lines = [refine_line(ln,d_type,skip_first) for ln in lines[start_:]] return lines def map_gene(pairs_nms_,pairs_sqs_,code,tails,pair_limit_per_bit=10): """ Use as: map_gene([['name_pb-pair:[1,1]','name_pb-pair:[1,2]','name_pb-pair:[1,3]'],['name_pb-pair:[2,1]','name_pb-pair:[2,2]']], [['sq1','sq2','sq3'],['sq4','sq5']],[0,1,2], ['0000','1111','2222','3333','4444','5555'],pair_limit_per_bit=10) """ nms_gene,sqs_gene = [],[] cts_icode = [0 for i in range(len(code))] cts_vcode = [0 for i in range(len(code))] for nms_,sqs_ in zip(pairs_nms_,pairs_sqs_): nms_new,sqs_new = map_pair(nms_,sqs_,code,cts_icode,cts_vcode,tails,pair_limit_per_bit) nms_gene.extend(nms_new) sqs_gene.extend(sqs_new) if min(cts_vcode)>=pair_limit_per_bit: break return nms_gene,sqs_gene
[ 11748, 299, 32152, 355, 45941, 198, 11748, 28686, 198, 11748, 2298, 293, 198, 4299, 33756, 6015, 7, 8841, 2599, 198, 220, 220, 220, 366, 7783, 82, 262, 9575, 16829, 286, 257, 8379, 1, 198, 220, 220, 220, 288, 291, 62, 6015, 796, 693...
1.873525
5,764
# -*- coding: utf-8 -*- """Merge reader for SQLite storage files.""" from __future__ import unicode_literals import os import sqlite3 import zlib from plaso.containers import errors from plaso.containers import event_sources from plaso.containers import events from plaso.containers import reports from plaso.containers import tasks from plaso.lib import definitions from plaso.storage import identifiers from plaso.storage import interface class SQLiteStorageMergeReader(interface.StorageFileMergeReader): """SQLite-based storage file reader for merging.""" _CONTAINER_TYPE_ANALYSIS_REPORT = reports.AnalysisReport.CONTAINER_TYPE _CONTAINER_TYPE_EVENT = events.EventObject.CONTAINER_TYPE _CONTAINER_TYPE_EVENT_DATA = events.EventData.CONTAINER_TYPE _CONTAINER_TYPE_EVENT_SOURCE = event_sources.EventSource.CONTAINER_TYPE _CONTAINER_TYPE_EVENT_TAG = events.EventTag.CONTAINER_TYPE _CONTAINER_TYPE_EXTRACTION_ERROR = errors.ExtractionError.CONTAINER_TYPE _CONTAINER_TYPE_TASK_COMPLETION = tasks.TaskCompletion.CONTAINER_TYPE _CONTAINER_TYPE_TASK_START = tasks.TaskStart.CONTAINER_TYPE # Some container types reference other container types, such as event # referencing event_data. Container types in this tuple must be ordered after # all the container types they reference. _CONTAINER_TYPES = ( _CONTAINER_TYPE_EVENT_SOURCE, _CONTAINER_TYPE_EVENT_DATA, _CONTAINER_TYPE_EVENT, _CONTAINER_TYPE_EVENT_TAG, _CONTAINER_TYPE_EXTRACTION_ERROR, _CONTAINER_TYPE_ANALYSIS_REPORT) _ADD_CONTAINER_TYPE_METHODS = { _CONTAINER_TYPE_ANALYSIS_REPORT: '_AddAnalysisReport', _CONTAINER_TYPE_EVENT: '_AddEvent', _CONTAINER_TYPE_EVENT_DATA: '_AddEventData', _CONTAINER_TYPE_EVENT_SOURCE: '_AddEventSource', _CONTAINER_TYPE_EVENT_TAG: '_AddEventTag', _CONTAINER_TYPE_EXTRACTION_ERROR: '_AddError', } _TABLE_NAMES_QUERY = ( 'SELECT name FROM sqlite_master WHERE type = "table"') def __init__(self, storage_writer, path): """Initializes a storage merge reader. Args: storage_writer (StorageWriter): storage writer. path (str): path to the input file. Raises: IOError: if the input file cannot be opened. RuntimeError: if an add container method is missing. """ super(SQLiteStorageMergeReader, self).__init__(storage_writer) self._active_container_type = None self._active_cursor = None self._add_active_container_method = None self._add_container_type_methods = {} self._compression_format = definitions.COMPRESSION_FORMAT_NONE self._connection = None self._container_types = None self._cursor = None self._event_data_identifier_mappings = {} self._path = path # Create a runtime lookup table for the add container type method. This # prevents having to create a series of if-else checks for container types. # The table is generated at runtime as there are no forward function # declarations in Python. for container_type, method_name in self._ADD_CONTAINER_TYPE_METHODS.items(): method = getattr(self, method_name, None) if not method: raise RuntimeError( 'Add method missing for container type: {0:s}'.format( container_type)) self._add_container_type_methods[container_type] = method def _AddAnalysisReport(self, analysis_report): """Adds an analysis report. Args: analysis_report (AnalysisReport): analysis report. """ self._storage_writer.AddAnalysisReport(analysis_report) def _AddError(self, error): """Adds an error. Args: error (ExtractionError): error. """ self._storage_writer.AddError(error) def _AddEvent(self, event): """Adds an event. Args: event (EventObject): event. """ if hasattr(event, 'event_data_row_identifier'): event_data_identifier = identifiers.SQLTableIdentifier( self._CONTAINER_TYPE_EVENT_DATA, event.event_data_row_identifier) lookup_key = event_data_identifier.CopyToString() event_data_identifier = self._event_data_identifier_mappings[lookup_key] event.SetEventDataIdentifier(event_data_identifier) # TODO: add event identifier mappings for event tags. self._storage_writer.AddEvent(event) def _AddEventData(self, event_data): """Adds event data. Args: event_data (EventData): event data. """ identifier = event_data.GetIdentifier() lookup_key = identifier.CopyToString() self._storage_writer.AddEventData(event_data) identifier = event_data.GetIdentifier() self._event_data_identifier_mappings[lookup_key] = identifier def _AddEventSource(self, event_source): """Adds an event source. Args: event_source (EventSource): event source. """ self._storage_writer.AddEventSource(event_source) def _AddEventTag(self, event_tag): """Adds an event tag. Args: event_tag (EventTag): event tag. """ self._storage_writer.AddEventTag(event_tag) def _Close(self): """Closes the task storage after reading.""" self._connection.close() self._connection = None self._cursor = None def _GetContainerTypes(self): """Retrieves the container types to merge. Container types not defined in _CONTAINER_TYPES are ignored and not merged. Specific container types reference other container types, such as event referencing event data. The names are ordered to ensure the attribute containers are merged in the correct order. Returns: list[str]: names of the container types to merge. """ self._cursor.execute(self._TABLE_NAMES_QUERY) table_names = [row[0] for row in self._cursor.fetchall()] return [ table_name for table_name in self._CONTAINER_TYPES if table_name in table_names] def _Open(self): """Opens the task storage for reading.""" self._connection = sqlite3.connect( self._path, detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES) self._cursor = self._connection.cursor() def _ReadStorageMetadata(self): """Reads the task storage metadata.""" query = 'SELECT key, value FROM metadata' self._cursor.execute(query) metadata_values = {row[0]: row[1] for row in self._cursor.fetchall()} self._compression_format = metadata_values['compression_format'] def _PrepareForNextContainerType(self): """Prepares for the next container type. This method prepares the task storage for merging the next container type. It set the active container type, its add method and active cursor accordingly. """ self._active_container_type = self._container_types.pop(0) self._add_active_container_method = self._add_container_type_methods.get( self._active_container_type) query = 'SELECT _identifier, _data FROM {0:s}'.format( self._active_container_type) self._cursor.execute(query) self._active_cursor = self._cursor def MergeAttributeContainers( self, callback=None, maximum_number_of_containers=0): """Reads attribute containers from a task storage file into the writer. Args: callback (function[StorageWriter, AttributeContainer]): function to call after each attribute container is deserialized. maximum_number_of_containers (Optional[int]): maximum number of containers to merge, where 0 represent no limit. Returns: bool: True if the entire task storage file has been merged. Raises: RuntimeError: if the add method for the active attribute container type is missing. OSError: if the task storage file cannot be deleted. ValueError: if the maximum number of containers is a negative value. """ if maximum_number_of_containers < 0: raise ValueError('Invalid maximum number of containers') if not self._cursor: self._Open() self._ReadStorageMetadata() self._container_types = self._GetContainerTypes() number_of_containers = 0 while self._active_cursor or self._container_types: if not self._active_cursor: self._PrepareForNextContainerType() if maximum_number_of_containers == 0: rows = self._active_cursor.fetchall() else: number_of_rows = maximum_number_of_containers - number_of_containers rows = self._active_cursor.fetchmany(size=number_of_rows) if not rows: self._active_cursor = None continue for row in rows: identifier = identifiers.SQLTableIdentifier( self._active_container_type, row[0]) if self._compression_format == definitions.COMPRESSION_FORMAT_ZLIB: serialized_data = zlib.decompress(row[1]) else: serialized_data = row[1] attribute_container = self._DeserializeAttributeContainer( self._active_container_type, serialized_data) attribute_container.SetIdentifier(identifier) if self._active_container_type == self._CONTAINER_TYPE_EVENT_TAG: event_identifier = identifiers.SQLTableIdentifier( self._CONTAINER_TYPE_EVENT, attribute_container.event_row_identifier) attribute_container.SetEventIdentifier(event_identifier) del attribute_container.event_row_identifier if callback: callback(self._storage_writer, attribute_container) self._add_active_container_method(attribute_container) number_of_containers += 1 if (maximum_number_of_containers != 0 and number_of_containers >= maximum_number_of_containers): return False self._Close() os.remove(self._path) return True
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 13102, 469, 9173, 329, 16363, 578, 6143, 3696, 526, 15931, 198, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 198, 11748, 28686, 198, 11748,...
2.75864
3,530
import os from pathlib import Path import pytest from robotidy.app import Robotidy from robotidy.utils import decorate_diff_with_color, split_args_from_name_or_path, GlobalFormattingConfig @pytest.fixture
[ 11748, 28686, 198, 6738, 3108, 8019, 1330, 10644, 198, 198, 11748, 12972, 9288, 198, 198, 6738, 9379, 19325, 13, 1324, 1330, 16071, 19325, 198, 6738, 9379, 19325, 13, 26791, 1330, 11705, 378, 62, 26069, 62, 4480, 62, 8043, 11, 6626, 62,...
3.28125
64
# Generated by Django 3.2 on 2021-06-14 21:05 from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 513, 13, 17, 319, 33448, 12, 3312, 12, 1415, 2310, 25, 2713, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
2.966667
30
f() print("PASS")
[ 198, 69, 3419, 198, 198, 4798, 7203, 47924, 4943 ]
2.111111
9
# Copyright 2020 Google LLC. 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. # ============================================================================== """Distribution adapters for (soft) round functions.""" import tensorflow as tf import tensorflow_probability as tfp from tensorflow_compression.python.distributions import deep_factorized from tensorflow_compression.python.distributions import helpers from tensorflow_compression.python.distributions import uniform_noise from tensorflow_compression.python.ops import soft_round_ops __all__ = [ "MonotonicAdapter", "RoundAdapter", "NoisyRoundedNormal", "NoisyRoundedDeepFactorized", "SoftRoundAdapter", "NoisySoftRoundedNormal", "NoisySoftRoundedDeepFactorized" ] class MonotonicAdapter(tfp.distributions.Distribution): """Adapt a continuous distribution via an ascending monotonic function. This is described in Appendix E. in the paper > "Universally Quantized Neural Compression"<br /> > Eirikur Agustsson & Lucas Theis<br /> > https://arxiv.org/abs/2006.09952 """ invertible = True # Set to false if the transform is not invertible. def __init__(self, base, name="MonotonicAdapter"): """Initializer. Arguments: base: A `tfp.distributions.Distribution` object representing a continuous-valued random variable. name: String. A name for this distribution. """ parameters = dict(locals()) self._base = base super().__init__( dtype=base.dtype, reparameterization_type=base.reparameterization_type, validate_args=base.validate_args, allow_nan_stats=base.allow_nan_stats, parameters=parameters, name=name, ) @property def base(self): """The base distribution.""" return self._base def transform(self, x): """The forward transform.""" raise NotImplementedError() def inverse_transform(self, y): """The backward transform.""" # Let f(x) = self.transform(x) # Then g(y) = self.inverse_transform(y) is defined as # g(y) := inf_x { x : f(x) >= y } # which is just the inverse of `f` if it is invertible. raise NotImplementedError() # pylint: disable=protected-access # pylint: enable=protected-access class RoundAdapter(MonotonicAdapter): """Continuous density function + round.""" invertible = False class NoisyRoundAdapter(uniform_noise.UniformNoiseAdapter): """Uniform noise + round.""" def __init__(self, base, name="NoisyRoundAdapter"): """Initializer. Arguments: base: A `tfp.distributions.Distribution` object representing a continuous-valued random variable. name: String. A name for this distribution. """ super().__init__(RoundAdapter(base), name=name) class NoisyRoundedDeepFactorized(NoisyRoundAdapter): """Rounded DeepFactorized + uniform noise.""" class NoisyRoundedNormal(NoisyRoundAdapter): """Rounded normal distribution + uniform noise.""" class SoftRoundAdapter(MonotonicAdapter): """Differentiable approximation to round.""" def __init__(self, base, alpha, name="SoftRoundAdapter"): """Initializer. Arguments: base: A `tfp.distributions.Distribution` object representing a continuous-valued random variable. alpha: Float or tf.Tensor. Controls smoothness of the approximation. name: String. A name for this distribution. """ super().__init__(base=base, name=name) self._alpha = alpha class NoisySoftRoundAdapter(uniform_noise.UniformNoiseAdapter): """Uniform noise + differentiable approximation to round.""" def __init__(self, base, alpha, name="NoisySoftRoundAdapter"): """Initializer. Arguments: base: A `tfp.distributions.Distribution` object representing a continuous-valued random variable. alpha: Float or tf.Tensor. Controls smoothness of soft round. name: String. A name for this distribution. """ super().__init__(SoftRoundAdapter(base, alpha), name=name) class NoisySoftRoundedNormal(NoisySoftRoundAdapter): """Soft rounded normal distribution + uniform noise.""" class NoisySoftRoundedDeepFactorized(NoisySoftRoundAdapter): """Soft rounded deep factorized distribution + uniform noise."""
[ 2, 15069, 12131, 3012, 11419, 13, 1439, 6923, 33876, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, ...
3.151857
1,508
from django.views import generic class JalQuerySetView(generic.ListView): """View mixin to render a JSON response for Select2.""" def render_to_response(self, context): """Return a JSON response in Select2 format.""" return 'hello !'
[ 198, 6738, 42625, 14208, 13, 33571, 1330, 14276, 628, 198, 4871, 28649, 20746, 7248, 7680, 7, 41357, 13, 8053, 7680, 2599, 198, 220, 220, 220, 37227, 7680, 5022, 259, 284, 8543, 257, 19449, 2882, 329, 9683, 17, 526, 15931, 628, 220, 2...
3.011494
87
__author__ = 'Devesh Bajpai' ''' https://codeforces.com/problemset/problem/1167/A Solution: From the first occurrence of 8 in the given string s, we should have at least 10 characters. Say that 8 exists on ith index. Then n - 1 - i + 1 = n - i would give the length of the longest string starting with 8. That should be at least 11 characters. The extra ones (>11) can be deleted by the operations. ''' if __name__ == "__main__": t = int(raw_input()) for _ in xrange(0, t): n = int(raw_input()) s = raw_input() print solve(n, s)
[ 834, 9800, 834, 796, 705, 5005, 1158, 71, 347, 1228, 49712, 6, 198, 198, 7061, 6, 198, 5450, 1378, 19815, 891, 273, 728, 13, 785, 14, 1676, 22143, 316, 14, 45573, 14, 1157, 3134, 14, 32, 198, 198, 46344, 25, 3574, 262, 717, 19810,...
2.784314
204
# Copyright 2014 Hewlett-Packard Development Company, L.P. # # Author: Kiall Mac Innes <kiall@hpe.com> # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from sqlalchemy import MetaData, Table from migrate.changeset.constraint import ForeignKeyConstraint meta = MetaData()
[ 2, 15069, 1946, 30446, 15503, 12, 11869, 446, 7712, 5834, 11, 406, 13, 47, 13, 198, 2, 198, 2, 6434, 25, 21927, 439, 4100, 554, 2516, 1279, 4106, 439, 31, 71, 431, 13, 785, 29, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, ...
3.624413
213
# Generated by Django 4.0 on 2022-03-08 23:22 from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 604, 13, 15, 319, 33160, 12, 3070, 12, 2919, 2242, 25, 1828, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
2.966667
30
from __future__ import print_function import fileinput import asyncio asyncLib = asyncio.__file__ lineNum = 0 # This script is used to address an issue on Windows with asyncio in the Tornado web server. # See links below for more information # https://github.com/tornadoweb/tornado/issues/2608 # https://www.tornadoweb.org/en/stable/releases/v6.0.4.html#general-changes # https://bugs.python.org/issue37373 with open(asyncLib, 'r+') as origLib: lines = origLib.readlines() for line in lines: lineNum += 1 if line.startswith('import sys'): print('Found 1.') print(line, end='') importLine = lineNum elif line.startswith(' from .windows_events import'): print('Found 2.') print(line, end='') asyncLine = lineNum if importLine is not None and asyncLine is not None: origLib = fileinput.input(asyncLib, inplace = True) for n, line in enumerate(origLib, start=1): if n == importLine: print('import asyncio') if n == asyncLine + 1: print(' asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())') print(line, end='')
[ 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 11748, 2393, 15414, 198, 11748, 30351, 952, 198, 198, 292, 13361, 25835, 796, 30351, 952, 13, 834, 7753, 834, 198, 1370, 33111, 796, 657, 198, 198, 2, 770, 4226, 318, 973, 284, 2209,...
2.434959
492
from collections import Counter
[ 6738, 17268, 1330, 15034, 198, 220, 220, 220, 220 ]
4
9
import sys import numpy ensg_gene = open(sys.argv[1], 'r') abun_file = open(sys.argv[2], 'r') output_file = open(sys.argv[3],'w') #set up ensg dict ensg_dict = {} gene_dict = {} gene_list = [] for line in ensg_gene: ensg, gene = line.strip().split() ensg_dict[ ensg ] = gene if gene not in gene_dict: gene_dict[gene] = [ ensg, 0 ] else: gene_dict[gene][0] += ','+ensg if gene not in gene_list: gene_list.append(gene) ensg_gene.close() #add abundances to ensg_dict abun_file.readline() #skip first line for line in abun_file: ensg = line.strip().split()[0].split('_')[0] tpm = float(line.strip().split()[4]) if ensg in ensg_dict: gene = ensg_dict[ ensg ] gene_dict[gene][1] += tpm abun_file.close() #convert gene level tpm to log10(tpm+1) for gene in gene_dict.keys(): gene_dict[gene].append( numpy.log10(gene_dict[gene][1] + 1) ) #print output file output_file.write( '\t'.join( ['ensg', 'gene', 'tpm','log10tpm'] ) + '\n') for gene in gene_list: output_file.write( '\t'.join( [ gene_dict[gene][0], gene, str(gene_dict[gene][1]), str(gene_dict[gene][2]) ] )+ '\n') output_file.close()
[ 11748, 25064, 198, 11748, 299, 32152, 198, 198, 641, 70, 62, 70, 1734, 796, 1280, 7, 17597, 13, 853, 85, 58, 16, 4357, 705, 81, 11537, 198, 397, 403, 62, 7753, 796, 1280, 7, 17597, 13, 853, 85, 58, 17, 4357, 705, 81, 11537, 198,...
2.255489
501
# coding: utf-8 # /*########################################################################## # Copyright (C) 2021 European Synchrotron Radiation Facility # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # # ############################################################################*/ """Test silx.io.convert.write_to_h5""" import h5py import numpy from silx.io import spech5 from silx.io.convert import write_to_h5 from silx.io.dictdump import h5todict from silx.io import commonh5 from silx.io.spech5 import SpecH5 def test_with_commonh5(tmp_path): """Test write_to_h5 with commonh5 input""" fobj = commonh5.File("filename.txt", mode="w") group = fobj.create_group("group") dataset = group.create_dataset("dataset", data=numpy.array(50)) group["soft_link"] = dataset # Create softlink output_filepath = tmp_path / "output.h5" write_to_h5(fobj, str(output_filepath)) assert h5todict(str(output_filepath)) == { 'group': {'dataset': numpy.array(50), 'soft_link': numpy.array(50)}, } with h5py.File(output_filepath, mode="r") as h5file: soft_link = h5file.get("/group/soft_link", getlink=True) assert isinstance(soft_link, h5py.SoftLink) assert soft_link.path == "/group/dataset" def test_with_hdf5(tmp_path): """Test write_to_h5 with HDF5 file input""" filepath = tmp_path / "base.h5" with h5py.File(filepath, mode="w") as h5file: h5file["group/dataset"] = 50 h5file["group/soft_link"] = h5py.SoftLink("/group/dataset") h5file["group/external_link"] = h5py.ExternalLink("base.h5", "/group/dataset") output_filepath = tmp_path / "output.h5" write_to_h5(str(filepath), str(output_filepath)) assert h5todict(str(output_filepath)) == { 'group': {'dataset': 50, 'soft_link': 50}, } with h5py.File(output_filepath, mode="r") as h5file: soft_link = h5file.get("group/soft_link", getlink=True) assert isinstance(soft_link, h5py.SoftLink) assert soft_link.path == "/group/dataset" def test_with_spech5(tmp_path): """Test write_to_h5 with SpecH5 input""" filepath = tmp_path / "file.spec" filepath.write_bytes( bytes( """#F /tmp/sf.dat #S 1 cmd #L a b 1 2 """, encoding='ascii') ) output_filepath = tmp_path / "output.h5" with spech5.SpecH5(str(filepath)) as spech5file: write_to_h5(spech5file, str(output_filepath)) print(h5todict(str(output_filepath))) assert_equal(h5todict(str(output_filepath)), { '1.1': { 'instrument': { 'positioners': {}, 'specfile': { 'file_header': ['#F /tmp/sf.dat'], 'scan_header': ['#S 1 cmd', '#L a b'], }, }, 'measurement': { 'a': [1.], 'b': [2.], }, 'start_time': '', 'title': 'cmd', }, })
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 2, 11900, 29113, 29113, 7804, 2235, 198, 2, 15069, 357, 34, 8, 33448, 3427, 16065, 354, 10599, 1313, 47532, 29118, 198, 2, 198, 2, 2448, 3411, 318, 29376, 7520, 11, 1479, 286, 3877, 11, 284, 59...
2.462446
1,611
import pygame import os import time import random import requests from rx import Observable, Observer from rx.concurrency import ThreadPoolScheduler from waffles_feels import waffles_feels from waffles_commands import WafflesCMD from waffles_pos import five_second_timer print('0') #Updates the actual displayed image based on waffle's reported emotional state. #Helper method for retrieving images _image_library = {} #starting the display print('0') pygame.init() screen = pygame.display.set_mode((400, 300)) done = False clock = pygame.time.Clock() CMD = WafflesCMD() print('1') #Creates an observable that publishes the same stream to multiple observers emote_gen = Observable.create(waffles_feels).publish() print('2') #The display subscriber disp = emote_gen.subscribe(UpdateDisplay) print('3') #The serial communication subscriber pool_sch = ThreadPoolScheduler() pos_gen = Observable.create(five_second_timer).subscribe_on(pool_sch) emote_and_turn = Observable.merge(emote_gen, pos_gen) print('q') cmd = emote_and_turn.subscribe(CMD) print('4') emote_gen.connect() emote_and_turn.connect() print('5')
[ 11748, 12972, 6057, 198, 11748, 28686, 198, 11748, 640, 198, 11748, 4738, 198, 11748, 7007, 198, 6738, 374, 87, 1330, 19243, 540, 11, 27058, 198, 6738, 374, 87, 13, 1102, 34415, 1330, 14122, 27201, 50, 1740, 18173, 628, 198, 6738, 266, ...
3.125
360
################################################################################## ##########--this is an autogenerated python model definition for proDEX--######### ##--original file: Family_Assessment_v05_forprodex.dxi --## ################################################################################## from .lib.proDEX import * situ_social_activity_family = Node() Relative_activity_Family = Node() calls_last_7_days = Node() visits_last_7_days = Node() together_outside_last_7_days = Node() Absolute_daily_activity_Family = Node() feat_calls_count_family_relative = Atrib() feat_calls_duration_family_relative = Atrib() feat_visits_family_relative_past_week = Atrib() feat_visits_family_relative = Atrib() feat_outside_family_relative_past_week = Atrib() feat_outside_family_relative = Atrib() feat_calls_count_family_weekly_vs_goal = Atrib() feat_visits_count_family_weekly_vs_goal = Atrib() feat_outside_count_family_weekly_vs_goal = Atrib() situ_social_activity_family.setName('situ_social_activity_family') Relative_activity_Family.setName('Relative_activity_Family') calls_last_7_days.setName('calls_last_7_days') visits_last_7_days.setName('visits_last_7_days') together_outside_last_7_days.setName('together_outside_last_7_days') Absolute_daily_activity_Family.setName('Absolute_daily_activity_Family') feat_calls_count_family_relative.setName('feat_calls_count_family_relative') feat_calls_duration_family_relative.setName('feat_calls_duration_family_relative') feat_visits_family_relative_past_week.setName('feat_visits_family_relative_past_week') feat_visits_family_relative.setName('feat_visits_family_relative') feat_outside_family_relative_past_week.setName('feat_outside_family_relative_past_week') feat_outside_family_relative.setName('feat_outside_family_relative') feat_calls_count_family_weekly_vs_goal.setName('feat_calls_count_family_weekly_vs_goal') feat_visits_count_family_weekly_vs_goal.setName('feat_visits_count_family_weekly_vs_goal') feat_outside_count_family_weekly_vs_goal.setName('feat_outside_count_family_weekly_vs_goal') situ_social_activity_family.setValues(['very_low', 'low', 'medium', 'high', 'very_high']) Relative_activity_Family.setValues(['high decrease', 'decrease', 'stable', 'increase', 'high increase']) calls_last_7_days.setValues(['decrease', 'stable', 'increase']) visits_last_7_days.setValues(['decrease', 'stable', 'increase']) together_outside_last_7_days.setValues(['decrease', 'stable', 'increase']) Absolute_daily_activity_Family.setValues(['very low', 'low', 'medium', 'high', 'very high']) feat_calls_count_family_relative.setValues(['decrease', 'stable', 'increase']) feat_calls_duration_family_relative.setValues(['decrease', 'stable', 'increase']) feat_visits_family_relative_past_week.setValues(['decrease', 'stable', 'increase']) feat_visits_family_relative.setValues(['decrease', 'stable', 'increase']) feat_outside_family_relative_past_week.setValues(['decrease', 'stable', 'increase']) feat_outside_family_relative.setValues(['decrease', 'stable', 'increase']) feat_calls_count_family_weekly_vs_goal.setValues(['low', 'medium', 'high']) feat_visits_count_family_weekly_vs_goal.setValues(['low', 'medium', 'high']) feat_outside_count_family_weekly_vs_goal.setValues(['low', 'medium', 'high']) situ_social_activity_family.addChild(Relative_activity_Family) Relative_activity_Family.setParent(situ_social_activity_family) situ_social_activity_family.addChild(Absolute_daily_activity_Family) Absolute_daily_activity_Family.setParent(situ_social_activity_family) Relative_activity_Family.addChild(calls_last_7_days) calls_last_7_days.setParent(Relative_activity_Family) Relative_activity_Family.addChild(visits_last_7_days) visits_last_7_days.setParent(Relative_activity_Family) Relative_activity_Family.addChild(together_outside_last_7_days) together_outside_last_7_days.setParent(Relative_activity_Family) calls_last_7_days.addChild(feat_calls_count_family_relative) feat_calls_count_family_relative.setParent(calls_last_7_days) calls_last_7_days.addChild(feat_calls_duration_family_relative) feat_calls_duration_family_relative.setParent(calls_last_7_days) visits_last_7_days.addChild(feat_visits_family_relative_past_week) feat_visits_family_relative_past_week.setParent(visits_last_7_days) visits_last_7_days.addChild(feat_visits_family_relative) feat_visits_family_relative.setParent(visits_last_7_days) together_outside_last_7_days.addChild(feat_outside_family_relative_past_week) feat_outside_family_relative_past_week.setParent(together_outside_last_7_days) together_outside_last_7_days.addChild(feat_outside_family_relative) feat_outside_family_relative.setParent(together_outside_last_7_days) Absolute_daily_activity_Family.addChild(feat_calls_count_family_weekly_vs_goal) feat_calls_count_family_weekly_vs_goal.setParent(Absolute_daily_activity_Family) Absolute_daily_activity_Family.addChild(feat_visits_count_family_weekly_vs_goal) feat_visits_count_family_weekly_vs_goal.setParent(Absolute_daily_activity_Family) Absolute_daily_activity_Family.addChild(feat_outside_count_family_weekly_vs_goal) feat_outside_count_family_weekly_vs_goal.setParent(Absolute_daily_activity_Family) situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'high decrease', Absolute_daily_activity_Family:'very low'}, 'very_low']) situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'high decrease', Absolute_daily_activity_Family:'low'}, 'very_low']) situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'high decrease', Absolute_daily_activity_Family:'medium'}, 'low']) situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'high decrease', Absolute_daily_activity_Family:'high'}, 'medium']) situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'high decrease', Absolute_daily_activity_Family:'very high'}, 'high']) situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'decrease', Absolute_daily_activity_Family:'very low'}, 'very_low']) situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'decrease', Absolute_daily_activity_Family:'low'}, 'low']) situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'decrease', Absolute_daily_activity_Family:'medium'}, 'medium']) situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'decrease', Absolute_daily_activity_Family:'high'}, 'high']) situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'decrease', Absolute_daily_activity_Family:'very high'}, 'very_high']) situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'stable', Absolute_daily_activity_Family:'very low'}, 'very_low']) situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'stable', Absolute_daily_activity_Family:'low'}, 'low']) situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'stable', Absolute_daily_activity_Family:'medium'}, 'medium']) situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'stable', Absolute_daily_activity_Family:'high'}, 'high']) situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'stable', Absolute_daily_activity_Family:'very high'}, 'very_high']) situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'increase', Absolute_daily_activity_Family:'very low'}, 'very_low']) situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'increase', Absolute_daily_activity_Family:'low'}, 'low']) situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'increase', Absolute_daily_activity_Family:'medium'}, 'medium']) situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'increase', Absolute_daily_activity_Family:'high'}, 'high']) situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'increase', Absolute_daily_activity_Family:'very high'}, 'very_high']) situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'high increase', Absolute_daily_activity_Family:'very low'}, 'low']) situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'high increase', Absolute_daily_activity_Family:'low'}, 'medium']) situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'high increase', Absolute_daily_activity_Family:'medium'}, 'high']) situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'high increase', Absolute_daily_activity_Family:'high'}, 'very_high']) situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'high increase', Absolute_daily_activity_Family:'very high'}, 'very_high']) Relative_activity_Family.addFunctionRow([{calls_last_7_days:'decrease', visits_last_7_days:'decrease', together_outside_last_7_days:'decrease'}, 'high decrease']) Relative_activity_Family.addFunctionRow([{calls_last_7_days:'decrease', visits_last_7_days:'decrease', together_outside_last_7_days:'stable'}, 'high decrease']) Relative_activity_Family.addFunctionRow([{calls_last_7_days:'decrease', visits_last_7_days:'decrease', together_outside_last_7_days:'increase'}, 'decrease']) Relative_activity_Family.addFunctionRow([{calls_last_7_days:'decrease', visits_last_7_days:'stable', together_outside_last_7_days:'decrease'}, 'high decrease']) Relative_activity_Family.addFunctionRow([{calls_last_7_days:'decrease', visits_last_7_days:'stable', together_outside_last_7_days:'stable'}, 'decrease']) Relative_activity_Family.addFunctionRow([{calls_last_7_days:'decrease', visits_last_7_days:'stable', together_outside_last_7_days:'increase'}, 'stable']) Relative_activity_Family.addFunctionRow([{calls_last_7_days:'decrease', visits_last_7_days:'increase', together_outside_last_7_days:'decrease'}, 'decrease']) Relative_activity_Family.addFunctionRow([{calls_last_7_days:'decrease', visits_last_7_days:'increase', together_outside_last_7_days:'stable'}, 'stable']) Relative_activity_Family.addFunctionRow([{calls_last_7_days:'decrease', visits_last_7_days:'increase', together_outside_last_7_days:'increase'}, 'increase']) Relative_activity_Family.addFunctionRow([{calls_last_7_days:'stable', visits_last_7_days:'decrease', together_outside_last_7_days:'decrease'}, 'high decrease']) Relative_activity_Family.addFunctionRow([{calls_last_7_days:'stable', visits_last_7_days:'decrease', together_outside_last_7_days:'stable'}, 'decrease']) Relative_activity_Family.addFunctionRow([{calls_last_7_days:'stable', visits_last_7_days:'decrease', together_outside_last_7_days:'increase'}, 'stable']) Relative_activity_Family.addFunctionRow([{calls_last_7_days:'stable', visits_last_7_days:'stable', together_outside_last_7_days:'decrease'}, 'decrease']) Relative_activity_Family.addFunctionRow([{calls_last_7_days:'stable', visits_last_7_days:'stable', together_outside_last_7_days:'stable'}, 'stable']) Relative_activity_Family.addFunctionRow([{calls_last_7_days:'stable', visits_last_7_days:'stable', together_outside_last_7_days:'increase'}, 'increase']) Relative_activity_Family.addFunctionRow([{calls_last_7_days:'stable', visits_last_7_days:'increase', together_outside_last_7_days:'decrease'}, 'stable']) Relative_activity_Family.addFunctionRow([{calls_last_7_days:'stable', visits_last_7_days:'increase', together_outside_last_7_days:'stable'}, 'increase']) Relative_activity_Family.addFunctionRow([{calls_last_7_days:'stable', visits_last_7_days:'increase', together_outside_last_7_days:'increase'}, 'high increase']) Relative_activity_Family.addFunctionRow([{calls_last_7_days:'increase', visits_last_7_days:'decrease', together_outside_last_7_days:'decrease'}, 'decrease']) Relative_activity_Family.addFunctionRow([{calls_last_7_days:'increase', visits_last_7_days:'decrease', together_outside_last_7_days:'stable'}, 'stable']) Relative_activity_Family.addFunctionRow([{calls_last_7_days:'increase', visits_last_7_days:'decrease', together_outside_last_7_days:'increase'}, 'increase']) Relative_activity_Family.addFunctionRow([{calls_last_7_days:'increase', visits_last_7_days:'stable', together_outside_last_7_days:'decrease'}, 'stable']) Relative_activity_Family.addFunctionRow([{calls_last_7_days:'increase', visits_last_7_days:'stable', together_outside_last_7_days:'stable'}, 'increase']) Relative_activity_Family.addFunctionRow([{calls_last_7_days:'increase', visits_last_7_days:'stable', together_outside_last_7_days:'increase'}, 'high increase']) Relative_activity_Family.addFunctionRow([{calls_last_7_days:'increase', visits_last_7_days:'increase', together_outside_last_7_days:'decrease'}, 'increase']) Relative_activity_Family.addFunctionRow([{calls_last_7_days:'increase', visits_last_7_days:'increase', together_outside_last_7_days:'stable'}, 'high increase']) Relative_activity_Family.addFunctionRow([{calls_last_7_days:'increase', visits_last_7_days:'increase', together_outside_last_7_days:'increase'}, 'high increase']) calls_last_7_days.addFunctionRow([{feat_calls_count_family_relative:'decrease', feat_calls_duration_family_relative:'decrease'}, 'decrease']) calls_last_7_days.addFunctionRow([{feat_calls_count_family_relative:'decrease', feat_calls_duration_family_relative:'stable'}, 'decrease']) calls_last_7_days.addFunctionRow([{feat_calls_count_family_relative:'decrease', feat_calls_duration_family_relative:'increase'}, 'stable']) calls_last_7_days.addFunctionRow([{feat_calls_count_family_relative:'stable', feat_calls_duration_family_relative:'decrease'}, 'decrease']) calls_last_7_days.addFunctionRow([{feat_calls_count_family_relative:'stable', feat_calls_duration_family_relative:'stable'}, 'stable']) calls_last_7_days.addFunctionRow([{feat_calls_count_family_relative:'stable', feat_calls_duration_family_relative:'increase'}, 'increase']) calls_last_7_days.addFunctionRow([{feat_calls_count_family_relative:'increase', feat_calls_duration_family_relative:'decrease'}, 'stable']) calls_last_7_days.addFunctionRow([{feat_calls_count_family_relative:'increase', feat_calls_duration_family_relative:'stable'}, 'increase']) calls_last_7_days.addFunctionRow([{feat_calls_count_family_relative:'increase', feat_calls_duration_family_relative:'increase'}, 'increase']) visits_last_7_days.addFunctionRow([{feat_visits_family_relative_past_week:'decrease', feat_visits_family_relative:'decrease'}, 'decrease']) visits_last_7_days.addFunctionRow([{feat_visits_family_relative_past_week:'decrease', feat_visits_family_relative:'stable'}, 'stable']) visits_last_7_days.addFunctionRow([{feat_visits_family_relative_past_week:'decrease', feat_visits_family_relative:'increase'}, 'increase']) visits_last_7_days.addFunctionRow([{feat_visits_family_relative_past_week:'stable', feat_visits_family_relative:'decrease'}, 'decrease']) visits_last_7_days.addFunctionRow([{feat_visits_family_relative_past_week:'stable', feat_visits_family_relative:'stable'}, 'stable']) visits_last_7_days.addFunctionRow([{feat_visits_family_relative_past_week:'stable', feat_visits_family_relative:'increase'}, 'increase']) visits_last_7_days.addFunctionRow([{feat_visits_family_relative_past_week:'increase', feat_visits_family_relative:'decrease'}, 'decrease']) visits_last_7_days.addFunctionRow([{feat_visits_family_relative_past_week:'increase', feat_visits_family_relative:'stable'}, 'stable']) visits_last_7_days.addFunctionRow([{feat_visits_family_relative_past_week:'increase', feat_visits_family_relative:'increase'}, 'increase']) together_outside_last_7_days.addFunctionRow([{feat_outside_family_relative_past_week:'decrease', feat_outside_family_relative:'decrease'}, 'decrease']) together_outside_last_7_days.addFunctionRow([{feat_outside_family_relative_past_week:'decrease', feat_outside_family_relative:'stable'}, 'decrease']) together_outside_last_7_days.addFunctionRow([{feat_outside_family_relative_past_week:'decrease', feat_outside_family_relative:'increase'}, 'stable']) together_outside_last_7_days.addFunctionRow([{feat_outside_family_relative_past_week:'stable', feat_outside_family_relative:'decrease'}, 'decrease']) together_outside_last_7_days.addFunctionRow([{feat_outside_family_relative_past_week:'stable', feat_outside_family_relative:'stable'}, 'stable']) together_outside_last_7_days.addFunctionRow([{feat_outside_family_relative_past_week:'stable', feat_outside_family_relative:'increase'}, 'increase']) together_outside_last_7_days.addFunctionRow([{feat_outside_family_relative_past_week:'increase', feat_outside_family_relative:'decrease'}, 'decrease']) together_outside_last_7_days.addFunctionRow([{feat_outside_family_relative_past_week:'increase', feat_outside_family_relative:'stable'}, 'stable']) together_outside_last_7_days.addFunctionRow([{feat_outside_family_relative_past_week:'increase', feat_outside_family_relative:'increase'}, 'increase']) Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'low', feat_visits_count_family_weekly_vs_goal:'low', feat_outside_count_family_weekly_vs_goal:'low'}, 'very low']) Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'low', feat_visits_count_family_weekly_vs_goal:'low', feat_outside_count_family_weekly_vs_goal:'medium'}, 'very low']) Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'low', feat_visits_count_family_weekly_vs_goal:'low', feat_outside_count_family_weekly_vs_goal:'high'}, 'low']) Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'low', feat_visits_count_family_weekly_vs_goal:'medium', feat_outside_count_family_weekly_vs_goal:'low'}, 'very low']) Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'low', feat_visits_count_family_weekly_vs_goal:'medium', feat_outside_count_family_weekly_vs_goal:'medium'}, 'low']) Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'low', feat_visits_count_family_weekly_vs_goal:'medium', feat_outside_count_family_weekly_vs_goal:'high'}, 'medium']) Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'low', feat_visits_count_family_weekly_vs_goal:'high', feat_outside_count_family_weekly_vs_goal:'low'}, 'low']) Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'low', feat_visits_count_family_weekly_vs_goal:'high', feat_outside_count_family_weekly_vs_goal:'medium'}, 'medium']) Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'low', feat_visits_count_family_weekly_vs_goal:'high', feat_outside_count_family_weekly_vs_goal:'high'}, 'high']) Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'medium', feat_visits_count_family_weekly_vs_goal:'low', feat_outside_count_family_weekly_vs_goal:'low'}, 'very low']) Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'medium', feat_visits_count_family_weekly_vs_goal:'low', feat_outside_count_family_weekly_vs_goal:'medium'}, 'low']) Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'medium', feat_visits_count_family_weekly_vs_goal:'low', feat_outside_count_family_weekly_vs_goal:'high'}, 'medium']) Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'medium', feat_visits_count_family_weekly_vs_goal:'medium', feat_outside_count_family_weekly_vs_goal:'low'}, 'low']) Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'medium', feat_visits_count_family_weekly_vs_goal:'medium', feat_outside_count_family_weekly_vs_goal:'medium'}, 'medium']) Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'medium', feat_visits_count_family_weekly_vs_goal:'medium', feat_outside_count_family_weekly_vs_goal:'high'}, 'high']) Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'medium', feat_visits_count_family_weekly_vs_goal:'high', feat_outside_count_family_weekly_vs_goal:'low'}, 'medium']) Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'medium', feat_visits_count_family_weekly_vs_goal:'high', feat_outside_count_family_weekly_vs_goal:'medium'}, 'high']) Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'medium', feat_visits_count_family_weekly_vs_goal:'high', feat_outside_count_family_weekly_vs_goal:'high'}, 'very high']) Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'high', feat_visits_count_family_weekly_vs_goal:'low', feat_outside_count_family_weekly_vs_goal:'low'}, 'low']) Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'high', feat_visits_count_family_weekly_vs_goal:'low', feat_outside_count_family_weekly_vs_goal:'medium'}, 'medium']) Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'high', feat_visits_count_family_weekly_vs_goal:'low', feat_outside_count_family_weekly_vs_goal:'high'}, 'high']) Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'high', feat_visits_count_family_weekly_vs_goal:'medium', feat_outside_count_family_weekly_vs_goal:'low'}, 'medium']) Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'high', feat_visits_count_family_weekly_vs_goal:'medium', feat_outside_count_family_weekly_vs_goal:'medium'}, 'high']) Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'high', feat_visits_count_family_weekly_vs_goal:'medium', feat_outside_count_family_weekly_vs_goal:'high'}, 'very high']) Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'high', feat_visits_count_family_weekly_vs_goal:'high', feat_outside_count_family_weekly_vs_goal:'low'}, 'high']) Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'high', feat_visits_count_family_weekly_vs_goal:'high', feat_outside_count_family_weekly_vs_goal:'medium'}, 'very high']) Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'high', feat_visits_count_family_weekly_vs_goal:'high', feat_outside_count_family_weekly_vs_goal:'high'}, 'very high'])
[ 29113, 29113, 14468, 2235, 198, 7804, 2235, 438, 5661, 318, 281, 1960, 519, 877, 515, 21015, 2746, 6770, 329, 386, 35, 6369, 438, 7804, 2, 198, 2235, 438, 14986, 2393, 25, 7884, 62, 8021, 21687, 62, 85, 2713, 62, 1640, 1676, 67, 106...
2.965936
7,486
if __name__ == "__main__": s = MinStack() s.add(5) s.add(-3) s.add(1) s.add(6) s.add(-1) print(s.pop()) print(s.get_min()) s.add(-10) s.pop()
[ 628, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 264, 796, 1855, 25896, 3419, 198, 220, 220, 220, 264, 13, 2860, 7, 20, 8, 198, 220, 220, 220, 264, 13, 2860, 32590, 18, 8, 198, 220, 220...
1.646018
113
# -------------- import numpy as np import pandas as pd from sklearn.model_selection import train_test_split # path- variable storing file path df = pd.read_csv(path) df.columns[range(5)] X = df.drop(['Price'], axis = 1) y= df.Price X_train,X_test,y_train,y_test = train_test_split(X , y , test_size = 0.3, random_state = 6) corr = X_train.corr(method = 'pearson') print(corr) #Code starts here # -------------- from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_squared_error, r2_score from math import sqrt regressor = LinearRegression() regressor.fit(X_train, y_train) y_pred = regressor.predict(X_test) mse = (mean_squared_error(y_test, y_pred)) print(mse) r2 = r2_score (y_test, y_pred) # Code starts here # -------------- from sklearn.linear_model import Lasso # Code starts here lasso = Lasso() lasso.fit(X_train, y_train) lasso_pred = lasso.predict(X_test) r2_lasso = r2_score(y_test, y_pred) print(r2_lasso) # -------------- from sklearn.linear_model import Ridge # Code starts here ridge = Ridge() ridge.fit(X_train, y_train) ridge_pred = ridge.predict(X_test) r2_ridge = r2_score(y_test , y_pred) print(r2_ridge) # Code ends here # -------------- from sklearn.model_selection import cross_val_score #Code starts here score = cross_val_score(regressor, X_train, y_train, cv= 10) mean_score = np.mean(score) print(mean_score) # -------------- from sklearn.preprocessing import PolynomialFeatures from sklearn.pipeline import make_pipeline #Code starts here model = make_pipeline(PolynomialFeatures(2), LinearRegression()) model.fit(X_train , y_train) y_pred = model.predict(X_test) r2_poly = r2_score(y_test , y_pred) print(r2_poly)
[ 2, 220, 26171, 198, 11748, 299, 32152, 355, 45941, 201, 198, 11748, 19798, 292, 355, 279, 67, 201, 198, 6738, 1341, 35720, 13, 19849, 62, 49283, 1330, 4512, 62, 9288, 62, 35312, 201, 198, 201, 198, 2, 3108, 12, 7885, 23069, 2393, 31...
2.521552
696
import numpy as np import parl from parl.utils import logger from parl.utils import action_mapping # 将神经网络输出映射到对应的 实际动作取值范围 内 from parl.utils import ReplayMemory # 经验回放 from rlschool import make_env # 使用 RLSchool 创建飞行器环境 from parl.algorithms import DDPG import paddle.fluid as fluid import parl from parl import layers GAMMA = 0.99 # reward 的衰减因子,一般取 0.9 到 0.999 不等 TAU = 0.001 # target_model 跟 model 同步参数 的 软更新参数 ACTOR_LR = 0.0002 # Actor网络更新的 learning rate CRITIC_LR = 0.001 # Critic网络更新的 learning rate MEMORY_SIZE = 1e6 # replay memory的大小,越大越占用内存 MEMORY_WARMUP_SIZE = 1e4 # replay_memory 里需要预存一些经验数据,再从里面sample一个batch的经验让agent去learn REWARD_SCALE = 0.01 # reward 的缩放因子 BATCH_SIZE = 256 # 每次给agent learn的数据数量,从replay memory随机里sample一批数据出来 TRAIN_TOTAL_STEPS = 1e6 # 总训练步数 TEST_EVERY_STEPS = 1e4 # 每个N步评估一下算法效果,每次评估5个episode求平均reward # 评估 agent, 跑 5 个episode,总reward求平均 # 创建飞行器环境 env = make_env("Quadrotor", task="velocity_control", seed=0) env.reset() obs_dim = env.observation_space.shape[ 0 ] act_dim = 5 # 使用parl框架搭建Agent:QuadrotorModel, DDPG, QuadrotorAgent三者嵌套 model = QuadrotorModel(act_dim) algorithm = DDPG( model, gamma=GAMMA, tau=TAU, actor_lr=ACTOR_LR, critic_lr=CRITIC_LR) agent = QuadrotorAgent(algorithm, obs_dim, act_dim) # 加载模型 # save_path = 'model_dir_3/steps_1000000.ckpt' # agent.restore(save_path) # parl库也为DDPG算法内置了ReplayMemory,可直接从 parl.utils 引入使用 rpm = ReplayMemory(int(MEMORY_SIZE), obs_dim, act_dim) test_flag = 0 total_steps = 0 testing = 1 if (not testing): while total_steps < TRAIN_TOTAL_STEPS: train_reward, steps = run_episode(env, agent, rpm) total_steps += steps # logger.info('Steps: {} Reward: {}'.format(total_steps, train_reward)) if total_steps // TEST_EVERY_STEPS >= test_flag: while total_steps // TEST_EVERY_STEPS >= test_flag: test_flag += 1 evaluate_reward = evaluate(env, agent) logger.info('Steps {}, Test reward: {}'.format(total_steps, evaluate_reward)) # 保存模型 ckpt = 'model_dir_1/steps_{}.ckpt'.format(total_steps) agent.save(ckpt) else: # 加载模型 save_path = 'steps_1000000.ckpt' agent.restore(save_path) evaluate_reward = evaluate(env, agent, render=True) logger.info('Test reward: {}'.format(evaluate_reward))
[ 11748, 299, 32152, 355, 45941, 198, 11748, 1582, 75, 198, 6738, 1582, 75, 13, 26791, 1330, 49706, 198, 6738, 1582, 75, 13, 26791, 1330, 2223, 62, 76, 5912, 220, 1303, 10263, 108, 228, 15351, 163, 119, 237, 163, 121, 239, 163, 119, 2...
1.68042
1,430
# -*- coding: utf-8 -*- import redis import logging try: import simplejson as json except ImportError: import json _logger = logging.getLogger(__name__)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 2266, 271, 198, 11748, 18931, 198, 28311, 25, 198, 220, 220, 220, 1330, 2829, 17752, 355, 33918, 198, 16341, 17267, 12331, 25, 198, 220, 220, 220, 1330, 33918, 19...
2.584615
65
import os import pickle import numpy as np from tqdm import tqdm from argparse import ArgumentParser import optuna optuna.logging.set_verbosity ( optuna.logging.ERROR ) # silence Optuna during trials study import warnings warnings.filterwarnings ( "ignore", category = RuntimeWarning ) from sklearn.model_selection import StratifiedShuffleSplit from sklearn.preprocessing import MinMaxScaler from imblearn.over_sampling import SMOTE from sklearn.linear_model import LogisticRegression from sklearn.svm import SVC from sklearn.gaussian_process import GaussianProcessClassifier from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier from sklearn.feature_selection import RFECV from sklearn.metrics import roc_auc_score, confusion_matrix, roc_curve from utils import custom_predictions, multiclass_predictions, plot_conf_matrices, plot_multi_prf_histos LABELS = ["cHL", "GZL", "PMBCL"] # +-------------------+ # | Options setup | # +-------------------+ MODELS = [ "log-reg", "lin-svm", "gaus-proc", "rnd-frs", "grad-bdt" ] parser = ArgumentParser ( description = "training script" ) parser . add_argument ( "-m" , "--model" , required = True , choices = MODELS ) parser . add_argument ( "-s" , "--split" , default = "50/30/20" ) parser . add_argument ( "-t" , "--threshold" , default = "rec90" ) args = parser . parse_args() if len ( args.split.split("/") ) == 2: test_size = 0.5 * float(args.split.split("/")[-1]) / 100 val_size = test_size val_size /= ( 1 - test_size ) # w.r.t. new dataset size elif len ( args.split.split("/") ) == 3: test_size = float(args.split.split("/")[2]) / 100 val_size = float(args.split.split("/")[1]) / 100 val_size /= ( 1 - test_size ) # w.r.t. new dataset size else: raise ValueError (f"The splitting ratios should be passed as 'XX/YY/ZZ', where XX% is " f"the percentage of data used for training, while YY% and ZZ% are " f"the ones used for validation and testing respectively.") if "rec" in args.threshold: rec_score = float(args.threshold.split("rec")[-1]) / 100 prec_score = None elif "prec" in args.threshold: rec_score = None prec_score = float(args.threshold.split("prec")[-1]) / 100 else: raise ValueError (f"The rule for custom predictions should be passed as 'recXX' where " f"XX% is the minimum recall score required, or as 'precYY' where YY% " f"is the minimum precision score required.") # +------------------+ # | Data loading | # +------------------+ data_dir = "./data" data_file = "db_mediastinalbulky_reduced.pkl" file_path = os.path.join ( data_dir, data_file ) with open (file_path, "rb") as file: data = pickle.load (file) # +------------------------------+ # | Input/output preparation | # +------------------------------+ cols = list ( data.columns ) X_cols = cols[2:] y_cols = "lymphoma_type" X = data.query("lymphoma_type != 2")[X_cols] . to_numpy() y = data.query("lymphoma_type != 2")[y_cols] . to_numpy() . flatten() y = ( y == 3 ) # PMBCL/cHL classification X_gz = data.query("lymphoma_type == 2")[X_cols] . to_numpy() y_gz = data.query("lymphoma_type == 2")[y_cols] . to_numpy() . flatten() # +------------------------+ # | Sub-sample studies | # +------------------------+ conf_matrices = [ list() , list() , list() ] # container for confusion matrices recalls = [ list() , list() , list() ] # container for recalls precisions = [ list() , list() , list() ] # container for precisions roc_curves = [ list() , list() ] # container for ROC curve variables ## initial control values optimized = False append_to_roc = [ True , True ] n_roc_points = [ -1 , -1 ] for i in tqdm(range(250)): # +--------------------------+ # | Train/test splitting | # +--------------------------+ sss = StratifiedShuffleSplit ( n_splits = 1, test_size = test_size ) for idx_train, idx_test in sss . split ( X, y ): X_train , y_train = X[idx_train] , y[idx_train] X_test , y_test = X[idx_test] , y[idx_test] # +------------------------+ # | Data preprocessing | # +------------------------+ scaler_train = MinMaxScaler() X_train = scaler_train.fit_transform (X_train) scaler_test = MinMaxScaler() X_test = scaler_test.fit_transform (X_test) scaler_gz = MinMaxScaler() X_gz = scaler_gz.fit_transform (X_gz) # +------------------+ # | Optuna setup | # +------------------+ # +------------------------------+ # | Hyperparams optimization | # +------------------------------+ ## LOGISTIC REGRESSION if args.model == "log-reg": best_model = LogisticRegression() ## LINEAR SVM elif args.model == "lin-svm": best_model = SVC ( kernel = "linear", probability = True ) ## GAUSSIAN PROCESS elif args.model == "gaus-proc": best_model = GaussianProcessClassifier() ## RANDOM FOREST elif args.model == "rnd-frs": if not optimized: study = optuna_study ( model_name = "rnd_forest_clf" , storage_dir = "./storage" , objective = objective , n_trials = 50 , direction = "maximize" , load_if_exists = False ) optimized = True best_model = RandomForestClassifier ( n_estimators = study.best_params["n_estims"] , max_depth = study.best_params["max_depth"] ) ## GRADIENT BDT elif args.model == "grad-bdt": if not optimized: study = optuna_study ( model_name = "grad_bdt_clf" , storage_dir = "./storage" , objective = objective , n_trials = 50 , direction = "maximize" , load_if_exists = False ) optimized = True best_model = GradientBoostingClassifier ( learning_rate = study.best_params["learn_rate"] , n_estimators = study.best_params["n_estims"] , max_depth = study.best_params["max_depth"] ) # +---------------------------+ # | Multiclass boundaries | # +---------------------------+ # +-----------------------------------------+ # | Model performance on train/test set | # +-----------------------------------------+ ## train/val splitting sss = StratifiedShuffleSplit ( n_splits = 1, test_size = val_size ) for idx_trn, idx_val in sss . split ( X_train, y_train ): X_trn , y_trn = X_train[idx_trn] , y_train[idx_trn] X_val , y_val = X_train[idx_val] , y_train[idx_val] sm = SMOTE() # oversampling technique X_trn_res, y_trn_res = sm.fit_resample ( X_trn , y_trn ) ## combine the datasets X_trn_comb = np.concatenate ( [ X_trn, X_gz ] ) y_trn_comb = np.concatenate ( [ np.where(y_trn, 3, 1), y_gz ] ) X_val_comb = np.concatenate ( [ X_val, X_gz ] ) y_val_comb = np.concatenate ( [ np.where(y_val, 3, 1), y_gz ] ) X_test_comb = np.concatenate ( [ X_test, X_gz ] ) y_test_comb = np.concatenate ( [ np.where(y_test, 3, 1), y_gz ] ) X_eval_comb = np.concatenate ( [ X_val, X_test, X_gz ] ) y_eval_comb = np.concatenate ( [ np.where(y_val, 3, 1) , np.where(y_test, 3, 1), y_gz ] ) ## model training best_model . fit (X_trn_res, y_trn_res) ## model predictions y_scores_trn = best_model.predict_proba ( X_trn ) _, threshold = custom_predictions ( y_true = y_trn , y_scores = y_scores_trn , recall_score = rec_score , precision_score = prec_score ) y_scores_trn_comb = best_model.predict_proba ( X_trn_comb ) y_pred_trn = multiclass_predictions ( y_true = y_trn_comb , y_scores = y_scores_trn_comb , boundaries = get_decision_boundaries ( y_scores_trn, threshold, len(y_gz) / len(y_trn_comb) ) ) # pred for the true train-set y_scores_val_comb = best_model.predict_proba ( X_val_comb ) y_pred_val = multiclass_predictions ( y_true = y_val_comb , y_scores = y_scores_val_comb , boundaries = get_decision_boundaries ( y_scores_trn, threshold, len(y_gz) / len(y_trn_comb) ) ) # pred for the val-set y_scores_test_comb = best_model.predict_proba ( X_test_comb ) y_pred_test = multiclass_predictions ( y_true = y_test_comb , y_scores = y_scores_test_comb , boundaries = get_decision_boundaries ( y_scores_trn, threshold, len(y_gz) / len(y_trn_comb) ) ) # pred for the test-set y_scores_eval_comb = best_model.predict_proba ( X_eval_comb ) y_pred_eval = multiclass_predictions ( y_true = y_eval_comb , y_scores = y_scores_eval_comb , boundaries = get_decision_boundaries ( y_scores_trn, threshold, len(y_gz) / len(y_trn_comb) ) ) # pred for the val-set + test-set ## model performances conf_matrix_trn = confusion_matrix ( y_trn_comb, y_pred_trn ) recall_2 = conf_matrix_trn[2,2] / np.sum ( conf_matrix_trn[2,:] ) recall_1 = conf_matrix_trn[1,1] / np.sum ( conf_matrix_trn[1,:] ) precision_2 = conf_matrix_trn[2,2] / np.sum ( conf_matrix_trn[:,2] ) precision_1 = conf_matrix_trn[1,1] / np.sum ( conf_matrix_trn[:,1] ) conf_matrices[0] . append ( conf_matrix_trn ) # add to the relative container recalls[0] . append ( [recall_2, recall_1] ) # add to the relative container precisions[0] . append ( [precision_2, precision_1] ) # add to the relative container conf_matrix_val = confusion_matrix ( y_val_comb, y_pred_val ) recall_2 = conf_matrix_val[2,2] / np.sum ( conf_matrix_val[2,:] ) recall_1 = conf_matrix_val[1,1] / np.sum ( conf_matrix_val[1,:] ) precision_2 = conf_matrix_val[2,2] / np.sum ( conf_matrix_val[:,2] ) precision_1 = conf_matrix_val[1,1] / np.sum ( conf_matrix_val[:,1] ) conf_matrices[1] . append ( conf_matrix_val ) # add to the relative container recalls[1] . append ( [recall_2, recall_1] ) # add to the relative container precisions[1] . append ( [precision_2, precision_1] ) # add to the relative container conf_matrix_test = confusion_matrix ( y_test_comb, y_pred_test ) recall_2 = conf_matrix_test[2,2] / np.sum ( conf_matrix_test[2,:] ) recall_1 = conf_matrix_test[1,1] / np.sum ( conf_matrix_test[1,:] ) precision_2 = conf_matrix_test[2,2] / np.sum ( conf_matrix_test[:,2] ) precision_1 = conf_matrix_test[1,1] / np.sum ( conf_matrix_test[:,1] ) conf_matrices[2] . append ( conf_matrix_test ) # add to the relative container recalls[2] . append ( [recall_2, recall_1] ) # add to the relative container precisions[2] . append ( [precision_2, precision_1] ) # add to the relative container auc_eval_2 = roc_auc_score ( (y_eval_comb == 3), y_scores_eval_comb[:,1] ) # one-vs-all AUC score (PMBCL class) fpr_eval_2 , tpr_eval_2 , _ = roc_curve ( (y_eval_comb == 3), y_scores_eval_comb[:,1] ) # one-vs-all ROC curve (PMBCL class) if (len(fpr_eval_2) == n_roc_points[0]): append_to_roc[0] = True if append_to_roc[0]: roc_curves[0] . append ( np.c_ [1 - fpr_eval_2, tpr_eval_2, auc_eval_2 * np.ones_like(fpr_eval_2)] ) # add to the relative container append_to_roc[0] = False ; n_roc_points[0] = len(fpr_eval_2) auc_eval_1 = roc_auc_score ( (y_eval_comb == 2), y_scores_eval_comb[:,1] ) # one-vs-all AUC score (GZL class) fpr_eval_1 , tpr_eval_1 , _ = roc_curve ( (y_eval_comb == 2), y_scores_eval_comb[:,1] ) # one-vs-all ROC curve (GZL class) if (len(fpr_eval_1) == n_roc_points[1]): append_to_roc[1] = True if append_to_roc[1]: roc_curves[1] . append ( np.c_ [1 - fpr_eval_1, tpr_eval_1, auc_eval_1 * np.ones_like(fpr_eval_1)] ) # add to the relative container append_to_roc[1] = False ; n_roc_points[1] = len(fpr_eval_1) # +----------------------+ # | Plots generation | # +----------------------+ plot_conf_matrices ( conf_matrix = np.mean(conf_matrices[0], axis = 0) . astype(np.int32) , labels = LABELS , show_matrix = "both" , save_figure = True , fig_name = f"multi-clf/{args.model}/{args.model}_{args.threshold}_train" ) plot_conf_matrices ( conf_matrix = np.mean(conf_matrices[1], axis = 0) . astype(np.int32) , labels = LABELS , show_matrix = "both" , save_figure = True , fig_name = f"multi-clf/{args.model}/{args.model}_{args.threshold}_val" ) plot_conf_matrices ( conf_matrix = np.mean(conf_matrices[2], axis = 0) . astype(np.int32) , labels = LABELS , show_matrix = "both" , save_figure = True , fig_name = f"multi-clf/{args.model}/{args.model}_{args.threshold}_test" ) plot_multi_prf_histos ( rec_scores = ( np.array(recalls[0])[:,0] , np.array(recalls[0])[:,1] ) , prec_scores = ( np.array(precisions[0])[:,0] , np.array(precisions[0])[:,1] ) , bins = 25 , title = f"Performance of multi-class {model_name()} (on train-set)" , cls_labels = (LABELS[2], LABELS[1]) , save_figure = True , fig_name = f"multi-clf/{args.model}/{args.model}_{args.threshold}_train_prf" ) plot_multi_prf_histos ( rec_scores = ( np.array(recalls[1])[:,0] , np.array(recalls[1])[:,1] ) , prec_scores = ( np.array(precisions[1])[:,0] , np.array(precisions[1])[:,1] ) , bins = 25 , title = f"Performance of multi-class {model_name()} (on val-set)" , cls_labels = (LABELS[2], LABELS[1]) , save_figure = True , fig_name = f"multi-clf/{args.model}/{args.model}_{args.threshold}_val_prf" ) plot_multi_prf_histos ( rec_scores = ( np.array(recalls[2])[:,0] , np.array(recalls[2])[:,1] ) , prec_scores = ( np.array(precisions[2])[:,0] , np.array(precisions[2])[:,1] ) , bins = 25 , title = f"Performance of multi-class {model_name()} (on test-set)" , cls_labels = (LABELS[2], LABELS[1]) , save_figure = True , fig_name = f"multi-clf/{args.model}/{args.model}_{args.threshold}_test_prf" ) # +-------------------+ # | Scores export | # +-------------------+ roc_vars_lbl3 = np.c_ [ np.mean(roc_curves[0], axis = 0) , np.std(roc_curves[0], axis = 0)[:,2] ] roc_vars_lbl2 = np.c_ [ np.mean(roc_curves[1], axis = 0) , np.std(roc_curves[1], axis = 0)[:,2] ] score_dir = "scores" score_name = f"{args.model}_{args.threshold}" filename = f"{score_dir}/multi-clf/{score_name}.npz" np . savez ( filename, roc_vars_lbl3 = roc_vars_lbl3, roc_vars_lbl2 = roc_vars_lbl2 ) print (f"Scores correctly exported to {filename}")
[ 11748, 28686, 198, 11748, 2298, 293, 198, 11748, 299, 32152, 355, 45941, 198, 198, 6738, 256, 80, 36020, 220, 220, 220, 220, 1330, 256, 80, 36020, 198, 6738, 1822, 29572, 1330, 45751, 46677, 198, 198, 11748, 2172, 9613, 198, 8738, 9613,...
2.137855
7,283
import dsz, dsz.cmd, dsz.control import ops, ops.pprint import ops.data import traceback, sys from optparse import OptionParser if (__name__ == '__main__'): usage = 'python windows\\eventloqs.py [Options]\n-m, --monitor \n Runs in monitor mode, defaults to false\n-i, --interval [timeinterval]\n Interval between eventlogquery commands to use when running in monitor mode\n-l, --log [logname]\n Restricts query/monitor to one log\n-c, --classic\n If present, only queries System/Security/Application logs\n-t, --target\n Remote target to query\n' parser = OptionParser(usage=usage) parser.add_option('-m', '--monitor', dest='monitor', action='store_true', default=False) parser.add_option('-c', '--classic', dest='classic', action='store_true', default=False) parser.add_option('-i', '--interval', dest='interval', type='int', action='store', default='300') parser.add_option('-l', '--log', dest='logname', type='string', action='store', default='') parser.add_option('-t', '--target', dest='target', type='string', action='store', default=None) (options, args) = parser.parse_args(sys.argv) if options.monitor: monitorlogs(options.interval, options.classic, options.logname, options.target) else: logs = logquery(options.logname, options.target, options.classic) printlogtable(logs)
[ 198, 11748, 288, 82, 89, 11, 288, 82, 89, 13, 28758, 11, 288, 82, 89, 13, 13716, 198, 11748, 39628, 11, 39628, 13, 381, 22272, 198, 11748, 39628, 13, 7890, 198, 11748, 12854, 1891, 11, 25064, 198, 6738, 2172, 29572, 1330, 16018, 466...
2.839583
480
version="0.2.1"
[ 9641, 2625, 15, 13, 17, 13, 16, 1 ]
1.875
8
import logging from django.core.management.base import BaseCommand from django.utils.translation import ugettext_lazy as _ from oscar.apps.customer.alerts import utils logger = logging.getLogger(__name__) class Command(BaseCommand): """ Check stock records of products for availability and send out alerts to customers that have registered for an alert. """ help = _("Check for products that are back in " "stock and send out alerts") def handle(self, **options): """ Check all products with active product alerts for availability and send out email alerts when a product is available to buy. """ utils.send_alerts()
[ 11748, 18931, 201, 198, 201, 198, 6738, 42625, 14208, 13, 7295, 13, 27604, 13, 8692, 1330, 7308, 21575, 201, 198, 6738, 42625, 14208, 13, 26791, 13, 41519, 1330, 334, 1136, 5239, 62, 75, 12582, 355, 4808, 201, 198, 201, 198, 6738, 267...
2.755639
266
from __future__ import print_function from collections import OrderedDict import os import shutil import subprocess import tempfile import textwrap import unittest import conda_smithy.lint_recipe as linter if __name__ == '__main__': unittest.main()
[ 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 6738, 17268, 1330, 14230, 1068, 35, 713, 198, 11748, 28686, 198, 11748, 4423, 346, 198, 11748, 850, 14681, 198, 11748, 20218, 7753, 198, 11748, 2420, 37150, 198, 11748, 555, 715, 395, ...
3.185185
81
#!/usr/bin/env python """A script to split a fasta file into multiple smaller files. Output files will be <original>.xx.fasta """ from __future__ import print_function import argparse import sys import os import re from os.path import join as ospj if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--outdir', '-o', help="output directory") parser.add_argument('--input_fasta', help="Input read fasta 1") parser.add_argument('--prefix', help="output prefix") parser.add_argument('n_seqs', type=int, help="Number of sequences per file, the last file will contain slightly less") args = parser.parse_args() main(args)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 37811, 32, 4226, 284, 6626, 257, 3049, 64, 2393, 656, 3294, 4833, 3696, 13, 198, 198, 26410, 3696, 481, 307, 1279, 14986, 28401, 5324, 13, 7217, 64, 198, 37811, 198, 6738, 11593, 37443...
3.130045
223
# -*- coding: utf-8 -*- import dataset,codecs, Names, sqlite3 """ Under MIT-Licence, 2016 Perttu Rautaniemi """ def createtables(): """ Opening the database and tables, create tables if they dont exist """ conn = sqlite3.connect('LuontonurkkaDB.db') conn.execute('''CREATE TABLE `grid` ( `id` INTEGER NOT NULL, `N` INTEGER NOT NULL, `E` INTEGER NOT NULL, `sqrname` VARCHAR, PRIMARY KEY(id) );''') conn.execute('''CREATE TABLE `species` ( `id` INTEGER NOT NULL, `namelatin` VARCHAR NOT NULL, `namefin` VARCHAR, `type` INTEGER NOT NULL, `picture` VARCHAR, `idEN` VARCHAR, `idFI` VARCHAR, PRIMARY KEY(id) );''') conn.execute('''CREATE TABLE "species_in_square" ( `id` INTEGER NOT NULL, `sid` INTEGER NOT NULL, `gid` INTEGER NOT NULL, `freq` INTEGER, PRIMARY KEY(id) )''') ## ## Sql for indexes ## conn.execute('''CREATE INDEX gridIndex on grid (N, E);''') conn.execute('''CREATE INDEX sqrID on species_in_square (gid);''') conn.close() """filling both species in square and square tables using id data from speciestable and gridcsv for""" #createtables() data_fillfromCSV()
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 27039, 11, 19815, 721, 82, 11, 28531, 11, 44161, 578, 18, 198, 198, 37811, 198, 9203, 17168, 12, 26656, 594, 11, 1584, 350, 861, 28047, 371, 2306, 3216, 43967, ...
2.131849
584
# -*- coding: utf-8 -*- import math import threading import time
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 11748, 10688, 198, 11748, 4704, 278, 198, 11748, 640, 628, 628 ]
2.653846
26
from typing import Any, Tuple from pesto.ws.core.match_apply import MatchApply, Json
[ 6738, 19720, 1330, 4377, 11, 309, 29291, 198, 198, 6738, 28064, 78, 13, 18504, 13, 7295, 13, 15699, 62, 39014, 1330, 13225, 44836, 11, 449, 1559, 628 ]
3.222222
27
# 2019-11-15 00:35:39(JST) import operator as op import sys # import collections # import math # from string import ascii_lowercase, ascii_uppercase, digits # from bisect import bisect_left as bi_l, bisect_right as bi_r # import itertools from functools import reduce # from scipy.misc import comb # float # import numpy as np mod = 10 ** 9 + 7 if __name__ == "__main__": main()
[ 2, 13130, 12, 1157, 12, 1314, 3571, 25, 2327, 25, 2670, 7, 41, 2257, 8, 201, 198, 11748, 10088, 355, 1034, 201, 198, 11748, 25064, 201, 198, 201, 198, 2, 1330, 17268, 201, 198, 2, 1330, 10688, 201, 198, 2, 422, 4731, 1330, 355, ...
2.612903
155
from typing import Sequence, Union
[ 6738, 19720, 1330, 45835, 11, 4479, 198 ]
5
7
r""" CLI === **DO NOT USE (WIP)** This module contains the command line interface for gperc. Is this really needed? I am not sure. But having something along the lines of CLI means that running orchestration jobs would be possible. Add code to your github actions by loading data from one place, dispatch this for training and then testing it out all via CLI. I am using ``python-fire`` from google for this, `link <https://github.com/google/python-fire>`_, that can convert any arbitrary python object to a CLI. Normally I would use this with a ``main`` function, but since there has to be configuration in the CLI, I am using a class ``Main`` (yes, I know, weird). The default CLI has the following structure: .. code-block:: python3 -m gperc [BEHEVIOUR] [CONFIGS] [TASKS] BEHEVIOUR: -h, --help: Show this modal and exit. main: Run the main orchestration serve (WIP): serve using YoCo CONFIGS: main: configurations for the main orchestration. train: python3 -m gperc main train -h data: python3 -m gperc main data -h arch: python3 -m gperc main arch -h serve (WIP): configurations for the server mode. port: python3 -m gperc serve -h TASKS: Tasks are specific to behaviour and can raise errors for incorrect configs main: tasks for the main orchestration. profile: python3 -m gperc main [CONFIGS] profile -h start: python3 -m gperc main [CONFIGS] start -h deploy: deploy model on NimbleBox.ai. python3 -m gperc main [CONFIGS] deploy -h This is how something like loading a dataset and running a model would look like: .. code-block:: bash python3 -m gperc main --modality "image/class" \ data --dataset_name "cifar10" \ arch --mno [1024,128,1] --ced [3,32,10] \ train --epochs 10 --batch_size 32 --lr 0.001 \ start In the first line we have invoked the ``gperc`` module with modality (read below), in the next three lines we have specified the data, the architecture and the training parameters. It ends with the ``start`` command, which starts the training. """ from typing import List import torch from torch.profiler import profile, record_function, ProfilerActivity from .models import Perceiver from .configs import PerceiverConfig
[ 81, 37811, 198, 5097, 40, 198, 18604, 198, 198, 1174, 18227, 5626, 23210, 357, 54, 4061, 8, 1174, 198, 198, 1212, 8265, 4909, 262, 3141, 1627, 7071, 329, 308, 525, 66, 13, 1148, 428, 1107, 2622, 30, 314, 716, 407, 1654, 13, 198, 1...
2.897436
819
"""Python module to request PMU data from a running ANDES """ import logging import time from .dime import Dime from numpy import array, ndarray, zeros from pypmu import Pmu from pypmu.frame import ConfigFrame2, HeaderFrame if __name__ == "__main__": mini = MiniPMU( name='TestPMU', dime_address='ipc:///tmp/dime', pmu_idx=[1], pmu_port=1414) mini.run()
[ 37811, 37906, 8265, 284, 2581, 3122, 52, 1366, 422, 257, 2491, 5357, 1546, 198, 37811, 198, 198, 11748, 18931, 198, 11748, 640, 198, 198, 6738, 764, 67, 524, 1330, 360, 524, 198, 6738, 299, 32152, 1330, 7177, 11, 299, 67, 18747, 11, ...
2.415663
166
print("St-1") print(2/0) print("St-2")
[ 4798, 7203, 1273, 12, 16, 4943, 198, 4798, 7, 17, 14, 15, 8, 198, 4798, 7203, 1273, 12, 17, 4943, 198 ]
1.857143
21
import torch from torch.utils.data import Dataset import json import os from PIL import Image from utils.trms_util import transform class PascalVOCDataset(Dataset): """ A Dataset class to be used in a DataLoader to create batches. """ def __init__(self, data_folder, split="TEST", keep_difficult=False): """ Args: data_folder: folder where data files are stored. split: split, one of 'TRAIN' or 'TEST'. keep_difficult: keep or discard objects that are condidered difficult to detect. """ self.split = split.upper() assert self.split in {"TRAIN", "TEST"} self.data_folder = data_folder self.keep_difficult = keep_difficult with open(os.path.join(data_folder, self.split + "_images.json"), "r") as j: self.images = json.load(j) with open(os.path.join(data_folder, self.split + "_objects.json"), "r") as j: self.objects = json.load(j) assert len(self.images) == len(self.objects) def collate_fn(self, batch): """ Describes how to combine images with different number of objects by using lists. Since each image may have a different number of objects, we need a collate function (to bew passed to the DataLoader). Args: batch: an iterable of N sets from __getitem__() Returns: a tensor of images, lists of varying-size tensors of bounding boxes, labels, and difficulties. """ images = list() boxes = list() labels = list() difficulties = list() for b in batch: images.append(b[0]) boxes.append(b[1]) labels.append(b[2]) difficulties.append(b[3]) images = torch.stack(images, dim=0) return images, boxes, labels, difficulties
[ 11748, 28034, 198, 6738, 28034, 13, 26791, 13, 7890, 1330, 16092, 292, 316, 198, 11748, 33918, 198, 11748, 28686, 198, 6738, 350, 4146, 1330, 7412, 198, 198, 6738, 3384, 4487, 13, 2213, 907, 62, 22602, 1330, 6121, 628, 198, 4871, 35163,...
2.407979
777
#!/usr/bin/env python from distutils.core import setup from setuptools.command.test import test as TestCommand setup(name='neukrill-net', version='1.0', description='Neukrill-net NDSB tools', author='neuroglycerin', author_email='root@finlaymagui.re', packages=['neukrill_net'], tests_require=['pytest'], install_requires=['scipy==0.14.0', 'numpy==1.9.1', 'six==1.8.0', 'pytest==2.6.4', 'Pillow==2.7.0', 'scikit-image==0.10.1', 'scikit-learn==0.15.2'], cmdclass={'test': PyTest}, )
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 6738, 1233, 26791, 13, 7295, 1330, 9058, 198, 6738, 900, 37623, 10141, 13, 21812, 13, 9288, 1330, 1332, 355, 6208, 21575, 198, 198, 40406, 7, 3672, 11639, 710, 2724, 20190, 12, 32...
1.755844
385
from tensornetwork.contractors.custom_path_solvers import pathsolvers from tensornetwork.contractors.custom_path_solvers import nconinterface #pylint: disable=line-too-long from tensornetwork.contractors.custom_path_solvers.pathsolvers import greedy_cost_solve, greedy_size_solve, full_solve_complete #pylint: disable=line-too-long from tensornetwork.contractors.custom_path_solvers.nconinterface import ncon_solver, ncon_to_adj, ord_to_ncon, ncon_cost_check
[ 6738, 11192, 1211, 316, 1818, 13, 28484, 669, 13, 23144, 62, 6978, 62, 34453, 690, 1330, 13532, 349, 690, 198, 6738, 11192, 1211, 316, 1818, 13, 28484, 669, 13, 23144, 62, 6978, 62, 34453, 690, 1330, 299, 1102, 39994, 198, 2, 79, 26...
2.980519
154
#!/usr/bin/python2 import os import yaml
[ 2, 48443, 14629, 14, 8800, 14, 29412, 17, 198, 198, 11748, 28686, 198, 11748, 331, 43695, 198 ]
2.470588
17
from .base import * from .site import *
[ 6738, 764, 8692, 1330, 1635, 198, 6738, 764, 15654, 1330, 1635, 198 ]
3.333333
12
import numpy as np from np_model_base import NNModelBase import pandas as pd __author__ = "Christopher Potts" __version__ = "CS224u, Stanford, Spring 2020" if __name__ == '__main__': simple_example()
[ 11748, 299, 32152, 355, 45941, 198, 6738, 45941, 62, 19849, 62, 8692, 1330, 399, 45, 17633, 14881, 198, 11748, 19798, 292, 355, 279, 67, 198, 198, 834, 9800, 834, 796, 366, 38025, 6902, 912, 1, 198, 834, 9641, 834, 796, 366, 7902, 2...
2.929577
71
# Generated by Django 2.0.2 on 2018-02-27 10:01 from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 362, 13, 15, 13, 17, 319, 2864, 12, 2999, 12, 1983, 838, 25, 486, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
2.84375
32
import os import numpy as np import cv2 import argparse from sklearn.metrics import confusion_matrix import matplotlib.pyplot as plt import seaborn as sns from tensorflow.keras import Input from model import u_net from preprocessing.preprocess_utils import display from experiments import lip_hair_color def make_confusion_matrix(cf, categories, group_names=None, count=True, percent=True, color_bar=True, xy_ticks=True, xy_plot_labels=True, sum_stats=True, fig_size=None, c_map='Blues', title=None): """ Code to generate text within each box and beautify confusion matrix. :param cf: Confusion matrix. :type cf: numpy array :param categories: array of classes. :type categories: numpy array :param group_names: classes in the project. :type group_names: numpy array :param count: whether to display the count of each class. :type count: boolean :param percent: whether to display percentage for each class. :type percent: boolean :param color_bar: whether to display color bar for the heat map. :type color_bar: boolean :param xy_ticks: whether to display xy labels. :type xy_ticks: boolean :param xy_plot_labels: whether to display xy title. :type xy_plot_labels: boolean :param sum_stats: whether to display overall accuracy. :type sum_stats: boolean :param fig_size: size of the plot. :type fig_size: tuple :param c_map: color scheme to use. :type c_map: str :param title: Title of the plot. :type title: str """ blanks = ['' for i in range(cf.size)] if group_names and len(group_names) == cf.size: group_labels = ["{}\n".format(value) for value in group_names] else: group_labels = blanks if count: group_counts = ["{0:0.0f}\n".format(value) for value in cf.flatten()] else: group_counts = blanks if percent: row_size = np.size(cf, 0) col_size = np.size(cf, 1) group_percentages = [] for i in range(row_size): for j in range(col_size): group_percentages.append(cf[i][j] / cf[i].sum()) group_percentages = ["{0:.2%}".format(value) for value in group_percentages] else: group_percentages = blanks box_labels = [f"{v1}{v2}{v3}".strip() for v1, v2, v3 in zip(group_labels, group_counts, group_percentages)] box_labels = np.asarray(box_labels).reshape(cf.shape[0], cf.shape[1]) # CODE TO GENERATE SUMMARY STATISTICS & TEXT FOR SUMMARY STATS if sum_stats: # Accuracy is sum of diagonal divided by total observations accuracy = np.trace(cf) / float(np.sum(cf)) stats_text = "\n\nAccuracy={0:0.2%}".format(accuracy) else: stats_text = "" # SET FIGURE PARAMETERS ACCORDING TO OTHER ARGUMENTS if fig_size is None: # Get default figure size if not set fig_size = plt.rcParams.get('figure.figsize') if not xy_ticks: # Do not show categories if xyticks is False categories = False # MAKE THE HEAT MAP VISUALIZATION plt.figure(figsize=fig_size) sns.heatmap(cf, annot=box_labels, fmt="", cmap=c_map, cbar=color_bar, xticklabels=categories, yticklabels=categories) if xy_plot_labels: plt.ylabel('True label') plt.xlabel('Predicted label' + stats_text) else: plt.xlabel(stats_text) if title: plt.title(title) def plot_confusion_matrix(predictions, masks, path): """ Visualize confusion matrix. :param predictions: predicted output of the model. :type predictions: array :param masks: true masks of the images. :type masks: array :param path: directory to store the output :type path: str """ print('[INFO] Plotting confusion matrix...') corr = confusion_matrix(masks.ravel(), predictions.ravel()) make_confusion_matrix(corr, categories=['bg', 'skin', 'nose', 'eye_g', 'l_eye', 'r_eye', 'l_brow', 'r_brow', 'l_ear', 'r_ear', 'mouth', 'u_lip', 'l_lip', 'hair', 'hat', 'ear_r', 'neck_l', 'neck', 'cloth'], count=True, percent=False, color_bar=False, xy_ticks=True, xy_plot_labels=True, sum_stats=True, fig_size=(20, 18), c_map='coolwarm', title='Confusion matrix') # error correction - cropped heat map b, t = plt.ylim() # discover the values for bottom and top b += 0.5 # Add 0.5 to the bottom t -= 0.5 # Subtract 0.5 from the top plt.ylim(b, t) # update the ylim(bottom, top) values plt.savefig(os.path.join(path, 'confusion_matrix.png')) print('[ACTION] See results/visualization/confusion_matrix.png') def plot_mask(prediction, mask, norm_image): """ PLot segmentation mask for the given image. :param prediction: predicted output of the model. :type prediction: array :param mask: true masks of the images. :type mask: array :param norm_image: original image. :type norm_image: array """ image = (norm_image * 255.).astype(np.uint8) im_base = np.zeros((256, 256, 3), dtype=np.uint8) for idx, color in enumerate(color_list): im_base[prediction == idx] = color cv2.addWeighted(im_base, 0.8, image, 1, 0, im_base) display([image, mask, im_base], ['Original image', 'True mask', 'Predicted mask'], 'predict') def test(image, masks, action, color='red'): """ Used to plot either confusion matrix or predicted mask or apply makeup. :param image: original image. :type image: bytearray :param masks: true segmentation masks. :type masks: array :param action: user input specifying confusion matrix/mask prediction/applying makeup. :type action: str :param color: if action is applying makeup, then color to apply. Defaults to red. :type color: str """ input_img = Input(shape=(256, 256, 3), name='img') model = u_net.get_u_net(input_img, num_classes=19) model.load_weights(os.path.join(MODEL_DIR, 'u_net.h5')) print('[INFO] Predicting ...') predictions = model.predict(image) predictions = np.argmax(predictions, axis=-1) table = { 'hair': 13, 'upper_lip': 11, 'lower_lip': 12 } colors = { 'red': [212, 34, 34], 'purple': [128, 51, 125], 'pink': [247, 32, 125] } # Redirect to the function of specified action. if action == 'confusion_matrix': print('[INFO] Plotting confusion matrix ...') plot_confusion_matrix(predictions, masks, VISUALIZATION_DIR) elif action == 'mask': print('[INFO] Plotting segmentation mask ...') plot_mask(predictions[sample], masks[sample], image[sample]) elif action == 'hair_color': print('[INFO] Applying hair color ...') parts = [table['hair']] changed = lip_hair_color.color_change(image[sample], predictions[sample], parts, colors[color]) display([image[sample], changed], 'hair') elif action == "lip_color": print('[INFO] Applying lip color ...') parts = [table['upper_lip'], table['lower_lip']] changed = lip_hair_color.color_change(image[sample], predictions[sample], parts, colors[color]) display([image[sample], changed], 'lip') def main(): """ Define user arguments. """ ap = argparse.ArgumentParser() ap.add_argument("-v", "--visualize", type=str, required=True, choices=("confusion_matrix", "mask", "hair_color", "lip_color"), help="type of model") ap.add_argument("-c", "--color", type=str, choices=("red", "pink", "purple"), help="color to apply") args = vars(ap.parse_args()) # print('[INFO] Getting test data...') # test_data = get_test() # imgs = [] # masks = [] # for img, label in test_data: # for i in img: # i = np.array(i, dtype='float32') # imgs.append(i) # for j in label: # j = np.array(j, dtype='float32') # masks.append(j) # images = np.array(imgs) # masks = np.array(masks) # np.save('data/test_images.npy', images) # np.save('data/test_mask.npy', masks) # Load test images images = np.load('data/test_images.npy') masks = np.load('data/test_mask.npy') test(images, masks, args["visualize"], args["color"]) if __name__ == '__main__': VISUALIZATION_DIR = 'results/visualization/' MODEL_DIR = 'results/models/' color_list = [[0, 0, 0], [204, 0, 0], [255, 140, 26], [204, 204, 0], [51, 51, 255], [204, 0, 204], [0, 255, 255], [255, 204, 204], [102, 51, 0], [255, 0, 0], [102, 204, 0], [255, 255, 0], [0, 0, 153], [0, 0, 204], [255, 51, 153], [0, 204, 204], [0, 51, 0], [255, 153, 51], [0, 204, 0]] sample = 4 main()
[ 11748, 28686, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 269, 85, 17, 198, 11748, 1822, 29572, 198, 6738, 1341, 35720, 13, 4164, 10466, 1330, 10802, 62, 6759, 8609, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198,...
2.094695
4,731
import large_image_source_tiff as tiff # from large_image.tilesource.base import GirderTileSource from large_image_source_tiff import girder_source from .tiff_reader import TiledTiffDirectory tiff.TiledTiffDirectory = TiledTiffDirectory
[ 11748, 1588, 62, 9060, 62, 10459, 62, 83, 733, 355, 256, 733, 198, 2, 422, 1588, 62, 9060, 13, 83, 2915, 1668, 13, 8692, 1330, 23837, 1082, 35103, 7416, 198, 6738, 1588, 62, 9060, 62, 10459, 62, 83, 733, 1330, 37370, 1082, 62, 104...
3.2
75
# Auto generated by generator.py. Delete this line if you make modification. from scrapy.spiders import Rule from scrapy.linkextractors import LinkExtractor XPATH = { 'name' : "//div[@class='header_layer_2']/h1", 'price' : "//input[@name='price']/@value", 'category' : "//div[@class='thanh_dinh_huong']/a", 'description' : "", 'images' : "//img[@id='anh_chitiet_sanpham']/@src", 'canonical' : "", 'base_url' : "//base/@href", 'brand' : "" } name = 'songvu.net' allowed_domains = ['songvu.net'] start_urls = ['http://songvu.net/ao-so-mi-nam-d37v3.html'] tracking_url = '' sitemap_urls = [''] sitemap_rules = [('', 'parse_item')] sitemap_follow = [] rules = [ Rule(LinkExtractor(allow=['/[a-zA-Z0-9-]+-id\d+\.html$']), 'parse_item'), Rule(LinkExtractor(allow=['/[a-zA-Z0-9-]+-d\d+(v3)?(p\d+)?\.html$']), 'parse'), #Rule(LinkExtractor(), 'parse_item_and_links'), ]
[ 2, 11160, 7560, 416, 17301, 13, 9078, 13, 23520, 428, 1627, 611, 345, 787, 17613, 13, 198, 6738, 15881, 88, 13, 2777, 4157, 1330, 14330, 198, 6738, 15881, 88, 13, 2815, 365, 742, 974, 669, 1330, 7502, 11627, 40450, 198, 198, 27481, ...
2.24505
404
# Generated by Django 2.1.3 on 2019-01-08 04:17 from django.db import migrations
[ 2, 2980, 515, 416, 37770, 362, 13, 16, 13, 18, 319, 13130, 12, 486, 12, 2919, 8702, 25, 1558, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 628 ]
2.766667
30
import numpy as np import time import xgboost as xgb from sklearn.model_selection import KFold from regularization.score import myFeval from sklearn.metrics import mean_squared_error from regularization.data_process import data_process s = time.time() X_train, y_train, X_test, train_len, test_len = data_process() print('加载数据及预处理消耗时间:', time.time()-s) xgb_params = {"booster": 'gbtree', 'eta': 0.005, 'max_depth': 5, 'subsample': 0.7, # 随机采样训练样本 'colsample_bytree': 0.8, 'objective': 'reg:linear', 'eval_metric': 'rmse', 'silent': True, 'lambda': 1 } folds = KFold(n_splits=5, shuffle=True, random_state=2018) oof_xgb = np.zeros(train_len) predictions_xgb = np.zeros(test_len) for fold_, (trn_idx, val_idx) in enumerate(folds.split(X_train, y_train)): print("fold n°{}".format(fold_ + 1)) trn_data = xgb.DMatrix(X_train[trn_idx], y_train[trn_idx]) val_data = xgb.DMatrix(X_train[val_idx], y_train[val_idx]) watchlist = [(trn_data, 'train'), (val_data, 'valid_data')] clf = xgb.train(dtrain=trn_data, num_boost_round=20000, evals=watchlist, early_stopping_rounds=200, verbose_eval=100, params=xgb_params, feval=myFeval) oof_xgb[val_idx] = clf.predict(xgb.DMatrix(X_train[val_idx]), ntree_limit=clf.best_ntree_limit) predictions_xgb += clf.predict(xgb.DMatrix(X_test), ntree_limit=clf.best_ntree_limit) / folds.n_splits print("CV score: {:<8.8f}".format(mean_squared_error(oof_xgb, y_train.tolist()))) ''' -------------------------------------------- 1. 初始参数 reg:linear 0.45434592 2. 增加L2正则 'lambda':2 0.45488106 3. 2+增加L1正则 'alpha': 1 0.45456481 4. 增加L1正则 'alpha': 1 0.45460193 5. 3+subsample改为0.6 0.45449627 6. 只改subsample 0.6 0.45448684 7. 只改subsample 0.8 0.45625735 8. 1+增加L1正则0.5 0.45431723 9. 1+增加L1正则0.3 0.45450940 10.1+增加L1正则0.7 0.45447847 11.1+增加L1正则0.6 0.45467713 12.1+增加L1正则0.55 0.45430484 ○ 13.12+L2正则0.5 0.45467713 14.12+L2正则3 0.45431729 15.1+增加L2正则3 0.45484879 16.1+增加L2正则1 0.45434592 17.1+增加L2正则0.5 0.45469010 '''
[ 11748, 299, 32152, 355, 45941, 198, 11748, 640, 198, 11748, 2124, 70, 39521, 355, 2124, 22296, 198, 6738, 1341, 35720, 13, 19849, 62, 49283, 1330, 509, 37, 727, 198, 6738, 3218, 1634, 13, 26675, 1330, 616, 37, 18206, 198, 6738, 1341, ...
1.690583
1,338
from django.test import TestCase from apps.datablock.models import DataBlock from apps.fleet.models import Fleet from apps.physicaldevice.models import Device from apps.stream.models import StreamId, StreamVariable from ..test_util import TestMixin from .utils import * from .utils import _get_real_slug
[ 6738, 42625, 14208, 13, 9288, 1330, 6208, 20448, 198, 198, 6738, 6725, 13, 19608, 397, 5354, 13, 27530, 1330, 6060, 12235, 198, 6738, 6725, 13, 33559, 13, 27530, 1330, 20001, 198, 6738, 6725, 13, 42854, 25202, 13, 27530, 1330, 16232, 19...
3.698795
83
# Copyright 2016 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. import os TEST_APP_URL = os.environ['TEST_APP_URL']
[ 2, 15069, 1584, 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, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 198, 2, 921, 743, ...
3.605714
175
import nengo model = nengo.Network() with model: a = nengo.Ensemble(n_neurons=100, dimensions=2, radius=1) stim = nengo.Node([0,0]) nengo.Connection(stim, a)
[ 11748, 299, 1516, 78, 198, 198, 19849, 796, 299, 1516, 78, 13, 26245, 3419, 198, 4480, 2746, 25, 198, 220, 220, 220, 257, 796, 299, 1516, 78, 13, 4834, 15140, 7, 77, 62, 710, 333, 684, 28, 3064, 11, 15225, 28, 17, 11, 16874, 28,...
2.068966
87
# 時系列予測の問題に季節項を導入する # 時系列データは、目的変数を観測値の要素の和に分解するのが定石 # Own Library import mcmc_tools import analysis_data as ad import seaborn as sns import matplotlib.pyplot as plt if __name__ == '__main__': spm = SPM('data-ss2.txt', '../model/model12-2') spm.describe() spm.observe_ts() stan_data = spm.create_data() mcmc_sample = spm.fit(stan_data) # 全体の観測および予測分布 spm.create_figure(mcmc_sample, 'y_mean_pred') # 要素ごとに分けて観測および予測分布 spm.create_figure(mcmc_sample, 'mu_pred') spm.create_figure(mcmc_sample, 'season_pred')
[ 2, 10545, 25081, 163, 111, 119, 26344, 245, 12859, 230, 162, 116, 105, 15474, 243, 237, 165, 94, 234, 28618, 27764, 96, 163, 107, 222, 165, 254, 227, 31758, 22887, 236, 17739, 98, 33623, 25748, 198, 2, 10545, 25081, 163, 111, 119, 2...
1.520548
365
################################################################################ # # MRC FGU Computational Genomics Group # # $Id$ # # Copyright (C) 2009 Andreas Heger # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. ################################################################################# ''' ScopTester.py - ====================================================== :Author: Andreas Heger :Release: $Id$ :Date: |today| :Tags: Python Code ---- ''' import sys import re import string import os import time from Pairsdb import * import alignlib import pairsdblib from MessagePairsdb import MessagePairsdb from TableDomainsScopTest import TableDomainsScopTest from TablePairsdbNeighbours import TablePairsdbNeighbours from Pairsdb import * import Tools #------------------------------------------- # Class: ScopTest # Superclasses: Message # Subclasses: # Function: update ScopTest-database # # Author: Andreas Heger #------------------------------------------- ##-------------------------------------------------------------------------------------- ##-------------------------------------------------------------------------------------- ##-------------------------------------------------------------------------------------- class ScopTesterFullProfiles( ScopTesterProfiles ): """use full length profiles. beware of multidomain-proteins, use iterative multiple alignment method. """ ##-------------------------------------------------------------------------------------- class Alignator: """ aligns two sequences and returns result. """ ##-------------------------------------------------------------------------------------- ##-------------------------------------------------------------------------------------- def CheckResult( self, result, info1 = None, info2 = None): """check if result is ok. The function below returns everything. return tuple of strings as result. """ if (result.getLength() > 0): row_ali, col_ali = alignlib.writeAlignataCompressed( result ) return map(str, (result.getScore(), result.getLength(), result.getNumGaps(), alignlib.calculatePercentSimilarity( result ), result.getRowFrom(), result.getRowTo(), row_ali, result.getColFrom(), result.getColTo(), col_ali ) ) else: return ("0",) * 12 ##-------------------------------------------------------------------------------------- class AlignatorIterative(Alignator): """ aligns two sequences iteratively, checks if alignment regions are overlapping with domain regions and returns result only for those overlapping. This is useful if you have several domains in a sequence, but you need only compare to one. """ ##-------------------------------------------------------------------------------------- def Align( self, a1, a2, result ): """align repetetively. Take highest scoring alignment, that overlaps with domains and put it in result. Note: performIterativeAlignment does not work, as it is linear. It requires domains to be in the same order. Result is empty, fragments are saved in object. """ fragmentor = alignlib.makeFragmentorRepetitive( self.mAlignator, self.mMinScore ) ## align iteratively and convert fragments to Alignata-objects val = fragmentor.Fragment( a1, a2, result) self.mFragments = map( lambda x: alignlib.AlignataPtr(x), val) for fragment in self.mFragments: fragment.thisown = 1 ## alignlib.performIterativeAlignmentNonConst( result, ## a1, a2, ## self.mAlignator, ## self.mMinScore ) ##-------------------------------------------------------------------------------------- def CheckResult( self, result, info1, info2): """check if result is ok. Check for each fragment, if it overlaps with the domains to be tested and dump if ok. This simulates psiblast. """ row_from, row_to = map(string.atoi, info1[1:3]) col_from, col_to = map(string.atoi, info2[1:3]) ## check for overlap for fragment in self.mFragments: # print alignlib.writeAlignataTable( fragment, 8, 1) xcol_from = Tools.MapRight(fragment, row_from ) xcol_to = Tools.MapLeft(fragment, row_to ) overlap = min(col_to, xcol_to) - max(col_from, xcol_from) # print self.mMinOverlap, overlap, xcol_from, xcol_to, col_from, col_to if overlap > self.mMinOverlap: return map(str, (fragment.getScore(), fragment.getLength(), fragment.getNumGaps(), alignlib.calculatePercentSimilarity( fragment ), fragment.getRowFrom(), fragment.getRowTo(), fragment.getColFrom(), fragment.getColTo(), overlap, xcol_from, xcol_to, (xcol_to - xcol_from) - (col_to - col_from)) ) return ("0",) * 12 ##-------------------------------------------------------------------------------------- if __name__ == '__main__': dbhandle = Pairsdb() if not dbhandle.Connect(): print "Connection failed" sys.exit(1) a = alignlib.makeFullDP( -10.0, -2.0 ) alignator = Alignator( a ) x = ScopTesterSequences( dbhandle, alignator ) x.Process() if param_alignator == 0: a = alignlib.makeFullDP( param_gop, param_gep) alignator = Alignator( a ) if param_entities == 0: tester = ScopTesterSequences( dbhandle, alignator ) tester.mLogLevel = param_loglevel matches = a.CalculateMatches()
[ 29113, 29113, 14468, 198, 2, 198, 2, 220, 220, 337, 7397, 25503, 52, 22476, 864, 5215, 31994, 4912, 198, 2, 198, 2, 220, 220, 720, 7390, 3, 198, 2, 198, 2, 220, 220, 15069, 357, 34, 8, 3717, 33728, 679, 1362, 198, 2, 198, 2, 2...
2.462457
2,930
import webracer import nose.plugins.attrib from . import utils from .apps import kitchen_sink_app utils.app_runner_setup(__name__, kitchen_sink_app.app, 8056) base_config = dict(host='localhost', port=8056) @nose.plugins.attrib.attr('client')
[ 11748, 356, 1671, 11736, 198, 11748, 9686, 13, 37390, 13, 1078, 822, 198, 6738, 764, 1330, 3384, 4487, 198, 6738, 764, 18211, 1330, 9592, 62, 82, 676, 62, 1324, 198, 198, 26791, 13, 1324, 62, 16737, 62, 40406, 7, 834, 3672, 834, 11,...
2.764045
89
from django.db import models from lectures.models import Day # Create your models here.
[ 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 6738, 25917, 13, 27530, 1330, 3596, 198, 198, 2, 13610, 534, 4981, 994, 13, 628 ]
3.913043
23
from tests.test_helper import * from datetime import date from braintree.dispute import Dispute
[ 6738, 5254, 13, 9288, 62, 2978, 525, 1330, 1635, 198, 6738, 4818, 8079, 1330, 3128, 198, 6738, 865, 2913, 631, 13, 6381, 79, 1133, 1330, 36060, 1133, 198 ]
3.428571
28
"Step 3: Stepping Up to OOP" 'Adding Persistence' # Notice how we still fetch, update, and # reassign to keys to update the shelve. import shelve db = shelve.open('class-shelve') sue = db['sue'] sue.giveRaise(.25) db['sue'] = sue tom = db['tom'] tom.giveRaise(.20) db['tom'] = tom db.close() ''' class instances allow us to combine both data and behavior for our stored items. In a sense, instance attributes and class methods take the place of records and processing programs in more traditional schemes. '''
[ 1, 8600, 513, 25, 2441, 2105, 3205, 284, 440, 3185, 1, 198, 6, 32901, 9467, 13274, 6, 198, 2, 17641, 703, 356, 991, 21207, 11, 4296, 11, 290, 220, 198, 2, 12719, 570, 284, 8251, 284, 4296, 262, 7497, 303, 13, 198, 198, 11748, 74...
3.058824
170
#!/usr/bin/python # # Exemplary script to read the annotations generated by the web application # in this repo. # # @author: Luis Carlos Garcia-Peraza Herrera (luiscarlos.gph@gmail.com). # @date : 20 Jan 2021. import argparse import json import cv2 import numpy as np import os # My imports import wat.common def parse_cmdline_params(): """ @brief Parse command line parameters to get input and output file names. @param[in] argv Array of command line arguments. @return input and output file names if they were specified. """ parser = argparse.ArgumentParser() parser.add_argument('--dir', required=True, help='Path to the output directory.') parser.add_argument('--gt-suffix', default='_seg', required=False, help='Suffix of the segmentation-like annotations.') args = parser.parse_args() return args if __name__ == "__main__": main()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 2, 220, 198, 2, 1475, 18856, 560, 4226, 284, 1100, 262, 37647, 7560, 416, 262, 3992, 3586, 198, 2, 287, 428, 29924, 13, 198, 2, 198, 2, 2488, 9800, 25, 20894, 17409, 18555, 12, 5990, 7056...
2.967213
305
# Copyright 2018 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Module to enforce authentication on endpoints.method. Usage: ----- # configuration of an endpoints method with enforced user auth check only. @loaner_endpoints.authed_method( chrome_message.ChromeRequest, chrome_message.ChromeResponse, name='heartbeat', path='heartbeat', http_method='GET', user_auth_only=True) def do_something(self, request): ... The above method will execute if the current user is authenticated properly. # configuration of an endpoints method with enforced permission. @loaner_endpoints.authed_method( chrome_message.ChromeRequest, chrome_message.ChromeResponse, name='heartbeat', path='heartbeat', http_method='GET', permission='view') def do_something(self, request): ... The above method will only execute if the current user's role has the permission "view". Note: ----- Please see permission module for more information on how the check_auth() decorator works. """ import endpoints from loaner.web_app.backend.auth import permissions class Error(Exception): """Default error class for this module.""" class AuthCheckNotPresent(Error): """Raised when auth_method was called without auth check.""" def authed_method(*args, **kwargs): """Configures an endpoint method and enforces permissions.""" def auth_method_decorator(auth_function): """Decorator for auth_method.""" kwarg_auth = None kwarg_permission = None for key in kwargs: if key is 'permission': kwarg_permission = kwargs.pop('permission') auth_function = permissions.check_auth( permission=kwarg_permission)(auth_function) break elif key is 'user_auth_only': kwarg_auth = kwargs.pop('user_auth_only') auth_function = permissions.check_auth( user_auth_only=kwarg_auth)(auth_function) break if not kwarg_auth and not kwarg_permission: raise AuthCheckNotPresent( 'No permission or user_auth_only was passed. Authentication on this ' 'method cannot run.') # Always apply the standard `endpoints.method` decorator. return endpoints.method(*args, **kwargs)(auth_function) return auth_method_decorator
[ 2, 15069, 2864, 3012, 3457, 13, 1439, 6923, 33876, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, ...
3.079121
910
import FWCore.ParameterSet.Config as cms from DQMServices.Core.DQMEDHarvester import DQMEDHarvester from DQM.SiPixelPhase1Common.HistogramManager_cfi import * import DQM.SiPixelPhase1Common.TriggerEventFlag_cfi as trigger SiPixelPhase1RecHitsNRecHits = DefaultHistoTrack.clone( name = "rechits", title = "RecHits", range_min = 0, range_max = 30, range_nbins = 30, xlabel = "rechits", dimensions = 0, specs = VPSet( StandardSpecificationTrend_Num, Specification().groupBy("PXBarrel/Event") .reduce("COUNT") .groupBy("PXBarrel") .save(nbins=100, xmin=0, xmax=5000), Specification().groupBy("PXForward/Event") .reduce("COUNT") .groupBy("PXForward") .save(nbins=100, xmin=0, xmax=5000), Specification().groupBy("PXAll/Event") .reduce("COUNT") .groupBy("PXAll") .save(nbins=100, xmin=0, xmax=5000) ) ) SiPixelPhase1RecHitsClustX = DefaultHistoTrack.clone( name = "clustersize_x", title = "Cluster Size X (OnTrack)", range_min = 0, range_max = 50, range_nbins = 50, xlabel = "size[pixels]", dimensions = 1, specs = VPSet( StandardSpecification2DProfile ) ) SiPixelPhase1RecHitsClustY = SiPixelPhase1RecHitsClustX.clone( name = "clustersize_y", title = "Cluster Size Y (OnTrack)", xlabel = "size[pixels]" ) SiPixelPhase1RecHitsErrorX = DefaultHistoTrack.clone( enabled=False, name = "rechiterror_x", title = "RecHit Error in X-direction", range_min = 0, range_max = 0.02, range_nbins = 100, xlabel = "X error", dimensions = 1, specs = VPSet( StandardSpecification2DProfile ) ) SiPixelPhase1RecHitsErrorY = SiPixelPhase1RecHitsErrorX.clone( enabled=False, name = "rechiterror_y", title = "RecHit Error in Y-direction", xlabel = "Y error" ) SiPixelPhase1RecHitsPosition = DefaultHistoTrack.clone( enabled = False, name = "rechit_pos", title = "Position of RecHits on Module", range_min = -1, range_max = 1, range_nbins = 100, range_y_min = -4, range_y_max = 4, range_y_nbins = 100, xlabel = "x offset", ylabel = "y offset", dimensions = 2, specs = VPSet( Specification(PerModule).groupBy("PXBarrel/PXLayer/DetId").save(), Specification(PerModule).groupBy("PXForward/PXDisk/DetId").save(), ) ) SiPixelPhase1RecHitsProb = DefaultHistoTrack.clone( name = "clusterprob", title = "Cluster Probability", xlabel = "log_10(Pr)", range_min = -10, range_max = 1, range_nbins = 50, dimensions = 1, specs = VPSet( Specification().groupBy("PXBarrel/PXLayer").saveAll(), Specification().groupBy("PXForward/PXDisk").saveAll(), StandardSpecification2DProfile, Specification().groupBy("PXBarrel/LumiBlock") .reduce("MEAN") .groupBy("PXBarrel", "EXTEND_X") .save(), Specification().groupBy("PXForward/LumiBlock") .reduce("MEAN") .groupBy("PXForward", "EXTEND_X") .save(), Specification(PerLayer1D).groupBy("PXBarrel/Shell/PXLayer").save(), Specification(PerLayer1D).groupBy("PXForward/HalfCylinder/PXRing/PXDisk").save() ) ) SiPixelPhase1RecHitsConf = cms.VPSet( SiPixelPhase1RecHitsNRecHits, SiPixelPhase1RecHitsClustX, SiPixelPhase1RecHitsClustY, SiPixelPhase1RecHitsErrorX, SiPixelPhase1RecHitsErrorY, SiPixelPhase1RecHitsPosition, SiPixelPhase1RecHitsProb, ) from DQMServices.Core.DQMEDAnalyzer import DQMEDAnalyzer SiPixelPhase1RecHitsAnalyzer = DQMEDAnalyzer('SiPixelPhase1RecHits', src = cms.InputTag("generalTracks"), histograms = SiPixelPhase1RecHitsConf, geometry = SiPixelPhase1Geometry, onlyValidHits = cms.bool(False), triggerflags = trigger.SiPixelPhase1Triggers ) SiPixelPhase1RecHitsHarvester = DQMEDHarvester("SiPixelPhase1Harvester", histograms = SiPixelPhase1RecHitsConf, geometry = SiPixelPhase1Geometry )
[ 11748, 48849, 14055, 13, 36301, 7248, 13, 16934, 355, 269, 907, 198, 6738, 360, 48, 5653, 712, 1063, 13, 14055, 13, 35, 48, 30733, 13587, 1158, 353, 1330, 360, 48, 30733, 13587, 1158, 353, 198, 6738, 360, 48, 44, 13, 42801, 40809, 3...
2.24492
1,821
import os, requests from progressbar import progressbar from caltechdata_api import get_metadata, caltechdata_edit def get_datacite_dates(prefix): """Get sumbitted date for DataCite DOIs with specific prefix""" doi_dates = {} doi_urls = {} url = ( "https://api.datacite.org/dois?query=prefix:" + prefix + "&page[cursor]=1&page[size]=500" ) next_link = url meta = requests.get(next_link).json()["meta"] for j in progressbar(range(meta["totalPages"])): r = requests.get(next_link) data = r.json() for doi in data["data"]: date = doi["attributes"]["registered"].split("T")[0] doi_dates[doi["id"]] = date doi_urls[doi["id"]] = doi["attributes"]["url"] if "next" in data["links"]: next_link = data["links"]["next"] else: next_link = None return doi_dates, doi_urls token = os.environ["TINDTOK"] doi_dates, doi_urls = get_datacite_dates("10.14291") for doi in doi_urls: if "data.caltech.edu" in doi_urls[doi]: caltech_id = doi_urls[doi].split("/")[-1] if caltech_id not in ["252", "253", "254", "255"]: metadata = get_metadata(caltech_id, emails=True) print(caltech_id) # print(metadata['dates']) for date in metadata["dates"]: if date["dateType"] == "Issued": print(date["date"], doi_dates[doi]) date["date"] = doi_dates[doi] response = caltechdata_edit(token, caltech_id, metadata, production=True) print(response)
[ 11748, 28686, 11, 7007, 198, 6738, 4371, 5657, 1330, 4371, 5657, 198, 6738, 2386, 13670, 7890, 62, 15042, 1330, 651, 62, 38993, 11, 2386, 13670, 7890, 62, 19312, 628, 198, 4299, 651, 62, 19608, 330, 578, 62, 19581, 7, 40290, 2599, 198...
2.122876
765
import json from app import Category
[ 11748, 33918, 198, 6738, 598, 1330, 21743, 628 ]
4.75
8
"""Transformation between two frames. """ from compas.geometry import Frame from compas.geometry import Point from compas.geometry import Transformation F1 = Frame.worldXY() F2 = Frame([1.5, 1, 0], [0.68, 0.68, 0.27], [-0.67, 0.73, -0.15]) P = Point(2, 2, 2) # local point in F1 # transformation between 2 frames F1, F2 T = Transformation.from_frame_to_frame(F1, F2) # Transform geometry (=point P) into another coordinate frame print(P.transformed(T))
[ 37811, 8291, 1161, 1022, 734, 13431, 13, 198, 37811, 198, 6738, 552, 292, 13, 469, 15748, 1330, 25184, 198, 6738, 552, 292, 13, 469, 15748, 1330, 6252, 198, 6738, 552, 292, 13, 469, 15748, 1330, 49127, 198, 198, 37, 16, 796, 25184, ...
2.85625
160
import os
[ 11748, 28686, 628, 628, 628 ]
3
5
import torch from torch import nn from torchvision import transforms from .faster_rcnn import FasterRCNN from ..builder import DETECTORS from PIL import Image import numpy as np @DETECTORS.register_module()
[ 11748, 28034, 198, 6738, 28034, 1330, 299, 77, 198, 6738, 28034, 10178, 1330, 31408, 198, 198, 6738, 764, 69, 1603, 62, 6015, 20471, 1330, 38996, 7397, 6144, 198, 6738, 11485, 38272, 1330, 38267, 9782, 20673, 198, 6738, 350, 4146, 1330, ...
3.525424
59
from django.conf.urls import url from . import views from django.conf import settings from django.conf.urls.static import static urlpatterns=[ url('^$',views.login_page,name = 'come'), url(r'^new/profile$', views.profile, name='profile'), url(r'^user/', views.user, name='user'), url(r'^search/', views.search_results, name='search_results'), url(r'^new/article$', views.new_article, name='new-article'), url(r'^home/', views.home, name='home'), url(r'^comment/', views.comment, name='comment'), ] if settings.DEBUG: urlpatterns+= static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
[ 6738, 42625, 14208, 13, 10414, 13, 6371, 82, 1330, 19016, 198, 6738, 764, 1330, 5009, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 6738, 42625, 14208, 13, 10414, 13, 6371, 82, 13, 12708, 1330, 9037, 628, 198, 6371, 33279, 82, ...
2.627049
244
# Import ROS2 libraries import rclpy from rclpy.node import Node from rclpy.action import ActionClient, ActionServer, GoalResponse, CancelResponse from rclpy.qos import QoSProfile from rclpy.callback_groups import ReentrantCallbackGroup from rclpy.executors import MultiThreadedExecutor # Import message files from geometry_msgs.msg import PoseStamped from nav_msgs.msg import OccupancyGrid as OccG from nav_msgs.msg import Odometry from nav2_msgs.action import NavigateToPose from tf2_msgs.msg import TFMessage from autonomous_exploration_msgs.msg import ExplorationTargets, ExplorationTarget, PosData from autonomous_exploration_msgs.action import AutonomousExplorationAction # Import other libraries import numpy as np import time ################################################################################################### if __name__ == '__main__': main()
[ 2, 17267, 48263, 17, 12782, 198, 11748, 374, 565, 9078, 198, 6738, 374, 565, 9078, 13, 17440, 1330, 19081, 198, 6738, 374, 565, 9078, 13, 2673, 1330, 7561, 11792, 11, 7561, 10697, 11, 25376, 31077, 11, 27910, 31077, 198, 6738, 374, 56...
3.837719
228
from abc import ABC, abstractmethod from enum import Enum from typing import Optional, Union, Iterable, NoReturn try: # Assume we're a sub-module in a package. from utils import arguments as arg from base.abstract.tree_item import TreeInterface from loggers.extended_logger_interface import ExtendedLoggerInterface except ImportError: # Apparently no higher-level package has been imported, fall back to a local import. from ..utils import arguments as arg from ..base.abstract.tree_item import TreeInterface from .extended_logger_interface import ExtendedLoggerInterface Logger = Union[ExtendedLoggerInterface, arg.DefaultArgument]
[ 6738, 450, 66, 1330, 9738, 11, 12531, 24396, 198, 6738, 33829, 1330, 2039, 388, 198, 6738, 19720, 1330, 32233, 11, 4479, 11, 40806, 540, 11, 1400, 13615, 198, 198, 28311, 25, 220, 1303, 2195, 2454, 356, 821, 257, 850, 12, 21412, 287, ...
3.622951
183
import sys import math BASE=20 Sym2Base={} Base2Sym={} l, h = [int(i) for i in input().split()] for i in range(h): numeral=input() for j in range(BASE): idx=l*j STR=numeral[idx:idx+l] if j in Base2Sym: Base2Sym[j]+=[STR] else: Base2Sym[j]=[STR] for key,value in Base2Sym.items(): Sym2Base[''.join(value)]=key ######################################## N1_sym=[] N2_sym=[] s1 = int(int(input())/h) for i in range(s1): N1_sym.append(''.join([input() for i in range(h)])) s2 = int(int(input())/h) for i in range(s2): N2_sym.append(''.join([input() for i in range(h)])) ######################################### N1=0 N2=0 for i in N1_sym: N1=N1*20+Sym2Base[i] for i in N2_sym: N2=N2*20+Sym2Base[i] ######################################### operation = input() if operation=='+': result=N1+N2 elif operation=='*': result=N1*N2 elif operation=='-': result=N1-N2 elif operation=='/': result=N1/N2 result_Base=[] if result==0: result_Base.append(0) while not(result/BASE==0): result_Base.append(result % BASE) result=int(result/BASE) result_Base.reverse() for i in result_Base: for j in Base2Sym[i]: print(j)
[ 11748, 25064, 198, 11748, 10688, 198, 198, 33, 11159, 28, 1238, 198, 43094, 17, 14881, 34758, 92, 198, 14881, 17, 43094, 34758, 92, 198, 198, 75, 11, 289, 796, 685, 600, 7, 72, 8, 329, 1312, 287, 5128, 22446, 35312, 3419, 60, 198, ...
2.149047
577
import os import shutil import zipfile import urllib import xml.etree.ElementTree as ET import numpy as np import csv import pandas # from google.colab import drive # from google.colab import files # %matplotlib inline # # automatically reload modules when they have changed # %reload_ext autoreload # %autoreload 2 # # import keras import keras # import keras_retinanet from keras_retinanet import models from keras_retinanet.utils.image import read_image_bgr, preprocess_image, resize_image from keras_retinanet.utils.visualization import draw_box, draw_caption from keras_retinanet.utils.colors import label_color # import miscellaneous modules import matplotlib.pyplot as plt import cv2 import os import numpy as np import time # set tf backend to allow memory to grow, instead of claiming everything import tensorflow as tf import json import os import pickle as pkl import Save_solar import shutil solar_detection(images_path = './keras-retinanet/7fc8992d8a_012288112DOPENPIPELINE_Orthomosaic_export_FriNov22014645.383588.jpg') Save_solar.save_json('./list_bb.json')
[ 11748, 28686, 198, 11748, 4423, 346, 198, 11748, 19974, 7753, 198, 11748, 2956, 297, 571, 198, 11748, 35555, 13, 316, 631, 13, 20180, 27660, 355, 12152, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 269, 21370, 198, 11748, 19798, 292, ...
3.002778
360
"""Clean Code in Python - Chapter 6: Descriptors > A Pythonic Implementation """ class HistoryTracedAttribute: """Trace the values of this attribute into another one given by the name at ``trace_attribute_name``. """ def _needs_to_track_change(self, instance, value) -> bool: """Determine if the value change needs to be traced or not. Rules for adding a value to the trace: * If the value is not previously set (it's the first one). * If the new value is != than the current one. """ try: current_value = instance.__dict__[self._name] except KeyError: return True return value != current_value class Traveller: """A person visiting several cities. We wish to track the path of the traveller, as he or she is visiting each new city. >>> alice = Traveller("Alice", "Barcelona") >>> alice.current_city = "Paris" >>> alice.current_city = "Brussels" >>> alice.current_city = "Amsterdam" >>> alice.cities_visited ['Barcelona', 'Paris', 'Brussels', 'Amsterdam'] >>> alice.current_city 'Amsterdam' >>> alice.current_city = "Amsterdam" >>> alice.cities_visited ['Barcelona', 'Paris', 'Brussels', 'Amsterdam'] >>> bob = Traveller("Bob", "Rotterdam") >>> bob.current_city = "Amsterdam" >>> bob.current_city 'Amsterdam' >>> bob.cities_visited ['Rotterdam', 'Amsterdam'] """ current_city = HistoryTracedAttribute("cities_visited")
[ 37811, 32657, 6127, 287, 11361, 532, 7006, 718, 25, 2935, 6519, 669, 198, 198, 29, 317, 11361, 291, 46333, 198, 198, 37811, 628, 198, 4871, 7443, 2898, 2286, 33682, 25, 198, 220, 220, 220, 37227, 2898, 558, 262, 3815, 286, 428, 11688,...
2.660312
577
"""Retrieve data from PyPI.""" from distutils.version import LooseVersion from logging import getLogger import xmlrpclib from flask.ext.celery import single_instance from pypi_portal.extensions import celery, db, redis from pypi_portal.models.pypi import Package from pypi_portal.models.redis import POLL_SIMPLE_THROTTLE LOG = getLogger(__name__) THROTTLE = 1 * 60 * 60 @celery.task(bind=True, soft_time_limit=120) @single_instance def update_package_list(): """Get a list of all packages from PyPI through their XMLRPC API. This task returns something in case the user schedules it from a view. The view can wait up to a certain amount of time for this task to finish, and if nothing times out, it can tell the user if it found any new packages. Since views can schedule this task, we don't want some rude person hammering PyPI or our application with repeated requests. This task is limited to one run per 1 hour at most. Returns: List of new packages found. Returns None if task is rate-limited. """ # Rate limit. lock = redis.lock(POLL_SIMPLE_THROTTLE, timeout=int(THROTTLE)) have_lock = lock.acquire(blocking=False) if not have_lock: LOG.warning('poll_simple() task has already executed in the past 4 hours. Rate limiting.') return None # Query API. client = xmlrpclib.ServerProxy('https://pypi.python.org/pypi') results = client.search(dict(summary='')) if not results: LOG.error('Reply from API had no results.') return list() LOG.debug('Sorting results.') results.sort(key=lambda x: (x['name'], LooseVersion(x['version']))) filtered = (r for r in results if r['version'][0].isdigit()) packages = {r['name']: dict(summary=r['summary'], version=r['version'], id=0) for r in filtered} LOG.debug('Pruning unchanged packages.') for row in db.session.query(Package.id, Package.name, Package.summary, Package.latest_version): if packages.get(row[1]) == dict(summary=row[2], version=row[3], id=0): packages.pop(row[1]) elif row[1] in packages: packages[row[1]]['id'] = row[0] new_package_names = {n for n, d in packages.items() if not d['id']} # Merge into database. LOG.debug('Found {} new packages in PyPI, updating {} total.'.format(len(new_package_names), len(packages))) with db.session.begin_nested(): for name, data in packages.items(): db.session.merge(Package(id=data['id'], name=name, summary=data['summary'], latest_version=data['version'])) db.session.commit() return list(new_package_names)
[ 37811, 9781, 30227, 1366, 422, 9485, 11901, 526, 15931, 198, 198, 6738, 1233, 26791, 13, 9641, 1330, 6706, 577, 14815, 198, 6738, 18931, 1330, 651, 11187, 1362, 198, 11748, 35555, 81, 79, 565, 571, 198, 198, 6738, 42903, 13, 2302, 13, ...
2.794243
938
# Project Quex (http://quex.sourceforge.net); License: MIT; # (C) 2005-2020 Frank-Rene Schaefer; #_______________________________________________________________________________ import quex.output.core.state.core as state_coder import quex.output.core.state.entry as entry import quex.output.core.mega_state.core as mega_state_coder from quex.blackboard import Lng from collections import defaultdict from copy import copy def do(TheAnalyzer): """Generate source code for a given state machine 'SM'. """ Lng.register_analyzer(TheAnalyzer) assert id(Lng.analyzer) == id(TheAnalyzer) # (*) Init State must be first! txt = [] state_coder.do(txt, TheAnalyzer.state_db[TheAnalyzer.init_state_index], TheAnalyzer) # (*) Second: The drop-out catcher, since it is referenced the most. # (Is implemented entirely by 'entry') code_drop_out_catcher(txt, TheAnalyzer) # (*) Code the Mega States (implementing multiple states in one) for state in TheAnalyzer.mega_state_list: mega_state_coder.do(txt, state, TheAnalyzer) # (*) All other (normal) states (sorted by their frequency of appearance) for state in remaining_non_mega_state_iterable(TheAnalyzer): state_coder.do(txt, state, TheAnalyzer) Lng.unregister_analyzer() return txt def get_frequency_db(StateDB, RemainderStateIndexList): """Sort the list in a away, so that states that are used more often appear earlier. This happens in the hope of more cache locality. """ # Count number of transitions to a state: frequency_db frequency_db = defaultdict(int) for state in (StateDB[i] for i in RemainderStateIndexList): assert state.transition_map is not None for interval, target_index in state.transition_map: frequency_db[target_index] += 1 return frequency_db
[ 2, 4935, 4670, 87, 357, 4023, 1378, 421, 1069, 13, 10459, 30293, 13, 3262, 1776, 13789, 25, 17168, 26, 198, 2, 357, 34, 8, 5075, 12, 42334, 5278, 12, 49, 1734, 35756, 41027, 26, 220, 198, 2, 27193, 2602, 37405, 198, 11748, 627, 10...
2.765805
696
# python-3 # coding: utf-8 ''' Script Name: BuildConsolidatedFeaturesFile.py Created date : Sunday, 27th March Author : Sreejith Menon Description : buildFeatureFl(input file,output file) Reads from a csv file (taken as a parameter) containing a list of image GIDs. Extracts the below features from the IBEIS dataset: 1. nid 2. names 3. species_texts 4. sex_texts 5. age_months_est 6. exemplar_flags 7. quality_texts Outputs 3 files in the same directory as the outFL directory File 1 : Map of all images and their annotation IDs (csv) File 2 : Annotation ID's and their features (csv) File 3 : Image GID, annotation ID's and their features (csv) File 4 : Image GID, annotation ID's and their features (json) ''' from __future__ import print_function import GetPropertiesAPI as GP import importlib, json, re, sys, csv, time, math # importlib.reload(GP) # un-comment if there are any changes made to API import pandas as pd # import DataStructsHelperAPI as DS from math import floor # importlib.reload(GP) from multiprocessing import Process import DataStructsHelperAPI as DS # Original Microsoft Tagging API output is a R list, # This method parses the data into python readable form and dumps the output into a JSON. ''' Logic for reading data from the consolidatedHITResults file - changed The input for the below method will be a csv file/list with all the image GID's for which the features have to be extracted. ''' # these APIs require encoded annot_uuid_list ggr_eco_ftr_api_map = {'age': "/api/annot/age/months/json", 'sex': "/api/annot/sex/text/json", 'bbox': "/api/annot/bbox/json", 'nid': "/api/annot/name/rowid/json", 'exemplar': "/api/annot/exemplar/json", 'species': "/api/annot/species/json", 'quality': "/api/annot/quality/text/json", 'view_point': "/api/annot/yaw/text/json" } # these APIs takes in an encoded gid list ggr_otr_ftr_api_map = {'contributor': "/api/image/note", 'lat': "/api/image/lat", 'long': "/api/image/lon", 'datetime': "/api/image/unixtime", 'width': "/api/image/width", 'height': "/api/image/height", 'orientation': "/api/image/orientation" } if __name__ == "__main__": gids = list(map(str, list(range(1, 1862)))) buildFeatureFl(gids, "../data/Flickr_IBEIS_Giraffe_Ftrs.csv", False) # __main__() # gidAidMapFl = "../data/full_gid_aid_map.json" # getAdditionalAnnotFeatures(gidAidMapFl,'bbox',"../data/gid_bbox.json") # buildBeautyFtrFl("../data/beautyFeatures_GZC_R.csv",['GID','pleasure','arousal','dominance','y'],"../data/beautyFeatures_GZC") # DS.combineJson("../data/beautyFeatures_GZC.json","../data/imgs_exif_data_full.json","../data/GZC_exifs_beauty_full.json") # p1 = Process(target=build_exif_ftrs_fl_ggr, args=("uuid_gid_map.json", "ggr_uuid_list.dat", "ggr_exif_extract_1.json",1,5000)) # p2 = Process(target=build_exif_ftrs_fl_ggr, args=("uuid_gid_map.json", "ggr_uuid_list.dat", "ggr_exif_extract_2.json",5001,10000)) # p3 = Process(target=build_exif_ftrs_fl_ggr, args=("uuid_gid_map.json", "ggr_uuid_list.dat", "ggr_exif_extract_3.json",10001,15000)) # p4 = Process(target=build_exif_ftrs_fl_ggr, args=("uuid_gid_map.json", "ggr_uuid_list.dat", "ggr_exif_extract_4.json",15001,20000)) # p5 = Process(target=build_exif_ftrs_fl_ggr, args=("uuid_gid_map.json", "ggr_uuid_list.dat", "ggr_exif_extract_5.json",20001,25000)) # p6 = Process(target=build_exif_ftrs_fl_ggr, args=("uuid_gid_map.json", "ggr_uuid_list.dat", "ggr_exif_extract_6.json",25001,30000)) # p7 = Process(target=build_exif_ftrs_fl_ggr, args=("uuid_gid_map.json", "ggr_uuid_list.dat", "ggr_exif_extract_7.json",30001,35000)) # p8 = Process(target=build_exif_ftrs_fl_ggr, args=("uuid_gid_map.json", "ggr_uuid_list.dat", "ggr_exif_extract_8.json",35001,37433)) # p9 = Process(target=build_feature_file_ggr, args=("uuid_gid_map.json", "ggr_ftr_extract_1",1,5000)) # p10 = Process(target=build_feature_file_ggr, args=("uuid_gid_map.json", "ggr_ftr_extract_2",5001,10000)) # p11 = Process(target=build_feature_file_ggr, args=("uuid_gid_map.json", "ggr_ftr_extract_3",10001,15000)) # p12 = Process(target=build_feature_file_ggr, args=("uuid_gid_map.json", "ggr_ftr_extract_4",15001,20000)) # p13 = Process(target=build_feature_file_ggr, args=("uuid_gid_map.json", "ggr_ftr_extract_5",20001,25000)) # p14 = Process(target=build_feature_file_ggr, args=("uuid_gid_map.json", "ggr_ftr_extract_6",25001,30000)) # p15 = Process(target=build_feature_file_ggr, args=("uuid_gid_map.json", "ggr_ftr_extract_7",30001,35000)) # p16 = Process(target=build_feature_file_ggr, args=("uuid_gid_map.json", "ggr_ftr_extract_8",35001,37433)) # p1 = Process(target=test, args=(0, 400, "/tmp/test1.json")) # p2 = Process(target=test, args=(400, 800, "/tmp/test2.json")) # p3 = Process(target=test, args=(800, 1200, "/tmp/test3.json")) # p4 = Process(target=test, args=(1200, 1600, "/tmp/test4.json")) # p5 = Process(target=test, args=(1600, 2000, "/tmp/test5.json")) # p6 = Process(target=test, args=(2000, 2400, "/tmp/test6.json")) # p7 = Process(target=test, args=(2400, 2800, "/tmp/test7.json")) # p8 = Process(target=test, args=(2800, 3200, "/tmp/test8.json")) # p9 = Process(target=test, args=(3200, 3600, "/tmp/test9.json")) # p10 = Process(target=test, args=(3600, 4033, "/tmp/test10.json")) # p1.start() # p2.start() # p3.start() # p4.start() # p5.start() # p6.start() # p7.start() # p8.start() # p9.start() # p10.start() # # p11.start() # # p12.start() # # p13.start() # # p14.start() # # p15.start() # # p16.start()
[ 2, 21015, 12, 18, 198, 2, 19617, 25, 3384, 69, 12, 23, 198, 7061, 6, 198, 7391, 6530, 25, 10934, 9444, 10180, 515, 23595, 8979, 13, 9078, 198, 198, 41972, 3128, 1058, 3502, 11, 2681, 400, 2805, 198, 198, 13838, 1058, 311, 631, 73,...
2.275402
2,549
# TODO import subprocess import sys import os import re from glob import glob try: from PySide2.QtWidgets import * from PySide2.QtGui import * from PySide2.QtCore import * except: from PySide.QtGui import * from PySide.QtCore import *
[ 2, 16926, 46, 220, 198, 198, 11748, 850, 14681, 198, 11748, 25064, 198, 11748, 28686, 198, 11748, 302, 198, 6738, 15095, 1330, 15095, 198, 198, 28311, 25, 198, 220, 220, 220, 422, 9485, 24819, 17, 13, 48, 83, 54, 312, 11407, 1330, 1...
2.409091
110
# /usr/bin/env python3.6 # -*- mode: python -*- # ============================================================================= # @@-COPYRIGHT-START-@@ # # Copyright (c) 2021, Qualcomm Innovation Center, Inc. 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. # # SPDX-License-Identifier: BSD-3-Clause # # @@-COPYRIGHT-END-@@ # ============================================================================= """ AdaRound Nightly Tests """ import pytest import json import unittest import logging import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' import numpy as np import tensorflow as tf from tensorflow.keras.applications.mobilenet import MobileNet from packaging import version from aimet_common.utils import AimetLogger from aimet_common.defs import QuantScheme from aimet_tensorflow.examples.test_models import keras_model from aimet_tensorflow.quantsim import QuantizationSimModel from aimet_tensorflow.adaround.adaround_weight import Adaround, AdaroundParameters tf.compat.v1.disable_eager_execution() class AdaroundAcceptanceTests(unittest.TestCase): """ AdaRound test cases """ @pytest.mark.cuda def test_adaround_mobilenet_only_weights(self): """ test end to end adaround with only weight quantized """ def dummy_forward_pass(session: tf.compat.v1.Session): """ Dummy forward pass """ input_data = np.random.rand(1, 224, 224, 3) input_tensor = session.graph.get_tensor_by_name('input_1:0') output_tensor = session.graph.get_tensor_by_name('conv_preds/BiasAdd:0') output = session.run(output_tensor, feed_dict={input_tensor: input_data}) return output AimetLogger.set_level_for_all_areas(logging.DEBUG) tf.compat.v1.reset_default_graph() _ = MobileNet(weights=None, input_shape=(224, 224, 3)) init = tf.compat.v1.global_variables_initializer() dataset_size = 128 batch_size = 64 possible_batches = dataset_size // batch_size input_data = np.random.rand(dataset_size, 224, 224, 3) dataset = tf.data.Dataset.from_tensor_slices(input_data) dataset = dataset.batch(batch_size=batch_size) session = tf.compat.v1.Session(graph=tf.compat.v1.get_default_graph()) session.run(init) params = AdaroundParameters(data_set=dataset, num_batches=possible_batches, default_num_iterations=1, default_reg_param=0.01, default_beta_range=(20, 2), default_warm_start=0.2) starting_op_names = ['input_1'] if version.parse(tf.version.VERSION) >= version.parse("2.00"): output_op_names = ['predictions/Softmax'] else: output_op_names = ['act_softmax/Softmax'] adarounded_session = Adaround.apply_adaround(session, starting_op_names, output_op_names, params, path='./', filename_prefix='mobilenet', default_param_bw=4, default_quant_scheme=QuantScheme.post_training_tf_enhanced) orig_output = dummy_forward_pass(session) adarounded_output = dummy_forward_pass(adarounded_session) self.assertEqual(orig_output.shape, adarounded_output.shape) # Test exported encodings JSON file with open('./mobilenet.encodings') as json_file: encoding_data = json.load(json_file) print(encoding_data) self.assertTrue(isinstance(encoding_data["conv1/Conv2D/ReadVariableOp:0"], list)) session.close() adarounded_session.close() # Delete encodings JSON file if os.path.exists("./mobilenet.encodings"): os.remove("./mobilenet.encodings") def test_adaround_resnet18_followed_by_quantsim(self): """ test end to end adaround with weight 4 bits and output activations 8 bits quantized """ def dummy_forward_pass(session: tf.compat.v1.Session, _): """ Dummy forward pass """ input_data = np.random.rand(32, 16, 16, 3) input_tensor = session.graph.get_tensor_by_name('conv2d_input:0') output_tensor = session.graph.get_tensor_by_name('keras_model/Softmax:0') output = session.run(output_tensor, feed_dict={input_tensor: input_data}) return output np.random.seed(1) AimetLogger.set_level_for_all_areas(logging.DEBUG) tf.compat.v1.reset_default_graph() _ = keras_model() init = tf.compat.v1.global_variables_initializer() dataset_size = 32 batch_size = 16 possible_batches = dataset_size // batch_size input_data = np.random.rand(dataset_size, 16, 16, 3) dataset = tf.data.Dataset.from_tensor_slices(input_data) dataset = dataset.batch(batch_size=batch_size) session = tf.compat.v1.Session(graph=tf.compat.v1.get_default_graph()) session.run(init) params = AdaroundParameters(data_set=dataset, num_batches=possible_batches, default_num_iterations=10) starting_op_names = ['conv2d_input'] output_op_names = ['keras_model/Softmax'] # W4A8 param_bw = 4 output_bw = 8 quant_scheme = QuantScheme.post_training_tf_enhanced adarounded_session = Adaround.apply_adaround(session, starting_op_names, output_op_names, params, path='./', filename_prefix='dummy', default_param_bw=param_bw, default_quant_scheme=quant_scheme, default_config_file=None) # Read exported param encodings JSON file with open('./dummy.encodings') as json_file: encoding_data = json.load(json_file) encoding = encoding_data["conv2d/Conv2D/ReadVariableOp:0"][0] before_min, before_max, before_delta, before_offset = encoding.get('min'), encoding.get('max'), \ encoding.get('scale'), encoding.get('offset') print(before_min, before_max, before_delta, before_offset) # Create QuantSim using adarounded_model, set and freeze parameter encodings and then invoke compute_encodings sim = QuantizationSimModel(adarounded_session, starting_op_names, output_op_names, quant_scheme, default_output_bw=output_bw, default_param_bw=param_bw, use_cuda=False) sim.set_and_freeze_param_encodings(encoding_path='./dummy.encodings') sim.compute_encodings(dummy_forward_pass, None) quantizer = sim.quantizer_config('conv2d/Conv2D/ReadVariableOp_quantized') encoding = quantizer.get_encoding() after_min, after_max, after_delta, after_offset = encoding.min, encoding.max, encoding.delta, encoding.offset print(after_min, after_max, after_delta, after_offset) self.assertEqual(before_min, after_min) self.assertEqual(before_max, after_max) self.assertAlmostEqual(before_delta, after_delta, places=4) self.assertEqual(before_offset, after_offset) session.close() adarounded_session.close() # Delete encodings file if os.path.exists("./dummy.encodings"): os.remove("./dummy.encodings")
[ 2, 1220, 14629, 14, 8800, 14, 24330, 21015, 18, 13, 21, 198, 2, 532, 9, 12, 4235, 25, 21015, 532, 9, 12, 198, 2, 38093, 25609, 198, 2, 220, 25248, 12, 34, 3185, 38162, 9947, 12, 2257, 7227, 12, 12404, 198, 2, 198, 2, 220, 1506...
2.415177
3,637
import unittest import logging logging.basicConfig(level=logging.CRITICAL) from aoc2019 import Amplifier
[ 11748, 555, 715, 395, 201, 198, 11748, 18931, 201, 198, 6404, 2667, 13, 35487, 16934, 7, 5715, 28, 6404, 2667, 13, 9419, 2043, 20151, 8, 201, 198, 6738, 257, 420, 23344, 1330, 44074, 7483, 201 ]
3.085714
35
import time from selenium import webdriver import json from crawlpack.helpers import id_gen, connect chrome_options = webdriver.ChromeOptions() chrome_options.add_experimental_option( "prefs",{'profile.managed_default_content_settings.javascript': 2}) driver = webdriver.Chrome(chrome_options=chrome_options) conn, cur = connect() for count in range(1,89): try: url = "file:///home/Desktop/crawler%20scripts/scripts/uber_eats/page_source"+str(count)+".html" driver.get(url) raw_title = driver.find_element_by_xpath('//*[@id="app-content"]/div/div/div[1]/div/div[1]/div[2]/div/div[2]/div/div/h1').text try: split_title = raw_title.split('-') rest_name = split_title[0].strip() location = split_title[1].strip() except: rest_name = raw_title location = "Bangalore" dedupe_id = id_gen(rest_name,location) items = driver.find_elements_by_css_selector('#app-content>div>div>div:nth-child(1)>div>div:nth-child(1)>div:nth-child(2)>div>div:nth-child(3)>div:nth-child(2)>div:nth-child(1)>div>div:nth-child(2)>div>div>div>div:nth-child(1)>div:nth-child(1)') prices = driver.find_elements_by_css_selector('#app-content>div>div>div:nth-child(1)>div>div:nth-child(1)>div:nth-child(2)>div>div:nth-child(3)>div:nth-child(2)>div:nth-child(1)>div>div:nth-child(2)>div>div>div>div:nth-child(1)>div:nth-child(3)>span:nth-child(1)') items_final = {} num_items = len(items) for i in range(0,num_items): item_price = prices[i].text.replace("INR","") item_name = items[i].text items_final[item_name] = item_price items_json = json.dumps(items_final) cur.execute("""INSERT INTO uber_eats2 (name,location,items) VALUES (%s,%s,%s)""",(rest_name,location,items_json)) conn.commit() print("Crawled {0}/88 Restaurant: {1} Items: {2}".format(count,rest_name,str(len(items_final)))) except: print("error ",url)
[ 11748, 640, 198, 6738, 384, 11925, 1505, 1330, 3992, 26230, 198, 11748, 33918, 198, 6738, 27318, 8002, 13, 16794, 364, 1330, 4686, 62, 5235, 11, 2018, 628, 198, 198, 46659, 62, 25811, 796, 3992, 26230, 13, 1925, 5998, 29046, 3419, 198, ...
2.143617
940
from .DepthNet import DepthNet from .MotionNet import MotionNet
[ 6738, 764, 48791, 7934, 1330, 36350, 7934, 198, 6738, 764, 45740, 7934, 1330, 20843, 7934, 198 ]
4
16
from django.test import TestCase from .models import Image, Profile # Create your tests here.
[ 6738, 42625, 14208, 13, 9288, 1330, 6208, 20448, 198, 6738, 764, 27530, 1330, 7412, 11, 13118, 198, 198, 2, 13610, 534, 5254, 994, 13, 198 ]
3.8
25
# # PySNMP MIB module NBS-SIGLANE-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NBS-SIGLANE-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 20:07:45 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # Integer, ObjectIdentifier, OctetString = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueRangeConstraint, ConstraintsIntersection, ConstraintsUnion, ValueSizeConstraint, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ConstraintsIntersection", "ConstraintsUnion", "ValueSizeConstraint", "SingleValueConstraint") InterfaceIndex, = mibBuilder.importSymbols("IF-MIB", "InterfaceIndex") NbsCmmcChannelBand, = mibBuilder.importSymbols("NBS-CMMCENUM-MIB", "NbsCmmcChannelBand") NbsTcMicroAmp, NbsTcMHz, NbsTcTemperature, NbsTcMilliDb, nbs = mibBuilder.importSymbols("NBS-MIB", "NbsTcMicroAmp", "NbsTcMHz", "NbsTcTemperature", "NbsTcMilliDb", "nbs") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") MibScalar, MibTable, MibTableRow, MibTableColumn, Counter64, Unsigned32, ModuleIdentity, ObjectIdentity, Bits, Gauge32, iso, TimeTicks, IpAddress, Integer32, MibIdentifier, NotificationType, Counter32 = mibBuilder.importSymbols("SNMPv2-SMI", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Counter64", "Unsigned32", "ModuleIdentity", "ObjectIdentity", "Bits", "Gauge32", "iso", "TimeTicks", "IpAddress", "Integer32", "MibIdentifier", "NotificationType", "Counter32") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") nbsSigLaneMib = ModuleIdentity((1, 3, 6, 1, 4, 1, 629, 236)) if mibBuilder.loadTexts: nbsSigLaneMib.setLastUpdated('201503120000Z') if mibBuilder.loadTexts: nbsSigLaneMib.setOrganization('NBS') nbsSigLanePortGrp = ObjectIdentity((1, 3, 6, 1, 4, 1, 629, 236, 10)) if mibBuilder.loadTexts: nbsSigLanePortGrp.setStatus('current') nbsSigLaneLaneGrp = ObjectIdentity((1, 3, 6, 1, 4, 1, 629, 236, 20)) if mibBuilder.loadTexts: nbsSigLaneLaneGrp.setStatus('current') nbsSigLaneTraps = ObjectIdentity((1, 3, 6, 1, 4, 1, 629, 236, 100)) if mibBuilder.loadTexts: nbsSigLaneTraps.setStatus('current') nbsSigLaneTraps0 = ObjectIdentity((1, 3, 6, 1, 4, 1, 629, 236, 100, 0)) if mibBuilder.loadTexts: nbsSigLaneTraps0.setStatus('current') nbsSigLanePortTable = MibTable((1, 3, 6, 1, 4, 1, 629, 236, 10, 1), ) if mibBuilder.loadTexts: nbsSigLanePortTable.setStatus('current') nbsSigLanePortEntry = MibTableRow((1, 3, 6, 1, 4, 1, 629, 236, 10, 1, 1), ).setIndexNames((0, "NBS-SIGLANE-MIB", "nbsSigLanePortIfIndex")) if mibBuilder.loadTexts: nbsSigLanePortEntry.setStatus('current') nbsSigLanePortIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 629, 236, 10, 1, 1, 1), InterfaceIndex()).setMaxAccess("readonly") if mibBuilder.loadTexts: nbsSigLanePortIfIndex.setStatus('current') nbsSigLanePortFacility = MibTableColumn((1, 3, 6, 1, 4, 1, 629, 236, 10, 1, 1, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("other", 1), ("fiber", 2), ("lambda", 3)))).setMaxAccess("readonly") if mibBuilder.loadTexts: nbsSigLanePortFacility.setStatus('current') nbsSigLanePortLanes = MibTableColumn((1, 3, 6, 1, 4, 1, 629, 236, 10, 1, 1, 20), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: nbsSigLanePortLanes.setStatus('current') nbsSigLaneLaneTable = MibTable((1, 3, 6, 1, 4, 1, 629, 236, 20, 1), ) if mibBuilder.loadTexts: nbsSigLaneLaneTable.setStatus('current') nbsSigLaneLaneEntry = MibTableRow((1, 3, 6, 1, 4, 1, 629, 236, 20, 1, 1), ).setIndexNames((0, "NBS-SIGLANE-MIB", "nbsSigLaneLaneIfIndex"), (0, "NBS-SIGLANE-MIB", "nbsSigLaneLaneIndex")) if mibBuilder.loadTexts: nbsSigLaneLaneEntry.setStatus('current') nbsSigLaneLaneIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 629, 236, 20, 1, 1, 1), InterfaceIndex()).setMaxAccess("readonly") if mibBuilder.loadTexts: nbsSigLaneLaneIfIndex.setStatus('current') nbsSigLaneLaneIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 629, 236, 20, 1, 1, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: nbsSigLaneLaneIndex.setStatus('current') nbsSigLaneLaneFrequency = MibTableColumn((1, 3, 6, 1, 4, 1, 629, 236, 20, 1, 1, 10), NbsTcMHz()).setMaxAccess("readonly") if mibBuilder.loadTexts: nbsSigLaneLaneFrequency.setStatus('current') nbsSigLaneLaneWavelengthX = MibTableColumn((1, 3, 6, 1, 4, 1, 629, 236, 20, 1, 1, 11), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(4, 8))).setMaxAccess("readonly") if mibBuilder.loadTexts: nbsSigLaneLaneWavelengthX.setStatus('current') nbsSigLaneLaneChannelBand = MibTableColumn((1, 3, 6, 1, 4, 1, 629, 236, 20, 1, 1, 12), NbsCmmcChannelBand()).setMaxAccess("readonly") if mibBuilder.loadTexts: nbsSigLaneLaneChannelBand.setStatus('current') nbsSigLaneLaneChannelNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 629, 236, 20, 1, 1, 13), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: nbsSigLaneLaneChannelNumber.setStatus('current') nbsSigLaneLaneTxPowerLevel = MibTableColumn((1, 3, 6, 1, 4, 1, 629, 236, 20, 1, 1, 20), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6))).clone(namedValues=NamedValues(("notSupported", 1), ("lowAlarm", 2), ("lowWarning", 3), ("ok", 4), ("highWarning", 5), ("highAlarm", 6))).clone('ok')).setMaxAccess("readonly") if mibBuilder.loadTexts: nbsSigLaneLaneTxPowerLevel.setStatus('current') nbsSigLaneLaneTxPower = MibTableColumn((1, 3, 6, 1, 4, 1, 629, 236, 20, 1, 1, 21), NbsTcMilliDb().clone(-2147483648)).setMaxAccess("readonly") if mibBuilder.loadTexts: nbsSigLaneLaneTxPower.setStatus('current') nbsSigLaneLaneRxPowerLevel = MibTableColumn((1, 3, 6, 1, 4, 1, 629, 236, 20, 1, 1, 30), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6))).clone(namedValues=NamedValues(("notSupported", 1), ("lowAlarm", 2), ("lowWarning", 3), ("ok", 4), ("highWarning", 5), ("highAlarm", 6))).clone('ok')).setMaxAccess("readonly") if mibBuilder.loadTexts: nbsSigLaneLaneRxPowerLevel.setStatus('current') nbsSigLaneLaneRxPower = MibTableColumn((1, 3, 6, 1, 4, 1, 629, 236, 20, 1, 1, 31), NbsTcMilliDb().clone(-2147483648)).setMaxAccess("readonly") if mibBuilder.loadTexts: nbsSigLaneLaneRxPower.setStatus('current') nbsSigLaneLaneBiasAmpsLevel = MibTableColumn((1, 3, 6, 1, 4, 1, 629, 236, 20, 1, 1, 40), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6))).clone(namedValues=NamedValues(("notSupported", 1), ("lowAlarm", 2), ("lowWarning", 3), ("ok", 4), ("highWarning", 5), ("highAlarm", 6))).clone('ok')).setMaxAccess("readonly") if mibBuilder.loadTexts: nbsSigLaneLaneBiasAmpsLevel.setStatus('current') nbsSigLaneLaneBiasAmps = MibTableColumn((1, 3, 6, 1, 4, 1, 629, 236, 20, 1, 1, 41), NbsTcMicroAmp().clone(-1)).setMaxAccess("readonly") if mibBuilder.loadTexts: nbsSigLaneLaneBiasAmps.setStatus('current') nbsSigLaneLaneLaserTempLevel = MibTableColumn((1, 3, 6, 1, 4, 1, 629, 236, 20, 1, 1, 50), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6))).clone(namedValues=NamedValues(("notSupported", 1), ("lowAlarm", 2), ("lowWarning", 3), ("ok", 4), ("highWarning", 5), ("highAlarm", 6))).clone('ok')).setMaxAccess("readonly") if mibBuilder.loadTexts: nbsSigLaneLaneLaserTempLevel.setStatus('current') nbsSigLaneLaneLaserTemp = MibTableColumn((1, 3, 6, 1, 4, 1, 629, 236, 20, 1, 1, 51), NbsTcTemperature().clone(-2147483648)).setMaxAccess("readonly") if mibBuilder.loadTexts: nbsSigLaneLaneLaserTemp.setStatus('current') mibBuilder.exportSymbols("NBS-SIGLANE-MIB", nbsSigLanePortEntry=nbsSigLanePortEntry, nbsSigLaneLaneLaserTempLevel=nbsSigLaneLaneLaserTempLevel, nbsSigLanePortTable=nbsSigLanePortTable, nbsSigLaneLaneEntry=nbsSigLaneLaneEntry, nbsSigLaneTraps0=nbsSigLaneTraps0, nbsSigLaneMib=nbsSigLaneMib, PYSNMP_MODULE_ID=nbsSigLaneMib, nbsSigLaneLaneIfIndex=nbsSigLaneLaneIfIndex, nbsSigLaneLaneTable=nbsSigLaneLaneTable, nbsSigLaneLaneLaserTemp=nbsSigLaneLaneLaserTemp, nbsSigLaneLaneIndex=nbsSigLaneLaneIndex, nbsSigLaneLaneBiasAmps=nbsSigLaneLaneBiasAmps, nbsSigLanePortFacility=nbsSigLanePortFacility, nbsSigLaneLaneChannelBand=nbsSigLaneLaneChannelBand, nbsSigLaneLaneTxPowerLevel=nbsSigLaneLaneTxPowerLevel, nbsSigLanePortGrp=nbsSigLanePortGrp, nbsSigLaneLaneTxPower=nbsSigLaneLaneTxPower, nbsSigLanePortLanes=nbsSigLanePortLanes, nbsSigLaneLaneWavelengthX=nbsSigLaneLaneWavelengthX, nbsSigLaneLaneBiasAmpsLevel=nbsSigLaneLaneBiasAmpsLevel, nbsSigLanePortIfIndex=nbsSigLanePortIfIndex, nbsSigLaneLaneGrp=nbsSigLaneLaneGrp, nbsSigLaneLaneRxPowerLevel=nbsSigLaneLaneRxPowerLevel, nbsSigLaneTraps=nbsSigLaneTraps, nbsSigLaneLaneRxPower=nbsSigLaneLaneRxPower, nbsSigLaneLaneFrequency=nbsSigLaneLaneFrequency, nbsSigLaneLaneChannelNumber=nbsSigLaneLaneChannelNumber)
[ 2, 198, 2, 9485, 15571, 7378, 337, 9865, 8265, 399, 4462, 12, 50, 3528, 25697, 36, 12, 8895, 33, 357, 4023, 1378, 16184, 76, 489, 8937, 13, 785, 14, 79, 893, 11632, 8, 198, 2, 7054, 45, 13, 16, 2723, 2393, 1378, 14, 14490, 14, ...
2.409369
3,757
from django.contrib import admin from .models import CarMake, CarModel # Register your models here. #admin.site.register(CarMake) #admin.site.register(CarModel) # CarModelInline class # CarModelAdmin class # CarMakeAdmin class with CarModelInline # Register models here admin.site.register(CarModel) admin.site.register(CarMake, CarMakeAdmin)
[ 6738, 42625, 14208, 13, 3642, 822, 1330, 13169, 198, 6738, 764, 27530, 1330, 1879, 12050, 11, 1879, 17633, 628, 198, 2, 17296, 534, 4981, 994, 13, 198, 2, 28482, 13, 15654, 13, 30238, 7, 9914, 12050, 8, 198, 2, 28482, 13, 15654, 13,...
3.25
108
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. norm_cfg = dict(type='SyncBN', requires_grad=True) model = dict( type='EncoderDecoder', pretrained=None, backbone=dict( type='ConvNeXt', in_chans=3, depths=[3, 3, 9, 3], dims=[96, 192, 384, 768], drop_path_rate=0.2, layer_scale_init_value=1.0, out_indices=[0, 1, 2, 3], ), decode_head=dict( type='UPerHead', in_channels=[128, 256, 512, 1024], in_index=[0, 1, 2, 3], pool_scales=(1, 2, 3, 6), channels=512, dropout_ratio=0.1, num_classes=19, norm_cfg=norm_cfg, align_corners=False, loss_decode=dict( type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0)), auxiliary_head=dict( type='FCNHead', in_channels=384, in_index=2, channels=256, num_convs=1, concat_input=False, dropout_ratio=0.1, num_classes=19, norm_cfg=norm_cfg, align_corners=False, loss_decode=dict( type='CrossEntropyLoss', use_sigmoid=False, loss_weight=0.4)), # model training and testing settings train_cfg=dict(), test_cfg=dict(mode='whole'))
[ 2, 15069, 357, 66, 8, 30277, 19193, 82, 11, 3457, 13, 290, 29116, 13, 198, 198, 2, 1439, 2489, 10395, 13, 198, 198, 2, 770, 2723, 2438, 318, 11971, 739, 262, 5964, 1043, 287, 262, 198, 2, 38559, 24290, 2393, 287, 262, 6808, 8619, ...
2.023088
693
# ================================================================================================== # Copyright 2011 Twitter, Inc. # -------------------------------------------------------------------------------------------------- # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this work except in compliance with the License. # You may obtain a copy of the License in the LICENSE file, or 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 pytest from twitter.common.quantity import Time, Amount from twitter.common.quantity.parse_simple import parse_time, InvalidTime
[ 2, 38093, 10052, 28, 198, 2, 15069, 2813, 3009, 11, 3457, 13, 198, 2, 16529, 3880, 438, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 670, 2845, 287, ...
5.083333
204
__author__ = "Tauseef Hilal Tantary" __title__ = "iCODE-BOT" __version__ = 1.0
[ 834, 9800, 834, 796, 366, 51, 682, 891, 24410, 282, 44116, 560, 1, 198, 834, 7839, 834, 796, 366, 72, 34, 16820, 12, 33, 2394, 1, 198, 834, 9641, 834, 796, 352, 13, 15, 198 ]
2.257143
35
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import pulumi import pulumi.runtime from .. import utilities, tables class DatabaseInstance(pulumi.CustomResource): """ Creates a new Google SQL Database Instance. For more information, see the [official documentation](https://cloud.google.com/sql/), or the [JSON API](https://cloud.google.com/sql/docs/admin-api/v1beta4/instances). ~> **NOTE on `google_sql_database_instance`:** - Second-generation instances include a default 'root'@'%' user with no password. This user will be deleted by Terraform on instance creation. You should use `google_sql_user` to define a custom user with a restricted host and strong password. """ def __init__(__self__, __name__, __opts__=None, database_version=None, master_instance_name=None, name=None, project=None, region=None, replica_configuration=None, settings=None): """Create a DatabaseInstance resource with the given unique name, props, and options.""" if not __name__: raise TypeError('Missing resource name argument (for URN creation)') if not isinstance(__name__, str): raise TypeError('Expected resource name to be a string') if __opts__ and not isinstance(__opts__, pulumi.ResourceOptions): raise TypeError('Expected resource options to be a ResourceOptions instance') __props__ = dict() __props__['database_version'] = database_version __props__['master_instance_name'] = master_instance_name __props__['name'] = name __props__['project'] = project __props__['region'] = region __props__['replica_configuration'] = replica_configuration if not settings: raise TypeError('Missing required property settings') __props__['settings'] = settings __props__['connection_name'] = None __props__['first_ip_address'] = None __props__['ip_addresses'] = None __props__['self_link'] = None __props__['server_ca_cert'] = None __props__['service_account_email_address'] = None super(DatabaseInstance, __self__).__init__( 'gcp:sql/databaseInstance:DatabaseInstance', __name__, __props__, __opts__)
[ 2, 19617, 28, 40477, 12, 23, 198, 2, 17202, 39410, 25, 428, 2393, 373, 7560, 416, 262, 21624, 12994, 24118, 687, 10290, 357, 27110, 5235, 8, 16984, 13, 17202, 198, 2, 17202, 2141, 407, 4370, 416, 1021, 4556, 345, 821, 1728, 345, 760...
2.742373
885
from django.db import models from django.contrib.auth.models import AbstractUser from django.contrib.auth import get_user_model # Create your models here. class UserProfile(AbstractUser): """ 自定义的用户Model 拓展字段gender, nick_name, mobile, qq """ GENDER_CHOICES = ( ('male', "男"), ('female', "女"), ('secret', "保密") ) nick_name = models.CharField(max_length=40, blank=True, verbose_name="昵称") # 头像url avatar = models.CharField(verbose_name="头像", blank=True, null=True, max_length=256) gender = models.CharField(max_length=6, choices=GENDER_CHOICES, default="secret", verbose_name="性别") # email可以随便填,但是手机号需要唯一: 后续可加入校验验证码 mobile = models.CharField(max_length=11, verbose_name="手机号", unique=True) qq = models.CharField(max_length=12, verbose_name="QQ号", blank=True, null=True) # 公司有时候会用到钉钉/微信发送消息,需要记录用户相关ID dingding = models.CharField(max_length=40, verbose_name="钉钉ID", blank=True, null=True) wechat = models.CharField(max_length=40, verbose_name="微信ID", blank=True, null=True) # 能否访问本系统,默认是不可以访问本系统 # 注意第一个管理员用户,可以去数据库调整can_view的值为1 can_view = models.BooleanField(verbose_name="能访问", default=False, blank=True) is_deleted = models.BooleanField(verbose_name="删除", default=False, blank=True) # 注意:get_user_model()方法可以获取到本系统使用的是哪个用户Model # 默认的用户Model是:django.contrib.auth.models.User # 在settings.py中配置:AUTH_USER_MODEL可以修改成指定的用户Model # AUTH_USER_MODEL = "account.UserProfile" User = get_user_model() # 注意这句是要放在class UserProfile后面的 class MessageScope(models.Model): """ 消息范围 """ scope = models.SlugField(verbose_name="范围", max_length=10) name = models.CharField(verbose_name="范围名称", max_length=10, blank=True) class Message(models.Model): """ 用户消息Model """ user = models.ForeignKey(to=User, verbose_name='用户', on_delete=models.CASCADE) sender = models.CharField(max_length=15, verbose_name="发送者", default='system', blank=True) # 消息类型,想用type,但是还是用scope,type和types是mysql的预保留字 scope = models.ForeignKey(to=MessageScope, verbose_name="消息范围", blank=True, on_delete=models.CASCADE) title = models.CharField(max_length=100, verbose_name="消息标题") content = models.CharField(max_length=512, verbose_name="消息内容", blank=True) link = models.CharField(max_length=128, verbose_name="链接", blank=True, null=True) unread = models.BooleanField(verbose_name="未读", blank=True, default=True) time_added = models.DateTimeField(auto_now_add=True, verbose_name="添加时间") is_deleted = models.BooleanField(verbose_name="删除", default=False, blank=True)
[ 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 27530, 1330, 27741, 12982, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 1330, 651, 62, 7220, 62, 19849, 198, 198, 2, 13610, 534, 49...
1.763926
1,508
# Generated by Django 3.2.3 on 2021-06-09 13:27 from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 513, 13, 17, 13, 18, 319, 33448, 12, 3312, 12, 2931, 1511, 25, 1983, 201, 198, 201, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 201, 198, 201, 198 ]
2.567568
37
import torch from torch import nn import numpy as np import matplotlib.pyplot as plt # hyper parameters TIME_STEP = 10 INPUT_SIZE = 1 LR = 0.02 steps = np.linspace(0, np.pi * 2, 100, dtype=np.float32) x_np = np.sin(steps) y_np = np.cos(steps) plt.plot(steps, y_np, 'r-', label='target (cos)') plt.plot(steps, x_np, 'b-', label='input (sin)') plt.legend(loc='best') plt.show() rnn = RNN() print(rnn) optimizer = torch.optim.Adam(rnn.parameters(), lr=LR) loss_func = nn.MSELoss() h_state = None plt.figure(1, figsize=(12, 5)) plt.ion() for step in range(100): start, end = step * np.pi, (step + 1) * np.pi # use sin predicts cos steps = np.linspace(start, end, TIME_STEP, dtype=np.float32, endpoint=False) x_np = np.sin(steps) y_np = np.cos(steps) x = torch.from_numpy(x_np[np.newaxis, :, np.newaxis]) y = torch.from_numpy(y_np[np.newaxis, :, np.newaxis]) prediction, h_state = rnn(x, h_state) h_state = h_state.data loss = loss_func(prediction, y) optimizer.zero_grad() loss.backward() optimizer.step() plt.plot(steps, y_np.flatten(), 'r-') plt.plot(steps, prediction.data.numpy().flatten(), 'b-') plt.draw(); plt.pause(0.05) plt.ioff() plt.show()
[ 11748, 28034, 201, 198, 6738, 28034, 1330, 299, 77, 201, 198, 11748, 299, 32152, 355, 45941, 201, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 201, 198, 201, 198, 201, 198, 2, 8718, 10007, 201, 198, 34694, 62, 42135, ...
2.040562
641
import os import re import collections NOTES_DIR = '/home/dave/nonlinearfunction/gatsby-garden/_notes' md_files = [fname for fname in os.listdir(NOTES_DIR) if fname.endswith('.md')] existing_notes = [fname[:-3] for fname in md_files] refs = collections.defaultdict(int) linked_notes = set() for filename in md_files: with open(os.path.join(NOTES_DIR, filename), 'r') as f: md_str = f.read() wikilinks = re.findall(r'\[\[([^\]]+)\]\]', md_str) wikilinks = set([s.split('|')[0] for s in wikilinks]) for s in wikilinks: refs[s] += 1 # print(f"File: {filename} wikilinks: {wikilinks}") linked_notes = linked_notes.union(wikilinks) new_notes = linked_notes - set(existing_notes) trivial_notes = set() for s in new_notes: if refs[s] > 1: print(f'creating {s} with {refs[s]} refs') with open(os.path.join(NOTES_DIR, s + '.md'), 'w') as f: f.write('') else: trivial_notes.add(s) for filename in md_files: with open(os.path.join(NOTES_DIR, filename), 'r') as f: md_str = f.read() for s in trivial_notes: new_md_str = re.sub(r'\[\[' + s + r'(\|([^\]]+))?\]\]', lambda m: m.group(2) if m.group(2) else s, md_str) if new_md_str != md_str: print(f"{filename}: removed trivial link '{s}'") md_str = new_md_str with open(os.path.join(NOTES_DIR, filename), 'w') as f: f.write(md_str)
[ 11748, 28686, 198, 11748, 302, 198, 11748, 17268, 198, 198, 11929, 1546, 62, 34720, 796, 31051, 11195, 14, 67, 1015, 14, 13159, 29127, 8818, 14, 70, 1381, 1525, 12, 70, 5872, 47835, 17815, 6, 198, 198, 9132, 62, 16624, 796, 685, 69, ...
2.04426
723
import pytesseract import numpy as np import cv2
[ 11748, 12972, 83, 408, 263, 529, 198, 11748, 299, 32152, 355, 45941, 220, 198, 11748, 269, 85, 17, 220, 628, 628, 628 ]
2.545455
22
from . import special from . import old_special from .mode_indices import rmax_to_lmax, lmax_to_rmax, mode_indices from .vsh_functions import (Emn, vsh_mode, get_zn, VSH, vsh_normalization_values, get_zn_far, VSH_far, vsh_normalization_values_far) from .vsh_translation import vsh_translation from .vsh_rotation import vsh_rotation_matrix, rotate_expansion_coefficients from .expansion import expand_E, expand_E_far, expand_H, expand_H_far from .decomposition import (near_field_point_matching, far_field_point_matching, integral_project_fields_onto, integral_project_fields, integral_project_source, integral_project_source) from .cluster_coefficients import cluster_coefficients
[ 6738, 764, 1330, 2041, 198, 6738, 764, 1330, 1468, 62, 20887, 198, 198, 6738, 764, 14171, 62, 521, 1063, 1330, 374, 9806, 62, 1462, 62, 75, 9806, 11, 300, 9806, 62, 1462, 62, 81, 9806, 11, 4235, 62, 521, 1063, 198, 6738, 764, 85, ...
2.488673
309
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Apr 14 10:10:32 2021 @author: carlos.rodriguez1@bsc.es asier.gutierrez@bsc.es carme.armentano@bsc.es """ import spacy import os import json from typing import List, Tuple, Optional from thinc.api import Model from spacy.pipeline import Lemmatizer from spacy.tokens import Token from spacy.language import Language from spacy.lang.ca import Catalan @spacy.registry.callbacks("before_callback") @spacy.registry.misc("ca_lookups_loader") @Catalan.factory( "lemmatizer", assigns=["token.lemma"], default_config={"model": None, "mode": "rule", "overwrite": False}, default_score_weights={"lemma_acc": 1.0}, ) class CatalanLemmatizer(Lemmatizer): """ Copied from French Lemmatizer Catalan language lemmatizer applies the default rule based lemmatization procedure with some modifications for better Catalan language support. The parts of speech 'ADV', 'PRON', 'DET', 'ADP' and 'AUX' are added to use the rule-based lemmatization. As a last resort, the lemmatizer checks in the lookup table. """ @classmethod
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41972, 319, 3300, 2758, 1478, 838, 25, 940, 25, 2624, 33448, 198, 198, 31, 9800, 25, 1097, 33280, 13,...
2.825436
401
from typing import Any
[ 6738, 19720, 1330, 4377, 628, 198 ]
4.166667
6
#!/usr/bin/python3 # -*- coding: utf-8 -*- # Energized Blu import urllib.request import datetime import os import time File = 'energized/blu' List = [] # Thanks to all maintainers of hosts lists. Sources = [ 'https://raw.githubusercontent.com/AdroitAdorKhan/Energized/master/EnergizedHosts/EnergizedHosts', 'https://raw.githubusercontent.com/StevenBlack/hosts/master/alternates/fakenews-gambling/hosts', 'http://someonewhocares.org/hosts/zero/', 'https://hblock.molinero.xyz/hosts', 'https://raw.githubusercontent.com/EnergizedProtection/EnergizedTools/master/Mirror/MoaAB/MoaAB.active.txt', 'https://raw.githubusercontent.com/hoshsadiq/adblock-nocoin-list/master/hosts.txt', 'https://raw.githubusercontent.com/Yhonay/antipopads/master/hosts', 'https://raw.githubusercontent.com/notracking/hosts-blocklists/master/hostnames.txt', 'https://raw.githubusercontent.com/FadeMind/hosts.extras/master/add.2o7Net/hosts', 'https://raw.githubusercontent.com/FadeMind/hosts.extras/master/add.Dead/hosts', 'https://raw.githubusercontent.com/FadeMind/hosts.extras/master/add.Risk/hosts', 'https://raw.githubusercontent.com/FadeMind/hosts.extras/master/add.Spam/hosts', 'https://raw.githubusercontent.com/EnergizedProtection/EnergizedTools/master/Converter/Hosts/ZeusTracker.txt', 'https://raw.githubusercontent.com/StevenBlack/hosts/master/data/StevenBlack/hosts', 'https://zerodot1.gitlab.io/CoinBlockerLists/hosts_browser', 'https://zerodot1.gitlab.io/CoinBlockerLists/hosts', 'https://raw.githubusercontent.com/EnergizedProtection/EnergizedTools/master/Converter/Hosts/Spam404.txt', 'https://raw.githubusercontent.com/CHEF-KOCH/NSABlocklist/master/HOSTS', 'https://raw.githubusercontent.com/azet12/KADhosts/master/KADhosts.txt', 'https://raw.githubusercontent.com/EnergizedProtection/EnergizedTools/master/Converter/Hosts/AdguardMobileSpyware.txt', 'https://raw.githubusercontent.com/EnergizedProtection/EnergizedTools/master/Converter/Hosts/AdguardTracking.txt', 'https://raw.githubusercontent.com/EnergizedProtection/EnergizedTools/master/Converter/Hosts/EasylistAdserver.txt', 'https://raw.githubusercontent.com/EnergizedProtection/EnergizedTools/master/Converter/Hosts/EasyPrivacySpecific.txt', 'https://raw.githubusercontent.com/EnergizedProtection/EnergizedTools/master/Converter/Hosts/EasyPrivacyTracking.txt', 'https://raw.githubusercontent.com/EnergizedProtection/EnergizedTools/master/Converter/Hosts/DisconnectMEAds.txt', 'https://raw.githubusercontent.com/EnergizedProtection/EnergizedTools/master/Converter/Hosts/DisconnectMEMalvertising.txt', 'https://raw.githubusercontent.com/EnergizedProtection/EnergizedTools/master/Converter/Hosts/DisconnectMEMalware.txt', 'https://raw.githubusercontent.com/EnergizedProtection/EnergizedTools/master/Converter/Hosts/Wally3K_Blacklist.txt' ] for Link in Sources: try: print('[+] Retrieving list from: {}'.format(Link)) r = urllib.request.urlopen(Link) Host = r.readlines() Host = [x.decode('UTF-8') for x in Host] Host = [x.strip() for x in Host] Host = [z for z in Host if z != '' and z[0] != '#'] Host = [h.split()[1] for h in Host if h.split()[0] in ['0.0.0.0', '127.0.0.1']] Host = [x for x in Host if x not in ['localhost', 'localhost.localdomain', 'locals']] print('[+] Found {} domains to block.'.format(str(len(Host)))) r.close() List += Host except: print('[-] ERROR: I can\'t retrieve the list from: {}'.format(Link)) print('[+] Removing duplicates and sorting...') List = sorted(list(set(List))) print('[+] Applying whitelist...') r = urllib.request.urlopen('https://raw.githubusercontent.com/AdroitAdorKhan/Energized/master/EnergizedHosts/EnergizedWhites') Whitelist = r.readlines() Whitelist = [x.decode('utf-8') for x in Whitelist] Whitelist = [x.strip() for x in Whitelist] Whitelist = [z for z in Whitelist if z != '' and z[0] != '#'] r.close() for i in range(0, len(Whitelist)): try: List.remove(Whitelist[i]) except: pass print('[+] Total domains count {}.'.format(str(len(List)))) if not os.path.exists(os.path.dirname(File)): os.makedirs(os.path.dirname(File)) with open(File, 'w') as f: print('[+] Writing to file...') f.write('''# Energized - ad.porn.malware blocking.\n# A merged collection of hosts from reputable sources.\n# https://ador.chorompotro.com\n\n# Energized Blu - Lightweight Energized Protection.\n# Version: ''' + time.strftime("%y.%m.%j", time.gmtime()) + '''\n# Project Git: https://github.com/EnergizedProtection/EnergizedBlu\n# RAW Source: https://raw.githubusercontent.com/EnergizedProtection/EnergizedBlu/master/energized/blu\n# Last updated: {}'''.format(datetime.datetime.now().strftime('%a, %d %b %y %X'))) f.write('''\n# Total Domains: {}\n\n'''.format(str(len(List)))) f.write('''\n# -================-Maintainer-================-\n# Nayem Ador - https://adroitadorkhan.github.io\n# -============================================-\n\n''') f.write('''\n127.0.0.1 localhost\n127.0.0.1 localhost.localdomain\n127.0.0.1 local\n255.255.255.255 broadcasthost\n::1 localhost\n::1 ip6-localhost\n::1 ip6-loopback\nfe80::1%lo0 localhost\nff00::0 ip6-localnet\nff00::0 ip6-mcastprefix\nff02::1 ip6-allnodes\nff02::2 ip6-allrouters\nff02::3 ip6-allhosts\n0.0.0.0 0.0.0.0\n\n\n# -====================-Features-====================-\n# # Lightweight Energized Protection Ever! #\n#\n# - Based on Hosts file, all the bad stuff blocked with 0.0.0.0 \n# - Compatible with all devices, regardless of OS. \n# - Strictly blocks all advertisements, malwares, spams, statistics, trackers on both web browsing and applications. \n# - YouTube, Spotify, UC and Shareit Ads Blocking. \n# - Reduces page loading time. \n# - Reduces data consumptions. Saves data expenses. \n# - Increases privacy. \n# - No extra abracadabra!\n#\n# -==================================================-\n\n\n''') f.write('\n'.join('0.0.0.0 ' + url for url in List)) print('[+] Done!')
[ 2, 48443, 14629, 14, 8800, 14, 29412, 18, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 2, 412, 25649, 1143, 12391, 220, 198, 198, 11748, 2956, 297, 571, 13, 25927, 198, 11748, 4818, 8079, 198, 11748, 28...
2.681468
2,207
import json import requests from settings import * if __name__ == "__main__": post_rain_notice()
[ 11748, 33918, 198, 11748, 7007, 198, 6738, 6460, 1330, 1635, 628, 628, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 1281, 62, 3201, 62, 42138, 3419, 198 ]
3.028571
35
from collections import deque from abc import ABC, abstractmethod from multiprocessing import Queue as MQueue from multiprocessing import Process from redrawing.components.stage import Stage class Queue(ABC): '''! Generic queue for communication between stages. ''' @abstractmethod def get(self): '''! Returns the first element of the queue. Returns: @returns the first element of the queue ''' ... @abstractmethod def insert(self, value): '''! Insert a value in the end of the queue. Parameters: @param value - the value ''' ... @abstractmethod def empty(self): '''! See if the queue is empty. Returns: @returns True if empty ''' ... @abstractmethod def full(self): '''! See if the queue if full Returns: @returns True if full ''' ... class SimpleQueue(Queue): '''! A simple queue. Must not be used for multiprocessing Uses collections.deque for implement the queue ''' def get(self): '''! Returns the first element of the queue. Returns: @returns the first element of the queue ''' return self.queue.popleft() def insert(self, value): '''! Insert a value in the end of the queue. Parameters: @param value - the value ''' self.queue.append(value) def empty(self): '''! See if the queue is empty. Returns: @returns True if empty ''' if len(self.queue) > 0: return False return True def full(self): '''! See if the queue if full Returns: @returns True if full ''' if len(self.queue) >= self.max_size: return True return False class ProcessQueue(Queue): '''! Queue for using in multiprocessing. For single process pipeline, SimpleQueue is better Uses multiprocessing.queue for implement the queue ''' def get(self): '''! Returns the first element of the queue. Returns: @returns the first element of the queue ''' return self.queue.get() def insert(self, value): '''! Insert a value in the end of the queue. Parameters: @param value - the value ''' self.queue.put(value) def empty(self): '''! See if the queue is empty. Returns: @returns True if empty ''' return self.queue.empty() def full(self): '''! See if the queue if full Returns: @returns True if full ''' return self.queue.full() class Pipeline(ABC): '''! Generic pipeline of stages ''' def insert_stage(self, stage): '''! Inserts a new stage to the pipeline Parameters: @param state - the stage @todo Alterar para o tipo correto de exceção ''' if not isinstance(stage, Stage): raise Exception("Stages must be of Stage class") if stage in self.substages: return self.stages.append(stage) self.substages_configs[stage] = [] @abstractmethod def create_connection(self, stage_out, id_out, stage_in, id_in, max_size): '''! Create a connection between stages Parameters: @param stage_out - Stage where the data will come from @param id_out - ID of the output communication channel @param stage_in - Stage from where the data will go @param id_in - ID of the input communication channel @param max_size - Maximum channel queue size ''' queue = None if stage_in.has_input_queue(id_in): queue = stage_in.input_queue[id_in] else: queue = self.create_queue(max_size) stage_in._setInputQueue(queue, id_in) stage_out._setOutputQueue(queue, id_out) @abstractmethod def run(self): '''! Runs the pipeline until error/exception ''' ... class SingleProcess_Pipeline(Pipeline): '''! Pipeline of stages to be runned on a single process ''' def start(self): '''! Starts the stages Is automatically called by the run and runOnce method ''' for stage in self.stages: for substage in self.substages_configs[stage]: substage["substage"].setup() stage.setup() self.started = True def run(self): '''! Runs the pipeline until error/exception ''' if not self.started: self.start() while True: self.runOnce() def runOnce(self): '''! Runs all the stages once ''' if not self.started: self.start() for stage in self.stages: for substage in self.substages_configs[stage]: if substage["run_before"] == True: substage["substage"].run(stage._context) stage.run() for substage in self.substages_configs[stage]: if substage["run_before"] == False: substage["substage"].run(stage._context) class MultiProcess_Pipeline(Pipeline): '''! Pipeline of stages runned parallely on multiple process ''' def _run_stage(self, stage): '''! Starts and runs a stage Parameters: @param stage - stage to be runned ''' for substage in self.substages_configs[stage]: substage["substage"].setup() stage.setup() while True: for substage in self.substages_configs[stage]: if substage["run_before"] == True: substage["substage"].run(stage._context) stage.run() for substage in self.substages_configs[stage]: if substage["run_before"] == False: substage["substage"].run(stage._context) def run(self): '''! Run the stages on multiple process. Locks the code until the stages end ''' process = [] for stage in self.stages: p = Process(target=self._run_stage, args=(stage,)) p.start() process.append(p) while 1: try: pass except KeyboardInterrupt: break print("TERMINANDO") for p in process: p.terminate() p.join(1) p.close()
[ 6738, 17268, 1330, 390, 4188, 198, 6738, 450, 66, 1330, 9738, 11, 12531, 24396, 198, 6738, 18540, 305, 919, 278, 1330, 4670, 518, 355, 337, 34991, 198, 6738, 18540, 305, 919, 278, 1330, 10854, 198, 198, 6738, 2266, 1831, 278, 13, 5589...
1.974973
3,676
""" Contains Python "bindings" to molecule object and Python functions utilizing molecule object key functionalities The intent is to provide a Pythonic interface to mo utilities and, thus, enable easy/consistent use of mo from within python programs. Testing: $ python <path-to-location>/pymo.py """ import os import subprocess as sp import shlex import shutil import sys import argparse import logging import unittest from tempfile import NamedTemporaryFile, mkdtemp log = logging.getLogger('lilly.' + __name__) log.addHandler(logging.NullHandler()) build_dir = 'Linux' try: build_dir = os.environ['BUILD_DIR'] except EnvironmentError: pass home_dir = os.environ['LILLYMOL_HOME'] root_dir = home_dir + '/bin/' + build_dir # dictionary of commands that will be turned into functions # function_name: [script_name, debug_message, default_params_dict] mo_tool_map = { 'dicer': [root_dir + '/dicer', 'Recursively cuts molecules based on queries', {}], 'fileconv': [root_dir + '/fileconv', 'file/molecule conversion utilities', {}], 'iwdescr': [root_dir + '/iwdescr', 'compute physicochemical descriptors using iwdescr', {'-l': ''}], 'make_these_molecules': [root_dir + '/make_these_molecules', 'Makes molecules from isotopically labelled ' 'reagents according to make file, not ' 'combinatorial join', {}], 'preferred_smiles': [root_dir + '/preferred_smiles', '', {}], 'alogp': [root_dir + '/abraham', '', {'-l': '', '-F': home_dir + '/contrib/data/queries/abraham/Abraham', '-P': home_dir + '/contrib/data/queries/abraham/Alpha2H', '-g': 'all' }] } def __function_generator(fct_name, script_name, debug_msg, default_params_dict, expect_zero=True): """ A generator for functions which runs one of LillyMol scripts with a predefined set of parameters. :param str fct_name: the function name of the newly generated function :param script_name: your LillyMol script path (from mo_tool above) :param debug_msg: quick message about what the script does (from mo_tool above) :param default_params_dict: default parameters :param expect_zero: whether to expect zero as a return value from the script :return: a function which you can call to run the script :rtype: callable """ funct.__name__ = fct_name funct.__doc__ = debug_msg return funct for name, params in list(mo_tool_map.items()): nparams = len(params) if not (3 <= nparams <= 5): raise IndexError('mo_tool_map: "{}" has {:d} parameter(s) but should ' 'have 3-5'.format(name, nparams)) locals()[name] = __function_generator(name, *params) def make_these_molecules(rgnt_list, make_these_file, reaction_file_list, outfile=None, params_dict={}, debug=True, loggero=None): """ Alternative to trxn, used in MMP code for generating new mols from MMP's, trxn version would be alternative: For connecting one bond (two components, single cut fragments): trxn.sh -S - -r oneConnection.rxn partOne.smi partTwo.smi For connecting two bonds (three component, two cut fragments): trxn.sh -S -rxn -S - -r twoConnection.rxn partThree.smi partOne.smi partTwo.smi BUT, if we have a long list of different contexts (partOne) and don't want exhaustive enumeration, specify rxn's: make_these_molecules.sh -R oneConnection.rxn -M m2Make.txt -S - partOne.smi partTwo.smi In this case, you can put all context fragments SMILES (context1a, context 1b, ...) in one reagent file, and all fragments SMILES (frag1, frag2, ...) in the second reagent file. If you have something like (context1a frag1\n context1a frag2\ncontext1b frag3\n...) in your m2Make.txt file, you will create the molecules you wanted """ log.debug("Generating virtual compounds using rxn and reagents supplied plus specified combinations file") # prep reagents file string rgnt_string = " ".join(rgnt_list) log.debug("These are the reagent files...." + str(rgnt_string)) # prep params string params_string = " " for k, v in list(params_dict.items()): params_string += k + " " + v + " " params_string = params_string[:-1] # set outfile # improved a bit to handle files with '.' in main name, other than in the extension if outfile: if outfile[-4:] == ".smi" or outfile[-4:] == ".txt": params_string += " -S " + os.path.splitext(outfile)[0] else: params_string += " -S " + outfile reaction_file = "" for rxn_file in reaction_file_list: # todo: if single string, this is split in characters reaction_file += ' -R ' + rxn_file cmd_line = (mo_tool_map['make_these_molecules'][0] + reaction_file + ' -M ' + make_these_file + " " + params_string + " " + rgnt_string) log.debug("Executing: %s" % cmd_line) #if debug: #print(cmd_line) my_proc = sp.Popen(shlex.split(cmd_line), stdout=None, stderr=sp.PIPE, shell=False) for line in my_proc.stderr.readlines(): log.debug(line.rstrip()) exit_status = my_proc.wait() log.debug("Done generating compounds") return exit_status ##################################################### class _TestPymo(unittest.TestCase): """Test class for pymo module Example usage: python pymo.py (to execute all tests) python pymo.py -c (for verbose console logging) python pymo.py -f mylog.log (for logging to file mylog.log) python pymo.py -c -f mylog.log (for both) python pymo.py _Test_pymo.test_fetch_smiles # (to execute only the specified test) coverage run pymo.py (to run test code coverage analysis) coverage report pymo.py (to view the result of the test code coverage analysis) """ def setUp(self): """setup test data location, unittest config and logger""" # location of test data self.test_data_location = root_dir + '/contrib/script/py/mmp/testdata/' # temp output file and dir self.temp_inp_file = NamedTemporaryFile(encoding='utf-8', mode='wt', suffix='.smi', delete=False) self.temp_out_file = NamedTemporaryFile(encoding='utf-8', mode='wt', delete=False) self.temp_out_dir = mkdtemp() test_smiles = { # basic test set - all the below id's and structures are CHEMBL '3105327': 'Cc1ccc2c(ccn2c3nc(cs3)c4cc(ccc4F)C(F)(F)F)c1', '1526778': 'CC(=O)c1c(C)n(c(C)c1C(=O)C)c2nc(c(C)s2)c3ccc(C)c(C)c3', '1494678': 'CC(=O)c1c(C)n(c(C)c1C(=O)C)c2nc(c(C)s2)c3ccccc3', '472166': 'OC(CCn1ccnc1)(c2ccccc2)c3ccccc3', '69798': 'Cc1nccn1CCC(O)(c2ccccc2)c3ccccc3', '367346': 'Cc1sc(N)nc1c2cccc(Cl)c2', '366881': 'Cc1sc(N)nc1c2ccc(Cl)c(Cl)c2', '1477460': 'COc1ccc(cc1)c2nc(sc2C)n3c(C)c(C(=O)C)c(C(=O)C)c3C', '1441050': 'COc1ccc(cc1OC)c2nc(sc2C)n3c(C)c(C(=O)C)c(C(=O)C)c3C' } # write test data to temp file 01 for smi_id, smi in test_smiles.items(): string = smi+' '+smi_id+'\n' self.temp_inp_file.write(string) self.temp_inp_file.close() def tearDown(self): """cleanup test data and settings""" # Clean up the directory # os.removedirs(self.temp_out_dir) shutil.rmtree(self.temp_out_dir) if __name__ == "__main__": # optional command line flags parser = argparse.ArgumentParser() parser.add_argument('-l', '--log_file', help='Name of file to place debug log info in') parser.add_argument('-c', '--console', help='Switch on console logging', default=False, action='store_true') args = parser.parse_args() #print(args) logger_file = args.log_file console_on = args.console pymotest_logger = logging.getLogger("pymo.testlogger") pymotest_logger.setLevel(logging.DEBUG) log_formatter = logging.Formatter("%(asctime)s [%(funcName)-12.12s] " "[%(levelname)-5.5s] %(message)s", datefmt="%Y-%m-%d %H:%M:%S") if console_on: print("Switched on console") h1 = logging.StreamHandler(stream=sys.stdout) h1.setLevel(logging.DEBUG) h1.setFormatter(log_formatter) pymotest_logger.addHandler(h1) else: print("console off") if logger_file is not None: print(("Switched on logging to file: {}".format(logger_file))) fileHandler = logging.FileHandler(filename=logger_file) fileHandler.setFormatter(log_formatter) fileHandler.setLevel(logging.DEBUG) pymotest_logger.addHandler(fileHandler) else: print("file logging off") if console_on is False and logger_file is None: pymotest_logger.setLevel(logging.CRITICAL) unittest.main()
[ 37811, 198, 4264, 1299, 11361, 366, 21653, 654, 1, 284, 27756, 2134, 290, 11361, 5499, 198, 22602, 2890, 27756, 2134, 1994, 10345, 871, 198, 464, 6824, 318, 284, 2148, 257, 11361, 291, 7071, 284, 6941, 20081, 290, 11, 4145, 11, 198, 2...
2.219023
4,237
import pandas as pd # import pytz import unittest from records_mover.records.pandas import prep_df_for_csv_output from records_mover.records.schema import RecordsSchema from records_mover.records import DelimitedRecordsFormat, ProcessingInstructions
[ 11748, 19798, 292, 355, 279, 67, 198, 2, 1330, 12972, 22877, 198, 11748, 555, 715, 395, 198, 6738, 4406, 62, 76, 2502, 13, 8344, 3669, 13, 79, 392, 292, 1330, 3143, 62, 7568, 62, 1640, 62, 40664, 62, 22915, 198, 6738, 4406, 62, 76...
3.302632
76
import numpy as np from tensorflow.python.keras.utils import Sequence, to_categorical from tensorflow.python.keras.preprocessing.sequence import pad_sequences class TemporalOrderExp6aSequence(Sequence): """ From Hochreiter&Schmidhuber(1997): The goal is to classify sequences. Elements and targets are represented locally (input vectors with only one non-zero bit). The sequence starts with an E, ends with a B (the "trigger symbol") and otherwise consists of randomly chosen symbols from the set {a, b, c, d} except for two elements at positions t1 and t2 that are either X or Y . The sequence length is randomly chosen between 100 and 110, t1 is randomly chosen between 10 and 20, and t2 is randomly chosen between 50 and 60. There are 4 sequence classes Q, R, S, U which depend on the temporal order of X and Y. The rules are: X, X -> Q, X, Y -> R, Y , X -> S, Y , Y -> U. """ # encoding/decoding single instance version # encoding/decoding batch versions def __len__(self): """ Let's assume 1000 sequences as the size of data. """ return int(1000. / self.batch_size) class DifficultyLevel: """ On HARD, settings are identical to the original settings from the '97 paper.""" EASY, NORMAL, MODERATE, HARD, NIGHTMARE = range(5) @staticmethod
[ 11748, 299, 32152, 355, 45941, 198, 6738, 11192, 273, 11125, 13, 29412, 13, 6122, 292, 13, 26791, 1330, 45835, 11, 284, 62, 66, 2397, 12409, 198, 6738, 11192, 273, 11125, 13, 29412, 13, 6122, 292, 13, 3866, 36948, 13, 43167, 1330, 148...
2.812992
508
#pilaniamte version 0.4.1 from PIL import Image, ImageDraw, ImageOps, ImageFilter, ImageEnhance, ImageColor, ImageFont, ImageSequence import cv2 import numpy from time import sleep import os, math #functions that draw stuff on #translation functions #transparency functions #UNTESTED #transform #color change functions #image filter functions #blend #clear image functions #save frame image #turn frame into png #shortcut save functions (ie a function that translates every frame and also saves frame)
[ 2, 79, 38239, 1789, 660, 2196, 657, 13, 19, 13, 16, 198, 6738, 350, 4146, 1330, 7412, 11, 7412, 25302, 11, 7412, 41472, 11, 7412, 22417, 11, 7412, 35476, 590, 11, 7412, 10258, 11, 7412, 23252, 11, 7412, 44015, 594, 198, 11748, 269, ...
3.593333
150
import numpy as np from pygsl import statistics as gsl_stat from scipy import stats as sp_stat import ineqpy as ineq from ineqpy import _statistics as ineq_stat # Generate random data x, w = ineq.utils.generate_data_to_test((60,90)) # Replicating weights x_rep, w_rep = ineq.utils.repeat_data_from_weighted(x, w) svy = ineq.api.Survey print( """ ========== Quickstart ========== We generate random weighted data to show how ineqpy works. The variables simulate being: x : Income w : Weights ```python >>> x, w = ineq.utils.generate_data_to_test((60,90)) ``` To test with classical statistics we generate: x_rep : Income values replicated w times each one. w_rep : Ones column. ```python >>> x_rep, w_rep = ineq.utils.repeat_data_from_weighted(x, w) ``` Additional information: np : numpy package sp : scipy package pd : pandas package gsl_stat : GNU Scientific Library written in C. ineq : IneqPy """ ) print( """ Examples and comparision with other packages ============================================ STATISTICS ========== MEAN ---- """ ) print('```python') print('>>> np.mean(x_rep)'.ljust(24), '=', np.mean(x_rep)) print('>>> ineq.mean(x, w)'.ljust(24), '=', ineq.mean(x, w)) print('>>> gsl_stat.wmean(w, x)'.ljust(24), '=', gsl_stat.wmean(w, x)) print('```') # %timeit ineq.mean(None, x, w) # %timeit gsl_stat.wmean(w, x) # %timeit ineq_stat.mean(x, w) print( """ VARIANCE -------- """ ) np_var = np.var(x_rep) inq_var = ineq.var(x, w) wvar_1 = ineq_stat.wvar(x, w, 1) # population variance wvar_2 = ineq_stat.wvar(x, w, 2) # sample frequency variance gsl_wvar = gsl_stat.wvariance(w, x) wvar_3 = ineq_stat.wvar(x, w, 3) # sample reliability variance print('```python') print('>>> np.var(x_rep)'.ljust(32), '=', np_var) print('>>> ineq.var(x, w)'.ljust(32), '=', inq_var) print('>>> ineq_stat.wvar(x, w, kind=1)'.ljust(32), '=', wvar_1) print('>>> ineq_stat.wvar(x, w, kind=2)'.ljust(32), '=', wvar_2) print('>>> gsl_stat.wvariance(w, x)'.ljust(32), '=', gsl_wvar) print('>>> ineq_stat.wvar(x, w, kind=3)'.ljust(32), '=', wvar_3) print('```') print( """ COVARIANCE ---------- """ ) np_cov = np.cov(x_rep, x_rep) ineq_wcov1 = ineq_stat.wcov(x, x, w, 1) ineq_wcov2 = ineq_stat.wcov(x, x, w, 2) ineq_wcov3 = ineq_stat.wcov(x, x, w, 3) print('```python') print('>>> np.cov(x_rep, x_rep)'.ljust(35), '= ', np_cov) print('>>> ineq_stat.wcov(x, x, w, kind=1)'.ljust(35), '= ', ineq_wcov1) print('>>> ineq_stat.wcov(x, x, w, kind=2)'.ljust(35), '= ', ineq_wcov2) print('>>> ineq_stat.wcov(x, x, w, kind=3)'.ljust(35), '= ', ineq_wcov3) print('```') print( """ SKEWNESS -------- """ ) gsl_wskew = gsl_stat.wskew(w, x) sp_skew = sp_stat.skew(x_rep) ineq_skew = ineq.skew(x, w) print('```python') print('>>> gsl_stat.wskew(w, x)'.ljust(24), '= ', gsl_wskew) print('>>> sp_stat.skew(x_rep)'.ljust(24), '= ', sp_skew) print('>>> ineq.skew(x, w)'.ljust(24), '= ', ineq_skew) print('```') # %timeit gsl_stat.wskew(w, x) # %timeit sp_stat.skew(x_rep) # %timeit ineq.skew(None, x, w) print( """ KURTOSIS -------- """ ) sp_kurt = sp_stat.kurtosis(x_rep) gsl_wkurt = gsl_stat.wkurtosis(w, x) ineq_kurt = ineq.kurt(x, w) - 3 print('```python') print('>>> sp_stat.kurtosis(x_rep)'.ljust(28), '= ', sp_kurt) print('>>> gsl_stat.wkurtosis(w, x)'.ljust(28), '= ', gsl_wkurt) print('>>> ineq.kurt(x, w) - 3'.ljust(28), '= ', ineq_kurt) print('```') # %timeit sp_stat.kurtosis(x_rep) # %timeit gsl_stat.wkurtosis(w, x) # %timeit ineq.kurt(None, x, w) - 3 print( """ PERCENTILES ----------- """ ) q = 50 ineq_perc_50 = ineq_stat.percentile(x, w, q) np_perc_50 = np.percentile(x_rep, q) print('```python') print('>>> ineq_stat.percentile(x, w, %s)'.ljust(34) % q, '= ', ineq_perc_50) print('>>> np.percentile(x_rep, %s)'.ljust(34) % q, '= ', np_perc_50) q = 25 ineq_perc_25 = ineq_stat.percentile(x, w, q) np_perc_25 = np.percentile(x_rep, q) print('>>> ineq_stat.percentile(x, w, %s)'.ljust(34) % q, '= ', ineq_perc_25) print('>>> np.percentile(x_rep, %s)'.ljust(34) % q, '= ', np_perc_25) q = 75 ineq_perc_75 = ineq_stat.percentile(x, w, q) np_perc_75 = np.percentile(x_rep, q) print('>>> ineq_stat.percentile(x, w, %s)'.ljust(34) % q, '= ', ineq_perc_75) print('>>> np.percentile(x_rep, %s)'.ljust(34) % q, '= ', np_perc_75) q = 10 ineq_perc_10 = ineq_stat.percentile(x, w, q) np_perc_10 = np.percentile(x_rep, q) print('>>> ineq_stat.percentile(x, w, %s)'.ljust(34) % q, '= ', ineq_perc_10) print('>>> np.percentile(x_rep, %s)'.ljust(34) % q, '= ', np_perc_10) q = 90 ineq_perc_90 = ineq_stat.percentile(x, w, q) np_perc_90 = np.percentile(x_rep, q) print('>>> ineq_stat.percentile(x, w, %s)'.ljust(34) % q, '= ', ineq_perc_90) print('>>> np.percentile(x_rep, %s)'.ljust(34) % q, '= ', np_perc_90) print('```') print( """ Another way to use this is through the API module as shown below: API MODULE ========== """ ) data = np.c_[x, w] columns = list('xw') df = svy(data=data, columns=columns, weights='w') print('```python') print(">>> data = svy(data=data, columns=columns, weights='w')") print(">>> data.head()") print(df.head()) print('') print('>>> data.weights =', df.weights) print('```') print('') main_var = 'x' # df.mean(main_var) # df.var(main_var) # df.skew(main_var) # df.kurt(main_var) # df.gini(main_var) # df.atkinson(main_var) # df.theil(main_var) # df.percentile(main_var) print('```python') print('>>> df.mean(main_var)'.ljust(27), '=', df.mean(main_var)) print('>>> df.percentile(main_var)'.ljust(27), '=', df.percentile(main_var)) print('>>> df.var(main_var)'.ljust(27), '=', df.var(main_var)) print('>>> df.skew(main_var)'.ljust(27), '=', df.skew(main_var)) print('>>> df.kurt(main_var)'.ljust(27), '=', df.kurt(main_var)) print('>>> df.gini(main_var)'.ljust(27), '=', df.gini(main_var)) print('>>> df.atkinson(main_var)'.ljust(27), '=', df.atkinson(main_var)) print('>>> df.theil(main_var)'.ljust(27), '=', df.theil(main_var)) print('```')
[ 11748, 299, 32152, 355, 45941, 198, 6738, 12972, 70, 6649, 1330, 7869, 355, 308, 6649, 62, 14269, 198, 6738, 629, 541, 88, 1330, 9756, 355, 599, 62, 14269, 198, 198, 11748, 287, 27363, 9078, 355, 287, 27363, 198, 6738, 287, 27363, 907...
2.126029
2,793