content
stringlengths
1
1.04M
input_ids
listlengths
1
774k
ratio_char_token
float64
0.38
22.9
token_count
int64
1
774k
from django.conf.urls import url from traffic import views app_name = 'traffic' urlpatterns = [ # url(r'^$', views.index), # url(r'^index/', views.index), url(r'^traffic/pages/$', views.page_view, name='performance'), url(r'^traffic/calender/$', views.calender_view, name='calender'), url(r'^traffic/users/$', views.users_view, name='userAnalyze'), url(r'^traffic/locations/$', views.locations_view, name='locationAnalyze'), ]
[ 6738, 42625, 14208, 13, 10414, 13, 6371, 82, 1330, 19016, 198, 198, 6738, 4979, 1330, 5009, 198, 198, 1324, 62, 3672, 796, 705, 9535, 2108, 6, 198, 198, 6371, 33279, 82, 796, 685, 198, 220, 220, 220, 1303, 19016, 7, 81, 6, 61, 3, ...
2.550562
178
from django.urls import path, include from accounts import views urlpatterns = [ path('', views.indx, name='accounts'), <<<<<<< HEAD path('/signup', views.signup, name='signup'), path('logout', views.logout, name='logout'), path('/login', views.loginn, name='login'), path('/usertpe/<int:pk>/', views.usertype, name='usertpe/'), path('/userSelection/<int:id>', views.UserSelection, name='userSelection'), path('dashboard', views.dashboard, name='dashboard'), path('/organiser', include('Organizer.urls'), name='organiserIndex'), path('/sponsor', include('Sponsor.urls'), name='sponsorIndex'), path('/participant/', include('Participant.urls'), name='participantIndex'), ======= path('signup', views.signup, name='signup'), path('logout', views.logout, name='logout'), path('login', views.loginn, name='login'), path('usertpe/<int:pk>/', views.usertype, name='usertpe/'), path('userSelection/<int:id>', views.UserSelection, name='userSelection'), path('dashboard', views.dashboard, name='dashboard'), path('organiser', include('Organizer.urls'), name='organiserIndex'), path('sponsor', include('Sponsor.urls'), name='sponsorIndex'), path('participant/', include('Participant.urls'), name='participantIndex'), >>>>>>> 00486efd62bd717f2eaff3e6c9f80a737c54bef9 ]
[ 6738, 42625, 14208, 13, 6371, 82, 1330, 3108, 11, 2291, 198, 198, 6738, 5504, 1330, 5009, 198, 198, 6371, 33279, 82, 796, 685, 198, 220, 220, 220, 3108, 10786, 3256, 5009, 13, 521, 87, 11, 1438, 11639, 23317, 82, 33809, 198, 16791, ...
2.711968
493
default_app_config = 'silverlance.apps.SilverlanceAppConfig'
[ 12286, 62, 1324, 62, 11250, 796, 705, 40503, 23215, 13, 18211, 13, 26766, 23215, 4677, 16934, 6, 198 ]
3.388889
18
""" A really simple MediaWiki API client for the Scratch Wiki. Can: * read pages * edit pages * list pages in category * list page backlinks ("what links here") * list page transclusions Requires the `requests` library. http://wiki.scratch.mit.edu/ Example Usage ============= Get a page:: wiki = ScratchWiki() wiki.login("blob8108", password) sandbox = wiki.page("User:Blob8108/Sandbox") Edit page: # Get the page contents = sandbox.read() # Change contents += "\n This is a test!" summary = "Made a test edit" # Submit sandbox.edit(contents, summary) List pages in category:: for page in wiki.category_members("Redirects"): print page.title Remove all uses of a template:: target_pages = wiki.transclusions("Template:unreleased") # Sort by title because it's prettier that way target_pages.sort(key=lambda x: x.title) # Main namespace only target_pages = [p for p in target_pages if p.query_info()['ns'] == 0] for page in target_pages: page.replace("{{unreleased}}", "") Made by ~blob8108. MIT Licensed. """ from urllib import urlencode import json import requests ERRORS = { 'permissiondenied': PermissionDenied, }
[ 37811, 198, 32, 1107, 2829, 6343, 32603, 7824, 5456, 329, 262, 1446, 36722, 13078, 13, 198, 198, 6090, 25, 628, 220, 1635, 1100, 5468, 198, 220, 1635, 4370, 5468, 198, 220, 1635, 1351, 5468, 287, 6536, 198, 220, 1635, 1351, 2443, 736,...
2.831461
445
from evntbus import Event
[ 6738, 819, 429, 10885, 1330, 8558, 628, 628, 628 ]
3.444444
9
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright 2020 Palo Alto Networks, 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. from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = ''' --- module: panos_commit_panorama short_description: Commit Panorama's candidate configuration. description: - Module that will commit the candidate configuration on a Panorama instance. - The new configuration will become active immediately. author: - Robert Hagen (@stealthllama) version_added: '2.0.0' requirements: - pan-os-python extends_documentation_fragment: - paloaltonetworks.panos.fragments.provider options: description: description: - A description of the commit. type: str admins: description: - Commit only the changes made by specified list of administrators. type: list elements: str device_groups: description: - Commit changes made to these device groups. type: list elements: str templates: description: - Commit changes made to these templates. type: list elements: str template_stacks: description: - Commit changes made to these template stacks. type: list elements: str wildfire_appliances: description: - Commit changes made to these WildFire appliances. type: list elements: str wildfire_clusters: description: - Commit changes made to these WildFire clusters. type: list elements: str log_collectors: description: - Commit changes made to these log collectors. type: list elements: str log_collector_groups: description: - Commit changes made to these log collector groups. type: list elements: str exclude_device_and_network: description: - Exclude network and device configuration changes. type: bool default: False exclude_shared_objects: description: - Exclude shared object configuration changes. type: bool default: False force: description: - Force the commit. type: bool default: False sync: description: - Wait for the commit to complete. type: bool default: True ''' EXAMPLES = r''' - name: commit candidate configs on panorama panos_commit_panorama: provider: '{{ credentials }}' - name: commit changes by specified admins on panorama panos_commit_panorama: provider: '{{ credentials }}' admins: ['netops','secops','cloudops'] description: 'Saturday change window' - name: commit specific device group changes on panorama panos_commit_panorama: provider: '{{ credentials }}' device_groups: ['production','development','testing'] - name: commit log collector group changes on panorama panos_commit_panorama: provider: '{{ credentials }}' log_collector_groups: ['us-west-loggers','apac-loggers','latam-loggers'] description: 'Log collector changes' ''' RETURN = r''' jobid: description: The ID of the PAN-OS commit job. type: int returned: always sample: 49152 details: description: Commit job completion messages. type: str returned: on success sample: Configuration committed successfully ''' from ansible.module_utils.basic import AnsibleModule from ansible_collections.paloaltonetworks.panos.plugins.module_utils.panos import get_connection try: from panos.panorama import PanoramaCommit except ImportError: pass if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 2, 220, 15069, 12131, 44878, 34317, 27862, 11, 3457, 198, 2, 198, 2, 220, 49962, 739, 262, 24843, 13789, 11, 10628, 362...
2.762679
1,538
from .Person import Person from .Role import Role from .Event import Event
[ 6738, 764, 15439, 1330, 7755, 198, 6738, 764, 47445, 1330, 20934, 198, 6738, 764, 9237, 1330, 8558, 198 ]
4.166667
18
import numpy as np import random import time import copy def kmax(data, init_centriod, L = 2, K = 3, max_iterations = 50): ''' data: a collection of records init_centriod: the inital centriod L: top K attributes K: cluster numbers max_iterations: the max iteration before stop ''' start = time.time() length, width = data.shape partitions = [[] for _ in range(K)] attribute_sum = np.zeros((K, width)) largest_sum = 0 increment = [] for iteration in range(max_iterations): # data partition tmp_p = copy.deepcopy(partitions) _sum = 0 tmp_sum = np.zeros((length, len(init_centriod))) selected_data = np.take(data, init_centriod, axis = 1) for k in range(K): #selected_attr = data[:, init_centriod[i]] #tmp_sum[:, i] = np.sum(selected_attr, axis = 1) tmp_sum[:, k] = selected_data[:, k, :].sum(1) tmp = np.argmax(tmp_sum, 1) increment.append(np.sum(np.max(tmp_sum, 1)))# / (length * K)) for k in range(K): partitions[k] = np.where(tmp == k)[0].tolist() attribute_sum[k] = np.sum(data[partitions[k], :], 0) # recompute the centriod for k in range(K): _sum += sum(np.sort(attribute_sum[k], kind = "stable")[-L:]) tmp_idx = np.argsort(attribute_sum[k], kind = "stable") new_centriod = tuple(tmp_idx[-L:].tolist()) init_centriod[k] = new_centriod largest_sum = _sum #increment.append(iteration_sum / (length * K)) Flag = True for k in range(K): Flag = Flag & (tmp_p[k] == partitions[k]) if Flag == True: break end = time.time() return iteration + 1, end - start, largest_sum, init_centriod, partitions, increment def multiple_init_kmax(data, L = 2, K = 3, init_num = 1): ''' data: a collection of records init_centriod: the inital centriod L: top L attributes K: cluster numbers init_num: the number of different initialization ''' # randomly initalize the centriod of each cluster length, width = data.shape func = lambda x : random.sample(range(width), x) init_centriod_sets = [[] for _ in range(init_num)] # generate different initialization for i in range(init_num): while len(init_centriod_sets[i]) < K: sample = func(L) flag = False for _, j in enumerate(init_centriod_sets[i]): if set(sample) == set(j): flag = True break if flag == True: continue else: init_centriod_sets[i].append(sample) Largest_sum_list = [] time_elapsed_list = [] iteration_list = [] partition_list = [] attribute_list = [] increment_list = [] for i in range(init_num): iteration, time, largest_sum, centriod, partitions, increment = kmax(data, init_centriod_sets[i], L, K) Largest_sum_list.append(largest_sum) time_elapsed_list.append(time) iteration_list.append(iteration) partition_list.append(partitions) attribute_list.append(centriod) increment_list.append(increment) return Largest_sum_list, time_elapsed_list, iteration_list, attribute_list, partition_list, increment_list if __name__ == "__main__": data = np.load("../titanic/titanic_importance_neg.npy") print(data) for i in range(1, 10): largest_sum, time_elapsed, _, _, _, _ = multiple_init_kmax(data, 2, i, init_num = 10) print("Largest sum\t", np.max(largest_sum))
[ 11748, 299, 32152, 355, 45941, 220, 198, 11748, 4738, 198, 11748, 640, 198, 11748, 4866, 198, 198, 4299, 479, 9806, 7, 7890, 11, 2315, 62, 1087, 380, 375, 11, 406, 796, 362, 11, 509, 796, 220, 513, 11, 3509, 62, 2676, 602, 796, 20...
2.185163
1,685
''' Module to generate the TC with the given probability to "go straight", "turn left" or "turn right" ''' import numpy as np from car_road import Map import os import config as cf import json class RoadGen: """Class for generating roads""" def test_case_generate(self): """Function that produces a list with states and road points""" # initialization self.road_points = [] self.init_states = ["straight", "left", "right"] self.car_map = Map(self.map_size) self.init_a = [int(self.car_map.init_pos[0]), int(self.car_map.init_pos[1])] self.init_b = [int(self.car_map.init_end[0]), int(self.car_map.init_end[1])] self.road_points.append( tuple( ( (self.init_a[0] + self.init_b[0]) / 2, (self.init_a[1] + self.init_b[1]) / 2, ) ) ) self.car_map.go_straight(5) self.road_points.append( tuple((self.car_map.current_pos[0] + self.car_map.current_pos[1]) / 2) ) self.states = [["straight", 5]] state = "straight" flag = True while flag == True: if state == "straight": change = np.random.choice( self.transitionName[0], p=self.transitionMatrix[0] ) # choose the next state if change == "SS": # stay in the same state value = np.random.choice(self.len_values) state = "straight" self.states.append([state, value]) flag = self.car_map.go_straight(value) if flag == False: del self.road_points[-1] del self.states[-1] if len(self.road_points) <= 2: self.car_map.go_straight(1) self.road_points.append( tuple( ( self.car_map.current_pos[0] + self.car_map.current_pos[1] ) / 2 ) ) return self.states_to_dict() self.road_points.append( tuple( (self.car_map.current_pos[0] + self.car_map.current_pos[1]) / 2 ) ) pass elif change == "SL": # change from go straight to turn left value = np.random.choice(self.ang_values) state = "left" self.states.append([state, value]) flag = self.car_map.turn_left(value) if flag == False: del self.road_points[-1] del self.states[-1] if len(self.road_points) <= 2: self.car_map.go_straight(1) self.road_points.append( tuple( ( self.car_map.current_pos[0] + self.car_map.current_pos[1] ) / 2 ) ) return self.states_to_dict() self.road_points.append( tuple( (self.car_map.current_pos[0] + self.car_map.current_pos[1]) / 2 ) ) pass elif change == "SR": value = np.random.choice(self.ang_values) state = "right" self.states.append([state, value]) flag = self.car_map.turn_right(value) if flag == False: del self.road_points[-1] del self.states[-1] if len(self.road_points) <= 2: self.car_map.go_straight(1) self.road_points.append( tuple( ( self.car_map.current_pos[0] + self.car_map.current_pos[1] ) / 2 ) ) return self.states_to_dict() self.road_points.append( tuple( (self.car_map.current_pos[0] + self.car_map.current_pos[1]) / 2 ) ) pass else: print("Error") elif state == "left": change = np.random.choice( self.transitionName[1], p=self.transitionMatrix[1] ) if change == "LS": value = np.random.choice(self.len_values) state = "straight" self.states.append([state, value]) flag = self.car_map.go_straight(value) if flag == False: del self.road_points[-1] del self.states[-1] if len(self.road_points) <= 2: self.car_map.go_straight(1) self.road_points.append( tuple( ( self.car_map.current_pos[0] + self.car_map.current_pos[1] ) / 2 ) ) return self.states_to_dict() self.road_points.append( tuple( (self.car_map.current_pos[0] + self.car_map.current_pos[1]) / 2 ) ) pass elif change == "LL": value = np.random.choice(self.ang_values) state = "left" self.states.append([state, value]) flag = self.car_map.turn_left(value) if flag == False: del self.road_points[-1] del self.states[-1] if len(self.road_points) <= 2: self.car_map.go_straight(1) self.road_points.append( tuple( ( self.car_map.current_pos[0] + self.car_map.current_pos[1] ) / 2 ) ) return self.states_to_dict() self.road_points.append( tuple( (self.car_map.current_pos[0] + self.car_map.current_pos[1]) / 2 ) ) pass elif change == "LR": value = np.random.choice(self.ang_values) state = "right" self.states.append([state, value]) flag = self.car_map.turn_right(value) if flag == False: del self.road_points[-1] del self.states[-1] if len(self.road_points) <= 2: self.car_map.go_straight(1) self.road_points.append( tuple( ( self.car_map.current_pos[0] + self.car_map.current_pos[1] ) / 2 ) ) return self.states_to_dict() self.road_points.append( tuple( (self.car_map.current_pos[0] + self.car_map.current_pos[1]) / 2 ) ) pass else: print("Error") pass elif state == "right": change = np.random.choice( self.transitionName[2], p=self.transitionMatrix[2] ) if change == "RS": value = np.random.choice(self.len_values) state = "straight" self.states.append([state, value]) flag = self.car_map.go_straight(value) if flag == False: del self.road_points[-1] del self.states[-1] if len(self.road_points) <= 2: self.car_map.go_straight(1) self.road_points.append( tuple( ( self.car_map.current_pos[0] + self.car_map.current_pos[1] ) / 2 ) ) return self.states_to_dict() self.road_points.append( tuple( (self.car_map.current_pos[0] + self.car_map.current_pos[1]) / 2 ) ) pass elif change == "RL": value = np.random.choice(self.ang_values) state = "left" self.states.append([state, value]) flag = self.car_map.turn_left(value) if flag == False: del self.road_points[-1] del self.states[-1] if len(self.road_points) <= 2: self.car_map.go_straight(1) self.road_points.append( tuple( ( self.car_map.current_pos[0] + self.car_map.current_pos[1] ) / 2 ) ) return self.states_to_dict() self.road_points.append( tuple( (self.car_map.current_pos[0] + self.car_map.current_pos[1]) / 2 ) ) pass elif change == "RR": value = np.random.choice(self.ang_values) state = "right" self.states.append([state, value]) flag = self.car_map.turn_right(value) if flag == False: del self.road_points[-1] del self.states[-1] if len(self.road_points) <= 2: self.car_map.go_straight(1) self.road_points.append( tuple( ( self.car_map.current_pos[0] + self.car_map.current_pos[1] ) / 2 ) ) return self.states_to_dict() self.road_points.append( tuple( (self.car_map.current_pos[0] + self.car_map.current_pos[1]) / 2 ) ) pass else: print("Error") del self.road_points[-1] # last point might be going over the border del self.states[-1] return self.states_to_dict() def states_to_dict(self): """Transforms a list of test cases to a dictionary""" test_cases = {} i = 0 for element in self.states: test_cases["st" + str(i)] = {} test_cases["st" + str(i)]["state"] = element[0] test_cases["st" + str(i)]["value"] = int(element[1]) i += 1 # print("test_cases", test_cases) return test_cases def write_states_to_file(self): """Writes the generated test case to file""" if os.stat(self.file).st_size == 0: test_cases = {} else: with open(self.file) as file: test_cases = json.load(file) if os.stat(self.init_file).st_size == 0: positions = {} else: with open(self.init_file) as file: positions = json.load(file) if os.stat(self.points_file).st_size == 0: points = {} else: with open(self.points_file) as file: points = json.load(file) num = len(test_cases) tc = "tc" + str(num) test_cases[tc] = {} positions[tc] = {"a": self.init_a, "b": self.init_b} points[tc] = self.road_points i = 0 for element in self.states: test_cases[tc]["st" + str(i)] = {} test_cases[tc]["st" + str(i)]["state"] = str(element[0]) test_cases[tc]["st" + str(i)]["value"] = int(element[1]) i += 1 with open(self.file, "w") as outfile: json.dump(test_cases, outfile) with open(self.init_file, "w") as outfile: json.dump(positions, outfile) with open(self.points_file, "w") as outfile: json.dump(points, outfile) if __name__ == "__main__": # steps = [5, 6, 7] i = 0 road = RoadGen(250, 5, 50, 10, 70) while i < 100: # generate N number of schedules print("generating test case" + str(i)) road.test_case_generate() road.write_states_to_file() i += 1
[ 7061, 6, 198, 26796, 284, 7716, 262, 17283, 351, 262, 1813, 12867, 284, 366, 2188, 3892, 1600, 366, 15344, 1364, 1, 393, 366, 15344, 826, 1, 198, 7061, 6, 198, 198, 11748, 299, 32152, 355, 45941, 198, 198, 6738, 1097, 62, 6344, 1330...
1.482099
10,251
import logging from scipy.interpolate import splev, splrep import numpy as np from barry.cosmology import pk2xi from barry.cosmology.camb_generator import getCambGenerator from barry.datasets import PowerSpectrum_SDSS_DR12_Z061_NGC, CorrelationFunction_SDSS_DR12_Z061_NGC class DummyPowerSpectrum_SDSS_DR12_Z061_NGC(PowerSpectrum_SDSS_DR12_Z061_NGC): """ Dummy power spectrum. Uses CAMB's linear power spectrum and faked uncertainty. Utilised the SDSS DR12 window function, with option to make a dummy window function too. """ class DummyCorrelationFunction_SDSS_DR12_Z061_NGC(CorrelationFunction_SDSS_DR12_Z061_NGC): """ Dummy correlation function. Uses CAMB's linear power spectrum and faked uncertainty. """ if __name__ == "__main__": logging.basicConfig(level=logging.DEBUG, format="[%(levelname)7s |%(funcName)18s] %(message)s") dataset = DummyPowerSpectrum_SDSS_DR12_Z061_NGC() data = dataset.get_data() import matplotlib.pyplot as plt import seaborn as sb import numpy as np plt.errorbar(data["ks"], data["ks"] * data["pk"], yerr=data["ks"] * np.sqrt(np.diag(data["cov"])), fmt="o", c="k") plt.show() sb.heatmap(data["cov"]) plt.show()
[ 11748, 18931, 198, 6738, 629, 541, 88, 13, 3849, 16104, 378, 1330, 599, 2768, 11, 4328, 7856, 198, 11748, 299, 32152, 355, 45941, 198, 198, 6738, 2318, 563, 13, 6966, 29126, 1330, 279, 74, 17, 29992, 198, 6738, 2318, 563, 13, 6966, ...
2.527835
485
import logging from datetime import datetime import django_rq from api.models import CheckTaskJob from utils.check_url import check_url logger = logging.getLogger(__name__)
[ 11748, 18931, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 198, 11748, 42625, 14208, 62, 81, 80, 198, 198, 6738, 40391, 13, 27530, 1330, 6822, 25714, 33308, 198, 6738, 3384, 4487, 13, 9122, 62, 6371, 1330, 2198, 62, 6371, 198, 198, 6...
3.178571
56
#!/usr/bin/env python from optparse import OptionParser parser = OptionParser(usage="%prog infile outfile") opts, args = parser.parse_args() try: infile, outfile = args except ValueError: infile = "/data/uwa/jvansanten/projects/2012/muongun/corsika/SIBYLL/Hoerandel5/atmod_12.hdf5" outfile = "Hoerandel5_atmod12_SIBYLL.radius.fits" print(infile, outfile) import numpy, tables, dashi, os from icecube.photospline import spglam as glam from icecube.photospline import splinefitstable from utils import load_radial_distribution, pad_knots bias = 50 h = load_radial_distribution(infile, bias) extents = [(e[1], e[-2]) for e in h._h_binedges] # construct a pseudo-chi^2 weight such that weight_i*(log(x_i + sigma_i) - log(x_i)) = 1 weights = 1./(numpy.log(numpy.exp(h.bincontent - bias) + numpy.sqrt(h._h_squaredweights[h._h_visiblerange])) - (h.bincontent - bias)) weights[numpy.logical_not(numpy.isfinite(weights))] = 0 weights[:,:,0,:] = 0 # ignore the single-track bin # weights[0,:,6,:] = 0 # ignore high-multiplicity bin at the horizon knots = [ pad_knots(numpy.linspace(0, 1, 11), 2), # cos(theta) pad_knots(numpy.linspace(1, 3, 11), 2), # vertical depth [km] pad_knots(numpy.linspace(0, numpy.sqrt(100), 15)**2, 2), # bundle multiplicity pad_knots(numpy.linspace(0, numpy.sqrt(250), 25)**2, 2), # radius [m] ] smooth = weights[weights > 0].mean() # make the smoothing term proportional to the weights order = [2,2,2,2] penalties = {2:[smooth/1e5, smooth/1e5, smooth/1e4, smooth/10]} # Penalize curvature spline = glam.fit(h.bincontent,weights,h._h_bincenters,knots,order,smooth,penalties=penalties) spline.bias = bias if os.path.exists(outfile): os.unlink(outfile) splinefitstable.write(spline, outfile)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 6738, 2172, 29572, 1330, 16018, 46677, 198, 198, 48610, 796, 16018, 46677, 7, 26060, 2625, 4, 1676, 70, 1167, 576, 503, 7753, 4943, 198, 404, 912, 11, 26498, 796, 30751, 13, 29572...
2.467143
700
#!/usr/bin/env python # -*- coding: utf-8 -*- from executiveorder.util import * from executiveorder.executiveorder import ExecutiveOrder base_url = "https://en.wikisource.org" url = "/wiki/Category:United_States_executive_orders" eos = [] def get_all_pages(url): ''' Gets all the pages in the base site. ''' soup = get_soup(base_url+url) links = soup.find_all('a', { 'class': 'CategoryTreeLabel' } ) links = [link for link in links if is_int(link.text[-4:]) ] result = [] for link in links: link_text = link.text[-4:] print link_text,"...", soup_page = get_soup(base_url+link['href']) sub_pages = soup_page.find(id='mw-pages').find_all('a') print "found",str(len(sub_pages)) for sub_page in sub_pages: result.append(sub_page['href']) return result def crawl(url): ''' Crawls a url. ''' soup = get_soup(base_url+url) result = parse_page(soup) return result def parse_page(soup): ''' Parses the HTML of a page. ''' eo = ExecutiveOrder() parse_heading(eo,soup) if soup.find(id='nav_cite_bar') is None: return eo parse_cite_bar(eo,soup) parse_amendments(eo,soup) return eo def parse_heading(eo,soup): ''' Parses the heading for the title and number. ''' number = soup.find(id='firstHeading').text.split(' ')[-1] div = soup.find(id='navigationHeader') section_title = div.find(id='header_section_text') if section_title is not None: title = section_title.text else: title = div.find(id='header_title_text').text eo.number = number eo.title = title return eo def parse_cite_bar(eo,soup): ''' Parses the cite bar for author, statute, FR, publication and signed date. ''' div = soup.find(id='nav_cite_bar') links = div.find_all('a') links = [link for link in links if 'Signed' not in link.text] cite_bar = div.text.strip() if links[0] is not None: author = links[0].text.split(' ') lenauthor = len(links[0].text) ind = cite_bar.index(links[0].text) eo.author = format_president_name(author) date_and_cite = cite_bar[ind+lenauthor:].split('\n') eo.signed_date = date_and_cite[0] for link in links[1:]: if 'Stat' in link.text: eo.statute = link.text if is_int(link.text): eo.fr = int(link.text) eo.pdf = link['href'] for cite in date_and_cite[1:]: if 'FR' in cite: fr = cite.split(' ')[2] ind = cite.index(fr) eo.published_date = cite[ind+len(fr):] return eo def parse_amendments(eo,soup): ''' Parses the Notes section for any possible amendments. ''' div = soup.find(id='Notes') if div is None: return amends = [] div = div.parent.parent dt = div.find('dt') if dt is not None and 'Amends' in dt.text: items = dt.parent.find_next('ul').find_all('li') for item in items: link = item.find('a') if link is not None: amends.append(link.text.split(' ')[-1]) eo.amends = amends return eo def format_president_name(name): ''' Formats the president name to be FIRST-NAME MIDDLE-INITIALS LAST-NAME. ''' out_name = [i[0].upper() for i in name] out_name[0] = name[0].decode('utf-8').upper() out_name[-1] = name[-1].decode('utf-8').upper() return " ".join([unicode(i) for i in out_name])
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 4640, 2875, 13, 22602, 1330, 1635, 198, 6738, 4640, 2875, 13, 18558, 8827, 2875, 1330, 10390, 18743, 198, 198, 86...
2.415623
1,357
import heterocl as hcl if __name__ == "__main__": test()
[ 11748, 14445, 38679, 355, 289, 565, 628, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 1332, 3419 ]
2.583333
24
""" Given the mapping a = 1, b = 2, ... z = 26, and an encoded message, count the number of ways it can be decoded. For example, the message '111' would give 3, since it could be decoded as 'aaa', 'ka', and 'ak'. You can assume that the messages are decodable. For example, '001' is not allowed. """ import time encode_message = "11111111111111111111111111111" start_time = time.time() print(num_ways(encode_message)) end_time = time.time() print(end_time - start_time) start_time = time.time() print(num_ways_dp(encode_message)) end_time = time.time() print(end_time - start_time)
[ 37811, 201, 198, 15056, 262, 16855, 257, 796, 352, 11, 275, 796, 362, 11, 2644, 1976, 796, 2608, 11, 290, 281, 30240, 3275, 11, 954, 262, 1271, 286, 2842, 340, 460, 307, 875, 9043, 13, 201, 198, 201, 198, 1890, 1672, 11, 262, 3275...
2.703057
229
from selenium import webdriver from selenium.webdriver.common.keys import Keys import os import time #"./chromedriver" PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__)) DRIVER_BIN = os.path.join(PROJECT_ROOT, "chromedriver.exe") browser = webdriver.Chrome(executable_path = DRIVER_BIN) browser.get("https://en.wiktionary.org/wiki/Wiktionary:Main_Page") time.sleep(10) print ("Driver chrome Initialized") browser.quit()
[ 6738, 384, 11925, 1505, 1330, 3992, 26230, 198, 6738, 384, 11925, 1505, 13, 12384, 26230, 13, 11321, 13, 13083, 1330, 26363, 198, 11748, 28686, 198, 11748, 640, 198, 198, 2, 1911, 14, 28663, 276, 38291, 1, 198, 198, 31190, 23680, 62, ...
2.757962
157
import logging import re import os import glob class FileOpener: ''' Test class that hosts common file functions like opening text files ''' @classmethod def open_text_file(cls, filename: str, lowercase: bool = True) -> str: """Opens and returns text file in utf-8-sig encoding Args: filename (str): text file to open lowercase (bool): defines if returned str is converted to lovercase or not. Default - True Raises: FileNotFoundError: if file is not found Returns: str: contents of the text file converted to lowercase """ try: with open(filename, 'r', encoding='utf-8-sig') as text_file: # 'utf-8-sig' is mandatory for UTF-8 w/BOM if lowercase: return text_file.read().lower() else: return text_file.read() except Exception as ex: logging.error(f"Skipping the file {filename}, {ex}") raise FileNotFoundError(f"Can't open the file {filename}") @classmethod def replace_all_keys_in_file_with_values(cls, path_to_files: str, dict_with_strings_to_replace: dict, lowercase: bool = True) -> None: """Parse all files in passed dictionary and replaces encountered keys with values from passed dict Args: path_to_files (str): path to folder with files to open dict_with_strings_to_replace (dict): dict with keys that represent the string to replace, and values to replace keys with lowercase (bool, optional): if opened files should be in lowercase. Defaults to True. """ for filename in glob.iglob(path_to_files + '**/*.txt', recursive=True): text_file = FileOpener.open_text_file(filename, lowercase=lowercase) for key, value in dict_with_strings_to_replace.items(): if key in text_file: text_file = text_file.replace(key, value) with open(filename, 'w', encoding='utf-8') as text_file_write: text_file_write.write(text_file)
[ 11748, 18931, 198, 11748, 302, 198, 11748, 28686, 198, 11748, 15095, 628, 198, 4871, 9220, 18257, 877, 25, 198, 220, 220, 220, 705, 7061, 198, 220, 220, 220, 6208, 1398, 326, 11453, 2219, 2393, 5499, 588, 4756, 2420, 3696, 198, 220, 2...
2.38324
895
# # Copyright 2021 Red Hat Inc. # SPDX-License-Identifier: Apache-2.0 # """ Handler module for gathering configuration data. """ from .env import ENVIRONMENT CLOWDER_ENABLED = ENVIRONMENT.bool("CLOWDER_ENABLED", default=False) if CLOWDER_ENABLED: from app_common_python import ObjectBuckets, LoadedConfig, KafkaTopics, DependencyEndpoints class Configurator: """Obtain configuration based on mode.""" @staticmethod def is_clowder_enabled(): """Check if clowder is enabled.""" return CLOWDER_ENABLED @staticmethod def get_in_memory_db_host(): """Obtain in memory (redis) db host.""" pass @staticmethod def get_in_memory_db_port(): """Obtain in memory (redis) db port.""" pass @staticmethod def get_kafka_broker_host(): """Obtain kafka broker host address.""" pass @staticmethod def get_kafka_broker_port(): """Obtain kafka broker port.""" pass @staticmethod def get_kafka_topic(requestedName: str): """Obtain kafka topic.""" pass @staticmethod def get_cloudwatch_access_id(): """Obtain cloudwatch access id.""" pass @staticmethod def get_cloudwatch_access_key(): """Obtain cloudwatch access key.""" pass @staticmethod def get_cloudwatch_region(): """Obtain cloudwatch region.""" pass @staticmethod def get_cloudwatch_log_group(): """Obtain cloudwatch log group.""" pass @staticmethod def get_object_store_endpoint(): """Obtain object store endpoint.""" pass @staticmethod def get_object_store_host(): """Obtain object store host.""" pass @staticmethod def get_object_store_port(): """Obtain object store port.""" pass @staticmethod def get_object_store_tls(): """Obtain object store secret key.""" pass @staticmethod def get_object_store_access_key(requestedName: str = ""): """Obtain object store access key.""" pass @staticmethod def get_object_store_secret_key(requestedName: str = ""): """Obtain object store secret key.""" pass @staticmethod def get_object_store_bucket(requestedName: str = ""): """Obtain object store bucket.""" pass @staticmethod def get_database_name(): """Obtain database name.""" pass @staticmethod def get_database_user(): """Obtain database user.""" pass @staticmethod def get_database_password(): """Obtain database password.""" pass @staticmethod def get_database_host(): """Obtain database host.""" pass @staticmethod def get_database_port(): """Obtain database port.""" pass @staticmethod def get_database_ca(): """Obtain database ca.""" pass @staticmethod def get_database_ca_file(): """Obtain database ca file.""" pass @staticmethod def get_metrics_port(): """Obtain metrics port.""" pass @staticmethod def get_metrics_path(): """Obtain metrics path.""" pass @staticmethod def get_endpoint_host(app, name, default): """Obtain endpoint hostname.""" pass @staticmethod def get_endpoint_port(app, name, default): """Obtain endpoint port.""" pass class EnvConfigurator(Configurator): """Returns information based on the environment data""" @staticmethod def get_in_memory_db_host(): """Obtain in memory (redis) db host.""" return ENVIRONMENT.get_value("REDIS_HOST", default="redis") @staticmethod def get_in_memory_db_port(): """Obtain in memory (redis) db port.""" return ENVIRONMENT.get_value("REDIS_PORT", default="6379") @staticmethod def get_kafka_broker_host(): """Obtain kafka broker host address.""" return ENVIRONMENT.get_value("INSIGHTS_KAFKA_HOST", default="localhost") @staticmethod def get_kafka_broker_port(): """Obtain kafka broker port.""" return ENVIRONMENT.get_value("INSIGHTS_KAFKA_PORT", default="29092") @staticmethod def get_kafka_topic(requestedName: str): """Obtain kafka topic.""" return requestedName @staticmethod def get_cloudwatch_access_id(): """Obtain cloudwatch access id.""" return ENVIRONMENT.get_value("CW_AWS_ACCESS_KEY_ID", default=None) @staticmethod def get_cloudwatch_access_key(): """Obtain cloudwatch access key.""" return ENVIRONMENT.get_value("CW_AWS_SECRET_ACCESS_KEY", default=None) @staticmethod def get_cloudwatch_region(): """Obtain cloudwatch region.""" return ENVIRONMENT.get_value("CW_AWS_REGION", default="us-east-1") @staticmethod def get_cloudwatch_log_group(): """Obtain cloudwatch log group.""" return ENVIRONMENT.get_value("CW_LOG_GROUP", default="platform-dev") @staticmethod def get_object_store_endpoint(): """Obtain object store endpoint.""" S3_ENDPOINT = ENVIRONMENT.get_value("S3_ENDPOINT", default="s3.us-east-1.amazonaws.com") if not (S3_ENDPOINT.startswith("https://") or S3_ENDPOINT.startswith("http://")): S3_ENDPOINT = "https://" + S3_ENDPOINT return S3_ENDPOINT @staticmethod def get_object_store_host(): """Obtain object store host.""" # return ENVIRONMENT.get_value("S3_HOST", default=None) pass @staticmethod def get_object_store_port(): """Obtain object store port.""" # return ENVIRONMENT.get_value("S3_PORT", default=443) pass @staticmethod def get_object_store_tls(): """Obtain object store secret key.""" # return ENVIRONMENT.bool("S3_SECURE", default=False) pass @staticmethod def get_object_store_access_key(requestedName: str = ""): """Obtain object store access key.""" return ENVIRONMENT.get_value("S3_ACCESS_KEY", default=None) @staticmethod def get_object_store_secret_key(requestedName: str = ""): """Obtain object store secret key.""" return ENVIRONMENT.get_value("S3_SECRET", default=None) @staticmethod def get_object_store_bucket(requestedName: str = ""): """Obtain object store bucket.""" return ENVIRONMENT.get_value("S3_BUCKET_NAME", default=requestedName) @staticmethod def get_database_name(): """Obtain database name.""" return ENVIRONMENT.get_value("DATABASE_NAME", default="postgres") @staticmethod def get_database_user(): """Obtain database user.""" return ENVIRONMENT.get_value("DATABASE_USER", default="postgres") @staticmethod def get_database_password(): """Obtain database password.""" return ENVIRONMENT.get_value("DATABASE_PASSWORD", default="postgres") @staticmethod def get_database_host(): """Obtain database host.""" SERVICE_NAME = ENVIRONMENT.get_value("DATABASE_SERVICE_NAME", default="").upper().replace("-", "_") return ENVIRONMENT.get_value(f"{SERVICE_NAME}_SERVICE_HOST", default="localhost") @staticmethod def get_database_port(): """Obtain database port.""" SERVICE_NAME = ENVIRONMENT.get_value("DATABASE_SERVICE_NAME", default="").upper().replace("-", "_") return ENVIRONMENT.get_value(f"{SERVICE_NAME}_SERVICE_PORT", default="15432") @staticmethod def get_database_ca(): """Obtain database ca.""" return ENVIRONMENT.get_value("DATABASE_SERVICE_CERT", default=None) @staticmethod def get_database_ca_file(): """Obtain database ca file.""" return ENVIRONMENT.get_value("DATABASE_SERVICE_CERTFILE", default="/etc/ssl/certs/server.pem") @staticmethod def get_metrics_port(): """Obtain metrics port.""" return 8080 @staticmethod def get_metrics_path(): """Obtain metrics path.""" return "/metrics" @staticmethod def get_endpoint_host(app, name, default): """Obtain endpoint hostname.""" svc = "_".join((app, name, "HOST")).replace("-", "_").upper() return ENVIRONMENT.get_value(svc, default=default) @staticmethod def get_endpoint_port(app, name, default): """Obtain endpoint port.""" svc = "_".join((app, name, "PORT")).replace("-", "_").upper() return ENVIRONMENT.get_value(svc, default=default) class ClowderConfigurator(Configurator): """Obtain configuration based on using Clowder and app-common.""" @staticmethod def get_in_memory_db_host(): """Obtain in memory (redis) db host.""" return LoadedConfig.inMemoryDb.hostname # TODO: if we drop an elasticache instance or clowder supports more # than 1 elasticache instance, we can switch to using the inMemoryDb # return ENVIRONMENT.get_value("REDIS_HOST", default="redis") @staticmethod def get_in_memory_db_port(): """Obtain in memory (redis) db port.""" return LoadedConfig.inMemoryDb.port # return ENVIRONMENT.get_value("REDIS_PORT", default="6379") @staticmethod def get_kafka_broker_host(): """Obtain kafka broker host address.""" return LoadedConfig.kafka.brokers[0].hostname @staticmethod def get_kafka_broker_port(): """Obtain kafka broker port.""" return LoadedConfig.kafka.brokers[0].port @staticmethod def get_kafka_topic(requestedName: str): """Obtain kafka topic.""" return KafkaTopics.get(requestedName).name @staticmethod def get_cloudwatch_access_id(): """Obtain cloudwatch access id.""" return LoadedConfig.logging.cloudwatch.accessKeyId @staticmethod def get_cloudwatch_access_key(): """Obtain cloudwatch access key.""" return LoadedConfig.logging.cloudwatch.secretAccessKey @staticmethod def get_cloudwatch_region(): """Obtain cloudwatch region.""" return LoadedConfig.logging.cloudwatch.region @staticmethod def get_cloudwatch_log_group(): """Obtain cloudwatch log group.""" return LoadedConfig.logging.cloudwatch.logGroup @staticmethod def get_object_store_endpoint(): """Obtain object store endpoint.""" S3_SECURE = CONFIGURATOR.get_object_store_tls() S3_HOST = CONFIGURATOR.get_object_store_host() S3_PORT = CONFIGURATOR.get_object_store_port() S3_PREFIX = "https://" if S3_SECURE else "http://" endpoint = f"{S3_PREFIX}{S3_HOST}" if bool(S3_PORT): endpoint += f":{S3_PORT}" return endpoint @staticmethod def get_object_store_host(): """Obtain object store host.""" return LoadedConfig.objectStore.hostname @staticmethod def get_object_store_port(): """Obtain object store port.""" return LoadedConfig.objectStore.port @staticmethod def get_object_store_tls(): """Obtain object store secret key.""" value = LoadedConfig.objectStore.tls if type(value) == bool: return value if value and value.lower() in ["true", "false"]: return value.lower() == "true" else: return False @staticmethod def get_object_store_access_key(requestedName: str = ""): """Obtain object store access key.""" if requestedName != "" and ObjectBuckets.get(requestedName): return ObjectBuckets.get(requestedName).accessKey if len(LoadedConfig.objectStore.buckets) > 0: return LoadedConfig.objectStore.buckets[0].accessKey if LoadedConfig.objectStore.accessKey: return LoadedConfig.objectStore.accessKey @staticmethod def get_object_store_secret_key(requestedName: str = ""): """Obtain object store secret key.""" if requestedName != "" and ObjectBuckets.get(requestedName): return ObjectBuckets.get(requestedName).secretKey if len(LoadedConfig.objectStore.buckets) > 0: return LoadedConfig.objectStore.buckets[0].secretKey if LoadedConfig.objectStore.secretKey: return LoadedConfig.objectStore.secretKey @staticmethod def get_object_store_bucket(requestedName: str = ""): """Obtain object store bucket.""" if ObjectBuckets.get(requestedName): return ObjectBuckets.get(requestedName).name return requestedName @staticmethod def get_database_name(): """Obtain database name.""" return LoadedConfig.database.name @staticmethod def get_database_user(): """Obtain database user.""" return LoadedConfig.database.username @staticmethod def get_database_password(): """Obtain database password.""" return LoadedConfig.database.password @staticmethod def get_database_host(): """Obtain database host.""" return LoadedConfig.database.hostname @staticmethod def get_database_port(): """Obtain database port.""" return LoadedConfig.database.port @staticmethod def get_database_ca(): """Obtain database ca.""" return LoadedConfig.database.rdsCa @staticmethod def get_database_ca_file(): """Obtain database ca file.""" if LoadedConfig.database.rdsCa: return LoadedConfig.rds_ca() return None @staticmethod def get_metrics_port(): """Obtain metrics port.""" return LoadedConfig.metricsPort @staticmethod def get_metrics_path(): """Obtain metrics path.""" return LoadedConfig.metricsPath @staticmethod def get_endpoint_host(app, name, default): """Obtain endpoint hostname.""" endpoint = DependencyEndpoints.get(app, {}).get(name) if endpoint: return endpoint.hostname # if the endpoint is not defined by clowder, fall back to env variable svc = "_".join((app, name, "HOST")).replace("-", "_").upper() return ENVIRONMENT.get_value(svc, default=default) @staticmethod def get_endpoint_port(app, name, default): """Obtain endpoint port.""" endpoint = DependencyEndpoints.get(app, {}).get(name) if endpoint: return endpoint.port # if the endpoint is not defined by clowder, fall back to env variable svc = "_".join((app, name, "PORT")).replace("-", "_").upper() return ENVIRONMENT.get_value(svc, default=default) class ConfigFactory: """Returns configurator based on mode.""" @staticmethod def get_configurator(): """Returns configurator based on mode from env variable.""" return ClowderConfigurator if CLOWDER_ENABLED else EnvConfigurator CONFIGURATOR = ConfigFactory.get_configurator()
[ 2, 198, 2, 15069, 33448, 2297, 10983, 3457, 13, 198, 2, 30628, 55, 12, 34156, 12, 33234, 7483, 25, 24843, 12, 17, 13, 15, 198, 2, 198, 37811, 198, 25060, 8265, 329, 11228, 8398, 1366, 13, 198, 37811, 198, 6738, 764, 24330, 1330, 1...
2.435233
6,176
from thefuck import shells
[ 6738, 262, 31699, 1330, 19679, 628, 198 ]
4.142857
7
from random import randint from time import sleep from player import Player
[ 6738, 4738, 1330, 43720, 600, 198, 6738, 640, 1330, 3993, 198, 6738, 2137, 1330, 7853, 198 ]
4.75
16
import EulerRunner numFile = open('../data/Problem067_numbers.txt', 'r') nums = [[int(num) for num in line.split(' ')] for line in numFile.readlines()] print len(nums) print len(nums[-1]) EulerRunner.solve_problem(problem67_dp)
[ 11748, 412, 18173, 49493, 198, 198, 22510, 8979, 796, 1280, 10786, 40720, 7890, 14, 40781, 15, 3134, 62, 77, 17024, 13, 14116, 3256, 705, 81, 11537, 198, 77, 5700, 796, 16410, 600, 7, 22510, 8, 329, 997, 287, 1627, 13, 35312, 10786, ...
2.613636
88
# -*- coding: utf-8 -*- import os import shutil import numpy as np import six import tensorflow as tf from tfsnippet.utils import (ensure_variables_initialized, VarScopeObject, get_variables_as_dict, reopen_variable_scope, VariableSaver, lagacy_default_name_arg) __all__ = ['Model'] class Model(VarScopeObject): """Scaffold for defining models with TensorFlow. This class provides a basic scaffold for defining models with TensorFlow. It settles a common practice for organizing the variables of parameters, as well as variables for training and prediction Parameters ---------- name : str Name of the model. When `scope` is not specified, the model will obtain a variable scope with unique name, according to the name suggested by `name`. If `name` is also not specified, it will use the underscored class name as the default name. scope : str Scope of the model. Note that if `scope` is specified, the variable scope of constructed model will take exactly this scope, even if another model has already taken such scope. That is to say, these two models will share the same variable scope. global_step : tf.Variable Manually specify a `global_step` variable instead of using the one which is created inside the model variable scope. """ @lagacy_default_name_arg @property def has_built(self): """Whether or not the model has been built?""" return self._has_built def set_global_step(self, global_step): """Manually set a variable as global step. This method must be called before `build` or any other method that will cause the model to be built has been called. Parameters ---------- global_step : tf.Variable The global step variable to use. Raises ------ RuntimeError If the `global_step` has already been set or created. """ if self._global_step is not None: raise RuntimeError( 'The `global_step` variable has already been set or created.') self._global_step = global_step def get_global_step(self): """Get the global step variable of this model.""" self.build() return self._global_step def build(self): """Build the model and the trainer. Although this method will be called automatically when the model is required to be built, however, it is recommended to call this method soon after the model object is constructed. """ if self._has_built: return self._has_built = True with reopen_variable_scope(self.variable_scope): # create the global step variable if there's none if self._global_step is None: self._global_step = tf.get_variable( 'global_step', dtype=tf.int64, trainable=False, initializer=np.asarray(0, dtype=np.int64) ) # build the model self._build() def _build(self): """Build the main part of the model. Derived classes should override this to actually build the model. Note that all the variables to be considered as parameters must be created within the "model" sub-scope, which will be saved and restored via the interfaces of this class. For example, one may override the `_build` method as follows: class MyModel(Model): def _build(self): with tf.variable_scope('model'): hidden_layer = layers.fully_connected( self.input_x, num_outputs=100 ) self.output = layers.fully_connected( hidden_layer, num_outputs=1 ) with tf.variable_scope('train'): loss = tf.reduce_mean( tf.square(self.output - self.label) ) self.train_op = tf.AdamOptimizer().minimize(loss) In this way, any variables introduced by the trainer will not be collected as parameter variables (although they will still be considered as model variables, and can be collected by the method `get_variables`). """ raise NotImplementedError() def get_variables(self, collection=tf.GraphKeys.GLOBAL_VARIABLES): """Get the variables defined within the model's scope. This method will get variables which are in `variable_scope` and the specified `collection`, as a dict which maps relative names to variable objects. By "relative name" we mean to remove the name of `variable_scope` from the front of variable names. Parameters ---------- collection : str The name of the variable collection. If not specified, will use `tf.GraphKeys.GLOBAL_VARIABLES`. Returns ------- dict[str, tf.Variable] Dict which maps from relative names to variable objects. """ self.build() return get_variables_as_dict(self.variable_scope, collection=collection) def get_param_variables(self, collection=tf.GraphKeys.GLOBAL_VARIABLES): """Get the parameter variables. The parameter variables are the variables defined in "model" sub-scope within the model's variable scope. Parameters ---------- collection : str The name of the variable collection. If not specified, will use `tf.GraphKeys.GLOBAL_VARIABLES`. Returns ------- dict[str, tf.Variable] Dict which maps from relative names to variable objects. """ self.build() vs_name = self.variable_scope.name + '/' if vs_name and not vs_name.endswith('/'): vs_name += '/' vs_name += 'model/' variables = get_variables_as_dict(vs_name, collection=collection) return {'model/' + k: v for k, v in six.iteritems(variables)} def ensure_variables_initialized(self): """Initialize all uninitialized variables within model's scope. If the `global_step` is created by the model itself, then it will also be initialized. Otherwise the `global_step` must be manually initialized. """ self.build() var_list = list(six.itervalues(self.get_variables())) ensure_variables_initialized(var_list) def save_model(self, save_dir, overwrite=False): """Save the model parameters onto disk. Parameters ---------- save_dir : str Directory where to place the saved variables. overwrite : bool Whether or not to overwrite the existing directory? """ self.build() path = os.path.abspath(save_dir) if os.path.exists(path): if overwrite: if os.path.isdir(path): shutil.rmtree(path) else: os.remove(path) elif not os.path.isdir(path) or len(os.listdir(path)) > 0: raise IOError('%r already exists.' % save_dir) saver = VariableSaver(self.get_param_variables(), path) saver.save() def load_model(self, save_dir): """Load the model parameters from disk. Parameters ---------- save_dir : str Directory where the saved variables are placed. """ self.build() path = os.path.abspath(save_dir) saver = VariableSaver(self.get_param_variables(), path) saver.restore(ignore_non_exist=False)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 28686, 198, 11748, 4423, 346, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 2237, 198, 11748, 11192, 273, 11125, 355, 48700, 198, 198, 6738, 256, 9501, 77, ...
2.336438
3,436
import rospy import sys, select, os import roslib import time from tool.test_utils import * roslib.load_manifest('mecanum_robot_gazebo') if __name__ == '__main__' : rospy.init_node('pingpong') mecanum_0 = Make_mecanum_left('mecanum_0') #mecanum_0.torque = [0, -2000000, 0] #mecanum_0.torque = [0, 0, 2000000] #mecanum_0.torque = [0, 0, 0] mecanum_0.del_ball() time.sleep(0.2) #mecanum_0.move(-12.2,1,mecanum_0) while True: mecanum_0.spwan_ball("ball_left") mecanum_0.throw_ball() mecanum_0.move(-12.2,1,mecanum_0) time.sleep(1)
[ 11748, 686, 2777, 88, 198, 11748, 25064, 11, 2922, 11, 28686, 198, 11748, 686, 6649, 571, 198, 11748, 640, 198, 198, 6738, 2891, 13, 9288, 62, 26791, 1330, 1635, 198, 198, 4951, 8019, 13, 2220, 62, 805, 8409, 10786, 76, 721, 272, 38...
1.861862
333
import azapi api = azapi.AZlyrics() def get_lyrics(artist, title, dir='./', save=False): """artist=name of artist, title=name of song, dir=directory to save (if saving), save=save the lyrics in a text file (boolean input)""" attempts = 0 val = None title_lower = title.lower() if ' feat' in title_lower or '(feat' in title_lower: title = title[:title_lower.index('feat.')] elif ' ft' in title_lower or '(ft' in title_lower: title = title[:title_lower.index('ft')] elif ' featuring' in title_lower or '(featuring' in title_lower: title = title[:title_lower.index('featuring')] print(title + ' - ' + artist) data = api.search(title + ' - ' + artist) print(data) # Sometimes a network error will lead to the value being None. If this is the case, try again a few times. while val is None and attempts < 3: try: if data and type(data) is dict and len(data) > 0: print(data) url = data[0]['url'] val = api.getLyrics(url=url, save=save, dir=dir, sleep=1) else: val = api.getLyrics(artist=artist, title=title, save=save, search=False, dir=dir, sleep=1) except Exception as e: print(e) attempts += 1 print(val) return val
[ 11748, 35560, 15042, 198, 198, 15042, 796, 35560, 15042, 13, 22778, 306, 10466, 3419, 198, 198, 4299, 651, 62, 306, 10466, 7, 49016, 11, 3670, 11, 26672, 28, 4458, 14, 3256, 3613, 28, 25101, 2599, 198, 220, 220, 220, 37227, 49016, 28,...
2.358289
561
# Twper - Async Twitter Scraper # Copyright Sacha Jungerman # See LICENSE for details. __version__ = '0.1.1' __author__ = 'Sacha Jungerman' __license__ = 'MIT' from Twper.Twper import Tweet, TwitterAccount, Query, Queries
[ 2, 1815, 525, 532, 1081, 13361, 3009, 1446, 38545, 198, 2, 15069, 20678, 64, 7653, 1362, 805, 198, 2, 4091, 38559, 24290, 329, 3307, 13, 198, 198, 834, 9641, 834, 796, 705, 15, 13, 16, 13, 16, 6, 198, 834, 9800, 834, 796, 705, 5...
2.922078
77
import numpy as np import PIL.Image as image from sklearn.cluster import KMeans from skfuzzy.cluster import cmeans imgData,row,col = loadData('11.jpg') imgData = imgData.T center, u, u0, d, jm, p, fpc = cmeans(imgData, m=2, c=2, error=0.0001, maxiter=1000) for i in u: label = np.argmax(u, axis=0) label = label.reshape([row,col]) pic_new = image.new("L", (row, col)) for i in range(row): for j in range(col): pic_new.putpixel((i,j), int(256/(label[i][j]+1))) pic_new.save("result-bull-5.jpg", "JPEG")
[ 11748, 299, 32152, 355, 45941, 198, 11748, 350, 4146, 13, 5159, 355, 2939, 198, 6738, 1341, 35720, 13, 565, 5819, 1330, 509, 5308, 504, 198, 6738, 1341, 69, 4715, 88, 13, 565, 5819, 1330, 269, 1326, 504, 198, 9600, 6601, 11, 808, 11...
2.330275
218
# # Copyright (c) SAS Institute 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. # """ Contains information gathered during cooking, to be used mostly if the cook failed in order to resume using the same destdir """ import time
[ 2, 198, 2, 15069, 357, 66, 8, 35516, 5136, 3457, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, ...
3.837696
191
import numpy as np import tensorflow as tf from jass.base.const import color_masks from jass.base.player_round import PlayerRound from jass.player.player import Player from tensorflow.keras.models import load_model class DeepLearningPlayer(Player): """ Deep learning implementation of a player to play Jass. """ def select_trump(self, rnd: PlayerRound) -> int: """ Player chooses a trump based on the given round information. Args: rnd: current round Returns: selected trump """ # select the trump with the largest number of cards #if rnd.forehand is None: # forehand = 0 #else: # forehand = 1 #arr = np.array([np.append(rnd.hand, forehand)]) trump_weights = self.trumpModel.predict(np.array([rnd.hand]))[0] trump_selected = int(np.argmax(trump_weights)) if trump_selected == 6 and rnd.forehand is None: #want to push and possible #print(f'Can Push -> Forehand: {rnd.forehand}') return self._assert_if_wrong_trump(int(10), rnd) #Push elif trump_selected == 6: best_without_pushing = int(np.argmax(trump_weights[0:5])) #print(f'Cannot Push anymore -> Best without Push: {best_without_pushing}, Possible Trumps: {trump_weights[0:5]}') return self._assert_if_wrong_trump(best_without_pushing, rnd) #print(f'Select Trump: {trump_selected}') return self._assert_if_wrong_trump(trump_selected, rnd) def play_card(self, rnd: PlayerRound) -> int: """ Player returns a card to play based on the given round information. Args: rnd: current round Returns: card to play, int encoded """ # get the valid cards to play valid_cards = rnd.get_valid_cards() # select a random card player = self._one_hot(rnd.player, 4) trump = self._one_hot(rnd.trump, 6) current_trick = self._get_current_trick(rnd.tricks) arr = np.array([np.append(valid_cards, current_trick)]) arr = np.array([np.append(arr, player)]) arr = np.array([np.append(arr, trump)]) card_to_play = int(np.argmax(self.playCardModel.predict(arr))) if valid_cards[card_to_play] == 1: #valid card return card_to_play else: return int(np.nonzero(valid_cards == 1)[0][0]) def _one_hot(self, number, size): """ One hot encoding for a single value. Output is float array of size size Args: number: number to one hot encode size: length of the returned array Returns: array filled with 0.0 where index != number and 1.0 where index == number """ result = np.zeros(size, dtype=np.int) result[number] = 1 return result
[ 11748, 299, 32152, 355, 45941, 198, 11748, 11192, 273, 11125, 355, 48700, 198, 198, 6738, 474, 562, 13, 8692, 13, 9979, 1330, 3124, 62, 5356, 591, 198, 6738, 474, 562, 13, 8692, 13, 7829, 62, 744, 1330, 7853, 22685, 198, 6738, 474, ...
2.297704
1,263
# 27、移除元素 # 一、双指针法,设置快慢指针,当快指针指向元素等于删除元素时,快指针快走一步, # 慢指针不走;否则,快慢指针同时走一步,并把快指针的元素值赋给慢指针,这样 # 慢指针走过的元素就是删除掉指定元素的数组,时间复杂度O(n),空间复杂度O(1) nums = [0, 1, 2, 2, 3, 0, 4, 2] val = 2 print(removeElement0(nums, val))
[ 2, 2681, 23513, 163, 100, 119, 165, 247, 97, 17739, 225, 163, 112, 254, 198, 2, 220, 31660, 23513, 20998, 234, 162, 234, 229, 165, 240, 230, 37345, 243, 171, 120, 234, 164, 106, 122, 163, 121, 106, 33232, 104, 162, 227, 95, 162, ...
0.642424
330
import pytest import os import slug from slug import ProcessGroup, Process, Pipe from conftest import runpy, not_in_path @pytest.mark.skipif(not hasattr(ProcessGroup, 'pgid'), reason="No Process Group IDs") @pytest.mark.skipif(ProcessGroup is slug.base.ProcessGroup, reason="Base Process Group is broken this way") @pytest.mark.skipif(not_in_path('ls', 'wc'), reason="Requires the ls and wc binaries") def test_lswc_gh10(): """ Tests ls|wc """ # From https://github.com/xonsh/slug/issues/10 with ProcessGroup() as pg: pipe = Pipe() pg.add(Process(['ls'], stdout=pipe.side_in)) pg.add(Process(['wc'], stdin=pipe.side_out)) pg.start() pipe.side_in.close() pipe.side_out.close() pg.join()
[ 11748, 12972, 9288, 198, 11748, 28686, 198, 11748, 31065, 198, 6738, 31065, 1330, 10854, 13247, 11, 10854, 11, 36039, 198, 6738, 369, 701, 395, 1330, 1057, 9078, 11, 407, 62, 259, 62, 6978, 628, 628, 198, 198, 31, 9078, 9288, 13, 4102...
2.275766
359
import torch import enchanter.addons.criterions as C import enchanter
[ 11748, 28034, 198, 11748, 551, 3147, 353, 13, 39996, 13, 22213, 263, 507, 355, 327, 198, 11748, 551, 3147, 353, 628, 628, 628 ]
3.26087
23
r""" This script creates a plot of the mass-loading factor eta and the star formation e-folding timescale as functions of Galactocentric radius in the forms adopted by Johnson et al. (2021). """ from .. import env from ...simulations.models.insideout import insideout from .utils import named_colors import matplotlib.pyplot as plt import math as m import vice def main(stem): r""" Plot a 1x2 panel figure, showing the mass-loading factor :math:`\eta` and the e-folding timescales of the star formation history as functions of galactocentric radius in kpc as adopted by Johnson et al. (2021). Parameters ---------- stem : ``str`` The relative or absolute path to the output image, with no extension. This function will save the figure in both PDF and PNG formats. """ ax1, ax2 = setup_axes() plot_eta(ax1) plot_tau_sfh(ax2) plt.tight_layout() plt.subplots_adjust(hspace = 0) plt.savefig("%s.png" % (stem)) plt.savefig("%s.pdf" % (stem)) plt.close() def plot_eta(ax): r""" Plot the mass-loading factor :math:`\eta` as a function of Galactocentric radius in kpc as adopted by Johnson et al. (2021). Parameters ---------- ax : ``axes`` The matplotlib subplot to plot on. """ rgal = [0.01 * _ for _ in range(1551)] eta = [vice.milkyway.default_mass_loading(_) for _ in rgal] ax.plot(rgal, eta, c = named_colors()["black"]) ax.plot(2 * [8.], ax.get_ylim(), c = named_colors()["crimson"], linestyle = ':') ax.plot(ax.get_xlim(), 2 * [vice.milkyway.default_mass_loading(8.)], c = named_colors()["crimson"], linestyle = ':') def plot_tau_sfh(ax): r""" Plot the e-folding timescales of the star formation history as a function of Galactocentric radius as adopted by Johnson et al. (2021). Parameters ---------- ax : ``axes`` The matplotlib subplot to plot on. """ rgal = [0.01 * _ for _ in range(1551)] tau = [insideout.timescale(_) for _ in rgal] ax.plot(rgal, tau, c = named_colors()["black"]) ax.plot(2 * [8.], ax.get_ylim(), c = named_colors()["crimson"], linestyle = ':') ax.plot(ax.get_xlim(), 2 * [insideout.timescale(8.)], c = named_colors()["crimson"], linestyle = ':') def setup_axes(): r""" Setup the 1x2 axes to plot the :math:`\eta-R_\text{gal}` and the :math:`\tau_\text{sfh}-R_\text{gal}` relation on. Return them as a ``list``. """ fig = plt.figure(figsize = (7, 14), facecolor = "white") ax1 = fig.add_subplot(211) ax2 = fig.add_subplot(212) ax1.set_ylabel(r"$\eta \equiv \dot{M}_\text{out} / \dot{M}_\star$") ax2.set_ylabel(r"$\tau_\text{sfh}$ [Gyr]") ax2.set_xlabel(r"$R_\text{gal}$ [kpc]") plt.setp(ax1.get_xticklabels(), visible = False) for i in [ax1, ax2]: i.set_xlim([-1, 17]) i.set_xticks([0, 5, 10, 15]) ax1.set_ylim([-1, 11]) ax2.set_ylim([0, 50]) return [ax1, ax2]
[ 81, 37811, 198, 1212, 4226, 8075, 257, 7110, 286, 262, 2347, 12, 25138, 5766, 2123, 64, 290, 262, 3491, 198, 1161, 304, 12, 11379, 278, 1661, 38765, 355, 5499, 286, 5027, 529, 420, 22317, 16874, 287, 262, 198, 23914, 8197, 416, 5030, ...
2.468388
1,123
#!/usr/bin/env python3 """ BranchExplorer is the high-level tool that tries to explore specific parts of code rather than maximizing coverage like regular automatic testing. """ import argparse import logging import os import sys import time import datetime import branchexp.imports import branchexp.config from branchexp.explo.simple_explorer import Explorer, explore_apk from branchexp.utils.utils import quit log = logging.getLogger("branchexp") try: import coloredlogs coloredlogs.install( show_hostname=False, show_name=True, logger=log, level='DEBUG' ) except ImportError: log.error("Can't import coloredlogs, logs may not appear correctly.") DESCRIPTION = "Manager for APK instrumentation and branch-forcing." if __name__ == "__main__": main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 37811, 20551, 18438, 11934, 318, 262, 1029, 12, 5715, 2891, 326, 8404, 284, 7301, 2176, 3354, 198, 1659, 2438, 2138, 621, 48350, 5197, 588, 3218, 11353, 4856, 13, 37227, 198, 198, ...
3.140625
256
import tempfile from frekenbok.settings import * from frekenbok.settings.dev import * DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': tempfile.mkstemp(suffix='.sqlite3', prefix='frekenbok_')[1], } }
[ 11748, 20218, 7753, 198, 198, 6738, 2030, 3464, 65, 482, 13, 33692, 1330, 1635, 198, 6738, 2030, 3464, 65, 482, 13, 33692, 13, 7959, 1330, 1635, 198, 198, 35, 1404, 6242, 1921, 1546, 796, 1391, 198, 220, 220, 220, 705, 12286, 10354, ...
2.230088
113
import torch import torch.nn.functional as F from torch import nn class Interpolate(nn.Module): """nn.Module wrapper for F.interpolate""" def conv3x3(in_planes, out_planes, stride=1): """3x3 convolution with padding""" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False) def conv1x1(in_planes, out_planes, stride=1): """1x1 convolution""" return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False) def resize_conv3x3(in_planes, out_planes, scale=1): """upsample + 3x3 convolution with padding to avoid checkerboard artifact""" if scale == 1: return conv3x3(in_planes, out_planes) else: return nn.Sequential(Interpolate(scale_factor=scale), conv3x3(in_planes, out_planes)) def resize_conv1x1(in_planes, out_planes, scale=1): """upsample + 1x1 convolution with padding to avoid checkerboard artifact""" if scale == 1: return conv1x1(in_planes, out_planes) else: return nn.Sequential(Interpolate(scale_factor=scale), conv1x1(in_planes, out_planes)) class EncoderBlock(nn.Module): """ ResNet block, copied from https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py#L35 """ expansion = 1 class EncoderBottleneck(nn.Module): """ ResNet bottleneck, copied from https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py#L75 """ expansion = 4 class DecoderBlock(nn.Module): """ ResNet block, but convs replaced with resize convs, and channel increase is in second conv, not first """ expansion = 1 class DecoderBottleneck(nn.Module): """ ResNet bottleneck, but convs replaced with resize convs """ expansion = 4 class ResNetDecoder(nn.Module): """ Resnet in reverse order """
[ 11748, 28034, 198, 11748, 28034, 13, 20471, 13, 45124, 355, 376, 198, 6738, 28034, 1330, 299, 77, 628, 198, 4871, 4225, 16104, 378, 7, 20471, 13, 26796, 2599, 198, 220, 220, 220, 37227, 20471, 13, 26796, 29908, 329, 376, 13, 3849, 161...
2.644886
704
# ########################################################################### # # CLOUDERA APPLIED MACHINE LEARNING PROTOTYPE (AMP) # (C) Cloudera, Inc. 2020 # All rights reserved. # # Applicable Open Source License: Apache 2.0 # # NOTE: Cloudera open source products are modular software products # made up of hundreds of individual components, each of which was # individually copyrighted. Each Cloudera open source product is a # collective work under U.S. Copyright Law. Your license to use the # collective work is as provided in your written agreement with # Cloudera. Used apart from the collective work, this file is # licensed for your use pursuant to the open source license # identified above. # # This code is provided to you pursuant a written agreement with # (i) Cloudera, Inc. or (ii) a third-party authorized to distribute # this code. If you do not have a written agreement with Cloudera nor # with an authorized and properly licensed third party, you do not # have any rights to access nor to use this code. # # Absent a written agreement with Cloudera, Inc. (“Cloudera”) to the # contrary, A) CLOUDERA PROVIDES THIS CODE TO YOU WITHOUT WARRANTIES OF ANY # KIND; (B) CLOUDERA DISCLAIMS ANY AND ALL EXPRESS AND IMPLIED # WARRANTIES WITH RESPECT TO THIS CODE, INCLUDING BUT NOT LIMITED TO # IMPLIED WARRANTIES OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY AND # FITNESS FOR A PARTICULAR PURPOSE; (C) CLOUDERA IS NOT LIABLE TO YOU, # AND WILL NOT DEFEND, INDEMNIFY, NOR HOLD YOU HARMLESS FOR ANY CLAIMS # ARISING FROM OR RELATED TO THE CODE; AND (D)WITH RESPECT TO YOUR EXERCISE # OF ANY RIGHTS GRANTED TO YOU FOR THE CODE, CLOUDERA IS NOT LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, PUNITIVE OR # CONSEQUENTIAL DAMAGES INCLUDING, BUT NOT LIMITED TO, DAMAGES # RELATED TO LOST REVENUE, LOST PROFITS, LOSS OF INCOME, LOSS OF # BUSINESS ADVANTAGE OR UNAVAILABILITY, OR LOSS OR CORRUPTION OF # DATA. # # ########################################################################### import os import json import urllib.request import zipfile from pandas.tseries.holiday import USFederalHolidayCalendar as calendar import pandas as pd import pickle def get_trends_by_name(df, location_name): """Returns a dict of trends for given location name Args: df (pd.DataFrame): [dataframe created by processor.py] location_name (str): [description] Returns: [dict]: dict of matched values """ if (location_name): df = (df[df.location == location_name]) df = df.to_dict(orient="records") return (df) # df = pd.read_json("data/metadata/trends.json") # print(get_trends_by_name(df, "US-California-Santa oi Clara (HQ)"))
[ 2, 1303, 29113, 29113, 7804, 2235, 198, 2, 198, 2, 220, 7852, 2606, 14418, 32, 3486, 49094, 337, 16219, 8881, 12509, 1503, 15871, 48006, 2394, 56, 11401, 357, 23518, 8, 198, 2, 220, 357, 34, 8, 1012, 280, 1082, 64, 11, 3457, 13, 1...
3.133409
877
import importlib import logging from typing import Iterable, Any # noqa: F401 from pyhocon import ConfigTree # noqa: F401 from databuilder.extractor.base_extractor import Extractor LOGGER = logging.getLogger(__name__) class DBAPIExtractor(Extractor): """ Generic DB API extractor. """ CONNECTION_CONFIG_KEY = 'connection' SQL_CONFIG_KEY = 'sql' def init(self, conf): # type: (ConfigTree) -> None """ Receives a {Connection} object and {sql} to execute. An optional model class can be passed, in which, sql result row would be converted to a class instance and returned to calling function :param conf: :return: """ self.conf = conf self.connection = conf.get(DBAPIExtractor.CONNECTION_CONFIG_KEY) # type: Any self.cursor = self.connection.cursor() self.sql = conf.get(DBAPIExtractor.SQL_CONFIG_KEY) model_class = conf.get('model_class', None) if model_class: module_name, class_name = model_class.rsplit(".", 1) mod = importlib.import_module(module_name) self.model_class = getattr(mod, class_name) self._iter = iter(self._execute_query()) def _execute_query(self): # type: () -> Iterable[Any] """ Use cursor to execute the {sql} :return: """ self.cursor.execute(self.sql) return self.cursor.fetchall() def extract(self): # type: () -> Any """ Fetch one sql result row, convert to {model_class} if specified before returning. :return: """ try: result = next(self._iter) except StopIteration: return None if hasattr(self, 'model_class'): obj = self.model_class(*result[:len(result)]) return obj else: return result def close(self): # type: () -> None """ close cursor and connection handlers :return: """ try: self.cursor.close() self.connection.close() except Exception: LOGGER.exception("Exception encountered while closing up connection handler!")
[ 11748, 1330, 8019, 198, 11748, 18931, 198, 6738, 19720, 1330, 40806, 540, 11, 4377, 220, 1303, 645, 20402, 25, 376, 21844, 198, 198, 6738, 12972, 71, 36221, 1330, 17056, 27660, 220, 1303, 645, 20402, 25, 376, 21844, 198, 198, 6738, 4818...
2.250499
1,002
# Utils for small Ising models from itertools import product import numpy as np from jax import jit from jax import random from jax.config import config from jax.scipy.special import logsumexp from tqdm import tqdm config.update("jax_disable_jit", False) """ Note: in our experiments we consider two classes of Ising models: - models with observations in {0, 1} and energy E1(x) = -0.5 * x.T * W * x - x.T * b, as this is traditionally the case - models with observations in {-1, 1} and energy E2(x) = - x.T * W * x - x.T * b as defined in some work we are comparing our methods with. """ ##################################### ###### Log partition function ####### ##################################### @jit @jit ##################################### ############# Useful ############### ##################################### ##################################### ########## KL divergences ########### #####################################
[ 2, 7273, 4487, 329, 1402, 1148, 278, 4981, 198, 198, 6738, 340, 861, 10141, 1330, 1720, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 474, 897, 1330, 474, 270, 198, 6738, 474, 897, 1330, 4738, 198, 6738, 474, 897, 13, 11250, 1330, ...
3.710425
259
NAME_CHARS = set('ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz0123456789') NAME_FIRST_CHARS = set('ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz')
[ 20608, 62, 3398, 27415, 796, 900, 10786, 24694, 32988, 17511, 23852, 42, 31288, 45, 3185, 48, 49, 2257, 52, 30133, 34278, 57, 6, 1343, 198, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 705, 39305, ...
1.638462
130
import setuptools import re long_description = "" # with open("README.md", "r") as fh: # long_description = fh.read() version = re.search( r"^__version__\s*?=\s*?'(.*)'", open('safe_env/version.py').read(), re.M ).group(1) requires_base = load_requirements_from_file("requirements-base.txt") requires_local = load_requirements_from_file("requirements-local.txt") requires_build = load_requirements_from_file("requirements-build.txt") setuptools.setup( name="safe-env", version=version, author="Antons Mislevics", author_email="antonsm@outlook.com", description="Safe Environment Manager", long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/antonsmislevics/safe-env", packages=setuptools.find_packages(), entry_points = { 'console_scripts': [ 'se=safe_env.cli:app' ] }, classifiers=[ "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ], python_requires='>=3.6', install_requires = requires_base, extras_require={ 'all': requires_local + requires_build, 'local': requires_local } )
[ 11748, 900, 37623, 10141, 198, 11748, 302, 198, 198, 6511, 62, 11213, 796, 13538, 198, 2, 351, 1280, 7203, 15675, 11682, 13, 9132, 1600, 366, 81, 4943, 355, 277, 71, 25, 198, 2, 220, 220, 220, 220, 890, 62, 11213, 796, 277, 71, 13...
2.520958
501
from unittest.case import TestCase from tweepy.error import TweepError from responsebot.common.exceptions import MissingConfigError, APIQuotaError, AuthenticationError try: from mock import patch, MagicMock except ImportError: from unittest.mock import patch, MagicMock from responsebot.responsebot import ResponseBot
[ 6738, 555, 715, 395, 13, 7442, 1330, 6208, 20448, 198, 198, 6738, 4184, 538, 88, 13, 18224, 1330, 24205, 538, 12331, 198, 198, 6738, 2882, 13645, 13, 11321, 13, 1069, 11755, 1330, 25639, 16934, 12331, 11, 7824, 4507, 4265, 12331, 11, ...
3.55914
93
""" profiles.py Copyright 2007 Andres Riancho This file is part of w3af, http://w3af.org/ . w3af 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 version 2 of the License. w3af 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 w3af; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA """ import gtk import cgi from w3af.core.ui.gui import helpers, entries from w3af.core.controllers.exceptions import BaseFrameworkException from w3af.core.data.profile.profile import profile as profile class ProfileList(gtk.TreeView): """A list showing all the profiles. :param w3af: The main core class. :param initial: The profile to start :author: Facundo Batista <facundobatista =at= taniquetil.com.ar> """ def load_profiles(self, selected=None, retry=True): """Load the profiles. :param selected: which profile is already selected. """ # create the ListStore, with the info listed below liststore = gtk.ListStore(str, str, str, int, str) # we will keep the profile instances here self.profile_instances = {None: None} # build the list with the profiles name, description, profile_instance instance_list, invalid_profiles = self.w3af.profiles.get_profile_list() tmpprofiles = [] for profile_obj in instance_list: nom = profile_obj.get_name() desc = profile_obj.get_desc() tmpprofiles.append((nom, desc, profile_obj)) # Also add to that list the "selected" profile, that was specified by # the user with the "-p" parameter when executing w3af if self._parameter_profile: try: profile_obj = profile(self._parameter_profile) except BaseFrameworkException: raise ValueError(_("The profile %r does not exists!") % self._parameter_profile) else: nom = profile_obj.get_name() desc = profile_obj.get_desc() # I don't want to add duplicates, so I perform this test: add_to_list = True for nom_tmp, desc_tmp, profile_tmp in tmpprofiles: if nom_tmp == nom and desc_tmp == desc: add_to_list = False break if add_to_list: tmpprofiles.append((nom, desc, profile_obj)) # Create the liststore using a specially sorted list, what I basically # want is the empty profile at the beginning of the list, and the rest # sorted in alpha order tmpprofiles = sorted(tmpprofiles) tmpprofiles_special_order = [] for nom, desc, profile_obj in tmpprofiles: if nom == 'empty_profile': tmpprofiles_special_order.insert(0, (nom, desc, profile_obj)) else: tmpprofiles_special_order.append((nom, desc, profile_obj)) # And now create the liststore and the internal dict for nom, desc, profile_obj in tmpprofiles_special_order: prfid = str(id(profile_obj)) self.profile_instances[prfid] = profile_obj liststore.append([nom, desc, prfid, 0, nom]) # set this liststore self.liststore = liststore self.set_model(liststore) # select the indicated one self.selectedProfile = None if selected is None: self.set_cursor(0) self._use_profile() else: for i, (nom, desc, prfid, changed, perm) in enumerate(liststore): the_prof = self.profile_instances[prfid] if selected == the_prof.get_profile_file() or \ selected == the_prof.get_name(): self.set_cursor(i) self._use_profile() break else: # In some cases, this function is called in a thread while # the profile file is being stored to disk. Because of that # it might happen that the profile "is there" but didn't get # loaded properly in the first call to load_profiles. if retry: self.load_profiles(selected, retry=False) else: self.set_cursor(0) # Now that we've finished loading everything, show the invalid profiles # in a nice pop-up window if invalid_profiles: message = 'The following profiles are invalid and failed to load:\n' for i in invalid_profiles: message += '\n\t- ' + i message += '\n\nPlease click OK to continue without these profiles.' dlg = gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_WARNING, gtk.BUTTONS_OK, message) dlg.run() dlg.destroy() def _controlDifferences(self): """Returns if something is different against initial state.""" # Always check activation status nowActive = sorted(self.w3af.mainwin.pcbody.get_activated_plugins()) if nowActive != self.origActPlugins: return True # Check plugins config for ptype in self.w3af.plugins.get_plugin_types(): for pname in self.w3af.plugins.get_plugin_list(ptype): opts = self.w3af.plugins.get_plugin_options(ptype, pname) if not opts: continue # let's see if we have it (if we don't, it means # we never got into that plugin, therefore it's ok if (ptype, pname) not in self.pluginsConfigs: continue # compare it savedconfig = self.pluginsConfigs[(ptype, pname)] for (k, origv) in savedconfig.items(): newv = str(opts[k]) if newv != origv: return True return False def profile_changed(self, plugin=None, changed=None): """Get executed when a plugin is changed. :param plugin: The plugin which changed. :param changed: Force a change. When executed, this check if the saved config is equal or not to the original one, and enables color and buttons. """ if changed is None: changed = self._controlDifferences() # update boldness and info path = self.get_cursor()[0] if not path: return row = self.liststore[path] row[3] = changed if changed: row[0] = "<b>%s</b>" % row[4] else: row[0] = row[4] # update the mainwin buttons newstatus = self._get_actionsSensitivity(path) self.w3af.mainwin.activate_profile_actions([True] + newstatus) def plugin_config(self, plugin): """Gets executed when a plugin config panel is created. :param plugin: The plugin which will be configured. When executed, takes a snapshot of the original plugin configuration. """ # only stores the original one if (plugin.ptype, plugin.pname) in self.pluginsConfigs: return # we adapt this information to a only-options dict, as that's # the information that we can get later from the core opts = plugin.get_options() realopts = {} for opt in opts: realopts[opt.get_name()] = opt.get_default_value_str() self.pluginsConfigs[(plugin.ptype, plugin.pname)] = realopts def _changeAtempt(self, widget, event): """Let the user change profile if the actual is saved.""" path = self.get_cursor()[0] if not path: return row = self.liststore[path] if row[3]: # The profile is changed if event.button != 1: return True # Clicked with left button msg = _("Do you want to discard the changes in the Profile?") dlg = gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_WARNING, gtk.BUTTONS_YES_NO, msg) stayhere = dlg.run() != gtk.RESPONSE_YES dlg.destroy() if not stayhere: # even if it's modified, we're leaving it: when we come back, # the previous configuration will be loaded... so here we just # unbold it and set it as not modified row[0] = row[4] row[3] = False self.w3af.mainwin.sb( _("The previous profile configuration was discarded")) return stayhere return False def _popupMenu(self, tv, event): """Shows a menu when you right click on a plugin. :param tv: the treeview. :param event: The GTK event """ if event.button != 3: return # don't allow right button in other widget if actual is not saved path = self.get_cursor()[0] if not path: return row = self.liststore[path] posic = self.get_path_at_pos(int(event.x), int(event.y)) if posic is None: return clickpath = posic[0] if row[3] and clickpath != path: return True # creates the whole menu only once if self._rightButtonMenu is None: gm = gtk.Menu() self._rightButtonMenu = gm # the items e = gtk.MenuItem(_("Save configuration to profile")) e.connect('activate', self.save_profile) gm.append(e) e = gtk.MenuItem(_("Save configuration to a new profile")) e.connect('activate', self.save_as_profile) gm.append(e) e = gtk.MenuItem(_("Revert to saved profile state")) e.connect('activate', self.revert_profile) gm.append(e) e = gtk.MenuItem(_("Delete this profile")) e.connect('activate', self.delete_profile) gm.append(e) gm.show_all() else: gm = self._rightButtonMenu (path, column) = tv.get_cursor() # Is it over a plugin name ? if path is not None and len(path) == 1: # Enable/disable the options in function of state newstatus = self._get_actionsSensitivity(path) children = gm.get_children() for child, stt in zip(children, newstatus): child.set_sensitive(stt) gm.popup(None, None, None, event.button, event.time) def _get_actionsSensitivity(self, path): """Returns which actions must be activated or not :param path: where the cursor is located :return: four booleans indicating the state for each option """ vals = [] row = self.liststore[path] # save: enabled if it's modified vals.append(row[3]) # save as: always enabled vals.append(True) # revert: enabled if it's modified vals.append(row[3]) # delete: enabled vals.append(True) return vals def _get_profile(self): """Gets the current profile instance. :return: The profile instance for the actual cursor position. """ path, focus = self.get_cursor() if path is None: return None prfid = self.liststore[path][2] profile_obj = self.profile_instances[prfid] return profile_obj def _get_profile_name(self): """Gets the actual profile name. :return: The profile name for the actual cursor position. """ profile_obj = self._get_profile() if profile_obj is None: return None return profile_obj.get_name() def _use_profile(self, widget=None): """Uses the selected profile.""" profile_obj = self._get_profile() profile_name = self._get_profile_name() if profile_name == self.selectedProfile: return # Changed the profile in the UI self.selectedProfile = profile_name try: self.w3af.profiles.use_profile(profile_obj.get_profile_file()) except BaseFrameworkException, w3: dlg = gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_WARNING, gtk.BUTTONS_OK, str(w3)) dlg.run() dlg.destroy() return # Reload the UI profdesc = None if profile_obj is None else profile_obj.get_desc() self.w3af.mainwin.pcbody.reload(profdesc) # get the activated plugins self.origActPlugins = self.w3af.mainwin.pcbody.get_activated_plugins() # update the mainwin buttons path = self.get_cursor()[0] newstatus = self._get_actionsSensitivity(path) self.w3af.mainwin.activate_profile_actions(newstatus) def new_profile(self, widget=None): """Creates a new profile.""" # ask for new profile info dlg = entries.EntryDialog( _("New profile"), gtk.STOCK_NEW, [_("Name:"), _("Description:")]) dlg.run() dlgResponse = dlg.inputtexts dlg.destroy() if dlgResponse is None: return # use the empty profile try: self.w3af.profiles.use_profile(None) except BaseFrameworkException, w3: dlg = gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_WARNING, gtk.BUTTONS_OK, str(w3)) dlg.run() dlg.destroy() return self.w3af.mainwin.pcbody.reload(None) # save it filename, description = dlgResponse filename = cgi.escape(filename) try: profile_obj = helpers.coreWrap( self.w3af.profiles.save_current_to_new_profile, filename, description) except BaseFrameworkException: #FIXME: This message should be more descriptive self.w3af.mainwin.sb(_("Problem hit!")) return self.w3af.mainwin.sb(_("New profile created")) self.load_profiles(selected=profile_obj.get_name()) # get the activated plugins self.origActPlugins = self.w3af.mainwin.pcbody.get_activated_plugins() # update the mainwin buttons path = self.get_cursor()[0] newstatus = self._get_actionsSensitivity(path) self.w3af.mainwin.activate_profile_actions(newstatus) def save_profile(self, widget=None): """Saves the selected profile.""" profile_obj = self._get_profile() if profile_obj is None: # AttributeError: 'NoneType' object has no attribute 'get_name' # https://github.com/andresriancho/w3af/issues/11941 return if not self.w3af.mainwin.save_state_to_core(relaxedTarget=True): return self.w3af.profiles.save_current_to_profile(profile_obj.get_name(), prof_desc=profile_obj.get_desc(), prof_path=profile_obj.get_profile_file()) self.w3af.mainwin.sb(_('Profile saved')) path = self.get_cursor()[0] row = self.liststore[path] row[0] = row[4] row[3] = False def save_as_profile(self, widget=None): """Copies the selected profile.""" if not self.w3af.mainwin.save_state_to_core(relaxedTarget=True): return dlg = entries.EntryDialog(_("Save as..."), gtk.STOCK_SAVE_AS, [_("Name:"), _("Description:")]) dlg.run() dlgResponse = dlg.inputtexts dlg.destroy() if dlgResponse is not None: filename, description = dlgResponse filename = cgi.escape(filename) try: profile_obj = helpers.coreWrap(self.w3af.profiles.save_current_to_new_profile, filename, description) except BaseFrameworkException: self.w3af.mainwin.sb( _("There was a problem saving the profile!")) return self.w3af.mainwin.sb(_("New profile created")) self.load_profiles(selected=profile_obj.get_name()) def revert_profile(self, widget=None): """Reverts the selected profile to its saved state.""" msg = _("Do you really want to discard the changes in the the profile" " and load the previous saved configuration?") dlg = gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_WARNING, gtk.BUTTONS_YES_NO, msg) opt = dlg.run() dlg.destroy() if opt == gtk.RESPONSE_YES: self.selectedProfile = -1 path = self.get_cursor()[0] if not path: # https://github.com/andresriancho/w3af/issues/1886 return row = self.liststore[path] row[0] = row[4] row[3] = False self._use_profile() self.w3af.mainwin.sb(_("The profile configuration was reverted to" " its last saved state")) def delete_profile(self, widget=None): """Deletes the selected profile.""" profile_obj = self._get_profile() msg = _("Do you really want to DELETE the profile '%s'?") dlg = gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_WARNING, gtk.BUTTONS_YES_NO, msg % profile_obj.get_name()) opt = dlg.run() dlg.destroy() if opt == gtk.RESPONSE_YES: # Special case to handle the parameter profile if profile_obj.get_profile_file() == self._parameter_profile: self._parameter_profile = None self.w3af.profiles.remove_profile(profile_obj.get_profile_file()) self.w3af.mainwin.sb(_("The profile was deleted")) self.load_profiles()
[ 37811, 198, 5577, 2915, 13, 9078, 198, 198, 15269, 4343, 843, 411, 371, 666, 6679, 198, 198, 1212, 2393, 318, 636, 286, 266, 18, 1878, 11, 2638, 1378, 86, 18, 1878, 13, 2398, 14, 764, 198, 198, 86, 18, 1878, 318, 1479, 3788, 26, ...
2.099103
8,920
from django.db import models # Create your models here.
[ 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 198, 2, 13610, 534, 4981, 994, 13, 628 ]
3.625
16
#!/usr/bin/python3 # -*- coding: utf-8 -*- from PyQt5.QtCore import QObject, pyqtSlot, QUrl from PyQt5.QtWebKitWidgets import QWebView view = QWebView() frame = view.page().mainFrame() # todo check is it changing
[ 2, 48443, 14629, 14, 8800, 14, 29412, 18, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 6738, 9485, 48, 83, 20, 13, 48, 83, 14055, 1330, 1195, 10267, 11, 12972, 39568, 38963, 11, 1195, 28165, 198, 6738, ...
2.449438
89
#! /usr/bin/jython # -*- coding: utf-8 -*- # # csv_read.py # # Jul/20/2015 # import sys import string # sys.path.append ('/var/www/data_base/common/python_common') sys.path.append ('/var/www/data_base/common/jython_common') from jython_text_manipulate import csv_read_proc from text_manipulate import dict_display_proc # -------------------------------------------------------------------- print ("*** 開始 ***") file_in = sys.argv[1] # dict_aa = csv_read_proc (file_in) print dict_aa.keys () # dict_display_proc (dict_aa) print ("*** 終了 ***") # --------------------------------------------------------------------
[ 2, 0, 1220, 14629, 14, 8800, 14, 73, 7535, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 2, 197, 40664, 62, 961, 13, 9078, 198, 2, 198, 2, 197, 197, 197, 197, 197, 197, 16980, 14, 1238, 14, 4626...
2.83945
218
from subprocess import Popen, PIPE from typing import Optional, List from requests import Response from Core.ConfigHandler import ConfigHandler from VersionControlProvider.Github.ConfigGithub import ConfigGithub from VersionControlProvider.Github.Github import Github
[ 6738, 850, 14681, 1330, 8099, 268, 11, 350, 4061, 36, 198, 6738, 19720, 1330, 32233, 11, 7343, 198, 198, 6738, 7007, 1330, 18261, 198, 198, 6738, 7231, 13, 16934, 25060, 1330, 17056, 25060, 198, 6738, 10628, 15988, 29495, 13, 38, 10060,...
4.301587
63
import numpy as np from integration import *
[ 11748, 299, 32152, 355, 45941, 198, 6738, 11812, 1330, 1635, 628 ]
4.181818
11
# -*- coding: utf-8 -*- from distutils.core import setup import py2exe, sys sys.argv.append('py2exe') #C:\Python34\python.exe setup.py setup( windows=[ { "script": "huiini.py", "icon_resources": [(1, "myicon.ico")] } ], options={ "py2exe":{ "unbuffered": True, "optimize": 2, "includes":["PySide.QtCore","PySide.QtGui", "urllib3", "requests", "queue"] } }, )
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 1233, 26791, 13, 7295, 1330, 9058, 198, 11748, 12972, 17, 13499, 11, 25064, 198, 198, 17597, 13, 853, 85, 13, 33295, 10786, 9078, 17, 13499, 11537, 198, 2, 34, 7...
1.669753
324
import datetime as dt import itertools as it from pathlib import Path import re import simplejson import altair.vegalite.v3 as A from bs4 import BeautifulSoup import requests import pandas as pd import numpy as np pth = Path("~/repos/covid/data").expanduser() url_ga_county = url_ga = "https://dph.georgia.gov/covid-19-daily-status-report" # Utils def nonull_tdd(s): """ Gets timedelta in days for non-null elements. The rest are nan. """ nonull_tdd.s = s nn_bm = s == s # print(s[nn_bm]) # print(s[nn_bm].astype("timedelta64[D]")) tdd = s[nn_bm] / np.timedelta64(1, "D") res = pd.Series([np.nan] * len(s), index=s.index) res.loc[nn_bm] = tdd # print(res) return res ############# # GA county # ############# ###################### # Georgia aggregates # ###################### def get_ga_agg(): """ Table on page expected to have columns 'Lab' 'Number of Positive Tests' 'Total Tests' """ tables = pd.read_html(url_ga) [table] = [t for t in tables if "Lab" in t] gen_date = get_generated_date(url_ga) table = table.assign(date_gen=gen_date).assign( date_gen=lambda x: pd.to_datetime(x.date_gen) ) return table ################### # Load State data # ################### def load_states(date="03-16"): """ DataFrameate doesn't mean anyting. Just for caching """ r = requests.get("http://covidtracking.com/api/states/daily") return pd.DataFrame(simplejson.loads(r.content)) ########### # Process # ########### # Mortality def filter_mortality(dfs, days_previous=4, min_death_days=4): """ Get list of states with at least `min_death_days` rows of mortality data. Add column `pos_delayed` of positive cases `days_previous` days ago. """ mortal_states = ( dfs.query("death > 0") .state.value_counts(normalize=0) .pipe(lambda x: x[x > min_death_days]) .index.tolist() ) dfd = ( dfs.query(f"state in {mortal_states}") .query("death > 3") .sort_values(["state", "date"], ascending=True) .assign(tot=lambda x: x["positive"] + x["negative"]) .assign( pos_delayed=lambda df: df.groupby(["state"]).positive.transform( mkshft(days_previous) ), tot_delayed=lambda df: df.groupby(["state"]).tot.transform( mkshft(days_previous) ), ) .assign(perc_delayed=lambda df: df.pos_delayed / df.tot_delayed) .assign( prev_perc_delayed=lambda x: x.groupby( ["state"], sort=False ).perc_delayed.transform(shift_perc_del) ) ) return dfd # Plot lgs = A.Scale(type="log", zero=False) def write_model(mbase, dfsim, form, plot): """ Save formula, plots, vegalite spec, predicted data to `mbase` model dir. """ dfsim.to_parquet(mbase / "preds.pq") with open(mbase / "form.txt", "w") as fp: fp.write(f"Formula: {form}") with A.data_transformers.enable("default"): A.Chart.save(plot, str(mbase / "preds.png")) A.Chart.save(plot, str(mbase / "preds.json")) A.Chart.pipe = pipe def clf_states_mapping(df, n_groups=3, topn=4): """ Order states by highest deaths into `n_groups` """ df = df[["date", "state", "death"]] df_latest = df.pipe(lambda x: x[x.date == x.date.max()]).sort_values( "death", ascending=False ) top4 = df_latest.state[:topn].tolist() df_rest = df_latest.query("state not in @top4") top4 q, _q = pd.qcut(df_rest.death, n_groups - 1, retbins=True, labels=False) q += 1 mapping = dict(zip(df_rest.state, q)) mapping.update(dict(zip(top4, it.repeat(0)))) return mapping # return df.state.map(mapping)
[ 11748, 4818, 8079, 355, 288, 83, 198, 11748, 340, 861, 10141, 355, 340, 198, 6738, 3108, 8019, 1330, 10644, 198, 11748, 302, 198, 11748, 2829, 17752, 198, 198, 11748, 5988, 958, 13, 303, 13528, 578, 13, 85, 18, 355, 317, 198, 6738, ...
2.230948
1,719
import time from math import sqrt from collections import OrderedDict class Solver(object): """executes the alogirithms in order to find the intersections"""
[ 11748, 640, 198, 6738, 10688, 1330, 19862, 17034, 198, 6738, 17268, 1330, 14230, 1068, 35, 713, 628, 198, 4871, 4294, 332, 7, 15252, 2599, 198, 220, 220, 220, 37227, 18558, 1769, 262, 435, 519, 343, 342, 907, 287, 1502, 284, 1064, 262...
3.644444
45
import numpy as np
[ 11748, 299, 32152, 355, 45941, 628, 628 ]
3.142857
7
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Aug 14 09:35:37 2020 @author: Jeremias Knoblauch and Lara Vomfell Description: Likelihood function wrappers for use within NPL class """ import numpy as np import pdb from scipy.stats import poisson, norm, binom from scipy.optimize import minimize import statsmodels.api as sm from scipy.special import logit, expit import torch from torch import nn import torch.nn.functional as F from torch.autograd import Variable # set the seeds and make sure computations are reproducible torch.manual_seed(0) class Likelihood(): """An empty/abstract class that dictates what functions a sub-class of the likelihood type needs to have""" def initialize(self,Y,X): """Returns an initialization for the likelihood parameters, typically based on the maximum likelihood estimate.""" return 0 def evaluate(self, params, Y, X): """Letting Y be of shape (n,) and X of shape (n,d), compute the likelihoods of each pair (Y[i], X[i,:]) at parameter value param""" return 0 class NN_logsoftmax(nn.Module): """Build a new class for the network you want to run, returning log softmax""" def set_parameters(self, initializers): """Set the parameter values obtained from vanilla NN as initializers""" with torch.no_grad(): self.fc1.weight.data = torch.from_numpy(initializers[0].copy()) self.fc1.bias.data = torch.from_numpy(initializers[1].copy()) self.fc2.weight.data = torch.from_numpy(initializers[2].copy()) self.fc2.bias.data = torch.from_numpy(initializers[3].copy()) """Single layer network with layer_size nodes""" """Return the log softmax values for each of the classes""" class NN_softmax(NN_logsoftmax): """Build a new class for the network you want to run, returning non-log softmax""" """Return the softmax values for each of the classes""" class SoftMaxNN(Likelihood): """Get a single-layer softmax-final-layer neural network to classify data""" def store_transformed_Y(self, Y): """From Y = [0,2,1] -> Y = [[1,0,0], [0,0,1], [0,1,0]]""" n = len(Y) self.Y_new = np.zeros((n,self.num_classes)) #DEBU:G THIS ONLY WORKS IF Y IS BINARY! self.Y_new[range(0,n), Y.copy()] = 1.0 self.Y_new = torch.from_numpy(self.Y_new.copy()).float() # NOTE: We don't use this def predict(self, Y,X, parameter_sample): """Given a sample of (X,Y) as well as a sample of network parameters, compute p_{\theta}(Y|X) and compare against the actual values of Y""" n,d = X.shape B = len(parameter_sample) Y_new = np.zeros((n,self.num_classes)) Y_new[range(0,n), Y] = 1.0 # create an empty list to store full predictions, accuracy (0-1) & CE predictions = [] accuracy = [] cross_entropy = [] # log_probs = np.zeros((n,B)) # loop over parameter samples; each theta will be a list for theta,j in zip(parameter_sample, range(0,B)): # set the parameter values of the NN to theta # NOTE: We use the vanilla NN because it returns the log-softmax # (rather than the softmax). Since we endow it with the # parameters extracted from the TVD network, this means that # we will get the log softmax with the TVD-optimal weights self.NN_vanilla.set_parameters(theta) # loop over observations for i in range(0,n): # compute the model probability vectors p_{\theta}(Y|X) w. fixed X # print("X[i,:]", X[i,:].shape) log_probabilities = self.NN_vanilla(torch.from_numpy( X[i,:].reshape(1,d)).float()) # print(model_probabilities.type) # print(model_probabilities.shape) # print("log probs", log_probabilities) # extract the probabilities and store them log_model_probabilities = log_probabilities.data.detach().numpy().copy().flatten() # log_probs[:,i] = log_model_probabilities # ßprint("log probs", log_model_probabilities) # log_model_probabilities is 2d array # print("values", np.exp(log_model_probabilities)) # print("shape", log_model_probabilities.shape) # probability of Y = 1 predictions += [log_model_probabilities[1]] # compute accuracy (whether or not we made mistake in prediction) biggest_probability_index = np.argmax(log_model_probabilities) if biggest_probability_index == Y[i]: accuracy += [1] else: accuracy += [0] # compute cross-entropy cross_entropy += [-np.sum(log_model_probabilities * Y_new[i,:])] # convert into numpy arrays accuracy = np.array(accuracy) predictions = np.array(predictions) cross_entropy = np.array(cross_entropy) return (predictions, accuracy, cross_entropy) class PoissonLikelihood(Likelihood): """Use the traditional link function lambda(x) = exp(xb)""" def predict(self, Y,X, parameter_sample): """Given a sample of (X,Y) as well as a sample of network parameters, compute p_{\theta}(Y|X) and compare against the actual values of Y""" # Get the lambda(X, \theta_i) for all parameters \theta_i in sample. # The i-th column corresponds to lambda(X, \theta_i). lambdas = np.exp(np.matmul(X, np.transpose(parameter_sample))) # Get the predictive/test log likelihoods predictive_log_likelihoods = poisson.logpmf( Y[:, None], lambdas) # Get the MSE and MAE SE = (Y[:, None] - lambdas)**2 AE = np.abs(Y[:, None] - lambdas) return (predictive_log_likelihoods, SE, AE) class SimplePoissonLikelihood(Likelihood): """Simplified Poisson inference without any covariates""" def predict(self, Y,X, parameter_sample): """Given a sample of (X,Y) as well as a sample of network parameters, compute p_{\theta}(Y|X) and compare against the actual values of Y""" # Get the lambda(X, \theta_i) for all parameters \theta_i in sample. # The i-th column corresponds to lambda(X, \theta_i). lambdas = np.matmul(X, np.transpose(parameter_sample)) # Get the predictive/test log likelihoods predictive_log_likelihoods = poisson.logpmf( Y[:, None], lambdas) # Get the MSE and MAE SE = (Y[:, None] - lambdas)**2 AE = np.abs(Y[:, None] - lambdas) return (predictive_log_likelihoods, SE, AE) class PoissonLikelihoodSqrt(Likelihood): """Use the link function lambda(x) = |abs(x)|^1/2 to make the gradients nicer. We still use the (transformed) MLE for initialization"""
[ 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, 19480, 2447, 1478, 7769, 25, 2327, 25, 2718, 12131, 198, 198, 31, 9800, 25, 10272, 76, 44...
2.202679
3,360
import time import machine from network import WLAN from mqtt import MQTTClient # Grapped from https://github.com/pycom/pycom-libraries/blob/master/examples/mqtt/mqtt.py # Add to your /lib folder and upload import pycom pycom.heartbeat(False) # disable the heartbeat LED # Configuration variables WIFI_SSID = "Johnny2000" WIFI_PW = "fedkarma" MQTT_CLIENT = "xddddd9" # Here you make up a client ID which should be unique MQTT_HOST = "influx.itu.dk" MQTT_USER = "iot2022" MQTT_PW = "50b1ll10n" MQTT_TOPIC = "IoT2022sec/fgor" # Test-topic is for testing MQTT_SSL = True # If possible, always use SSL print("WiFi: connecting to %s ..." % WIFI_SSID) # Connect to wifi. wlan = WLAN(mode=WLAN.STA) wlan.connect(ssid=WIFI_SSID, auth=(WLAN.WPA2, WIFI_PW)) while not wlan.isconnected(): machine.idle() print("WiFi: connected successfully to %s" % WIFI_SSID) # Connect to MQTT mqtt = MQTTClient(MQTT_CLIENT, MQTT_HOST, user=MQTT_USER, password=MQTT_PW, ssl=MQTT_SSL) mqtt.connect() print("MQTT connected") # Publish a single message mqtt.publish(topic=MQTT_TOPIC, msg="hello")
[ 11748, 640, 198, 11748, 4572, 198, 6738, 3127, 1330, 370, 25697, 198, 6738, 285, 80, 926, 1330, 337, 48, 15751, 11792, 1303, 7037, 1496, 422, 3740, 1378, 12567, 13, 785, 14, 9078, 785, 14, 9078, 785, 12, 75, 11127, 14, 2436, 672, 14...
2.412664
458
from nornir import InitNornir from nornir.core.filter import F if __name__ == "__main__": main()
[ 6738, 299, 1211, 343, 1330, 44707, 45, 1211, 343, 198, 6738, 299, 1211, 343, 13, 7295, 13, 24455, 1330, 376, 628, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 1388, 3419, 198 ]
2.6
40
# Generated by Django 3.2.7 on 2021-09-27 18:57 from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 513, 13, 17, 13, 22, 319, 33448, 12, 2931, 12, 1983, 1248, 25, 3553, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
2.84375
32
from django.core import mail from django.core.signing import Signer from django.db import transaction from django.contrib.auth.models import User, Group from django.utils import translation from django.core.urlresolvers import resolve, reverse from rest_framework.test import APITestCase from django_tenants.test.cases import TenantTestCase from django_tenants.test.client import TenantClient from smegurus import constants from foundation_tenant.models.base.fileupload import FileUpload from foundation_tenant.models.base.imageupload import ImageUpload from foundation_tenant.models.base.governmentbenefitoption import GovernmentBenefitOption from foundation_tenant.models.base.identifyoption import IdentifyOption from foundation_tenant.models.base.language import Language from foundation_tenant.models.base.postaladdress import PostalAddress from foundation_tenant.models.base.naicsoption import NAICSOption from foundation_tenant.models.base.openinghoursspecification import OpeningHoursSpecification from foundation_tenant.models.base.contactpoint import ContactPoint from foundation_tenant.models.base.geocoordinate import GeoCoordinate from foundation_tenant.models.base.abstract_place import AbstractPlace from foundation_tenant.models.base.country import Country from foundation_tenant.models.base.abstract_intangible import AbstractIntangible from foundation_tenant.models.base.brand import Brand from foundation_tenant.models.base.place import Place from foundation_tenant.models.base.abstract_person import AbstractPerson from foundation_tenant.models.base.tag import Tag from foundation_tenant.models.base.businessidea import BusinessIdea from foundation_tenant.models.base.tellusyourneed import TellUsYourNeed from foundation_tenant.models.base.calendarevent import CalendarEvent from foundation_tenant.models.base.intake import Intake from foundation_tenant.models.base.admission import Admission from foundation_tenant.models.base.faqitem import FAQItem from foundation_tenant.models.base.faqgroup import FAQGroup from foundation_tenant.models.base.communitypost import CommunityPost from foundation_tenant.models.base.communityadvertisement import CommunityAdvertisement from foundation_tenant.models.base.message import Message from foundation_tenant.models.base.note import Note from foundation_tenant.models.base.me import Me from foundation_tenant.models.base.logevent import SortedLogEventByCreated from foundation_tenant.models.base.commentpost import SortedCommentPostByCreated from foundation_tenant.models.base.task import Task from foundation_tenant.models.base.countryoption import CountryOption from foundation_tenant.models.base.provinceoption import ProvinceOption from foundation_tenant.models.base.cityoption import CityOption from foundation_tenant.models.base.visitor import Visitor from foundation_tenant.models.base.inforesource import InfoResource TEST_USER_EMAIL = "ledo@gah.com" TEST_USER_USERNAME = "Ledo" TEST_USER_PASSWORD = "GalacticAllianceOfHumankind" TEST_USER_FIRST_NAME = "Ledo" TEST_USER_LAST_NAME = ""
[ 6738, 42625, 14208, 13, 7295, 1330, 6920, 198, 6738, 42625, 14208, 13, 7295, 13, 12683, 278, 1330, 5865, 263, 198, 6738, 42625, 14208, 13, 9945, 1330, 8611, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 27530, 1330, 11787, 11, ...
3.76942
811
#!/usr/bin/env python # Author(s): Smruti Panigrahi # Import modules import rospy import pcl import numpy as np import ctypes import struct import sensor_msgs.point_cloud2 as pc2 from sensor_msgs.msg import PointCloud2, PointField from std_msgs.msg import Header from random import randint #from pcl_helper import * import pcl_helper as pclh import filtering as flt # TODO: Define functions as required # Callback function for your Point Cloud Subscriber if __name__ == '__main__': # TODO: ROS node initialization rospy.init_node('object_segmentation', anonymous = True) # TODO: Create Publishers to visualize PointCloud topics in rviz pcl_objects_pub = rospy.Publisher("/pcl_objects", PointCloud2, queue_size = 1) pcl_table_pub = rospy.Publisher("/pcl_table", PointCloud2, queue_size = 1) pcl_cluster_pub = rospy.Publisher("/pcl_cluster", PointCloud2, queue_size = 1) # TODO: Create Subscribers pcl_sub = rospy.Subscriber("/sensor_stick/point_cloud", pc2.PointCloud2, pcl_callback, queue_size = 1) # Initialize color_list pclh.get_color_list.color_list = [] # TODO: Spin while node is not shutdown while not rospy.is_shutdown(): rospy.spin()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 2, 6434, 7, 82, 2599, 2439, 81, 47966, 5961, 328, 430, 5303, 198, 198, 2, 17267, 13103, 198, 11748, 686, 2777, 88, 198, 11748, 279, 565, 198, 11748, 299, 32152, 355, 45941, 198,...
2.730337
445
from __future__ import ( absolute_import, unicode_literals, ) import uuid from pysoa.common.metrics import TimerResolution from pysoa.common.transport.base import ( ClientTransport, ) from pysoa.common.transport.exceptions import MessageReceiveTimeout from pysoa.common.transport.http2_gateway.settings import Http2TransportSchema from pysoa.common.transport.http2_gateway.core import Http2ClientTransportCore from conformity import fields @fields.ClassConfigurationSchema.provider(Http2TransportSchema())
[ 6738, 11593, 37443, 834, 1330, 357, 198, 220, 220, 220, 4112, 62, 11748, 11, 198, 220, 220, 220, 28000, 1098, 62, 17201, 874, 11, 198, 8, 198, 198, 11748, 334, 27112, 198, 198, 6738, 12972, 568, 64, 13, 11321, 13, 4164, 10466, 1330,...
3.113095
168
import pickle import numpy as np import networkx as nx import matplotlib.pyplot as plt import utils.plot_functions as pf import utils.data_manipulation as dm import utils.network_manipulation as nm from ast import literal_eval # to evaluate what is in a string literally. flg_plot_graph_on_map = True flg_imshow_adjacency = True #LOOK UP: from VS260C Rowland Taylor Lecture. # anishenko 2010 j neurophys # baden Nature 2016 529. imaging retina # This script Construct directed network Graph object that NetworkX can analyze from the Adjacency matrix # loaded from an .npz file. It will save the graph object as a .gpickle file. It will also save output # figures of the Adjacency Matrix, and the network overlayed on a map. #------------------------------------------------------------------------------------------------------------ ## (0). Check what Operating System you are on (either my machine or Cortex cluster) and adjust directory structure accordingly. dirPre = dm.set_dir_tree() ### Loop over each year - # For each year: Each trade network from years 1962 - 2014. years = range(1962,2015) for y in years: print(str(y)) try: trade_ntwrkG = nx.read_gpickle( str( dirPre + 'adjacency_ntwrkX_pickle_files/trade_ntwrkX_'+ str(y) + '.gpickle' ) ) except: print('Can not find gpickle file') continue # extrace node attributes for plotting LatLon = nx.get_node_attributes(trade_ntwrkG,'LatLon') # these output dicts containing tuples of [(key, value)]. continent = nx.get_node_attributes(trade_ntwrkG,'continent') countryId3 = nx.get_node_attributes(trade_ntwrkG,'countryId3') countryName = nx.get_node_attributes(trade_ntwrkG,'countryName') exports = nx.get_node_attributes(trade_ntwrkG,'exports') imports = nx.get_node_attributes(trade_ntwrkG,'imports') num_countries = len(trade_ntwrkG.nodes()) # Construct an array to color nodes by their continent affiliation node_colors_by_continent = np.zeros(num_countries) conts = set(continent.values()) cntr=0 for each in conts: idx = [key for key, val in continent.items() if val==each] # list <- dict idx = np.array(idx).astype(int) # int array <- list node_colors_by_continent[idx] = cntr cntr=cntr+1 # list comprehensions to extract node attributes from dicts. LatLon = [literal_eval(val) for key, val in LatLon.items()] exports = [literal_eval(val) for key, val in exports.items()] imports = [literal_eval(val) for key, val in imports.items()] # imports = np.array(imports) exports = np.array(exports) # #continent = [val for key, val in continent.items()] #countryId3 = [val for key, val in countryId3.items()] #countryName = [val for key, val in countryName.items()] #------------------------------------------------------------------------------------------------------------ # (5). Plot and save figure of graph in networkX (with nodes in relative geographic location, # labels for names, importd & exports for size. # if flg_plot_graph_on_map: figG = plt.figure(figsize=(15,9)) nSize = exports # could also be imports OR mean(imports,exports) nSize = 1000*(nSize / np.max(nSize)) # Set up vector of log of relative size of edges for colormap and edge thickness in trade map plot nWidth = [literal_eval(trade_ntwrkG[u][v]["weight"]) for u,v in trade_ntwrkG.edges()] nWidth = np.asarray(nWidth) nz = np.rot90(np.nonzero(nWidth)) # a tuple of x & y location of each nonzero value in Adjacency matrix low = np.min(nWidth[nz]) high = np.max(nWidth) nWidth[nz] = np.log(nWidth[nz] - low + 1.1) # subtract off min value and nWidth = nWidth/np.max(nWidth) # take log of normalized width of edges # edgeG = nx.draw_networkx_edges(trade_ntwrkG, pos=LatLon, arrows=False, font_weight='bold', alpha=0.2, width=3*nWidth, edge_color=nWidth, edge_cmap=plt.cm.jet) # edge_vmin=np.min(nWidth), edge_vmax=np.max(nWidth), # nodeG = nx.draw_networkx_nodes(trade_ntwrkG, pos=LatLon, node_size=nSize, cmap=plt.cm.Dark2, with_labels=True, font_weight='bold', node_color=node_colors_by_continent) # labelG = nx.draw_networkx_labels(trade_ntwrkG, pos=LatLon, labels=countryId3, font_size=12) # pf.draw_map() # using BaseMap package. # pf.plot_labels(figG, str( 'Global Trade Map : ' + str(y) ), 'Longitude', 'Latitude', 20) # title, xlabel, ylabel and plot ticks formatting # plt.xlim(-180, +180) plt.ylim(-90,+90) plt.grid(linewidth=2) # sm = plt.cm.ScalarMappable(cmap=plt.cm.jet) sm._A = [] cbar = plt.colorbar(sm, ticks=[0, 1]) cbar.ax.set_yticklabels([pf.order_mag(low), pf.order_mag(high)]) #plt.legend(trade_ntwrkG.nodes()) figG.savefig(str( '../out_figures/trade_maps/' + str(y) + '_trade_map.png' ), bbox_inches='tight') #plt.show() plt.close(figG) #------------------------------------------------------------------------------------------------------------ # (6). Imshow and save figure of Adjacency Matrix - another way to visualize changes in network # # if flg_imshow_adjacency: trade_ntwrkA, imports, exports = dm.load_adjacency_npz_year(str( dirPre + 'adjacency_ntwrk_npz_files/'), y, num_countries) #trade_ntwrkA = out[0] figA = plt.figure(figsize=(15,15)) plt.imshow(np.log10(trade_ntwrkA)) plt.colorbar() pf.plot_labels(figA, str( 'Global Trade Adjacency : ' + str(y) ), 'Country', 'Country', 20) # title, xlabel, ylabel and plot ticks formatting figA.savefig(str( dirPre + 'out_figures/adjacency_mats/' + str(y) + '_adj_mat.png' )) #plt.show() plt.close(figA)
[ 11748, 2298, 293, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 3127, 87, 355, 299, 87, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 198, 11748, 3384, 4487, 13, 29487, 62, 12543, 2733, 355, 279, 69, 220, 198, ...
2.64038
2,105
#%% import importlib from numpy.core.fromnumeric import transpose import aseAtoms2cfg import myread importlib.reload(aseAtoms2cfg) importlib.reload(myread) import copy from random import random import numpy as np # seed random number generator from aseAtoms2cfg import atoms2cfg from ase.build import graphene_nanoribbon from ase import Atoms, Atom from ase.calculators.lammpslib import LAMMPSlib import os import random import generate as gn # atoms = getMirrorChain(deg, cc_dist) # # # atoms = mirrorChain(ixshift, deg, shift, cc_dist) # def mirrorChain(deg, shift, cc_dist): # # atoms1 = getBendedAtomsSpecies2(nLines=2, sheet=False, deg=deg, h=0.0, l=cc_dist) # # for i in range(len(atoms2)): # # atoms1[i].position[0] -= 2*cc_dist * np.sqrt(3) # # # # atoms2 = getBendedAtomsSpecies2(nLines=2, sheet=False, deg=deg, h=0.0, l=cc_dist) # _, _, alat2, _, _, _ = atoms2.cell.cellpar() # for i in range(len(atoms2)): # # atoms2[i].position[2] += 0.125 * alat2 # atoms2[i].position[2] += shift * alat2 # if i in [1,2, 5,6, 9,10, 13,14]: # atoms2[i].position[0] -= cc_dist * np.sqrt(3) # # # # # # atoms2.wrap() # x0 = atoms2[0].position[0] # for i in range(len(atoms2)): # atoms2[i].position[0] -= x0 # # # # for i in range(len(atoms2)): # # atoms2[i].position[0] += (ixshift * cc_dist * np.sqrt(3)) + dx # # # # return atoms2 # # # atoms, ixshift, dx, previousChain = addChain(option, previousOption, ixshift, atoms, previousChain, deg) # # _, _, alat2, _, _, _ = atoms2.cell.cellpar() # atoms2[i].position[2] += shift * alat2 # # atoms = generateRandomStr(atoms, deg, nLines, nRepeat) # # atoms = generateSurface(nLines, deg, nRepeat) # # alats, energies = getCurvesNotHighlyOrdrd(xlim=[14.0, 20.0], nLines=9, nRepeat=1) # #%% #deg = 120 #nLines = 9 #nRepeat = 1 #atoms = generateSurface(nLines, deg, nRepeat) #print(gn.getMinDist(atoms)) #gn.visualize(atoms) # %%
[ 2, 16626, 198, 11748, 1330, 8019, 198, 198, 6738, 299, 32152, 13, 7295, 13, 6738, 77, 39223, 1330, 1007, 3455, 198, 11748, 257, 325, 2953, 3150, 17, 37581, 198, 11748, 616, 961, 198, 11748, 8019, 13, 260, 2220, 7, 589, 2953, 3150, 1...
2.185265
923
#!/usr/bin/env python3 import watson import time import json import arrow import datetime if __name__ == "__main__": main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 11748, 266, 13506, 198, 11748, 640, 198, 11748, 33918, 198, 11748, 15452, 198, 11748, 4818, 8079, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, ...
2.866667
45
#!/usr/bin/env python # -*- coding: utf-8 -*- import datetime # --- UTILITY METHODS --- def _convert_dates_to_strings(row): """ Given a database row returned by psycopg2, convert all dates to strings (usually used to ensure JSON serialisability). """ for key in row: if type(row[key]) == datetime.date: row[key] = str(row[key]) # --- SUMMARY QUERIES --- # --- LATERAL QUERIES --- def _add_lateral_query(db, query, eIDs, result, field, subfield, max_rows_per_eID): """ Executes a LATERAL JOIN query and stores the resulting rows for each eID as a list in result[eID][field][subfield]. """ # Query the database query_data = [max_rows_per_eID, tuple(eIDs)] rows = db.query(query, query_data) # Store database responses in the result dictionary for row in rows: # Ensure insertion location exists in the result JSON eID = row['eid'] if field not in result[eID]: result[eID][field] = {} if subfield not in result[eID][field]: result[eID][field][subfield] = [] # Prepare the row for insertion into the JSON and insert del row['eid'] _convert_dates_to_strings(row) result[eID][field][subfield].append(row) # --- MAIN METHOD ---
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 4818, 8079, 628, 198, 2, 11420, 19255, 4146, 9050, 337, 36252, 50, 11420, 198, 4299, 4808, 1102, 1851, 62, 19581...
2.47619
525
from sygicmaps.client import Client from sygicmaps.input import Input __version__ = "0.2.7-dev"
[ 6738, 827, 70, 291, 31803, 13, 16366, 1330, 20985, 198, 6738, 827, 70, 291, 31803, 13, 15414, 1330, 23412, 198, 198, 834, 9641, 834, 796, 366, 15, 13, 17, 13, 22, 12, 7959, 1, 198 ]
2.771429
35
#!/usr/bin/env python3 # Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. An additional grant # of patent rights can be found in the PATENTS file in the same directory. """Basic example which iterates through the tasks specified and evaluates the given model on them. For more documentation, see parlai.scripts.eval_model. """ from parlai.scripts.eval_model import setup_args, eval_model if __name__ == '__main__': parser = setup_args() opt = parser.parse_args(print_args=False) eval_model(opt, print_parser=parser)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 2, 15069, 357, 66, 8, 2177, 12, 25579, 11, 3203, 11, 3457, 13, 198, 2, 1439, 2489, 10395, 13, 198, 2, 770, 2723, 2438, 318, 11971, 739, 262, 347, 10305, 12, 7635, 5964, ...
3.429293
198
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Time : 2019/2/13 08:58 # @User : zhunishengrikuaile # @File : config.py # @Email : binary@shujian.org # @MyBlog : WWW.SHUJIAN.ORG # @NetName : 書劍 # @Software: 百度识图Api封装 # 配置文件 ''' 应用ID: 14348843 应用API_KEY: wc68dHtiY9mwuD7980EXr1I2 应用SECRET_KEY: dCaMG095LvB9pdtRqbn5eWP4RFSLnj74 ''' import os # from bin.AccessToken.GetToken.GetAccesToken import getname # ACCESS_TOKEN = '' BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # ID,KEY的配置信息 # INFO_CONFIG = { # 'ID': '14348843', # 'API_KEY': 'wc68dHtiY9mwuD7980EXr1I2', # 'SECRET_KEY': 'dCaMG095LvB9pdtRqbn5eWP4RFSLnj74' # } INFO_CONFIG = { 'ID': '16011927', 'API_KEY': '4lbIEZi7tlVLgraSVI7fTw1C', 'SECRET_KEY': 'H1clCsXeAmDYNhGQsVAbHG7iwePSigMH' } # 本地路径配置 LOCALHOST_PATH = { 'PATH': os.path.join(BASE_DIR, 'test/img/') } # URL配置 URL_LIST_URL = { # ACCESS_TOKEN_URL用于获取ACCESS_TOKEN, POST请求, # grant_type必须参数,固定为client_credentials,client_id必须参数,应用的API Key,client_secre 必须参数,应用的Secret Key. 'ACCESS_TOKEN_URL': 'https://aip.baidubce.com/oauth/2.0/token?' + 'grant_type=client_credentials&client_id={API_KEYS}&client_secret={SECRET_KEYS}&'.format( API_KEYS=INFO_CONFIG['API_KEY'], SECRET_KEYS=INFO_CONFIG['SECRET_KEY']), # 通用文字识别, 接口POST请求, # url参数: ## access_token 调用AccessToken模块获取 # Header参数: ## Content-Type: application/x-www-form-urlencoded # Body中的请求参数: ## 参数:image , 是否必选:和url二选一, 类型:string, 可选值范围:null, 说明:图像数据,base64编码后进行urlencode,要求base64编码和urlencode后大小不超过4M,最短边至少15px,最长边最大4096px,支持jpg/png/bmp格式,当image字段存在时url字段失效 ## 参数:url , 是否必选:和image二选一, 类型:string, 可选值范围:null, 说明:图片完整URL,URL长度不超过1024字节,URL对应的图片base64编码后大小不超过4M,最短边至少15px,最长边最大4096px,支持jpg/png/bmp格式,当image字段存在时url字段失效,不支持https的图片链接 ## 参数:language_type , 是否必选:false, 类型:string, 可选值范围:[CHN_ENG、ENG、POR、FRE、GER、ITA、SPA、RUS、JAP、KOR], 说明:识别语言类型,默认为CHN_ENG。可选值包括: [- CHN_ENG:中英文混合; - ENG:英文; - POR:葡萄牙语; - FRE:法语; - GER:德语; - ITA:意大利语; - SPA:西班牙语; - RUS:俄语; - JAP:日语; - KOR:韩语] ## 参数:detect_direction , 是否必选:false, 类型:string, 可选值范围:[true、false], 说明:是否检测图像朝向,默认不检测,即:false。朝向是指输入图像是正常方向、逆时针旋转90/180/270度。可选值包括: - true:检测朝向; - false:不检测朝向。 ## 参数:detect_language, 是否可选:false, 类型:string, 可选值范围:[true、false], 说明:是否检测语言,默认不检测。当前支持(中文、英语、日语、韩语) ## 参数:probability, 是否可选:false, 类型:string, 可选值范围:[true、false], 说明:是否返回识别结果中每一行的置信度 # ------------------------------------------------------------------ # 返回参数 ## 字段:direction, 是否必选:否 类型:int32, 说明:图像方向,当detect_direction=true时存在。 - -1:未定义, - 0:正向, - 1: 逆时针90度, - 2:逆时针180度, - 3:逆时针270度 ## 字段:log_id, 是否必选:是 类型:uint64, 说明:唯一的log id,用于问题定位 ## 字段:words_result, 是否必选:是 类型:array(), 说明:识别结果数组 ## 字段:words_result_num, 是否必选:是 类型:uint32, 说明:识别结果数,表示words_result的元素个数 ## 字段:+words, 是否必选:否 类型:string, 说明:识别结果字符串 ## 字段:probability, 是否必选:否 类型:object , 说明:识别结果中每一行的置信度值,包含average:行置信度平均值,variance:行置信度方差,min:行置信度最小值 'GENERAL_BASIC': 'https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic', # 通用文字识别(高精度版) # URL参数: ## access_token 调用AccessToken模块获取 # Headers参数 ## 参数:Content-Type ,值:application/x-www-form-urlencoded # Body请求参数 ## 参数:image, 是否必选:true, 类型:string, 可选值范围:null 说明:图像数据,base64编码后进行urlencode,要求base64编码和urlencode后大小不超过4M,最短边至少15px,最长边最大4096px,支持jpg/png/bmp格式 ## 参数:detect_direction, 是否必选:false, 类型:string, 可选值范围:[true、false] 说明:是否检测图像朝向,默认不检测,即:false。朝向是指输入图像是正常方向、逆时针旋转90/180/270度。可选值包括: - true:检测朝向; - false:不检测朝向。 ## 参数:probability, 是否必选:false, 类型:string, 可选值范围:[true、false] 说明:是否返回识别结果中每一行的置信度 # ----------------------------------------------------------------------- # 返回说明 ## 字段:direction, 是否必选:否 类型:int32, 说明:图像方向,当detect_direction=true时存在。 - -1:未定义, - 0:正向, - 1: 逆时针90度, - 2:逆时针180度, - 3:逆时针270度 ## 字段:log_id, 是否必选:是 类型:uint64, 说明:唯一的log id,用于问题定位 ## 字段:words_result, 是否必选:是 类型:array(), 说明:识别结果数组 ## 字段:words_result_num, 是否必选:是 类型:uint32, 说明:识别结果数,表示words_result的元素个数 ## 字段:+words, 是否必选:否 类型:string, 说明:识别结果字符串 ## 字段:probability, 是否必选:否 类型:object , 说明:识别结果中每一行的置信度值,包含average:行置信度平均值,variance:行置信度方差,min:行置信度最小值 'ACCURATE_BASIC': 'https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic', # 通用文字识别(含位置信息版) # URL参数: ## access_token 调用AccessToken模块获取 # Headers参数 ## 参数:Content-Type ,值:application/x-www-form-urlencoded # Body请求参数: ## 参数:image, 是否必选:和url二选一, 类型:string, 可选值范围:null 说明:图像数据,base64编码后进行urlencode,要求base64编码和urlencode后大小不超过4M,最短边至少15px,最长边最大4096px,支持jpg/png/bmp格式,当image字段存在时url字段失效 ## 参数:url, 是否必选:和image二选一, 类型:string, 可选值范围:null 说明:图片完整URL,URL长度不超过1024字节,URL对应的图片base64编码后大小不超过4M,最短边至少15px,最长边最大4096px,支持jpg/png/bmp格式,当image字段存在时url字段失效,不支持https的图片链接 ## 参数:recognize_granularity, 是否必选:false, 类型:string, 可选值范围:[big、small] 说明:是否定位单字符位置,big:不定位单字符位置,默认值;small:定位单字符位置 ## 参数:language_type, 是否必选:false, 类型:string, 可选值范围:[CHN_ENG、ENG、POR、FRE、GER、ITA、SPA、RUS、JAP、KOR] 说明:识别语言类型,默认为CHN_ENG。可选值包括: - CHN_ENG:中英文混合; - ENG:英文; - POR:葡萄牙语; - FRE:法语; - GER:德语; - ITA:意大利语; - SPA:西班牙语; - RUS:俄语; - JAP:日语; - KOR:韩语 ## 参数:detect_direction, 是否必选:false, 类型:string, 可选值范围:[true、false] 说明:是否检测图像朝向,默认不检测,即:false。朝向是指输入图像是正常方向、逆时针旋转90/180/270度。可选值包括: - true:检测朝向; - false:不检测朝向。 ## 参数:detect_language, 是否必选:FALSE, 类型:string, 可选值范围:[true、false] 说明:是否检测语言,默认不检测。当前支持(中文、英语、日语、韩语) ## 参数:vertexes_location, 是否必选:FALSE, 类型:string, 可选值范围:[true、false] 说明:是否返回文字外接多边形顶点位置,不支持单字位置。默认为false ## 参数:probability, 是否必选:false, 类型:string, 可选值范围:[true、false] 说明:是否返回识别结果中每一行的置信度 # --------------------------------------------------------------------------------------- # 返回说明 ## 字段:direction, 是否必选:否 类型:int32, 说明:图像方向,当detect_direction=true时存在。 - -1:未定义, - 0:正向, - 1: 逆时针90度, - 2:逆时针180度, - 3:逆时针270度 ## 字段:log_id, 是否必选:是 类型:uint64, 说明:唯一的log id,用于问题定位 ## 字段:words_result, 是否必选:是 类型:array(), 说明:定位和识别结果数组 ## 字段:words_result_num, 是否必选:是 类型:uint32, 说明:识别结果数,表示words_result的元素个数 ## 字段:+vertexes_location, 是否必选:否 类型:array(), 说明:当前为四个顶点: 左上,右上,右下,左下。当vertexes_location=true时存在 ## 字段:++x, 是否必选:是 类型:uint32, 说明:水平坐标(坐标0点为左上角) ## 字段:++y, 是否必选:是 类型:uint32, 说明:垂直坐标(坐标0点为左上角) ## 字段:+location, 是否必选:是 类型:array(), 说明:位置数组(坐标0点为左上角 ## 字段:++left, 是否必选:是 类型:uint32, 说明:表示定位位置的长方形左上顶点的水平坐标 ## 字段:++top, 是否必选:是 类型:uint32, 说明:表示定位位置的长方形左上顶点的垂直坐标 ## 字段:++width, 是否必选:是 类型:uint32, 说明:表示定位位置的长方形的宽度 ## 字段:++height, 是否必选:是 类型:uint32, 说明:表示定位位置的长方形的高度 ## 字段:+words, 是否必选:否 类型:string, 说明:识别结果字符串 ## 字段:+chars, 是否必选:否 类型:array() , 说明:单字符结果,recognize_granularity=small时存在 ## 字段:++location, 是否必选:是 类型:array(), 说明:位置数组(坐标0点为左上角) ## 字段:+++left, 是否必选:是 类型:uint32, 说明:表示定位位置的长方形左上顶点的水平坐标 ## 字段:+++top, 是否必选:是 类型:uint32, 说明:表示定位位置的长方形左上顶点的垂直坐标 ## 字段:+++width, 是否必选:是 类型:uint32, 说明:表示定位定位位置的长方形的宽度 ## 字段:+++height, 是否必选:是 类型:uint32, 说明:表示位置的长方形的高度 ## 字段:++char, 是否必选:是 类型:string, 说明:单字符识别结果 ## 字段:probability, 是否必选:否 类型:object, 说明:识别结果中每一行的置信度值,包含average:行置信度平均值,variance:行置信度方差,min:行置信度最小值 'GENERAL': 'https://aip.baidubce.com/rest/2.0/ocr/v1/general', # 通用文字识别(含位置高精度版) # URL参数: ## access_token 调用AccessToken模块获取 # Headers参数 ## 参数:Content-Type ,值:application/x-www-form-urlencoded # Body请求参数: ## 参数:image, 是否必选:和url二选一, 类型:string, 可选值范围:null 说明:图像数据,base64编码后进行urlencode,要求base64编码和urlencode后大小不超过4M,最短边至少15px,最长边最大4096px,支持jpg/png/bmp格式,当image字段存在时url字段失效 ## 参数:recognize_granularity, 是否必选:false, 类型:string, 可选值范围:[big、small] 说明:是否定位单字符位置,big:不定位单字符位置,默认值;small:定位单字符位置 ## 参数:detect_direction, 是否必选:false, 类型:string, 可选值范围:[true、false] 说明:是否检测图像朝向,默认不检测,即:false。朝向是指输入图像是正常方向、逆时针旋转90/180/270度。可选值包括: - true:检测朝向; - false:不检测朝向。 ## 参数:vertexes_location, 是否必选:FALSE, 类型:string, 可选值范围:[true、false] 说明:是否返回文字外接多边形顶点位置,不支持单字位置。默认为false ## 参数:probability, 是否必选:false, 类型:string, 可选值范围:[true、false] 说明:是否返回识别结果中每一行的置信度 # --------------------------------------------------------------------------------------- # 返回说明 ## 字段:direction, 是否必选:否 类型:int32, 说明:图像方向,当detect_direction=true时存在。 - -1:未定义, - 0:正向, - 1: 逆时针90度, - 2:逆时针180度, - 3:逆时针270度 ## 字段:log_id, 是否必选:是 类型:uint64, 说明:唯一的log id,用于问题定位 ## 字段:words_result, 是否必选:是 类型:array(), 说明:定位和识别结果数组 ## 字段:words_result_num, 是否必选:是 类型:uint32, 说明:识别结果数,表示words_result的元素个数 ## 字段:+vertexes_location, 是否必选:否 类型:array(), 说明:当前为四个顶点: 左上,右上,右下,左下。当vertexes_location=true时存在 ## 字段:++x, 是否必选:是 类型:uint32, 说明:水平坐标(坐标0点为左上角) ## 字段:++y, 是否必选:是 类型:uint32, 说明:垂直坐标(坐标0点为左上角) ## 字段:+location, 是否必选:是 类型:array(), 说明:位置数组(坐标0点为左上角 ## 字段:++left, 是否必选:是 类型:uint32, 说明:表示定位位置的长方形左上顶点的水平坐标 ## 字段:++top, 是否必选:是 类型:uint32, 说明:表示定位位置的长方形左上顶点的垂直坐标 ## 字段:++width, 是否必选:是 类型:uint32, 说明:表示定位位置的长方形的宽度 ## 字段:++height, 是否必选:是 类型:uint32, 说明:表示定位位置的长方形的高度 ## 字段:+words, 是否必选:否 类型:string, 说明:识别结果字符串 ## 字段:+chars, 是否必选:否 类型:array() , 说明:单字符结果,recognize_granularity=small时存在 ## 字段:++location, 是否必选:是 类型:array(), 说明:位置数组(坐标0点为左上角) ## 字段:+++left, 是否必选:是 类型:uint32, 说明:表示定位位置的长方形左上顶点的水平坐标 ## 字段:+++top, 是否必选:是 类型:uint32, 说明:表示定位位置的长方形左上顶点的垂直坐标 ## 字段:+++width, 是否必选:是 类型:uint32, 说明:表示定位定位位置的长方形的宽度 ## 字段:+++height, 是否必选:是 类型:uint32, 说明:表示位置的长方形的高度 ## 字段:++char, 是否必选:是 类型:string, 说明:单字符识别结果 ## 字段:probability, 是否必选:否 类型:object, 说明:识别结果中每一行的置信度值,包含average:行置信度平均值,variance:行置信度方差,min:行置信度最小值 'ACCURATE': 'https://aip.baidubce.com/rest/2.0/ocr/v1/accurate', # 通用文字识别(含生僻字版) # URL参数: ## access_token 调用AccessToken模块获取 # Headers参数 ## 参数:Content-Type ,值:application/x-www-form-urlencoded # Body请求参数: ## 参数:image, 是否必选:和url二选一, 类型:string, 可选值范围:null 说明:图像数据,base64编码后进行urlencode,要求base64编码和urlencode后大小不超过4M,最短边至少15px,最长边最大4096px,支持jpg/png/bmp格式,当image字段存在时url字段失效 ## 参数:url, 是否必选:和image二选一, 类型:string, 可选值范围:null 说明:图片完整URL,URL长度不超过1024字节,URL对应的图片base64编码后大小不超过4M,最短边至少15px,最长边最大4096px,支持jpg/png/bmp格式,当image字段存在时url字段失效,不支持https的图片链接 ## 参数:language_type, 是否必选:false, 类型:string, 可选值范围:[CHN_ENG、ENG、POR、FRE、GER、ITA、SPA、RUS、JAP、KOR] 说明:[识别语言类型,默认为CHN_ENG。可选值包括: - CHN_ENG:中英文混合; - ENG:英文; - POR:葡萄牙语; - FRE:法语; - GER:德语; - ITA:意大利语; - SPA:西班牙语; - RUS:俄语; - JAP:日语; - KOR:韩语] ## 参数:detect_direction, 是否必选:false, 类型:string, 可选值范围:[true、false] 说明:是否检测图像朝向,默认不检测,即:false。朝向是指输入图像是正常方向、逆时针旋转90/180/270度。可选值包括: - true:检测朝向; - false:不检测朝向。 ## 参数:detect_language, 是否必选:FALSE, 类型:string, 可选值范围:[true、false] 说明:是否检测语言,默认不检测。当前支持(中文、英语、日语、韩语) ## 参数:probability, 是否必选:false, 类型:string, 可选值范围:[true、false] # --------------------------------------------------------------------------------------- # 返回说明 ## 字段:direction, 是否必选:否 类型:int32, 说明:图像方向,当detect_direction=true时存在。 - -1:未定义, - 0:正向, - 1: 逆时针90度, - 2:逆时针180度, - 3:逆时针270度 ## 字段:log_id, 是否必选:是 类型:uint64, 说明:唯一的log id,用于问题定位 ## 字段:words_result, 是否必选:是 类型:array(), 说明:识别结果数组 ## 字段:words_result_num, 是否必选:是 类型:uint32, 说明:识别结果数,表示words_result的元素个数 ## 字段:+words, 是否必选:否 类型:string, 说明:识别结果字符串 ## 字段:probability, 是否必选:否 类型:object, 说明:识别结果中每一行的置信度值,包含average:行置信度平均值,variance:行置信度方差,min:行置信度最小值 'GENNERAL_ENHANCED': 'https://aip.baidubce.com/rest/2.0/ocr/v1/general_enhanced', # 网络图片文字识别 # URL参数: ## access_token 调用AccessToken模块获取 # Headers参数 ## 参数:Content-Type ,值:application/x-www-form-urlencoded # Body请求参数: ## 参数:image, 是否必选:和url二选一, 类型:string, 可选值范围:null 说明:图像数据,base64编码后进行urlencode,要求base64编码和urlencode后大小不超过4M,最短边至少15px,最长边最大4096px,支持jpg/png/bmp格式,当image字段存在时url字段失效 ## 参数:url, 是否必选:和image二选一, 类型:string, 可选值范围:null 说明:图片完整URL,URL长度不超过1024字节,URL对应的图片base64编码后大小不超过4M,最短边至少15px,最长边最大4096px,支持jpg/png/bmp格式,当image字段存在时url字段失效,不支持https的图片链接 ## 参数:detect_direction , 是否必选:false, 类型:string, 可选值范围:[true、false], 说明:是否检测图像朝向,默认不检测,即:false。朝向是指输入图像是正常方向、逆时针旋转90/180/270度。可选值包括: - true:检测朝向; - false:不检测朝向。 ## 参数:detect_language, 是否可选:false, 类型:string, 可选值范围:[true、false], 说明:是否检测语言,默认不检测。当前支持(中文、英语、日语、韩语) # --------------------------------------------------------------------------------------- # 返回说明 ## 字段:direction, 是否必选:否 类型:int32, 说明:图像方向,当detect_direction=true时存在。 - -1:未定义, - 0:正向, - 1: 逆时针90度, - 2:逆时针180度, - 3:逆时针270度 ## 字段:log_id, 是否必选:是 类型:uint64, 说明:唯一的log id,用于问题定位 ## 字段:words_result, 是否必选:是 类型:array(), 说明:识别结果数组 ## 字段:words_result_num, 是否必选:是 类型:uint32, 说明:识别结果数,表示words_result的元素个数 ## 字段:+words, 是否必选:否 类型:string, 说明:识别结果字符串 ## 字段:probability, 是否必选:否 类型:object, 说明:识别结果中每一行的置信度值,包含average:行置信度平均值,variance:行置信度方差,min:行置信度最小值 'WEB_IMAGE': 'https://aip.baidubce.com/rest/2.0/ocr/v1/webimage', # 手写文字识别 # URL参数: ## access_token 调用AccessToken模块获取 # Headers参数 ## 参数:Content-Type ,值:application/x-www-form-urlencoded # Body请求参数: ## 参数:image, 是否必选:是 , 类型:string, 可选值范围:NULL, 说明:图像数据,base64编码后进行urlencode,要求base64编码和urlencode后大小不超过4M,最短边至少15px,最长边最大4096px,支持jpg/png/bmp格式 ## 参数:recognize_granularity, 是否必选:false, 类型:string, 可选值范围:[big、small], 说明:是否定位单字符位置,big:不定位单字符位置,默认值;small:定位单字符位置 ## 参数:words_type, 是否必选:false, 类型:string, 可选值范围:[默认/number], 说明:words_type=number:手写数字识别;无此参数或传其它值 默认手写通用识别(目前支持汉字和英文) # --------------------------------------------------------------------------------------- # 返回说明: ## 字段:log_id, 是否必选:是 类型:uint64, 说明:唯一的log id,用于问题定位 ## 字段:words_result_num, 是否必选:是 类型:uint32, 说明:识别结果数,表示words_result的元素个数 ## 字段:words_result, 是否必选:是 类型:array() , 说明:定位和识别结果数组 ## 字段:location, 是否必选:是 类型:object, 说明:位置数组(坐标0点为左上角) ## 字段:left, 是否必选:是 类型:uint32 , 说明:表示定位位置的长方形左上顶点的水平坐标 ## 字段:top, 是否必选:是 类型:uint32, 说明:表示定位位置的长方形左上顶点的垂直坐标 ## 字段:width, 是否必选:是 类型:uint32, 说明:表示定位位置的长方形的宽度 ## 字段:height, 是否必选:是 类型:uint32, 说明:表示定位位置的长方形的高度 ## 字段:words, 是否必选:是 类型:string, 说明:识别结果字符串 ## 字段:chars, 是否必选:否 类型:array(), 说明:单字符结果,recognize_granularity=small时存在 ## 字段:location, 是否必选:是 类型:array() , 说明:位置数组(坐标0点为左上角) ## 字段:left, 是否必选:是 类型:uint32, 说明:表示定位位置的长方形左上顶点的水平坐标 ## 字段:top, 是否必选:是 类型:uint32, 说明:表示定位位置的长方形左上顶点的垂直坐标 ## 字段:width, 是否必选:是 类型:uint32, 说明:表示定位定位位置的长方形的宽度 ## 字段:height, 是否必选:是 类型:uint32, 说明:表示位置的长方形的高度 ## 字段:char, 是否必选:是 类型:string, 说明:单字符识别结果 ## 字段:probability, 是否必选:否 类型:object, 说明:识别结果中每一行的置信度值,包含average:行置信度平均值,variance:行置信度方差,min:行置信度最小值 'HANDWRITING': 'https://aip.baidubce.com/rest/2.0/ocr/v1/handwriting', # 身份证识别 # URL参数: ## access_token 调用AccessToken模块获取 # Headers参数 ## 参数:Content-Type ,值:application/x-www-form-urlencoded # Body请求参数: ## 参数:detect_direction, 是否必选:false, 类型:string, 可选值范围:[true、false], 说明:是否检测图像旋转角度,默认不检测,即:false。朝向是指输入图像是正常方向、逆时针旋转90/180/270度。可选值包括: - true:检测旋转角度并矫正识别; - false:不检测旋转角度,针对摆放情况不可控制的情况建议本参数置为true。 ## 参数:id_card_side, 是否必选:true, 类型:string, 可选值范围:[front、back], 说明:front:身份证含照片的一面;back:身份证带国徽的一面 ## 参数:image, 是否必选:true, 类型:string, 可选值范围:null, 说明:图像数据,base64编码后进行urlencode,要求base64编码和urlencode后大小不超过4M,最短边至少15px,最长边最大4096px,支持jpg/png/bmp格式 ## 参数:detect_risk, 是否必选:false, 类型:string, 可选值范围:[true,false], 说明:是否开启身份证风险类型(身份证复印件、临时身份证、身份证翻拍、修改过的身份证)功能,默认不开启,即:false。可选值:true-开启;false-不开启 # --------------------------------------------------------------------------------------- # 返回说明: ## 字段:direction, 是否必选:否 类型:int32, 说明:图像方向,当detect_direction=true时存在。 - -1:未定义, - 0:正向, - 1: 逆时针90度, - 2:逆时针180度, - 3:逆时针270度 ## 字段:image_status, 是否必选:是 类型:string, 说明:normal-识别正常reversed_side-身份证正反面颠倒non_idcard-上传的图片中不包含身份证blurred-身份证模糊other_type_card-其他类型证照over_exposure-身份证关键字段反光或过曝over_dark-身份证欠曝(亮度过低)unknown-未知状态 ## 字段:risk_type, 是否必选:否 类型:string, 说明:输入参数 detect_risk = true 时,则返回该字段识别身份证类型: normal-正常身份证;copy-复印件;temporary-临时身份证;screen-翻拍;unknown-其他未知情况 ## 字段:edit_tool, 是否必选:否 类型:string, 说明:如果参数 detect_risk = true 时,则返回此字段。如果检测身份证被编辑过,该字段指定编辑软件名称,如:Adobe Photoshop CC 2014 (Macintosh),如果没有被编辑过则返回值无此参数 ## 字段:log_id, 是否必选:是 类型:uint64, 说明:唯一的log id,用于问题定位 ## 字段:words_result, 是否必选:是 类型:array(), 说明:定位和识别结果数组 ## 字段:words_result_num, 是否必选:是 类型:uint32, 说明:识别结果数,表示words_result的元素个数 ## 字段:+location, 是否必选:是 类型:array() , 说明:位置数组(坐标0点为左上角) ## 字段:++left, 是否必选:是 类型:uint32, 说明:表示定位位置的长方形左上顶点的水平坐标 ## 字段:++top, 是否必选:是 类型:uint32, 说明:表示定位位置的长方形左上顶点的垂直坐标 ## 字段:++width, 是否必选:是 类型:uint32, 说明:表示定位位置的长方形的宽度 ## 字段:++height, 是否必选:是 类型:uint32, 说明:表示定位位置的长方形的高度 ## 字段:+words, 是否必选:是 类型:string, 说明:识别结果字符串 'IDCARD': 'https://aip.baidubce.com/rest/2.0/ocr/v1/idcard', # 银行卡识别 # URL参数: ## access_token 调用AccessToken模块获取 # Headers参数 ## 参数:Content-Type ,值:application/x-www-form-urlencoded # Body请求参数: ## 参数:image, 是否必选:true, 类型:string, 可选值范围:null, 说明:图像数据,base64编码后进行urlencode,要求base64编码和urlencode后大小不超过4M,最短边至少15px,最长边最大4096px,支持jpg/png/bmp格式 # --------------------------------------------------------------------------------------- # 返回说明: ## 字段:log_id, 是否必选:是 类型:uint64, 说明:请求标识码,随机数,唯一。 ## 字段:result, 是否必选:是 类型:object, 说明:返回结果 ## 字段:+bank_card_number, 是否必选:是 类型:string, 说明:银行卡卡号 ## 字段:+bank_name, 是否必选:是 类型:string, 说明:银行名,不能识别时为空 ## 字段:+bank_card_type, 是否必选:是 类型:uint32, 说明:银行卡类型,0:不能识别; 1: 借记卡; 2: 信用卡 'BANK_CARD': 'https://aip.baidubce.com/rest/2.0/ocr/v1/bankcard', # 营业执照识别 # URL参数: ## access_token 调用AccessToken模块获取 # Headers参数 ## 参数:Content-Type ,值:application/x-www-form-urlencoded # Body请求参数: ## 参数:image, 是否必选:TRUE, 类型:string, 可选值范围:null, 说明:图像数据,base64编码后进行urlencode,要求base64编码和urlencode后大小不超过4M,最短边至少15px,最长边最大4096px,支持jpg/png/bmp格式 ## 参数:detect_direction, 是否必选:FALSE, 类型:string, 可选值范围:null, 说明:可选值 true,false是否检测图像朝向,默认不检测,即:false。可选值包括true - 检测朝向;false - 不检测朝向。朝向是指输入图像是正常方向、逆时针旋转90/180/270度 ## 参数:accuracy, 是否必选:FALSE, 类型:string, 可选值范围:null, 说明:可选值:normal,high参数选normal或为空使用快速服务;选择high使用高精度服务,但是时延会根据具体图片有相应的增加 # --------------------------------------------------------------------------------------- # 返回说明: ## 字段:log_id, 是否必选:是 类型:uint64, 说明:请求标识码,随机数,唯一。 ## 字段:words_result_num是否必选:是 类型:uint32, 说明:表示定位位置的长方形左上顶点的水平坐标 ## 字段:words_result, 是否必选:是 类型:array(), 说明:识别结果数组 ## 字段:left, 是否必选:是 类型:uint32, 说明:表示定位位置的长方形左上顶点的水平坐标 ## 字段:top, 是否必选:是 类型:uint32, 说明:表示定位位置的长方形左上顶点的垂直坐标 ## 字段:width, 是否必选:是 类型:uint32, 说明:表示定位位置的长方形的宽度 ## 字段:height, 是否必选:是 类型:uint32, 说明:表示定位位置的长方形的高度 ## 字段:words, 是否必选:是 类型:string, 说明:识别结果字符串 'BUSINESS_LICENSE': 'https://aip.baidubce.com/rest/2.0/ocr/v1/business_license', # 护照识别 # URL参数: ## access_token 调用AccessToken模块获取 # Headers参数 ## 参数:Content-Type ,值:application/x-www-form-urlencoded # Body请求参数: ## 参数:image, 是否必选:TRUE, 类型:string, 可选值范围:null, 说明:图像数据,base64编码后进行urlencode,要求base64编码和urlencode后大小不超过4M,最短边至少15px,最长边最大4096px,支持jpg/png/bmp格式 # --------------------------------------------------------------------------------------- # 返回说明: ## 字段:log_id, 是否必选:是 类型:uint64, 说明:唯一的log id,用于问题定位 ## 字段:words_result_num是否必选:是 类型:uint32, 说明:识别结果数,表示words_result的元素个数 ## 字段:words_result, 是否必选:是 类型:array(), 说明:定位和识别结果数组 ## 字段:-location, 是否必选:是 类型:uint32, 说明:水平坐标 ## 字段:-words, 是否必选:是 类型:string, 说明:识别内容 'PASSPORT': 'https://aip.baidubce.com/rest/2.0/ocr/v1/passport', # 名片识别 # URL参数: ## access_token 调用AccessToken模块获取 # Headers参数 ## 参数:Content-Type ,值:application/x-www-form-urlencoded # Body请求参数: ## 参数:image, 是否必选:TRUE, 类型:string, 可选值范围:null, 说明:图像数据,base64编码后进行urlencode,要求base64编码和urlencode后大小不超过4M,最短边至少15px,最长边最大4096px,支持jpg/png/bmp格式 # --------------------------------------------------------------------------------------- # 返回说明: ## 字段:log_id, 是否必选:是 类型:uint64, 说明:唯一的log id,用于问题定位 ## 字段:words_result_num是否必选:是 类型:uint32, 说明:识别结果数,表示words_result的元素个数 ## 字段:words_result, 是否必选:是 类型:array(), 说明:定位和识别结果数组 'BUSUNESS_CARD': 'https://aip.baidubce.com/rest/2.0/ocr/v1/business_card', # 户口本识别 # URL参数: ## access_token 调用AccessToken模块获取 # Headers参数 ## 参数:Content-Type ,值:application/x-www-form-urlencoded # Body请求参数: ## 参数:image, 是否必选:TRUE, 类型:string, 可选值范围:null, 说明:图像数据,base64编码后进行urlencode,要求base64编码和urlencode后大小不超过4M,最短边至少15px,最长边最大4096px,支持jpg/png/bmp格式 # --------------------------------------------------------------------------------------- # 返回说明: ## 字段:log_id, 是否必选:是 类型:uint64, 说明:唯一的log id,用于问题定位 ## 字段:BirthAddress 是否必选:是 类型:string, 说明:出生地 ## 字段:Birthday, 是否必选:是 类型:string, 说明:生日 ## 字段:CardNo, 是否必选:是 类型:string, 说明:身份证号 ## 字段:Name 是否必选:是 类型:string, 说明:姓名 ## 字段:Nation, 是否必选:是 类型:string, 说明:民族 ## 字段:Relationship, 是否必选:是 类型:string, 说明:与户主关系 ## 字段:Sex 是否必选:是 类型:string, 说明:性别 'HOUSEHOLD_REGISTER': 'https://aip.baidubce.com/rest/2.0/ocr/v1/household_register', # 出生医学证明识别 # URL参数: ## access_token 调用AccessToken模块获取 # Headers参数 ## 参数:Content-Type ,值:application/x-www-form-urlencoded # Body请求参数: ## 参数:image, 是否必选:TRUE, 类型:string, 可选值范围:null, 说明:图像数据,base64编码后进行urlencode,要求base64编码和urlencode后大小不超过4M,最短边至少15px,最长边最大4096px,支持jpg/png/bmp格式 # --------------------------------------------------------------------------------------- # 返回说明: ## 字段:log_id, 是否必选:是 类型:uint64, 说明:唯一的log id,用于问题定位 ## 字段:BabyBirthday, 是否必选:是 类型:string, 说明:出生时间 ## 字段:BabyName 是否必选:是 类型:string, 说明:姓名 ## 字段:BabySex, 是否必选:是 类型:string, 说明:性别 ## 字段:Code 是否必选:是 类型:string, 说明:出生证编号 ## 字段:FatherName, 是否必选:是 类型:string, 说明:父亲姓名 ## 字段:MotherName, 是否必选:是 类型:string, 说明:母亲姓名 'BIRTH_CERTIFICATE': 'https://aip.baidubce.com/rest/2.0/ocr/v1/birth_certificate', # 港澳通行证识别 # URL参数: ## access_token 调用AccessToken模块获取 # Headers参数 ## 参数:Content-Type ,值:application/x-www-form-urlencoded # Body请求参数: ## 参数:image, 是否必选:TRUE, 类型:string, 可选值范围:null, 说明:图像数据,base64编码后进行urlencode,要求base64编码和urlencode后大小不超过4M,最短边至少15px,最长边最大4096px,支持jpg/png/bmp格式 # --------------------------------------------------------------------------------------- # 返回说明: ## 字段:log_id, 是否必选:是 类型:uint64, 说明:唯一的log id,用于问题定位 ## 字段:Address, 是否必选:是 类型:string, 说明:签发地点 ## 字段:Birthday 是否必选:是 类型:string, 说明:出生日期 ## 字段:CardNum, 是否必选:是 类型:string, 说明:卡号 ## 字段:NameChn 是否必选:是 类型:string, 说明:姓名 ## 字段:NameEng, 是否必选:是 类型:string, 说明:姓名拼音 ## 字段:Sex, 是否必选:是 类型:string, 说明:性别 ## 字段:ValidDate, 是否必选:是 类型:string, 说明:有效期限 'HK_MACAU_EXITENTRPERMIT': 'https://aip.baidubce.com/rest/2.0/ocr/v1/HK_Macau_exitentrypermit', # 台湾通行证识别 # URL参数: ## access_token 调用AccessToken模块获取 # Headers参数 ## 参数:Content-Type ,值:application/x-www-form-urlencoded # Body请求参数: ## 参数:image, 是否必选:TRUE, 类型:string, 可选值范围:null, 说明:图像数据,base64编码后进行urlencode,要求base64编码和urlencode后大小不超过4M,最短边至少15px,最长边最大4096px,支持jpg/png/bmp格式 # --------------------------------------------------------------------------------------- # 返回说明: ## 字段:log_id, 是否必选:是 类型:uint64, 说明:唯一的log id,用于问题定位 ## 字段:Address, 是否必选:是 类型:string, 说明:签发地点 ## 字段:Birthday 是否必选:是 类型:string, 说明:出生日期 ## 字段:CardNum, 是否必选:是 类型:string, 说明:卡号 ## 字段:NameChn 是否必选:是 类型:string, 说明:姓名 ## 字段:NameEng, 是否必选:是 类型:string, 说明:姓名拼音 ## 字段:Sex, 是否必选:是 类型:string, 说明:性别 ## 字段:ValidDate, 是否必选:是 类型:string, 说明:有效期限 'TAIWAN_EXITENTRYPERMIT': 'https://aip.baidubce.com/rest/2.0/ocr/v1/taiwan_exitentrypermit', # 表格文字识别(异步接口) # URL参数: ## access_token 调用AccessToken模块获取 # Headers参数 ## 参数:Content-Type ,值:application/x-www-form-urlencoded # Body请求参数: ## 参数:image, 是否必选:TRUE, 类型:string, 可选值范围:null, 说明:图像数据,base64编码后进行urlencode,要求base64编码和urlencode后大小不超过4M,最短边至少15px,最长边最大4096px,支持jpg/png/bmp格式 # --------------------------------------------------------------------------------------- # 返回说明: ## 字段:log_id, 是否必选:是 类型:long, 说明:唯一的log id,用于问题定位 ## 字段:result, 是否必选:是 类型:list, 说明:返回的结果列表 ## 字段:+request_id 是否必选:是 类型:string, 说明:该请求生成的request_id,后续使用该request_id获取识别结果 'FORM_ORC_REQUEST': 'https://aip.baidubce.com/rest/2.0/solution/v1/form_ocr/request', # 表格文字识别(异步接口), 获取请求结果 # URL参数: ## access_token 调用AccessToken模块获取 # Headers参数 ## 参数:Content-Type ,值:application/x-www-form-urlencoded # Body请求参数: ## 参数:request_id, 是否必选:TRUE, 类型:string, 可选值范围:null, 说明:发送表格文字识别请求时返回的request id ## 参数:result_type, 是否必选:False, 类型:string, 可选值范围:null, 说明:期望获取结果的类型,取值为“excel”时返回xls文件的地址,取值为“json”时返回json格式的字符串,默认为”excel” # --------------------------------------------------------------------------------------- # 返回说明: ## 字段:log_id, 是否必选:是 类型:long, 说明:唯一的log id,用于问题定位 ## 字段:result, 是否必选:是 类型:object, 说明:返回的结果列表 ## 字段:+result_data, 是否必选:是 类型:string, 说明:识别结果字符串,如果request_type是excel,则返回excel的文件下载地址,如果request_type是json,则返回json格式的字符串 ## 字段:+percent, 是否必选:是 类型:int, 说明:表格识别进度(百分比) ## 字段:+request_id 是否必选:是 类型:string, 说明:该图片对应请求的request_id ## 字段:+ret_code, 是否必选:是 类型:int, 说明:识别状态,1:任务未开始,2:进行中,3:已完成 ## 字段:+ret_msg, 是否必选:是 类型:string, 说明:识别状态信息,任务未开始,进行中,已完成 'FORM_ORC_GET_REQUEST_RESULT': 'https://aip.baidubce.com/rest/2.0/solution/v1/form_ocr/get_request_result', # 表格文字识别(同步接口) # URL参数: ## access_token 调用AccessToken模块获取 # Headers参数 ## 参数:Content-Type ,值:application/x-www-form-urlencoded # Body请求参数: ## 参数:image, 是否必选:TRUE, 类型:string, 可选值范围:null, 说明:图像数据,base64编码后进行urlencode,要求base64编码和urlencode后大小不超过4M,最短边至少15px,最长边最大4096px,支持jpg/png/bmp格式 # --------------------------------------------------------------------------------------- # 返回说明: ## 字段:log_id, 是否必选:是 类型:long, 说明:唯一的log id,用于问题定位 ## 字段:forms_result_num, 是否必选:是 类型:uint32, 说明:识别结果元素个数 ## 字段:forms_result 是否必选:是 类型:object, 说明:识别结果 ## 字段:-body 是否必选:是 类型:object, 说明:表格主体区域 ## 字段:-footer 是否必选:是 类型:object, 说明:表格尾部区域信息 ## 字段:header 是否必选:是 类型:object, 说明:表格头部区域信息 ## 字段:vertexes_location 是否必选:是 类型:object, 说明:表格边界顶点 'FORM': 'https://aip.baidubce.com/rest/2.0/ocr/v1/form', # 通用票据识别 # URL参数: ## access_token 调用AccessToken模块获取 # Headers参数 ## 参数:Content-Type ,值:application/x-www-form-urlencoded # Body请求参数: ## 参数:image, 是否必选:TRUE, 类型:string, 可选值范围:null, 说明:图像数据,base64编码后进行urlencode,要求base64编码和urlencode后大小不超过4M,最短边至少15px,最长边最大4096px,支持jpg/png/bmp格式 ## 参数:recognize_granularity, 是否必选:false, 类型:string, 可选值范围:big、small, 说明:是否定位单字符位置,big:不定位单字符位置,默认值;small:定位单字符位置 ## 参数:probability, 是否必选:false, 类型:string, 可选值范围:true、false, 说明:是否返回识别结果中每一行的置信度 ## 参数:accuracy, 是否必选:false, 类型:string, 可选值范围:normal,缺省, 说明:normal 使用快速服务;缺省或其它值使用高精度服务 ## 参数:detect_direction, 是否必选:false, 类型:string, 可选值范围:true、false, 说明:是否检测图像朝向,默认不检测,即:false。可选值包括true - 检测朝向;false - 不检测朝向。朝向是指输入图像是正常方向、逆时针旋转90/180/270度。 # --------------------------------------------------------------------------------------- # 返回说明: ## 字段:log_id, 是否必选:是 类型:uint64, 说明:唯一的log id,用于问题定位 ## 字段:words_result_num, 是否必选:是 类型:uint32, 说明:识别结果数,表示words_result的元素个数 ## 字段:words_result, 是否必选:是 类型:array(), 说明:定位和识别结果数组 ## 字段:location, 是否必选:是 类型:object, 说明:位置数组(坐标0点为左上角) ## 字段:left, 是否必选:是 类型:uint32, 说明:表示定位位置的长方形左上顶点的水平坐标 ## 字段:top, 是否必选:是 类型:uint32, 说明:表示定位位置的长方形左上顶点的垂直坐标 ## 字段:width, 是否必选:是 类型:uint32, 说明:表示定位位置的长方形的宽度 ## 字段:height, 是否必选:是 类型:uint32, 说明:表示定位位置的长方形的高度 ## 字段:words, 是否必选:是 类型:string, 说明:识别结果字符串 ## 字段:chars, 是否必选:否 类型:array(), 说明:单字符结果,recognize_granularity=small时存在 ## 字段:location, 是否必选:是 类型:array(), 说明:位置数组(坐标0点为左上角) ## 字段:left, 是否必选:是 类型:uint32, 说明:表示定位位置的长方形左上顶点的水平坐标 ## 字段:top, 是否必选:是 类型:uint32, 说明:表示定位位置的长方形左上顶点的垂直坐标 ## 字段:width, 是否必选:是 类型:uint32, 说明:表示定位定位位置的长方形的宽度 ## 字段:height, 是否必选:是 类型:uint32, 说明:表示位置的长方形的高度 ## 字段:char, 是否必选:是 类型:long, 说明:单字符识别结果 ## 字段:probability, 是否必选:否 类型:object, 说明:识别结果中每一行的置信度值,包含average:行置信度平均值,variance:行置信度方差,min:行置信度最小值 'RECEIPT': 'https://aip.baidubce.com/rest/2.0/ocr/v1/receipt', # 增值税发票识别 # URL参数: ## access_token 调用AccessToken模块获取 # Headers参数 ## 参数:Content-Type ,值:application/x-www-form-urlencoded # Body请求参数: ## 参数:image, 是否必选:TRUE, 类型:string, 可选值范围:null, 说明:图像数据,base64编码后进行urlencode,要求base64编码和urlencode后大小不超过4M,最短边至少15px,最长边最大4096px,支持jpg/png/bmp格式 ## 参数:accuracy, 是否必选:false, 类型:string, 可选值范围:normal、high, 说明:normal(默认配置)对应普通精度模型,识别速度较快,在四要素的准确率上和high模型保持一致,high对应高精度识别模型,相应的时延会增加,因为超时导致失败的情况也会增加(错误码282000) # --------------------------------------------------------------------------------------- # 返回说明: # 字段 是否必选 类型 说明 # log_id 是 uint64 唯一的log id,用于问题定位 # words_result_num 是 uint32 识别结果数,表示words_result的元素个数 # words_result 是 array() 识别结果数组 # InvoiceType 是 string 发票种类名称 # InvoiceCode 是 uint32 发票代码 # InvoiceNum 是 uint32 发票号码 # InvoiceDate 是 uint32 开票日期 # TotalAmount 是 uint32 合计金额 # TotalTax 是 string 合计税额 # AmountInFiguers 是 array() 价税合计(小写) # AmountInWords 是 object 价税合计(大写) # CheckCode 是 string 校验码 # SellerName 是 uint32 销售方名称 # SellerRegisterNum 是 uint32 销售方纳税人识别号 # PurchaserName 是 uint32 购方名称 # PurchaserRegisterNum 是 uint32 购方纳税人识别号 # CommodityName 是 object[] 货物名称 # -row 是 uint32 行号 # -word 是 string 内容 # CommodityType 是 object[] 规格型号 # -row 是 uint32 行号 # -word 是 string 内容 # CommodityUnit 是 object[] 单位 # -row 是 uint32 行号 # -word 是 string 内容 # CommodityNum 是 object[] 数量 # -row 是 uint32 行号 # -word 是 string 内容 # CommodityPrice 是 object[] 单价 # -row 是 uint32 行号 # -word 是 string 内容 # CommodityAmount 是 object[] 金额 # -row 是 uint32 行号 # -word 是 string 内容 # CommodityTaxRate 是 object[] 税率 # -row 是 uint32 行号 # -word 是 string 内容 # CommodityTax 是 object[] 税额 # -row 是 uint32 行号 # -word 是 string 内容 'VAT_INVOICE': 'https://aip.baidubce.com/rest/2.0/ocr/v1/vat_invoice', # 火车票识别 # URL参数: ## access_token 调用AccessToken模块获取 # Headers参数 ## 参数:Content-Type ,值:application/x-www-form-urlencoded # Body请求参数: ## 参数:image, 是否必选:TRUE, 类型:string, 可选值范围:null, 说明:图像数据,base64编码后进行urlencode,要求base64编码和urlencode后大小不超过4M,最短边至少15px,最长边最大4096px,支持jpg/png/bmp格式 # --------------------------------------------------------------------------------------- # 返回说明: # 参数 类型 是否必须 说明 # log_id uint64 是 请求标识码,随机数,唯一。 # ticket_num string 是 车票号 # starting_station string 是 始发站 # train_num string 是 车次号 # destination_station string 是 到达站 # date string 是 出发日期 # ticket_rates string 是 车票金额 # seat_category string 是 席别 # name string 是 乘客姓名 'TRAIN_TICKET': 'https://aip.baidubce.com/rest/2.0/ocr/v1/train_ticket', # 出租车票识别 # URL参数: ## access_token 调用AccessToken模块获取 # Headers参数 ## 参数:Content-Type ,值:application/x-www-form-urlencoded # Body请求参数: ## 参数:image, 是否必选:TRUE, 类型:string, 可选值范围:null, 说明:图像数据,base64编码后进行urlencode,要求base64编码和urlencode后大小不超过4M,最短边至少15px,最长边最大4096px,支持jpg/png/bmp格式 # --------------------------------------------------------------------------------------- # 返回说明: # 参数 类型 是否必须 说明 # log_id uint64 是 请求标识码,随机数,唯一。 # words_result_num uint32 是 # Date string 是 日期 # Fare string 是 实付金额 # InvoiceCode string 是 发票代号 # InvoiceNum string 是 发票号码 # TaxiNum string 是 车牌号 # Time string 是 上下车时间 'TAXI_RECEIPT': 'https://aip.baidubce.com/rest/2.0/ocr/v1/taxi_receipt', # 定额发票识别 # URL参数: ## access_token 调用AccessToken模块获取 # Headers参数 ## 参数:Content-Type ,值:application/x-www-form-urlencoded # Body请求参数: ## 参数:image, 是否必选:TRUE, 类型:string, 可选值范围:null, 说明:图像数据,base64编码后进行urlencode,要求base64编码和urlencode后大小不超过4M,最短边至少15px,最长边最大4096px,支持jpg/png/bmp格式 # --------------------------------------------------------------------------------------- # 返回说明: # 字段 是否必选 类型 说明 # log_id 是 uint64 唯一的log id,用于问题定位 # invoice_code 是 string 发票代码 # invoice_number 是 string 发票号码 # invoice_rate 是 string 金额 'QUOTA_INVOICE': 'https://aip.baidubce.com/rest/2.0/ocr/v1/quota_invoice', # 驾驶证识别 # URL参数: ## access_token 调用AccessToken模块获取 # Headers参数 ## 参数:Content-Type ,值:application/x-www-form-urlencoded # Body请求参数: ## 参数:image, 是否必选:TRUE, 类型:string, 可选值范围:null, 说明:图像数据,base64编码后进行urlencode,要求base64编码和urlencode后大小不超过4M,最短边至少15px,最长边最大4096px,支持jpg/png/bmp格式 ## 参数:detect_direction, 是否必选:false, 类型:string, 可选值范围:true、false, 说明:是否检测图像朝向,默认不检测,即:false。朝向是指输入图像是正常方向、逆时针旋转90/180/270度。可选值包括:- true:检测朝向;- false:不检测朝向。 ## 参数:unified_valid_period, 是否必选:false, 类型:bool, 可选值范围:true、false, 说明:true: 归一化格式输出;false 或无此参数按非归一化格式输出 # --------------------------------------------------------------------------------------- # 返回说明: # log_id 是 uint64 唯一的log id,用于问题定位 # words_result_num 是 uint32 识别结果数,表示words_result的元素个数 # words_result 是 array() 识别结果数组 # +words 否 string 识别结果字符串 'DRIVING_LICENSE': 'https://aip.baidubce.com/rest/2.0/ocr/v1/driving_license', # 行驶证识别 # URL参数: ## access_token 调用AccessToken模块获取 # Headers参数 ## 参数:Content-Type ,值:application/x-www-form-urlencoded # Body请求参数: ## 参数:image, 是否必选:TRUE, 类型:string, 可选值范围:null, 说明:图像数据,base64编码后进行urlencode,要求base64编码和urlencode后大小不超过4M,最短边至少15px,最长边最大4096px,支持jpg/png/bmp格式 ## 参数:detect_direction, 是否必选:false, 类型:string, 可选值范围:true、false, 说明:是否检测图像朝向,默认不检测,即:false。朝向是指输入图像是正常方向、逆时针旋转90/180/270度。可选值包括:- true:检测朝向;- false:不检测朝向。 ## 参数:accuracy, 是否必选:false, 类型:bool, 可选值范围:normal,缺省, 说明:normal 使用快速服务,1200ms左右时延;缺省或其它值使用高精度服务,1600ms左右时延 # --------------------------------------------------------------------------------------- # 返回说明: # 字段 必选 类型 说明 # log_id 是 uint64 唯一的log id,用于问题定位 # words_result_num 是 uint32 识别结果数,表示words_result的元素个数 # words_result 是 array() 识别结果数组 # +words 否 string 识别结果字符串 'VEHICLE_LICENSE': 'https://aip.baidubce.com/rest/2.0/ocr/v1/vehicle_license', # 车牌识别 # URL参数: ## access_token 调用AccessToken模块获取 # Headers参数 ## 参数:Content-Type ,值:application/x-www-form-urlencoded # Body请求参数: ## 参数:image, 是否必选:TRUE, 类型:string, 可选值范围:null, 说明:图像数据,base64编码后进行urlencode,要求base64编码和urlencode后大小不超过4M,最短边至少15px,最长边最大4096px,支持jpg/png/bmp格式 ## 参数:multi_detect, 是否必选:false, 类型:boolen, 可选值范围:true、false, 说明:是否检测多张车牌,默认为false,当置为true的时候可以对一张图片内的多张车牌进行识别 # --------------------------------------------------------------------------------------- # 返回说明: # log_id uint64 是 请求标识码,随机数,唯一。 # Color string 是 车牌颜色 # number string 是 车牌号码 # probability string 是 车牌中每个字符的置信度,区间为0-1 # vertexes_location string 是 返回文字外接多边形顶点位置 'LICENSE_PLATE': 'https://aip.baidubce.com/rest/2.0/ocr/v1/license_plate', # 机动车销售发票识别 # URL参数: ## access_token 调用AccessToken模块获取 # Headers参数 ## 参数:Content-Type ,值:application/x-www-form-urlencoded # Body请求参数: ## 参数:image, 是否必选:TRUE, 类型:string, 可选值范围:null, 说明:图像数据,base64编码后进行urlencode,要求base64编码和urlencode后大小不超过4M,最短边至少15px,最长边最大4096px,支持jpg/png/bmp格式 # --------------------------------------------------------------------------------------- # 返回说明: # log_id 是 uint64 唯一的log id,用于问题定位 # InvoiceNum 是 string 发票号码 # 发票号码 是 string 定位和识别结果数组 # PriceTaxLow 是 string 价税合计小写 # PayerCode 是 string 纳税人识别号 # InvoiceCode 是 string 发票代码 # InvoiceDate 是 string 开票日期 # EngineNum 是 string 发动机号码 # ManuModel 是 string 厂商型号 # Price 是 string 不含税价格 # Saler 是 string 销售方 # PriceTax 是 string 价税合计 # Tax 是 string 税额 # MachineCode 是 string 机器编码 # VinNum 是 string 车架号 'VEHICLE_INVOICE': 'https://aip.baidubce.com/rest/2.0/ocr/v1/vehicle_invoice', # 车辆合格证识别 # URL参数: ## access_token 调用AccessToken模块获取 # Headers参数 ## 参数:Content-Type ,值:application/x-www-form-urlencoded # Body请求参数: ## 参数:image, 是否必选:TRUE, 类型:string, 可选值范围:null, 说明:图像数据,base64编码后进行urlencode,要求base64编码和urlencode后大小不超过4M,最短边至少15px,最长边最大4096px,支持jpg/png/bmp格式 # --------------------------------------------------------------------------------------- # 返回说明: # log_id 是 uint64 唯一的log id,用于问题定位 # InnerSize 是 string 货箱内部尺寸 # VinNo 是 string 车架号 # Power 是 string 功率 # FuelType 是 string 燃油种类 # EmissionStandard 是 string 排放标准 # TyreNum 是 string 轮胎数 # CertificationNo 是 string 合格证编号 # EngineNo 是 string 发动机编号 # ChassisType 是 string 底盘型号/底盘ID # CarName 是 string 车辆品牌/车辆名称 # EngineType 是 string 发动机型号 # AxleNum 是 string 轴数 'VEHICLE_CERTIFICATE': 'https://aip.baidubce.com/rest/2.0/ocr/v1/vehicle_certificate', # 车辆VIN码识别 # URL参数: ## access_token 调用AccessToken模块获取 # Headers参数 ## 参数:Content-Type ,值:application/x-www-form-urlencoded # Body请求参数: ## 参数:image, 是否必选:TRUE, 类型:string, 可选值范围:null, 说明:图像数据,base64编码后进行urlencode,要求base64编码和urlencode后大小不超过4M,最短边至少15px,最长边最大4096px,支持jpg/png/bmp格式 ## 参数:imgDirection 是否必选:否 类型: string 可选值范围:默认、setImgDirFlag 说明:该参数决定模型是否自动纠正图像方向,默认不检测,当该参数=setImgDirFlag 时自动检测、纠正图像方向并识别 # --------------------------------------------------------------------------------------- # 返回说明: # log_id 是 uint64 唯一的log id,用于问题定位 # word 是 string VIN码值 'VIN_CODE': 'https://aip.baidubce.com/rest/2.0/ocr/v1/vin_code', # 二维码识别 # URL参数: ## access_token 调用AccessToken模块获取 # Headers参数 ## 参数:Content-Type ,值:application/x-www-form-urlencoded # Body请求参数: ## 参数:image, 是否必选:TRUE, 类型:string, 可选值范围:null, 说明:图像数据,base64编码后进行urlencode,要求base64编码和urlencode后大小不超过4M,最短边至少15px,最长边最大4096px,支持jpg/png/bmp格式 # --------------------------------------------------------------------------------------- # 返回说明: # log_id 是 uint64 唯一的log id,用于问题定位 # codes_result_num 是 uint32 识别结果数,表示codes_result的元素个数 # codes_result 是 array() 定位和识别结果数组 # -type 是 string 识别码类型条码类型包括:9种条形码(UPC_A、UPC_E、EAN_13、EAN_8、CODE_39、CODE_93、CODE_128、ITF、CODABAR),4种二维码(QR_CODE、DATA_MATRIX、AZTEC、PDF_417) # -text 是 string 'QRCODE': 'https://aip.baidubce.com/rest/2.0/ocr/v1/qrcode', # 数字识别 # URL参数: ## access_token 调用AccessToken模块获取 # Headers参数 ## 参数:Content-Type ,值:application/x-www-form-urlencoded # Body请求参数: ## 参数:image, 是否必选:TRUE, 类型:string, 可选值范围:null, 说明:图像数据,base64编码后进行urlencode,要求base64编码和urlencode后大小不超过4M,最短边至少15px,最长边最大4096px,支持jpg/png/bmp格式 ## 参数:recognize_granularity 是否必选:false 类型:string 可选值范围: big、small 说明:是否定位单字符位置,big:不定位单字符位置,默认值;small:定位单字符位置 ## 参数:detect_direction 是否必选:FALSE 类型:string 可选值范围:true、false 说明:是否检测图像朝向,默认不检测,即:false。可选值包括true - 检测朝向;false - 不检测朝向。朝向是指输入图像是正常方向、逆时针旋转90/180/270度。 # --------------------------------------------------------------------------------------- # 返回说明: # log_id 是 uint64 唯一的log id,用于问题定位 # words_result_num 是 uint32 识别结果数,表示words_result的元素个数 # words_result 是 array() 定位和识别结果数组 # location 是 object 位置数组(坐标0点为左上角) # left 是 uint32 表示定位位置的长方形左上顶点的水平坐标 # top 是 uint32 表示定位位置的长方形左上顶点的垂直坐标 # width 是 uint32 表示定位位置的长方形的宽度 # height 是 uint32 表示定位位置的长方形的高度 # words 是 string 识别结果字符串 # chars 否 array() 单字符结果,recognize_granularity=small时存在 # location 是 array() 位置数组(坐标0点为左上角) # left 是 uint32 表示定位位置的长方形左上顶点的水平坐标 # top 是 uint32 表示定位位置的长方形左上顶点的垂直坐标 # width 是 uint32 表示定位定位位置的长方形的宽度 # height 是 uint32 表示位置的长方形的高度 # char 是 string 单字符识别结果 'NUMBERS': 'https://aip.baidubce.com/rest/2.0/ocr/v1/numbers', # 彩票识别 # URL参数: ## access_token 调用AccessToken模块获取 # Headers参数 ## 参数:Content-Type ,值:application/x-www-form-urlencoded # Body请求参数: ## image 是 string - 图像数据,base64编码后进行urlencode,要求base64编码和urlencode后大小不超过4M,最短边至少15px,最长边最大4096px,支持jpg/png/bmp格式 ## recognize_granularity false string big、small 是否定位单字符位置,big:不定位单字符位置,默认值;small:定位单字符位置 # --------------------------------------------------------------------------------------- # 返回说明: # log_id 是 uint64 唯一的log id,用于问题定位 # words_result_num 是 uint32 识别结果数,表示words_result的元素个数 # words_result 是 array() 定位和识别结果数组 # location 是 object 位置数组(坐标0点为左上角) # left 是 uint32 表示定位位置的长方形左上顶点的水平坐标 # top 是 uint32 表示定位位置的长方形左上顶点的垂直坐标 # width 是 uint32 表示定位位置的长方形的宽度 # height 是 uint32 表示定位位置的长方形的高度 # words 是 string 识别结果字符串 # chars 否 array() 单字符结果,recognize_granularity=small时存在 # location 是 array() 位置数组(坐标0点为左上角) # left 是 uint32 表示定位位置的长方形左上顶点的水平坐标 # top 是 uint32 表示定位位置的长方形左上顶点的垂直坐标 # width 是 uint32 表示定位定位位置的长方形的宽度 # height 是 uint32 表示位置的长方形的高度 # char 是 string 单字符识别结果 'LOTTERY': 'https://aip.baidubce.com/rest/2.0/ocr/v1/lottery', # 保单识别 # URL参数: ## access_token 调用AccessToken模块获取 # Headers参数 ## 参数:Content-Type ,值:application/x-www-form-urlencoded # Body请求参数: # image 是 string - 图像数据,base64编码后进行urlencode,要求base64编码和urlencode后大小不超过4M,最短边至少15px,最长边最大4096px,支持jpg/png/bmp格式 # rkv_business 否 string true/false 是否进行商业逻辑处理,rue:进行商业逻辑处理,false:不进行商业逻辑处理,默认true # --------------------------------------------------------------------------------------- # 返回说明: # log_id 是 uint64 唯一的log id,用于问题定位 # words_result_num 是 uint32 识别结果数,表示words_result的元素个数 # words_result 是 object 定位和识别结果数组 # BenPerLst 否 object 受益人信息 # BenPerLst 否 string 受益人姓名 # BenPerPro 否 string 受益比例 # BenPerOrd 否 string 受益顺序 # BenPerTyp 否 string 受益人类型 # InsBilCom 否 string 公司名称 # InsBilNo 否 string 保险单号码 # InsBilTim 否 string 保单生效日期 # InsCltGd1 否 string 投保人性别 # InsCltNa1 否 string 投保人 # InsIdcNb1 否 string 投保人证件号码 # InsIdcTy1 否 string 投保人证件类型 # InsPerLst 否 object 被保人信息 # InsCltGd2 否 string 被保人性别 # InsCltNa2 否 string 被保险人 # InsBthDa2 否 string 被保险人出生日期 # InsIdcNb2 否 string 被保险人证件号码 # InsIdcTy2 否 string 被保险人证件类型 # InsPrdList 否 object 保险信息 # InsCovDur 否 string 保险期限 # InsIcvAmt 否 string 基本保险金额 # InsPayDur 否 string 交费期间 # InsPayFeq 否 string 缴费频率 # InsPerAmt 否 string 每期交费金额 # InsPrdNam 否 string 产品名称 'INSURANCE_DOCUMENTS': 'https://aip.baidubce.com/rest/2.0/ocr/v1/insurance_documents', # 税务局通用机打发票识别 # URL参数: ## access_token 调用AccessToken模块获取 # Headers参数 ## 参数:Content-Type ,值:application/x-www-form-urlencoded # Body请求参数: # image 是 string - 图像数据,base64编码后进行urlencode,要求base64编码和urlencode后大小不超过4M,最短边至少15px,最长边最大4096px,支持jpg/png/bmp格式 # location 否 string true/false 是否输出位置信息,true:输出位置信息,false:不输出位置信息,默认false # --------------------------------------------------------------------------------------- # 返回说明: # log_id 是 uint64 唯一的log id,用于问题定位 # words_result_num 是 uint32 识别结果数,表示words_result的元素个数 # words_result 是 object 定位和识别结果数组 # CommodityName 否 string 商品名称 # InvoiceCode 否 string 发票代码 # InvoiceDate 否 string 发票日期 # InvoiceNum - - 发票号码 # InvoiceType - - 发票类型 # TotalTax - - 合计金额 'INVOICE': 'https://aip.baidubce.com/rest/2.0/ocr/v1/invoice', # 行程单识别 # URL参数: ## access_token 调用AccessToken模块获取 # Headers参数 ## 参数:Content-Type ,值:application/x-www-form-urlencoded # Body请求参数: # image 是 string - 图像数据,base64编码后进行urlencode,要求base64编码和urlencode后大小不超过4M,最短边至少15px,最长边最大4096px,支持jpg/png/bmp格式 # --------------------------------------------------------------------------------------- # 返回说明: # log_id 是 uint64 唯一的log id,用于问题定位 # words_result_num 是 uint32 识别结果数,表示words_result的元素个数 # words_result 是 object 定位和识别结果数组 # name 否 string 姓名 # starting_station 否 string 始发站 # destination_station 否 string 目的站 # flight 否 string 航班号 # date 否 string 日期 # ticket_rates 否 string 票价 'AIR_TICKET': 'https://aip.baidubce.com/rest/2.0/ocr/v1/air_ticket', 'car_info': 'https://aip.baidubce.com/rest/2.0/image-classify/v1/car', }
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2488, 7575, 220, 220, 220, 1058, 13130, 14, 17, 14, 1485, 8487, 25, 3365, 198, 2, 2488, 12982, 220, 220, 220...
0.977379
53,447
# geometry calculations # TODO: # - swap to x^(0.5) instead of sqrt for speed? import numpy as np # from scipy.spatial import distance
[ 2, 22939, 16765, 198, 2, 16926, 46, 25, 198, 2, 220, 532, 16075, 284, 2124, 61, 7, 15, 13, 20, 8, 2427, 286, 19862, 17034, 329, 2866, 30, 198, 198, 11748, 299, 32152, 355, 45941, 198, 2, 422, 629, 541, 88, 13, 2777, 34961, 1330,...
2.843137
51
# -*- coding: utf-8 -*- """ Created on Wed Apr 28 20:46:54 2021 @author: ahmed """ import numpy as np from sklearn import preprocessing, neighbors, svm from sklearn.model_selection import train_test_split import pandas as pd df = pd.read_csv('breast-cancer-wisconsin.txt') df.replace('?',-99999, inplace=True) df.drop(['id'], 1, inplace=True) X = np.array(df.drop(['class'], 1)) y = np.array(df['class']) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1) clf = svm.SVC(kernel = "linear", gamma = 'auto') # clf = svm.SVC(gamma = 'auto') clf.fit(X_train, y_train) confidence = clf.score(X_test, y_test) print(confidence) # example_measures = np.array([[4,2,1,1,1,2,3,2,1]]) # example_measures = example_measures.reshape(len(example_measures), -1) # prediction = clf.predict(example_measures) # print(prediction)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41972, 319, 3300, 2758, 2579, 1160, 25, 3510, 25, 4051, 33448, 198, 198, 31, 9800, 25, 29042, 1150, 198, 37811, 198, 198, 11748, 299, 32152, 355, 45941, 198,...
2.451895
343
import setuptools from cli_badges import __version__ with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="cli_badges", # Replace with your own username version=__version__, author="Haider Ali Punjabi", author_email="me@haideralipunjabi.com", keywords=["color","colour","paint","ansi","terminal","linux","python","cli","badges","cli-badges","terminal-badges","console","console-badges"], description="Quirky little python package for generating badges for your cli apps", long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/haideralipunjabi/cli-badges", packages=["cli_badges"], classifiers=[ "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.0", "Programming Language :: Python :: 3.2", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Development Status :: 5 - Production/Stable", "Environment :: Console", "Operating System :: POSIX", "Operating System :: POSIX :: Linux", "Operating System :: Microsoft", "Operating System :: Microsoft :: Windows", "Operating System :: Microsoft :: Windows :: Windows 10", "Operating System :: POSIX :: Other", "Programming Language :: Unix Shell", "Topic :: Terminals" ], python_requires='>=3.6', install_requires=[ 'colored' ] )
[ 11748, 900, 37623, 10141, 198, 6738, 537, 72, 62, 14774, 3212, 1330, 11593, 9641, 834, 198, 4480, 1280, 7203, 15675, 11682, 13, 9132, 1600, 366, 81, 4943, 355, 277, 71, 25, 198, 220, 220, 220, 890, 62, 11213, 796, 277, 71, 13, 961, ...
2.707038
611
# -*- coding: utf-8 -*- import emoji from typing import Tuple from nonebot.adapters.onebot.v11 import Message, MessageSegment # CONSTANT PLAIN_TEXT = ['face', 'reply', 'at', 'text']
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 44805, 198, 6738, 19720, 1330, 309, 29291, 198, 6738, 4844, 13645, 13, 324, 12126, 13, 505, 13645, 13, 85, 1157, 1330, 16000, 11, 16000, 41030, 434, 198, 198, 2, ...
2.8
65
"""Ascii menu class""" from __future__ import print_function from cloudmesh_client.common.Printer import Printer from builtins import input def ascii_menu(title=None, menu_list=None): """ creates a simple ASCII menu from a list of tuples containing a label and a functions reference. The function should not use parameters. :param title: the title of the menu :param menu_list: an array of tuples [('label', f1), ...] """ if not title: title = "Menu" n = len(menu_list) display() running = True while running: result = input("Select between {0} - {1}: ".format(1, n)) print("<{0}>".format(result)) if result.strip() in ["q"]: running = False else: try: result = int(result) - 1 if 0 <= result < n: (label, f) = menu_list[result] print("EXECUTING:", label, f.__name__) f() else: print("ERROR: wrong selection") except Exception as e: print("ERROR: ", e) display() def menu_return_num(title=None, menu_list=None, tries=1, with_display=True): """ creates a simple ASCII menu from a list of labels :param title: the title of the menu :param menu_list: a list of labels to choose :param tries: num of tries till discard :return: choice num (head: 0), quit: return 'q' """ if not title: title = "Menu" n = len(menu_list) display() while tries > 0: # display() result = input("Select between {0} - {1}: ".format(1, n)) if result == "q": return 'q' else: try: result = int(result) except: print("invalid input...") tries -= 1 continue if 0 < result <= n: print("choice {0} selected.".format(result)) return result - 1 else: print("ERROR: wrong selection") return 'q'
[ 37811, 1722, 979, 72, 6859, 1398, 37811, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 6738, 6279, 76, 5069, 62, 16366, 13, 11321, 13, 6836, 3849, 1330, 1736, 3849, 198, 198, 6738, 3170, 1040, 1330, 5128, 628, 198, 4299, 35...
2.115694
994
# -*- coding: cp936 -*- A=[] B=[] f=open('1.txt','r') c=[] for i in range(0,16): a = f.readline() b = a.split() c.append(b) #print(c) for i in c: A.append(i[0]) B.append(i[1]) #print (A) #print (B) xor=[] for i in range(0,len(A)): for j in range(0,len(A[0])): d = int(A[i][j])^int(B[i][j]) xor.append(d) #print (xor) #print (len(xor)) j=0 C="" D=[] for i in xor: #print (i,end="") C+=str(i) j=j+1 if j==8: #print() D.append(C) C="" j=0 #print(D) for i in D: print(i)
[ 2, 532, 9, 12, 19617, 25, 31396, 24, 2623, 532, 9, 12, 201, 198, 201, 198, 32, 28, 21737, 201, 198, 33, 28, 21737, 201, 198, 69, 28, 9654, 10786, 16, 13, 14116, 41707, 81, 11537, 201, 198, 66, 28, 21737, 201, 198, 1640, 1312, ...
1.5625
384
#! python #-*- coding: utf-8 -*- # 标准化输出。 from __future__ import print_function # 各种包。 import os, sys, time import math # PYMC import pymc as pm from pymc import Uniform, Normal, MCMC, AdaptiveMetropolis # NUMPY import numpy as np # SPARK from pyspark.sql import SparkSession # 外部依赖项 from model_DALEC_LAI_All import init_Model, NEE_eval, tau_eval, save_Traces print ('model loaded') # 数据处理函数。 # Main: 程序开始执行的地方. if __name__ == "__main__": # 0、spark对话内容。 spark = SparkSession.builder.appName('parallize_DALEC_LAI_All').getOrCreate() sc = spark.sparkContext #sc.addPyFile('/root/xuq/20200614/model_DALEC_LAI_All.py') #sc.addPyFile('/root/xuq/20200614/simulation_DALEC_LAI_All.py') # ====================================================================================== # 数据标记。 strFlag = '_20200702' #strFlag = '_part_area' # '_all_nation' print (time.asctime()) start_time = time.time() # ====================================================================================== # 1、数据容器:驱动数据 &观测数据。 # all #path_all = 'hdfs:///user/root/Data/data_LAI' + strFlag + '.csv' path_all = '/CodingDiary/files/data_test.csv' all_RDD_data = sc.textFile(path_all).take(2) # all_List = [map(float, e.split(',')) for e in all_RDD_data] all_data = np.array(all_List) print (len(all_data)) # ====================================================================================== print ('数据加载成功 ~') # 单个。 #run(all_data[4561]) # 并行。 data = sc.parallelize(all_data) data.foreach(run) # 结束。 print ('结束') print (time.time() - start_time) print (time.asctime())
[ 2, 0, 21015, 198, 2, 12, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 10545, 254, 229, 49035, 228, 44293, 244, 164, 122, 241, 49035, 118, 16764, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 2, 10263, 238, ...
2.23783
719
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.11.3 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # %% import pandas as pd # %% tags=["parameters"] upstream = None product = None # %% df = pd.DataFrame({ 'name': ['Hemingway, Ernest', 'virginia woolf', 'charles dickens '], 'birth_year': [1899, 1882, 1812], }) # %% df.to_csv(product['data'], index=False)
[ 2, 11420, 198, 2, 474, 929, 88, 353, 25, 198, 2, 220, 220, 474, 929, 88, 5239, 25, 198, 2, 220, 220, 220, 220, 2420, 62, 15603, 341, 25, 198, 2, 220, 220, 220, 220, 220, 220, 7552, 25, 764, 9078, 198, 2, 220, 220, 220, 220, ...
2.187251
251
import unittest from unittest.mock import patch import numpy as np import pytest import pysprint from pysprint import FFTMethod, Generator from pysprint.core._fft_tools import ( find_roi, find_center, _ensure_window_at_origin, predict_fwhm, ) from pysprint.utils import NotCalculatedException # Obviously we need more verbose tests for that later. @pytest.mark.parametrize("printing", [True, False]) if __name__ == "__main__": unittest.main()
[ 11748, 555, 715, 395, 198, 6738, 555, 715, 395, 13, 76, 735, 1330, 8529, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 12972, 9288, 198, 198, 11748, 279, 893, 4798, 198, 6738, 279, 893, 4798, 1330, 376, 9792, 17410, 11, 35986, ...
2.751445
173
import turtle as trtl import random as rand # leaderboard variables leaderboard_file_name = "a122_leaderboard.txt" leader_names_list = [] leader_scores_list = [] player_name = input ("Please enter your name:") import leaderboard as lb score = 0 colors = ["black", "sky blue", "salmon", "orchid", "pale green"] font_setup = ("Arial", 20, "normal") spot_size = 2 spot_color = 'pink' spot_shape = "turtle" timer = 30 counter_interval = 1000 timer_up = False score = 0 #-----initialize the turtles----- spot = trtl.Turtle() spot.shape(spot_shape) spot.shapesize(spot_size) spot.fillcolor(spot_color) score_writer = trtl.Turtle() score_writer.hideturtle() score_writer.penup() score_writer.goto(160, 160) # x,y set to fit on smaller screen score_writer.pendown() #score_writer.showturtle() counter = trtl.Turtle() counter.hideturtle() counter.penup() counter.goto(-160, 160) # x,y set to fit on smaller screen counter.pendown() #counter.showturtle() #-----game functions----- # countdown function # update and display the score # what happens when the spot is clicked # resize the turtle # stamp turtle # change the position of spot # starting the game #----------events---------- start_game() wn = trtl.Screen() wn.bgcolor("white smoke") wn.mainloop()
[ 11748, 28699, 355, 491, 28781, 201, 198, 11748, 4738, 355, 43720, 201, 198, 201, 198, 2, 3554, 3526, 9633, 201, 198, 27940, 3526, 62, 7753, 62, 3672, 796, 366, 64, 18376, 62, 27940, 3526, 13, 14116, 1, 201, 198, 27940, 62, 14933, 62...
2.705882
493
class KshellDataStructureError(Exception): """ Raise when KSHELL data file has unexpected structure / syntax. """
[ 4871, 509, 29149, 6601, 1273, 5620, 12331, 7, 16922, 2599, 198, 220, 220, 220, 37227, 198, 220, 220, 220, 35123, 618, 509, 9693, 23304, 1366, 2393, 468, 10059, 4645, 1220, 15582, 13, 198, 220, 220, 220, 37227 ]
3.378378
37
import typing from modtox.modtox.Molecules.target_col import CollectionFromTarget, IDs from modtox.modtox.Molecules.mol import MoleculeFromInChI from modtox.modtox.utils.enums import Database, StandardTypes from unittest.mock import MagicMock, Mock, PropertyMock, patch import pickle5 ## sm stands for molecule identifier (smiles previously) @patch( "modtox.modtox.Molecules.col.RetrieveBDB.activities", create=True, new_callable=PropertyMock, ) @patch( "modtox.modtox.Molecules.col.RetrieveBDB.ids", create=True, new_callable=PropertyMock, ) @patch("modtox.modtox.Molecules.col.RetrieveBDB.retrieve_by_target") @patch( "modtox.modtox.Molecules.col.RetrieveChEMBL.activities", create=True, new_callable=PropertyMock, ) @patch( "modtox.modtox.Molecules.col.RetrieveChEMBL.ids", create=True, new_callable=PropertyMock, ) @patch("modtox.modtox.Molecules.col.RetrieveChEMBL.retrieve_by_target") @patch( "modtox.modtox.Molecules.col.RetrievePubChem.activities", create=True, new_callable=PropertyMock, ) @patch( "modtox.modtox.Molecules.col.RetrievePubChem.ids", create=True, new_callable=PropertyMock, ) @patch("modtox.modtox.Molecules.col.RetrievePubChem.retrieve_by_target") def test_fetch( pc_ret, pc_ids, pc_acts, ch_ret, ch_ids, ch_acts, bdb_ret, bdb_ids, bdb_acts, ): """Tests activities and molecules are correctly merged when retrieval is called from modtox.Collection. """ pc_ids.return_value = {"sm1": "cid1", "sm2": "cid2"} pc_acts.return_value = ["pc_act1", "pc_act2", "pc_act3"] ch_ids.return_value = {"sm1": "ch1", "sm3": "ch2"} ch_acts.return_value = ["ch_act1", "ch_act2", "ch_act3"] bdb_ids.return_value = {"sm2": "bdbm1", "sm4": "bdbm2"} bdb_acts.return_value = ["bdb_act1", "bdb_act2", "bdb_act3"] c = CollectionFromTarget("abc") c.fetch([e for e in Database]) assert c.activities == [ "bdb_act1", "bdb_act2", "bdb_act3", "pc_act1", "pc_act2", "pc_act3", "ch_act1", "ch_act2", "ch_act3", ] assert c.ids == { Database.BindingDB: {"sm2": "bdbm1", "sm4": "bdbm2"}, Database.PubChem: {"sm1": "cid1", "sm2": "cid2"}, Database.ChEMBL: {"sm1": "ch1", "sm3": "ch2"}, } def test_unique_smiles(): """Tests that duplicates from different databases are removed.""" c = CollectionFromTarget("abc") c.ids = { "db1": {"sm1": "id1", "sm2": "id2"}, "db2": {"sm1": "id3", "sm3": "id4"}, "db3": {"sm4": "id5", "sm1": "id6"}, } c.get_unique_inchis() assert c.unique_inchis == {"sm1", "sm2", "sm3", "sm4"} def test_unify_ids(): """Tests IDs are correctly unified in IDs object for each molecule. """ c = CollectionFromTarget("abc") c.ids = { Database.BindingDB: {"sm1": "id1", "sm2": "id2"}, Database.ChEMBL: {"sm1": "id3", "sm3": "id4"}, } c.unique_inchis = {"sm1", "sm2", "sm3"} c._unify_ids() for obj in c.unified_ids.values(): assert isinstance(obj, IDs) assert c.unified_ids["sm1"].bindingdb_id == "id1" assert c.unified_ids["sm1"].chembl_id == "id3" assert c.unified_ids["sm2"].bindingdb_id == "id2" assert c.unified_ids["sm3"].chembl_id == "id4" def test_create_molecules(): """ 1. Same number of molecules and unique inchis. 2. Associates activities to each molecule. """ c = CollectionFromTarget("abc") c.unique_inchis = [ "sm1", "sm2", "sm3", ] # As a list instead of set to maintain order c.activities = [ MockAct("sm1"), MockAct("sm2"), MockAct("sm3"), MockAct("sm1"), MockAct("sm1"), MockAct("sm2"), ] c.unified_ids = {"sm1": IDs(), "sm2": IDs(), "sm3": IDs()} c.create_molecules() assert len(c.molecules) == len(c.unique_inchis) assert isinstance(c.molecules[0].ids, IDs) assert len(c.molecules[0].activities) == 3 assert len(c.molecules[1].activities) == 2 assert len(c.molecules[2].activities) == 1 assert c.molecules[0].name == "abc_0" assert c.molecules[1].name == "abc_1" assert c.molecules[2].name == "abc_2" def test_integration_test(): """For debugging purposes, does not test anything.""" c = CollectionFromTarget("P23316") c.fetch([Database.BindingDB, Database.ChEMBL, Database.PubChem]) c.get_unique_inchis() c._unify_ids() c.create_molecules() c.assess_activity( {StandardTypes.Ki: 100, "pubchem": 0, StandardTypes.IC50: 100} ) with open("P23316.pickle", "wb") as f: pickle5.dump(c, f) c.to_sdf("P23316.sdf") return @patch("modtox.modtox.Molecules.mol.MoleculeFromInChI.assess_activity") def test_asses_activity(mock): """Tests that the function of the molecules to assess the activity is called once per molecule and per criterion.""" c = CollectionFromTarget("P23316") c.molecules = [MoleculeFromInChI("hi"), MoleculeFromInChI("hi")] criteria = {"Ki": 10, "IC50": 30} c.assess_activity(criteria) assert mock.call_count == 4 def test_add_pubchem_activity(): """Tests that depending on the activity tags in the pubchem_activity attribute, molecules are classified correctly. """ c = CollectionFromTarget("P23316") c.molecules = [ MoleculeFromInChI("inchi1", "mol1"), MoleculeFromInChI("inchi2", "mol2"), MoleculeFromInChI("inchi3, mol3"), ] c.pubchem_activity = {"inchi1": ["Active"], "inchi2": ["Inactive", "Active"]} c.add_pubchem_activity() assert c.molecules[0].activity_tags["pubchem"] == "Active" assert c.molecules[1].activity_tags["pubchem"] == "Contradictory data" assert c.molecules[2].activity_tags["pubchem"] == "No data" @patch( "modtox.modtox.Molecules.target_col.CollectionFromTarget.add_pubchem_activity" ) def test_assess_activity_pubchem(mock): """""" c = CollectionFromTarget("P23316") c.assess_activity({"pubchem": 0}) mock.assert_called_once_with()
[ 11748, 19720, 198, 6738, 953, 83, 1140, 13, 4666, 83, 1140, 13, 44, 2305, 13930, 13, 16793, 62, 4033, 1330, 12251, 4863, 21745, 11, 32373, 198, 6738, 953, 83, 1140, 13, 4666, 83, 1140, 13, 44, 2305, 13930, 13, 43132, 1330, 25726, 23...
2.232143
2,744
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ ============= TAP plus ============= @author: Juan Carlos Segovia @contact: juan.carlos.segovia@sciops.esa.int European Space Astronomy Centre (ESAC) European Space Agency (ESA) Created on 30 jun. 2016 """ import xml.sax from astroquery.utils.tap.model.taptable import TapTableMeta from astroquery.utils.tap.model.tapcolumn import TapColumn from astroquery.utils.tap.xmlparser import utils as Utils READING_SCHEMA = 10 READING_TABLE = 20 READING_TABLE_COLUMN = 30 class TableSaxParser(xml.sax.ContentHandler): ''' classdocs ''' def __init__(self): ''' Constructor ''' self.__internal_init()
[ 2, 49962, 739, 257, 513, 12, 565, 682, 347, 10305, 3918, 5964, 532, 766, 38559, 24290, 13, 81, 301, 201, 198, 37811, 201, 198, 25609, 28, 201, 198, 51, 2969, 5556, 201, 198, 25609, 28, 201, 198, 201, 198, 31, 9800, 25, 16852, 1740...
2.423077
312
from django.conf.urls import url from explorer import views urlpatterns = [ # 首页 url(r'^get_block_chart$', views.get_block_chart), # 爆块信息统计 url(r'^get_overview$', views.get_overview), # 概览 url(r'^get_hashrate_ranking$', views.get_hashrate_ranking), # 算力走势-有效算力 url(r'^get_power_valid$', views.get_power_valid), # 矿工排行榜-有效算力 url(r'^get_blocks$', views.get_blocks), # 矿工排行榜-出块数 url(r'^get_power_growth$', views.get_power_growth), # 矿工排行榜-算力增速 url(r'^get_tipset$', views.get_tipset), # 最新区块列表 url(r'^get_message_list$', views.get_message_list), # 消息列表 url(r'^get_block_statistics$', views.get_block_statistics), # 出块统计 # 首页点击事件 # 矿工查询(矿工id) url(r'^address/(?P<address_id>.*?)/overview$', views.address_overview), # 账户信息_概览 判断是普通用户还是管理用户 根据miner字段判断 url(r'^address/(?P<address_id>.*?)/balance$', views.address_balance), # 账户信息_账户钱包变化 url(r'^address/(?P<address_id>.*?)/power-stats$', views.address_power_stats), # 账户信息_算力变化(根据miner查询) url(r'^address/(?P<address_id>.*?)/message$', views.address_message), # 账户信息_消息列表 # url(r'^address/(?P<address_id>.*?)/power-overview$', views.address_power_overview), # 账户信息_算力概览 url(r'^address/(?P<address_id>.*?)/mining_stats$', views.address_mining_stats), # 账户信息_算力概览(内部调用,不需要使用) # 根据区块高度查询 url(r'^block_high/(?P<high_value>.*?)/block_high_info$', views.block_high_info), # 区块高度详情 url(r'^block/(?P<block_id>.*?)/block_info$', views.block_id_info), # 区块详情 url(r'^block/(?P<block_id>.*?)/block_message_list$', views.by_block_id_message_list), # 区块消息列表 # 消息搜索 url(r'^message/(?P<message_id>.*?)/message_info$', views.message_info_by_message_id), # 区块高度详情 # 节点搜索 url(r'^peer/(?P<peer_id>.*?)/peer_info$', views.peer_info), # 节点详情 url('^search$', views.search), # 首页搜索按钮 # 统计---挖矿图表 url(r'^get_block_distribution$', views.get_block_distribution), # 矿工有效算力分布 url(r'^get_mining_earnings$', views.get_mining_earnings), # 挖矿收益 url(r'^get_sector_pledge$', views.get_sector_pledge), # 挖矿收益 url(r'^get_miner_power_increment_tendency$', views.get_miner_power_increment_tendency), # 矿工算力增量走势 # 统计---gas统计 url(r'^get_gas_tendency$', views.get_gas_tendency), # gas走势 url(r'^get_gas_data_24h$', views.get_gas_data_24h), # 24小时gas数据 # 长地址转短地址 url(r'^address_to_miner_no&', views.address_to_miner_no) ]
[ 6738, 42625, 14208, 13, 10414, 13, 6371, 82, 1330, 19016, 198, 198, 6738, 39349, 1330, 5009, 198, 198, 6371, 33279, 82, 796, 685, 198, 220, 220, 220, 1303, 16268, 99, 244, 165, 94, 113, 198, 220, 220, 220, 19016, 7, 81, 6, 61, 113...
1.520557
1,581
import math import numpy as np import os import vmdutil from vmdutil import vmddef from lookat import LookAt, MotionFrame FPS = 30 MIXEL = 0.08 G = -9.8 / MIXEL / FPS / FPS GV = (0, G, 0) # fixed HALFG = G / 2 cp_all = vmddef.BONE_LERP_CONTROLPOINTS replace_controlpoints(cp_all, vmdutil.PARABOLA2_CONTROLPOINTS, 1) PARABOLA2 = vmddef.bone_controlpoints_to_vmdformat(cp_all) replace_controlpoints(cp_all, vmdutil.PARABOLA1_CONTROLPOINTS, 1) PARABOLA1 = vmddef.bone_controlpoints_to_vmdformat(cp_all)
[ 11748, 10688, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 28686, 198, 198, 11748, 410, 9132, 22602, 198, 6738, 410, 9132, 22602, 1330, 45887, 1860, 891, 198, 6738, 804, 265, 1330, 6803, 2953, 11, 20843, 19778, 198, 198, 37, 3705, 79...
2.297297
222
# Generated by Django 3.2.6 on 2021-08-24 01:05 from django.db import migrations
[ 2, 2980, 515, 416, 37770, 513, 13, 17, 13, 21, 319, 33448, 12, 2919, 12, 1731, 5534, 25, 2713, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 628 ]
2.766667
30
#!/usr/bin/env python from __future__ import print_function from time import localtime from sys import exc_info from sys import exit DEFAULT_RESOLUTION = 5 MIDDAY = 12 HOUR_WORD_MAPPINGS = { 0: "midnight", 1: "one", 2: "two", 3: "three", 4: "four", 5: "five", 6: "six", 7: "seven", 8: "eight", 9: "nine", 10: "ten", 11: "eleven", 12: "noon" } MINUTE_WORD_MAPPINGS = { 0: "", 5: "five", 10: "ten", 15: "quarter", 20: "twenty", 25: "twenty-five", 30: "half", 35: "twenty-five", 40: "twenty", 45: "quarter", 50: "ten", 55: "five" } if __name__ == "__main__": time_to_convert = localtime() resolution = DEFAULT_RESOLUTION try: print(to_fuzzy_time(time_to_convert.tm_hour, time_to_convert.tm_min, resolution)) except: print("Failed to convert {0} due to {1}".format(time_to_convert, exc_info())) exit(1)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 6738, 640, 1330, 1957, 2435, 198, 6738, 25064, 1330, 2859, 62, 10951, 198, 6738, 25064, 1330, 8420, 198, 198, 7206, 38865, 62, ...
1.853403
573
from icalendar import Calendar, Event import urllib.request from bs4 import BeautifulSoup mainParse(2018)
[ 6738, 220, 605, 9239, 1330, 26506, 11, 8558, 198, 11748, 2956, 297, 571, 13, 25927, 198, 6738, 275, 82, 19, 1330, 23762, 50, 10486, 628, 198, 198, 12417, 10044, 325, 7, 7908, 8, 198 ]
3.205882
34
from . import *
[ 6738, 764, 1330, 1635, 198 ]
3.2
5
from .tfe_client import Client
[ 6738, 764, 83, 5036, 62, 16366, 1330, 20985, 198 ]
3.444444
9
# coding: utf-8 from __future__ import absolute_import from datetime import date, datetime # noqa: F401 from typing import List, Dict # noqa: F401 from swagger_server.models.base_model_ import Model from swagger_server import util class Protein(Model): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ def __init__(self, antibody_name: str=None, target_genes: List[str]=None, validation_status: str=None, company: str=None, catalog_number: str=None): # noqa: E501 """Protein - a model defined in Swagger :param antibody_name: The antibody_name of this Protein. # noqa: E501 :type antibody_name: str :param target_genes: The target_genes of this Protein. # noqa: E501 :type target_genes: List[str] :param validation_status: The validation_status of this Protein. # noqa: E501 :type validation_status: str :param company: The company of this Protein. # noqa: E501 :type company: str :param catalog_number: The catalog_number of this Protein. # noqa: E501 :type catalog_number: str """ self.swagger_types = { 'antibody_name': str, 'target_genes': List[str], 'validation_status': str, 'company': str, 'catalog_number': str } self.attribute_map = { 'antibody_name': 'antibody_name', 'target_genes': 'target_genes', 'validation_status': 'validation_status', 'company': 'company', 'catalog_number': 'catalog_number' } self._antibody_name = antibody_name self._target_genes = target_genes self._validation_status = validation_status self._company = company self._catalog_number = catalog_number @classmethod def from_dict(cls, dikt) -> 'Protein': """Returns the dict as a model :param dikt: A dict. :type: dict :return: The protein of this Protein. # noqa: E501 :rtype: Protein """ return util.deserialize_model(dikt, cls) @property def antibody_name(self) -> str: """Gets the antibody_name of this Protein. :return: The antibody_name of this Protein. :rtype: str """ return self._antibody_name @antibody_name.setter def antibody_name(self, antibody_name: str): """Sets the antibody_name of this Protein. :param antibody_name: The antibody_name of this Protein. :type antibody_name: str """ self._antibody_name = antibody_name @property def target_genes(self) -> List[str]: """Gets the target_genes of this Protein. :return: The target_genes of this Protein. :rtype: List[str] """ return self._target_genes @target_genes.setter def target_genes(self, target_genes: List[str]): """Sets the target_genes of this Protein. :param target_genes: The target_genes of this Protein. :type target_genes: List[str] """ self._target_genes = target_genes @property def validation_status(self) -> str: """Gets the validation_status of this Protein. :return: The validation_status of this Protein. :rtype: str """ return self._validation_status @validation_status.setter def validation_status(self, validation_status: str): """Sets the validation_status of this Protein. :param validation_status: The validation_status of this Protein. :type validation_status: str """ self._validation_status = validation_status @property def company(self) -> str: """Gets the company of this Protein. :return: The company of this Protein. :rtype: str """ return self._company @company.setter def company(self, company: str): """Sets the company of this Protein. :param company: The company of this Protein. :type company: str """ self._company = company @property def catalog_number(self) -> str: """Gets the catalog_number of this Protein. :return: The catalog_number of this Protein. :rtype: str """ return self._catalog_number @catalog_number.setter def catalog_number(self, catalog_number: str): """Sets the catalog_number of this Protein. :param catalog_number: The catalog_number of this Protein. :type catalog_number: str """ self._catalog_number = catalog_number
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 6738, 4818, 8079, 1330, 3128, 11, 4818, 8079, 220, 1303, 645, 20402, 25, 376, 21844, 198, 198, 6738, 19720, 1330, 7343, 11, 360, 713, 220...
2.403374
1,956
#!/usr/bin/env python ''' Synfire chains -------------- M. Diesmann et al. (1999). Stable propagation of synchronous spiking in cortical neural networks. Nature 402, 529-533. ''' from angela2 import * duration = 100*ms # Neuron model parameters Vr = -70*mV Vt = -55*mV taum = 10*ms taupsp = 0.325*ms weight = 4.86*mV # Neuron model eqs = Equations(''' dV/dt = (-(V-Vr)+x)*(1./taum) : volt dx/dt = (-x+y)*(1./taupsp) : volt dy/dt = -y*(1./taupsp)+25.27*mV/ms+ (39.24*mV/ms**0.5)*xi : volt ''') # Neuron groups n_groups = 10 group_size = 100 P = NeuronGroup(N=n_groups*group_size, model=eqs, threshold='V>Vt', reset='V=Vr', refractory=1*ms, method='euler') Pinput = SpikeGeneratorGroup(85, np.arange(85), np.random.randn(85)*1*ms + 50*ms) # The network structure S = Synapses(P, P, on_pre='y+=weight') S.connect(j='k for k in range((int(i/group_size)+1)*group_size, (int(i/group_size)+2)*group_size) ' 'if i<N_pre-group_size') Sinput = Synapses(Pinput, P[:group_size], on_pre='y+=weight') Sinput.connect() # Record the spikes Mgp = SpikeMonitor(P) Minput = SpikeMonitor(Pinput) # Setup the network, and run it P.V = 'Vr + rand() * (Vt - Vr)' run(duration) plot(Mgp.t/ms, 1.0*Mgp.i/group_size, '.') plot([0, duration/ms], np.arange(n_groups).repeat(2).reshape(-1, 2).T, 'k-') ylabel('group number') yticks(np.arange(n_groups)) xlabel('time (ms)') show()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 7061, 6, 198, 29934, 6495, 14659, 198, 26171, 198, 44, 13, 360, 444, 9038, 2123, 435, 13, 357, 18946, 737, 520, 540, 43594, 286, 18305, 516, 599, 14132, 287, 35001, 198, 710, 1523, 7...
2.154423
667
#87671-Joao Freitas 87693-Pedro Soares Grupo 15 # -*- coding: utf-8 -*- """ Created on Mon Oct 16 20:31:54 2017 @author: mlopes """ import numpy as np import random from tempfile import TemporaryFile outfile = TemporaryFile()
[ 2, 5774, 46250, 12, 9908, 5488, 4848, 21416, 10083, 48528, 12, 43468, 305, 1406, 3565, 25665, 7501, 1315, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41972, 319, 2892, 2556, 1467, 1160, 25, 3132, ...
2.674157
89
from .. import Interpreter, adapter from ..interface import Block from typing import Optional import random
[ 6738, 11485, 1330, 4225, 3866, 353, 11, 21302, 198, 6738, 11485, 39994, 1330, 9726, 198, 6738, 19720, 1330, 32233, 198, 11748, 4738, 198 ]
4.695652
23
"""Model definition.""" from dataclasses import dataclass from typing import Any, Optional from dcorm.alias import Alias from dcorm.column import Column from dcorm.database import Database from dcorm.engine import Engine from dcorm.path import Path __all__ = ['ModelType', 'Model'] class ModelType(type): """Metaclass for models.""" @property def __schema__(cls) -> str: """Returns the database schema.""" if (database := cls.__database__) is not None: return database return None @property class Model(metaclass=ModelType): """Model base class to inherit actual dataclass models from.""" __database__ = None def __init_subclass__( cls, *, database: Optional[Database] = None, table_name: Optional[str] = None ): """Initialize the model with meta data.""" dataclass(cls) if database is not None: cls.__database__ = database cls.__table_name__ = table_name or cls.__name__.lower() # pylint: disable-next=E1101 for attribute, field in cls.__dataclass_fields__.items(): setattr(cls, attribute, Column(cls, field)) def __setattr__(self, attribute: str, value: Any) -> None: """Hook to set special field values.""" try: # pylint: disable-next=E1101 field = self.__dataclass_fields__[attribute] except KeyError: # Not a field. return super().__setattr__(attribute, value) if (converter := field.metadata.get('converter')): value = converter(value) elif not isinstance(value, field.type): value = field.type(value) return super().__setattr__(attribute, value) @classmethod def alias(cls, name: Optional[str] = None) -> Alias: """Creates a model alias.""" return Alias(cls, name)
[ 37811, 17633, 6770, 526, 15931, 198, 198, 6738, 4818, 330, 28958, 1330, 4818, 330, 31172, 198, 6738, 19720, 1330, 4377, 11, 32233, 198, 198, 6738, 30736, 579, 13, 26011, 1330, 978, 4448, 198, 6738, 30736, 579, 13, 28665, 1330, 29201, 19...
2.420253
790
from __future__ import print_function import sys sys.path.append(r"../..") import sys from pytestqt import qtbot from lxml import etree from PyQt5.QtWidgets import QWidget, QPlainTextEdit from pymdwizard.gui import datacred
[ 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 198, 11748, 25064, 198, 198, 17597, 13, 6978, 13, 33295, 7, 81, 1, 40720, 492, 4943, 198, 198, 11748, 25064, 198, 6738, 12972, 9288, 39568, 1330, 10662, 83, 13645, 198, 6738, 300, 19...
2.783133
83
""" Init segments (phases) """ from compendium.initsegment.checksegment import CheckSegment from compendium.initsegment.folderstructure import FolderStructureSegment from compendium.initsegment.github import GithubSegment from compendium.initsegment.pyenv import PyEnvSegment SEGMENTS = [ GithubSegment, FolderStructureSegment, PyEnvSegment, CheckSegment, ]
[ 37811, 198, 31768, 17894, 357, 746, 1386, 8, 198, 37811, 198, 198, 6738, 552, 49811, 13, 15003, 325, 5154, 13, 9122, 325, 5154, 1330, 6822, 41030, 434, 198, 6738, 552, 49811, 13, 15003, 325, 5154, 13, 43551, 301, 5620, 1330, 48107, 12...
2.808511
141
import unittest import tempfile import os import logging import filecmp import cfg import utils from kneaddata import run from kneaddata import utilities class TestHumann2Functions(unittest.TestCase): """ Test the functions found in kneaddata """ def test_read_in_file_n_lines(self): """ Test the function that reads in a file n lines at a time """ # Get the sequences from the file, removing end-lines and the fastq "@" character sequences=[lines[0].rstrip()[1:] for lines in utilities.read_file_n_lines(cfg.merge_files[0], 4)] self.assertEqual(sorted(sequences), sorted(cfg.merge_files_1_sequences)) def test_intersect_fastq(self): """ Test the intersect_fastq function """ file_handle, temp_output_file=tempfile.mkstemp(prefix="kneaddata_test") run.intersect_fastq(cfg.merge_files, temp_output_file) # read in the sequences from the fastq output file # Get the sequences from the file, removing end-lines and the fastq "@" character sequences=[lines[0].rstrip()[1:] for lines in utilities.read_file_n_lines(temp_output_file, 4)] # remove the temp output file utils.remove_temp_file(temp_output_file) self.assertEqual(sorted(sequences), sorted(cfg.merge_files_sequences_intersect)) def test_count_reads_in_fastq_file(self): """ Test the count reads in fastq file function """ read_count=utilities.count_reads_in_fastq_file(cfg.merge_files[0],False) self.assertEqual(read_count, len(cfg.merge_files_1_sequences)) def test_is_file_fastq(self): """ Test the is file fastq function and also the get file format function """ self.assertTrue(utilities.is_file_fastq(cfg.merge_files[0])) def test_find_database_index_folder(self): """ Test the find database index function with a folder as input """ db_index=utilities.find_database_index(cfg.bowtie2_db_folder, "bowtie2") self.assertEqual(db_index, cfg.bowtie2_db_index) def test_find_database_index_file(self): """ Test the find database index function with a file as input """ db_index=utilities.find_database_index(cfg.bowtie2_db_file, "bowtie2") self.assertEqual(db_index, cfg.bowtie2_db_index) def test_find_database_index_index(self): """ Test the find database index function with an index as input """ db_index=utilities.find_database_index(cfg.bowtie2_db_index, "bowtie2") self.assertEqual(db_index, cfg.bowtie2_db_index) def test_sam_to_fastq(self): """ Test the sam to fastq function Test sam file contains one read with two mappings (to test it is only written once to the fastq output file) """ file_handle, temp_output_file=tempfile.mkstemp(prefix="kneaddata_test") utilities.sam_to_fastq(cfg.file_sam, temp_output_file) self.assertTrue(filecmp.cmp(temp_output_file, cfg.fastq_file_matches_sam_and_bam, shallow=False)) utils.remove_temp_file(temp_output_file)
[ 11748, 555, 715, 395, 198, 11748, 20218, 7753, 198, 11748, 28686, 198, 11748, 18931, 198, 11748, 2393, 48991, 198, 198, 11748, 30218, 70, 198, 11748, 3384, 4487, 198, 198, 6738, 638, 1329, 7890, 1330, 1057, 198, 6738, 638, 1329, 7890, 1...
2.173804
1,588
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities __all__ = ['CertificateArgs', 'Certificate'] @pulumi.input_type warnings.warn("""Certificate is not yet supported by AWS Native, so its creation will currently fail. Please use the classic AWS provider, if possible.""", DeprecationWarning)
[ 2, 19617, 28, 40477, 12, 23, 198, 2, 17202, 39410, 25, 428, 2393, 373, 7560, 416, 262, 21624, 12994, 26144, 35986, 13, 17202, 198, 2, 17202, 2141, 407, 4370, 416, 1021, 4556, 345, 821, 1728, 345, 760, 644, 345, 389, 1804, 0, 17202, ...
3.797297
148
from phlm import *
[ 6738, 872, 75, 76, 1330, 1635, 198 ]
2.714286
7
from flask import Flask, jsonify, abort, make_response from flask_restful import Api, Resource, reqparse, marshal from flasgger import swag_from from flask_jwt_extended import jwt_required, get_jwt_identity from app import db from models import models from resources.fields import role_fields
[ 6738, 42903, 1330, 46947, 11, 33918, 1958, 11, 15614, 11, 787, 62, 26209, 198, 6738, 42903, 62, 2118, 913, 1330, 5949, 72, 11, 20857, 11, 43089, 29572, 11, 22397, 282, 198, 6738, 781, 292, 26679, 1330, 1509, 363, 62, 6738, 198, 6738, ...
3.511905
84
from RDRPOSTagger.InitialTagger.InitialTagger import initializeCorpus, initializeSentence from RDRPOSTagger.SCRDRlearner.Object import FWObject from RDRPOSTagger.SCRDRlearner.SCRDRTree import SCRDRTree from RDRPOSTagger.SCRDRlearner.SCRDRTreeLearner import SCRDRTreeLearner from RDRPOSTagger.Utility.Config import NUMBER_OF_PROCESSES, THRESHOLD from RDRPOSTagger.Utility.Utils import getWordTag, getRawText, readDictionary from RDRPOSTagger.Utility.LexiconCreator import createLexicon from multiprocessing import Pool class RDRPOSTagger(SCRDRTree): """ RDRPOSTagger for a particular language """ french_tagger = RDRPOSTagger() french_tagger.constructSCRDRtreeFromRDRfile("../Models/POS/French.RDR") frenchDICT = readDictionary("../Models/POS/French.DICT") english_tagger = RDRPOSTagger() english_tagger.constructSCRDRtreeFromRDRfile("../Models/POS/English.RDR") englishDICT = readDictionary("../Models/POS/English.DICT")
[ 6738, 371, 7707, 32782, 7928, 13, 24243, 51, 7928, 13, 24243, 51, 7928, 1330, 41216, 45680, 385, 11, 41216, 31837, 594, 198, 6738, 371, 7707, 32782, 7928, 13, 6173, 49, 7707, 3238, 1008, 13, 10267, 1330, 48849, 10267, 198, 6738, 371, ...
2.940252
318
#!/usr/bin/env python # # Copyright (C) 2016 The Android Open Source Project # # 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. # """Packages the platform's RenderScript for the NDK.""" import os import shutil import site import subprocess import sys site.addsitedir(os.path.join(os.path.dirname(__file__), '../lib')) import build_support # pylint: disable=import-error if __name__ == '__main__': build_support.run(main)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 198, 2, 15069, 357, 34, 8, 1584, 383, 5565, 4946, 8090, 4935, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, ...
3.395604
273
# # Copyright (c) 2017 Juniper Networks, Inc. All rights reserved. # """ MESOS CNI Server """ # Standard library import import bottle import json # Application library import from cfgm_common.rest import LinkObject from mesos_cni import MESOSCniDataObject from vnc_api.vnc_api import * # end # end # Public Methods # end get_args # end get_ip_addr # end get_port # end get_pipe_start_app # end add_cni_info # end del_cni_info # end get_cni_info_all # purge expired cni # end cleanup_http_get # end show_config # end show_stats # end homepage_http_get # start_server # end class MesosServer
[ 2, 198, 2, 15069, 357, 66, 8, 2177, 7653, 9346, 27862, 11, 3457, 13, 1439, 2489, 10395, 13, 198, 2, 198, 198, 37811, 198, 44, 1546, 2640, 327, 22125, 9652, 198, 37811, 198, 198, 2, 8997, 5888, 1330, 198, 11748, 9294, 198, 11748, 3...
2.602362
254
"""A helper for remembering useful shell commands.""" import os from subprocess import check_output, CalledProcessError from .cmdmanager import CmdManager from .dbitem import DBItem from .main import main, __version__ # Inspect git version if we're in a git repo __dev_version__ = '' thisdir = os.path.dirname(os.path.realpath(__file__)) if os.path.isdir(os.path.join(thisdir, os.pardir, '.git')): try: ver = check_output('git describe --tags'.split()) except CalledProcessError: ver = '' # don't care if ver: ver = ver.decode('utf-8').strip() __dev_version__ = ver __all__ = ('DBItem', 'CmdManager', 'main', '__version__', '__dev_version__')
[ 37811, 32, 31904, 329, 24865, 4465, 7582, 9729, 526, 15931, 198, 11748, 28686, 198, 6738, 850, 14681, 1330, 2198, 62, 22915, 11, 34099, 18709, 12331, 198, 6738, 764, 28758, 37153, 1330, 327, 9132, 13511, 198, 6738, 764, 67, 2545, 368, 1...
2.790323
248