hexsha
stringlengths
40
40
size
int64
6
782k
ext
stringclasses
7 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
237
max_stars_repo_name
stringlengths
6
72
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
list
max_stars_count
int64
1
53k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
184
max_issues_repo_name
stringlengths
6
72
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
list
max_issues_count
int64
1
27.1k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
184
max_forks_repo_name
stringlengths
6
72
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
list
max_forks_count
int64
1
12.2k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
6
782k
avg_line_length
float64
2.75
664k
max_line_length
int64
5
782k
alphanum_fraction
float64
0
1
b03b85560632c7d285f2936c1fc7df527781f42d
2,100
py
Python
scripts/scraper.py
jhKessler/Tagesschau-Analysis
40490b13fa2f3e5cf3bd4b5f4f46b5bf72ab9899
[ "MIT" ]
null
null
null
scripts/scraper.py
jhKessler/Tagesschau-Analysis
40490b13fa2f3e5cf3bd4b5f4f46b5bf72ab9899
[ "MIT" ]
null
null
null
scripts/scraper.py
jhKessler/Tagesschau-Analysis
40490b13fa2f3e5cf3bd4b5f4f46b5bf72ab9899
[ "MIT" ]
null
null
null
# # scraper for getting the data from article descriptions # import time import datetime import requests import pandas as pd from tqdm import tqdm from bs4 import BeautifulSoup DATE_FORMAT = "%d/%m/%Y" ARCHIVE_URL = "https://www.tagesschau.de/multimedia/video/videoarchiv2~_date-" SECOND_DELAY = 1 # dates first_description = datetime.date(year=2013, month=4, day=22) today = datetime.date.today() current_date = first_description # list for storing articles all_articles = [] def update_progress_bar(pbar: tqdm, current_date: datetime.datetime) -> None: """Update Progress bar""" pbar.update(1) estimated_time = round(((today - current_date).days * (SECOND_DELAY+0.3)) / 60) pbar.set_description(f"Scraping articles: Date:{current_date.strftime(DATE_FORMAT)}, Articles: {len(all_articles)}, Estimated time left: {round(estimated_time, 2)} min") # init progressbar total_days = (today - first_description).days print(total_days) progress_bar = tqdm(total=total_days) update_progress_bar(progress_bar, current_date) # loop over days while current_date <= today: date_string = current_date.strftime("%Y%m%d") # format url to right form url_string = f"{ARCHIVE_URL}{date_string}.html" # request html and scrape it for the datapoints response = requests.get(url_string).text soup = BeautifulSoup(response, 'html.parser') # save articles article_teasers = list(soup.findAll(class_="teasertext")) titles = soup.findAll(class_="headline") dates_and_times = list(soup.findAll(class_="dachzeile")) for title, date_and_time, article, in zip(titles, dates_and_times, article_teasers): all_articles.append([current_date.strftime(DATE_FORMAT), article.text, title.text, date_and_time.text]) # go to next day current_date = current_date + datetime.timedelta(days=1) # sleep time.sleep(SECOND_DELAY) update_progress_bar(progress_bar, current_date) # format data article_df = pd.DataFrame(all_articles, columns=["date", "article", "title", "time_text"]) article_df.to_excel("data/raw.xlsx", index=False)
32.307692
173
0.739524
afd6664432eb837b50bee769a174cb19c16d821f
329
py
Python
server/bumf/api/views/auth.py
bumfiness/bumf
71c404c0a8f804b8f0e127df3de6d8916db4c660
[ "Apache-2.0" ]
6
2017-01-07T17:59:46.000Z
2017-02-10T13:19:46.000Z
server/bumf/api/views/auth.py
rixx/bumf
71c404c0a8f804b8f0e127df3de6d8916db4c660
[ "Apache-2.0" ]
null
null
null
server/bumf/api/views/auth.py
rixx/bumf
71c404c0a8f804b8f0e127df3de6d8916db4c660
[ "Apache-2.0" ]
null
null
null
from rest_framework import mixins, permissions, viewsets from bumf.api.serializers import UserSerializer from bumf.core.models import User class UserView(mixins.CreateModelMixin, viewsets.GenericViewSet): queryset = User.objects.none() permission_classes = [permissions.AllowAny] serializer_class = UserSerializer
29.909091
65
0.808511
a566fd8c43c862cab7e4250aec18c8b8495f8ba7
84
py
Python
Python/if-else.py
bunny8469/Hello-World
722b5961cbcd9b2c2eec2cb6aa700eaa451e008b
[ "MIT" ]
133
2021-01-15T16:29:40.000Z
2022-03-21T16:35:42.000Z
Python/if-else.py
bunny8469/Hello-World
722b5961cbcd9b2c2eec2cb6aa700eaa451e008b
[ "MIT" ]
117
2021-01-17T08:54:22.000Z
2022-01-17T16:38:11.000Z
Python/if-else.py
bunny8469/Hello-World
722b5961cbcd9b2c2eec2cb6aa700eaa451e008b
[ "MIT" ]
146
2021-01-15T12:57:19.000Z
2022-03-15T20:10:23.000Z
t=int(input()) if t>=1: print("bigger than 1") else: print("smaller than 1")
16.8
27
0.595238
a57d7dab18bdfa799114ea56df3d758834aa2120
407
py
Python
setup.py
raicheff/flask-spf
abfeb35bde6235be80aacdfdcfce71f40421ed91
[ "MIT" ]
null
null
null
setup.py
raicheff/flask-spf
abfeb35bde6235be80aacdfdcfce71f40421ed91
[ "MIT" ]
null
null
null
setup.py
raicheff/flask-spf
abfeb35bde6235be80aacdfdcfce71f40421ed91
[ "MIT" ]
null
null
null
# # Flask-SPF # # Copyright (C) 2017 Boris Raicheff # All rights reserved # from setuptools import find_packages, setup setup( name='Flask-SPF', version='0.1.0', description='Flask-SPF', author='Boris Raicheff', author_email='[email protected]', url='https://github.com/raicheff/flask-spf', install_requires=('flask', 'beautifulsoup4'), py_modules=('flask_spf',), ) # EOF
16.28
49
0.660934
3cef0e52a2048eb5b25bb85af93f0adab276a41b
631
py
Python
finbyz_dashboard/finbyz_dashboard/dashboard_overrides/install_fixtures.py
finbyz/finbyz_dashboard
9c58ab7bccf589bc010d0e5bf95b20cadd4d71f0
[ "MIT" ]
1
2021-11-19T05:27:11.000Z
2021-11-19T05:27:11.000Z
finbyz_dashboard/finbyz_dashboard/dashboard_overrides/install_fixtures.py
finbyz/finbyz_dashboard
9c58ab7bccf589bc010d0e5bf95b20cadd4d71f0
[ "MIT" ]
null
null
null
finbyz_dashboard/finbyz_dashboard/dashboard_overrides/install_fixtures.py
finbyz/finbyz_dashboard
9c58ab7bccf589bc010d0e5bf95b20cadd4d71f0
[ "MIT" ]
2
2021-08-21T10:41:38.000Z
2021-11-19T05:27:13.000Z
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from frappe import _ from frappe.desk.doctype.global_search_settings.global_search_settings import update_global_search_doctypes # Finbyz CHanges Import from finbyz_dashboard.finbyz_dashboard.dashboard_overrides.dashboard_utils import sync_dashboards def install(): update_genders() update_salutations() update_global_search_doctypes() setup_email_linking() # Finbyz CHanges START sync_dashboards() # Finbyz CHanges END add_unsubscribe()
30.047619
107
0.835182
055dbd21f9914f317100d134cb4bb20c0c841ad9
14,731
py
Python
official/cv/fastscnn/infer/sdk/main.py
leelige/mindspore
5199e05ba3888963473f2b07da3f7bca5b9ef6dc
[ "Apache-2.0" ]
77
2021-10-15T08:32:37.000Z
2022-03-30T13:09:11.000Z
official/cv/fastscnn/infer/sdk/main.py
leelige/mindspore
5199e05ba3888963473f2b07da3f7bca5b9ef6dc
[ "Apache-2.0" ]
3
2021-10-30T14:44:57.000Z
2022-02-14T06:57:57.000Z
official/cv/fastscnn/infer/sdk/main.py
leelige/mindspore
5199e05ba3888963473f2b07da3f7bca5b9ef6dc
[ "Apache-2.0" ]
24
2021-10-15T08:32:45.000Z
2022-03-24T18:45:20.000Z
''' The scripts to execute sdk infer ''' # Copyright 2021 Huawei Technologies Co., Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ import argparse import os import time import numpy as np import PIL.Image as Image from tabulate import tabulate import MxpiDataType_pb2 as MxpiDataType from StreamManagerApi import StreamManagerApi, InProtobufVector, \ MxProtobufIn, StringVector def parse_args(): """set and check parameters.""" parser = argparse.ArgumentParser(description="FastSCNN process") parser.add_argument("--pipeline", type=str, default=None, help="SDK infer pipeline") parser.add_argument("--image_path", type=str, default=None, help="root path of image") parser.add_argument('--image_width', default=768, type=int, help='image width') parser.add_argument('--image_height', default=768, type=int, help='image height') parser.add_argument('--save_mask', default=1, type=int, help='0 for False, 1 for True') parser.add_argument('--mask_result_path', default='./mask_result', type=str, help='the folder to save the semantic mask images') args_opt = parser.parse_args() return args_opt def send_source_data(appsrc_id, tensor, stream_name, stream_manager): """ Construct the input of the stream, send inputs data to a specified stream based on streamName. Returns: bool: send data success or not """ tensor_package_list = MxpiDataType.MxpiTensorPackageList() tensor_package = tensor_package_list.tensorPackageVec.add() array_bytes = tensor.tobytes() tensor_vec = tensor_package.tensorVec.add() tensor_vec.deviceId = 0 tensor_vec.memType = 0 for i in tensor.shape: tensor_vec.tensorShape.append(i) tensor_vec.dataStr = array_bytes tensor_vec.tensorDataSize = len(array_bytes) key = "appsrc{}".format(appsrc_id).encode('utf-8') protobuf_vec = InProtobufVector() protobuf = MxProtobufIn() protobuf.key = key protobuf.type = b'MxTools.MxpiTensorPackageList' protobuf.protobuf = tensor_package_list.SerializeToString() protobuf_vec.push_back(protobuf) ret = stream_manager.SendProtobuf(stream_name, appsrc_id, protobuf_vec) if ret < 0: print("Failed to send data to stream.") return False return True cityspallete = [ 128, 64, 128, 244, 35, 232, 70, 70, 70, 102, 102, 156, 190, 153, 153, 153, 153, 153, 250, 170, 30, 220, 220, 0, 107, 142, 35, 152, 251, 152, 0, 130, 180, 220, 20, 60, 255, 0, 0, 0, 0, 142, 0, 0, 70, 0, 60, 100, 0, 80, 100, 0, 0, 230, 119, 11, 32, ] classes = ('road', 'sidewalk', 'building', 'wall', 'fence', 'pole', 'traffic light', 'traffic sign', 'vegetation', 'terrain', 'sky', 'person', 'rider', 'car', 'truck', 'bus', 'train', 'motorcycle', 'bicycle') valid_classes = [7, 8, 11, 12, 13, 17, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 31, 32, 33] _key = np.array([-1, -1, -1, -1, -1, -1, -1, -1, 0, 1, -1, -1, 2, 3, 4, -1, -1, -1, 5, -1, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, -1, -1, 16, 17, 18]) _mapping = np.array(range(-1, len(_key) - 1)).astype('int32') def _get_city_pairs(folder, split='train'): '''_get_city_pairs''' def get_path_pairs(img_folder, mask_folder): img_paths = [] mask_paths = [] for root, _, files in os.walk(img_folder): for filename in files: if filename.startswith('._'): continue if filename.endswith('.png'): imgpath = os.path.join(root, filename) foldername = os.path.basename(os.path.dirname(imgpath)) maskname = filename.replace('leftImg8bit', 'gtFine_labelIds') maskpath = os.path.join(mask_folder, foldername, maskname) if os.path.isfile(imgpath) and os.path.isfile(maskpath): img_paths.append(imgpath) mask_paths.append(maskpath) else: print('cannot find the mask or image:', imgpath, maskpath) print('Found {} images in the folder {}'.format(len(img_paths), img_folder)) return img_paths, mask_paths if split in ('train', 'val'): img_folder = os.path.join(folder, 'leftImg8bit' + os.sep + split) mask_folder = os.path.join(folder, 'gtFine' + os.sep + split) img_paths, mask_paths = get_path_pairs(img_folder, mask_folder) return img_paths, mask_paths assert split == 'trainval' print('trainval set') train_img_folder = os.path.join(folder, 'leftImg8bit' + os.sep + 'train') train_mask_folder = os.path.join(folder, 'gtFine' + os.sep + 'train') val_img_folder = os.path.join(folder, 'leftImg8bit' + os.sep + 'val') val_mask_folder = os.path.join(folder, 'gtFine' + os.sep + 'val') train_img_paths, train_mask_paths = get_path_pairs(train_img_folder, train_mask_folder) val_img_paths, val_mask_paths = get_path_pairs(val_img_folder, val_mask_folder) img_paths = train_img_paths + val_img_paths mask_paths = train_mask_paths + val_mask_paths return img_paths, mask_paths def _val_sync_transform(outsize, img, mask): '''_val_sync_transform''' short_size = min(outsize) w, h = img.size if w > h: oh = short_size ow = int(1.0 * w * oh / h) else: ow = short_size oh = int(1.0 * h * ow / w) img = img.resize((ow, oh), Image.BILINEAR) mask = mask.resize((ow, oh), Image.NEAREST) # center crop w, h = img.size x1 = int(round((w - outsize[1]) / 2.)) y1 = int(round((h - outsize[0]) / 2.)) img = img.crop((x1, y1, x1 + outsize[1], y1 + outsize[0])) mask = mask.crop((x1, y1, x1 + outsize[1], y1 + outsize[0])) # final transform img, mask = np.array(img), _mask_transform(mask) return img, mask def _class_to_index(mask): # assert the value values = np.unique(mask) for value in values: assert value in _mapping index = np.digitize(mask.ravel(), _mapping, right=True) return _key[index].reshape(mask.shape) def _mask_transform(mask): target = _class_to_index(np.array(mask).astype('int32')) return np.array(target).astype('int32') class SegmentationMetric(): """Computes pixAcc and mIoU metric scores """ def __init__(self, nclass): super(SegmentationMetric, self).__init__() self.nclass = nclass self.reset() def update(self, preds, labels): """Updates the internal evaluation result. Parameters ---------- labels : 'NumpyArray' or list of `NumpyArray` The labels of the data. preds : 'NumpyArray' or list of `NumpyArray` Predicted values. """ def evaluate_worker(self, pred, label): correct, labeled = batch_pix_accuracy(pred, label) inter, union = batch_intersection_union(pred, label, self.nclass) self.total_correct += correct self.total_label += labeled self.total_inter += inter self.total_union += union evaluate_worker(self, preds, labels) def get(self, return_category_iou=False): """Gets the current evaluation result. Returns ------- metrics : tuple of float pixAcc and mIoU """ # remove np.spacing(1) pixAcc = 1.0 * self.total_correct / (2.220446049250313e-16 + self.total_label) IoU = 1.0 * self.total_inter / (2.220446049250313e-16 + self.total_union) mIoU = IoU.mean().item() if return_category_iou: return pixAcc, mIoU, IoU return pixAcc, mIoU def reset(self): """Resets the internal evaluation result to initial state.""" self.total_inter = np.zeros(self.nclass) self.total_union = np.zeros(self.nclass) self.total_correct = 0 self.total_label = 0 def batch_pix_accuracy(output, target): """PixAcc""" # inputs are numpy array, output 4D NCHW where 'C' means label classes, target 3D NHW predict = np.argmax(output.astype(np.int64), 1) + 1 target = target.astype(np.int64) + 1 pixel_labeled = (target > 0).sum() pixel_correct = ((predict == target) * (target > 0)).sum() assert pixel_correct <= pixel_labeled, "Correct area should be smaller than Labeled" return pixel_correct, pixel_labeled def batch_intersection_union(output, target, nclass): """mIoU""" # inputs are numpy array, output 4D, target 3D mini = 1 maxi = nclass nbins = nclass predict = np.argmax(output.astype(np.float32), 1) + 1 target = target.astype(np.float32) + 1 predict = predict.astype(np.float32) * (target > 0).astype(np.float32) intersection = predict * (predict == target).astype(np.float32) # areas of intersection and union # element 0 in intersection occur the main difference from np.bincount. set boundary to -1 is necessary. area_inter, _ = np.histogram(intersection, bins=nbins, range=(mini, maxi)) area_pred, _ = np.histogram(predict, bins=nbins, range=(mini, maxi)) area_lab, _ = np.histogram(target, bins=nbins, range=(mini, maxi)) area_union = area_pred + area_lab - area_inter assert (area_inter > area_union).sum() == 0, "Intersection area should be smaller than Union area" return area_inter.astype(np.float32), area_union.astype(np.float32) def main(): """ read pipeline and do infer """ args = parse_args() # init stream manager stream_manager_api = StreamManagerApi() ret = stream_manager_api.InitManager() if ret != 0: print("Failed to init Stream manager, ret=%s" % str(ret)) return # create streams by pipeline config file with open(os.path.realpath(args.pipeline), 'rb') as f: pipeline_str = f.read() ret = stream_manager_api.CreateMultipleStreams(pipeline_str) if ret != 0: print("Failed to create Stream, ret=%s" % str(ret)) return stream_name = b'fastscnn' infer_total_time = 0 assert os.path.exists(args.image_path), "Please put dataset in " + str(args.image_path) images, mask_paths = _get_city_pairs(args.image_path, 'val') assert len(images) == len(mask_paths) if not images: raise RuntimeError("Found 0 images in subfolders of:" + args.image_path + "\n") if args.save_mask and not os.path.exists(args.mask_result_path): os.makedirs(args.mask_result_path) metric = SegmentationMetric(19) metric.reset() for index in range(len(images)): image_name = images[index].split(os.sep)[-1].split(".")[0] # get the name of image file print("Processing ---> ", image_name) img = Image.open(images[index]).convert('RGB') mask = Image.open(mask_paths[index]) img, mask = _val_sync_transform((args.image_height, args.image_width), img, mask) img = img.astype(np.float32) mask = mask.astype(np.int32) mean = [0.485, 0.456, 0.406] std = [0.229, 0.224, 0.225] img = img.transpose((2, 0, 1))#HWC->CHW for channel, _ in enumerate(img): # Normalization img[channel] /= 255 img[channel] -= mean[channel] img[channel] /= std[channel] img = np.expand_dims(img, 0)#NCHW mask = np.expand_dims(mask, 0)#NHW if not send_source_data(0, img, stream_name, stream_manager_api): return # Obtain the inference result by specifying streamName and uniqueId. key_vec = StringVector() key_vec.push_back(b'modelInfer') start_time = time.time() infer_result = stream_manager_api.GetProtobuf(stream_name, 0, key_vec) infer_total_time += time.time() - start_time if infer_result.size() == 0: print("inferResult is null") return if infer_result[0].errorCode != 0: print("GetProtobuf error. errorCode=%d" % (infer_result[0].errorCode)) return result = MxpiDataType.MxpiTensorPackageList() result.ParseFromString(infer_result[0].messageBuf) res = np.frombuffer(result.tensorPackageVec[0].tensorVec[0].dataStr, dtype='<f4') mask_image = res.reshape(1, 19, args.image_height, args.image_width) metric.update(mask_image, mask) pixAcc, mIoU = metric.get() print("[EVAL] Sample: {:d}, pixAcc: {:.3f}, mIoU: {:.3f}".format(index + 1, pixAcc * 100, mIoU * 100)) if args.save_mask: output = np.argmax(mask_image[0], axis=0) out_img = Image.fromarray(output.astype('uint8')) out_img.putpalette(cityspallete) outname = str(image_name) + '.png' out_img.save(os.path.join(args.mask_result_path, outname)) pixAcc, mIoU, category_iou = metric.get(return_category_iou=True) print('End validation pixAcc: {:.3f}, mIoU: {:.3f}'.format(pixAcc * 100, mIoU * 100)) txtName = os.path.join(args.mask_result_path, "eval_results.txt") with open(txtName, "w") as f: string = 'validation pixAcc:' + str(pixAcc * 100) + ', mIoU:' + str(mIoU * 100) f.write(string) f.write('\n') headers = ['class id', 'class name', 'iou'] table = [] for i, cls_name in enumerate(classes): table.append([cls_name, category_iou[i]]) string = 'class name: ' + cls_name + ' iou: ' + str(category_iou[i]) + '\n' f.write(string) print('Category iou: \n {}'.format(tabulate(table, headers, \ tablefmt='grid', showindex="always", numalign='center', stralign='center'))) print("Testing finished....") print("=======================================") print("The total time of inference is {} s".format(infer_total_time)) print("=======================================") # destroy streams stream_manager_api.DestroyAllStreams() if __name__ == '__main__': main()
39.282667
110
0.621003
f93f27538f5cdd1b46073b7e5bfef848372aeb0c
6,498
py
Python
fahrplanauskunft-vvs.py
wienand/fahrplanauskunft-vvs
ca595e2f51af1d00ea8db463d9fc3390c51c5741
[ "MIT" ]
1
2018-11-27T15:31:40.000Z
2018-11-27T15:31:40.000Z
fahrplanauskunft-vvs.py
wienand/fahrplanauskunft-vvs
ca595e2f51af1d00ea8db463d9fc3390c51c5741
[ "MIT" ]
null
null
null
fahrplanauskunft-vvs.py
wienand/fahrplanauskunft-vvs
ca595e2f51af1d00ea8db463d9fc3390c51c5741
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- import collections import datetime import json import os import urllib from flask import Flask, request port = int(os.environ.get("PORT", 5000)) runsAtHeroku = port != 5000 app = Flask(__name__) @app.route('/', methods=['GET', 'POST']) def queryVVS(): intent = request.json['request']['intent'] slots = {key.lower(): data['value'] for key, data in intent['slots'].items() if 'value' in data} if intent['name'] == 'GetDepartures': result = getDepartures(**slots) elif intent['name'] == 'GetConnection': result = getConnection(**slots) return json.dumps(result) def getConnection(source='Am Kriegsbergturm', target='Hauptbahnhof', time=None, date=None): url = 'http://mobil.vvs.de/jqm/controller/XSLT_TRIP_REQUEST2?outputFormat=JSON&type_destination=stop&type_origin=stop&useRealtime=1&name_origin=%s&name_destination=%s' \ % (urllib.quote_plus(source.encode('utf8')), urllib.quote_plus(target.encode('utf8'))) if time: url += '&itdTime=%s' % time.replace(':', '') if date: url += '&itdDate=%s' % date.replace('-', '') response = urllib.urlopen(url) response = json.loads(response.read().decode('latin1')) trips = [] now = datetime.datetime.now() for trip in response['trips'] or []: hours, minutes = (int(x) for x in trip['duration'].split(':')) tripText = 'Fahrzeit' if hours: tripText += ' %d Stunden und' % hours tripText += ' %d Minuten' % minutes interchanges = int(trip['interchange']) if interchanges: if interchanges == 1: tripText += ' bei einem Umstieg' else: tripText += ' bei %d Umstiegen' % interchanges firstLeg = True for leg in trip['legs']: if firstLeg: firstLeg = False dateTime = leg['points'][0]['dateTime'] departureTime = datetime.datetime.strptime(dateTime.get('rtDate', dateTime['date']) + ' ' + dateTime.get('rtTime', dateTime['time']), '%d.%m.%Y %H:%M') minutesTillDeparture = (departureTime - now).total_seconds() / 60 if runsAtHeroku: minutesTillDeparture -= 60 if minutesTillDeparture < 0.5 or minutesTillDeparture > 60: tripText += ' mit %s in Richtung %s ab %s Uhr bis %s' % (leg['mode']['name'], leg['mode']['destination'].split(' (')[0], dateTime.get('rtTime', dateTime['time']), leg['points'][-1]['name']) elif minutesTillDeparture > 0.5: tripText += ' mit %s in Richtung %s in %d Minuten bis %s' % (leg['mode']['name'], leg['mode']['destination'].split(' (')[0], minutesTillDeparture, leg['points'][-1]['name']) else: dateTime = leg['points'][0]['dateTime'] departureTime = datetime.datetime.strptime(dateTime.get('rtDate', dateTime['date']) + ' ' + dateTime.get('rtTime', dateTime['time']), '%d.%m.%Y %H:%M') minutesForInterchange = (departureTime - lastArrivalTime).total_seconds() / 60 tripText += ', dann in %d Minuten umsteigen in %s Richtung %s bis %s' % (minutesForInterchange, leg['mode']['name'], leg['mode']['destination'].split(' (')[0], leg['points'][-1]['name']) dateTime = leg['points'][-1]['dateTime'] lastArrivalTime = datetime.datetime.strptime(dateTime.get('rtDate', dateTime['date']) + ' ' + dateTime.get('rtTime', dateTime['time']), '%d.%m.%Y %H:%M') trips.append(tripText) result = { "version" : "1.0", "sessionAttributes": {}, "response" : { "outputSpeech" : { "type": "PlainText", "text": ". ".join(trips) }, "shouldEndSession": True } } return result def getDepartures(stop='Am Kriegsbergturm', time=None, date=None): url = 'http://mobile.vvs.de/jqm/controller/XSLT_DM_REQUEST?limit=20&mode=direct&type_dm=stop&useRealtime=1&outputFormat=JSON&name_dm=%s' % stop if time: url += '&itdTime=%s' % time.replace(':', '') if date: url += '&itdDate=%s' % date.replace('-', '') response = urllib.urlopen(url) response = json.loads(response.read().decode('latin1')) departures = collections.defaultdict(list) for departure in response['departureList'] or []: departures[(departure['servingLine']['name'], departure['servingLine']['number'], departure['servingLine']['direction'].split(' (')[0])].append(departure) parts = [] now = datetime.datetime.now() for (name, tag, direction), departureList in departures.items(): minutes = [] times = [] for departure in departureList: departureTime = departure.get('realDateTime', departure['dateTime']) departureTime = {key: int(departureTime[key]) for key in ('hour', 'month', 'year', 'day', 'minute')} minutesTillDeparture = (datetime.datetime(**departureTime) - now).total_seconds() / 60 if runsAtHeroku: minutesTillDeparture -= 60 if minutesTillDeparture < 0.5 or minutesTillDeparture > 60: times += ['%d:%02d' % (departureTime['hour'], departureTime['minute'])] elif minutesTillDeparture > 0.5: minutes += ['%d' % minutesTillDeparture] if len(minutes) + len(times) > 2: break if len(minutes) > 1: minutes = ', '.join(minutes[:-1]) + ' und ' + minutes[-1] else: minutes = ''.join(minutes) if len(times) > 1: times = ', '.join(times[:-1]) + ' und ' + times[-1] else: times = ''.join(times) part = '%s %s Richtung %s ' % (name, tag, direction) if minutes: part += "in %s Minuten" % minutes if times: if minutes: part += ' und ' part += "um %s Uhr" % times parts.append(part) result = { "version" : "1.0", "sessionAttributes": {}, "response" : { "outputSpeech" : { "type": "PlainText", "text": " und ".join(parts) }, "shouldEndSession": True } } return result if __name__ == '__main__': if runsAtHeroku: app.run(host='0.0.0.0', port=port) else: app.run(debug=True)
43.905405
209
0.554786
fd25ba81163d883a65a07de03662e866968a9ede
57
py
Python
Python/Books/Learning-Programming-with-Python.Tamim-Shahriar-Subeen/chapter-005/pg-5.1-check-turtle.py
shihab4t/Books-Code
b637b6b2ad42e11faf87d29047311160fe3b2490
[ "Unlicense" ]
null
null
null
Python/Books/Learning-Programming-with-Python.Tamim-Shahriar-Subeen/chapter-005/pg-5.1-check-turtle.py
shihab4t/Books-Code
b637b6b2ad42e11faf87d29047311160fe3b2490
[ "Unlicense" ]
null
null
null
Python/Books/Learning-Programming-with-Python.Tamim-Shahriar-Subeen/chapter-005/pg-5.1-check-turtle.py
shihab4t/Books-Code
b637b6b2ad42e11faf87d29047311160fe3b2490
[ "Unlicense" ]
null
null
null
import turtle turtle.forward(100) turtle.exitonclick()
9.5
20
0.789474
fd308d7dbc333d082e34f58aff0ed51ad0791375
439
py
Python
exercises/pt/test_02_02_01.py
tuanducdesign/spacy-course
f8d092c5fa2997fccb3f367d174dce8667932b3d
[ "MIT" ]
null
null
null
exercises/pt/test_02_02_01.py
tuanducdesign/spacy-course
f8d092c5fa2997fccb3f367d174dce8667932b3d
[ "MIT" ]
null
null
null
exercises/pt/test_02_02_01.py
tuanducdesign/spacy-course
f8d092c5fa2997fccb3f367d174dce8667932b3d
[ "MIT" ]
null
null
null
def test(): assert gato_hash == nlp.vocab.strings["gato"], "Você atribuiu o código hash corretamente?" assert 'nlp.vocab.strings["gato"]' in __solution__, "Você selecionou a string corretamente?" assert gato_string == "gato", "Você selecionou a string corretamente?" assert ( "nlp.vocab.strings[gato_hash]" in __solution__ ), "Você obteve a string a partir do código hash?" __msg__.good("Ótimo trabalho!")
43.9
96
0.697039
bd2ef38a0612241d1de44edb38334800ba3dd48e
251
py
Python
Chapter2_Python/01-Variables.py
olebause/TensorFlow2
70fcb7c85c7ead0dc4f88ffa35be5f2eb93e618e
[ "MIT" ]
11
2020-10-12T14:06:31.000Z
2022-02-22T09:16:32.000Z
Chapter2_Basics/Variables.py
franneck94/UdemyPythonIntro
4895a91a04eedce7d59b61bf12e5aa209fe60f85
[ "MIT" ]
1
2020-12-21T15:29:20.000Z
2022-01-15T12:06:09.000Z
Chapter2_Basics/Variables.py
franneck94/UdemyPythonIntro
4895a91a04eedce7d59b61bf12e5aa209fe60f85
[ "MIT" ]
8
2020-10-29T07:53:49.000Z
2022-03-17T11:01:20.000Z
# 1. var names cannot contain whitespaces # 2. var names cannot start with a number my_age = 27 # int price = 0.5 # float my_name_is_jan = True # bool my_name_is_peter = False # bool my_name = "Jan Schaffranek" # str print(my_age) print(price)
20.916667
41
0.713147
2f9999fb7e0a0ffa1363366f7c683a7fee0c73f2
240
py
Python
exercises/pt/solution_03_03.py
tuanducdesign/spacy-course
f8d092c5fa2997fccb3f367d174dce8667932b3d
[ "MIT" ]
null
null
null
exercises/pt/solution_03_03.py
tuanducdesign/spacy-course
f8d092c5fa2997fccb3f367d174dce8667932b3d
[ "MIT" ]
null
null
null
exercises/pt/solution_03_03.py
tuanducdesign/spacy-course
f8d092c5fa2997fccb3f367d174dce8667932b3d
[ "MIT" ]
null
null
null
import spacy # Carregue o fluxo de procesamento en_core_web_sm nlp = spacy.load("pt_core_news_sm") # Imprima o nome dos componentes do fluxo print(nlp.pipe_names) # Imprima as informações das tuplas (name, component) print(nlp.pipeline)
21.818182
53
0.7875
f1b47f048a9998081bfd0ddeb605e84241c854d2
330
py
Python
pusta2/config.py
EE/flexdb
08a80b9e56201e678ef055af27bdefa6d52bcbf5
[ "MIT" ]
null
null
null
pusta2/config.py
EE/flexdb
08a80b9e56201e678ef055af27bdefa6d52bcbf5
[ "MIT" ]
null
null
null
pusta2/config.py
EE/flexdb
08a80b9e56201e678ef055af27bdefa6d52bcbf5
[ "MIT" ]
null
null
null
app_name = "pusta2" prefix_url = "pusta2" static_files = { 'js': { 'pusta2/js/': ['main.js', ] }, 'css': { 'pusta2/css/': ['main.css', ] }, 'html': { 'pusta2/html/': ['index.html', ] } } permissions = { "edit": "Editing actualy nothing.", "sample1": "sample1longversion", }
18.333333
40
0.487879
7b075b0059651433f0f15cf456c5036b91957e78
38
py
Python
Python/Books/Learning-Programming-with-Python.Tamim-Shahriar-Subeen/chapter-006/ph-6.16-list-with-maltiple-range.py
shihab4t/Books-Code
b637b6b2ad42e11faf87d29047311160fe3b2490
[ "Unlicense" ]
null
null
null
Python/Books/Learning-Programming-with-Python.Tamim-Shahriar-Subeen/chapter-006/ph-6.16-list-with-maltiple-range.py
shihab4t/Books-Code
b637b6b2ad42e11faf87d29047311160fe3b2490
[ "Unlicense" ]
null
null
null
Python/Books/Learning-Programming-with-Python.Tamim-Shahriar-Subeen/chapter-006/ph-6.16-list-with-maltiple-range.py
shihab4t/Books-Code
b637b6b2ad42e11faf87d29047311160fe3b2490
[ "Unlicense" ]
null
null
null
li = list(range(2, 21, 2)) print(li)
9.5
26
0.578947
c8a7cac846d8b813597b47640cc31911b8185e4a
3,308
py
Python
projekte_ss2017/Minensuche_Benjamin/field.py
krother/python_abv_zedat
1e2e1fe16da6612c470f06f519cd053c567e0611
[ "MIT" ]
1
2019-03-04T20:09:26.000Z
2019-03-04T20:09:26.000Z
projekte_ss2017/Minensuche_Benjamin/field.py
krother/python_abv_zedat
1e2e1fe16da6612c470f06f519cd053c567e0611
[ "MIT" ]
null
null
null
projekte_ss2017/Minensuche_Benjamin/field.py
krother/python_abv_zedat
1e2e1fe16da6612c470f06f519cd053c567e0611
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- """ Created on Mon Jul 31 22:06:35 2017 @author: Benny """ import random as rnd def printField(field): '''printField printes the Minesweeperfield''' for row in range(len(field)): print() for col in range(len(field[0])): print(field[row][col], end = "") class Field: '''Field is a class for gameboards specially for Minesweeper''' def __init__(self, height, width, p): self.height = height self.width = width self.p = p self.emptyfield = self.generateField() self.minedfield = self.mineplanting() self.solution = self.generateSolution() def generateField(self): '''generateField generates an empty (with 0 filled) Field''' gamefield = [] for height in range(self.height): row = [] for width in range(self.width): row.append(0) gamefield.append(row) return gamefield def mineplanting(self): '''mineplanting plants randomly a given number of mines in a new field with the objects height and width''' minelist = [] field = [] while len(minelist) < self.p: mine_x = rnd.randint(0, self.width-1) mine_y = rnd.randint(0, self.height-1) if not (mine_x, mine_y) in minelist: minelist.append( (mine_x, mine_y) ) for height in range(self.height): row = [] for width in range(self.width): if (width, height) in minelist: row.append("*") else: row.append(0) field.append(row) return field def generateSolution(self): '''generateSolution generates the solution to the field, with the field as model''' solution = self.generateField() for height in range(self.height): row = solution[height] for width in range(self.width): if self.minedfield[height][width] == '*': row[width] = '*' else: if height == 0: h = (0,1) elif height == self.height-1: h = (0,-1) else: h = (-1,0,1) if width == 0: b = (0,1) elif width == self.width-1: b = (0,-1) else: b = (-1,0,1) for i in h: for j in b: if self.minedfield[height+i][width+j] == '*': row[width] += 1 if row[width] == 0: row[width] = '.' return solution if __name__ == "__main__": gameBoard = Field(5, 10, 5) printField(gameBoard.emptyfield) print("\n") printField(gameBoard.minedfield) print("\n") printField(gameBoard.solution)
30.915888
88
0.441959
c8ba9141db4d8766c1713040f5459df594f79e19
277
py
Python
src/terracotta.py
magistersart/ZTC_fork
ce72734ea575d9846b5b81f3efbfd14fa1f7e532
[ "PostgreSQL" ]
null
null
null
src/terracotta.py
magistersart/ZTC_fork
ce72734ea575d9846b5b81f3efbfd14fa1f7e532
[ "PostgreSQL" ]
null
null
null
src/terracotta.py
magistersart/ZTC_fork
ce72734ea575d9846b5b81f3efbfd14fa1f7e532
[ "PostgreSQL" ]
null
null
null
#!/usr/bin/python # pylint: disable=W0142 """ terracotta.* scripts item This file is part of ZTC and distributed under GNU GPL v.3 Copyright (c) 2011 Vladimir Rusinov] """ from ztc.java.terracotta import JMXTerracotta j = JMXTerracotta() m = j.args[0] j.get(m, *j.args[1:])
18.466667
58
0.714801
a80e4fd7647e2b2049ab30c37ad79eba0682f08f
2,743
py
Python
simple-tensorflow-demo/4.demos/3.backPropagationTest.py
crackedcd/Intern.MT
36398837af377a7e1c4edd7cbb15eabecd2c3103
[ "MIT" ]
1
2019-07-05T03:42:17.000Z
2019-07-05T03:42:17.000Z
simple-tensorflow-demo/4.demos/3.backPropagationTest.py
crackedcd/Intern.MT
36398837af377a7e1c4edd7cbb15eabecd2c3103
[ "MIT" ]
null
null
null
simple-tensorflow-demo/4.demos/3.backPropagationTest.py
crackedcd/Intern.MT
36398837af377a7e1c4edd7cbb15eabecd2c3103
[ "MIT" ]
1
2019-06-24T05:56:55.000Z
2019-06-24T05:56:55.000Z
""" 损失函数 loss 预测值(predict)(y)与已知答案(target)(y_)的差距 均方误差 MSE mean-square error MSE(y, y_) = sigma ((y - y_)^2 / n) loss = tf.reduce_mean(tf.square(y, y_)) 反向传播 BP back propagation 为训练模型参数, 在所有参数上用梯度下降, 使NN模型在训练数据上的损失最小. train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss) train_step = tf.train.MomentumOptimizer(learning_rate, momentum).minimize(loss) train_step = tf.train.AdamOptimizer(learning_rate).minimize(loss) 学习率 LR learning rate 学习率 大 学习率 小 学习速度 快 慢 使用时间点 刚开始训练时 一定轮数过后 副作用 1.易损失值爆炸; 2.易振荡. 1.易过拟合; 2.收敛速度慢. 刚开始训练时: 学习率以 0.01 ~ 0.001 为宜. 一定轮数过后: 逐渐减缓. 接近训练结束: 学习速率的衰减应该在100倍以上. """ import tensorflow as tf import numpy as np def back_propagation_test(): # 训练次数 steps = 3000 # 每次喂入数据数量 batch_size = 8 # 随机种子 seed = 8731 # 基于seed产生随机数 rng = np.random.RandomState(seed) # 生成32组重量和体积作为输入数据集, 32行2列的矩阵 mat_x = rng.rand(32, 2) mat_y = [] # print(mat_x) # 假设"体积 + 重量 < 1"的零件合格, 构造mat_y. 从X中取出一行, 判断如果两者的和小于1, 给Y赋值1, 否则赋值0. # 神经网络判断的依据是"数据"和"概率", 它并不知道人为标注y是0或1的方法. # pythonic code: mat_y = [[int(x0 + x1 < 1)] for (x0, x1) in mat_x] for x0, x1 in mat_x: if x0 + x1 < 1: mat_y.append([1]) else: mat_y.append([0]) # print(mat_y) # 前向传播 x = tf.placeholder(tf.float32, shape=(None, 2)) y_ = tf.placeholder(tf.float32, shape=(None, 1)) w1 = tf.Variable(tf.random_normal([2, 3], stddev=1, seed=1)) w2 = tf.Variable(tf.random_normal([3, 1], stddev=1, seed=1)) a = tf.matmul(x, w1) y = tf.matmul(a, w2) # 反向传播 loss = tf.reduce_mean(tf.square(y - y_)) lr = 0.001 train_step = tf.train.GradientDescentOptimizer(lr).minimize(loss) # 训练 with tf.Session() as sess: init_op = tf.global_variables_initializer() sess.run(init_op) # 输出未训练的参数取值 print("训练前的结果") print(sess.run(w1)) print(sess.run(w2)) for i in range(steps): # 数据集只有32个(行), 所以对32取余, 让start在数据集范围内, i * batch_size让每次训练跨度batch_size个数据 start = (i * batch_size) % 32 end = start + batch_size feeds = { x: mat_x[start:end], y_: mat_y[start:end] } # 每次循环中, 代入输入特征(data)和标准答案(target) sess.run(train_step, feed_dict=feeds) if i % 500 == 0: total_loss = sess.run(loss, feed_dict={x: mat_x, y_: mat_y}) print("在%d次训练后, 损失为%g" % (i, total_loss)) print("训练后的结果") print(sess.run(w1)) print(sess.run(w2)) return None if __name__ == '__main__': back_propagation_test()
27.158416
85
0.582574
93b61103d8019f377a14047dd0b12051d80f41d7
637
py
Python
py/test/test_inception_v2.py
zjZSTU/GoogLeNet
a0801e45006d34b4901a8834397961ce17f24e2e
[ "Apache-2.0" ]
1
2021-04-18T15:36:33.000Z
2021-04-18T15:36:33.000Z
py/test/test_inception_v2.py
zjZSTU/GoogLeNet
a0801e45006d34b4901a8834397961ce17f24e2e
[ "Apache-2.0" ]
null
null
null
py/test/test_inception_v2.py
zjZSTU/GoogLeNet
a0801e45006d34b4901a8834397961ce17f24e2e
[ "Apache-2.0" ]
3
2020-07-10T11:45:52.000Z
2022-01-15T08:46:14.000Z
# -*- coding: utf-8 -*- """ @date: 2020/4/9 下午11:37 @file: test_inception_v2.py @author: zj @description: """ import torch import models.inception_v2 as inception def test(): model_googlenet = inception.Inception_v2(num_classes=1000) # print(model_googlenet) # 训练阶段 model_googlenet.train() data = torch.randn((1, 3, 299, 299)) outputs, aux = model_googlenet.forward(data) print(outputs.shape) print(aux.shape) # 测试阶段 model_googlenet.eval() data = torch.randn((1, 3, 299, 299)) outputs = model_googlenet.forward(data) print(outputs.shape) if __name__ == '__main__': test()
18.735294
62
0.660911
27a9c70335e5cc4b5a56e709850c0d0067a0b822
5,917
py
Python
BruteForce/Wordpress.py
Zusyaku/Termux-And-Lali-Linux-V2
b1a1b0841d22d4bf2cc7932b72716d55f070871e
[ "Apache-2.0" ]
2
2021-11-17T03:35:03.000Z
2021-12-08T06:00:31.000Z
BruteForce/Wordpress.py
Zusyaku/Termux-And-Lali-Linux-V2
b1a1b0841d22d4bf2cc7932b72716d55f070871e
[ "Apache-2.0" ]
null
null
null
BruteForce/Wordpress.py
Zusyaku/Termux-And-Lali-Linux-V2
b1a1b0841d22d4bf2cc7932b72716d55f070871e
[ "Apache-2.0" ]
2
2021-11-05T18:07:48.000Z
2022-02-24T21:25:07.000Z
# uncompyle6 version 2.11.5 # Python bytecode 2.7 (62211) # Decompiled from: Python 2.7.18 (default, Apr 20 2020, 20:30:41) # [GCC 9.3.0] # Embedded file name: BruteForce\Wordpress.py import requests import re import threading import time import json from Exploits import printModule from Tools import shellupload r = '\x1b[31m' g = '\x1b[32m' y = '\x1b[33m' b = '\x1b[34m' m = '\x1b[35m' c = '\x1b[36m' w = '\x1b[37m' Headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:72.0) Gecko/20100101 Firefox/72.0'} passwords = open('files/DefaultPasswords_Wordpress.txt', 'r').read().splitlines() class Wordpress(object): def __init__(self): self.flag = 0 self.password = passwords def Run(self, site, users): try: thread = [] for username in users: if self.flag == 1: break for passwd in self.password: t = threading.Thread(target=self.BruteForce, args=( site, passwd, username)) if self.flag == 1: break else: t.start() thread.append(t) time.sleep(0.08) for j in thread: j.join() if self.flag == 0: return printModule.returnNo(site, 'N/A', 'Wordpress Bruteforce', 'Wordpress') return printModule.returnYes(site, 'N/A', 'Wordpress Bruteforce', 'Wordpress') except: return printModule.returnNo(site, 'N/A', 'Wordpress Bruteforce', 'Wordpress') def UserName_Enumeration(self, site): users = [] session = requests.session() for i in range(10): try: GETSource = session.get('http://' + site + '/?author={}'.format(str(i + 1)), timeout=7, headers=Headers) find = re.findall('/author/(.*)/"', str(GETSource.content)) username = find[0] if '/feed' in str(username): find = re.findall('/author/(.*)/feed/"', str(GETSource.content)) username2 = find[0] users.append(str(username2)) else: users.append(str(username)) except: pass if not len(users) == 0: pass else: for i in range(10): try: GETSource2 = session.get('http://' + site + '/wp-json/wp/v2/users/' + str(i + 1), timeout=7, headers=Headers) __InFo = json.loads(str(GETSource2.content)) if 'id' not in str(__InFo): pass else: try: users.append(str(__InFo['slug'])) except: pass except: pass if not len(users) == 0: pass else: try: GETSource3 = session.get('http://' + site + '/author-sitemap.xml', timeout=7, headers=Headers) yost = re.findall('(<loc>(.*?)</loc>)\\s', GETSource3.content) for user in yost: users.append(str(user[1].split('/')[4])) except: pass if not len(users) == 0: pass else: users.append('admin') return self.Run(site, users) def BruteForce(self, site, passwd, username): try: sess = requests.session() Headersz = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:72.0) Gecko/20100101 Firefox/72.0' } sess.get('http://' + site + '', timeout=10, headers=Headersz) source = sess.get('http://' + site + '/wp-login.php', timeout=10, headers=Headersz).content WpSubmitValue = re.findall('class="button button-primary button-large" value="(.*)"', str(source))[0] WpRedirctTo = re.findall('name="redirect_to" value="(.*)"', str(source))[0] if 'Log In' in WpSubmitValue: WpSubmitValue = 'Log+In' else: WpSubmitValue = WpSubmitValue Headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:72.0) Gecko/20100101 Firefox/72.0','Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'Accept-Language': 'en-US,en;q=0.5', 'Accept-Encoding': 'gzip, deflate', 'Referer': 'http://{}'.format(site), 'Content-Type': 'application/x-www-form-urlencoded', 'Origin': 'http://{}'.format(site), 'Connection': 'keep-alive', 'Upgrade-Insecure-Requests': '1', 'Sec-Fetch-Dest': 'document', 'Sec-Fetch-Mode': 'navigate', 'Sec-Fetch-Site': 'same-origin', 'Sec-Fetch-User': '?1' } post = {'log': username, 'pwd': passwd, 'wp-submit': WpSubmitValue, 'redirect_to': WpRedirctTo, 'testcookie': '1' } url = site + '/wp-login.php' sess.post('http://' + url, data=post, headers=Headers, timeout=10) G = sess.get('http://' + site + '/wp-admin/', timeout=10, headers=Headersz) if '_logged' in str(sess.cookies) and 'dashboard' in str(G.content): with open('result/Wordpress_Hacked.txt', 'a') as writer: writer.write('http://' + site + '/wp-login.php' + '\n Username: {}'.format(username) + '\n Password: ' + passwd + '\n-----------------------------------------\n') shellupload.UploadshellWordpress(site, sess) self.flag = 1 except: pass
39.97973
205
0.488085
e3879e265593ab018ada0842a7f018865afdb065
792
py
Python
ryu/app/otherApp/getFlowTab.py
yuesir137/SDN-CLB
58b12a9412cffdf2945440528b1885c8899edd08
[ "Apache-2.0" ]
null
null
null
ryu/app/otherApp/getFlowTab.py
yuesir137/SDN-CLB
58b12a9412cffdf2945440528b1885c8899edd08
[ "Apache-2.0" ]
null
null
null
ryu/app/otherApp/getFlowTab.py
yuesir137/SDN-CLB
58b12a9412cffdf2945440528b1885c8899edd08
[ "Apache-2.0" ]
null
null
null
import os import time local=1 while True: tables=os.popen('sudo ovs-ofctl dump-flows s{}'.format(local)).readlines()[1:] minPacketN=100 minPort=-1 for table in tables: print(table) details=table.split(',') # print(details) if len(details)>9: duration=details[1][10:-1] print(duration) n_packets=details[3][11:] print(n_packets) packetRate=int(n_packets)/float(duration) print(packetRate) srcIP=details[10][7:] print(srcIP) dstIP=details[11][7:] print(dstIP) port=details[12][7:] print(port) if n_packets<minPacketN: minPacketN=n_packets minPort=port time.sleep(1)
27.310345
82
0.539141
4750a43892925cea105fadd9b59420a1313f7f95
3,566
py
Python
Python/calculator_gui.py
saurabhpal007/hacktoberfest2021-1
5abad37ab426a7b34fc7bcd98ded885fd6ce02ef
[ "CC0-1.0" ]
81
2021-10-01T13:19:13.000Z
2021-10-06T08:43:35.000Z
Python/calculator_gui.py
saurabhpal007/hacktoberfest2021-1
5abad37ab426a7b34fc7bcd98ded885fd6ce02ef
[ "CC0-1.0" ]
67
2021-10-01T13:43:46.000Z
2021-10-06T13:55:49.000Z
Python/calculator_gui.py
saurabhpal007/hacktoberfest2021-1
5abad37ab426a7b34fc7bcd98ded885fd6ce02ef
[ "CC0-1.0" ]
394
2021-10-01T11:55:24.000Z
2021-10-06T13:45:57.000Z
from tkinter import * import parser from math import factorial root = Tk() root.title("Calculator") i=0 def get_variables(num): global i display.insert(i,num) i+=1 def perhitungan(): entire_string = display.get() try: a = parser.expr(entire_string).compile() result = eval(a) clear_all() display.insert(0,result) except Exception: clear_all() display.insert(0,"Error") def get_operation(operator): global i length = len(operator) display.insert(i,operator) i+=length def clear_all(): display.delete(0,END) def undo(): entire_string = display.get() if len(entire_string): new_string = entire_string[:-1] clear_all() display.insert(0,new_string) else: clear_all() display.insert(0,"Error") def fact(): entire_string = display.get() try: result = factorial(int(entire_string)) clear_all() display.insert(0,result) except Exception: clear_all() display.insert(0,"Error") display = Entry(root) display.grid(row=1,columnspan=6,sticky=N+E+W+S) Button(root,text="1",command = lambda : get_variables(1)).grid(row=2,column=0, sticky=N+S+E+W) Button(root,text="2",command = lambda : get_variables(2)).grid(row=2,column=1, sticky=N+S+E+W) Button(root,text="3",command = lambda : get_variables(3)).grid(row=2,column=2, sticky=N+S+E+W) Button(root,text="4",command = lambda : get_variables(4)).grid(row=3,column=0, sticky=N+S+E+W) Button(root,text="5",command = lambda : get_variables(5)).grid(row=3,column=1, sticky=N+S+E+W) Button(root,text="6",command = lambda : get_variables(6)).grid(row=3,column=2, sticky=N+S+E+W) Button(root,text="7",command = lambda : get_variables(7)).grid(row=4,column=0, sticky=N+S+E+W) Button(root,text="8",command = lambda : get_variables(8)).grid(row=4,column=1, sticky=N+S+E+W) Button(root,text="9",command = lambda : get_variables(9)).grid(row=4,column=2, sticky=N+S+E+W) Button(root,text="AC",command = lambda : clear_all()).grid(row=5,column=0, sticky=N+S+E+W) Button(root,text="0",command = lambda : get_variables(0)).grid(row=5,column=1, sticky=N+S+E+W) Button(root,text=" .",command = lambda : get_variables(".")).grid(row=5,column=2, sticky=N+S+E+W) Button(root,text="+",command = lambda : get_operation("+")).grid(row=2,column=3, sticky=N+S+E+W) Button(root,text="-",command = lambda : get_operation("-")).grid(row=3,column=3, sticky=N+S+E+W) Button(root,text="*",command = lambda : get_operation("*")).grid(row=4,column=3, sticky=N+S+E+W) Button(root,text="/",command = lambda : get_operation("//")).grid(row=5,column=3, sticky=N+S+E+W) Button(root,text="pi",command = lambda : get_operation("*3.14")).grid(row=2,column=4, sticky=N+S+E+W) Button(root,text="%",command = lambda : get_operation("%")).grid(row=3,column=4, sticky=N+S+E+W) Button(root,text="(",command = lambda : get_operation("(")).grid(row=4,column=4, sticky=N+S+E+W) Button(root,text="exp",command = lambda : get_operation("**")).grid(row=5,column=4, sticky=N+S+E+W) Button(root,text="<-",command = lambda : undo()).grid(row=2,column=5, sticky=N+S+E+W) Button(root,text="x!",command = lambda : fact()).grid(row=3,column=5, sticky=N+S+E+W) Button(root,text=")",command = lambda : get_operation(")")).grid(row=4,column=5, sticky=N+S+E+W) Button(root,text="^2",command = lambda : get_operation("**2")).grid(row=5,column=5, sticky=N+S+E+W) Button(root,text="=",command = lambda : perhitungan()).grid(columnspan=6, sticky=N+S+E+W) root.mainloop()
42.452381
101
0.660404
47c46d3061e5499818d18eca27a7cbab630d6878
396
py
Python
exercises/zh/exc_04_10.py
Jette16/spacy-course
32df0c8f6192de6c9daba89740a28c0537e4d6a0
[ "MIT" ]
2,085
2019-04-17T13:10:40.000Z
2022-03-30T21:51:46.000Z
exercises/zh/exc_04_10.py
Jette16/spacy-course
32df0c8f6192de6c9daba89740a28c0537e4d6a0
[ "MIT" ]
79
2019-04-18T14:42:55.000Z
2022-03-07T08:15:43.000Z
exercises/zh/exc_04_10.py
Jette16/spacy-course
32df0c8f6192de6c9daba89740a28c0537e4d6a0
[ "MIT" ]
361
2019-04-17T13:34:32.000Z
2022-03-28T04:42:45.000Z
TRAINING_DATA = [ ( "我去年去了西安,那里的城墙很壮观!", {"entities": [(4, 5, "TOURIST_DESTINATION")]}, ), ( "人一辈子一定要去一趟巴黎,但那里的埃菲尔铁塔有点无趣。", {"entities": [(5, 6, "TOURIST_DESTINATION")]}, ), ( "深圳也有个巴黎的埃菲尔铁塔,哈哈哈", {"entities": []} ), ( "北京很适合暑假去:长城、故宫,还有各种好吃的小吃!", {"entities": [(0, 1, "TOURIST_DESTINATION")]}, ), ]
20.842105
54
0.467172
d089f978def3108a932d726df6fa2d43634cb62e
5,448
py
Python
contrib/华为云垃圾分类大赛心得与案例-GitLD/src_Xception_all_aug+TTA/data_gen.py
huaweicloud/ModelArts-Lab
75d06fb70d81469cc23cd422200877ce443866be
[ "Apache-2.0" ]
1,045
2019-05-09T02:50:43.000Z
2022-03-31T06:22:11.000Z
contrib/华为云垃圾分类大赛心得与案例-GitLD/src_Xception_all_aug+TTA/data_gen.py
huaweicloud/ModelArts-Lab
75d06fb70d81469cc23cd422200877ce443866be
[ "Apache-2.0" ]
1,468
2019-05-16T00:48:18.000Z
2022-03-08T04:12:44.000Z
contrib/华为云垃圾分类大赛心得与案例-GitLD/src_Xception_all_aug+TTA/data_gen.py
huaweicloud/ModelArts-Lab
75d06fb70d81469cc23cd422200877ce443866be
[ "Apache-2.0" ]
1,077
2019-05-09T02:50:53.000Z
2022-03-27T11:05:32.000Z
# -*- coding: utf-8 -*- import os import math import codecs import random import numpy as np from glob import glob from PIL import Image from keras.utils import np_utils, Sequence from sklearn.model_selection import train_test_split class BaseSequence(Sequence): """ 基础的数据流生成器,每次迭代返回一个batch BaseSequence可直接用于fit_generator的generator参数 fit_generator会将BaseSequence再次封装为一个多进程的数据流生成器 而且能保证在多进程下的一个epoch中不会重复取相同的样本 """ def __init__(self, img_paths, labels, batch_size, img_size): assert len(img_paths) == len(labels), "len(img_paths) must equal to len(lables)" assert img_size[0] == img_size[1], "img_size[0] must equal to img_size[1]" self.x_y = np.hstack((np.array(img_paths).reshape(len(img_paths), 1), np.array(labels))) self.batch_size = batch_size self.img_size = img_size def __len__(self): return math.ceil(len(self.x_y) / self.batch_size) @staticmethod def center_img(img, size=None, fill_value=255): """ center img in a square background """ h, w = img.shape[:2] if size is None: size = max(h, w) shape = (size, size) + img.shape[2:] background = np.full(shape, fill_value, np.uint8) center_x = (size - w) // 2 center_y = (size - h) // 2 background[center_y:center_y + h, center_x:center_x + w] = img return background def preprocess_img(self, img_path): """ image preprocessing you can add your special preprocess method here """ img = Image.open(img_path) img = img.resize((self.img_size[0], self.img_size[0])) img = img.convert('RGB') img = np.array(img) img = img[:, :, ::-1] return img def __getitem__(self, idx): batch_x = self.x_y[idx * self.batch_size: (idx + 1) * self.batch_size, 0] batch_y = self.x_y[idx * self.batch_size: (idx + 1) * self.batch_size, 1:] batch_x = np.array([self.preprocess_img(img_path) for img_path in batch_x]) batch_y = np.array(batch_y).astype(np.float32) return batch_x, batch_y def on_epoch_end(self): """Method called at the end of every epoch. """ np.random.shuffle(self.x_y) def data_flow(train_data_dir, batch_size, num_classes, input_size): # need modify label_files = glob(os.path.join(train_data_dir, '*.txt')) random.shuffle(label_files) img_paths = [] labels = [] for index, file_path in enumerate(label_files): with codecs.open(file_path, 'r', 'utf-8') as f: line = f.readline() line_split = line.strip().split(', ') if len(line_split) != 2: print('%s contain error lable' % os.path.basename(file_path)) continue img_name = line_split[0] label = int(line_split[1]) img_paths.append(os.path.join(train_data_dir, img_name)) labels.append(label) labels = np_utils.to_categorical(labels, num_classes) train_img_paths, validation_img_paths, train_labels, validation_labels = \ train_test_split(img_paths, labels, test_size=0.2, random_state=0) print('total samples: %d, training samples: %d, validation samples: %d' % (len(img_paths), len(train_img_paths), len(validation_img_paths))) train_sequence = BaseSequence(train_img_paths, train_labels, batch_size, [input_size, input_size]) validation_sequence = BaseSequence(validation_img_paths, validation_labels, batch_size, [input_size, input_size]) # # 构造多进程的数据流生成器 # train_enqueuer = OrderedEnqueuer(train_sequence, use_multiprocessing=True, shuffle=True) # validation_enqueuer = OrderedEnqueuer(validation_sequence, use_multiprocessing=True, shuffle=True) # # # 启动数据生成器 # n_cpu = multiprocessing.cpu_count() # train_enqueuer.start(workers=int(n_cpu * 0.7), max_queue_size=10) # validation_enqueuer.start(workers=1, max_queue_size=10) # train_data_generator = train_enqueuer.get() # validation_data_generator = validation_enqueuer.get() # return train_enqueuer, validation_enqueuer, train_data_generator, validation_data_generator return train_sequence, validation_sequence if __name__ == '__main__': # train_enqueuer, validation_enqueuer, train_data_generator, validation_data_generator = data_flow(dog_cat_data_path, batch_size) # for i in range(10): # train_data_batch = next(train_data_generator) # train_enqueuer.stop() # validation_enqueuer.stop() train_sequence, validation_sequence = data_flow(train_data_dir, batch_size) batch_data, bacth_label = train_sequence.__getitem__(5) label_name = ['cat', 'dog'] for index, data in enumerate(batch_data): img = Image.fromarray(data[:, :, ::-1]) img.save('./debug/%d_%s.jpg' % (index, label_name[int(bacth_label[index][1])])) train_sequence.on_epoch_end() batch_data, bacth_label = train_sequence.__getitem__(5) for index, data in enumerate(batch_data): img = Image.fromarray(data[:, :, ::-1]) img.save('./debug/%d_2_%s.jpg' % (index, label_name[int(bacth_label[index][1])])) train_sequence.on_epoch_end() batch_data, bacth_label = train_sequence.__getitem__(5) for index, data in enumerate(batch_data): img = Image.fromarray(data[:, :, ::-1]) img.save('./debug/%d_3_%s.jpg' % (index, label_name[int(bacth_label[index][1])])) print('end')
41.272727
144
0.672173
d0a0e3262a093befa973a8e125897b334151be59
1,047
py
Python
018-C127-WebScraping/main.py
somePythonProgrammer/PythonCode
fb2b2245db631cefd916a960768f411969b0e78f
[ "MIT" ]
2
2021-09-28T13:55:20.000Z
2021-11-15T10:08:49.000Z
018-C127-WebScraping/main.py
somePythonProgrammer/PythonCode
fb2b2245db631cefd916a960768f411969b0e78f
[ "MIT" ]
null
null
null
018-C127-WebScraping/main.py
somePythonProgrammer/PythonCode
fb2b2245db631cefd916a960768f411969b0e78f
[ "MIT" ]
1
2022-01-20T03:02:20.000Z
2022-01-20T03:02:20.000Z
from selenium import webdriver from bs4 import BeautifulSoup import time import csv START_URL = "https://en.wikipedia.org/wiki/List_of_brightest_stars_and_other_record_stars" browser = webdriver.Chrome("chromedriver.exe") browser.get(START_URL) time.sleep(3) def scrape(): headers = ["vmag", "name", "bayer", "distance_ly", "spectral_class", "mass", "radius", "luminosity"] star_data = [] soup = BeautifulSoup(browser.page_source, "html.parser") table = soup.find_all("table", attrs={"class", "wikitable sortable jquery-tablesorter"})[0] for row in table.find_all("tr"): cols = row.find_all("td") if len(cols) == 0: continue star_data.append([col.text.strip() for col in cols]) with open("stars.csv", "w") as f: csvwriter = csv.writer(f) csvwriter.writerow(headers) # use for loop to write each row of data to csv for row in star_data: try: csvwriter.writerow(row) except: pass scrape() exit()
29.914286
104
0.636103
ef7372b2f45a71a889cf69edf89aa0ccd564cb51
5,955
py
Python
AntColonyOptimizer.py
siej88/FuzzyACO
989a58049c8417cd023cfc312fb99d2649333ca7
[ "MIT" ]
null
null
null
AntColonyOptimizer.py
siej88/FuzzyACO
989a58049c8417cd023cfc312fb99d2649333ca7
[ "MIT" ]
null
null
null
AntColonyOptimizer.py
siej88/FuzzyACO
989a58049c8417cd023cfc312fb99d2649333ca7
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- """ UNIVERSIDAD DE CONCEPCION Departamento de Ingenieria Informatica y Ciencias de la Computacion Memoria de Titulo Ingenieria Civil Informatica DETECCION DE BORDES EN IMAGENES DGGE USANDO UN SISTEMA HIBRIDO ACO CON LOGICA DIFUSA Autor: Sebastian Ignacio Espinoza Jimenez Patrocinante: Maria Angelica Pinninghoff Junemann """ import numpy as N import MathTools as mat class AntColonyOptimizer(object): """Ant Colony Optimization Engine""" def __init__(self): """AntColonyOptimizer AntColonyOptimizer()""" self._pheromoneMatrix = None self._imageFlag = False def hasPheromoneMatrix(self): """bool hasPheromoneMatrix()""" return self._imageFlag def getPheromoneMatrix(self): """numpy.array getPheromoneMatrix()""" return N.copy(self._pheromoneMatrix) def generatePheromoneMatrix(self, imageMatrix, heuristicMatrix, parameterSet): """numpy.array generatePheromoneMatrix( numpy.array imageMatrix, numpy.array heuristicMatrix, dict parameterSet)""" antMovementMode = parameterSet['antMovementMode'] antCount = parameterSet['antCount'] cycleCount = parameterSet['cycleCount'] stepCount = parameterSet['stepCount'] alpha = parameterSet['alpha'] beta = parameterSet['beta'] delta = parameterSet['delta'] tuning = parameterSet['tuning'] rho = parameterSet['rho'] psi = parameterSet['psi'] mathTools = mat.MathTools() pheromoneMatrix = self._generateInitialPheromoneMatrix(N.copy(imageMatrix)) matrixHeight = heuristicMatrix.shape[0] matrixWidth = heuristicMatrix.shape[1] indexes = list(N.ndindex(matrixHeight, matrixWidth)) N.random.shuffle(indexes) antSet = indexes[0:antCount] initialPheromoneMatrix = N.copy(pheromoneMatrix) heuristiqMatrix = N.copy(heuristicMatrix) heuristiqMatrix[N.where(heuristiqMatrix == 0)] = 1e-10 for cycle in xrange(cycleCount): N.random.shuffle(antSet) antPrevious = list(antSet) for i in xrange(antCount): for step in xrange(stepCount): x = antSet[i][0] y = antSet[i][1] dx = antPrevious[i][0] - x dy = antPrevious[i][1] - y top = x > 0 bottom = x < matrixHeight - 1 left = y > 0 right = y < matrixWidth - 1 heuristicWindow = heuristiqMatrix[x-top:x+bottom+1, y-left:y+right+1] pheromoneWindow = pheromoneMatrix[x-top:x+bottom+1, y-left:y+right+1] mask = float(heuristicWindow[top, left]) heuristicWindow[top, left] = 2. minHeuristic = N.min(heuristicWindow) heuristicWindow[top, left] = -2. maxHeuristic = N.max(heuristicWindow) heuristicWindow[top, left] = mask if (maxHeuristic - minHeuristic > delta): alpha -= tuning beta += tuning else: alpha += tuning beta -= tuning probabilityMatrix = N.power(pheromoneWindow, alpha)*N.power(heuristicWindow, beta) probabilityMatrix[top, left] = -2. probabilityMatrix[top + dx, left + dy] = -2. if antMovementMode == 1: maxProbability = N.max(probabilityMatrix) indexes = N.where(probabilityMatrix == maxProbability) randomIndex = N.random.randint(indexes[0].shape[0]) newIndex = (indexes[0][randomIndex], indexes[1][randomIndex]) else: indexes = N.where(probabilityMatrix >= 0) probabilityArray = probabilityMatrix[indexes] summationArray = N.cumsum(probabilityArray) randomValue = N.random.rand(1)*summationArray[summationArray.shape[0] - 1] probabilityIndex = N.where(summationArray >= randomValue[0]) probabilityValue = probabilityArray[probabilityIndex][0] newIndex = N.where(probabilityMatrix == probabilityValue) randomIndex = N.random.randint(newIndex[0].shape[0]) newIndex = (newIndex[0][randomIndex], newIndex[1][randomIndex]) newX = x+newIndex[0]-top newY = y+newIndex[1]-left antPrevious[i] = (x, y) antSet[i] = (newX, newY) pheromone = pheromoneMatrix[x,y] heuristic = heuristiqMatrix[x,y] pheromoneMatrix[x,y] = (1-rho)*pheromone + rho*heuristic pheromoneMatrix = (1-psi)*pheromoneMatrix + psi*initialPheromoneMatrix pheromoneMatrix = mathTools.normalize(pheromoneMatrix) self._pheromoneMatrix = N.copy(pheromoneMatrix) self._imageFlag = True return pheromoneMatrix def _generateInitialPheromoneMatrix(self, inputMatrix): """numpy.array _generateInitialPheromoneMatrix(numpy.array inputMatrix)""" mathTools = mat.MathTools() gaussianMatrix = mathTools.gaussianFilter(inputMatrix) gradientMatrix = mathTools.gradient(gaussianMatrix) laplacianMatrix = mathTools.gradient(gradientMatrix) initialPheromoneMatrix = gradientMatrix-laplacianMatrix initialPheromoneMatrix = mathTools.normalize(initialPheromoneMatrix) return initialPheromoneMatrix
48.024194
105
0.573468
ef994720ea2a999f0b5e3dfb0c277052b19ae51f
534
py
Python
Packs/CommonScripts/Scripts/Cut/Cut_test.py
diCagri/content
c532c50b213e6dddb8ae6a378d6d09198e08fc9f
[ "MIT" ]
799
2016-08-02T06:43:14.000Z
2022-03-31T11:10:11.000Z
Packs/CommonScripts/Scripts/Cut/Cut_test.py
diCagri/content
c532c50b213e6dddb8ae6a378d6d09198e08fc9f
[ "MIT" ]
9,317
2016-08-07T19:00:51.000Z
2022-03-31T21:56:04.000Z
Packs/CommonScripts/Scripts/Cut/Cut_test.py
diCagri/content
c532c50b213e6dddb8ae6a378d6d09198e08fc9f
[ "MIT" ]
1,297
2016-08-04T13:59:00.000Z
2022-03-31T23:43:06.000Z
from Cut import cut import pytest @pytest.mark.parametrize('value,delimiter,fields,expected', [ ('A-B-C-D-E', '-', '1,5', 'A-E'), ('a,ב,c', ',', '2,3', 'ב,c'), ]) def test_cut(value, delimiter, fields, expected): """ Given: Case 1: A-B-C-D-E to split by - from char 1 to 5 Case 2: a,ב,c to split by , from char 2 to 3 When: Running Cut Then: Case 1: Ensure A-E is returned Case 2: Ensure ב,c is returned """ assert cut(value, fields, delimiter) == expected
22.25
61
0.558052
329062c006761cb11d903f71c24e59c1e35e6910
3,731
py
Python
extractTool/extractTool/similar.py
corneliazy/Geosoftware2
8604c79c58a61b84c602f16b5f1e74e30dfcbd0e
[ "MIT" ]
null
null
null
extractTool/extractTool/similar.py
corneliazy/Geosoftware2
8604c79c58a61b84c602f16b5f1e74e30dfcbd0e
[ "MIT" ]
47
2018-11-13T13:55:01.000Z
2019-09-16T13:38:11.000Z
extractTool/extractTool/similar.py
corneliazy/Geosoftware2
8604c79c58a61b84c602f16b5f1e74e30dfcbd0e
[ "MIT" ]
4
2018-11-27T12:36:51.000Z
2020-10-14T18:07:04.000Z
import math import detailebenen import click # import typ # Beispielkoordinaten # bbox1 = [5.8663155, 47.270111, 15.041932 , 55.099159] # bbox2 = [7.5234, 52.0326, 7.7556, 52.152] # def mastersim(filepath): # bbox1 = detailebenen(filepath) blabla Hier muessen die Bboxen berechet werden # bbox2 = detailebee(filepath) blabla also detailebenen Aufrufen # sim = aehnlickeit(bbox1, bbox2) # Hier muss typ.py # input1 = typ.getTyp(filepath) # input2 = typ.getTyp(filepath) # whatDataType(input1, input2, sim) """returns the new calculated similarity score :param input1: filepath from a file :param input2: filepath from a file :param imput3: similarity score from two bounding boxes """ def whatDataType(input1, input2, sim): if input1 == "raster" and input2 == "raster": click.echo("These files are rasterdata") return sim if input1 == "vector" and input2 == "vector": click.echo("These files are vectordata") return sim if input1 == "raster" and input2 == "vector" or input1 == "vector" and input2 == "raster": click.echo("These files are not the same datatype") sim = sim*5/4 if sim > 1: sim = 1 return sim """ Function to calculate the similarity score :param bbox1: Bounding Box from a file :param bbox2: Bounding Box from a file :returns: similarity score from the two Bounding Boxes """ def aehnlickeit (bbox1,bbox2): if isinstance(bbox1[0], float) and isinstance(bbox1[1], float) and isinstance(bbox1[2], float) and isinstance(bbox1[3], float): if isinstance(bbox2[0], float) and isinstance(bbox2[1], float) and isinstance(bbox2[2], float) and isinstance(bbox2[3], float): if distance(bbox1,bbox2) < 20000: simdis = distance(bbox1,bbox2)/20000 else: simdis = 1 if abs(area(bbox1) - area(bbox2)) < 1000000: simA = (abs(area(bbox1) - area(bbox2)))/1000000 else: simA = 1 sim = (2 * simdis + simA)/3 print(sim) return sim else: return None """ Function to calculate the mean latitude :param list: :returns: the mean Latitude """ def meanLatitude (list): lat = (list[3]+list[1])/2 return lat """ Function to calculate the mean longitude :param list: :returns: the mean Longitude """ def meanLongitude (list): lon = (list[2]+list[0])/2 return lon """ Function to calculate the latitude :param list: :returns: the Latitude """ def width (list): x = (list[2]-list[0])*111.3 * (math.cos(meanLatitude(list)*math.pi/180)) return x """ Function to calculate the mean longitude :param list: :returns: the longitude """ def length (list): y =(list[3]-list[1])*111.3 return y """ Function to calculate area :param list: :returns: the area """ def area (list): A = width(list) * length(list) return A """ auxiliary calculation :param bbox1: Bounding Box from a file :param bbox2: Bounding Box from a file :returns: the cosinus """ def lawOfCosines(bbox1,bbox2): cos = math.sin((meanLatitude(bbox1) * math.pi/180))*math.sin((meanLatitude(bbox2)*math.pi/180)) + math.cos((meanLatitude(bbox1)*math.pi/180)) * math.cos((meanLatitude(bbox2)*math.pi/180)) * math.cos((meanLongitude(bbox1)*math.pi/180)-(meanLongitude(bbox2)*math.pi/180)) return cos """ function to calculate the distace between two Bounding Boxes :param bbox1: Bounding Box from a file :param bbox2: Bounding Box from a file :returns: the distance """ def distance(bbox1,bbox2): dist = math.acos(lawOfCosines(bbox1,bbox2)) * 6378.388 return dist if __name__ == '__main__': aehnlickeit(bbox1, bbox2)
28.480916
273
0.654248
08c0a7cb786a0eb7250f9d1fe3bd7eb0533d2522
600
py
Python
0009palindrome-number.py
meat00/my-leetcode-python
8312de396b29e1d6dd54a65f87fa0511eb400faa
[ "MIT" ]
null
null
null
0009palindrome-number.py
meat00/my-leetcode-python
8312de396b29e1d6dd54a65f87fa0511eb400faa
[ "MIT" ]
null
null
null
0009palindrome-number.py
meat00/my-leetcode-python
8312de396b29e1d6dd54a65f87fa0511eb400faa
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 # -*- coding: utf-8 -*- class Solution(): def isPalindrome(self, x: int) -> bool: ''' 注意特殊情况 1. x小于0 2. 最后一位为0 3. x为0 ''' if x < 0 or (x % 10 == 0 and x != 0): return False rev = 0 while x > rev: rev = rev * 10 + x % 10 x = x // 10 print("rev:%d,x:%d" %(rev, x)) return x == rev or rev // 10 == x if __name__ == "__main__": s = Solution() test = [0, 121, 10, -121] for x in test: ret = s.isPalindrome(x) print(ret)
22.222222
45
0.416667
de3b2bf4d4c0e709ae15751a616c74112bddc8e9
1,804
py
Python
resources/mechanics_lib/Ant.py
PRECISE/ROSLab
2a6a295b71d4c73bc5c6ae2ec0330274afa31d0d
[ "Apache-2.0" ]
7
2016-01-20T02:33:00.000Z
2021-02-04T04:06:57.000Z
resources/mechanics_lib/Ant.py
PRECISE/ROSLab
2a6a295b71d4c73bc5c6ae2ec0330274afa31d0d
[ "Apache-2.0" ]
null
null
null
resources/mechanics_lib/Ant.py
PRECISE/ROSLab
2a6a295b71d4c73bc5c6ae2ec0330274afa31d0d
[ "Apache-2.0" ]
3
2016-10-05T07:20:30.000Z
2017-11-20T10:36:50.000Z
from api.component import Component class Ant(Component): def defComponents(self): self.addSubcomponent("brain", "Brains", inherit=True, prefix=None) self.addSubcomponent("front", "LegPair", inherit=True, prefix=None) self.addSubcomponent("back", "LegPair", inherit=True, prefix=None) def defParameters(self): self.delParameter("width") def defConstraints(self): self.addConstraint(("front", "width"), ("brain", "servo"), "x[0].getParameter('width') + \ x[1].getParameter('motorheight') * 2") self.addConstraint(("back", "width"), ("brain", "servo"), "x[0].getParameter('width') + \ x[1].getParameter('motorheight') * 2") def defConnections(self): self.addConnection(("brain", "botright"), ("front", "topedge.1"), "Fold", angle=-180) self.addConnection(("brain", "topleft"), ("back", "topedge.1"), "Fold", angle=-180) self.addConnection(("front", "botedge.2"), ("back", "topedge.3"), "Tab", name="tabfront", depth=9) self.addConnection(("back", "botedge.2"), ("front", "topedge.3"), "Tab", name="tabback", depth=9) if __name__ == "__main__": f = Ant() f.toYaml("output/ant.yaml") from utils.dimensions import tgy1370a, proMini f.setParameter("servo", tgy1370a) f.setParameter("brain", proMini) f.setParameter("length", 48) f.setParameter("height", 25) f.setParameter("leg.beamwidth", 10) f.makeOutput("output/ant", display=True)
37.583333
101
0.517738
dec08e4b05b41dd81d160d7e41ed3c728b977af9
1,383
py
Python
python/oneflow/utils/vision/__init__.py
wangyuyue/oneflow
0a71c22fe8355392acc8dc0e301589faee4c4832
[ "Apache-2.0" ]
3,285
2020-07-31T05:51:22.000Z
2022-03-31T15:20:16.000Z
python/oneflow/utils/vision/__init__.py
wangyuyue/oneflow
0a71c22fe8355392acc8dc0e301589faee4c4832
[ "Apache-2.0" ]
2,417
2020-07-31T06:28:58.000Z
2022-03-31T23:04:14.000Z
python/oneflow/utils/vision/__init__.py
wangyuyue/oneflow
0a71c22fe8355392acc8dc0e301589faee4c4832
[ "Apache-2.0" ]
520
2020-07-31T05:52:42.000Z
2022-03-29T02:38:11.000Z
""" Copyright 2020 The OneFlow Authors. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from oneflow.utils.vision import datasets from oneflow.utils.vision import transforms _image_backend = "PIL" def set_image_backend(backend): """ Specifies the package used to load images. Args: backend (string): Name of the image backend. one of {'PIL', 'accimage'}. The :mod:`accimage` package uses the Intel IPP library. It is generally faster than PIL, but does not support as many operations. """ global _image_backend if backend not in ["PIL", "accimage"]: raise ValueError( "Invalid backend '{}'. Options are 'PIL' and 'accimage'".format(backend) ) _image_backend = backend def get_image_backend(): """ Gets the name of the package used to load images """ return _image_backend
32.162791
84
0.710774
72181adc745c56619ee60682e9432eea3a374283
92
py
Python
2015/02/nurse-injury-rates/graphic_config.py
nprapps/graphics-archive
97b0ef326b46a959df930f5522d325e537f7a655
[ "FSFAP" ]
14
2015-05-08T13:41:51.000Z
2021-02-24T12:34:55.000Z
2015/02/nurse-injury-rates/graphic_config.py
nprapps/graphics-archive
97b0ef326b46a959df930f5522d325e537f7a655
[ "FSFAP" ]
null
null
null
2015/02/nurse-injury-rates/graphic_config.py
nprapps/graphics-archive
97b0ef326b46a959df930f5522d325e537f7a655
[ "FSFAP" ]
7
2015-04-04T04:45:54.000Z
2021-02-18T11:12:48.000Z
#!/usr/bin/env python COPY_GOOGLE_DOC_KEY = '1assIFoHbgfYcQ-OdFmm2q7ia2VaGQwrdZ5NmhoKImOk'
23
68
0.836957
a0f19af25be558d43e8977913bf66c771223f953
1,121
py
Python
Lab_02/fib.py
SadequrRahman/advance-SoC
35da93adfcdb1b4ec740cb44ffc54d9c8cc7adc4
[ "BSD-4-Clause-UC" ]
null
null
null
Lab_02/fib.py
SadequrRahman/advance-SoC
35da93adfcdb1b4ec740cb44ffc54d9c8cc7adc4
[ "BSD-4-Clause-UC" ]
null
null
null
Lab_02/fib.py
SadequrRahman/advance-SoC
35da93adfcdb1b4ec740cb44ffc54d9c8cc7adc4
[ "BSD-4-Clause-UC" ]
null
null
null
# # Copyright (C) 2019 Mohammad Sadequr Rahman <[email protected]> # # This file is part of Advance SoC Design Lab Soultion. # # SoC Design Lab Soultion can not be copied and/or distributed without the express # permission of Mohammad Sadequr Rahman # # File: fib.py # This is a pymtl fibonacci gloden algorithm implementation in pymtl3. # # Outputs: # out -> output of the block. contain fibonacci result fo 'n' # from pymtl3 import * class add(Component): def construct(s, Type): s.inl = InPort (Type) s.inr = InPort (Type) s.out = OutPort(Type) @s.update def add(): s.out = s.inl + s.inr class Fib( Component ): def construct(s, dType, n): #s.in_ = InPort(dType) s.out = OutPort(dType) if n < 2 : s.out //= dType(n) return else: s.t1 = n - 1 s.t2 = n - 2 s.l = Fib(dType, s.t1) s.r = Fib(dType, s.t2) s.f = add(dType) s.f.inl //= s.l.out s.f.inr //= s.r.out s.f.out //= s.out return
21.557692
82
0.540589
261e85d58df7266cfd7e58e24f7b48125975f239
1,171
py
Python
chemolab/core/unicode.py
MeleiDigitalMedia/ChemoLab
b27421a836d76de88b23845f6c808d4429925702
[ "MIT" ]
null
null
null
chemolab/core/unicode.py
MeleiDigitalMedia/ChemoLab
b27421a836d76de88b23845f6c808d4429925702
[ "MIT" ]
null
null
null
chemolab/core/unicode.py
MeleiDigitalMedia/ChemoLab
b27421a836d76de88b23845f6c808d4429925702
[ "MIT" ]
null
null
null
class SubScript(): """Creates an instance of SubScript""" def __init__(self): self.NUM_0 = u'\u2080' self.NUM_1 = u'\u2081' self.NUM_2 = u'\u2082' self.NUM_3 = u'\u2083' self.NUM_4 = u'\u2084' self.NUM_5 = u'\u2085' self.NUM_6 = u'\u2086' self.NUM_7 = u'\u2087' self.NUM_8 = u'\u2088' self.NUM_9 = u'\u2089' self.PLUS = u'\u208a' self.MINUS = u'\u208b' self.EQUALS = u'\u208c' self.L_PAR = u'\u208d' self.R_PAR = u'\u208e' class SuperScript(): """Creates an instance of SuperScript""" def __init__(self): self.NUM_0 = u'\u2070' self.NUM_1 = u'\u00b9' self.NUM_2 = u'\u00b2' self.NUM_3 = u'\u00b3' self.NUM_4 = u'\u2074' self.NUM_5 = u'\u2075' self.NUM_6 = u'\u2076' self.NUM_7 = u'\u2077' self.NUM_8 = u'\u2078' self.NUM_9 = u'\u2079' self.PLUS = u'\u207a' self.MINUS = u'\u207b' self.EQUALS = u'\u207c' self.L_PAR = u'\u207d' self.R_PAR = u'\u207e'
31.648649
45
0.485056
26bb10f45a5b4f95ec9fcb604d781837ada01030
345
py
Python
init.py
two-doges/tpf
a98f68fba40b3f07ce0ef14f6ca982e915ee3e07
[ "MIT" ]
2
2018-03-04T13:36:22.000Z
2018-03-04T13:36:33.000Z
init.py
two-doges/tpf
a98f68fba40b3f07ce0ef14f6ca982e915ee3e07
[ "MIT" ]
null
null
null
init.py
two-doges/tpf
a98f68fba40b3f07ce0ef14f6ca982e915ee3e07
[ "MIT" ]
null
null
null
import os import sys sys.path.append("..") import dataoper def initall(): pat = "devhost" fp = open("devdata.py","w+") s = str(os.getcwd()) fp.write('dir = '+'"'+s+'/'+pat+'"'+'\n') fp.write('pos = '+'"'+s+'/'+"devdata"+'"') dataoper.make_table(pat) if __name__ == "__main__": dataoper.delete_table() initall()
20.294118
46
0.553623
90320414d5545b38764cd72587480188bd9c886c
422
py
Python
python/en/_numpy/organize_this/test_numpy.Quickstart_tutorial-03.py
aimldl/coding
70ddbfaa454ab92fd072ee8dc614ecc330b34a70
[ "MIT" ]
null
null
null
python/en/_numpy/organize_this/test_numpy.Quickstart_tutorial-03.py
aimldl/coding
70ddbfaa454ab92fd072ee8dc614ecc330b34a70
[ "MIT" ]
null
null
null
python/en/_numpy/organize_this/test_numpy.Quickstart_tutorial-03.py
aimldl/coding
70ddbfaa454ab92fd072ee8dc614ecc330b34a70
[ "MIT" ]
null
null
null
""" test_numpy.Quickstart_tutorial-03.py * References Quickstart tutorial https://docs.scipy.org/doc/numpy/user/quickstart.html TODO: Start from A frequent error consists in calling array with multiple numeric """ import numpy as np a = np.array( [2,3,4] ) """ >>> a array([2, 3, 4]) >>> a.dtype dtype('int64') >>> a.dtype.name 'int64' """ b = np.array( [1.2, 3.5, 5.1] ) """ >>> b.dtype dtype('float64') """
14.066667
65
0.63981
840e3e92339d6c3635dffee4c74621caca209267
94
py
Python
python_lessons/freecodecamp_python/014_dict_object_d_for_in_print.py
1986MMartin/coding-sections-markus
e13be32e5d83e69250ecfb3c76a04ee48a320607
[ "Apache-2.0" ]
null
null
null
python_lessons/freecodecamp_python/014_dict_object_d_for_in_print.py
1986MMartin/coding-sections-markus
e13be32e5d83e69250ecfb3c76a04ee48a320607
[ "Apache-2.0" ]
null
null
null
python_lessons/freecodecamp_python/014_dict_object_d_for_in_print.py
1986MMartin/coding-sections-markus
e13be32e5d83e69250ecfb3c76a04ee48a320607
[ "Apache-2.0" ]
null
null
null
d = dict() d['quincy'] = 1 d['beau'] = 5 d['kris'] = 9 for (k,i) in d.items(): print(k, i)
15.666667
23
0.478723
4b974cf32caa7c6b6283e803dcfb8044ee9063ed
9,140
py
Python
SAC2018/SAC.py
Wen2chao/RL-Algorithm-
6cb31f2e02a90fceef498c7ee46a4d06eb976005
[ "MIT" ]
19
2020-06-09T07:48:10.000Z
2022-03-27T04:52:36.000Z
SAC2018/SAC.py
Wen2chao/RL-Algorithm-
6cb31f2e02a90fceef498c7ee46a4d06eb976005
[ "MIT" ]
1
2020-09-17T07:39:35.000Z
2021-08-02T02:31:52.000Z
SAC2018/SAC.py
Wen2chao/RL-Algorithm-
6cb31f2e02a90fceef498c7ee46a4d06eb976005
[ "MIT" ]
12
2020-03-28T08:19:26.000Z
2022-03-21T11:08:08.000Z
import gym import torch import random import torch.nn as nn import collections import numpy as np import torch.nn.functional as F import torch.optim as optim import matplotlib.pyplot as plt from torch.distributions import Normal class ReplayBeffer(): def __init__(self, buffer_maxlen): self.buffer = collections.deque(maxlen=buffer_maxlen) def push(self, data): self.buffer.append(data) def sample(self, batch_size): state_list = [] action_list = [] reward_list = [] next_state_list = [] done_list = [] batch = random.sample(self.buffer, batch_size) for experience in batch: s, a, r, n_s, d = experience # state, action, reward, next_state, done state_list.append(s) action_list.append(a) reward_list.append(r) next_state_list.append(n_s) done_list.append(d) return torch.FloatTensor(state_list).to(device), \ torch.FloatTensor(action_list).to(device), \ torch.FloatTensor(reward_list).unsqueeze(-1).to(device), \ torch.FloatTensor(next_state_list).to(device), \ torch.FloatTensor(done_list).unsqueeze(-1).to(device) def buffer_len(self): return len(self.buffer) # Value Net class ValueNet(nn.Module): def __init__(self, state_dim, edge=3e-3): super(ValueNet, self).__init__() self.linear1 = nn.Linear(state_dim, 256) self.linear2 = nn.Linear(256, 256) self.linear3 = nn.Linear(256, 1) self.linear3.weight.data.uniform_(-edge, edge) self.linear3.bias.data.uniform_(-edge, edge) def forward(self, state): x = F.relu(self.linear1(state)) x = F.relu(self.linear2(x)) x = self.linear3(x) return x # Soft Q Net class SoftQNet(nn.Module): def __init__(self, state_dim, action_dim, edge=3e-3): super(SoftQNet, self).__init__() self.linear1 = nn.Linear(state_dim + action_dim, 256) self.linear2 = nn.Linear(256, 256) self.linear3 = nn.Linear(256, 1) self.linear3.weight.data.uniform_(-edge, edge) self.linear3.bias.data.uniform_(-edge, edge) def forward(self, state, action): x = torch.cat([state, action], 1) x = F.relu(self.linear1(x)) x = F.relu(self.linear2(x)) x = self.linear3(x) return x # Policy Net class PolicyNet(nn.Module): def __init__(self, state_dim, action_dim, log_std_min=-20, log_std_max=2, edge=3e-3): super(PolicyNet, self).__init__() self.log_std_min = log_std_min self.log_std_max = log_std_max self.linear1 = nn.Linear(state_dim, 256) self.linear2 = nn.Linear(256, 256) self.mean_linear = nn.Linear(256, action_dim) self.mean_linear.weight.data.uniform_(-edge, edge) self.mean_linear.bias.data.uniform_(-edge, edge) self.log_std_linear = nn.Linear(256, action_dim) self.log_std_linear.weight.data.uniform_(-edge, edge) self.log_std_linear.bias.data.uniform_(-edge, edge) def forward(self, state): x = F.relu(self.linear1(state)) x = F.relu(self.linear2(x)) mean = self.mean_linear(x) log_std = self.log_std_linear(x) log_std = torch.clamp(log_std, self.log_std_min, self.log_std_max) return mean, log_std def action(self, state): state = torch.FloatTensor(state).to(device) mean, log_std = self.forward(state) std = log_std.exp() normal = Normal(mean, std) z = normal.sample() action = torch.tanh(z).detach().cpu().numpy() return action # Use re-parameterization tick def evaluate(self, state, epsilon=1e-6): mean, log_std = self.forward(state) std = log_std.exp() normal = Normal(mean, std) noise = Normal(0, 1) z = noise.sample() action = torch.tanh(mean + std * z.to(device)) log_prob = normal.log_prob(mean + std * z.to(device)) - torch.log(1 - action.pow(2) + epsilon) return action, log_prob class SAC: def __init__(self, env, gamma, tau, buffer_maxlen, value_lr, q_lr, policy_lr): self.env = env self.state_dim = env.observation_space.shape[0] self.action_dim = env.action_space.shape[0] # hyperparameters self.gamma = gamma self.tau = tau # initialize networks self.value_net = ValueNet(self.state_dim).to(device) self.target_value_net = ValueNet(self.state_dim).to(device) self.q1_net = SoftQNet(self.state_dim, self.action_dim).to(device) self.q2_net = SoftQNet(self.state_dim, self.action_dim).to(device) self.policy_net = PolicyNet(self.state_dim, self.action_dim).to(device) # Load the target value network parameters for target_param, param in zip(self.target_value_net.parameters(), self.value_net.parameters()): target_param.data.copy_(self.tau * param + (1 - self.tau) * target_param) # Initialize the optimizer self.value_optimizer = optim.Adam(self.value_net.parameters(), lr=value_lr) self.q1_optimizer = optim.Adam(self.q1_net.parameters(), lr=q_lr) self.q2_optimizer = optim.Adam(self.q2_net.parameters(), lr=q_lr) self.policy_optimizer = optim.Adam(self.policy_net.parameters(), lr=policy_lr) # Initialize thebuffer self.buffer = ReplayBeffer(buffer_maxlen) def get_action(self, state): action = self.policy_net.action(state) return action def update(self, batch_size): state, action, reward, next_state, done = self.buffer.sample(batch_size) new_action, log_prob = self.policy_net.evaluate(state) # V value loss value = self.value_net(state) new_q1_value = self.q1_net(state, new_action) new_q2_value = self.q2_net(state, new_action) next_value = torch.min(new_q1_value, new_q2_value) - log_prob value_loss = F.mse_loss(value, next_value.detach()) # Soft q loss q1_value = self.q1_net(state, action) q2_value = self.q2_net(state, action) target_value = self.target_value_net(next_state) target_q_value = reward + done * self.gamma * target_value q1_value_loss = F.mse_loss(q1_value, target_q_value.detach()) q2_value_loss = F.mse_loss(q2_value, target_q_value.detach()) # Policy loss policy_loss = (log_prob - torch.min(new_q1_value, new_q2_value)).mean() # Update Policy self.policy_optimizer.zero_grad() policy_loss.backward() self.policy_optimizer.step() # Update v self.value_optimizer.zero_grad() value_loss.backward() self.value_optimizer.step() # Update Soft q self.q1_optimizer.zero_grad() self.q2_optimizer.zero_grad() q1_value_loss.backward() q2_value_loss.backward() self.q1_optimizer.step() self.q2_optimizer.step() # Update target networks for target_param, param in zip(self.target_value_net.parameters(), self.value_net.parameters()): target_param.data.copy_(self.tau * param + (1 - self.tau) * target_param) def main(env, agent, Episode, batch_size): Return = [] action_range = [env.action_space.low, env.action_space.high] for episode in range(Episode): score = 0 state = env.reset() for i in range(300): action = agent.get_action(state) # action output range[-1,1],expand to allowable range action_in = action * (action_range[1] - action_range[0]) / 2.0 + (action_range[1] + action_range[0]) / 2.0 next_state, reward, done, _ = env.step(action_in) done_mask = 0.0 if done else 1.0 agent.buffer.push((state, action, reward, next_state, done_mask)) state = next_state score += reward if done: break if agent.buffer.buffer_len() > 500: agent.update(batch_size) print("episode:{}, Return:{}, buffer_capacity:{}".format(episode, score, agent.buffer.buffer_len())) Return.append(score) score = 0 env.close() plt.plot(Return) plt.ylabel('Return') plt.xlabel("Episode") plt.grid(True) plt.show() if __name__ == '__main__': env = gym.make("Pendulum-v0") device = torch.device("cuda:1" if torch.cuda.is_available() else "cpu") # Params tau = 0.01 gamma = 0.99 q_lr = 3e-3 value_lr = 3e-3 policy_lr = 3e-3 buffer_maxlen = 50000 Episode = 100 batch_size = 128 agent = SAC(env, gamma, tau, buffer_maxlen, value_lr, q_lr, policy_lr) main(env, agent, Episode, batch_size)
33.726937
121
0.609409
4b165c49280c7f812571921ae83d0c505571bf4d
10,637
py
Python
GZP_GTO_QGIS/INSTALLATION/GeoTaskOrganizer/gto_remote.py
msgis/swwat-gzp-template
080afbe9d49fb34ed60ba45654383d9cfca01e24
[ "MIT" ]
3
2019-06-18T15:28:09.000Z
2019-07-11T07:31:45.000Z
GZP_GTO_QGIS/INSTALLATION/GeoTaskOrganizer/gto_remote.py
msgis/swwat-gzp-template
080afbe9d49fb34ed60ba45654383d9cfca01e24
[ "MIT" ]
2
2019-07-11T14:03:25.000Z
2021-02-08T16:14:04.000Z
GZP_GTO_QGIS/INSTALLATION/GeoTaskOrganizer/gto_remote.py
msgis/swwat-gzp-template
080afbe9d49fb34ed60ba45654383d9cfca01e24
[ "MIT" ]
1
2019-06-12T11:07:37.000Z
2019-06-12T11:07:37.000Z
#!/usr/bin/python # -*- coding: utf-8 -*- from builtins import str from PyQt5.QtCore import Qt,QObject,QFileSystemWatcher #from PyQt5.QtGui import * import os import json import io from qgis.core import QgsProject,QgsFeatureRequest from .gto_info import gtoInfo class gtoRemote(QObject): def __init__(self, gtomain, parent = None): try: super(gtoRemote, self).__init__(parent) self.gtomain = gtomain self.iface = gtomain.iface self.debug = gtomain.debug self.info = gtoInfo(self) self.fs_watcher =None if 'remote_watch_file' in gtomain.settings: remote_watch_path = gtomain.settings.get('remote_watch_file',None) if remote_watch_path is not None and remote_watch_path != "": remote_watch_path = self.gtomain.helper.getFilePath(remote_watch_path) self.remote_watch_file = os.path.basename(remote_watch_path) self.remote_watch_dir = os.path.dirname(remote_watch_path) if self.debug: self.info.log("Watching:",self.remote_watch_dir) if not os.path.exists(self.remote_watch_dir): os.makedirs(self.remote_watch_dir) if self.debug: self.info.log("Created:",self.remote_watch_dir) self.paths = [self.remote_watch_dir] self.fs_watcher = QFileSystemWatcher(self.paths) #if file already exists self.directory_changed(self.paths[0]) self.fs_watcher.directoryChanged.connect(self.directory_changed) self.fs_watcher.fileChanged.connect(self.file_changed) except Exception as e: self.info.err(e) def unload(self): try: if self.fs_watcher is not None: self.fs_watcher.directoryChanged.disconnect() self.fs_watcher.fileChanged.disconnect() self.fs_watcher = None except Exception as e: self.info.err(e) def directory_changed(self,path): try: if self.debug: self.info.log('Directory Changed: %s' % path) for f in os.listdir(path): #self.info.log(os.listdir(path)) #if (self.debug and f.lower().endswith(".json")) or f.lower() == self.remote_watch_file.lower(): if f.lower() == self.remote_watch_file.lower(): if self.debug: self.info.log("Execute",f.lower()) self.fs_watcher.blockSignals(True) self.excuteCommand(path,f) self.fs_watcher.blockSignals(False) except Exception as e: self.info.err(e) def file_changed(self,path): try: if self.debug: self.info.log('File Changed: %s' % path) except Exception as e: self.info.err(e) def excuteCommand(self,path,f): try: if self.debug: self.info.log('excute command') filename = path + '/' + f #time.sleep(0.5) f = io.open(filename, encoding='utf-8') jdata = json.load(f) f.close() res = True for cmd in jdata['commands']: if self.debug: self.info.log(cmd) method = getattr(self, cmd['ecommand']) res = res and (method(self.gtomain, self.debug, **cmd['config'])) if self.debug: self.info.log('result:', res) if res: os.remove(filename) except Exception as e: self.info.err(e) def writeRemoteFile(self,jdata,prefix = ''): try: if self.debug: self.info.log('writeRemoteFile:', 'data:', jdata) remotefile = self.gtomain.settings['remote_file'] remotefile = self.gtomain.helper.getFilePath(remotefile, True) remotefile = '%s%s' % (remotefile,prefix) if self.debug: self.info.log("remotefile",remotefile) # write the file # from io import StringIO # io = StringIO() # json.dump(jdata,io,ensure_ascii=False, sort_keys=True,indent=4) # io.close() with open(remotefile, 'w',encoding='utf8') as outfile: sort =True #simplejson.dump(jdata, outfile,ensure_ascii=False, sort_keys=sort,indent=4)#,encoding='utf8')#.encode('utf8') json.dump(jdata, outfile, ensure_ascii=False, sort_keys=sort, indent=4) # ,encoding='utf8')#.encode('utf8') # import pickle # with open(remotefile, 'wb') as f: # pickle.dump(jdata,f) #activate/start remote app if self.debug: self.info.log('writeRemoteFile:', 'settings:', self.gtomain.settings) remote_app_file = self.gtomain.settings['remote_app_file'] remote_app_title = self.gtomain.settings['remote_app_title'] if os.name == 'nt': try: from .gto_windows import ActivateApp ActivateApp(self.gtomain, self.debug, remote_app_title, remote_app_file) except Exception as e: self.info.err(e) else: os.startfile(remote_app_file) except Exception as e: self.info.err(e) def getLayerByName(self,layername): try: layers = QgsProject.instance().mapLayersByName(layername) if layers: return layers[0]# duplicte names => take the first else: return None except Exception as e: self.info.err(e) def getFeatures(self, gtoobj, debug, **kwargs): try: if self.debug: self.info.log('getFeatures:', 'parameters:', kwargs) layername = kwargs['objectclass'] layer = self.getLayerByName(layername) request = QgsFeatureRequest() if 'whereclause' in kwargs: whereclause = kwargs['whereclause'] request.setFilterExpression(whereclause) elif 'attribute' in kwargs: attribute = kwargs['attribute'] values = kwargs['data'] expr_in = '' for v in values: expr_in = expr_in + '%s ,' % str(v) expr_in = expr_in[:-1] expr = '"' + attribute + '" IN (%s)' % expr_in if self.debug: self.info.log("expr: %s" % expr) request.setFilterExpression(expr) features = layer.getFeatures(request) ids = [f.id() for f in features] if self.debug: self.info.log("res from request ids:",layer, ids) return layer, ids except Exception as e: gtoobj.info.err(e) def ZOOMTOFEATURESET(self,gtoobj,debug,**kwargs): try: scale = kwargs.get('scale',0) iface = gtoobj.iface layer, ids = self.getFeatures(gtoobj,debug,**kwargs) iface.setActiveLayer(layer) prj = QgsProject.instance() prj.layerTreeRoot().findLayer(layer.id()).setItemVisibilityCheckedParentRecursive(True) #legend.setCurrentLayer(layer) #legend.setLayerVisible(layer, True) layer.selectByIds(ids) iface.mapCanvas().zoomToSelected() if scale > 0: iface.mapCanvas().zoomScale(scale) return True except Exception as e: gtoobj.info.err(e) def SETSELECTSET(self,gtoobj,debug,**kwargs): try: iface = gtoobj.iface layer, ids = self.getFeatures(gtoobj,debug,**kwargs) layer.removeSelection() layer.selectByIds(ids) self.iface.mapCanvas().refresh() return True except Exception as e: gtoobj.info.err(e) def GETCOORDINATE(self,gtoobj,debug,**kwargs): try: objclass = kwargs['objectclass'] id = kwargs['id'] esubcommand = kwargs['esubcommand'] iface = gtoobj.iface from qgis.gui import QgsMapToolEmitPoint # create tool prevTool = iface.mapCanvas().mapTool() curTool = QgsMapToolEmitPoint(iface.mapCanvas()) def on_click(coordinate, clickedMouseButton): if debug: gtoobj.info.log("Coordinate:", coordinate) if clickedMouseButton == Qt.LeftButton: if esubcommand == 'GETCOORDINATE_ID': #jdata = {"commands": [{"ecommand": "SETCOORDINATE", "config": {"esubcommand": "SETCOORDINATE_ID","objectclass": objclass.encode('utf8'),"id":id, "x": round( coordinate.x(),3),"y":round(coordinate.y(),3)}}]} jdata = {"commands": [{"ecommand": "SETCOORDINATE", "config": {"esubcommand": "SETCOORDINATE_ID", "objectclass": objclass, "id": id, "x": round(coordinate.x(), 3), "y": round(coordinate.y(), 3)}}]} self.writeRemoteFile(jdata) if debug: self.info.log("Set prev tool:", prevTool.toolName()) if prevTool is curTool: iface.mapCanvas().setMapTool(None) else: iface.mapCanvas().setMapTool(prevTool) else: if debug: self.info.log('Unknown esubcommand:',esubcommand) def tool_changed(tool): # another tool was activated iface.mapCanvas().mapToolSet.disconnect(tool_changed) #curTool.deleteLater() curTool.canvasClicked.connect(on_click) iface.mapCanvas().setMapTool(curTool) iface.mapCanvas().mapToolSet.connect(tool_changed) return True except Exception as e: gtoobj.info.err(e) def getSelectedFeatures(self,gtoobj, debug, layer,attribute): try: data = [] for f in layer.selectedFeatures(): val = f[attribute] try: if int(val) == val: val = int(val) except: pass data.append("%s" % str(val)) return data except Exception as e: gtoobj.info.err(e)
42.043478
231
0.540378
4b2694efc137f8ec6d32dfa08a19037c42e42cdd
3,457
py
Python
accounts/forms.py
JanakiRaman-2002/Arre-yaar
c0b44ca1f8884a09116241dcd0bf7cfcee3b785d
[ "Apache-2.0" ]
null
null
null
accounts/forms.py
JanakiRaman-2002/Arre-yaar
c0b44ca1f8884a09116241dcd0bf7cfcee3b785d
[ "Apache-2.0" ]
null
null
null
accounts/forms.py
JanakiRaman-2002/Arre-yaar
c0b44ca1f8884a09116241dcd0bf7cfcee3b785d
[ "Apache-2.0" ]
null
null
null
from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm,AuthenticationForm from django.forms.widgets import TextInput, Textarea from .models import * class UserForm(forms.Form): # class Meta: # model = User # fields = ('username','email','password1','password2') username = forms.CharField(max_length=50, required=True, widget=forms.TextInput( attrs= { 'class': "u-border-1 u-border-grey-30 u-custom-font u-font-montserrat u-input u-input-rectangle u-radius-17 u-white", 'placeholder': "Enter an Username", 'id':"name-e91f", 'name':"usernameda" } )) email = forms.CharField(max_length=50, required=True, widget = forms.TextInput( attrs = { 'class':"u-border-1 u-border-grey-30 u-custom-font u-font-montserrat u-input u-input-rectangle u-radius-17 u-white", 'name':"email", 'id':"email-e91f", 'placeholder':"Enter a valid email address", 'type':"email" } )) password1 = forms.CharField(required=True, widget = forms.PasswordInput( attrs= { 'placeholder':"Enter a password", 'id':"text-e114", 'name':"pass1", 'class':"u-border-1 u-border-grey-30 u-custom-font u-font-montserrat u-input u-input-rectangle u-radius-17 u-white" } )) password2 = forms.CharField(required=True, widget = forms.PasswordInput( attrs= { 'placeholder':"Confirm Password", 'id':"text-e114", 'name':"pass1", 'class':"u-border-1 u-border-grey-30 u-custom-font u-font-montserrat u-input u-input-rectangle u-radius-17 u-white" } )) class CustomerForm(forms.Form): address = forms.CharField(required=True, widget = forms.Textarea( attrs= { 'rows':"4", 'cols':"50", 'id':"textarea-6b48", 'name':"address", 'class':"u-border-1 u-border-grey-30 u-custom-font u-font-montserrat u-input u-input-rectangle u-radius-17 u-white", 'placeholder':'Enter Delivery Address' } )) phone_no = forms.CharField(required = True, widget= forms.TextInput( attrs = { 'pattern':"\+?\d{0,3}[\s\(\-]?([0-9]{2,3})[\s\)\-]?([\s\-]?)([0-9]{3})[\s\-]?([0-9]{2})[\s\-]?([0-9]{2})", 'placeholder':"Enter your phone number", 'id':"phone-d55a", 'name':"phone", 'class':"u-border-1 u-border-grey-30 u-custom-font u-font-montserrat u-input u-input-rectangle u-radius-17 u-white" } )) class Loginform(AuthenticationForm): username = forms.CharField(widget = forms.TextInput( attrs = { 'placeholder':"Enter Username", 'id':"name-e91f", 'name':"usernameda", 'class':"u-border-1 u-border-grey-30 u-custom-font u-font-montserrat u-input u-input-rectangle u-radius-17 u-white", 'required':"required" })) password = forms.CharField(widget = forms.PasswordInput( attrs = { 'placeholder':"Enter Password", 'id':"text-6e34", 'name':"passwordda", 'class':"u-border-1 u-border-grey-30 u-custom-font u-font-montserrat u-input u-input-rectangle u-radius-17 u-white", 'required':"required" }))
41.650602
129
0.57304
8ad3d7138e5cc42b191ab7f7b90915eb7d6894bf
1,090
py
Python
research/cv/SRGAN/src/loss/psnr_loss.py
leelige/mindspore
5199e05ba3888963473f2b07da3f7bca5b9ef6dc
[ "Apache-2.0" ]
77
2021-10-15T08:32:37.000Z
2022-03-30T13:09:11.000Z
research/cv/SRGAN/src/loss/psnr_loss.py
leelige/mindspore
5199e05ba3888963473f2b07da3f7bca5b9ef6dc
[ "Apache-2.0" ]
3
2021-10-30T14:44:57.000Z
2022-02-14T06:57:57.000Z
research/cv/SRGAN/src/loss/psnr_loss.py
leelige/mindspore
5199e05ba3888963473f2b07da3f7bca5b9ef6dc
[ "Apache-2.0" ]
24
2021-10-15T08:32:45.000Z
2022-03-24T18:45:20.000Z
# Copyright 2021 Huawei Technologies Co., Ltd # # 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. # ============================================================================ """PSNRLOSS""" import mindspore.nn as nn class PSNRLoss(nn.Cell): """Loss for srresnet""" def __init__(self, generator): super(PSNRLoss, self).__init__() self.generator = generator self.pixel_criterion = nn.MSELoss() def construct(self, HR_img, LR_img): hr = HR_img sr = self.generator(LR_img) psnr_loss = self.pixel_criterion(hr, sr) return psnr_loss
35.16129
78
0.658716
6ae2efdb4e7a2f5616ad6b4dce2044e09d204517
3,293
py
Python
research/inference.py
jieming2002/models-quiz8
421dc407a10444cab4bd88c25599077acca96bdb
[ "Apache-2.0" ]
null
null
null
research/inference.py
jieming2002/models-quiz8
421dc407a10444cab4bd88c25599077acca96bdb
[ "Apache-2.0" ]
null
null
null
research/inference.py
jieming2002/models-quiz8
421dc407a10444cab4bd88c25599077acca96bdb
[ "Apache-2.0" ]
null
null
null
import argparse import os import numpy as np import tensorflow as tf from matplotlib import pyplot as plt from PIL import Image from utils import visualization_utils as vis_util from utils import label_map_util if tf.__version__ < '1.4.0': raise ImportError('Please upgrade your tensorflow installation to v1.4.* or later!') NUM_CLASSES = 5 def parse_args(check=True): parser = argparse.ArgumentParser() parser.add_argument('--output_dir', type=str, required=True) parser.add_argument('--dataset_dir', type=str, required=True) FLAGS, unparsed = parser.parse_known_args() return FLAGS, unparsed if __name__ == '__main__': FLAGS, unparsed = parse_args() PATH_TO_CKPT = os.path.join(FLAGS.output_dir, 'exported_graphs/frozen_inference_graph.pb') PATH_TO_LABELS = os.path.join(FLAGS.dataset_dir, 'labels_items.txt') detection_graph = tf.Graph() with detection_graph.as_default(): od_graph_def = tf.GraphDef() with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid: serialized_graph = fid.read() od_graph_def.ParseFromString(serialized_graph) tf.import_graph_def(od_graph_def, name='') label_map = label_map_util.load_labelmap(PATH_TO_LABELS) categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True) category_index = label_map_util.create_category_index(categories) def load_image_into_numpy_array(image): (im_width, im_height) = image.size return np.array(image.getdata()).reshape( (im_height, im_width, 3)).astype(np.uint8) test_img_path = os.path.join(FLAGS.dataset_dir, 'test.jpg') with detection_graph.as_default(): with tf.Session(graph=detection_graph) as sess: image_tensor = detection_graph.get_tensor_by_name('image_tensor:0') detection_boxes = detection_graph.get_tensor_by_name('detection_boxes:0') detection_scores = detection_graph.get_tensor_by_name('detection_scores:0') detection_classes = detection_graph.get_tensor_by_name('detection_classes:0') num_detections = detection_graph.get_tensor_by_name('num_detections:0') image = Image.open(test_img_path) image_np = load_image_into_numpy_array(image) image_np_expanded = np.expand_dims(image_np, axis=0) (boxes, scores, classes, num) = sess.run( [detection_boxes, detection_scores, detection_classes, num_detections], feed_dict={image_tensor: image_np_expanded}) print('skye boxes=', boxes) # scores[0][0] = 0.99 # Output.png 上面没有预测结果信息. 准确率太低?是的。最后的框是会有个准确率阈值的。 print('skye scores=',scores) print('skye classes=', classes) print('skye category_index=', category_index) image_np = vis_util.visualize_boxes_and_labels_on_image_array( image_np, np.squeeze(boxes), np.squeeze(classes).astype(np.int32), np.squeeze(scores), category_index, use_normalized_coordinates=True, line_thickness=8) plt.imsave(os.path.join(FLAGS.output_dir, 'output.png'), image_np)
41.1625
126
0.683875
0aa1c7468484eee02456915485470e6e25a46577
5,918
py
Python
tests/test_tokenization_bart.py
zyxdSTU/pytorch-pretrained-BERT
5ec89489dd66302023821f2d27e109861e9f593d
[ "Apache-2.0" ]
4
2021-01-15T20:20:47.000Z
2021-11-14T18:33:42.000Z
tests/test_tokenization_bart.py
yym6472/transformers
abd01205561e5caec167c1fbb20bccea24d7ba46
[ "Apache-2.0" ]
1
2021-09-15T09:20:01.000Z
2022-03-02T17:16:01.000Z
tests/test_tokenization_bart.py
yym6472/transformers
abd01205561e5caec167c1fbb20bccea24d7ba46
[ "Apache-2.0" ]
3
2021-04-26T08:01:16.000Z
2022-03-23T04:47:56.000Z
import json import os import unittest from transformers import BartTokenizer, BartTokenizerFast, BatchEncoding from transformers.file_utils import cached_property from transformers.testing_utils import require_torch from transformers.tokenization_roberta import VOCAB_FILES_NAMES from .test_tokenization_common import TokenizerTesterMixin class TestTokenizationBart(TokenizerTesterMixin, unittest.TestCase): tokenizer_class = BartTokenizer rust_tokenizer_class = BartTokenizerFast test_rust_tokenizer = True def setUp(self): super().setUp() vocab = [ "l", "o", "w", "e", "r", "s", "t", "i", "d", "n", "\u0120", "\u0120l", "\u0120n", "\u0120lo", "\u0120low", "er", "\u0120lowest", "\u0120newer", "\u0120wider", "<unk>", ] vocab_tokens = dict(zip(vocab, range(len(vocab)))) merges = ["#version: 0.2", "\u0120 l", "\u0120l o", "\u0120lo w", "e r", ""] self.special_tokens_map = {"unk_token": "<unk>"} self.vocab_file = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES["vocab_file"]) self.merges_file = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES["merges_file"]) with open(self.vocab_file, "w", encoding="utf-8") as fp: fp.write(json.dumps(vocab_tokens) + "\n") with open(self.merges_file, "w", encoding="utf-8") as fp: fp.write("\n".join(merges)) def get_tokenizer(self, **kwargs): kwargs.update(self.special_tokens_map) return self.tokenizer_class.from_pretrained(self.tmpdirname, **kwargs) def get_rust_tokenizer(self, **kwargs): kwargs.update(self.special_tokens_map) return BartTokenizerFast.from_pretrained(self.tmpdirname, **kwargs) def get_input_output_texts(self, tokenizer): return "lower newer", "lower newer" @cached_property def default_tokenizer(self): return BartTokenizer.from_pretrained("facebook/bart-large") @cached_property def default_tokenizer_fast(self): return BartTokenizerFast.from_pretrained("facebook/bart-large") @require_torch def test_prepare_seq2seq_batch(self): src_text = ["A long paragraph for summarization.", "Another paragraph for summarization."] tgt_text = [ "Summary of the text.", "Another summary.", ] expected_src_tokens = [0, 250, 251, 17818, 13, 39186, 1938, 4, 2] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: batch = tokenizer.prepare_seq2seq_batch( src_text, tgt_texts=tgt_text, max_length=len(expected_src_tokens), return_tensors="pt" ) self.assertIsInstance(batch, BatchEncoding) self.assertEqual((2, 9), batch.input_ids.shape) self.assertEqual((2, 9), batch.attention_mask.shape) result = batch.input_ids.tolist()[0] self.assertListEqual(expected_src_tokens, result) # Test that special tokens are reset # Test Prepare Seq @require_torch def test_seq2seq_batch_empty_target_text(self): src_text = ["A long paragraph for summarization.", "Another paragraph for summarization."] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: batch = tokenizer.prepare_seq2seq_batch(src_text, return_tensors="pt") # check if input_ids are returned and no labels self.assertIn("input_ids", batch) self.assertIn("attention_mask", batch) self.assertNotIn("labels", batch) self.assertNotIn("decoder_attention_mask", batch) @require_torch def test_seq2seq_batch_max_target_length(self): src_text = ["A long paragraph for summarization.", "Another paragraph for summarization."] tgt_text = [ "Summary of the text.", "Another summary.", ] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: batch = tokenizer.prepare_seq2seq_batch( src_text, tgt_texts=tgt_text, max_target_length=32, padding="max_length", return_tensors="pt" ) self.assertEqual(32, batch["labels"].shape[1]) # test None max_target_length batch = tokenizer.prepare_seq2seq_batch( src_text, tgt_texts=tgt_text, max_length=32, padding="max_length", return_tensors="pt" ) self.assertEqual(32, batch["labels"].shape[1]) @require_torch def test_seq2seq_batch_not_longer_than_maxlen(self): for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: batch = tokenizer.prepare_seq2seq_batch( ["I am a small frog" * 1024, "I am a small frog"], return_tensors="pt" ) self.assertIsInstance(batch, BatchEncoding) self.assertEqual(batch.input_ids.shape, (2, 1024)) @require_torch def test_special_tokens(self): src_text = ["A long paragraph for summarization."] tgt_text = [ "Summary of the text.", ] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: batch = tokenizer.prepare_seq2seq_batch(src_text, tgt_texts=tgt_text, return_tensors="pt") input_ids = batch["input_ids"] labels = batch["labels"] self.assertTrue((input_ids[:, 0] == tokenizer.bos_token_id).all().item()) self.assertTrue((labels[:, 0] == tokenizer.bos_token_id).all().item()) self.assertTrue((input_ids[:, -1] == tokenizer.eos_token_id).all().item()) self.assertTrue((labels[:, -1] == tokenizer.eos_token_id).all().item())
39.986486
109
0.628929
0abc761c4d0f1015b3d182238014d8363430208c
693
py
Python
old/baxter_test.py
YoshimitsuMatsutaIe/hoge_flow_test
22e2e2ce043a3107bd06449f6f9958641293e414
[ "MIT" ]
null
null
null
old/baxter_test.py
YoshimitsuMatsutaIe/hoge_flow_test
22e2e2ce043a3107bd06449f6f9958641293e414
[ "MIT" ]
null
null
null
old/baxter_test.py
YoshimitsuMatsutaIe/hoge_flow_test
22e2e2ce043a3107bd06449f6f9958641293e414
[ "MIT" ]
null
null
null
"""baxter関連をテストする""" import numpy as np from math import cos, sin, tan, pi #import itertools import csv import matplotlib.pyplot as plt import matplotlib.animation as anm from mpl_toolkits.mplot3d import Axes3D #import matplotlib.patches as patches #from matplotlib.font_manager import FontProperties #fp = FontProperties(fname=r'C:\WINDOWS\Fonts\Arial.ttf', size=14) import time # from baxter_utils_2 import * # from baxter_utils import * import baxter_utils_3 BaxterKinema = baxter_utils_3.BaxterKinematics3( L = 278e-3, h = 64e-3, H = 1104e-3, L0 = 270.35e-3, L1 = 69e-3, L2 = 364.35e-3, L3 = 69e-3, L4 = 374.29e-3, L5 = 10e-3, L6 = 368.3e-3 )
21
66
0.702742
7c7cc5d03503a565bf1f10598b682a71e75a2d48
2,955
py
Python
events/views.py
rocky-roll-call/rrc-backend
02e8e11c3dab7661e48650e2e861a4a97788a4ce
[ "MIT" ]
null
null
null
events/views.py
rocky-roll-call/rrc-backend
02e8e11c3dab7661e48650e2e861a4a97788a4ce
[ "MIT" ]
null
null
null
events/views.py
rocky-roll-call/rrc-backend
02e8e11c3dab7661e48650e2e861a4a97788a4ce
[ "MIT" ]
null
null
null
""" Event API Views """ # django from django.shortcuts import get_object_or_404 # library from rest_framework import generics from rest_framework.exceptions import ValidationError # app from casts.models import Cast from casts.permissions import IsManagerOrReadOnly from users.models import Profile from .models import Event, Casting from .serializers import CastingSerializer, EventSerializer class EventListCreate(generics.ListCreateAPIView): """List available events or create a new one""" queryset = Event.objects.all() serializer_class = EventSerializer permission_classes = (IsManagerOrReadOnly,) def perform_create(self, serializer): cast = get_object_or_404(Cast, pk=self.request.data["cast"]) self.check_object_permissions(self.request, cast) serializer.save(cast=cast) class EventRetrieveUpdateDestroy(generics.RetrieveUpdateDestroyAPIView): """Retrieve, update, or delete an event""" queryset = Event.objects.all() serializer_class = EventSerializer permission_classes = (IsManagerOrReadOnly,) def perform_update(self, serializer): if "cast" in self.request.data: raise ValidationError( "You cannot change the cast after an event has been created" ) serializer.save() class CastingListCreate(generics.ListCreateAPIView): """List available events or create a new one""" serializer_class = CastingSerializer permission_classes = (IsManagerOrReadOnly,) def get_queryset(self): return Casting.objects.filter(event=self.kwargs["pk"]) def perform_create(self, serializer): event = get_object_or_404(Event, pk=self.kwargs["pk"]) self.check_object_permissions(self.request, event) if "profile" in self.request.data: profile = get_object_or_404(Profile, pk=self.request.data["profile"]) if not event.cast.is_member(profile): raise ValidationError(f"{profile} is not a member of {event.cast}") serializer.save(event=event, profile=profile) serializer.save(event=event) class CastingRetrieveUpdateDestroy(generics.RetrieveUpdateDestroyAPIView): """Retrieve, update, or delete an event casting""" queryset = Casting.objects.all() serializer_class = CastingSerializer permission_classes = (IsManagerOrReadOnly,) def perform_update(self, serializer): if "event" in self.request.data: raise ValidationError( "You cannot change the event after a casting has been created" ) if "profile" in self.request.data: profile = get_object_or_404(Profile, pk=self.request.data["profile"]) cast = self.get_object().event.cast if not cast.is_member(profile): raise ValidationError(f"{profile} is not a member of {cast}") serializer.save(profile=profile) serializer.save()
33.965517
83
0.698816
7cc242f60c16ba220614e43c292406585aa58ed9
408
py
Python
Algorithms/Sorting/InsertionSort/insertion_sort.py
Nidita/Data-Structures-Algorithms
7b5198c8d37e9a70dd0885c6eef6dddd9d85d74a
[ "MIT" ]
26
2019-07-17T11:05:43.000Z
2022-02-06T08:31:40.000Z
Algorithms/Sorting/InsertionSort/insertion_sort.py
Nidita/Data-Structures-Algorithms
7b5198c8d37e9a70dd0885c6eef6dddd9d85d74a
[ "MIT" ]
7
2019-07-16T19:52:25.000Z
2022-01-08T08:03:44.000Z
Algorithms/Sorting/InsertionSort/insertion_sort.py
Nidita/Data-Structures-Algorithms
7b5198c8d37e9a70dd0885c6eef6dddd9d85d74a
[ "MIT" ]
19
2020-01-14T02:44:28.000Z
2021-12-27T17:31:59.000Z
def insertion_sort(arr): for i in range(1, len(arr)): key = arr[i] j = i - 1 while(j>=0 and arr[j]>key): arr[j+1]=arr[j] j = j - 1 arr[j+1] = key return arr def main(): arr = [6, 5, 8, 9, 3, 1, 4, 7, 2] sorted_arr = insertion_sort(arr) for i in sorted_arr: print(i, end=" ") if __name__ == "__main__": main()
20.4
37
0.458333
7cd061d6e0313657c5bd26a9b8283e3bedc8bf98
1,648
py
Python
etl/transforms/primitives/df/restructure.py
cloud-cds/cds-stack
d68a1654d4f604369a071f784cdb5c42fc855d6e
[ "Apache-2.0" ]
6
2018-06-27T00:09:55.000Z
2019-03-07T14:06:53.000Z
etl/transforms/primitives/df/restructure.py
cloud-cds/cds-stack
d68a1654d4f604369a071f784cdb5c42fc855d6e
[ "Apache-2.0" ]
3
2021-03-31T18:37:46.000Z
2021-06-01T21:49:41.000Z
etl/transforms/primitives/df/restructure.py
cloud-cds/cds-stack
d68a1654d4f604369a071f784cdb5c42fc855d6e
[ "Apache-2.0" ]
3
2020-01-24T16:40:49.000Z
2021-09-30T02:28:55.000Z
import etl.transforms.primitives.df.pandas_utils as pandas_utils import pandas as pd import numpy as np import logging def select_columns(df, selection_dict): try: df = df[list(selection_dict.keys())]\ .rename(index=str, columns=selection_dict)\ .reset_index(drop=True) except KeyError as e: for col in selection_dict.values(): df[col] = np.nan return df def unlist(df, unlist_col): return pandas_utils.unlistify_pandas_column(df, unlist_col) def extract(df, dict_column, selection_dict): def fill_none(val): if val is None or str(val) == 'nan': return {} return val df[dict_column] = df[dict_column].apply(fill_none) new_cols = pd.DataFrame(df[dict_column].tolist()) new_cols = select_columns(new_cols, selection_dict) old_cols = df.drop(dict_column, axis=1) return pd.concat([old_cols, new_cols], axis=1) def concat_str(df, new_col, col_1, col_2, drop_original=True): df[new_col] = df[col_1].str.cat(df[col_2], sep=' ') if drop_original: df.drop([col_1, col_2], axis=1, inplace=True) return df import random def make_null_time_midnight(df): df['time'] = df['time'].apply(lambda x: '12:00 AM' if x is None else x) return df def extract_id_from_list(df, id_column, id_type): def get_id(id_list): for x in id_list: if x.get('Type') == id_type: return str(x['ID']) logging.error('Could not find an ID. Throwing away row.') return 'Invalid ID' df[id_column] = df[id_column].apply(get_id) return df[~(df[id_column] == 'Invalid ID')]
32.313725
75
0.652913
86a6b22c2d771d5bbbd8c2ebed050c8c9fd2e1e6
2,560
py
Python
exercises/networking_selfpaced/networking-workshop/collections/ansible_collections/community/general/scripts/inventory/lxc_inventory.py
tr3ck3r/linklight
5060f624c235ecf46cb62cefcc6bddc6bf8ca3e7
[ "MIT" ]
null
null
null
exercises/networking_selfpaced/networking-workshop/collections/ansible_collections/community/general/scripts/inventory/lxc_inventory.py
tr3ck3r/linklight
5060f624c235ecf46cb62cefcc6bddc6bf8ca3e7
[ "MIT" ]
null
null
null
exercises/networking_selfpaced/networking-workshop/collections/ansible_collections/community/general/scripts/inventory/lxc_inventory.py
tr3ck3r/linklight
5060f624c235ecf46cb62cefcc6bddc6bf8ca3e7
[ "MIT" ]
null
null
null
#!/usr/bin/env python # # (c) 2015-16 Florian Haas, hastexo Professional Services GmbH # <[email protected]> # Based in part on: # libvirt_lxc.py, (c) 2013, Michael Scherer <[email protected]> # # This file is part of Ansible, # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>. """ Ansible inventory script for LXC containers. Requires Python bindings for LXC API. In LXC, containers can be grouped by setting the lxc.group option, which may be found more than once in a container's configuration. So, we enumerate all containers, fetch their list of groups, and then build the dictionary in the way Ansible expects it. """ from __future__ import print_function import sys import lxc import json def build_dict(): """Returns a dictionary keyed to the defined LXC groups. All containers, including the ones not in any group, are included in the "all" group.""" # Enumerate all containers, and list the groups they are in. Also, # implicitly add every container to the 'all' group. containers = dict([(c, ['all'] + (lxc.Container(c).get_config_item('lxc.group') or [])) for c in lxc.list_containers()]) # Extract the groups, flatten the list, and remove duplicates groups = set(sum([g for g in containers.values()], [])) # Create a dictionary for each group (including the 'all' group return dict([(g, {'hosts': [k for k, v in containers.items() if g in v], 'vars': {'ansible_connection': 'lxc'}}) for g in groups]) def main(argv): """Returns a JSON dictionary as expected by Ansible""" result = build_dict() if len(argv) == 2 and argv[1] == '--list': json.dump(result, sys.stdout) elif len(argv) == 3 and argv[1] == '--host': json.dump({'ansible_connection': 'lxc'}, sys.stdout) else: print("Need an argument, either --list or --host <host>", file=sys.stderr) if __name__ == '__main__': main(sys.argv)
36.056338
82
0.678516
d4954ea39c55d5e1eb404391d9b9f35a36d9d496
2,079
py
Python
oldp/utils/test_utils.py
ImgBotApp/oldp
575dc6f711dde3470d910e21c9440ee9b79a69ed
[ "MIT" ]
3
2020-06-27T08:19:35.000Z
2020-12-27T17:46:02.000Z
oldp/utils/test_utils.py
ImgBotApp/oldp
575dc6f711dde3470d910e21c9440ee9b79a69ed
[ "MIT" ]
null
null
null
oldp/utils/test_utils.py
ImgBotApp/oldp
575dc6f711dde3470d910e21c9440ee9b79a69ed
[ "MIT" ]
null
null
null
import logging import os from unittest import TestCase from django.conf import settings logger = logging.getLogger(__name__) class TestCaseHelper(object): resource_dir = None @staticmethod def get_app_root_dir(): return os.path.dirname(os.path.dirname(os.path.realpath(__file__))) def get_resource_dir(self): # return os.path.join(os.path.dirname(os.path.realpath(__file__)), 'resources') return self.resource_dir def get_resource(self, file_name): return os.path.join(self.get_resource_dir(), file_name) def get_resource_as_string(self, file_name): with open(self.get_resource(file_name), 'r') as f: return f.read() def assert_items_equal(self, expected, actual, msg, debug=False): if debug: logger.debug('Expected:\t%s\nActual:\t%s' % (sorted(expected), sorted(actual))) TestCase().assertTrue(len(expected) == len(actual) and sorted(expected) == sorted(actual), msg) # @staticmethod # def get_log_level(): # return get_log_level_from_env('OLDP_TEST_LOG_LEVEL', 'debug') def mysql_only_test(fn): """Use this decorator for tests (e.g. DataErrors, IntegrityErrors) that apply only with MySQL (not SQLite)""" def modified_fn(x): if settings.DATABASES['default']['ENGINE'] != 'django.db.backends.mysql': logger.warning('Skip test (DB is not MySQL): %s' % fn.__name__) else: return fn(x) return modified_fn def web_test(fn): """Use this decorator for tests that interact with external websites""" def modified_fn(x): if not settings.TEST_WITH_WEB: logger.warning('Skip test (without web): %s' % fn.__name__) else: return fn(x) return modified_fn def es_test(fn): """Use this decorator for tests that require Elasticsearch""" def modified_fn(x): if not settings.TEST_WITH_ES: logger.warning('Skip test (without Elasticsearch): %s' % fn.__name__) else: return fn(x) return modified_fn
29.7
113
0.658009
d4da6651eaa60ead25c4d44b2f69a592b2f35122
10,794
py
Python
tests/model/test_game.py
jonashellmann/informaticup21-team-chillow
f2e519af0a5d9a9368d62556703cfb1066ebb58f
[ "MIT" ]
3
2021-01-17T23:32:07.000Z
2022-01-30T14:49:16.000Z
tests/model/test_game.py
jonashellmann/informaticup21-team-chillow
f2e519af0a5d9a9368d62556703cfb1066ebb58f
[ "MIT" ]
2
2021-01-17T13:37:56.000Z
2021-04-14T12:28:49.000Z
tests/model/test_game.py
jonashellmann/informaticup21-team-chillow
f2e519af0a5d9a9368d62556703cfb1066ebb58f
[ "MIT" ]
2
2021-04-02T14:53:38.000Z
2021-04-20T11:10:17.000Z
import unittest from datetime import datetime, timezone import tests from chillow.model.cell import Cell from chillow.model.direction import Direction from chillow.model.game import Game from chillow.model.player import Player from chillow.exceptions import WrongGameWidthException, WrongGameHeightException, OwnPlayerMissingException, \ PlayerPositionException, PlayerWithGivenIdNotAvailableException from chillow.service.data_loader import JSONDataLoader class GameTest(unittest.TestCase): def test_examines_your_player_after_creation(self): player1 = Player(1, 0, 1, Direction.up, 0, True, "Name 1") player2 = Player(2, 1, 0, Direction.up, 0, True, "Name 2") player3 = Player(3, 0, 0, Direction.up, 0, True, "Name 3") players = [player1, player2, player3] cells = [[Cell([player3]), Cell([player2])], [Cell([player1]), Cell()]] game = Game(2, 2, cells, players, 2, True, datetime.now()) self.assertEqual(game.you, player2) def test_raise_exception_on_non_existing_own_player(self): player1 = Player(1, 0, 1, Direction.up, 0, True, "Name 1") player3 = Player(3, 0, 0, Direction.up, 0, True, "Name 3") players = [player1, player3] cells = [[Cell([player3]), Cell([])], [Cell([player1]), Cell()]] with self.assertRaises(OwnPlayerMissingException): Game(2, 2, cells, players, 2, True, datetime.now()) def test_raise_exception_on_wrong_player_position(self): player1 = Player(1, 1, 1, Direction.up, 0, True, "Name 1") player2 = Player(2, 0, 0, Direction.up, 0, True, "Name 2") player3 = Player(3, 0, 1, Direction.up, 0, True, "Name 3") players = [player1, player2, player3] cells = [[Cell([player2]), Cell([player3])], [Cell(), Cell([player1])]] with self.assertRaises(PlayerPositionException): Game(2, 2, cells, players, 2, True, datetime.now()) def test_dont_raise_exception_on_wrong_inactive_player_position(self): player1 = Player(1, 1, 1, Direction.up, 0, False, "Name 1") player2 = Player(2, 1, 0, Direction.up, 0, True, "Name 2") player3 = Player(3, 0, 1, Direction.up, 0, True, "Name 3") players = [player1, player2, player3] cells = [[Cell([]), Cell([player2])], [Cell([player3]), Cell([player3])]] game = Game(2, 2, cells, players, 2, True, datetime.now()) self.assertEqual(game.you, player2) def test_raise_exception_on_wrong_width(self): cells = [ [ Cell() ], [ Cell(), Cell() ] ] with self.assertRaises(WrongGameWidthException): Game(2, 2, cells, [], 0, True, datetime.now()) def test_raise_exception_on_wrong_height(self): cells = [ [ Cell(), Cell() ] ] with self.assertRaises(WrongGameHeightException): Game(2, 2, cells, [], 0, True, datetime.now()) def test_find_winner_in_ended_game(self): player1 = Player(1, 0, 0, Direction.up, 0, False, "Name") player2 = Player(1, 1, 0, Direction.up, 0, True, "Name") cells = [[Cell([player1]), Cell([player2])]] game = Game(2, 1, cells, [player1, player2], 1, False, datetime.now()) result = game.get_winner() self.assertEqual(player2, result) def test_raise_exception_for_winner_in_running_game(self): player = Player(1, 0, 0, Direction.up, 0, True, "Name") cells = [[Cell([player]), Cell()]] game = Game(2, 1, cells, [player], 1, True, datetime.now()) with self.assertRaises(Exception): game.get_winner() def test_return_no_winner_in_ended_game(self): player1 = Player(1, 0, 0, Direction.up, 0, False, "Name") player2 = Player(1, 1, 0, Direction.up, 0, False, "Name") cells = [[Cell([player1]), Cell([player2])]] game = Game(2, 1, cells, [player1, player2], 1, False, datetime.now()) result = game.get_winner() self.assertEqual(None, result) def test_player_with_id_should_be_returned(self): player1 = Player(1, 0, 0, Direction.up, 0, True, "Name") player2 = Player(2, 1, 0, Direction.up, 0, True, "Name") cells = [[Cell([player1]), Cell([player2])]] game = Game(2, 1, cells, [player1, player2], 1, True, datetime.now()) self.assertEqual(player1, game.get_player_by_id(1)) def test_raise_exception_when_player_id_invalid(self): player1 = Player(1, 1, 0, Direction.up, 0, True, "Name") player2 = Player(2, 0, 0, Direction.up, 0, True, "Name") cells = [[Cell([player2]), Cell([player1])]] game = Game(2, 1, cells, [player1, player2], 1, True, datetime.now()) with self.assertRaises(PlayerWithGivenIdNotAvailableException): game.get_player_by_id(100) def test_return_all_other_players(self): player1 = Player(1, 1, 1, Direction.up, 0, True, "Name 1") player2 = Player(2, 1, 0, Direction.up, 0, True, "Name 2") player3 = Player(3, 0, 0, Direction.up, 0, True, "Name 3") players = [player1, player2, player3] cells = [[Cell([player3]), Cell([player2])], [Cell([]), Cell([player1])]] game = Game(2, 2, cells, players, 2, True, datetime.now()) result = game.get_other_player_ids(player2) self.assertEqual([1, 3], result) def test_return_all_other_active_players(self): player1 = Player(1, 1, 1, Direction.up, 0, True, "Name 1") player2 = Player(2, 1, 0, Direction.up, 0, False, "Name 2") player3 = Player(3, 0, 0, Direction.up, 0, True, "Name 3") players = [player1, player2, player3] cells = [[Cell([player3]), Cell([player2])], [Cell([]), Cell([player1])]] game = Game(2, 2, cells, players, 1, True, datetime.now()) result = game.get_other_player_ids(player1, check_active=True) self.assertEqual([3], result) def test_return_all_players_except_one_within_distance_1(self): player1 = Player(1, 3, 3, Direction.up, 0, True, "Name 1") player2 = Player(2, 1, 3, Direction.up, 0, True, "Name 2") player3 = Player(3, 0, 0, Direction.up, 0, True, "Name 3") players = [player1, player2, player3] cells = [ [Cell([player3]), Cell(), Cell(), Cell(), Cell()], [Cell(), Cell(), Cell(), Cell(), Cell()], [Cell(), Cell(), Cell(), Cell(), Cell()], [Cell(), Cell([player2]), Cell(), Cell([player1]), Cell()], [Cell(), Cell(), Cell(), Cell(), Cell()] ] game = Game(5, 5, cells, players, 1, True, datetime.now()) result = game.get_other_player_ids(player1, 2) self.assertEqual([2], result) def test_return_all_players_except_one_within_distance_2(self): player1 = Player(1, 4, 4, Direction.up, 0, True, "Name 1") player2 = Player(2, 2, 3, Direction.up, 0, True, "Name 2") player3 = Player(3, 1, 4, Direction.up, 0, True, "Name 3") players = [player1, player2, player3] cells = [ [Cell(), Cell(), Cell(), Cell(), Cell()], [Cell(), Cell(), Cell(), Cell(), Cell()], [Cell(), Cell(), Cell(), Cell(), Cell()], [Cell(), Cell(), Cell([player2]), Cell(), Cell()], [Cell(), Cell([player3]), Cell([player2]), Cell(), Cell([player1])] ] game = Game(5, 5, cells, players, 1, True, datetime.now()) result = game.get_other_player_ids(player1, 3) self.assertEqual([2], result) def test_return_no_player_who_is_not_reachable(self): player1 = Player(1, 4, 4, Direction.up, 0, True, "Name 1") player2 = Player(2, 2, 3, Direction.up, 0, True, "Name 2") player3 = Player(3, 1, 4, Direction.up, 0, True, "Name 3") players = [player1, player2, player3] cells = [ [Cell(), Cell(), Cell([player2]), Cell(), Cell()], [Cell(), Cell(), Cell([player2]), Cell(), Cell()], [Cell(), Cell(), Cell([player2]), Cell(), Cell()], [Cell(), Cell(), Cell([player2]), Cell(), Cell()], [Cell(), Cell([player3]), Cell([player2]), Cell(), Cell([player1])] ] game = Game(5, 5, cells, players, 1, True, datetime.now()) result = game.get_other_player_ids(player1, 3) self.assertEqual([2], result) def test_translate_cell_matrix_to_pathfinding_matrix_should_be_correct(self): player1 = Player(1, 0, 0, Direction.up, 1, True, "") player2 = Player(2, 0, 1, Direction.down, 3, True, "") players = [player1, player2] cells = [[Cell([player1]), Cell()], [Cell([player2]), Cell()], [Cell(), Cell()]] game = Game(2, 3, cells, players, 2, True, datetime.now()) expected_matrix = [[0, 1], [0, 1], [1, 1]] matrix = game.translate_cell_matrix_to_pathfinding_matrix() self.assertEqual(matrix, expected_matrix) def test_copying_a_game_should_return_same_game_but_different_identity(self): player1 = Player(1, 1, 1, Direction.up, 0, True, "Name") player2 = Player(2, 1, 0, Direction.up, 0, True, "Name2") player3 = Player(3, 0, 0, Direction.up, 0, True, "Name3") players = [player1, player2, player3] cells = [[Cell([player3]), Cell([player2])], [Cell([]), Cell([player1])]] game = Game(2, 2, cells, players, 2, True, datetime.now()) result = game.copy() self.assertEqual(game, result) self.assertNotEqual(id(game), id(result)) def test_normalize_game_deadline_1(self): server_time = datetime(2020, 11, 20, 10, 33, 11, 0, timezone.utc) own_time = datetime(2020, 11, 20, 10, 33, 12, 941748, timezone.utc) game = JSONDataLoader().load(tests.read_test_file("model/game_1.json")) game.deadline = datetime(2020, 11, 20, 10, 33, 18, 0, timezone.utc) expected = datetime(2020, 11, 20, 10, 33, 19, 941748, timezone.utc) game.normalize_deadline(server_time, own_time) self.assertEqual(expected, game.deadline) def test_normalize_game_deadline_2(self): server_time = datetime(2020, 11, 20, 10, 33, 12, 941748, timezone.utc) own_time = datetime(2020, 11, 20, 10, 33, 11, 0, timezone.utc) game = JSONDataLoader().load(tests.read_test_file("model/game_1.json")) game.deadline = datetime(2020, 11, 20, 10, 33, 18, 941748, timezone.utc) expected = datetime(2020, 11, 20, 10, 33, 17, 0, timezone.utc) game.normalize_deadline(server_time, own_time) self.assertEqual(expected, game.deadline)
42.496063
110
0.592459
078c756cad7cad8808fa355832f4361f48528673
3,423
py
Python
src/onegov/translator_directory/app.py
politbuero-kampagnen/onegov-cloud
20148bf321b71f617b64376fe7249b2b9b9c4aa9
[ "MIT" ]
null
null
null
src/onegov/translator_directory/app.py
politbuero-kampagnen/onegov-cloud
20148bf321b71f617b64376fe7249b2b9b9c4aa9
[ "MIT" ]
null
null
null
src/onegov/translator_directory/app.py
politbuero-kampagnen/onegov-cloud
20148bf321b71f617b64376fe7249b2b9b9c4aa9
[ "MIT" ]
null
null
null
from datetime import datetime from sqlalchemy.orm import object_session from onegov.core import utils from onegov.core.crypto import random_token from onegov.file.utils import as_fileintent, extension_for_content_type, \ content_type_from_fileobj from onegov.gis import Coordinates from onegov.translator_directory.initial_content import create_new_organisation from onegov.org import OrgApp from onegov.org.app import get_common_asset as default_common_asset from onegov.org.app import get_i18n_localedirs as get_org_i18n_localedirs from onegov.translator_directory.models.voucher import TranslatorVoucherFile from onegov.translator_directory.request import TranslatorAppRequest from onegov.translator_directory.theme import TranslatorDirectoryTheme class TranslatorDirectoryApp(OrgApp): send_daily_ticket_statistics = False request_class = TranslatorAppRequest def es_may_use_private_search(self, request): return request.is_admin def configure_organisation(self, **cfg): cfg.setdefault('enable_user_registration', False) cfg.setdefault('enable_yubikey', False) cfg.setdefault('disable_password_reset', False) super().configure_organisation(**cfg) @property def coordinates(self): return self.org.meta.get('translator_directory_home') or Coordinates() @coordinates.setter def coordinates(self, value): self.org.meta['translator_directory_home'] = value or {} @property def voucher_excel(self): return object_session(self.org).query(TranslatorVoucherFile).first() @property def voucher_excel_file(self): return self.voucher_excel and self.voucher_excel.reference.file @voucher_excel_file.setter def voucher_excel_file(self, value): content_type = extension_for_content_type( content_type_from_fileobj(value) ) or 'xls' year = datetime.now().year filename = f'abrechnungsvorlage_{year}.{content_type}' if self.voucher_excel: self.voucher_excel.reference = as_fileintent(value, filename) self.voucher_excel.name = filename else: file = TranslatorVoucherFile(id=random_token()) file.reference = as_fileintent(value, filename) file.name = filename session = object_session(self.org) session.add(file) session.flush() @TranslatorDirectoryApp.template_directory() def get_template_directory(): return 'templates' @TranslatorDirectoryApp.static_directory() def get_static_directory(): return 'static' @TranslatorDirectoryApp.setting(section='core', name='theme') def get_theme(): return TranslatorDirectoryTheme() @TranslatorDirectoryApp.setting(section='org', name='create_new_organisation') def get_create_new_organisation_factory(): return create_new_organisation @TranslatorDirectoryApp.setting(section='i18n', name='localedirs') def get_i18n_localedirs(): mine = utils.module_path('onegov.translator_directory', 'locale') return [mine] + get_org_i18n_localedirs() @TranslatorDirectoryApp.webasset_path() def get_js_path(): return 'assets/js' @TranslatorDirectoryApp.webasset_output() def get_webasset_output(): return 'assets/bundles' @TranslatorDirectoryApp.webasset('common') def get_common_asset(): yield from default_common_asset() yield 'translator_directory.js'
31.694444
79
0.752848
07b99f525071369ad8a8683e936de85bf118cf18
2,964
py
Python
Examples/terminal/demo_all/demo-all.py
andino-systems/andinopy
28fc09fbdd67dd690b9b3f80f03a05c342c777e1
[ "Apache-2.0" ]
null
null
null
Examples/terminal/demo_all/demo-all.py
andino-systems/andinopy
28fc09fbdd67dd690b9b3f80f03a05c342c777e1
[ "Apache-2.0" ]
null
null
null
Examples/terminal/demo_all/demo-all.py
andino-systems/andinopy
28fc09fbdd67dd690b9b3f80f03a05c342c777e1
[ "Apache-2.0" ]
null
null
null
import time from andinopy import andinoterminal import logging class TerminalDemo: terminal: andinoterminal = None _last_keyboard: str = "" _last_rfid: str = "" def __init__(self): print("initializing Terminal") self.terminal = andinoterminal() self.terminal.rfid_keyboard_instance.on_function_button = self.on_function_button self.terminal.rfid_keyboard_instance.on_keyboard_button = self.on_keyboard_button self.terminal.rfid_keyboard_instance.on_rfid_string = self.on_rfid_string self.terminal.display_instance.on_display_touch = self.on_display_touch self.terminal.andinoio_instance.on_input_functions = \ [self.input_pin for i in range(len(self.terminal.andinoio_instance.inputs_counter))] def __get_counters(self): return self.terminal.andinoio_instance.inputs_counter def __get_relays(self): return self.terminal.andinoio_instance.relays_status def update_terminal(self): print("updating Display") ctr = self.__get_counters() for i in range(len(ctr)): self.terminal.display_instance.set_text(f"input{i + 1}", ctr[i]) rel_stats = ["on" if i == 1 else "off" for i in self.__get_relays()] for j in range(len(rel_stats)): self.terminal.display_instance.set_text(f"rel{j + 1}", rel_stats[j]) self.terminal.display_instance.set_attr(f"rel{j + 1}", "pco", 1346 if rel_stats[j] == "on" else 43300) self.terminal.display_instance.set_text(f"rfidtxt", self._last_rfid) self.terminal.display_instance.set_text(f"keybrtxt", self._last_keyboard) def start(self): print("starting") self.terminal.start() self.terminal.rfid_keyboard_instance.buzz_display(500) def input_pin(self): print("pin pressed") self.update_terminal() def on_function_button(self, btn: str): print(f"Function Button: {btn}") self._last_keyboard = f"Keyboard Function Button: {btn}" self.update_terminal() def on_keyboard_button(self, btn: str): print(f"Keyboard Button: {btn}") self._last_keyboard = f"Keyboard Button: {btn}" self.update_terminal() def on_rfid_string(self, rfid: str): print(f"RFID: {rfid}") self._last_rfid = rfid self.update_terminal() def on_display_touch(self, text: bytearray): print(f"Display Touch: {str(text)}") if text[:4] == b'e\x00\x17\x01': self.terminal.rfid_keyboard_instance.buzz_display(500) if __name__ == "__main__": log = logging.getLogger("andinopy") log.setLevel(logging.DEBUG) ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') ch.setFormatter(formatter) log.addHandler(ch) demo = TerminalDemo() demo.start() while True: time.sleep(1)
34.870588
114
0.67139
ed3c21f001a4067d79b6c959360144742570c9bb
1,687
py
Python
MzituCrawler/spiders/zipaiSpiders.py
yeming1001/-MzituCrawler
3e3dad298734658266fb4c12cd863be73eb4f4a2
[ "Apache-2.0" ]
1
2018-02-09T05:36:06.000Z
2018-02-09T05:36:06.000Z
MzituCrawler/spiders/zipaiSpiders.py
yeming1001/-MzituCrawler
3e3dad298734658266fb4c12cd863be73eb4f4a2
[ "Apache-2.0" ]
null
null
null
MzituCrawler/spiders/zipaiSpiders.py
yeming1001/-MzituCrawler
3e3dad298734658266fb4c12cd863be73eb4f4a2
[ "Apache-2.0" ]
1
2017-03-30T07:44:49.000Z
2017-03-30T07:44:49.000Z
from scrapy.selector import Selector import scrapy from MzituCrawler.items import MzituZiPaicrawlerItem # 妹子图自拍爬虫 class ZipaiSiders(scrapy.Spider): name = 'mzitu.zipai' allowed_domains = ['www.mzitu.com'] base_url = 'http://www.mzitu.com/zipai/comment-page-{}#comments' start_urls = ['http://www.mzitu.com/zipai'] custom_settings = { 'ITEM_PIPELINES': {'MzituCrawler.pipelines.MzituCrawlerZiPaiImagePipeline': 300,} } def parse(self, response): selector = Selector(response=response) page_count = selector.xpath( '//div[@class="main"]/div[@class="main-content"]/div[@class="postlist"]/div[@id="comments"]/div[@class="pagenavi-cm"]/span[@class="page-numbers current"]/text()').extract_first() self.log(u'自拍总共%s页'%page_count) for i in range(1,int(page_count)+1): self.log(u'当前解析第%d页'%i) url = self.base_url.format(str(i)) yield scrapy.Request(url=url,callback=self.parse_every_page) def parse_every_page(self, response): selector = Selector(response=response) comments = selector.xpath('//div[@class="main"]/div[@class="main-content"]/div[@class="postlist"]/div[@id="comments"]/ul') item = MzituZiPaicrawlerItem() li_list = comments.xpath('./li') for li in li_list: url = li.xpath('./div[@class="comment-body"]/p/img/@src').extract_first() title = li.xpath('./div[@class="comment-body"]/p/img/@alt').extract_first() self.log(u'alt:%s' % title) self.log(u'url:%s' % url) item['image_urls'] = [url] item['image_title'] = title yield item
35.145833
186
0.623592
92bb6c6e0a379cb864cc9e018d8b94120804e425
1,843
py
Python
python_first_step/partialsum/partialsum.py
cartellefo/projet
23c67e847b415fb47f71e830b89a227fffed109b
[ "MIT" ]
null
null
null
python_first_step/partialsum/partialsum.py
cartellefo/projet
23c67e847b415fb47f71e830b89a227fffed109b
[ "MIT" ]
null
null
null
python_first_step/partialsum/partialsum.py
cartellefo/projet
23c67e847b415fb47f71e830b89a227fffed109b
[ "MIT" ]
null
null
null
import time import numpy as np import numpy .linalg as nl import random import matplotlib.pyplot as plt import sys # Iteration über sämtliche Argumente: for eachArg in sys.argv: print(eachArg) #t1 = np.linspace(1,5,10) #t2 = np.linspace(1,5,20) #plt.plot(t1,t2) #(t1, t1, ’r -- ’,t1, t1++2, (bs, t2,np.log(t2)**3), 'g^-') #plt.show() # # n = 15 # # A = np .random.rand ( 1, n ) # Aprime = A.transpose() # print(A) # i = 0 # while i < 10: # # uu= yield _do() # uu = random.randint(1,10) # print(uu) # time.sleep(1) # i=i+1 # #r = random.randint(1,10) # #rint(r) # X = np.random.rand(5,2) # print(X) # #print("le produit est ",n) # def fill_tab(tab,int): # for index in len(tab) : tab[index] = 0 # # print(tab) # i=0 # su = 0 # N = 3 # while i < N: # su = su + 1./(i*i) # print(su) # i=i+1 def partialsum(n_max) : # summe des carre print(n_max) S=0 sums=[] for i in range(1, n_max,1) : S+= 1/(i*i) sums.append(S) return(sums) n_max= int(sys.argv[1]) r= partialsum(n_max) #x=np.linspace(1,n_max,n_max) #ssum =plt.plot(np.sqrt(x),'r',marker='.',linestyle='-',linewidth=1.5,markersize=1,markeredgecolor='red', label='ssum') psum = plt.plot(r,'g',marker='.',linestyle='-',linewidth=1,markersize=1.5,markeredgecolor='b',color='green', label='psum') plt.ylabel("partialsum") plt.xlabel("integer values to partial sum") plt.title("graph to Partialsumm and trigonomeric fonction") plt.legend() plt.show() # if __name__=='__main__': # import sys # if len(sys.argv)==1: # try: # partialsum=int(sys.argv[0]) # y=int(sys.argv[1]) # partialsum(n_max) # except ValueError: # print('the arguments is interger')
20.252747
122
0.560499
92c46a523a0d0e121e5938ce9c1fe6fda06192d6
1,488
py
Python
20-fs-ias-lec/groups/07-14-logCtrl/src/logStore/appconn/kotlin_connection.py
Kyrus1999/BACnet
5be8e1377252166041bcd0b066cce5b92b077d06
[ "MIT" ]
8
2020-03-17T21:12:18.000Z
2021-12-12T15:55:54.000Z
20-fs-ias-lec/groups/07-14-logCtrl/src/logStore/appconn/kotlin_connection.py
Kyrus1999/BACnet
5be8e1377252166041bcd0b066cce5b92b077d06
[ "MIT" ]
2
2021-07-19T06:18:43.000Z
2022-02-10T12:17:58.000Z
20-fs-ias-lec/groups/07-14-logCtrl/src/logStore/appconn/kotlin_connection.py
Kyrus1999/BACnet
5be8e1377252166041bcd0b066cce5b92b077d06
[ "MIT" ]
25
2020-03-20T09:32:45.000Z
2021-07-18T18:12:59.000Z
from .connection import Function class KotlinFunction(Function): """Connection to the group kotlin to insert and output the chat elements""" def __init__(self): super(KotlinFunction, self).__init__() def insert_data(self, cbor): """adds a new chat element as cbor @:parameter event: The new cbor event to be added @:returns 1 if successful, -1 if any error occurred """ self.insert_event(cbor) def get_usernames_and_feed_id(self): """Get all current usernames with the corresponding feed id @:returns a list with all Kotlin usernames and the corresponding feed id """ return self._handler.get_usernames_and_feed_id() def get_all_entries_by_feed_id(self, feed_id): """Get all elements with the corresponding feed id, thus all events of a user @:parameter feed_id: the feed id of a user @:returns a list of all Kotlin entries with the correct feed id """ return self._handler.get_all_entries_by_feed_id(feed_id) def get_all_kotlin_events(self): """Get all existing kotlin elements that are in the database @:returns a list of all Kotlin entries """ return self._handler.get_all_kotlin_events() def get_last_kotlin_event(self): """Get only the last added kotlin element @:returns a only the last Kotlin entry as cbor """ return self._handler.get_last_kotlin_event()
32.347826
85
0.670699
13068e620cee3b753c5b140b987eded2ed8c4625
3,847
py
Python
lib/tinyxml2/setversion.py
tokosattila/HomeEinkBadge
786e9314ef8119d968048ec77956f4fb7804082f
[ "Unlicense" ]
null
null
null
lib/tinyxml2/setversion.py
tokosattila/HomeEinkBadge
786e9314ef8119d968048ec77956f4fb7804082f
[ "Unlicense" ]
null
null
null
lib/tinyxml2/setversion.py
tokosattila/HomeEinkBadge
786e9314ef8119d968048ec77956f4fb7804082f
[ "Unlicense" ]
null
null
null
# Python program to set the version. ############################################## import re import sys import optparse def fileProcess( name, lineFunction ): filestream = open( name, 'r' ) if filestream.closed: print( "file " + name + " not open." ) return output = "" print( "--- Processing " + name + " ---------" ) while 1: line = filestream.readline() if not line: break output += lineFunction( line ) filestream.close() if not output: return # basic error checking print( "Writing file " + name ) filestream = open( name, "w" ); filestream.write( output ); filestream.close() def echoInput( line ): return line parser = optparse.OptionParser( "usage: %prog major minor build" ) (options, args) = parser.parse_args() if len(args) != 3: parser.error( "incorrect number of arguments" ); major = args[0] minor = args[1] build = args[2] versionStr = major + "." + minor + "." + build print ("Setting dox,tinyxml2.h") print ("Version: " + major + "." + minor + "." + build) #### Write the tinyxml.h #### def engineRule( line ): matchMajor = "static const int TIXML2_MAJOR_VERSION" matchMinor = "static const int TIXML2_MINOR_VERSION" matchBuild = "static const int TIXML2_PATCH_VERSION" if line[0:len(matchMajor)] == matchMajor: print( "1)tinyxml2.h Major found" ) return matchMajor + " = " + major + ";\n" elif line[0:len(matchMinor)] == matchMinor: print( "2)tinyxml2.h Minor found" ) return matchMinor + " = " + minor + ";\n" elif line[0:len(matchBuild)] == matchBuild: print( "3)tinyxml2.h Build found" ) return matchBuild + " = " + build + ";\n" else: return line; fileProcess( "tinyxml2.h", engineRule ) def macroVersionRule( line ): matchMajor = "#define TINYXML2_MAJOR_VERSION" matchMinor = "#define TINYXML2_MINOR_VERSION" matchBuild = "#define TINYXML2_PATCH_VERSION" if line[0:len(matchMajor)] == matchMajor: print( "1)macro Major found" ) return matchMajor + " " + major + "\n" elif line[0:len(matchMinor)] == matchMinor: print( "2)macro Minor found" ) return matchMinor + " " + minor + "\n" elif line[0:len(matchBuild)] == matchBuild: print( "3)macro Build found" ) return matchBuild + " " + build + "\n" else: return line; fileProcess("tinyxml2.h", macroVersionRule) #### Write the dox #### def doxRule( line ): match = "PROJECT_NUMBER" if line[0:len( match )] == match: print( "dox project found" ) return "PROJECT_NUMBER = " + major + "." + minor + "." + build + "\n" else: return line; fileProcess( "dox", doxRule ) #### Write the CMakeLists.txt #### def cmakeRule1( line ): matchVersion = "set(GENERIC_LIB_VERSION" if line[0:len(matchVersion)] == matchVersion: print( "1)tinyxml2.h Major found" ) return matchVersion + " \"" + major + "." + minor + "." + build + "\")" + "\n" else: return line; fileProcess( "CMakeLists.txt", cmakeRule1 ) def cmakeRule2( line ): matchSoversion = "set(GENERIC_LIB_SOVERSION" if line[0:len(matchSoversion)] == matchSoversion: print( "1)tinyxml2.h Major found" ) return matchSoversion + " \"" + major + "\")" + "\n" else: return line; fileProcess( "CMakeLists.txt", cmakeRule2 ) def mesonRule(line): match = re.search(r"(\s*version) : '(\d+.\d+.\d+)',", line) if match: print("1)meson.build version found.") return "{} : '{}.{}.{}',\n".format(match.group(1), major, minor, build) return line fileProcess("meson.build", mesonRule) print( "Release note:" ) print( '1. Build. g++ -Wall -DTINYXML2_DEBUG tinyxml2.cpp xmltest.cpp -o gccxmltest.exe' ) print( '2. Commit. git commit -am"setting the version to ' + versionStr + '"' ) print( '3. Tag. git tag ' + versionStr ) print( ' OR git tag -a ' + versionStr + ' -m [tag message]' ) print( 'Remember to "git push" both code and tag. For the tag:' ) print( 'git push origin [tagname]')
24.980519
92
0.639199
1356129dc0abaeb018a9096112b5fdcb2597e545
1,024
py
Python
frappe-bench/apps/erpnext/erpnext/patches/v4_2/repost_sle_for_si_with_no_warehouse.py
Semicheche/foa_frappe_docker
a186b65d5e807dd4caf049e8aeb3620a799c1225
[ "MIT" ]
1
2021-04-29T14:55:29.000Z
2021-04-29T14:55:29.000Z
frappe-bench/apps/erpnext/erpnext/patches/v4_2/repost_sle_for_si_with_no_warehouse.py
Semicheche/foa_frappe_docker
a186b65d5e807dd4caf049e8aeb3620a799c1225
[ "MIT" ]
null
null
null
frappe-bench/apps/erpnext/erpnext/patches/v4_2/repost_sle_for_si_with_no_warehouse.py
Semicheche/foa_frappe_docker
a186b65d5e807dd4caf049e8aeb3620a799c1225
[ "MIT" ]
1
2021-04-29T14:39:01.000Z
2021-04-29T14:39:01.000Z
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import print_function, unicode_literals import frappe from erpnext.stock.stock_ledger import NegativeStockError def execute(): si_list = frappe.db.sql("""select distinct si.name from `tabSales Invoice Item` si_item, `tabSales Invoice` si where si.name = si_item.parent and si.modified > '2015-02-16' and si.docstatus=1 and ifnull(si_item.warehouse, '') = '' and ifnull(si.update_stock, 0) = 1 order by posting_date, posting_time""", as_dict=1) failed_list = [] for si in si_list: try: si_doc = frappe.get_doc("Sales Invoice", si.name) si_doc.docstatus = 2 si_doc.on_cancel() si_doc.docstatus = 1 si_doc.set_missing_item_details() si_doc.on_submit() frappe.db.commit() except: failed_list.append(si.name) frappe.local.stockledger_exceptions = None frappe.db.rollback() print("Failed to repost: ", failed_list)
30.117647
83
0.723633
138d7bc4b0520e3a2db37c0f407ede225496a386
388
py
Python
Django/ballon/migrations/0002_auto_20180827_2341.py
ballon3/GRAD
c630e32272fe34ead590c04d8360169e02be87f1
[ "MIT" ]
null
null
null
Django/ballon/migrations/0002_auto_20180827_2341.py
ballon3/GRAD
c630e32272fe34ead590c04d8360169e02be87f1
[ "MIT" ]
null
null
null
Django/ballon/migrations/0002_auto_20180827_2341.py
ballon3/GRAD
c630e32272fe34ead590c04d8360169e02be87f1
[ "MIT" ]
null
null
null
# Generated by Django 2.1 on 2018-08-28 06:41 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('ballon', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='resume', name='category', ), migrations.DeleteModel( name='Category', ), ]
18.47619
45
0.556701
16570c371b0050e20e4bd40f17bb05001dc4a9ef
65
py
Python
Programming Languages/Python/Theory/100_Python_Exercises/Exercises/Exercise 1/1.py
jaswinder9051998/Resources
fd468af37bf24ca57555d153ee64693c018e822e
[ "MIT" ]
101
2021-12-20T11:57:11.000Z
2022-03-23T09:49:13.000Z
50-Python-Exercises/Exercises/Exercise 1/1.py
kuwarkapur/Hacktoberfest-2022
efaafeba5ce51d8d2e2d94c6326cc20bff946f17
[ "MIT" ]
4
2022-01-12T11:55:56.000Z
2022-02-12T04:53:33.000Z
50-Python-Exercises/Exercises/Exercise 1/1.py
kuwarkapur/Hacktoberfest-2022
efaafeba5ce51d8d2e2d94c6326cc20bff946f17
[ "MIT" ]
38
2022-01-12T11:56:16.000Z
2022-03-23T10:07:52.000Z
#What will this script produce? #A: 3 a = 1 a = 2 a = 3 print(a)
9.285714
31
0.6
169285c1ac74a7a129c46f31b711141ae326ac5b
6,780
py
Python
core/execute.py
littlecharacter/AutoWork
feebb8459f889b7a9165073be8fd44ba544cbb35
[ "Apache-2.0" ]
null
null
null
core/execute.py
littlecharacter/AutoWork
feebb8459f889b7a9165073be8fd44ba544cbb35
[ "Apache-2.0" ]
null
null
null
core/execute.py
littlecharacter/AutoWork
feebb8459f889b7a9165073be8fd44ba544cbb35
[ "Apache-2.0" ]
null
null
null
import os import time import copy import threading from queue import Queue from core.orm import * import cv2 import pyautogui import pyperclip import pyscreeze import subprocess import platform pyautogui.FAILSAFE = False IMG_PATH = '../img/' run_flag = Queue(1) run_work = {} stop_signal = Queue(1) class WorkThread(threading.Thread): def __init__(self, threadID, name): threading.Thread.__init__(self) self.threadID = threadID self.name = name self.wid = None # 把要执行的代码写到run函数里面 线程在创建后会直接运行run函数 def run(self): try: run_flag.put_nowait(self) global run_work run_work['wid'] = self.wid flow_dict = get_special_data(self.wid, FLOW_FILENAME) flow_dict['flow'] = sorted(flow_dict['flow'], key=lambda x: x['order']) flow_item_list = copy.deepcopy(flow_dict['flow']) monitor_item_list = [] monitor_dict = get_special_data(self.wid, MONITOR_FILENAME) if monitor_dict: monitor_item_list = monitor_dict['monitor'] while True: if stop_signal.full(): break # 执行流程 if not flow_item_list: flow_item_list = copy.deepcopy(flow_dict['flow']) flow_item = flow_item_list[0] if execute(self, flow_item['op_type'], flow_item['op_content']): flow_item_list.remove(flow_item) # 执行监控 if monitor_item_list: for monitor_item in monitor_item_list: execute(self, monitor_item['op_type'], monitor_item['op_content']) time.sleep(1) except: pass @unique class OperateTypeEnum(Enum): LEFT_CLICK = {'code': 1, 'desc': '单击'} DOUBLE_CLICK = {'code': 2, 'desc': '双击'} RIGHT_CLICK = {'code': 3, 'desc': '右击'} LEFT_CLICK_IMG = {'code': 4, 'desc': '单击图片'} DOUBLE_CLICK_IMG = {'code': 5, 'desc': '双击图片'} KEY_PRESS = {'code': 6, 'desc': '按键'} HOT_KEY = {'code': 7, 'desc': '热键'} KEY_MAP = {'code': 8, 'desc': '快捷键'} INPUT = {'code': 9, 'desc': '输入'} OPEN_APP = {'code': 10, 'desc': '打开APP'} @staticmethod def get_enum(code): for e in OperateTypeEnum: if code == e.value['code']: return e def code(self): return self.value['code'] def desc(self): return self.value['desc'] def execute(self, op_type, op_content): print(op_content) op_type_enum = OperateTypeEnum.get_enum(op_type) # 1-单击 if op_type_enum == OperateTypeEnum.LEFT_CLICK: position = op_content.split(",") x, y = pyautogui.position() pyautogui.moveTo(x=x+int(position[0]), y=y+int(position[1]), duration=0.25) pyautogui.click() return True # 2-双击 elif op_type_enum == OperateTypeEnum.DOUBLE_CLICK: position = op_content.split(",") x, y = pyautogui.position() pyautogui.moveTo(x=x + int(position[0]), y=y + int(position[1]), duration=0.25) pyautogui.doubleClick() return True # 3-右击 elif op_type_enum == OperateTypeEnum.RIGHT_CLICK: position = op_content.split(",") x, y = pyautogui.position() pyautogui.moveTo(x=x + int(position[0]), y=y + int(position[1]), duration=0.25) pyautogui.rightClick() return True # 4-单击图片 elif op_type_enum == OperateTypeEnum.LEFT_CLICK_IMG: return click_img(self.wid, op_content, 1) # 5-单击图片 elif op_type_enum == OperateTypeEnum.DOUBLE_CLICK_IMG: return click_img(self.wid, op_content, 2) # 6-按键 elif op_type_enum == OperateTypeEnum.KEY_PRESS: pyautogui.press(op_content) return True # 7-热键 elif op_type_enum == OperateTypeEnum.HOT_KEY: keys = op_content.split(",") pyautogui.hotkey(keys[0], keys[1]) return True # 8-快捷键 elif op_type_enum == OperateTypeEnum.KEY_MAP: keys = op_content.split("+") for key in keys[0:-1]: pyautogui.keyDown(key) pyautogui.press(keys[-1]) keys.reverse() for key in keys[1:]: pyautogui.keyUp(key) return True # 9-输入 elif op_type_enum == OperateTypeEnum.INPUT: pyperclip.copy(op_content) time.sleep(0.5) if platform.system().lower() == 'windows': pyautogui.hotkey('ctrl', 'v') else: pyautogui.hotkey('command', 'v') return True # 10-打开APP elif op_type_enum == OperateTypeEnum.OPEN_APP: if platform.system().lower() == 'windows': subprocess.Popen(op_content) else: os.system(f'open \"{op_content}\"') return True return False def click_img(wid, op_content, click_num): # 初始化目录 if not os.path.exists(IMG_PATH): os.makedirs(IMG_PATH) if not os.path.exists(f"{IMG_PATH}/{wid}/"): os.makedirs(f"{IMG_PATH}/{wid}/") # 屏幕缩放系数 mac缩放是2 windows一般是1 screenScale = pyautogui.screenshot().size[0] / pyautogui.size()[0] # print(pyautogui.size()) # print(f"屏幕缩放系数:{screenScale}") # 事先读取按钮截图 img_path = f"{IMG_PATH}/{wid}/{op_content}" target = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE) if target is None: print("未找到目标图片") return targetHeight, targetWidth = target.shape[:2] # 先截图 screenshot = pyscreeze.screenshot(f"{IMG_PATH}/screenshot.png") # 读取图片 灰色会快 source = cv2.imread(f"{IMG_PATH}/screenshot.png", cv2.IMREAD_GRAYSCALE) # sourceHeight, sourceWidth = source.shape[:2] # 先缩放屏幕截图(本程序中无需缩放,因为截图就是原图) # sourceScale = cv2.resize(source, (int(sourceWidth / screenScale), int(sourceHeight / screenScale)), interpolation=cv2.INTER_AREA) # print(sourceScale.shape[:2]) # 匹配图片 matchResult = cv2.matchTemplate(source, target, cv2.TM_CCOEFF_NORMED) minVal, maxVal, minLoc, maxLoc = cv2.minMaxLoc(matchResult) # print(f"minVal:{minVal},maxVal:{maxVal},minLoc:{minLoc},maxLoc:{maxLoc}") if maxVal >= 0.8: # 计算出中心点(因为截图就是原图,所以这里要缩放) tagHalfW = int(targetWidth / screenScale / 2) tagHalfH = int(targetHeight / screenScale / 2) tagCenterX = maxLoc[0] / screenScale + tagHalfW tagCenterY = maxLoc[1] / screenScale + tagHalfH # 左键点击屏幕上的这个位置 print(f"tagCenterX:{tagCenterX},tagCenterY:{tagCenterY}") # pyautogui.click(tagCenterX, tagCenterY, button='left') pyautogui.moveTo(x=tagCenterX, y=tagCenterY, duration=0.25) if click_num == 1: pyautogui.click() elif click_num == 2: pyautogui.doubleClick() return True print(f"没有匹配到{op_content}") return False
33.235294
135
0.604277
1696bcdc44faf9716acc2873aabb989ef4b6baca
1,521
py
Python
deprecated/fleet_x/examples/bert_app.py
hutuxian/FleetX
843c7aa33f5a14680becf058a3aaf0327eefafd4
[ "Apache-2.0" ]
170
2020-08-12T12:07:01.000Z
2022-03-07T02:38:26.000Z
deprecated/fleet_x/examples/bert_app.py
hutuxian/FleetX
843c7aa33f5a14680becf058a3aaf0327eefafd4
[ "Apache-2.0" ]
195
2020-08-13T03:22:15.000Z
2022-03-30T07:40:25.000Z
deprecated/fleet_x/examples/bert_app.py
hutuxian/FleetX
843c7aa33f5a14680becf058a3aaf0327eefafd4
[ "Apache-2.0" ]
67
2020-08-14T02:07:46.000Z
2022-03-28T10:05:33.000Z
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import paddle import fleetx as X import paddle.distributed.fleet as fleet paddle.enable_static() fleet.init(is_collective=True) configs = X.parse_train_configs() model = X.applications.BertBase() downloader = X.utils.Downloader() local_path = downloader.download_from_bos( fs_yaml='https://fleet.bj.bcebos.com/small_datasets/yaml_example/wiki_cn.yaml', local_path='./data') loader = model.get_train_dataloader(data_dir=local_path) dist_strategy = fleet.DistributedStrategy() dist_strategy.amp = True learning_rate = X.utils.linear_warmup_decay(configs.lr, 4000, 1000000) clip = paddle.fluid.clip.GradientClipByGlobalNorm(clip_norm=1.0) optimizer = paddle.fluid.optimizer.Adam( learning_rate=learning_rate, grad_clip=clip) optimizer = fleet.distributed_optimizer(optimizer, strategy=dist_strategy) optimizer.minimize(model.loss) trainer = X.MultiGPUTrainer() trainer.fit(model, loader, epoch=1)
37.097561
83
0.788297
bcaddff8d887bb1fd1c11d78ed87b7479ca2753e
2,714
py
Python
build/cpp/verify_runtime_deps.py
opensource-assist/fuschia
66646c55b3d0b36aae90a4b6706b87f1a6261935
[ "BSD-3-Clause" ]
null
null
null
build/cpp/verify_runtime_deps.py
opensource-assist/fuschia
66646c55b3d0b36aae90a4b6706b87f1a6261935
[ "BSD-3-Clause" ]
null
null
null
build/cpp/verify_runtime_deps.py
opensource-assist/fuschia
66646c55b3d0b36aae90a4b6706b87f1a6261935
[ "BSD-3-Clause" ]
null
null
null
#!/usr/bin/env python2.7 # Copyright 2018 The Fuchsia Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import argparse import json import os import sys def has_packaged_file(needed_file, deps): """Returns true if the given file could be found in the given deps.""" for dep in deps: for file in dep['files']: if needed_file == os.path.normpath(file['source']): return True return False def has_missing_files(runtime_files, package_deps): """Returns true if a runtime file is missing from the given deps.""" has_missing_files = False for file in runtime_files: # Some libraries are only known to GN as ABI stubs, whereas the real # runtime dependency is generated in parallel as a ".so.impl" file. if (not has_packaged_file(file, package_deps) and not has_packaged_file('%s.impl' % file, package_deps)): print('No package dependency generates %s' % file) has_missing_files = True return has_missing_files def main(): parser = argparse.ArgumentParser( "Verifies a prebuilt library's runtime dependencies") parser.add_argument( '--root-build-dir', help='Path to the root build directory', required=True) parser.add_argument( '--runtime-deps-file', help='Path to the list of runtime deps', required=True) parser.add_argument( '--manifest', help='Path to the target\'s SDK manifest file', required=True) parser.add_argument( '--stamp', help='Path to the stamp file to generate', required=True) args = parser.parse_args() # Read the list of runtime dependencies generated by GN. def normalize_dep(dep): return os.path.normpath(os.path.join(args.root_build_dir, dep.strip())) with open(args.runtime_deps_file, 'r') as runtime_deps_file: runtime_files = map(normalize_dep, runtime_deps_file.readlines()) # Read the list of package dependencies for the library's SDK incarnation. with open(args.manifest, 'r') as manifest_file: manifest = json.load(manifest_file) atom_id = manifest['ids'][0] def find_atom(id): return next(a for a in manifest['atoms'] if a['id'] == id) atom = find_atom(atom_id) deps = map(lambda a: find_atom(a), atom['deps']) deps += [atom] # Check whether all runtime files are available for packaging. if has_missing_files(runtime_files, deps): return 1 with open(args.stamp, 'w') as stamp: stamp.write('Success!') if __name__ == '__main__': sys.exit(main())
33.097561
79
0.660648
d5c48ed1b49eda67aaff43b79819a2e01281381f
925
py
Python
Python/zzz_training_challenge/Python_Challenge/solutions/ch05_datastructures/util/ListUtils.py
Kreijeck/learning
eaffee08e61f2a34e01eb8f9f04519aac633f48c
[ "MIT" ]
null
null
null
Python/zzz_training_challenge/Python_Challenge/solutions/ch05_datastructures/util/ListUtils.py
Kreijeck/learning
eaffee08e61f2a34e01eb8f9f04519aac633f48c
[ "MIT" ]
null
null
null
Python/zzz_training_challenge/Python_Challenge/solutions/ch05_datastructures/util/ListUtils.py
Kreijeck/learning
eaffee08e61f2a34e01eb8f9f04519aac633f48c
[ "MIT" ]
null
null
null
# Beispielprogramm für das Buch "Python Challenge" # # Copyright 2020 by Michael Inden def swap(values, first, second): value1 = values[first] value2 = values[second] values[first] = value2 values[second] = value1 def swap(values, first, second): tmp = values[first] values[first] = values[second] values[second] = tmp def find(values, search_for): for i in range(len(values)): if values[i] == search_for: return i return -1 def find(values, search_for): pos = 0 while pos < len(values) and not values[pos] == search_for: pos += 1 # i >= len(values) or values[i] == searchFor return -1 if pos >= len(values) else pos def find_with_enumerate(values, search_for): for i, value in enumerate(values): if value == search_for: return i return -1 def main(): pass if __name__ == "__main__": main()
18.137255
62
0.617297
e6cf49e5934c0be95398f25368e771acb43175b6
1,440
py
Python
ebenezer/atencion/migrations/0009_level.py
davrv93/ebenezer-backend
d3db4dafd9a8c35bea9f32afe2be1dd451f64298
[ "Apache-2.0" ]
null
null
null
ebenezer/atencion/migrations/0009_level.py
davrv93/ebenezer-backend
d3db4dafd9a8c35bea9f32afe2be1dd451f64298
[ "Apache-2.0" ]
3
2020-02-11T23:15:00.000Z
2021-06-10T20:52:17.000Z
ebenezer/atencion/migrations/0009_level.py
davrv93/ebenezer-backend
d3db4dafd9a8c35bea9f32afe2be1dd451f64298
[ "Apache-2.0" ]
null
null
null
# Generated by Django 2.1.2 on 2018-10-05 13:43 from django.db import migrations, models import django.db.models.deletion import mptt.fields import uuid class Migration(migrations.Migration): dependencies = [ ('atencion', '0008_typeoflevel'), ] operations = [ migrations.CreateModel( name='Level', fields=[ ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)), ('name', models.CharField(max_length=50, unique=True)), ('description', models.TextField(blank=True, null=True)), ('lft', models.PositiveIntegerField(db_index=True, editable=False)), ('rght', models.PositiveIntegerField(db_index=True, editable=False)), ('tree_id', models.PositiveIntegerField(db_index=True, editable=False)), ('level', models.PositiveIntegerField(db_index=True, editable=False)), ('parent', mptt.fields.TreeForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='children', to='atencion.Level')), ('type_of_level', models.ForeignKey(db_column='type_of_level_id', on_delete=django.db.models.deletion.CASCADE, related_name='level_type_of_level_set', to='atencion.TypeOfLevel')), ], options={ 'abstract': False, }, ), ]
42.352941
195
0.629861
fc006934a13cf8982d1cb7088c731a90c14873bf
2,965
py
Python
Co-Simulation/Sumo/sumo-1.7.0/tools/traci/storage.py
uruzahe/carla
940c2ab23cce1eda1ef66de35f66b42d40865fb1
[ "MIT" ]
4
2020-11-13T02:35:56.000Z
2021-03-29T20:15:54.000Z
Co-Simulation/Sumo/sumo-1.7.0/tools/traci/storage.py
uruzahe/carla
940c2ab23cce1eda1ef66de35f66b42d40865fb1
[ "MIT" ]
9
2020-12-09T02:12:39.000Z
2021-02-18T00:15:28.000Z
Co-Simulation/Sumo/sumo-1.7.0/tools/traci/storage.py
uruzahe/carla
940c2ab23cce1eda1ef66de35f66b42d40865fb1
[ "MIT" ]
1
2020-11-20T19:31:26.000Z
2020-11-20T19:31:26.000Z
# -*- coding: utf-8 -*- # Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo # Copyright (C) 2008-2020 German Aerospace Center (DLR) and others. # This program and the accompanying materials are made available under the # terms of the Eclipse Public License 2.0 which is available at # https://www.eclipse.org/legal/epl-2.0/ # This Source Code may also be made available under the following Secondary # Licenses when the conditions for such availability set forth in the Eclipse # Public License 2.0 are satisfied: GNU General Public License, version 2 # or later which is available at # https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html # SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later # @file storage.py # @author Michael Behrisch # @author Lena Kalleske # @author Mario Krumnow # @author Daniel Krajzewicz # @author Jakob Erdmann # @date 2008-10-09 from __future__ import print_function from __future__ import absolute_import import struct from . import constants as tc _DEBUG = False class Storage: def __init__(self, content): self._content = content self._pos = 0 def read(self, format): oldPos = self._pos self._pos += struct.calcsize(format) return struct.unpack(format, self._content[oldPos:self._pos]) def readInt(self): return self.read("!i")[0] def readTypedInt(self): t, i = self.read("!Bi") assert(t == tc.TYPE_INTEGER) return i def readDouble(self): return self.read("!d")[0] def readTypedDouble(self): t, d = self.read("!Bd") assert(t == tc.TYPE_DOUBLE) return d def readLength(self): length = self.read("!B")[0] if length > 0: return length return self.read("!i")[0] def readString(self): length = self.read("!i")[0] return str(self.read("!%ss" % length)[0].decode("latin1")) def readTypedString(self): t = self.read("!B")[0] assert t == tc.TYPE_STRING, "expected TYPE_STRING (%02x), found %02x." % (tc.TYPE_STRING, t) return self.readString() def readStringList(self): n = self.read("!i")[0] return tuple([self.readString() for i in range(n)]) def readTypedStringList(self): t = self.read("!B")[0] assert(t == tc.TYPE_STRINGLIST) return self.readStringList() def readShape(self): length = self.readLength() return tuple([self.read("!dd") for i in range(length)]) def readCompound(self, expectedSize=None): t, s = self.read("!Bi") assert(t == tc.TYPE_COMPOUND) assert(expectedSize is None or s == expectedSize) return s def ready(self): return self._pos < len(self._content) def printDebug(self): if _DEBUG: for char in self._content[self._pos:]: print("%03i %02x %s" % (ord(char), ord(char), char))
29.949495
100
0.633052
5d5e2faa22593ed62da301da0114b2b99e99f783
2,073
py
Python
code/1/utest.py
pwang13/AutomatedSE_Coursework
b416672d9756fcc60367143b989d29b0c905cfc3
[ "Unlicense" ]
null
null
null
code/1/utest.py
pwang13/AutomatedSE_Coursework
b416672d9756fcc60367143b989d29b0c905cfc3
[ "Unlicense" ]
null
null
null
code/1/utest.py
pwang13/AutomatedSE_Coursework
b416672d9756fcc60367143b989d29b0c905cfc3
[ "Unlicense" ]
null
null
null
#!/usr/bin/python """ utest.py (c) 2016 [email protected], MIT licence Part of http://tiny.cc/ase16: teaching tools for (model-based) automated software enginering. USAGE: (1) If you place '@ok' before a function, then load that file, then that function will execute and all assertion failures will add one to a FAIL count. (2) To get the final counts, add 'oks()' at the end of the source code. For more on this kind of tool, see https://www.youtube.com/watch?v=nIonZ6-4nuU """ from __future__ import division,print_function import sys,re,traceback,random,string sys.dont_write_bytecode=True PASS=FAIL=0 VERBOSE=True def oks(): global PASS, FAIL print("\n# PASS= %s FAIL= %s %%PASS = %s%%" % ( PASS, FAIL, int(round(PASS*100/(PASS+FAIL+0.001))))) def ok(f): global PASS, FAIL try: print("\n-----| %s |-----------------------" % f.__name__) if f.__doc__: print("# "+ re.sub(r'\n[ \t]*',"\n# ",f.__doc__)) f() print("# pass") PASS += 1 except Exception,e: FAIL += 1 print(traceback.format_exc()) return f ################################################# def same(x): return x def any(lst): return random.choice(lst) def any3(lst,a=None,b=None,c=None,it = same,retries=10): assert retries > 0 a = a or any(lst) b = b or any(lst) if it(a) == it(b): return any3(lst,a=a,b=None,it=it,retries=retries - 1) c = any(lst) if it(a) == it(c) or it(b) == it(c): return any3(lst,a=a,b=b,it=it,retries=retries - 1) return a,b,c @ok def _ok1(): "Can at least one test fail?" assert 1==2, "equality failure" @ok def _ok2(): "Can at least one test pass?" assert 1==1, "equality failure" @ok def _any3(): """There are 2600 three letter alphanet combinations. So if we pick just 10, there should be no repeats.""" random.seed(1) lst=list(string.ascii_lowercase) # abcdefghijklmnopqrstuvwxyz seen = {} for x in sorted([''.join(any3(lst)) for _ in xrange(10)]): seen[x] = seen.get(x,0) + 1 for k,v in seen.items(): assert v < 2 print("") oks()
24.104651
64
0.611674
53bb8d640caf8b9381c100c0bce1f921964c5e35
8,422
py
Python
V1/DDPG/ddpg_v1.py
marsXyr/GESRL
3d60dfd4ffa1e0ae24d64b09f431d8ee0a9b5c01
[ "Apache-2.0" ]
null
null
null
V1/DDPG/ddpg_v1.py
marsXyr/GESRL
3d60dfd4ffa1e0ae24d64b09f431d8ee0a9b5c01
[ "Apache-2.0" ]
null
null
null
V1/DDPG/ddpg_v1.py
marsXyr/GESRL
3d60dfd4ffa1e0ae24d64b09f431d8ee0a9b5c01
[ "Apache-2.0" ]
null
null
null
import argparse import numpy as np import gym import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F from utils import logz from utils.tools import get_output_folder, OUNoise, hard_update, soft_update from utils.buffer import ReplayBuffer FloatTensor = torch.FloatTensor """ Actor 和 Critic 分开训练 """ class Actor(nn.Module): def __init__(self, state_dim, action_dim, max_action, args): super(Actor, self).__init__() self.l1 = nn.Linear(state_dim, action_dim, bias=False) self.max_action = max_action self.optim = optim.Adam(self.parameters(), lr=args.critic_lr) self.loss = nn.MSELoss() def forward(self, x): out = self.l1(x) # abs_out = torch.abs(out) # abs_out_sum = torch.sum(abs_out).view(-1, 1) # abs_out_mean = abs_out_sum / self.action_dim / self.theta # ones = torch.ones(abs_out_mean.size()) # ones = ones.cuda() # mod = torch.where(abs_out_mean >= 1, abs_out_mean, ones) # out = out / mod # out = self.max_action * torch.tanh(out) return out def update(self, memory, batch_size, critic, actor_t): # Sample replay buffer states, _, _, _, _ = memory.sample(batch_size) # Compute actor loss actor_loss = - critic(states, self(states)).mean() # Optimize the policy self.optim.zero_grad() actor_loss.backward() self.optim.step() grads = self.get_grads() # Get policy gradients return grads def get_grads(self): grads = [v.grad.data.numpy() for v in self.parameters()] return grads[0] def get_params(self): params = [v.data.numpy() for v in self.parameters()] return params[0] def set_params(self, w): for i, param in enumerate(self.parameters()): param.data.copy_(torch.from_numpy(w).view(param.size())) class Critic(nn.Module): def __init__(self, state_dim, action_dim, args): super(Critic, self).__init__() l1_dim, l2_dim = 400, 300 self.l1 = nn.Linear(state_dim + action_dim, l1_dim) self.l2 = nn.Linear(l1_dim, l2_dim) self.l3 = nn.Linear(l2_dim, 1) if args.layer_norm: self.n1 = nn.LayerNorm(l1_dim) self.n2 = nn.LayerNorm(l2_dim) self.layer_norm = args.layer_norm self.discount = args.discount self.optim = optim.Adam(self.parameters(), lr=args.critic_lr) self.loss = nn.MSELoss() def forward(self, x, u): if not self.layer_norm: x = F.leaky_relu(self.l1(torch.cat([x, u], 1))) x = F.leaky_relu(self.l2(x)) x = self.l3(x) else: x = F.leaky_relu(self.n1(self.l1(torch.cat([x, u], 1)))) x = F.leaky_relu(self.n2(self.l2(x))) x = self.l3(x) return x def update(self, buffer, batch_size, actor_t, critic_t): # Sample replay buffer states, n_states, actions, rewards, dones = buffer.sample(batch_size) # Compute q target next_q = critic_t(n_states, actor_t(n_states)) q_target = (rewards + self.discount * (1 - dones.float()) * next_q).detach() # Compute q predict q_predict = self(states, actions) # Compute critic loss critic_loss = self.loss(q_target, q_predict) # Optimize the critic self.optim.zero_grad() critic_loss.backward() self.optim.step() class DDPG: def __init__(self, state_dim, action_dim, max_action, args): self.state_dim = state_dim self.action_dim = action_dim self.max_action = max_action self._init_parameters(args) self._init_nets(args) self.replay_buffer = ReplayBuffer(self.buffer_size, self.state_dim, self.action_dim) def _init_parameters(self, args): self.actor_lr = args.actor_lr self.critic_lr = args.critic_lr self.discount = args.discount self.tau = args.tau self.buffer_size = args.buffer_size self.batch_size = args.batch_size def _init_nets(self, args): self.actor = Actor(self.state_dim, self.action_dim, self.max_action, args) self.actor_t = Actor(self.state_dim, self.action_dim, self.max_action, args) self.critic = Critic(self.state_dim, self.action_dim, args) self.critic_t = Critic(self.state_dim, self.action_dim, args) hard_update(self.actor_t, self.actor) hard_update(self.critic_t, self.critic) def train(self): self.critic.update(self.replay_buffer, self.batch_size, self.actor, self.critic_t) grad = self.actor.update(self.replay_buffer, self.batch_size, self.critic, self.actor_t) return grad def update_nets(self): soft_update(self.actor_t, self.actor, self.tau) soft_update(self.critic_t, self.critic, self.tau) def run(args): log_dir = args.dir_path env = gym.make(args.env) state_dim = env.observation_space.shape[0] action_dim = env.action_space.shape[0] max_action = int(env.action_space.high[0]) env.seed(args.seed) np.random.seed(args.seed) torch.manual_seed(args.seed) ddpg = DDPG(state_dim, action_dim, max_action, args) ounoise = OUNoise(action_dim) def get_action(state, noise=None): action = ddpg.actor(FloatTensor(state)) action = (action.data.numpy() + noise.add()) if noise else action.data.numpy() return np.clip(action, -max_action, max_action) def rollout(eval=False): state, done, ep_reward, ep_len = env.reset(), False, 0.0, 0 while not done and ep_len < args.max_ep_len: if not eval: action = get_action(state, noise=ounoise) else: action = get_action(state) next_state, reward, done, _ = env.step(action) if not eval: done = False if ep_len + 1 == args.max_ep_len else done ddpg.replay_buffer.store((state, next_state, action, reward, done)) ep_reward += reward ep_len += 1 state = next_state return ep_reward, ep_len for epoch in range(args.epochs): ep_reward, ep_len = rollout(eval=False) if epoch > args.start_epoch: for _ in range(ep_len): ddpg.train() ddpg.update_nets() if epoch % args.save_freq == 0: test_rewards = [] for i in range(10): reward, _ = rollout() test_rewards.append(reward) test_rewards = np.array(test_rewards) np.savez(log_dir + '/policy_weights', ddpg.actor.get_params()) logz.log_tabular("Epoch", epoch) logz.log_tabular("AverageTestReward", np.mean(test_rewards)) logz.log_tabular("StdTestRewards", np.std(test_rewards)) logz.log_tabular("MaxTestRewardRollout", np.max(test_rewards)) logz.log_tabular("MinTestRewardRollout", np.min(test_rewards)) logz.dump_tabular() if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--env', type=str, default='HalfCheetah-v2') # RL parameters parser.add_argument('--actor_lr', type=float, default=0.0001) parser.add_argument('--critic_lr', type=float, default=0.0001) parser.add_argument('--discount', type=float, default=0.99) parser.add_argument('--tau', type=float, default=0.005) parser.add_argument('--batch_size', type=int, default=100) parser.add_argument('--buffer_size', type=int, default=1000000) parser.add_argument('--max_ep_len', type=int, default=1000) parser.add_argument('--layer_norm', type=bool, default=True) parser.add_argument('--epochs', type=int, default=1000) parser.add_argument('--start_epoch', type=int, default=10) parser.add_argument('--save_freq', type=int, default=5) parser.add_argument('--seed', type=int, default=1) parser.add_argument('--dir_path', type=str, default='results_v1/') args = parser.parse_args() output_path = args.dir_path for seed in range(1, 11): args.seed = seed args.dir_path = get_output_folder(output_path, args.env, args.seed) logz.configure_output_dir(args.dir_path) logz.save_params(vars(args)) run(args)
33.553785
96
0.628473
53cc51a93ef82b14a7ec16ec867df498664a7acf
7,468
py
Python
AP_SS16/504/python/plot_helpers.py
DimensionalScoop/kautschuk
90403f97cd60b9716cb6a06668196891d5d96578
[ "MIT" ]
3
2016-04-27T17:07:00.000Z
2022-02-02T15:43:15.000Z
AP_SS16/504/python/plot_helpers.py
DimensionalScoop/kautschuk
90403f97cd60b9716cb6a06668196891d5d96578
[ "MIT" ]
5
2016-04-27T17:10:03.000Z
2017-06-20T14:54:20.000Z
AP_SS16/504/python/plot_helpers.py
DimensionalScoop/kautschuk
90403f97cd60b9716cb6a06668196891d5d96578
[ "MIT" ]
null
null
null
import sys import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np import uncertainties import uncertainties.unumpy as unp from scipy.constants import C2K, K2C from scipy.optimize import curve_fit from uncertainties import ufloat from uncertainties.unumpy import uarray def extract_error(data): if(isinstance(data[0], uncertainties.UFloat)): error = unp.std_devs(data) nominal = unp.nominal_values(data) else: nominal = data error = None return nominal, error def autolimits(data, err=None): min_lim = min(data) max_lim = max(data) offset = (max(data) - min(data)) * 0.025 if err is not None: offset += max(err)/2 return [min_lim - offset, max_lim + offset] def plot(x_messung, y_messung, xlabel, ylabel, filename, theorie): """Plottet diskrete Messwerte gegen eine kontinuierliche Messkurve Args: x_messung (uarray) y_messung (uarray) theorie (func(x)): Theoriefunktion, die x-Werte annimmt und y-Werte ausspuckt xlabel (string) ylabel (string) filename (string) Returns: TYPE: None """ # plt.clf() # plt.clf() x_messung, x_error = extract_error(x_messung) y_messung, y_error = extract_error(y_messung) x_limit = autolimits(x_messung, err=x_error) x_flow = np.linspace(*x_limit, num=1000) y_messung = y_messung if theorie is not None: plt.plot(x_flow, theorie(x_flow), 'g-', label="Fit") #plt.errorbar(x_messung, y_messung, xerr=x_error, yerr=y_error, fmt='r,', label="Fehler") plt.plot(x_messung, y_messung, 'r.', label="Messwerte") plt.xlabel(xlabel) plt.ylabel(ylabel) plt.legend(loc='best') plt.grid() plt.tight_layout(pad=0, h_pad=1.18, w_pad=1.18) # plt.show() plt.savefig('../plots/' + filename) def plot2(x_messung, y_messung, xlabel, ylabel, filename, theorie): """Plottet diskrete Messwerte gegen eine kontinuierliche Messkurve Args: x_messung (uarray) y_messung (uarray) theorie (func(x)): Theoriefunktion, die x-Werte annimmt und y-Werte ausspuckt xlabel (string) ylabel (string) filename (string) Returns: TYPE: None """ # plt.clf() # plt.clf() x_messung, x_error = extract_error(x_messung) y_messung, y_error = extract_error(y_messung) x_limit = autolimits(x_messung, err=x_error) x_flow = np.linspace(*x_limit, num=1000) y_messung = y_messung if theorie is not None: plt.plot(x_flow, theorie(x_flow), 'g-', label="Fit") #plt.errorbar(x_messung, y_messung, xerr=x_error, yerr=y_error, fmt='b,', label="Fehler") plt.plot(x_messung, y_messung, 'b.', label="Messwerte") plt.xlabel(xlabel) plt.ylabel(ylabel) plt.legend(loc='best') plt.xlim(x_limit) plt.ylim(autolimits(y_messung, err=y_error)) plt.grid() plt.tight_layout(pad=0, h_pad=1.18, w_pad=1.18) # plt.show() plt.grid() plt.savefig('../plots/' + filename) def plot3(x_messung, y_messung, xlabel, ylabel, filename, theorie): """Plottet diskrete Messwerte gegen eine kontinuierliche Messkurve Args: x_messung (uarray) y_messung (uarray) theorie (func(x)): Theoriefunktion, die x-Werte annimmt und y-Werte ausspuckt xlabel (string) ylabel (string) filename (string) Returns: TYPE: None """ # plt.clf() # plt.clf() x_messung, x_error = extract_error(x_messung) y_messung, y_error = extract_error(y_messung) x_limit = autolimits(x_messung, err=x_error) x_flow = np.linspace(*x_limit, num=1000) y_messung = y_messung if theorie is not None: plt.plot(x_flow, theorie(x_flow), 'g-', label="Fit") #plt.errorbar(x_messung, y_messung, xerr=x_error, yerr=y_error, fmt='r,', label="Fehler") plt.plot(x_messung, y_messung, 'g.', label="Messwerte") plt.xlabel(xlabel) plt.ylabel(ylabel) plt.legend(loc='best') plt.grid() plt.tight_layout(pad=0, h_pad=1.18, w_pad=1.18) # plt.show() plt.savefig('../plots/' + filename) def plot4(x_messung, y_messung, xlabel, ylabel, filename, theorie): """Plottet diskrete Messwerte gegen eine kontinuierliche Messkurve Args: x_messung (uarray) y_messung (uarray) theorie (func(x)): Theoriefunktion, die x-Werte annimmt und y-Werte ausspuckt xlabel (string) ylabel (string) filename (string) Returns: TYPE: None """ # plt.clf() # plt.clf() x_messung, x_error = extract_error(x_messung) y_messung, y_error = extract_error(y_messung) x_limit = autolimits(x_messung, err=x_error) x_flow = np.linspace(*x_limit, num=1000) y_messung = y_messung if theorie is not None: plt.plot(x_flow, theorie(x_flow), 'g-', label="Fit") #plt.errorbar(x_messung, y_messung, xerr=x_error, yerr=y_error, fmt='r,', label="Fehler") plt.plot(x_messung, y_messung, 'm.', label="Messwerte") plt.xlabel(xlabel) plt.ylabel(ylabel) plt.legend(loc='best') plt.grid() plt.tight_layout(pad=0, h_pad=1.18, w_pad=1.18) # plt.show() plt.savefig('../plots/' + filename) def plot5(x_messung, y_messung, xlabel, ylabel, filename, theorie): """Plottet diskrete Messwerte gegen eine kontinuierliche Messkurve Args: x_messung (uarray) y_messung (uarray) theorie (func(x)): Theoriefunktion, die x-Werte annimmt und y-Werte ausspuckt xlabel (string) ylabel (string) filename (string) Returns: TYPE: None """ # plt.clf() # plt.clf() x_messung, x_error = extract_error(x_messung) y_messung, y_error = extract_error(y_messung) x_limit = autolimits(x_messung, err=x_error) x_flow = np.linspace(*x_limit, num=1000) y_messung = y_messung if theorie is not None: plt.plot(x_flow, theorie(x_flow), 'g-', label="Fit") #plt.errorbar(x_messung, y_messung, xerr=x_error, yerr=y_error, fmt='r,', label="Fehler") plt.plot(x_messung, y_messung, 'y.', label="Messwerte") plt.xlabel(xlabel) plt.ylabel(ylabel) plt.legend(loc='best') plt.grid() plt.tight_layout(pad=0, h_pad=1.18, w_pad=1.18) # plt.show() plt.savefig('../plots/' + filename) def log_plot(x_messung, y_messung, xlabel, ylabel, filename, theorie): """Plottet diskrete Messwerte gegen eine kontinuierliche Messkurve Args: x_messung (uarray) y_messung (uarray) theorie (func(x)): Theoriefunktion, die x-Werte annimmt und y-Werte ausspuckt xlabel (string) ylabel (string) filename (string) Returns: TYPE: None """ # plt.clf() # plt.clf() x_messung, x_error = extract_error(x_messung) y_messung, y_error = extract_error(y_messung) x_limit = autolimits(x_messung, err=x_error) x_flow = np.linspace(*x_limit, num=1000) y_messung = y_messung if theorie is not None: plt.loglog(x_flow, theorie(x_flow), 'g-', label="Fit") #plt.errorbar(x_messung, y_messung, xerr=x_error, yerr=y_error, fmt='r,', label="Fehler") plt.loglog(x_messung, y_messung, 'm.', label="Messwerte") plt.xlabel(xlabel) plt.ylabel(ylabel) plt.legend(loc='best') plt.grid() plt.tight_layout(pad=0, h_pad=1.18, w_pad=1.18) # plt.show() plt.savefig('../plots/' + filename)
26.960289
93
0.647161
4ac9cb55aec05451141c0c5425a601054eed08ff
2,754
py
Python
Automaten/Python/nka_terme.py
jneug/schule-projekte
4f1d56d6bb74a47ca019cf96d2d6cc89779803c9
[ "MIT" ]
2
2020-09-24T12:11:16.000Z
2022-03-31T04:47:24.000Z
Automaten/Python/nka_terme.py
jneug/schule-projekte
4f1d56d6bb74a47ca019cf96d2d6cc89779803c9
[ "MIT" ]
1
2021-02-27T15:06:27.000Z
2021-03-01T16:32:48.000Z
Automaten/Python/nka_terme.py
jneug/schule-projekte
4f1d56d6bb74a47ca019cf96d2d6cc89779803c9
[ "MIT" ]
1
2021-02-24T05:12:35.000Z
2021-02-24T05:12:35.000Z
def transition(state, char, stack_char): new_state = -1 new_stack_chars = "" if state == 0: new_state = 1 new_stack_chars = "S#" elif state == 1: if stack_char in "0123456789+-*:().": new_state = 1 new_stack_chars = "" elif stack_char == "S": if char in "123456789": new_state = 1 new_stack_chars = "A" elif char == "0": new_state = 1 new_stack_chars = "B" elif char == "(": new_state = 1 new_stack_chars = "E)R" elif stack_char == "A": if char in "0123456789": new_state = 1 new_stack_chars = "A" elif char == ".": new_state = 1 new_stack_chars = "C" elif char in "+-:*": new_state = 1 new_stack_chars = "E" elif stack_char == "B": if char == ".": new_state = 1 new_stack_chars = "C" elif char in "+-:*": new_state = 1 new_stack_chars = "E" elif stack_char == "C": if char in "0123456789": new_state = 1 new_stack_chars = "D" elif stack_char == "D": if char in "0123456789": new_state = 1 new_stack_chars = "D" elif char in "+-:*": new_state = 1 new_stack_chars = "E" elif stack_char == "E": if char in "123456789": new_state = 1 new_stack_chars = "A" elif char == "0": new_state = 1 new_stack_chars = "B" elif char == "(": new_state = 1 new_stack_chars = "E)R" elif stack_char == "R": if char in "+-:*": new_state = 1 new_stack_chars = "E" elif char == "": new_state = 2 elif stack_char == "#": new_state = 2 return new_state, new_stack_chars def scan_word(word): state = 0 stack = ["#"] for char in word: stack_char = stack.pop(0) state, stack_chars = transition(state, char, stack_char) for sc in reversed(stack_chars): stack.insert(0, sc) if len(stack) > 0: transition(state, "", stack[0]) return word == "" and state == 2 if __name__ == "__main__": word = input("Bitte ein Wort eingeben: ") accepted = scan_word(word) if accepted: print("Wort gehört zur Sprache") else: print("Wort gehört nicht zur Sprache")
28.391753
64
0.444808
4afe315c7c91d456e84455d89f39e76f2aef0620
7,453
py
Python
Packs/BitDam/Integrations/BitDam/BitDam.py
diCagri/content
c532c50b213e6dddb8ae6a378d6d09198e08fc9f
[ "MIT" ]
799
2016-08-02T06:43:14.000Z
2022-03-31T11:10:11.000Z
Packs/BitDam/Integrations/BitDam/BitDam.py
diCagri/content
c532c50b213e6dddb8ae6a378d6d09198e08fc9f
[ "MIT" ]
9,317
2016-08-07T19:00:51.000Z
2022-03-31T21:56:04.000Z
Packs/BitDam/Integrations/BitDam/BitDam.py
diCagri/content
c532c50b213e6dddb8ae6a378d6d09198e08fc9f
[ "MIT" ]
1,297
2016-08-04T13:59:00.000Z
2022-03-31T23:43:06.000Z
import demistomock as demisto from CommonServerPython import * '''IMPORTS''' import requests import base64 # disable insecure warnings requests.packages.urllib3.disable_warnings() '''INTEGRATION PARAMS''' API_TOKEN = demisto.params().get('apitoken') URL_BASE = demisto.params().get('url') USE_PROXY = demisto.params().get('proxy', False) UNSECURE = not demisto.params().get('insecure', False) '''CONSTANTS''' READ_BINARY_MODE = 'rb' SLASH = '/' SCAN_FILE_URL = 'direct/scan/file/' GET_FILE_VERDICT_URL = 'direct/verdict/?hash={}' TOKEN_PREFIX = 'Bearer' # guardrails-disable-line RESPONSE_CODE_OK = 200 STATUS_IN_PROGRESS = 'IN_PROGRESS' STATUS_DONE = 'DONE' AUTH_HEADERS = { 'Authorization': "{} {}".format(TOKEN_PREFIX, API_TOKEN) } VERDICT_SCANNING = 'Scanning' VERDICT_MALICIOUS = 'Malicious' VERDICT_APPROVED = 'Approved' VERDICT_ERROR = 'Error' VERDICT_BENIGN = 'Benign' VERDICT_TIMEOUT = 'Timeout' SCAN_ONGOING = 'Still scanning...' BITDAM_COMMAND_PREFIX = 'bitdam' DBOTSCORE_UNKNOWN = 0 DBOTSCORE_CLEAN = 1 DBOTSCORE_MALICIOUS = 3 '''HANDLE PROXY''' handle_proxy() '''HELPER FUNCTIONS''' def get_file_bytes(entry_id): get_file_path_res = demisto.getFilePath(entry_id) file_path = get_file_path_res["path"] with open(file_path, READ_BINARY_MODE) as fopen: bytes = fopen.read() return base64.b64encode(bytes) def get_url_base_with_trailing_slash(): ''' Returns the intergation's base url parameter, making sure it contains an trailing slash ''' url_base = URL_BASE return url_base if url_base.endswith(SLASH) else url_base + SLASH def build_json_response(content, context, human_readable): return { 'Type': entryTypes['note'], 'ContentsFormat': formats['json'], 'Contents': content, 'ReadableContentsFormat': formats['markdown'], 'HumanReadable': tableToMarkdown(human_readable, content), 'EntryContext': context } def get_file_name(entry_id): get_file_path_res = demisto.getFilePath(entry_id) return get_file_path_res["name"] def verdict_to_dbotscore(verdict): if VERDICT_APPROVED == verdict: return DBOTSCORE_CLEAN elif VERDICT_MALICIOUS == verdict: return DBOTSCORE_MALICIOUS elif VERDICT_SCANNING == verdict: return DBOTSCORE_UNKNOWN else: return DBOTSCORE_UNKNOWN '''API_IMPL''' def scan_file(): response = scan_file_command() returned_sha1 = parse_scan_file_response(response) # Build demisto reponse response_content = {'SHA1': returned_sha1} response_context = {'BitDam': {'FileScan': {'SHA1': returned_sha1}}} return build_json_response(response_content, response_context, "File was submitted successfully") def scan_file_command(): # Get data to build the request entry_id = demisto.args().get('entryId') file_name = get_file_name(entry_id) file_bytes = get_file_bytes(entry_id) json_data = {'file_name': file_name, 'file_data_base64': base64.b64encode(file_bytes)} raw_json = json.dumps(json_data, ensure_ascii=False) url = "{}{}".format(get_url_base_with_trailing_slash(), SCAN_FILE_URL) # Send the HTTP request response = requests.post(url, data=raw_json, headers=AUTH_HEADERS, verify=UNSECURE) return response def parse_scan_file_response(response): # Parse response if RESPONSE_CODE_OK != response.status_code: raise Exception("Scan file failed. Response code -{}, Data- '{}'".format(str(response.status_code), response.content)) response_json = json.loads(response.content) if 'sha1' not in response_json: raise Exception( "Scan file failed. Bad response json - {}".format(response.content)) returned_sha1 = response_json['sha1'] return returned_sha1 def get_file_verdict(): identifier_value = demisto.args().get('idValue') response = get_file_verdict_command(identifier_value) verdict, status = parse_get_file_verdict_response(response) response_content = {'STATUS': status, 'VERDICT': verdict, 'ID': identifier_value} context = {} context['BitDam.Analysis(val.ID && val.ID == obj.ID)'] = { 'Status': status, 'Verdict': verdict, 'ID': identifier_value } if VERDICT_MALICIOUS == verdict: context[outputPaths['file']] = {'SHA1': identifier_value} context[outputPaths['file']]['Malicious'] = { 'Vendor': 'BitDam', 'Description': 'Process whitelist inconsistency by bitdam-get-file-verdict', 'Name': identifier_value } dbotscore = verdict_to_dbotscore(verdict) if dbotscore: context[outputPaths['dbotscore']] = { 'Indicator': identifier_value, 'Type': 'File', 'Vendor': 'BitDam', 'Score': dbotscore } response_context = context return build_json_response(response_content, response_context, "Get file verdict was performed successfully") def parse_get_file_verdict_response(response): # Parse results if RESPONSE_CODE_OK != response.status_code: raise Exception("Get file verdict failed. Response code -{}, Data- '{}'".format(str(response.status_code), response.content)) response_json = json.loads(response.content) status = '' verdict = '' if 'scan_data' not in response_json or 'verdict' not in response_json['scan_data']: raise Exception("Get file verdict failed. Unknown response schema. Data- '{}'".format(response.content)) verdict = response_json['scan_data']['verdict'] if verdict == SCAN_ONGOING or verdict == VERDICT_SCANNING: # Still in progress verdict = VERDICT_SCANNING status = STATUS_IN_PROGRESS else: status = STATUS_DONE return verdict, status def get_file_verdict_command(identifier_value): # Get data to build the request scan_file_relative_url_formatted = GET_FILE_VERDICT_URL.format(identifier_value) url = "{}{}".format(get_url_base_with_trailing_slash(), scan_file_relative_url_formatted) # Send the request response = requests.get(url, headers=AUTH_HEADERS, verify=UNSECURE) return response def upload_test_file_to_scan(): d = { "file_name": "demisto.txt", "file_data_base64": 'ZGVtaXN0bw==' } url = "{}{}".format(get_url_base_with_trailing_slash(), SCAN_FILE_URL) response = requests.post(url, headers=AUTH_HEADERS, json=d, verify=UNSECURE) return response def test_module(): response = upload_test_file_to_scan() if RESPONSE_CODE_OK == response.status_code: return True raise Exception("Status code - {}, Error- '{}'".format(str(response.status_code), response.content)) '''COMMAND_CLASIFIER''' try: if demisto.command() == 'test-module': # This is the call made when pressing the integration test button. if test_module(): demisto.results('ok') sys.exit(0) elif demisto.command() == 'bitdam-upload-file': demisto.results(scan_file()) elif demisto.command() == 'bitdam-get-verdict': demisto.results(get_file_verdict()) except Exception as e: LOG(e) return_error("Error: {}".format(str(e)))
32.404348
126
0.671407
db6dce16e99bbd21687167c6e3bf52f7bad1adc0
1,024
py
Python
PINp/2014/Chernov_M_S/task_9_27.py
YukkaSarasti/pythonintask
eadf4245abb65f4400a3bae30a4256b4658e009c
[ "Apache-2.0" ]
null
null
null
PINp/2014/Chernov_M_S/task_9_27.py
YukkaSarasti/pythonintask
eadf4245abb65f4400a3bae30a4256b4658e009c
[ "Apache-2.0" ]
null
null
null
PINp/2014/Chernov_M_S/task_9_27.py
YukkaSarasti/pythonintask
eadf4245abb65f4400a3bae30a4256b4658e009c
[ "Apache-2.0" ]
null
null
null
#Задача 9. Вариант 27. #Создайте игру, в которой компьютер выбирает какое-либо слово, а игрок должен его отгадать. Компьютер сообщает игроку, сколько букв в слове, и дает пять попыток узнать, есть ли какая-либо буква в слове, причем программа может отвечать только "Да" и "Нет". Вслед за тем игрок должен попробовать отгадать слово. import random WORDS=("ромашка", "тюльпан", "кактус", "фиалка", "нарцисс", "гвоздика", "гладиолус", "жасмин") word=random.choice(WORDS) live=5 bukva="" slovo="" (number)=len(word) print("Компьютер загадал слово. Твоя цель угадать его. \nВ этом слове ",str(number)," букв.") print("У тебя "+str(live)+" попыток угадать буквы.") while live>0: bukva=input("Введите букву\n") if bukva in list (word): print("Да") live=live-1 else: print("Нет") live=live-1 if live==0: slovo=input("Ваши попытки кончились. \nВведите слово\n") if slovo==word: print("Поздравляю! Вы угадали слово :)") else: print("Вы не угадали слово :(") input("Нажмите Enter") #Chernov M. S. #28.05.2016
36.571429
309
0.708984
dbb0f6ca9a74b0ed550f6304dee3919819bd64f3
728
py
Python
tools/pythonpkg/tests/fast/test_transaction.py
AldoMyrtaj/duckdb
3aa4978a2ceab8df25e4b20c388bcd7629de73ed
[ "MIT" ]
2,816
2018-06-26T18:52:52.000Z
2021-04-06T10:39:15.000Z
tools/pythonpkg/tests/fast/test_transaction.py
AldoMyrtaj/duckdb
3aa4978a2ceab8df25e4b20c388bcd7629de73ed
[ "MIT" ]
1,310
2021-04-06T16:04:52.000Z
2022-03-31T13:52:53.000Z
tools/pythonpkg/tests/fast/test_transaction.py
AldoMyrtaj/duckdb
3aa4978a2ceab8df25e4b20c388bcd7629de73ed
[ "MIT" ]
270
2021-04-09T06:18:28.000Z
2022-03-31T11:55:37.000Z
import duckdb import pandas as pd class TestConnectionTransaction(object): def test_transaction(self, duckdb_cursor): con = duckdb.connect() con.execute('create table t (i integer)') con.execute ('insert into t values (1)') con.begin() con.execute ('insert into t values (1)') assert con.execute('select count (*) from t').fetchone()[0] == 2 con.rollback() assert con.execute('select count (*) from t').fetchone()[0] == 1 con.begin() con.execute ('insert into t values (1)') assert con.execute('select count (*) from t').fetchone()[0] == 2 con.commit() assert con.execute('select count (*) from t').fetchone()[0] == 2
36.4
72
0.596154
91a50515d6ddfd3b7262f7be8ec40e6696dd3187
304
py
Python
Chapter2_Python/ZipEnumerate.py
thisisjako/UdemyTF
ee4102391ed6bd50f764955f732f5740425a9209
[ "MIT" ]
null
null
null
Chapter2_Python/ZipEnumerate.py
thisisjako/UdemyTF
ee4102391ed6bd50f764955f732f5740425a9209
[ "MIT" ]
null
null
null
Chapter2_Python/ZipEnumerate.py
thisisjako/UdemyTF
ee4102391ed6bd50f764955f732f5740425a9209
[ "MIT" ]
null
null
null
list_a = [10, 20, 30] list_b = ["Jan", "Peter", "Max"] list_c = [True, False, True] for val_a, val_b, val_c in zip(list_a, list_b, list_c): print(val_a, val_b, val_c) print("\n") for i in range(len(list_a)): print(i, list_a[i]) print("\n") for i, val in enumerate(list_a): print(i, val)
17.882353
55
0.615132
91b1c7f2319c2b96912a3d9b4ae99fedff955d99
8,833
py
Python
Tests/Marketplace/search_and_uninstall_pack.py
jrauen/content
81a92be1cbb053a5f26a6f325eff3afc0ca840e0
[ "MIT" ]
null
null
null
Tests/Marketplace/search_and_uninstall_pack.py
jrauen/content
81a92be1cbb053a5f26a6f325eff3afc0ca840e0
[ "MIT" ]
40
2022-03-03T07:34:00.000Z
2022-03-31T07:38:35.000Z
Tests/Marketplace/search_and_uninstall_pack.py
jrauen/content
81a92be1cbb053a5f26a6f325eff3afc0ca840e0
[ "MIT" ]
null
null
null
import ast import json import argparse import os import sys import demisto_client from Tests.scripts.utils import logging_wrapper as logging from Tests.scripts.utils.log_util import install_logging from Tests.Marketplace.search_and_install_packs import install_packs from time import sleep def get_all_installed_packs(client: demisto_client): """ Args: client (demisto_client): The client to connect to. Returns: list of installed python """ try: logging.info("Attempting to fetch all installed packs.") response_data, status_code, _ = demisto_client.generic_request_func(client, path='/contentpacks/metadata/installed', method='GET', accept='application/json', _request_timeout=None) if 200 <= status_code < 300: installed_packs = ast.literal_eval(response_data) installed_packs_ids = [pack.get('id') for pack in installed_packs] logging.success('Successfully fetched all installed packs.') installed_packs_ids_str = ', '.join(installed_packs_ids) logging.debug( f'The following packs are currently installed from a previous build run:\n{installed_packs_ids_str}') if 'Base' in installed_packs_ids: installed_packs_ids.remove('Base') return installed_packs_ids else: result_object = ast.literal_eval(response_data) message = result_object.get('message', '') raise Exception(f'Failed to fetch installed packs - with status code {status_code}\n{message}') except Exception as e: logging.exception(f'The request to fetch installed packs has failed. Additional info: {str(e)}') return None def uninstall_packs(client: demisto_client, pack_ids: list): """ Args: client (demisto_client): The client to connect to. pack_ids: packs ids to uninstall Returns: True if uninstalling succeeded False otherwise. """ body = {"IDs": pack_ids} try: logging.info("Attempting to uninstall all installed packs.") response_data, status_code, _ = demisto_client.generic_request_func(client, path='/contentpacks/installed/delete', method='POST', body=body, accept='application/json', _request_timeout=None) except Exception as e: logging.exception(f'The request to uninstall packs has failed. Additional info: {str(e)}') return False return True def uninstall_all_packs(client: demisto_client, hostname): """ Lists all installed packs and uninstalling them. Args: client (demisto_client): The client to connect to. hostname (str): xsiam hostname Returns (list, bool): A flag that indicates if the operation succeeded or not. """ logging.info(f'Starting to search and uninstall packs in server: {hostname}') packs_to_uninstall: list = get_all_installed_packs(client) if packs_to_uninstall: return uninstall_packs(client, packs_to_uninstall) logging.debug('Skipping packs uninstallation - nothing to uninstall') return True def reset_base_pack_version(client: demisto_client): """ Resets base pack version to prod version. Args: client (demisto_client): The client to connect to. """ host = client.api_client.configuration.host.replace('https://api-', 'https://') # disable-secrets-detection try: # make the search request response_data, status_code, _ = demisto_client.generic_request_func(client, path='/contentpacks/marketplace/Base', method='GET', accept='application/json', _request_timeout=None) if 200 <= status_code < 300: result_object = ast.literal_eval(response_data) if result_object and result_object.get('currentVersion'): logging.debug('Found Base pack in bucket!') pack_data = { 'id': result_object.get('id'), 'version': result_object.get('currentVersion') } # install latest version of Base pack logging.info(f'updating base pack to version {result_object.get("currentVersion")}') return install_packs(client, host, [pack_data], False) else: raise Exception('Did not find Base pack') else: result_object = ast.literal_eval(response_data) msg = result_object.get('message', '') err_msg = f'Search request for base pack, failed with status code ' \ f'{status_code}\n{msg}' raise Exception(err_msg) except Exception: logging.exception('Search request Base pack has failed.') return False def wait_for_uninstallation_to_complete(client: demisto_client, retries: int = 30): """ Query if there are still installed packs, as it might take time to complete. Args: client (demisto_client): The client to connect to. retries: Max number of sleep priods. Returns: True if all packs were uninstalled successfully """ retry = 0 try: installed_packs = get_all_installed_packs(client) while len(installed_packs) > 1: if retry > retries: raise Exception('Waiting time for packs to be uninstalled has passed, there are still installed ' 'packs. Aborting.') logging.info(f'The process of uninstalling all packs is not over! There are still {len(installed_packs)} ' f'packs installed. Sleeping for 10 seconds.') sleep(10) installed_packs = get_all_installed_packs(client) retry = retry + 1 except Exception as e: logging.exception(f'Exception while waiting for the packs to be uninstalled. The error is {e}') return False return True def options_handler(): """ Returns: options parsed from input arguments. """ parser = argparse.ArgumentParser(description='Utility for instantiating and testing integration instances') parser.add_argument('--xsiam_machine', help='XSIAM machine to use, if it is XSIAM build.') parser.add_argument('--xsiam_servers_path', help='Path to secret xsiam server metadata file.') options = parser.parse_args() return options def get_json_file(path): """ Args: path: path to retrieve file from. Returns: json object loaded from the path. """ with open(path, 'r') as json_file: return json.loads(json_file.read()) def get_xsiam_configuration(xsiam_machine, xsiam_servers): """ Parses conf params from servers list. """ conf = xsiam_servers.get(xsiam_machine) return conf.get('api_key'), conf.get('base_url'), conf.get('x-xdr-auth-id') def main(): install_logging('cleanup_xsiam_instance.log', logger=logging) # in xsiam we dont use demisto username os.environ.pop('DEMISTO_USERNAME', None) options = options_handler() host = options.xsiam_machine xsiam_servers = get_json_file(options.xsiam_servers_path) api_key, base_url, xdr_auth_id = get_xsiam_configuration(options.xsiam_machine, xsiam_servers) logging.info(f'Starting cleanup for XSIAM server {host}') client = demisto_client.configure(base_url=base_url, verify_ssl=False, api_key=api_key, auth_id=xdr_auth_id) success = reset_base_pack_version(client) and uninstall_all_packs(client, host) and wait_for_uninstallation_to_complete( client) if not success: sys.exit(2) logging.info('Uninstalling packs done.') if __name__ == '__main__': main()
38.404348
118
0.582475
91d503c31210a49b924dbb63337d444d4de28f5c
2,853
py
Python
.vscode/extensions/ms-vscode.cpptools-1.9.0/debugAdapters/lldb/lib/python2.7/site-packages/lldb/formatters/Logger.py
Kvahn-ui/dotfiles
3f1364410f5bebcaacca6ae38a8e5fbb9bb51285
[ "MIT" ]
3
2016-02-10T14:18:40.000Z
2018-02-05T03:15:56.000Z
.vscode/extensions/ms-vscode.cpptools-1.9.0/debugAdapters/lldb/lib/python2.7/site-packages/lldb/formatters/Logger.py
Kvahn-ui/dotfiles
3f1364410f5bebcaacca6ae38a8e5fbb9bb51285
[ "MIT" ]
4
2019-06-16T09:52:03.000Z
2019-08-18T02:11:35.000Z
.vscode/extensions/ms-vscode.cpptools-1.9.0/debugAdapters/lldb/lib/python2.7/site-packages/lldb/formatters/Logger.py
Kvahn-ui/dotfiles
3f1364410f5bebcaacca6ae38a8e5fbb9bb51285
[ "MIT" ]
null
null
null
from __future__ import print_function import sys import os.path import inspect class NopLogger: def __init__(self): pass def write(self,data): pass def flush(self): pass def close(self): pass class StdoutLogger: def __init__(self): pass def write(self,data): print(data) def flush(self): pass def close(self): pass class FileLogger: def __init__(self, name): self.file = None try: name = os.path.abspath(name) self.file = open(name,'a') except: try: self.file = open('formatters.log','a') except: pass def write(self,data): if self.file != None: print(data,file=self.file) else: print(data) def flush(self): if self.file != None: self.file.flush() def close(self): if self.file != None: self.file.close() self.file = None # to enable logging: # define lldb.formatters.Logger._lldb_formatters_debug_level to any number greater than 0 # if you define it to any value greater than 1, the log will be automatically flushed after each write (slower but should make sure most of the stuff makes it to the log even if we crash) # if you define it to any value greater than 2, the calling function's details will automatically be logged (even slower, but provides additional details) # if you need the log to go to a file instead of on screen, define lldb.formatters.Logger._lldb_formatters_debug_filename to a valid filename class Logger: def __init__(self,autoflush=False,logcaller=False): global _lldb_formatters_debug_level global _lldb_formatters_debug_filename self.autoflush = autoflush want_log = False try: want_log = (_lldb_formatters_debug_level > 0) except: pass if not (want_log): self.impl = NopLogger() return want_file = False try: want_file = (_lldb_formatters_debug_filename != None and _lldb_formatters_debug_filename != '' and _lldb_formatters_debug_filename != 0) except: pass if want_file: self.impl = FileLogger(_lldb_formatters_debug_filename) else: self.impl = StdoutLogger() try: self.autoflush = (_lldb_formatters_debug_level > 1) except: self.autoflush = autoflush want_caller_info = False try: want_caller_info = (_lldb_formatters_debug_level > 2) except: pass if want_caller_info: self._log_caller() def _log_caller(self): caller = inspect.stack()[2] try: if caller != None and len(caller) > 3: self.write('Logging from function ' + str(caller)) else: self.write('Caller info not available - Required caller logging not possible') finally: del caller # needed per Python docs to avoid keeping objects alive longer than we care def write(self,data): self.impl.write(data) if self.autoflush: self.flush() def __rshift__(self,data): self.write(data) def flush(self): self.impl.flush() def close(self): self.impl.close()
23.195122
187
0.719243
37eff26f5b825f76373d94f0673d1cfc9374a61d
442
py
Python
tests/test_types.py
fgoettel/wgt
e093e2a003fa6c9d4c2082cebbc95701d7f9089d
[ "Unlicense" ]
null
null
null
tests/test_types.py
fgoettel/wgt
e093e2a003fa6c9d4c2082cebbc95701d7f9089d
[ "Unlicense" ]
null
null
null
tests/test_types.py
fgoettel/wgt
e093e2a003fa6c9d4c2082cebbc95701d7f9089d
[ "Unlicense" ]
1
2022-01-29T12:01:47.000Z
2022-01-29T12:01:47.000Z
#!/usr/bin/env python3 """Tests for `wgt` types.""" import pytest from wgt import types def test_celsius(): """Test celsisus as representative of units.""" expected = 42.42 celsius = types.Celsius(expected) assert celsius.value == expected assert celsius.unit == "°C" assert celsius.name == str(expected) assert str(celsius) == str(celsius.value) + celsius.unit if __name__ == "__main__": pytest.main()
20.090909
60
0.662896
53587c8e62ac8bf101f88a22bd046e76f3b783e7
4,453
py
Python
magenta_docker/task.py
googleinterns/step258-2020
49e7af1a381e076ee884f55857a7af2f72add74d
[ "Apache-2.0" ]
2
2020-08-28T15:17:40.000Z
2022-01-21T14:03:21.000Z
magenta_docker/task.py
googleinterns/step258-2020
49e7af1a381e076ee884f55857a7af2f72add74d
[ "Apache-2.0" ]
1
2021-01-27T18:22:46.000Z
2021-01-27T20:58:55.000Z
magenta_docker/task.py
googleinterns/step258-2020
49e7af1a381e076ee884f55857a7af2f72add74d
[ "Apache-2.0" ]
4
2020-07-28T12:13:11.000Z
2021-01-27T16:29:29.000Z
"""Script for running a containerised training on Google Cloud AI Platform.""" import json import os import subprocess from absl import app from absl import flags FLAGS = flags.FLAGS flags.DEFINE_string('save_dir', None, 'Path where checkpoints and summary events will be saved ' 'during training and evaluation.') flags.DEFINE_string('restore_dir', '', 'Path from which checkpoints will be restored before ' 'training. Can be different than the save_dir.') flags.DEFINE_string('file_pattern', None, 'Data file pattern') flags.DEFINE_integer('batch_size', 32, 'Batch size') flags.DEFINE_float('learning_rate', 0.003, 'Learning rate') flags.DEFINE_integer('num_steps', 30000, 'Number of training steps') flags.DEFINE_float('early_stop_loss_value', 0.0, 'Early stopping. When the total_loss reaches below this ' 'value training stops.') flags.DEFINE_integer('steps_per_summary', 300, 'Steps per summary') flags.DEFINE_integer('steps_per_save', 300, 'Steps per save') flags.DEFINE_boolean('hypertune', False, 'Enable metric reporting for hyperparameter tuning.') flags.DEFINE_multi_string('gin_search_path', [], 'Additional gin file search paths. ' 'Must be paths inside Docker container and ' 'necessary gin configs should be added at the ' 'Docker image building stage.') flags.DEFINE_multi_string('gin_file', [], 'List of paths to the config files. If file ' 'in gstorage bucket specify whole gstorage path: ' 'gs://bucket-name/dir/in/bucket/file.gin. If path ' 'should be local remember about copying the file ' 'inside the Docker container at building stage. ') flags.DEFINE_multi_string('gin_param', [], 'Newline separated list of Gin parameter bindings.') def get_worker_behavior_info(save_dir): """Infers worker behavior from the environment. Checks if TF_CONFIG environment variable is set and inferes cluster configuration and save_dir from it. Args: save_dir: Save directory given by the user. Returns: cluster_config: Infered cluster configuration. save_dir: Infered save directory. """ if 'TF_CONFIG' in os.environ: cluster_config = os.environ['TF_CONFIG'] cluster_config_dict = json.loads(cluster_config) if ('cluster' not in cluster_config_dict.keys() or 'task' not in cluster_config_dict or len(cluster_config_dict['cluster']) <= 1): cluster_config = '' elif cluster_config_dict['task']['type'] != 'chief': save_dir = '' else: cluster_config = '' return cluster_config, save_dir def parse_list_params(list_of_params, param_name): return [f'--{param_name}={param}' for param in list_of_params] def main(unused_argv): restore_dir = FLAGS.save_dir if not FLAGS.restore_dir else FLAGS.restore_dir cluster_config, save_dir = get_worker_behavior_info(FLAGS.save_dir) gin_search_path = parse_list_params(FLAGS.gin_search_path, 'gin_search_path') gin_file = parse_list_params(FLAGS.gin_file, 'gin_file') gin_param = parse_list_params(FLAGS.gin_param, 'gin_param') ddsp_run_command = ( ['ddsp_run', '--mode=train', '--alsologtostderr', '--gin_file=models/solo_instrument.gin', '-gin_file=datasets/tfrecord.gin', f'--cluster_config={cluster_config}', f'--save_dir={save_dir}', f'--restore_dir={restore_dir}', f'--hypertune={FLAGS.hypertune}', f'--early_stop_loss_value={FLAGS.early_stop_loss_value}', f'--gin_param=batch_size={FLAGS.batch_size}', f'--gin_param=learning_rate={FLAGS.learning_rate}', f'--gin_param=TFRecordProvider.file_pattern=\'{FLAGS.file_pattern}\'', f'--gin_param=train_util.train.num_steps={FLAGS.num_steps}', f'--gin_param=train_util.train.steps_per_save={FLAGS.steps_per_save}', ('--gin_param=train_util.train.steps_per_summary=' f'{FLAGS.steps_per_summary}')] + gin_search_path + gin_file + gin_param) subprocess.run(args=ddsp_run_command, check=True) if __name__ == '__main__': flags.mark_flag_as_required('file_pattern') flags.mark_flag_as_required('save_dir') app.run(main)
38.387931
79
0.669661
be44d532f6aa12d608ccd0be0854223b83c35355
4,444
py
Python
blockchain/wallet.py
tobias-fyi/xebec
731112b60ab4bd915a9c3f57a3a96c2e37b4a119
[ "MIT" ]
null
null
null
blockchain/wallet.py
tobias-fyi/xebec
731112b60ab4bd915a9c3f57a3a96c2e37b4a119
[ "MIT" ]
8
2020-03-24T17:47:23.000Z
2022-03-12T00:33:21.000Z
cs/lambda_cs/05_hash_tables_and_blockchain/Blockchain/client_mining_p/wallet.py
tobias-fyi/vela
b0b3d3c6dc3fa397c8c7a492098a02cf75e0ff82
[ "MIT" ]
null
null
null
""" Blockchain — Day 2 Project :: Wallet app > MVP * Allow the user to enter, save, or change the `user_id` used for the program * Display the current balance for that user * Display a list of all transactions for this user, including sender and recipient > Stretch Goals * Use styling to visually distinguish coins sent and coins received * Paginate the list of transactions if there are more than ten """ import json from pprint import pprint import requests class User: def __init__( self, user_id: str = "007", balance: float = 0.0, url: str = "http://localhost:5000", ): """Constructor for the user account management handler class.""" self.user_id = user_id self.url = url self.cache = [] self.last_index = 0 self.balance = balance @property def user_id(self) -> str: """User's account identifier.""" return self._user_id @user_id.setter def user_id(self, new_id) -> None: """Setter function for user_id property.""" self._user_id = new_id print(f"User ID: {new_id}") @property def balance(self) -> None: """User's current number of coins.""" return self._balance @balance.setter def balance(self, value: float) -> None: """Setter function for balance property.""" self._balance = value def show_transactions(self) -> None: """Displays user's transactions.""" pprint(self.cache) def post_transaction(self, recipient: str, amt: float) -> int: """Posts a new transaction from the user. Returns index of block into which transaction was posted.""" # TODO: Check if user has enough coins if self.balance - amt < 0: print("Error: Not enough coins for transaction") else: # Construct the POST object post_data = { "sender": self.user_id, "recipient": recipient, "amount": amt, } # Post transaction to blockchain server r = requests.post(url=self.url + "/transactions/new", json=post_data) # Parse the response if r.status_code == 200: resp = r.json() print(resp.get("message")) return resp.get("index") else: print("Post failed.") def get_transactions(self) -> list: """Helper function for retrieving all transactions involving user.""" # Retrieve full chain r = requests.get(url=self.url + "/chain") # Parse into list of dictionaries chain = r.json()["chain"] # Iterate through chain, starting after last processed block for block in chain[self.last_index :]: # Iterate through each block's transactions for transaction in block["transactions"]: # Look for transactions where user_id is recipient or sender if self.user_id in transaction.values(): # Add transaction to user's transaction cache transaction["block_index"] = block["index"] transaction["block_timestamp"] = block["timestamp"] self.cache.append(transaction) # Update user's balance if transaction["recipient"] == self.user_id: self.balance += transaction["amount"] else: self.balance -= transaction["amount"] self.last_index += 1 # Count block as processed print(f"Updated wallet up to block {self.last_index + 1}") if __name__ == "__main__": # === Instantiate users james_bond = User(user_id="007", balance=100.0) jane_bond = User(user_id="008", balance=50.0) # === Update wallets james_bond.get_transactions() jane_bond.get_transactions() # === Print balances print(james_bond.balance) print(jane_bond.balance) # === Post transactions james_bond.post_transaction("008", 1.8) jane_bond.post_transaction("007", 0.7) # === Post transactions jane_bond.post_transaction("007", 7.7) james_bond.post_transaction("008", 8.8) # === Update wallets james_bond.get_transactions() jane_bond.get_transactions() # === Print balances print(james_bond.balance) print(jane_bond.balance)
32.202899
82
0.593384
be488e981ad6a83f4dbe5d20f646a189ebba482e
959
py
Python
methods/transformers/examples/seq2seq/save_randomly_initialized_model.py
INK-USC/RiddleSense
a3d57eaf084da9cf6b77692c608e2cd2870fbd97
[ "MIT" ]
3
2021-07-06T20:02:31.000Z
2022-03-27T13:13:01.000Z
methods/transformers/examples/seq2seq/save_randomly_initialized_model.py
INK-USC/RiddleSense
a3d57eaf084da9cf6b77692c608e2cd2870fbd97
[ "MIT" ]
null
null
null
methods/transformers/examples/seq2seq/save_randomly_initialized_model.py
INK-USC/RiddleSense
a3d57eaf084da9cf6b77692c608e2cd2870fbd97
[ "MIT" ]
null
null
null
#!/usr/bin/env python import fire from transformers import AutoConfig, AutoModelForSeq2SeqLM, AutoTokenizer def save_randomly_initialized_version(config_name: str, save_dir: str, **config_kwargs): """Save a randomly initialized version of a model using a pretrained config. Args: config_name: which config to use save_dir: where to save the resulting model and tokenizer config_kwargs: Passed to AutoConfig Usage:: save_randomly_initialized_version("facebook/bart-large-cnn", "distilbart_random_cnn_6_3", encoder_layers=6, decoder_layers=3, num_beams=3) """ cfg = AutoConfig.from_pretrained(config_name, **config_kwargs) model = AutoModelForSeq2SeqLM.from_config(cfg) model.save_pretrained(save_dir) AutoTokenizer.from_pretrained(config_name).save_pretrained(save_dir) return model if __name__ == "__main__": fire.Fire(save_randomly_initialized_version)
35.518519
147
0.741397
fe657793db522efafe2f203d65640858801013a6
12,785
py
Python
Packs/UBIRCH/Integrations/UBIRCH/UBIRCH.py
diCagri/content
c532c50b213e6dddb8ae6a378d6d09198e08fc9f
[ "MIT" ]
799
2016-08-02T06:43:14.000Z
2022-03-31T11:10:11.000Z
Packs/UBIRCH/Integrations/UBIRCH/UBIRCH.py
diCagri/content
c532c50b213e6dddb8ae6a378d6d09198e08fc9f
[ "MIT" ]
9,317
2016-08-07T19:00:51.000Z
2022-03-31T21:56:04.000Z
Packs/UBIRCH/Integrations/UBIRCH/UBIRCH.py
diCagri/content
c532c50b213e6dddb8ae6a378d6d09198e08fc9f
[ "MIT" ]
1,297
2016-08-04T13:59:00.000Z
2022-03-31T23:43:06.000Z
import demistomock as demisto from CommonServerPython import * # noqa # pylint: disable=unused-wildcard-import from CommonServerUserPython import * # noqa import paho.mqtt.client as mqtt import paho from typing import Callable import traceback import json ''' CONSTANTS ''' QOS_AT_LEAST_ONCE = 1 # SEVERITY CRITICAL_SEVERITY = 4 HIGH_SEVERITY = 3 MEDIUM_SEVERITY = 2 LOW_SEVERITY = 1 UNKNOWN_SEVERITY = 0 # Types AUTHENTICATION_TYPE = 'Authentication' AUTHENTICITY_TYPE = 'UBIRCH Authenticity' INTEGRITY_TYPE = 'UBIRCH Integrity' PRIVACY_TYPE = 'UBIRCH Privacy' SEQUENCE_TYPE = 'UBIRCH Sequence' # Fields SEVERITY_FIELD = "severity" TYPE_FIELD = "type" MEANING_FIELD = "meaning" INCIDENT_SEVERITY_MAP = { "niomon-auth": { "1000": { MEANING_FIELD: "Authentication error: request malformed. Possible missing header and parameters.", SEVERITY_FIELD: LOW_SEVERITY, TYPE_FIELD: AUTHENTICATION_TYPE }, "2000": { MEANING_FIELD: "Authentication error: processing authentication response/Failed Request", SEVERITY_FIELD: LOW_SEVERITY, TYPE_FIELD: AUTHENTICATION_TYPE }, "3000": { MEANING_FIELD: "Authentication error (3rd party): error processing authentication request", SEVERITY_FIELD: LOW_SEVERITY, TYPE_FIELD: AUTHENTICATION_TYPE }, "4000": { MEANING_FIELD: "Authentication error: Failed Request", SEVERITY_FIELD: LOW_SEVERITY, TYPE_FIELD: AUTHENTICATION_TYPE } }, "niomon-decoder": { "1100": { MEANING_FIELD: "Invalid verification: request malformed. Possible missing headers or parameters.", SEVERITY_FIELD: MEDIUM_SEVERITY, TYPE_FIELD: AUTHENTICITY_TYPE }, "1200": { MEANING_FIELD: "Invalid verification: invalid parts", SEVERITY_FIELD: HIGH_SEVERITY, TYPE_FIELD: AUTHENTICITY_TYPE }, "1300": { MEANING_FIELD: "Invalid verification: signature verification failed. No public key or integrity is " "compromised.", SEVERITY_FIELD: HIGH_SEVERITY, TYPE_FIELD: AUTHENTICITY_TYPE }, "2100": { MEANING_FIELD: "Decoding error: request malformed. Possible missing headers or parameters.", SEVERITY_FIELD: LOW_SEVERITY, TYPE_FIELD: INTEGRITY_TYPE }, "2200": { MEANING_FIELD: "Decoding Error: Invalid Match", SEVERITY_FIELD: MEDIUM_SEVERITY, TYPE_FIELD: INTEGRITY_TYPE }, "2300": { MEANING_FIELD: "Decoding Error: Decoding Error/Null Payload", SEVERITY_FIELD: LOW_SEVERITY, TYPE_FIELD: INTEGRITY_TYPE } }, "niomon-enricher": { "1000": { MEANING_FIELD: "Tenant error: the owner of the device cannot be determined. Possible missing headers or " "parameters or body.", SEVERITY_FIELD: LOW_SEVERITY, TYPE_FIELD: AUTHENTICITY_TYPE }, "2000": { MEANING_FIELD: "Tenant error: the owner of the device does not exist or cannot be acquired.", SEVERITY_FIELD: HIGH_SEVERITY, TYPE_FIELD: AUTHENTICITY_TYPE }, "0000": { MEANING_FIELD: "Tenant error: the owner of the device does not exist or cannot be acquired (3rd Party).", SEVERITY_FIELD: HIGH_SEVERITY, TYPE_FIELD: AUTHENTICITY_TYPE } }, "filter-service": { "0000": { MEANING_FIELD: "Integrity violation: duplicate hash detected. Possible injection, reply attack, " "or hash collision. ", SEVERITY_FIELD: HIGH_SEVERITY, TYPE_FIELD: SEQUENCE_TYPE }, "0010": { MEANING_FIELD: "Privacy violation: hash is already disabled or non-existent", SEVERITY_FIELD: LOW_SEVERITY, TYPE_FIELD: PRIVACY_TYPE }, "0020": { MEANING_FIELD: "Privacy violation: hash is not disabled or non-existent", SEVERITY_FIELD: LOW_SEVERITY, TYPE_FIELD: PRIVACY_TYPE }, "0030": { MEANING_FIELD: "Privacy violation: hash does not exist. Possible DDOS attack", SEVERITY_FIELD: HIGH_SEVERITY, TYPE_FIELD: PRIVACY_TYPE } } } ''' CLIENT CLASS ''' class Client: """Client class to subscribe the error from MQTT server This Client class is a wrapper class of the paho mqtt Client. Args: mqtt_host(str): MQTT server's host name mqtt_port(int): MQTT server's port number username(str): MQTT server's user name password(str): MQTT server's password stage(str): MQTT server's environment tenant_id(str): tenant id related with errors subscribed Return: None """ def __init__(self, mqtt_host: str, mqtt_port: int, username: str, password: str, stage: str, tenant_id: str): self.mqtt_client = mqtt.Client() self.mqtt_client.username_pw_set(username, password) self.mqtt_host = mqtt_host self.mqtt_port = mqtt_port self.topic = "com/ubirch/{}/incident/tenant/{}".format(stage, tenant_id) def connect(self, on_connect_callback: Callable[[mqtt.Client, dict, dict, int], None] = None) -> None: if on_connect_callback is not None: self.mqtt_client.on_connect = on_connect_callback self.mqtt_client.connect(self.mqtt_host, self.mqtt_port) def subscribe(self, on_message_callback: Callable[[mqtt.Client, dict, mqtt.MQTTMessage], None] = None) -> None: if on_message_callback is not None: self.mqtt_client.on_message = on_message_callback self.mqtt_client.subscribe(self.topic, QOS_AT_LEAST_ONCE) def loop_forever(self) -> None: self.mqtt_client.loop_forever() def loop_stop(self) -> None: self.mqtt_client.loop_stop() ''' HELPER FUNCTIONS ''' def get_error_definition(incident: Dict) -> Dict: """Return the error definition from the incident Ex. { "meaning": "xxx", "severity": 1, "type": "AUTHENTICATION" } Args: incident(Dict): an incident Return: Dict: error definition """ microservice: str = incident.get("microservice", "") error_code: str = incident.get("errorCode", "") # ex. { "1000": { ... }, "1100": { ... } } error_codes: Dict = INCIDENT_SEVERITY_MAP.get(microservice, {}) # ex. { "meaning": "xxx", "severity": 1, "type": "AUTHENTICATION" } return error_codes.get(error_code, {}) def create_incidents(error_message: str) -> list: """Create the incidents Args: error_message (str): this is the message payload from MQTT server Return: list: list of incidents """ incident_dict = json.loads(error_message) error_definition = get_error_definition(incident_dict) return [{ 'name': error_definition.get(MEANING_FIELD, incident_dict.get("error")), 'type': error_definition.get(TYPE_FIELD, ""), 'labels': [{'type': "requestId", 'value': incident_dict.get("requestId")}, {'type': "hwDeviceId", 'value': incident_dict.get("hwDeviceId")}], 'rawJSON': json.dumps(incident_dict), 'details': json.dumps(incident_dict), 'severity': error_definition.get(SEVERITY_FIELD, UNKNOWN_SEVERITY), }] ''' COMMAND FUNCTIONS ''' def long_running_execution(client: Client) -> None: """Connects to a MQTT Server and subscribe the error from it in a loop. Args: client(Client): client class which is a wrapper of the mqtt.Client class. Return: None: no data returned """ def on_connect(_client: mqtt.Client, _userdata: dict, _flags: dict, rc: int) -> None: """ Callback function when a MQTT client connects to the server Check if the connection is succeeded. The rc argument is a connection result. """ if rc != mqtt.MQTT_ERR_SUCCESS: demisto.info(mqtt.connack_string(rc)) raise paho.mqtt.MQTTException(mqtt.connack_string(rc)) else: demisto.info(f"connection was succeeded for a long-running container. host: {client.mqtt_host}, port: " f"{client.mqtt_port}") def on_message(_client: mqtt.Client, _userdata: dict, message: mqtt.MQTTMessage) -> None: """ Callback function when a MQTT client subscribes to a message from the server Create incidents, when the client subscribes to an error from the mqtt server. """ demisto.info(f"on message. {message.topic} {message.qos} {message.payload}") incidents = create_incidents(message.payload.decode("utf-8", "ignore")) # the message payload is binary. demisto.info(f"catch an incident. {incidents}") demisto.createIncidents(incidents) try: client.connect(on_connect) client.subscribe(on_message) client.loop_forever() except Exception as e: demisto.error(f'An error occurred in the long running loop: {e}') finally: client.loop_stop() def test_module(client: Client) -> None: """Check if the user configuration is correct Return: None: no data returned """ def on_connect(_client: mqtt.Client, _userdata: dict, _flags: dict, rc: int) -> None: """ Callback function when a MQTT client connects to the server Check if the connection is succeeded. Stop the loop regardless of whether the connection is succeeded or not. The rc argument is a connection result. """ _client.disconnect() _client.loop_stop() if rc != mqtt.MQTT_ERR_SUCCESS: demisto.info(mqtt.connack_string(rc)) raise paho.mqtt.MQTTException(mqtt.connack_string(rc)) else: demisto.info("connection was succeeded for test") try: client.connect(on_connect) client.subscribe() client.loop_forever() except Exception as e: raise DemistoException( f"Test failed. Please check your parameters. \n {e}") demisto.results('ok') def create_sample_incidents() -> None: """Extract sample events stored in the integration context and create them as incidents Return: None: no data returned """ integration_context = get_integration_context() sample_events = integration_context.get('sample_events') if sample_events: try: incidents = [{'name': "sample_event", 'rawJSON': json.dumps(event)} for event in json.loads(sample_events)] demisto.createIncidents(incidents) demisto.info("it was succeeded to create the sample incident.") except json.decoder.JSONDecodeError as e: raise ValueError(f'Failed deserializing sample events - {e}') else: incidents = [{ 'name': 'sample incident.', }] demisto.createIncidents(incidents) demisto.info("it was succeeded to create the sample incident.") demisto.info("connection was succeeded for test") def main() -> None: """ main function, parses params and runs command functions """ params = demisto.params() username = params['credentials'].get('identifier') password = params['credentials'].get('password') tenant_id = params['tenant_id'] mqtt_host = params['url'] mqtt_port = params['port'] stage = params['stage'] command = demisto.command() demisto.debug(f'Command being called is {command}') try: try: mqtt_port = int(mqtt_port) except ValueError as e: raise ValueError(f"Invalid the mqtt server's port - {e}") client = Client( mqtt_host=mqtt_host, mqtt_port=mqtt_port, username=username, password=password, stage=stage, tenant_id=tenant_id ) if command == 'test-module': # This is the call made when pressing the integration Test button. test_module(client) elif command == 'long-running-execution': long_running_execution(client) elif command == 'create-sample-incidents': create_sample_incidents() # Log exceptions and return errors except Exception as e: demisto.error(traceback.format_exc()) # print the traceback return_error(f'Failed to execute {demisto.command()} command.\nError:\n{str(e)}') if __name__ in ('__main__', '__builtin__', 'builtins'): main()
34.184492
119
0.630426
606e7f4ea22341b5ce383d26e26fb0b9876fd29c
266
py
Python
DataStructure/U14/U14_97.py
qiaw99/Data-Structure
3b1cdce96d4f35329ccfec29c03de57378ef0552
[ "MIT" ]
1
2019-10-29T08:21:41.000Z
2019-10-29T08:21:41.000Z
DataStructure/U14/U14_97.py
qiaw99/Data-Structure
3b1cdce96d4f35329ccfec29c03de57378ef0552
[ "MIT" ]
null
null
null
DataStructure/U14/U14_97.py
qiaw99/Data-Structure
3b1cdce96d4f35329ccfec29c03de57378ef0552
[ "MIT" ]
null
null
null
nums = 34 coins= [1,2,5,10] temp = nums dp = [float("inf") for _ in range(nums)] dp[0] = 0 for i in range(1,nums): for j in range(len(coins)): if(coins[j] <= nums): dp[i] = min(dp[i], dp[i-coins[j]]+1) print(dp) print(dp[nums-1])
22.166667
48
0.518797
7196df947a719f1ad906027a0121949c2fb6e0d6
1,039
py
Python
python/oneflow/framework/tensor_tuple_util.py
wangyuyue/oneflow
0a71c22fe8355392acc8dc0e301589faee4c4832
[ "Apache-2.0" ]
3,285
2020-07-31T05:51:22.000Z
2022-03-31T15:20:16.000Z
python/oneflow/framework/tensor_tuple_util.py
wangyuyue/oneflow
0a71c22fe8355392acc8dc0e301589faee4c4832
[ "Apache-2.0" ]
2,417
2020-07-31T06:28:58.000Z
2022-03-31T23:04:14.000Z
python/oneflow/framework/tensor_tuple_util.py
wangyuyue/oneflow
0a71c22fe8355392acc8dc0e301589faee4c4832
[ "Apache-2.0" ]
520
2020-07-31T05:52:42.000Z
2022-03-29T02:38:11.000Z
""" Copyright 2020 The OneFlow Authors. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import collections from typing import Optional, Sequence, Union from oneflow._oneflow_internal import Tensor, TensorTuple def convert_to_tensor_tuple(args: Optional[Union[Tensor, Sequence[Tensor]]]): if args is None: return TensorTuple() elif isinstance(args, collections.abc.Sequence): return TensorTuple(args) else: tensor_tuple = TensorTuple() tensor_tuple.append(args) return tensor_tuple
32.46875
77
0.758422
71afa04ef8d0f57669ca0f129f2c50b754e901ac
365
py
Python
0-notes/job-search/Cracking the Coding Interview/C04TreesGraphs/questions/4.12-questions.py
eengineergz/Lambda
1fe511f7ef550aed998b75c18a432abf6ab41c5f
[ "MIT" ]
null
null
null
0-notes/job-search/Cracking the Coding Interview/C04TreesGraphs/questions/4.12-questions.py
eengineergz/Lambda
1fe511f7ef550aed998b75c18a432abf6ab41c5f
[ "MIT" ]
null
null
null
0-notes/job-search/Cracking the Coding Interview/C04TreesGraphs/questions/4.12-questions.py
eengineergz/Lambda
1fe511f7ef550aed998b75c18a432abf6ab41c5f
[ "MIT" ]
null
null
null
# 4.12 Paths with Sum # You are given a binary tree in which each node contains an integer value # which might be positive or negative. # Design an algorithm to count the number of paths that sum to a given value. # The path does not need to start or end at the root or a leaf, but it must go # downwards, traveling only from parent nodes to child nodes.
45.625
78
0.739726
e0aa0f61cc446160a9ed1bbc3c7d59ad1a2459a4
3,056
py
Python
cbm/ipycbm/ipy_view/view_background.py
CsabaWirnhardt/cbm
1822addd72881057af34ac6a7c2a1f02ea511225
[ "BSD-3-Clause" ]
17
2021-01-18T07:27:01.000Z
2022-03-10T12:26:21.000Z
cbm/ipycbm/ipy_view/view_background.py
CsabaWirnhardt/cbm
1822addd72881057af34ac6a7c2a1f02ea511225
[ "BSD-3-Clause" ]
4
2021-04-29T11:20:44.000Z
2021-12-06T10:19:17.000Z
cbm/ipycbm/ipy_view/view_background.py
CsabaWirnhardt/cbm
1822addd72881057af34ac6a7c2a1f02ea511225
[ "BSD-3-Clause" ]
47
2021-01-21T08:25:22.000Z
2022-03-21T14:28:42.000Z
import json import os.path import matplotlib.pyplot as plt from ipywidgets import Output, VBox, SelectionSlider from mpl_toolkits.axes_grid1 import ImageGrid import rasterio from rasterio.plot import show from descartes import PolygonPatch from copy import copy # import matplotlib.ticker as ticker # import numpy as np from cbm.utils import config, spatial_utils from cbm.get import background as bg def slider(aoi, pid, chipsize=512, extend=512, tms=['Google']): workdir = config.get_value(['paths', 'temp']) path = f'{workdir}/{aoi}/{pid}/' bg_path = f'{path}/backgrounds/' for t in tms: if not os.path.isfile(f'{bg_path}{t.lower()}.tif'): bg.by_pid(aoi, pid, chipsize, extend, t, True) with open(f'{path}info.json', "r") as f: json_data = json.load(f) def overlay_parcel(img, geom): patche = [PolygonPatch(feature, edgecolor="yellow", facecolor="none", linewidth=2 ) for feature in geom['geom']] return patche with rasterio.open(f'{bg_path}{tms[0].lower()}.tif') as img: img_epsg = img.crs.to_epsg() geom = spatial_utils.transform_geometry(json_data, img_epsg) patches = overlay_parcel(img, geom) selection = SelectionSlider( options=tms, value=tms[0], disabled=False, continuous_update=False, orientation='horizontal', readout=True ) output = Output() fig, ax = plt.subplots(figsize=(10, 10)) with output: with rasterio.open(f'{bg_path}{selection.value.lower()}.tif') as img: for patch in patches: ax.add_patch(copy(patch)) show(img, ax=ax) plt.show() def on_value_change(change): with output: output.clear_output() fig, ax = plt.subplots(figsize=(10, 10)) with rasterio.open(f'{bg_path}{selection.value.lower()}.tif') as im: for patch in patches: ax.add_patch(copy(patch)) show(im, ax=ax) plt.show() selection.observe(on_value_change, names='value') return VBox([selection, output]) def maps(aoi, pid, chipsize=512, extend=512, tms='Google'): workdir = config.get_value(['paths', 'temp']) path = f'{workdir}/{aoi}/{pid}/backgrounds/' for t in tms: if not os.path.isfile(f'{path}{t.lower()}.png'): bg.by_pid(aoi, pid, chipsize, extend, t, True) columns = 5 rows = int(len(tms) // columns + (len(tms) % columns > 0)) fig = plt.figure(figsize=(25, 5 * rows)) grid = ImageGrid(fig, 111, # similar to subplot(111) nrows_ncols=(rows, columns), # creates grid of axes axes_pad=0.1, # pad between axes in inch. ) for ax, im in zip(grid, tms): # Iterating over the grid returns the Axes. ax.axis('off') ax.imshow(plt.imread(f'{path}{im.lower()}.png', 3)) ax.set_title(im) plt.show()
31.183673
80
0.592605
1c19f2b5e50ed09f338bab660257e2262cf0a3ab
3,056
py
Python
TcpPortForward.py
Zusyaku/Termux-And-Lali-Linux-V2
b1a1b0841d22d4bf2cc7932b72716d55f070871e
[ "Apache-2.0" ]
2
2021-11-17T03:35:03.000Z
2021-12-08T06:00:31.000Z
TcpPortForward.py
Zusyaku/Termux-And-Lali-Linux-V2
b1a1b0841d22d4bf2cc7932b72716d55f070871e
[ "Apache-2.0" ]
null
null
null
TcpPortForward.py
Zusyaku/Termux-And-Lali-Linux-V2
b1a1b0841d22d4bf2cc7932b72716d55f070871e
[ "Apache-2.0" ]
2
2021-11-05T18:07:48.000Z
2022-02-24T21:25:07.000Z
#/usr/bin/python env # -*- coding: utf-8 -*- ''' filename:TcpPortForward.py @desc: 利用python的socket端口转发,用于远程维护,Hack 如果连接不到远程,会sleep 36s,最多尝试200(即两小时) @usage: ./TcpPortForward.py stream1 stream2 stream为:l:port或c:host:port l:port表示监听指定的本地端口 c:host:port表示监听远程指定的端口 ''' import socket import sys import threading import time streams = [None, None] # 存放需要进行数据转发的两个数据流(都是SocketObj对象) debug = 1 # 调试状态 0 or 1 def _usage(): print 'Usage: ./TcpPortForward.py stream1 stream2\nstream : l:port or c:host:port' def _get_another_stream(num): ''' 从streams获取另外一个流对象,如果当前为空,则等待 ''' if num == 0: num = 1 elif num == 1: num = 0 else: raise "ERROR" while True: if streams[num] == 'quit': print("can't connect to the target, quit now!") sys.exit(1) if streams[num] != None: return streams[num] else: time.sleep(1) def _xstream(num, s1, s2): ''' 交换两个流的数据 num为当前流编号,主要用于调试目的,区分两个回路状态用。 ''' try: while True: #注意,recv函数会阻塞,直到对端完全关闭(close后还需要一定时间才能关闭,最快关闭方法是shutdow) buff = s1.recv(1024) if debug > 0: print num,"recv" if len(buff) == 0: #对端关闭连接,读不到数据 print num,"one closed" break s2.sendall(buff) if debug > 0: print num,"sendall" except : print num,"one connect closed." try: s1.shutdown(socket.SHUT_RDWR) s1.close() except: pass try: s2.shutdown(socket.SHUT_RDWR) s2.close() except: pass streams[0] = None streams[1] = None print num, "CLOSED" def _server(port, num): ''' 处理服务情况,num为流编号(第0号还是第1号) ''' srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) srv.bind(('0.0.0.0', port)) srv.listen(1) while True: conn, addr = srv.accept() print "connected from:", addr streams[num] = conn # 放入本端流对象 s2 = _get_another_stream(num) # 获取另一端流对象 _xstream(num, conn, s2) def _connect(host, port, num): ''' 处理连接,num为流编号(第0号还是第1号) @note: 如果连接不到远程,会sleep 36s,最多尝试200(即两小时) ''' not_connet_time = 0 wait_time = 36 try_cnt = 199 while True: if not_connet_time > try_cnt: streams[num] = 'quit' print('not connected') return None conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: conn.connect((host, port)) except Exception, e: print ('can not connect %s:%s!' % (host, port)) not_connet_time += 1 time.sleep(wait_time) continue print "connected to %s:%i" % (host, port) streams[num] = conn #放入本端流对象 s2 = _get_another_stream(num) #获取另一端流对象 _xstream(num, conn, s2) if __name__ == '__main__': if len(sys.argv) != 3: _usage() sys.exit(1) tlist = [] # 线程列表,最终存放两个线程对象 targv = [sys.argv[1], sys.argv[2] ] for i in [0, 1]: s = targv[i] # stream描述 c:ip:port 或 l:port sl = s.split(':') if len(sl) == 2 and (sl[0] == 'l' or sl[0] == 'L'): # l:port t = threading.Thread(target=_server, args=(int(sl[1]), i)) tlist.append(t) elif len(sl) == 3 and (sl[0] == 'c' or sl[0] == 'C'): # c:host:port t = threading.Thread(target=_connect, args=(sl[1], int(sl[2]), i)) tlist.append(t) else: _usage() sys.exit(1) for t in tlist: t.start() for t in tlist: t.join() sys.exit(0)
20.238411
84
0.647251
1c26f17d2185eda40065447ee1354e5564503292
643
py
Python
keras_malicious_url_detector/library/utility/url_data_loader.py
Adrimeov/keras-malicious-url-detector
22b8d075b41117f016100bb5ebff14a77907dacb
[ "MIT" ]
null
null
null
keras_malicious_url_detector/library/utility/url_data_loader.py
Adrimeov/keras-malicious-url-detector
22b8d075b41117f016100bb5ebff14a77907dacb
[ "MIT" ]
null
null
null
keras_malicious_url_detector/library/utility/url_data_loader.py
Adrimeov/keras-malicious-url-detector
22b8d075b41117f016100bb5ebff14a77907dacb
[ "MIT" ]
null
null
null
import pandas as pd import os def load_url_data(data_dir_path): url_data = pd.read_csv(data_dir_path, sep=',') url_data.columns = ['text', 'label'] class_zero = url_data[url_data['label'] == 0].reset_index() class_one = url_data[url_data['label'] == 1].reset_index() class_zero = class_zero.truncate(before=1, after=class_one.shape[0]) url_data = pd.concat([class_zero, class_one]) url_data = url_data.sample(frac=1.0).reset_index() return url_data def main(): data_dir_path = './data' url_data = load_url_data(data_dir_path) print(url_data.head()) if __name__ == '__main__': main()
21.433333
72
0.678072
c70927eb1e75849d56fdcae49b01e64384fcad46
587
py
Python
computer-networking-a-top-down-approach/cp2/ping_client.py
Jocs/reading-notes
26b8331877a2de034b8860bc3e3967893112d52d
[ "MIT" ]
3
2021-08-04T07:59:48.000Z
2022-03-26T23:58:17.000Z
computer-networking-a-top-down-approach/cp2/ping_client.py
Jocs/reading-notes
26b8331877a2de034b8860bc3e3967893112d52d
[ "MIT" ]
null
null
null
computer-networking-a-top-down-approach/cp2/ping_client.py
Jocs/reading-notes
26b8331877a2de034b8860bc3e3967893112d52d
[ "MIT" ]
null
null
null
from socket import * import time serverName = '127.0.0.1' serverPort = 12000 socketClient = socket(AF_INET, SOCK_DGRAM) socketClient.settimeout(1) for i in range(0, 10): sendTime = time.time() message = ('Ping %d %s' % (i + 1, sendTime)).encode() try: socketClient.sendto(message, (serverName, serverPort)) modifiedMessage, serverAddress = socketClient.recvfrom(1024) rtt = time.time() - sendTime print('Sequence %d: Reply from %s RTT = %.3fs' % (i+1, serverName, rtt)) except Exception as e: print('Sequence %d timeout' % (i + 1)) socketClient.close()
27.952381
79
0.674617
c719e11e1ced89112513a66e444d40617c7ab79a
4,421
py
Python
tests/addons/res2dict/test_block.py
ihatov08/jumeaux
7d983474df4b6dcfa57ea1a66901fbc99ebababa
[ "MIT" ]
11
2017-10-02T01:29:12.000Z
2022-03-31T08:37:22.000Z
tests/addons/res2dict/test_block.py
ihatov08/jumeaux
7d983474df4b6dcfa57ea1a66901fbc99ebababa
[ "MIT" ]
79
2017-07-16T14:47:17.000Z
2022-03-31T08:49:14.000Z
tests/addons/res2dict/test_block.py
ihatov08/jumeaux
7d983474df4b6dcfa57ea1a66901fbc99ebababa
[ "MIT" ]
2
2019-01-28T06:11:58.000Z
2021-01-25T07:21:21.000Z
#!/usr/bin/env python # -*- coding:utf-8 -*- import datetime import pytest from owlmixin.util import load_yaml from jumeaux.addons.res2dict.block import Executor from jumeaux.models import Response, Res2DictAddOnPayload PATTERN1_BODY = """ [Module1] Name: Jumeaux License: MIT Version: 0.33.0 [Module2 alpha] Name: Jumeaux Viewer Version: 1.0.0 (r: 1585:1586) """.lstrip() PATTERN2_BODY = """ 1)Module1 Name Jumeaux License MIT Version 0.33.0 2)Module2 alpha Name Jumeaux Viewer Version 1.0.0 (r1585) """.lstrip() NO_END_LINEBREAK_BODY = """ [Module1] Name: Jumeaux License: MIT Version: 0.33.0 [Module2 alpha] Name: Jumeaux Viewer Version: 1.0.0 (r1585) """.strip() PATTERN1 = ("Normal", """ force: False header_regexp: '\\[(.+)\\]' record_regexp: '([^:]+): (.+)' """, Response.from_dict({ "body": PATTERN1_BODY.encode('utf-8'), "type": "plain", "encoding": 'utf-8', "headers": { "content-type": "text/plain; charset=utf-8" }, "url": "http://test", "status_code": 200, "elapsed": datetime.timedelta(seconds=1), "elapsed_sec": 1.0, }), { "Module1": { "Name": "Jumeaux", "License": "MIT", "Version": "0.33.0" }, "Module2 alpha": { "Name": "Jumeaux Viewer", "Version": "1.0.0 (r: 1585:1586)" } } ) PATTERN2 = ("Normal", """ force: False header_regexp: '^\\d+\\)(.+)' record_regexp: '([^ ]+) (.+)' """, Response.from_dict({ "body": PATTERN2_BODY.encode('utf-8'), "type": "plain", "encoding": 'utf-8', "headers": { "content-type": "text/plain; charset=utf-8" }, "url": "http://test", "status_code": 200, "elapsed": datetime.timedelta(seconds=1), "elapsed_sec": 1.0, }), { "Module1": { "Name": "Jumeaux", "License": "MIT", "Version": "0.33.0" }, "Module2 alpha": { "Name": "Jumeaux Viewer", "Version": "1.0.0 (r1585)" } } ) NO_END_LINEBREAK = ("No end linebreak", """ force: False header_regexp: '\\[(.+)\\]' record_regexp: '([^:]+): (.+)' """, Response.from_dict({ "body": NO_END_LINEBREAK_BODY.encode('utf-8'), "type": "plain", "encoding": 'utf-8', "headers": { "content-type": "text/plain; charset=utf-8" }, "url": "http://test", "status_code": 200, "elapsed": datetime.timedelta(seconds=1), "elapsed_sec": 1.0, }), { "Module1": { "Name": "Jumeaux", "License": "MIT", "Version": "0.33.0" }, "Module2 alpha": { "Name": "Jumeaux Viewer", "Version": "1.0.0 (r1585)" } } ) class TestExec: @pytest.mark.parametrize( 'title, config_yml, response, expected_result', [ PATTERN1, PATTERN2, NO_END_LINEBREAK, ] ) def test(self, title, config_yml, response, expected_result): payload: Res2DictAddOnPayload = Res2DictAddOnPayload.from_dict({ 'response': response, }) actual: Res2DictAddOnPayload = Executor(load_yaml(config_yml)).exec(payload) assert actual.response == response assert actual.result.get() == expected_result
28.522581
84
0.406243
c75729dda34f44378f1f02da98c296ce6020d9b8
720
py
Python
weibo/login/WeiboSearch.py
haiboz/weiboSpider
517cae2ef3e7bccd9e1d328a40965406707f5362
[ "Apache-2.0" ]
null
null
null
weibo/login/WeiboSearch.py
haiboz/weiboSpider
517cae2ef3e7bccd9e1d328a40965406707f5362
[ "Apache-2.0" ]
null
null
null
weibo/login/WeiboSearch.py
haiboz/weiboSpider
517cae2ef3e7bccd9e1d328a40965406707f5362
[ "Apache-2.0" ]
null
null
null
#encoding:utf8 ''' Created on 2016年4月11日 @author: wb-zhaohaibo ''' import re import json def sServerData(serverData): "Search the server time & nonce from server data" p = re.compile('\((.*)\)') jsonData = p.search(serverData).group(1) data = json.loads(jsonData) serverTime = str(data['servertime']) nonce = data['nonce'] pubkey = data['pubkey']# rsakv = data['rsakv']# print "Server time is:", serverTime print "Nonce is:", nonce return serverTime, nonce, pubkey, rsakv def sRedirectData(text): p = re.compile('location\.replace\([\'"](.*?)[\'"]\)') loginUrl = p.search(text).group(1) print 'loginUrl:',loginUrl return loginUrl
25.714286
59
0.613889
c78d99955e67deeb2e620ec322002ab6b93889ea
689
py
Python
exercises/pt/exc_02_14.py
tuanducdesign/spacy-course
f8d092c5fa2997fccb3f367d174dce8667932b3d
[ "MIT" ]
null
null
null
exercises/pt/exc_02_14.py
tuanducdesign/spacy-course
f8d092c5fa2997fccb3f367d174dce8667932b3d
[ "MIT" ]
null
null
null
exercises/pt/exc_02_14.py
tuanducdesign/spacy-course
f8d092c5fa2997fccb3f367d174dce8667932b3d
[ "MIT" ]
null
null
null
import json import spacy with open("exercises/pt/countries.json", encoding="utf8") as f: COUNTRIES = json.loads(f.read()) nlp = spacy.blank("pt") doc = nlp("A República Tcheca deve ajudar a Eslováquia a proteger seu espaço aéreo.") # Importar o PhraseMatcher e inicializá-lo from spacy.____ import ____ matcher = ____(____) # Criar objeto com a expressão e adicioná-lo ao comparador matcher # Essa é a forma mais eficiente: [nlp(country) for country in COUNTRIES] patterns = list(nlp.pipe(COUNTRIES)) matcher.add("COUNTRY", patterns) # Chamar o matcher no documento de teste e imprimir o resultado matches = ____(____) print([doc[start:end] for match_id, start, end in matches])
29.956522
85
0.750363
1be96298cc3d51bb4bedd0b7a44a6da10210454a
10,628
py
Python
algo/simplex.py
teastares/or_lab
c8fb5c22d31c1e2b93381397202be7b71a3fc796
[ "MIT" ]
1
2021-01-18T09:11:59.000Z
2021-01-18T09:11:59.000Z
algo/simplex.py
teastares/or_lab
c8fb5c22d31c1e2b93381397202be7b71a3fc796
[ "MIT" ]
null
null
null
algo/simplex.py
teastares/or_lab
c8fb5c22d31c1e2b93381397202be7b71a3fc796
[ "MIT" ]
null
null
null
""" This file defines the algorithms. Last edited by Teast Ares, 20190130. """ import itertools import numpy as np from util import * from constant import const class Simplex: """ Simplex method for solving linear programming. If model is not a LP, we will relax it to LP. paras: model: the original model. """ def __init__(self, model): self.model = model def get_standardize_model(self): """ get a standard model. ---------- Min cx s.t. Ax = b x >= 0 ---------- paras: model: the original model. returns: the standardized model. """ pass def map_variables(model): """ map the variables by the four types of variable bound. paras: model: the original model. returns: variable_map_dict: a dictionary contains four sub-dictionaries, each contains the replaced parameters. """ variable_map_dict = { const.BOUND_TWO_OPEN: defaultdict(lambda: None), const.BOUND_LEFT_OPEN: defaultdict(lambda: None), const.BOUND_RIGHT_OPEN: defaultdict(lambda: None), const.BOUND_TWO_CLOSED: defaultdict(lambda: None) } for variable in model.variable_dict.values(): # if x is two-side unbounded (-infinite, infinite), then x = x1 - x2 if variable.get_bound_type() == const.BOUND_TWO_OPEN: x1 = Variable(name=variable.name + "_plus",cat=variable.cat) x2 = Variable(name=variable.name + "_minus", cat=variable.cat) variable_map_dict[const.BOUND_TWO_OPEN][variable.name] = (x1, x2) # if x is left-side unbounded (-infinite, upper_bound), then x = -x1 + upper_bound elif variable.get_bound_type() == const.BOUND_LEFT_OPEN: x1 = Variable(name=variable.name + "_opposite_shift", cat=variable.cat) variable_map_dict[const.BOUND_LEFT_OPEN][variable.name] = (x1, variable.upper_bound) # if x is right-side unbounded (lower_bound, infinite), then x = x1 + lower_bound elif variable.get_bound_type() == const.BOUND_RIGHT_OPEN: x1 = Variable(name=variable.name + "_shift", cat=variable.cat) variable_map_dict[const.BOUND_RIGHT_OPEN][variable.name] = (x1, variable.lower_bound) # if x is two-side closed (lower_bound, upper_bound), then x = x1 + lower_bound, # and there should be a constrain x1 <= variable.upper_bound - variable.lower_bound else: x1 = Variable(name=variable.name + "_shift", cat=variable.cat) variable_map_dict[const.BOUND_TWO_CLOSED][variable.name] = (x1, variable.lower_bound, variable.upper_bound - variable.lower_bound) return variable_map_dict def replace_linear_expression(linear_expression, variable_map_dict): """ use the variable map dictionary to get the replaced linear expression. paras: linear_expression: the original linear expression variable_map_dict: a dictionary contains four sub-dictionaries, each contains the replaced parameters. returns: the replaced linear expression and the additional right hand side. """ replaced_linear_expression = LinearExpression() arhs = 0 for variable_name, coefficient in linear_expression.coefficient_dict.items(): variable = linear_expression.variable_dict[variable_name] if variable.get_bound_type() == const.BOUND_TWO_OPEN: x1, x2 = variable_map_dict[const.BOUND_TWO_OPEN][variable_name] replaced_linear_expression.add_item(x1, coefficient) replaced_linear_expression.add_item(x2, -coefficient) elif variable.get_bound_type() == const.BOUND_LEFT_OPEN: x1, shift = variable_map_dict[const.BOUND_LEFT_OPEN][variable_name] replaced_linear_expression.add_item(x1, -coefficient) arhs -= (shift * coefficient) elif variable.get_bound_type() == const.BOUND_RIGHT_OPEN: x1, shift = variable_map_dict[const.BOUND_RIGHT_OPEN][variable_name] replaced_linear_expression.add_item(x1, coefficient) arhs -= (shift * coefficient) else: x1, shift, _ = variable_map_dict[const.BOUND_TWO_CLOSED][variable_name] replaced_linear_expression.add_item(x1, coefficient) arhs -= (shift * coefficient) return replaced_linear_expression, arhs def standardize_model(model): """ get a standard model. ---------- Max cx s.t. Ax = b x >= 0 ---------- paras: model: the original model. returns: the standardized model. """ variable_map_dict = map_variables(model) standard_model = Model(name="standard " + model.name, sense=const.SENSE_MAX) # add the standard variables to the standard model. for x1, x2 in variable_map_dict[const.BOUND_TWO_OPEN].values(): standard_model.add_variable(x1) standard_model.add_variable(x2) for x1, _ in variable_map_dict[const.BOUND_LEFT_OPEN].values(): standard_model.add_variable(x1) for x1, _ in variable_map_dict[const.BOUND_RIGHT_OPEN].values(): standard_model.add_variable(x1) for x1, _, upper_bound in variable_map_dict[const.BOUND_TWO_CLOSED].values(): standard_model.add_variable(x1) upper_bound_constrain = Constraint(name=x1.name + "_upper_bound", sense=const.SENSE_EQ) slack_variable = Variable(name="slack_"+x1.name) standard_model.add_variable(slack_variable) upper_bound_constrain.add_lhs_item(x1, 1) upper_bound_constrain.add_lhs_item(slack_variable, 1) upper_bound_constrain.set_rhs(upper_bound) standard_model.add_constraint(upper_bound_constrain) # objective function if model.sense == const.SENSE_MAX: standard_model.set_objective(replace_linear_expression(model.objective, variable_map_dict)[0]) else: model.objective.oppose() standard_model.set_objective(replace_linear_expression(model.objective, variable_map_dict)[0]) model.objective.oppose() # constrains for original_constrain in model.constrain_dict.values(): lhs, arhs = replace_linear_expression(original_constrain.lhs, variable_map_dict) constrain = Constraint(name=original_constrain.name + "_replaced", lhs=lhs, sense=const.SENSE_EQ, rhs=original_constrain.rhs + arhs) if original_constrain.sense == const.SENSE_LEQ: slack_variable = Variable(name="slack_"+original_constrain.name) standard_model.add_variable(slack_variable) constrain.add_lhs_item(slack_variable, 1) elif original_constrain.sense == const.SENSE_GEQ: slack_variable = Variable(name="slack_"+original_constrain.name) standard_model.add_variable(slack_variable) constrain.add_lhs_item(slack_variable, -1) standard_model.add_constraint(constrain) return standard_model def matrix_generation(standard_model, variable_index_dict, constrain_index_dict): """ For a standard model, we have following structure: ------------------ Max cx s.t. Ax = b ------------------ This function will generate the Numpy Ndarray format data. paras: standard_model: a model with standard formation, variable_index_dict: the dict for variable's index, constrain_index_dict: the dict for constraint's index. returns: c: the cost function vector, A: the left hand side matrix, b: the right hand side vector. """ # the column number, or the number of variables. n = len(variable_index_dict) # the row number, or the number of constrains. m = len(constrain_index_dict) c = np.zeros(n) for variable_name, value in standard_model.objective.coefficient_dict.items(): index = variable_index_dict[variable_name] c[index] = value A = np.zeros((m, n)) b = np.zeros(m) for constrain_name, constrain in standard_model.constrain_dict.items(): row_index = constrain_index_dict[constrain_name] for variable_name, value in constrain.lhs.coefficient_dict.items(): column_index = variable_index_dict[variable_name] A[row_index, column_index] = value b[row_index] = constrain.rhs return c, A, b def is_solvable(A, b): """ To valid if the linear equations Ax=b is solvable. paras: A: the left hand side matrix, b: the right hand side vector. returns: True\False """ m = b.shape[0] _A = np.concatenate((A, b.reshape(m, 1)), axis=1) if np.linalg.matrix_rank(A) == np.linalg.matrix_rank(_A): return True else: return False def search_init_solution(A, b): """ For a linear equations Ax=b, search a extreme point as a initial solution. paras: A: the left hand side matrix, b: the right hand side vector. """ m, n = A.shape for item in itertools.permutations(range(n)[::-1], m): _A = A[:, item] basic_solution = np.linalg.solve(_A, b) for value in basic_solution: if value < 0: break else: init_solution = np.zeros(n) init_basic_position = np.zeros(n) for index, value in enumerate(basic_solution): position = item[index] init_solution[position] = value init_basic_position[position] = 1 return init_solution, init_basic_position def simplex_method(model, simplex_type): """ Use the simplex method to solve the linear programming. paras: model: the original linear programing model. returns: TBD """ standard_model = standardize_model(model) variable_list = list(standard_model.variable_dict) constrain_list = list(standard_model.constrain_dict) variable_index_dict = dict() constrain_index_dict = dict() for index, variable in enumerate(variable_list): variable_index_dict[variable] = index for index, constrain in enumerate(constrain_list): constrain_index_dict[constrain] = index c, A, b = matrix_generation(standard_model, variable_index_dict, constrain_index_dict) # check if there has a solution if is_solvable(A, b) == False: standard_model.status == const.STATUS_NO_SOLUTION return init_solution, init_basic_position = search_init_solution(A, b) return init_solution, init_basic_position
34.064103
142
0.665036
909efa8645242acf6bd1c290699feb5f896c38ba
1,917
py
Python
leetcode/005-Longest-Palindromic-Substring/LongPalSubstr_001.py
cc13ny/all-in
bc0b01e44e121ea68724da16f25f7e24386c53de
[ "MIT" ]
1
2017-05-18T06:11:02.000Z
2017-05-18T06:11:02.000Z
leetcode/005-Longest-Palindromic-Substring/LongPalSubstr_001.py
cc13ny/all-in
bc0b01e44e121ea68724da16f25f7e24386c53de
[ "MIT" ]
1
2016-02-09T06:00:07.000Z
2016-02-09T07:20:13.000Z
leetcode/005-Longest-Palindromic-Substring/LongPalSubstr_001.py
cc13ny/all-in
bc0b01e44e121ea68724da16f25f7e24386c53de
[ "MIT" ]
2
2019-06-27T09:07:26.000Z
2019-07-01T04:40:13.000Z
# @author: cchen # pretty long and should be simplified later class Solution: # @param {string} s # @return {string} def longestPalindrome(self, s): size = len(s) ls = [] ll = 0 rr = 0 l = 0 r = 0 maxlen = r - l + 1 for i in range(1, size): if s[i - 1] == s[i]: r = i else: if r - l + 1 > maxlen: maxlen = r - l + 1 ll = l rr = r ls.append([[l, r], s[i - 1]]) l = i r = i if r - l + 1 > maxlen: maxlen = r - l + 1 ll = l rr = r ls.append([[l, r], s[size - 1]]) for i in range(1, len(ls) - 1): l = i - 1 r = i + 1 clen = ls[i][0][1] - ls[i][0][0] + 1 while -1 < l and r < len(ls) and ls[l][1] == ls[r][1]: llen = ls[l][0][1] - ls[l][0][0] + 1 rlen = ls[r][0][1] - ls[r][0][0] + 1 if llen == rlen: clen += 2 * llen if clen > maxlen: maxlen = clen ll = ls[l][0][0] rr = ls[r][0][1] l -= 1 r += 1 else: if llen > rlen: clen += 2 * rlen else: clen += 2 * llen if clen > maxlen: maxlen = clen if llen > rlen: ll = ls[l][0][1] - rlen + 1 rr = ls[r][0][1] else: ll = ls[l][0][0] rr = ls[r][0][0] + llen - 1 break return s[ll:rr + 1]
28.191176
66
0.27856
46a0da48b68a91465765362d47177cf154fd8be0
1,313
py
Python
2020-09-02-1159-gma_istPrim.py
gmaubach/OOP-with-Python
9b059e911d55d616e756324564f1f2cc524aa53d
[ "MIT" ]
null
null
null
2020-09-02-1159-gma_istPrim.py
gmaubach/OOP-with-Python
9b059e911d55d616e756324564f1f2cc524aa53d
[ "MIT" ]
null
null
null
2020-09-02-1159-gma_istPrim.py
gmaubach/OOP-with-Python
9b059e911d55d616e756324564f1f2cc524aa53d
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- """ Created on Wed Sep 2 11:38:10 2020 @author: Georg Maubach Schreiben Sie eine Funktion istPrim(), die einen ganzzahligen Wert übergeben bekommt und die dann zurückliefert, ob der Wert eine Primzahl ist oder nicht. Definition Primzahl: - Zahl ist NUR durch 1 und durch sich selbst teilbar. """ def istPrim(wert): # Meine Lösung x = 2 primzahl = True; while(x < wert): if(wert % x == 0): primzahl = False; x += 1 return(primzahl); def istPrin(wert): if (wert == 1) return False; max = wert / 2; # wenn der Teiler größer als die Hälfte ist, # muss die Division nur noch ungerade Werte # liefern. y = 2; while y <= max: if((x % y) == 0: return False; # alle weiteren Werte muss # ich dann nicht mehr weiter # prüfen. Damit das Programm # schneller. y += 1 return True; if __name__ == "__main__": print("Primzahl ", istPrim(2)); print("Primzahl ", istPrim(5)); print("Primzahl ", istPrim(10)); print("Primzahl ", istPrim(99)); pass
26.26
68
0.50495
b4431f07b1d304fb8d5b45e5a3617709b7e19e3c
9,983
py
Python
Python/pyBitwiseAutomation/SocketDevice.py
jimwaschura/Automation
f655feeea74ff22ebe44d8b68374ba6983748f60
[ "BSL-1.0" ]
null
null
null
Python/pyBitwiseAutomation/SocketDevice.py
jimwaschura/Automation
f655feeea74ff22ebe44d8b68374ba6983748f60
[ "BSL-1.0" ]
null
null
null
Python/pyBitwiseAutomation/SocketDevice.py
jimwaschura/Automation
f655feeea74ff22ebe44d8b68374ba6983748f60
[ "BSL-1.0" ]
null
null
null
# SocketDevice.py # ================================================================================ # BOOST SOFTWARE LICENSE # # Copyright 2020 BitWise Laboratories Inc. # Original Author.......Jim Waschura # [email protected] # # Permission is hereby granted, free of charge, to any person or organization # obtaining a copy of the software and accompanying documentation covered by # this license (the "Software") to use, reproduce, display, distribute, # execute, and transmit the Software, and to prepare derivative works of the # Software, and to permit third-parties to whom the Software is furnished to # do so, all subject to the following: # # The copyright notices in the Software and this entire statement, including # the above license grant, this restriction and the following disclaimer, # must be included in all copies of the Software, in whole or in part, and # all derivative works of the Software, unless such copies or derivative # works are solely in the form of machine-executable object code generated by # a source language processor. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT # SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE # FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. # ================================================================================ import socket import time import struct from pyBitwiseAutomation.AutomationInterface import * from enum import Enum class SocketDevice(AutomationInterface): """Socket device class.""" Start = float(0.0) # Sock = None # IsConnected = False def __init__(self): self.Sock = None self.IsConnected = False self.Debugging = False return None def __del__(self): if self.IsConnected: self.Disconnect() return None @staticmethod def timestamp(): now = time.time() if SocketDevice.Start == 0.0: SocketDevice.Start = now return now-SocketDevice.Start def getDebugging(self) -> bool: return self.Debugging def setDebugging(self, newValue: bool): self.Debugging = newValue def getIsConnected(self) -> bool: return self.IsConnected def Connect( self, ipaddress: str, dflt_port:int = 923 ) : """Connect to socket device.""" if self.IsConnected: self.Disconnect() tempBuffer = ipaddress tempPort = dflt_port tokens = ipaddress.split(":") if len(tokens) > 1: tempBuffer = tokens[0] tempPort = int(tokens[1]) try: self.Sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except Exception as e: print("socket.socket() exception:", e) raise Exception("[Create_Socket_Failed") try: self.Sock.connect((tempBuffer, tempPort)) self.IsConnected = True except Exception as e: print("self.Sock.connect() exception is: ", e) self.Sock=None raise Exception("[Unable_To_Connect]") return None def Disconnect( self ): """Disconnect from socket device.""" if self.IsConnected: self.Sock.shutdown(socket.SHUT_RDWR) self.Sock.close() self.IsConnected = False self.Sock=None return None def Receive( self, buflen:int ) -> bytes: """Receive up to maximum number of bytes from socket device.""" if not self.IsConnected: raise Exception("[Not_Connected]") return self.Sock.recv(buflen) def Send( self, buffer: bytes): """Send specified number of bytes to socket device.""" if not isinstance(buffer,bytes) : raise Exception("[Invalid_Type]") if not self.IsConnected: raise Exception("[Not_Connected]") self.Sock.send(buffer) return None def SendCommand(self, command: str ): """Send command (ending with '\n') to socket device.""" if not isinstance(command,str) : raise Exception("[Invalid_Command_Type]") if not self.IsConnected: raise Exception("[Not_Connected]") if self.Debugging: print("SendCommand() command: " + command) self.Sock.send(bytes(command,'utf-8')) return None def QueryResponse( self, command: str, maxLength:int = 4096 ) -> str: """Query response from command (ending with '\n') from socket device.""" if not isinstance(command, str) : raise Exception("[Invalid_Command_Type]") if not self.IsConnected: raise Exception("[Not_Connected]") if self.Debugging: print( "QueryResponse() query: " + command ) self.Sock.send( bytes(command, 'utf-8')) tempBytes = self.Sock.recv(maxLength) tempString = str(tempBytes, encoding='utf-8') if len(tempString)>0 and tempString[-1]=="\n" : tempString = tempString[0:-1] if len(tempString)>1 and tempString[0] == '"' and tempString[-1] == '"' : tempString = tempString[1:-1] if self.Debugging: print( "QueryResponse() response: " + tempString ) return tempString def QueryResponse_int(self, command: str ) -> int: """Query integer response from command (ending with '\n') from socket device.""" return int(self.QueryResponse(command)) def QueryResponse_bool(self, command: str ) -> bool: """Query boolean response from command (ending with '\n') from socket device.""" response = self.QueryResponse(command) return bool( len(response) > 0 and (response[0] == 'T' or response[0] == 't' or response[0] == '1') ) def QueryResponse_float(self, command: str ) -> float: """Query float response from command (ending with '\n') from socket device.""" return float(self.QueryResponse( command)) def QueryResponse_enum(self, enumeration:Enum, command: str) -> Enum: """Query integer index of enum response from command (ending with '\n') from socket device.""" if not isinstance(command, str): raise Exception("[Command_Must_Be_String]") return enumeration(self.QueryResponse(command)) def SendBinaryCommand(self, command: str, buffer: bytes): """Send command (ending with '\n') followed by 4-byte count and array of bytes to socket device.""" if not isinstance(command, str): raise Exception("[Invalid_Command_Type]") if not isinstance(buffer, bytes): raise Exception("[Invalid_Buffer_Type]") if not self.IsConnected: raise Exception("[Not_Connected]") if self.Debugging: print("SendBinaryCommand() command: " + command) count = len(buffer) self.Sock.send(bytes(command,'utf-8')) self.Sock.send(count.to_bytes(4, byteorder='little')) self.Sock.send(buffer) return None def QueryBinaryResponse(self, command: str) -> bytes : """Query array of bytes response from command (ending with '\n') from socket device.""" if not isinstance(command, str) : raise Exception("[Invalid_Command_Type]") if not self.IsConnected: raise Exception("[Not_Connected]") if self.Debugging: print("QueryBinaryResponse() command: " + command) self.Sock.send(bytes(command, 'utf-8')) countBytes = self.Sock.recv(4) if len(countBytes) != 4: raise Exception("[Missing_Count_Response]") count = int.from_bytes(countBytes, byteorder="little") return_value = bytes(0) if count>0 : total = 0 while total<count : portion = self.Sock.recv(count-total) amount = len(portion) if amount == 0: raise Exception("[Error_Receiving_Buffer]") return_value += portion total += amount pass return return_value def QueryBinaryResponse_float(self, command: str) -> list: """Query array of floats response from command (ending with '\n') from socket device.""" data = self.QueryBinaryResponse(command) if not (len(data) % 4) == 0: raise Exception("[Binary_Float_Size_Invalid]") count = int(len(data)/4) retn = [] if count>0 : for i in range(count): retn.append(float(struct.unpack_from("<f", data, i*4)[0])) return retn def QueryBinaryResponse_int(self, command: str) -> list: """Query array of 32-bit integers response from command (ending with '\n') from socket device.""" data = self.QueryBinaryResponse(command) if not (len(data) % 4) == 0: raise Exception("[Binary_Float_Size_Invalid]") count = int(len(data)/4) retn = [count] if count>0 : for i in range(count): retn.append(int(struct.unpack_from("<i", data, i*4)[0])) return retn def QueryBinaryResponse_double(self, command: str) -> list: """Query array of doubles response from command (ending with '\n') from socket device.""" data = self.QueryBinaryResponse(command) if not (len(data) % 8) == 0: raise Exception("[Binary_Float_Size_Invalid]") count = int(len(data)/8) retn = [count] if count>0 : for i in range(count): retn.append(float(struct.unpack_from("<d", data, i*8)[0])) return retn # EOF
34.424138
110
0.608234
6f2011e99aa153ea426797f4955466f84ec63854
1,492
py
Python
angstrom/2019/crypto/Eightball/server.py
mystickev/ctf-archives
89e99a5cd5fb6b2923cad3fe1948d3ff78649b4e
[ "MIT" ]
1
2021-11-02T20:53:58.000Z
2021-11-02T20:53:58.000Z
angstrom/2019/crypto/Eightball/server.py
ruhan-islam/ctf-archives
8c2bf6a608c821314d1a1cfaa05a6cccef8e3103
[ "MIT" ]
null
null
null
angstrom/2019/crypto/Eightball/server.py
ruhan-islam/ctf-archives
8c2bf6a608c821314d1a1cfaa05a6cccef8e3103
[ "MIT" ]
1
2021-12-19T11:06:24.000Z
2021-12-19T11:06:24.000Z
import binascii import socketserver from Crypto.Random.random import choice from Crypto.Util.asn1 import DerSequence import benaloh answers = [ b'It is certain', b'It is decidedly so', b'Without a doubt', b'Yes definitely', b'You may rely on it', b'As I see it, yes', b'Most likely', b'Outlook good', b'Yes', b'Signs point to yes', b'Reply hazy try again', b'Ask again later', b'Better not tell you now', b'Cannot predict now', b'Concentrate and ask again', b'Don\'t count on it', b'My reply is no', b'My sources say no', b'Outlook not so good', b'Very doubtful' ] sk = benaloh.unpack('sk') def handle(self): while True: der = DerSequence() der.decode(binascii.unhexlify(self.query(b'Question: '))) question = bytes([benaloh.decrypt(c, sk) for c in der]) response = choice(answers) self.write(response) class RequestHandler(socketserver.BaseRequestHandler): handle = handle def read(self, until=b'\n'): out = b'' while not out.endswith(until): out += self.request.recv(1) return out[:-len(until)] def query(self, string=b''): self.write(string, newline=False) return self.read() def write(self, string, newline=True): self.request.sendall(string) if newline: self.request.sendall(b'\n') class Server(socketserver.ForkingTCPServer): allow_reuse_address = True def handle_error(self, request, client_address): pass port = 3000 server = Server(('0.0.0.0', port), RequestHandler) server.serve_forever()
21.314286
59
0.69437
48fe19da112a00251dbf32baa059193efdd1efc1
1,358
py
Python
make_executible.py
Morgadow/Bierliste_K3.1
088806849affbbf5ea0b24fc0393a2308cd5b4aa
[ "MIT" ]
null
null
null
make_executible.py
Morgadow/Bierliste_K3.1
088806849affbbf5ea0b24fc0393a2308cd5b4aa
[ "MIT" ]
null
null
null
make_executible.py
Morgadow/Bierliste_K3.1
088806849affbbf5ea0b24fc0393a2308cd5b4aa
[ "MIT" ]
null
null
null
#!/usr/bin/python3.7 # -*- coding: utf-8 -*- import os import shutil from Bierliste_Tool import __version__ import time PROJECT_NAME = "Bierliste_Tool" print("Create .exe file for version: " + __version__) print("") if not os.path.exists(os.path.join("Executible", 'v' + __version__)): print("Preparing folder " + 'v' + __version__) os.makedirs(os.path.join("Executible", 'v' + __version__)) shutil.copyfile("Example_file.xlsx", os.path.join("Executible", 'v' + __version__, "Example_file.xlsx")) shutil.copyfile("settings.ini", os.path.join("Executible", 'v' + __version__, "settings.ini")) else: print("Folder already exists, file will be replaced!") if os.path.exists(os.path.join("Executible", 'v' + __version__, "{}.exe".format(PROJECT_NAME))): os.remove(os.path.join("Executible", 'v' + __version__, "{}.exe".format(PROJECT_NAME))) print("\nMake executible:") os.system("mk_exe.bat") # give programm some time to finish task time.sleep(5) print("\nCleaning up ...") shutil.copyfile(os.path.join("dist", "{}.exe".format(PROJECT_NAME)), os.path.join("Executible", 'v' + __version__, "{}.exe".format(PROJECT_NAME))) for folder in ('build', 'dist', '__pycache__', '.idea'): try: shutil.rmtree(folder) except: pass os.remove("{}.spec".format(PROJECT_NAME))
35.736842
147
0.659057
7daf21b74d8b5eb42cd09299049750ed974bcb1b
345
py
Python
数据结构/NowCode/41_rectCover.py
Blankwhiter/LearningNotes
83e570bf386a8e2b5aa699c3d38b83e5dcdd9cb0
[ "MIT" ]
null
null
null
数据结构/NowCode/41_rectCover.py
Blankwhiter/LearningNotes
83e570bf386a8e2b5aa699c3d38b83e5dcdd9cb0
[ "MIT" ]
3
2020-08-14T07:50:27.000Z
2020-08-14T08:51:06.000Z
数据结构/NowCode/41_rectCover.py
Blankwhiter/LearningNotes
83e570bf386a8e2b5aa699c3d38b83e5dcdd9cb0
[ "MIT" ]
2
2021-03-14T05:58:45.000Z
2021-08-29T17:25:52.000Z
# 矩形覆盖 class Solution: def rectCover(self, number): # write code here if number == 0: return 0 if number == 1: return 1 if number == 2: return 2 a = 1 b = 2 for i in range(3, number + 1): b = a + b a = b - a return b
20.294118
38
0.394203
7defcf558669cbf65947bd91d6bd4823108f5d2b
696
py
Python
imwievaluation/semester.py
ESchae/IMWIEvaluation
2fa661711b7b65cba25c1fa9ba69e09e75c7655f
[ "MIT" ]
null
null
null
imwievaluation/semester.py
ESchae/IMWIEvaluation
2fa661711b7b65cba25c1fa9ba69e09e75c7655f
[ "MIT" ]
null
null
null
imwievaluation/semester.py
ESchae/IMWIEvaluation
2fa661711b7b65cba25c1fa9ba69e09e75c7655f
[ "MIT" ]
1
2019-10-19T10:11:17.000Z
2019-10-19T10:11:17.000Z
import sqlalchemy as db from sqlalchemy.dialects import mysql from sqlalchemy.orm import relationship from base import Base class Semester(Base): __tablename__ = 'semester' id = db.Column(db.Integer, primary_key=True) term = db.Column(mysql.ENUM('WS', 'SS'), nullable=False) year = db.Column(mysql.YEAR(), nullable=False) # prevent duplicate entries db.UniqueConstraint(term, year) # one two many relationship between semester and lecture lectures = relationship("Lecture", back_populates="semester") def __init__(self, term, year): self.term = term self.year = year def __str__(self): return '%s%s' % (self.term, self.year)
26.769231
65
0.689655
817a55f51bbc9d8522c0a10c412685bf4172baed
722
py
Python
leetcode/092-Reverse-Linked-List-II/RevLinkedListII_001.py
cc13ny/all-in
bc0b01e44e121ea68724da16f25f7e24386c53de
[ "MIT" ]
1
2015-12-16T04:01:03.000Z
2015-12-16T04:01:03.000Z
leetcode/092-Reverse-Linked-List-II/RevLinkedListII_001.py
cc13ny/all-in
bc0b01e44e121ea68724da16f25f7e24386c53de
[ "MIT" ]
1
2016-02-09T06:00:07.000Z
2016-02-09T07:20:13.000Z
leetcode/092-Reverse-Linked-List-II/RevLinkedListII_001.py
cc13ny/all-in
bc0b01e44e121ea68724da16f25f7e24386c53de
[ "MIT" ]
2
2019-06-27T09:07:26.000Z
2019-07-01T04:40:13.000Z
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: # @param {ListNode} head # @param {integer} m # @param {integer} n # @return {ListNode} def reverseBetween(self, head, m, n): dumpy = ListNode(0) dumpy.next = head pre = dumpy diff = n - m while m > 1: pre = pre.next m -= 1 p = pre.next while diff > 0 and p and p.next: # print p.val diff -= 1 tmp = p.next p.next = tmp.next q = pre.next pre.next = tmp tmp.next = q return dumpy.next
21.878788
41
0.470914
81bf6bf890fef439f92ad73919a95ca7433af382
272
py
Python
Licence 2/I33/TP 1/ex_9.py
axelcoezard/licence
1ed409c4572dea080169171beb7e8571159ba071
[ "MIT" ]
8
2020-11-26T20:45:12.000Z
2021-11-29T15:46:22.000Z
Licence 2/I33/TP 1/ex_9.py
axelcoezard/licence
1ed409c4572dea080169171beb7e8571159ba071
[ "MIT" ]
null
null
null
Licence 2/I33/TP 1/ex_9.py
axelcoezard/licence
1ed409c4572dea080169171beb7e8571159ba071
[ "MIT" ]
6
2020-10-23T15:29:24.000Z
2021-05-05T19:10:45.000Z
def tri_bulle(L): pointer = 0 while pointer < len(L): left = 0 right = 1 while right < len(L) - pointer: if L[right] < L[left]: L[left], L[right] = L[right], L[left] left += 1 right += 1 pointer += 1 return L print(tri_bulle([8, -1, 2, 5, 3, -2]))
19.428571
41
0.551471
b50fe49d8324b7d77943ea9dcfcba3e2f0c0b5be
251
py
Python
Packs/CommonScripts/Scripts/LastArrayElement/LastArrayElement.py
diCagri/content
c532c50b213e6dddb8ae6a378d6d09198e08fc9f
[ "MIT" ]
799
2016-08-02T06:43:14.000Z
2022-03-31T11:10:11.000Z
Packs/CommonScripts/Scripts/LastArrayElement/LastArrayElement.py
diCagri/content
c532c50b213e6dddb8ae6a378d6d09198e08fc9f
[ "MIT" ]
9,317
2016-08-07T19:00:51.000Z
2022-03-31T21:56:04.000Z
Packs/CommonScripts/Scripts/LastArrayElement/LastArrayElement.py
diCagri/content
c532c50b213e6dddb8ae6a378d6d09198e08fc9f
[ "MIT" ]
1,297
2016-08-04T13:59:00.000Z
2022-03-31T23:43:06.000Z
import demistomock as demisto def main(): value = demisto.args()['value'] if type(value) is list and len(value) > 0: value = value[-1] demisto.results(value) if __name__ == "__builtin__" or __name__ == "builtins": main()
16.733333
55
0.621514
d280380ee06ad6e8b6080dcc93810f12c6802282
832
py
Python
Course_1/Week_03/MyQuickSort.py
KnightZhang625/Stanford_Algorithm
7dacbbfa50e7b0e8380cf500df24af60cb9f42df
[ "Apache-2.0" ]
null
null
null
Course_1/Week_03/MyQuickSort.py
KnightZhang625/Stanford_Algorithm
7dacbbfa50e7b0e8380cf500df24af60cb9f42df
[ "Apache-2.0" ]
1
2020-07-16T08:03:22.000Z
2020-07-16T08:09:34.000Z
Course_1/Week_03/MyQuickSort.py
KnightZhang625/Stanford_Algorithm
7dacbbfa50e7b0e8380cf500df24af60cb9f42df
[ "Apache-2.0" ]
null
null
null
import random def MySwap(MyArray,i,j): temp = MyArray[i] MyArray[i] = MyArray[j] MyArray[j] = temp def MyQuickSort(MyArray,left,right): if left == right: return random.seed() pivot = random.randint(left,right) MySwap(MyArray,left,pivot) i = left+1 # first element in the right j = left+1 # last element in the right +1 while j <= right: if MyArray[j] < MyArray[left]: MySwap(MyArray,i,j) i += 1 j += 1 MySwap(MyArray,left,i-1) if i > left+2: MyQuickSort(MyArray,left,i-2) if right > i: MyQuickSort(MyArray,i,right) MyInput=[95,33,7,87,665,4,2,5,4,8,56,5,13,45,6,87,34,345,1,6,7,67,434,53,24,64] print('original:') print(MyInput) MyQuickSort(MyInput,0,len(MyInput)-1) print('after quick sort:') print(MyInput)
25.212121
79
0.604567