blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
288
content_id
stringlengths
40
40
detected_licenses
listlengths
0
112
license_type
stringclasses
2 values
repo_name
stringlengths
5
115
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
684 values
visit_date
timestamp[us]date
2015-08-06 10:31:46
2023-09-06 10:44:38
revision_date
timestamp[us]date
1970-01-01 02:38:32
2037-05-03 13:00:00
committer_date
timestamp[us]date
1970-01-01 02:38:32
2023-09-06 01:08:06
github_id
int64
4.92k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-04 01:52:49
2023-09-14 21:59:50
gha_created_at
timestamp[us]date
2008-05-22 07:58:19
2023-08-21 12:35:19
gha_language
stringclasses
147 values
src_encoding
stringclasses
25 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
128
12.7k
extension
stringclasses
142 values
content
stringlengths
128
8.19k
authors
listlengths
1
1
author_id
stringlengths
1
132
54d72878eac09a4ed9b40f9ef8fdc315b10a7f4d
99259216f11b15ec60446b4a141b3592a35560ce
/wex-python-api/test/test_json_node.py
c75004f2b70287a8c291d81ea8751f09dcf73ca6
[]
no_license
adam725417/Walsin
296ba868f0837077abff93e4f236c6ee50917c06
7fbefb9bb5064dabccf4a7e2bf49d2a43e0f66e9
refs/heads/master
2020-04-12T14:14:07.607675
2019-03-05T01:54:03
2019-03-05T01:54:03
162,546,202
0
0
null
null
null
null
UTF-8
Python
false
false
977
py
# coding: utf-8 """ WEX REST APIs Authentication methods - Basic Auth - JSON Web Token - [POST /api/v1/usermgmt/login](#!/User/signinUser) - [POST /api/v1/usermgmt/logout](#!/User/doLogout) - Python client sample [Download](/docs/wex-python-api.zip) OpenAPI spec version: 12.0.2.417 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import os import sys import unittest import ibmwex from ibmwex.rest import ApiException from ibmwex.models.json_node import JsonNode class TestJsonNode(unittest.TestCase): """ JsonNode unit test stubs """ def setUp(self): pass def tearDown(self): pass def testJsonNode(self): """ Test JsonNode """ # FIXME: construct object with mandatory attributes with example values #model = ibmwex.models.json_node.JsonNode() pass if __name__ == '__main__': unittest.main()
[ "adamtp_chen@walsin.com" ]
adamtp_chen@walsin.com
67ceb865d11bf7d82086694f8879b057f68bf848
864285315c3a154639355f14ab1ff14633576405
/mapclientplugins/segmentationstep/tools/handlers/abstractselection.py
4315d4f55f509d3c4b410e9a7a07ad7b29f48cb1
[]
no_license
hsorby/segmentationstep
774dc537967c9643bd0094dc4e64eefa472588b0
321505374f9434ac0ae832b0b00398c2d4ac1fbe
refs/heads/main
2021-09-28T09:06:07.197158
2015-08-14T07:59:55
2015-08-14T07:59:55
21,375,254
0
0
null
null
null
null
UTF-8
Python
false
false
5,527
py
''' MAP Client, a program to generate detailed musculoskeletal models for OpenSim. Copyright (C) 2012 University of Auckland This file is part of MAP Client. (http://launchpad.net/mapclient) MAP Client 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. MAP Client 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 MAP Client. If not, see <http://www.gnu.org/licenses/>.. ''' from PySide import QtCore from mapclientplugins.segmentationstep.tools.handlers.abstracthandler import AbstractHandler from mapclientplugins.segmentationstep.zincutils import setGlyphSize, setGlyphOffset, COORDINATE_SYSTEM_LOCAL, \ createSelectionBox from mapclientplugins.segmentationstep.undoredo import CommandSelection from mapclientplugins.segmentationstep.definitions import SELECTION_BOX_3D_GRAPHIC_NAME class SelectionMode(object): NONE = -1 EXCULSIVE = 0 ADDITIVE = 1 class AbstractSelection(AbstractHandler): def __init__(self, plane, undo_redo_stack): super(AbstractSelection, self).__init__(plane, undo_redo_stack) self._selection_box = createSelectionBox(plane.getRegion(), SELECTION_BOX_3D_GRAPHIC_NAME) self._selection_mode = SelectionMode.NONE self._selection_position_start = None def mousePressEvent(self, event): self._selection_mode = SelectionMode.NONE if event.modifiers() & QtCore.Qt.SHIFT and event.button() == QtCore.Qt.LeftButton: self._selection_position_start = [event.x(), event.y()] self._selection_mode = SelectionMode.EXCULSIVE if event.modifiers() & QtCore.Qt.ALT: self._selection_mode = SelectionMode.ADDITIVE self._start_selection = self._model.getCurrentSelection() else: super(AbstractSelection, self).mousePressEvent(event) def mouseMoveEvent(self, event): if self._selection_mode != SelectionMode.NONE: x = event.x() y = event.y() xdiff = float(x - self._selection_position_start[0]) ydiff = float(y - self._selection_position_start[1]) if abs(xdiff) < 0.0001: xdiff = 1 if abs(ydiff) < 0.0001: ydiff = 1 xoff = float(self._selection_position_start[0]) / xdiff + 0.5 yoff = float(self._selection_position_start[1]) / ydiff + 0.5 scene = self._selection_box.getScene() scene.beginChange() setGlyphSize(self._selection_box, [xdiff, -ydiff, 0.999]) setGlyphOffset(self._selection_box, [xoff, yoff, 0]) self._selection_box.setVisibilityFlag(True) scene.endChange() else: super(AbstractSelection, self).mouseMoveEvent(event) def mouseReleaseEvent(self, event): if self._selection_mode != SelectionMode.NONE: x = event.x() y = event.y() # Construct a small frustrum to look for nodes in. region = self._model.getRegion() region.beginHierarchicalChange() self._selection_box.setVisibilityFlag(False) selection_group = self._model.getSelectionGroupField() if (x != self._selection_position_start[0] and y != self._selection_position_start[1]): left = min(x, self._selection_position_start[0]) right = max(x, self._selection_position_start[0]) bottom = min(y, self._selection_position_start[1]) top = max(y, self._selection_position_start[1]) self._zinc_view.setPickingRectangle(COORDINATE_SYSTEM_LOCAL, left, bottom, right, top) if self._selection_mode == SelectionMode.EXCULSIVE: selection_group.clear() self._zinc_view.addPickedNodesToFieldGroup(selection_group) else: node = self._zinc_view.getNearestNode(x, y) if self._selection_mode == SelectionMode.EXCULSIVE and not node.isValid(): selection_group.clear() if node.isValid(): group = self._model.getSelectionGroup() if self._selection_mode == SelectionMode.EXCULSIVE: remove_current = group.getSize() == 1 and group.containsNode(node) selection_group.clear() if not remove_current: group.addNode(node) elif self._selection_mode == SelectionMode.ADDITIVE: if group.containsNode(node): group.removeNode(node) else: group.addNode(node) end_selection = self._model.getCurrentSelection() c = CommandSelection(self._model, self._start_selection, end_selection) self._undo_redo_stack.push(c) region.endHierarchicalChange() self._selection_mode = SelectionMode.NONE else: super(AbstractSelection, self).mouseReleaseEvent(event)
[ "h.sorby@auckland.ac.nz" ]
h.sorby@auckland.ac.nz
6fbd126342d2762103a2aff7486d0ce1305afb29
28297b7172bad2e427db185d449056340be2a429
/src/join_pairs.py
3bca92e18b11ac0a0c113c6e7492e6e049cf7c5b
[]
no_license
audy/cd-hit-that
6a3480c01c7930751325acbd716202ad514562da
27922835ebace8bcdcf8d7118ec2e05e11e5e9fa
refs/heads/master
2021-01-01T15:31:01.604403
2011-08-02T20:33:47
2011-08-02T20:33:47
1,357,454
0
0
null
null
null
null
UTF-8
Python
false
false
1,420
py
#!/usr/bin/env python # outputs a FASTQ file but with its filename in the header (sorta) # Also puts paired reads together with their 5' ends touching # This is for clustering # Takes input from STDIN import sys import os from itertools import cycle import string _complement = string.maketrans('GATCRYgatcry','CTAGYRctagyr') c = cycle([0, 1]) seq = { 0: '', 1: ''} i = 0 infile = sys.argv[1] minimum_read_length = int(sys.argv[2]) f_num = int(infile.split('_')[-1].split('.')[0]) kept, skipped = 0, 0 with open(infile) as handle: for line in handle: if line.startswith('>'): n = c.next() i += 1 if n == 1: header = '>%s:%s' % (f_num, hex(i)[2:]) else: seq[n] += line.strip() if n == 1: # Reverse-complement 3' pair seq[1] = seq[1].translate(_complement)[::-1] # Make sure reads are minimum length if (len(seq[0]) >= minimum_read_length) \ and (len(seq[1]) >= minimum_read_length): print header print '%s%s' % (seq[1], seq[0]) kept +=1 else: skipped +=1 seq = { 0: '', 1: ''} print >> sys.stderr, "kept: %.2f percent of pairs (%s : %s)" % (float(kept)/(skipped + kept), skipped, kept)
[ "harekrishna@gmail.com" ]
harekrishna@gmail.com
ac4d6e76ee26b19ee2ff04a77b386ed4cf0059c9
f7c1282dd377b95621436587fd2a6cb28a455d74
/om_hr_payroll/__manifest__.py
2c39fcc961672ef5c2c5369414d6b86b5a869f74
[]
no_license
odoomates/odooapps
a22fa15346694563733008c42549ebc0da7fc9f6
459f3b25d31da24043523e72f8be09af9a1e67e9
refs/heads/master
2023-08-11T15:25:28.508718
2022-10-14T07:58:36
2022-10-14T07:58:36
173,598,986
182
306
null
2023-08-10T17:58:46
2019-03-03T16:20:23
Python
UTF-8
Python
false
false
1,550
py
# -*- coding:utf-8 -*- { 'name': 'Odoo 16 HR Payroll', 'category': 'Generic Modules/Human Resources', 'version': '16.0.1.0.0', 'sequence': 1, 'author': 'Odoo Mates, Odoo SA', 'summary': 'Payroll For Odoo 16 Community Edition', 'live_test_url': 'https://www.youtube.com/watch?v=0kaHMTtn7oY', 'description': "Odoo 16 Payroll, Payroll Odoo 16, Odoo Community Payroll", 'website': 'https://www.odoomates.tech', 'license': 'LGPL-3', 'depends': [ 'mail', 'hr_contract', 'hr_holidays', ], 'data': [ 'security/hr_payroll_security.xml', 'security/ir.model.access.csv', 'data/hr_payroll_sequence.xml', 'data/hr_payroll_category.xml', 'data/hr_payroll_data.xml', 'wizard/hr_payroll_payslips_by_employees_views.xml', 'views/hr_contract_type_views.xml', 'views/hr_contract_views.xml', 'views/hr_salary_rule_views.xml', 'views/hr_payslip_views.xml', 'views/hr_employee_views.xml', 'views/hr_payroll_report.xml', 'wizard/hr_payroll_contribution_register_report_views.xml', 'views/res_config_settings_views.xml', 'views/report_contribution_register_templates.xml', 'views/report_payslip_templates.xml', 'views/report_payslip_details_templates.xml', 'views/hr_contract_history_views.xml', 'views/hr_leave_type_view.xml', 'data/mail_template.xml', ], 'images': ['static/description/banner.png'], 'application': True, }
[ "odoomates@gmail.com" ]
odoomates@gmail.com
44f758bb7c8d4183146ac4198ba226b5ea1ab1a6
ea515ab67b832dad3a9b69bef723bd9d918395e7
/03_Implementacao/DataBase/true_or_false_question_while_and_for_cicles/question/version_2/answers_program.py
bce77d50a8726979edc4b446b00a9c0313e7c11d
[]
no_license
projeto-exercicios/Exercicios-Python-de-correccao-automatica
b52be3211e75d97cb55b6cdccdaa1d9f9d84f65b
a7c80ea2bec33296a3c2fbe4901ca509df4b1be6
refs/heads/master
2022-12-13T15:53:59.283232
2020-09-20T21:25:57
2020-09-20T21:25:57
295,470,320
0
0
null
null
null
null
UTF-8
Python
false
false
150
py
answer_1_true = while_cicle(48) answer_2_true = p answer_3_true = print_indexes(69) print(answer_1_true) print(answer_2_true) print(answer_3_true)
[ "ruski@milo.com" ]
ruski@milo.com
f0284d22965f628a9a0b899b316fe6e649b59ee5
ce76b3ef70b885d7c354b6ddb8447d111548e0f1
/same_place/own_number/bad_way_or_year/different_week_or_able_work.py
66bfb32cdb2de9f544d9b8a983695a71eb049913
[]
no_license
JingkaiTang/github-play
9bdca4115eee94a7b5e4ae9d3d6052514729ff21
51b550425a91a97480714fe9bc63cb5112f6f729
refs/heads/master
2021-01-20T20:18:21.249162
2016-08-19T07:20:12
2016-08-19T07:20:12
60,834,519
0
0
null
null
null
null
UTF-8
Python
false
false
218
py
#! /usr/bin/env python def place(str_arg): find_world_by_case(str_arg) print('point_and_little_problem') def find_world_by_case(str_arg): print(str_arg) if __name__ == '__main__': place('last_day')
[ "jingkaitang@gmail.com" ]
jingkaitang@gmail.com
d22510d282ed3e0b33f8d3e501117b4b8527cca0
91438802ee114b2fb945aae4105a17993dd6953d
/build/learning_ros_noetic/Part_5/ur10_robot/ur_traj_client/catkin_generated/pkg.installspace.context.pc.py
4807c4137df7658f74a42609d61315e95299f603
[]
no_license
AlexLam616/Baxter-robot
3a4cef31fe46da0fdb23c0e3b5808d84b412d037
d10fdcd35f29427ca14bb75f14fa9c64af3b028c
refs/heads/master
2023-05-12T01:25:56.454549
2021-05-25T02:02:09
2021-05-25T02:02:09
367,070,028
0
0
null
null
null
null
UTF-8
Python
false
false
421
py
# generated from catkin/cmake/template/pkg.context.pc.in CATKIN_PACKAGE_PREFIX = "" PROJECT_PKG_CONFIG_INCLUDE_DIRS = "".split(';') if "" != "" else [] PROJECT_CATKIN_DEPENDS = "roscpp;actionlib;trajectory_msgs;control_msgs".replace(';', ' ') PKG_CONFIG_LIBRARIES_WITH_PREFIX = "".split(';') if "" != "" else [] PROJECT_NAME = "ur_traj_client" PROJECT_SPACE_DIR = "/home/alex/workspace/install" PROJECT_VERSION = "0.0.0"
[ "1155135145@link.cuhk.edu.hk" ]
1155135145@link.cuhk.edu.hk
fef8619855d686a10de3b4cc6d72b631190df666
15f321878face2af9317363c5f6de1e5ddd9b749
/solutions_python/Problem_201/2282.py
f467a7480d13917624dc75ae91326fb1c6115b5b
[]
no_license
dr-dos-ok/Code_Jam_Webscraper
c06fd59870842664cd79c41eb460a09553e1c80a
26a35bf114a3aa30fc4c677ef069d95f41665cc0
refs/heads/master
2020-04-06T08:17:40.938460
2018-10-14T10:12:47
2018-10-14T10:12:47
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,362
py
def rec_stall(n): res = [] if n == 1: return stalls[1] if n == 2: return stalls[2] if n == 3: return stalls[3] if n%2 == 0: a = rec_stall(n/2) b = rec_stall(n/2-1) res.extend([[n/2-1,n/2]]) c = [list(x) for x in zip(a,b)] c = [val for sublist in c for val in sublist] res.extend(c) res.extend([[0,0]]) return res else: a = rec_stall(n/2) res.extend([[n/2,n/2]]) c = [list(x) for x in zip(a,a)] c = [val for sublist in c for val in sublist] res.extend(c) res.extend([[0,0]]) return res stalls = [0,0,0,0] stalls[1] = [[0,0]] stalls[2] = [[0,1],[0,0]] stalls[3] = [[1,1],[0,0],[0,0]] #stalls[4] = [[1,2],[0,1],[0,0],[0,0]] #stalls[5] = [[2,2],[0,1],[0,1],[0,0],[0,0]] #stalls[6] = [[2,3],[1,1],[0,1],[0,0],[0,0],[0,0]] #print 1,rec_stall(1) #print 2,rec_stall(2) #print 3,rec_stall(3) #print 4,rec_stall(4) #print 5,rec_stall(5) #print 6,rec_stall(6) #print 7,rec_stall(7) #print 8,rec_stall(8) t = int(raw_input()) # read a line with a single integer for i in xrange(1, t + 1): n, m = [int(s) for s in raw_input().split(" ")] # read a list of integers, 2 in this case if n == m: print "Case #{}: {} {}".format(i, 0, 0) continue s = rec_stall(n) #print "Case #{}: {} {}", i, s, n, m, max(s[m-1]), min(s[m-1]) print "Case #{}: {} {}".format(i, max(s[m-1]), min(s[m-1]))
[ "miliar1732@gmail.com" ]
miliar1732@gmail.com
2f819d9b7131ebb5ab3ba5de2b16433c41ef6657
da7a893f0dc9c130b5f8c29d4875e7c5d98ac64f
/code-slides/0019-fib-more-fast-examples.py
8dbdcdff07628e4544477b3860838a7d9f952cf8
[]
no_license
py-yyc/decorators
a489d89869582a9127a5272e9342b8131ad91fe3
bd7c65b78b3f00cf8da216eab945f3ef26c1b2a8
refs/heads/master
2020-06-20T18:29:59.884497
2016-02-23T21:48:09
2016-02-23T21:48:09
52,392,195
1
0
null
null
null
null
UTF-8
Python
false
false
906
py
from __future__ import print_function # noslide ## <h1>how decorators work</h1> from time import time # noslide from contextlib import contextmanager # noslide @contextmanager # noslide def timer(): # noslide s = time() # noslide yield # noslide print("took {:.6f}s".format(time() - s)) # noslide def memoize(fn): # noslide cache = {} # noslide def wrapper(*args): # noslide try: # noslide return cache[args] # noslide except KeyError: # noslide r = fn(*args) # noslide cache[args] = r # noslide return r # noslide return wrapper # noslide @memoize # noslide def fib(x): # noslide if x in [1, 2]: # noslide return 1 # noslide return fib(x - 1) + fib(x - 2) # noslide with timer(): print("fib(100) =", fib(100)) with timer(): print("fib(200) =", fib(200)) ## show-output
[ "meejah@meejah.ca" ]
meejah@meejah.ca
5d7458f2c2d6962f5be50183283d1437f8dc2908
68f757e7be32235c73e316888ee65a41c48ecd4e
/python_book(이것이 코딩테스트다)/03 그리디/3-2 큰수의 법칙.py
b1f160381acf71c965174db1df86f096e154ed49
[]
no_license
leejongcheal/algorithm_python
b346fcdbe9b1fdee33f689477f983a63cf1557dc
f5d9bc468cab8de07b9853c97c3db983e6965d8f
refs/heads/master
2022-03-05T20:16:21.437936
2022-03-03T01:28:36
2022-03-03T01:28:36
246,039,901
1
0
null
null
null
null
UTF-8
Python
false
false
256
py
n, m, k = map(int,input().split()) L = list(map(int,input().split())) f = max(L) L.remove(f) s = max(L) flag = 0 result = 0 for i in range(m): flag += 1 if flag >= k: result += s flag = 0 else: result += f print(result)
[ "aksndk123@naver.com" ]
aksndk123@naver.com
fd13a713a5caf9c48c60ad83f504415838e20c7c
710d2f31b6808187c4895a618101c25b36d25b3c
/backend/home/migrations/0002_customtext_homepage_message.py
306e32a28d93fb23006c97f446b674b7a449a077
[]
no_license
crowdbotics-apps/haplen-28237
920231c921a3aa490acc97a7debacc6858c520de
938cef97a8534941cb5f4de9684c95361ae27ef3
refs/heads/master
2023-05-31T20:26:37.979544
2021-06-25T20:12:49
2021-06-25T20:12:49
380,344,291
0
0
null
null
null
null
UTF-8
Python
false
false
1,515
py
# Generated by Django 2.2.20 on 2021-06-25 20:12 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('dating', '0001_initial'), ('home', '0001_load_initial_data'), ] operations = [ migrations.CreateModel( name='CustomText', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=150)), ], ), migrations.CreateModel( name='HomePage', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('body', models.TextField()), ], ), migrations.CreateModel( name='Message', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('slug', models.SlugField()), ('created', models.DateTimeField(auto_now_add=True)), ('inbox', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='message_inbox', to='dating.Inbox')), ('match', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='message_match', to='dating.Match')), ], ), ]
[ "team@crowdbotics.com" ]
team@crowdbotics.com
3033e6d1836363f7bb5afdf44a0c0c1d5e093bf0
ad372f7753c70e3997d035097ee03f740a5fb068
/pygym/custom_storage.py
83d139b7b163479af1d7152929f4ca060d13b04d
[]
no_license
Insper/servidor-de-desafios
a5f09fe9368887b06b98800f2bb8f35ff13f80a9
9875e9b9248c14237161ca73983595f7d929e963
refs/heads/master
2022-12-14T17:28:42.963112
2022-09-12T19:18:36
2022-09-12T19:18:36
167,026,050
3
42
null
2022-12-08T07:36:47
2019-01-22T16:19:46
Python
UTF-8
Python
false
false
1,053
py
# Source: https://github.com/druids/django-chamber/blob/master/chamber/storages/boto3.py from django.core.files.base import ContentFile from storages.backends.s3boto3 import S3Boto3Storage def force_bytes_content(content, blocksize=1024): """Returns a tuple of content (file-like object) and bool indicating wheter the content has been casted or not""" block = content.read(blocksize) content.seek(0) if not isinstance(block, bytes): _content = bytes( content.read(), 'utf-8' if not hasattr(content, 'encoding') or content.encoding is None else content.encoding, ) return ContentFile(_content), True return content, False class MediaStorage(S3Boto3Storage): bucket_name = 'softdes-static' location = 'media' def _clean_name(self, name): # pathlib support return super()._clean_name(str(name)) def save(self, name, content, max_length=None): content, _ = force_bytes_content(content) return super().save(name, content, max_length)
[ "andrew.kurauchi@gmail.com" ]
andrew.kurauchi@gmail.com
b4732a7f6c96f3017dae541e6ef9294eb8632c9c
6982c3c54ee9199d93fb89c61cfdcba15b9b7012
/python3_cookbook/chapter08/demo02.py
85770265aaaf5341ddc89a3e76168dd08817c360
[]
no_license
gzgdouru/python_study
a640e1097ebc27d12049ded53fb1af3ba9729bac
e24b39e82e39ee5a5e54566781457e18c90a122a
refs/heads/master
2020-03-29T11:33:13.150869
2019-03-08T09:24:29
2019-03-08T09:24:29
149,858,658
0
1
null
null
null
null
UTF-8
Python
false
false
668
py
''' 自定义字符串的格式化 ''' _formats = { 'ymd': '{d.year}-{d.month}-{d.day}', 'mdy': '{d.month}/{d.day}/{d.year}', 'dmy': '{d.day}/{d.month}/{d.year}' } class Date: def __init__(self, year, month, day): self.year = year self.month = month self.day = day def __format__(self, format_spec): if format_spec == '': format_spec = "ymd" fmt = _formats[format_spec] return fmt.format(d=self) if __name__ == "__main__": d = Date(2019, 1, 17) print(format(d)) print(format(d, 'dmy')) print("this date is {:ymd}".format(d)) print("this date is {:dmy}".format(d))
[ "18719091650@163.com" ]
18719091650@163.com
09925f31f19351fda75ef9c39ecb6ecb186a5c99
24f354c0a362c0a44fe0946f0a947930f0724f4d
/tests/unit/config/test_ini.py
d3608a6f540a216b4c83bd97783eb9170438e817
[ "MIT" ]
permissive
pypa/virtualenv
783cf226c806bcb44ee63fd87c37d76e90c121ce
6d22da631fd289f89f921a4010047ad969b7bfa7
refs/heads/main
2023-09-04T06:50:16.410634
2023-08-30T14:32:38
2023-08-30T14:32:38
1,446,474
4,313
1,073
MIT
2023-09-12T14:54:09
2011-03-06T14:33:27
Python
UTF-8
Python
false
false
842
py
from __future__ import annotations import sys from textwrap import dedent import pytest from virtualenv.info import IS_PYPY, IS_WIN, fs_supports_symlink from virtualenv.run import session_via_cli @pytest.mark.skipif(not fs_supports_symlink(), reason="symlink is not supported") @pytest.mark.xfail(IS_PYPY and IS_WIN and sys.version_info[0:2] == (3, 9), reason="symlink is not supported") def test_ini_can_be_overwritten_by_flag(tmp_path, monkeypatch): custom_ini = tmp_path / "conf.ini" custom_ini.write_text( dedent( """ [virtualenv] copies = True """, ), encoding="utf-8", ) monkeypatch.setenv("VIRTUALENV_CONFIG_FILE", str(custom_ini)) result = session_via_cli(["venv", "--symlinks"]) symlinks = result.creator.symlinks assert symlinks is True
[ "noreply@github.com" ]
pypa.noreply@github.com
84a51f1c66522d2338158587e627aa28ee1c0298
6fa7f99d3d3d9b177ef01ebf9a9da4982813b7d4
/pyDemMDspSSFdWsh4_2.py
b7cb001bbe31b50d1e5bc5559aa8530b83963619
[]
no_license
daniel-reich/ubiquitous-fiesta
26e80f0082f8589e51d359ce7953117a3da7d38c
9af2700dbe59284f5697e612491499841a6c126f
refs/heads/master
2023-04-05T06:40:37.328213
2021-04-06T20:17:44
2021-04-06T20:17:44
355,318,759
0
0
null
null
null
null
UTF-8
Python
false
false
262
py
def digital_decipher(eMessage, key): keyPos = 0 key = str(key) decodeMessage = '' for digit in eMessage: decodeMessage += chr(int(digit) - int(key[keyPos])+96) keyPos += 1 if (keyPos >= len(key)): keyPos = 0 return decodeMessage
[ "daniel.reich@danielreichs-MacBook-Pro.local" ]
daniel.reich@danielreichs-MacBook-Pro.local
d20971ac7d122528ac943d5a46e7e8f529aa93db
19a4365d81507587ef09488edc7850c2227e7165
/159.py
1269b3a84de6cd5b5911a7d86d4ea7721918348b
[]
no_license
akauntotesuto888/Leetcode-Lintcode-Python
80d8d9870b3d81da7be9c103199dad618ea8739a
e2fc7d183d4708061ab9b610b3b7b9e2c3dfae6d
refs/heads/master
2023-08-07T12:53:43.966641
2021-09-17T19:51:09
2021-09-17T19:51:09
null
0
0
null
null
null
null
UTF-8
Python
false
false
654
py
# Time: O(n) # Space: O(1) class Solution: def lengthOfLongestSubstringTwoDistinct(self, s: str) -> int: d = {} count = 0 start, end = 0, 0 result = 0 while end < len(s): c = s[end] d[c] = d.get(c, 0) + 1 if d[c] == 1: count += 1 end += 1 while count > 2 and start < len(s): curr = s[start] if curr in d: d[curr] -= 1 if d[curr] == 0: count -= 1 start += 1 result = max(result, end-start) return result
[ "tiant@qualtrics.com" ]
tiant@qualtrics.com
39dcc0a8cb19d050d40f63af8512633fbbddc8e7
f17fe3c240aeda4205d934a34fc2fc407c6d9f8a
/backend/silent_lake_29099/wsgi.py
25d60da238c4e278e073595fb4c11c76d1b79f0b
[]
no_license
crowdbotics-apps/silent-lake-29099
d5baaa2272c8362af6cc2adacf738c99fa4bb770
6993bc68a87d0e835d5d3b4240e9e1412d851528
refs/heads/master
2023-06-22T22:49:18.030820
2021-07-23T23:51:23
2021-07-23T23:51:23
388,954,458
0
0
null
null
null
null
UTF-8
Python
false
false
411
py
""" WSGI config for silent_lake_29099 project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'silent_lake_29099.settings') application = get_wsgi_application()
[ "team@crowdbotics.com" ]
team@crowdbotics.com
a8a55c5ceaf4f047f4055dd69e03d9e78b0fb41b
e8c4392a4470abd770be6805e6032ef36cb50ea9
/dev/prepare_jvm_release.py
045adf5bd2e93b90499e8c464ec286e10128b43c
[ "Apache-2.0" ]
permissive
vishalbelsare/xgboost
3f133a97c20654e1ada64af4d89da2493a0197f0
b124a27f57c97123daf9629555aa07e90dc77aed
refs/heads/master
2023-08-17T01:50:45.285904
2021-11-23T08:45:36
2021-11-23T08:45:36
129,266,376
0
0
Apache-2.0
2021-11-23T18:35:32
2018-04-12T14:44:31
C++
UTF-8
Python
false
false
2,918
py
import os import sys import errno import subprocess import glob import shutil from contextlib import contextmanager def normpath(path): """Normalize UNIX path to a native path.""" normalized = os.path.join(*path.split("/")) if os.path.isabs(path): return os.path.abspath("/") + normalized else: return normalized def cp(source, target): source = normpath(source) target = normpath(target) print("cp {0} {1}".format(source, target)) shutil.copy(source, target) def maybe_makedirs(path): path = normpath(path) print("mkdir -p " + path) try: os.makedirs(path) except OSError as e: if e.errno != errno.EEXIST: raise @contextmanager def cd(path): path = normpath(path) cwd = os.getcwd() os.chdir(path) print("cd " + path) try: yield path finally: os.chdir(cwd) def run(command, **kwargs): print(command) subprocess.check_call(command, shell=True, **kwargs) def main(): with cd("jvm-packages/"): print("====copying pure-Python tracker====") for use_cuda in [True, False]: xgboost4j = "xgboost4j-gpu" if use_cuda else "xgboost4j" cp("../python-package/xgboost/tracker.py", f"{xgboost4j}/src/main/resources") print("====copying resources for testing====") with cd("../demo/CLI/regression"): run(f"{sys.executable} mapfeat.py") run(f"{sys.executable} mknfold.py machine.txt 1") for use_cuda in [True, False]: xgboost4j = "xgboost4j-gpu" if use_cuda else "xgboost4j" xgboost4j_spark = "xgboost4j-spark-gpu" if use_cuda else "xgboost4j-spark" maybe_makedirs(f"{xgboost4j}/src/test/resources") maybe_makedirs(f"{xgboost4j_spark}/src/test/resources") for file in glob.glob("../demo/data/agaricus.*"): cp(file, f"{xgboost4j}/src/test/resources") cp(file, f"{xgboost4j_spark}/src/test/resources") for file in glob.glob("../demo/CLI/regression/machine.txt.t*"): cp(file, f"{xgboost4j_spark}/src/test/resources") print("====Creating directories to hold native binaries====") for os, arch in [("linux", "x86_64"), ("windows", "x86_64"), ("macos", "x86_64")]: output_dir = f"xgboost4j/src/main/resources/lib/{os}/{arch}" maybe_makedirs(output_dir) for os, arch in [("linux", "x86_64")]: output_dir = f"xgboost4j-gpu/src/main/resources/lib/{os}/{arch}" maybe_makedirs(output_dir) print("====Next Steps====") print("1. Obtain Linux and Windows binaries from the CI server") print("2. Put them in xgboost4j(-gpu)/src/main/resources/lib/[os]/[arch]") print("3. Now on a Mac machine, run:") print(" GPG_TTY=$(tty) mvn deploy -Prelease -DskipTests") if __name__ == "__main__": main()
[ "noreply@github.com" ]
vishalbelsare.noreply@github.com
be23945603db0d48e9bf6c9b3d89f7c8c219bc1d
7d85c42e99e8009f63eade5aa54979abbbe4c350
/game/tools/build_tools/make.py
2e55e59e68a8d04a495b61e0b90078d11af6cf1a
[]
no_license
ToontownServerArchive/Cog-Invasion-Online-Alpha
19c0454da87e47f864c0a5cb8c6835bca6923f0e
40498d115ed716f1dec12cf40144015c806cc21f
refs/heads/master
2023-03-25T08:49:40.878384
2016-07-05T07:09:36
2016-07-05T07:09:36
348,172,701
0
0
null
null
null
null
UTF-8
Python
false
false
4,312
py
''' Use this script to invoke Nirai builder and compile the game. This process consists of 3 step: 1. Pack models into a models.mf. 2. Compile src/sample.cxx and generate sample.exe using NiraiCompiler. 3. Generate sample.nri, which contains the Python modules. ''' import argparse import sys import os from niraitools import * parser = argparse.ArgumentParser() parser.add_argument('--compile-cxx', '-c', action='store_true', help='Compile the CXX codes and generate coginvasion.exe into built.') parser.add_argument('--make-nri', '-n', action='store_true', help='Generate coginvasion.nri.') parser.add_argument('--is-launcher', '-l', action='store_true', help='Are we compiling the launcher?') parser.add_argument('--models', '-m', action='store_true', help='Pack models.mf.') args = parser.parse_args() def niraicall_obfuscate(code): # We'll obfuscate if len(code) % 4 == 0 # This way we make sure both obfuscated and non-obfuscated code work. if len(code) % 4: return False, None # There are several ways to obfuscate it # For this example, we'll invert the string return True, code[::-1] niraimarshal.niraicall_obfuscate = niraicall_obfuscate class CIOPackager(NiraiPackager): HEADER = 'COGINVASIONONLINE' BASEDIR = '.' def __init__(self, outfile): if args.is_launcher: self.HEADER = 'COGINVASIONLAUNCHER' NiraiPackager.__init__(self, outfile) self.__manglebase = self.get_mangle_base(self.BASEDIR) self.add_panda3d_dirs() self.add_default_lib() self.add_directory(self.BASEDIR, mangler=self.__mangler) def __mangler(self, name): # N.B. Mangler can be used to strip certain files from the build. # The file is not included if it returns an empty string. return name[self.__manglebase:].strip('.') def generate_niraidata(self): print 'Generating niraidata' config = self.get_file_contents('tools/build_tools/config.prc', True) niraidata = 'CONFIG = %r' % config self.add_module('niraidata', niraidata, compile=True) def process_modules(self): ''' This method is called when it's time to write the output. For sample.nri, we use an encrypted datagram. The datagram is read by sample.cxx, which populates Python frozen array. Datagram format: uint32 numModules for each module: string name int32 size * data(abs(size)) * Negative size means the file was an __init__ ''' dg = Datagram() dg.addUint32(len(self.modules)) for moduleName in self.modules: data, size = self.modules[moduleName] dg.addString(moduleName) dg.addInt32(size) dg.appendData(data) data = dg.getMessage() iv = '\0' * 16 if args.is_launcher: key = 'mmkfcaaph_cil_bm' else: key = 'mmkfcaaph_cio_bm' return aes.encrypt(data, key, iv) if args.compile_cxx and not args.is_launcher: compiler = NiraiCompiler('coginvasion.exe') compiler.add_nirai_files() compiler.add_source('tools/build_tools/coginvasion.cxx') compiler.run() elif args.is_launcher and args.compile_cxx: compiler = NiraiCompiler('launcher.exe') compiler.add_nirai_files() compiler.add_source('tools/build_tools/launcher.cxx') compiler.run() if args.make_nri and not args.is_launcher: pkg = CIOPackager('built/coginvasion.bin') pkg.add_file('lib/coginvasion/base/CIStartGlobal.py') pkg.add_directory('lib\\coginvasion') pkg.generate_niraidata() pkg.write_out() elif args.is_launcher and args.make_nri: pkg = CIOPackager('built/launcher.bin') pkg.add_file('lib/launcher.py') pkg.add_file('../Panda3D-CI/python/DLLs/_tkinter.pyd') pkg.generate_niraidata() pkg.write_out() if args.models: os.chdir('..') cmd = 'multify -cf build/built/models.mf models' p = subprocess.Popen(cmd, stdout=sys.stdout, stderr=sys.stderr, shell=True) v = p.wait() if v != 0: print 'The following command returned non-zero value (%d): %s' % (v, cmd[:100] + '...') sys.exit(1)
[ "brianlach72@gmail.com" ]
brianlach72@gmail.com
baf9e01690d9b7617c973a0ffbeaf8dff30a2ba2
3712a929d1124f514ea7af1ac0d4a1de03bb6773
/开班笔记/python网络爬虫部分/day02/lxmlTest.py
5436f0ebe77b8b9ef01a6d55ce88f6ab04779c42
[]
no_license
jiyabing/learning
abd82aa3fd37310b4a98b11ea802c5b0e37b7ad9
6059006b0f86aee9a74cfc116d2284eb44173f41
refs/heads/master
2020-04-02T20:47:33.025331
2018-10-26T05:46:10
2018-10-26T05:46:10
154,779,387
0
0
null
null
null
null
UTF-8
Python
false
false
602
py
# -*- coding: utf-8 -*- """ Created on Thu Jul 12 17:20:25 2018 @author: jyb """ from lxml import etree lxmlStr = ''' <bookstore> <book> <title lang="en">Harry Potter</title> <author>J K. Rowling</author> <year>2005</year> <price>29.99</price> </book> <book> <title lang="zh">hello world</title> <author>J K. Rowling</author> <year>2005</year> <price>29.99</price> </book> </bookstore> ''' # 根节点 root = etree.fromstring(lxmlStr) print(root) elements = root.xpath('//book/title') print(elements[0].text) print(elements[0].attrib) attrs = root.xpath('//@lang') print(attrs)
[ "yabing_ji@163.com" ]
yabing_ji@163.com
89e2373d1870ea26db666a16121383000169882e
8a081742c8a58c872a15f01d6d4d8c1028e4f7eb
/1404.py
b7f2fe45af35e2bd9b49f8c76ce20624ed64ad2c
[]
no_license
dibery/leetcode
01b933772e317ccd4885b508de503b7873a4b65f
096218b5d0b47ce38874c4b7141aca35e9d678c9
refs/heads/master
2022-05-20T03:50:45.525256
2022-05-17T00:57:48
2022-05-17T00:57:48
211,606,152
2
0
null
null
null
null
UTF-8
Python
false
false
187
py
class Solution: def numSteps(self, s: str) -> int: s, ans = int(s, 2), 0 while s > 1: ans += 1 s += 1 if s % 2 else s //= 2 return ans
[ "bor810818@yahoo.com.tw" ]
bor810818@yahoo.com.tw
1bccf0f17e21a5f80aa85d92e8131607b1f3fa1c
9818262abff066b528a4c24333f40bdbe0ae9e21
/Day 28/UtopianTree.py
1bc5b897230286bb4173fdca69d29b1cdd03d6f9
[ "MIT" ]
permissive
skdonepudi/100DaysOfCode
749f62eef5826cb2ec2a9ab890fa23e784072703
af4594fb6933e4281d298fa921311ccc07295a7c
refs/heads/master
2023-02-01T08:51:33.074538
2020-12-20T14:02:36
2020-12-20T14:02:36
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,435
py
''' The Utopian Tree goes through 2 cycles of growth every year. Each spring, it doubles in height. Each summer, its height increases by 1 meter. A Utopian Tree sapling with a height of 1 meter is planted at the onset of spring. How tall will the tree be after growth cycles? For example, if the number of growth cycles is , the calculations are as follows: Period Height 0 1 1 2 2 3 3 6 4 7 5 14 Function Description Complete the utopianTree function in the editor below. utopianTree has the following parameter(s): int n: the number of growth cycles to simulate Returns int: the height of the tree after the given number of cycles Input Format The first line contains an integer, , the number of test cases. subsequent lines each contain an integer, , the number of cycles for that test case. Sample Input 3 0 1 4 Sample Output 1 2 7 ''' #!/bin/python3 import math import os import random import re import sys # Complete the utopianTree function below. def utopianTree(n): if n < 3: return n + 1 if n % 2 == 0: return (utopianTree(n - 2) * 2) + 1 else: return (utopianTree(n - 2) + 1) * 2 if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') t = int(input()) for t_itr in range(t): n = int(input()) result = utopianTree(n) fptr.write(str(result) + '\n') fptr.close()
[ "sandeepiiitn@gmail.com" ]
sandeepiiitn@gmail.com
d7ce82cd92dd0e5ae2c3e33a2bbb2f04c5a3d44b
987697512ce9b8d7c29bfd2f18d5aec0261a6863
/最长回文串.py
8b40ab6ad9297a3c3ba8188befafb8af968ff812
[]
no_license
Luckyaxah/leetcode-python
65e7ff59d6f19312defdc4d4b4103c39193b198a
2b9c78ba88e7bf74a46a287fb1914b4d6ba9af38
refs/heads/master
2023-06-05T12:15:31.618879
2021-06-22T13:05:30
2021-06-22T13:05:30
262,287,940
0
0
null
null
null
null
UTF-8
Python
false
false
515
py
class Solution: def longestPalindrome(self, s: str) -> int: d = {} for i in s: if not i in d: d[i] = 1 else: d[i] += 1 ret = 0 m = 0 for i in d: if d[i] % 2 ==0: ret += d[i] else: ret += d[i]-1 if ret < len(s): ret += 1 return ret if __name__ == "__main__": a = Solution() print(a.longestPalindrome("civilwartestingwhee"))
[ "math_leqi@163.com" ]
math_leqi@163.com
f37207209c196d663aa2e43026e64b1a2b9cd70e
ce76b3ef70b885d7c354b6ddb8447d111548e0f1
/great_year_and_same_woman/important_part/group/want_old_place.py
611d05cfce1273ef655fed24e8b67caedddea3ff
[]
no_license
JingkaiTang/github-play
9bdca4115eee94a7b5e4ae9d3d6052514729ff21
51b550425a91a97480714fe9bc63cb5112f6f729
refs/heads/master
2021-01-20T20:18:21.249162
2016-08-19T07:20:12
2016-08-19T07:20:12
60,834,519
0
0
null
null
null
null
UTF-8
Python
false
false
193
py
#! /usr/bin/env python def great_work(str_arg): life(str_arg) print('able_person') def life(str_arg): print(str_arg) if __name__ == '__main__': great_work('life_and_child')
[ "jingkaitang@gmail.com" ]
jingkaitang@gmail.com
350aba3f5ae51a3e7b63b960204bddbeee38d131
d01822ba7fa5522c89c83f20907003f5c4823dde
/CNN_GPU.py
559d15521dd4810f15c81c1a9f11094f08a722f2
[]
no_license
cp4011/Neural-Network
853aab63c871d19aeb73911af56ccf9351ad1f3c
93b33b6a14fed7010285da8fb3efc4a62152cef3
refs/heads/master
2020-05-02T07:22:18.778871
2019-04-15T10:49:40
2019-04-15T10:49:40
177,816,249
2
0
null
null
null
null
UTF-8
Python
false
false
2,451
py
import torch import torch.nn as nn import torch.utils.data as Data import torchvision # torch.manual_seed(1) EPOCH = 1 BATCH_SIZE = 50 LR = 0.001 DOWNLOAD_MNIST = False train_data = torchvision.datasets.MNIST(root='./mnist/', train=True, transform=torchvision.transforms.ToTensor(), download=DOWNLOAD_MNIST,) train_loader = Data.DataLoader(dataset=train_data, batch_size=BATCH_SIZE, shuffle=True) test_data = torchvision.datasets.MNIST(root='./mnist/', train=False) # !!!!!!!! Change in here !!!!!!!!! # test_x = torch.unsqueeze(test_data.test_data, dim=1).type(torch.FloatTensor)[:2000].cuda()/255. # Tensor on GPU test_y = test_data.test_labels[:2000].cuda() class CNN(nn.Module): def __init__(self): super(CNN, self).__init__() self.conv1 = nn.Sequential(nn.Conv2d(in_channels=1, out_channels=16, kernel_size=5, stride=1, padding=2,), nn.ReLU(), nn.MaxPool2d(kernel_size=2),) self.conv2 = nn.Sequential(nn.Conv2d(16, 32, 5, 1, 2), nn.ReLU(), nn.MaxPool2d(2),) self.out = nn.Linear(32 * 7 * 7, 10) def forward(self, x): x = self.conv1(x) x = self.conv2(x) x = x.view(x.size(0), -1) output = self.out(x) return output cnn = CNN() # !!!!!!!! Change in here !!!!!!!!! # cnn.cuda() # Moves all model parameters and buffers to the GPU. optimizer = torch.optim.Adam(cnn.parameters(), lr=LR) loss_func = nn.CrossEntropyLoss() for epoch in range(EPOCH): for step, (x, y) in enumerate(train_loader): # !!!!!!!! Change in here !!!!!!!!! # b_x = x.cuda() # Tensor on GPU b_y = y.cuda() # Tensor on GPU output = cnn(b_x) loss = loss_func(output, b_y) optimizer.zero_grad() loss.backward() optimizer.step() if step % 50 == 0: test_output = cnn(test_x) # !!!!!!!! Change in here !!!!!!!!! # pred_y = torch.max(test_output, 1)[1].cuda().data # move the computation in GPU accuracy = torch.sum(pred_y == test_y).type(torch.FloatTensor) / test_y.size(0) print('Epoch: ', epoch, '| train loss: %.4f' % loss.data.cpu().numpy(), '| test accuracy: %.2f' % accuracy) test_output = cnn(test_x[:10]) # !!!!!!!! Change in here !!!!!!!!! # pred_y = torch.max(test_output, 1)[1].cuda().data # move the computation in GPU print(pred_y, 'prediction number') print(test_y[:10], 'real number')
[ "957628963@qq.com" ]
957628963@qq.com
a6f529f5c6d00ff3aba3df255dba713e85eac766
1c07579679f8a4c861777cff4faf30a8064862db
/social/__init__.py
e993f2fda050c964968927a8b09d383d28ce9fcc
[ "BSD-3-Clause", "Python-2.0", "BSD-2-Clause" ]
permissive
florelui001/python-social-auth
86591a1c12dfc011a0d755a7b397691e54821400
81093d2135c3eafd6fc5dd763f31a7889a9f1ce4
refs/heads/master
2021-01-15T08:10:42.444979
2014-02-27T21:00:17
2014-02-27T21:00:17
null
0
0
null
null
null
null
UTF-8
Python
false
false
216
py
""" python-social-auth application, allows OpenId or OAuth user registration/authentication just adding a few configurations. """ version = (0, 1, 22) extra = '-dev' __version__ = '.'.join(map(str, version)) + extra
[ "matiasaguirre@gmail.com" ]
matiasaguirre@gmail.com
b04b9e636a59a5c6f889dd245dae7adbd868af09
8f6946286dfad1d61be7425dde737daed7027c3f
/ckstyle/command/args.py
0c7551eafb4fb344689f8901ef20f989f68d82c1
[ "BSD-3-Clause" ]
permissive
ljspace/CSSCheckStyle
e75d7616d8c9444b581b38a91a10aff7b4f731ad
c12be2181d6576349bf52c218d8fb1809c11da12
refs/heads/master
2021-01-16T20:29:55.157662
2013-04-16T03:58:36
2013-04-16T03:58:36
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,211
py
class CommandArgs(): def __init__(self): self.operation = None self.errorLevel = 2 self.recursive = False self.printFlag = False self.extension = '.ckstyle.txt' self.include = 'all' self.exclude = 'none' self.standard = '' self.exportJson = False self.ignoreRuleSets = ['@unit-test-expecteds'] self.fixedExtension = '.fixed.css' self.fixToSingleLine = False self.compressConfig = CompressArgs() self.safeMode = False self.noBak = False # current browser self._curBrowser = None def __str__(self): return 'errorLevel: %s\n recursive: %s\n printFlag: %s\n extension: %s\n include: %s\n exclude: %s' % (self.errorLevel, self.recursive, self.printFlag, self.extension, self.include, self.exclude) class CompressArgs(): def __init__(self): self.extension = '.min.css' self.combineFile = True self.browsers = None self.noBak = False def __str__(self): return 'extension: %s, combineFile: %s, browsers: %s' % (self.recursive, self.extension, self.combineAttr, self.combineRuleSet, self.combineFile, self.browsers)
[ "wangjeaf@gmail.com" ]
wangjeaf@gmail.com
9615461a5293189ea9ccf409f475b6f55413cc97
7a550d2268bc4bc7e2fec608ffb1db4b2e5e94a0
/1201-1300/1273-Delete Tree Nodes/1273-Delete Tree Nodes.py
5aaf4cc9fdfc040b2b1d974afc0e5e5b2294eae5
[ "MIT" ]
permissive
jiadaizhao/LeetCode
be31bd0db50cc6835d9c9eff8e0175747098afc6
4ddea0a532fe7c5d053ffbd6870174ec99fc2d60
refs/heads/master
2021-11-05T04:38:47.252590
2021-10-31T09:54:53
2021-10-31T09:54:53
99,655,604
52
28
MIT
2020-10-02T12:47:47
2017-08-08T05:57:26
C++
UTF-8
Python
false
false
545
py
import collections class Solution: def deleteTreeNodes(self, nodes: int, parent: List[int], value: List[int]) -> int: graph = collections.defaultdict(list) for i in range(1, len(parent)): graph[parent[i]].append(i) def dfs(root): total = value[root] count = 1 for child in graph[root]: s, c = dfs(child) total += s count += c return total, count if total != 0 else 0 return dfs(0)[1]
[ "jiadaizhao@gmail.com" ]
jiadaizhao@gmail.com
b56cf17c850ee1b033aa5372bb53774fe8d95850
dd221d1ab80a49190a0c93277e2471debaa2db95
/hanlp/components/parsers/ud/ud_model.py
729f49c1af9decf8c14572ed1691eed63ed91021
[ "Apache-2.0", "CC-BY-NC-SA-4.0" ]
permissive
hankcs/HanLP
29a22d4e240617e4dc67929c2f9760a822402cf7
be2f04905a12990a527417bd47b79b851874a201
refs/heads/doc-zh
2023-08-18T12:48:43.533453
2020-02-15T17:19:28
2023-03-14T02:46:03
24,976,755
32,454
9,770
Apache-2.0
2023-08-13T03:11:39
2014-10-09T06:36:16
Python
UTF-8
Python
false
false
5,198
py
# -*- coding:utf-8 -*- # Author: hankcs # Date: 2020-12-15 14:21 from typing import Dict, Any import torch from hanlp.components.parsers.biaffine.biaffine_dep import BiaffineDependencyParser from hanlp.components.parsers.biaffine.biaffine_model import BiaffineDecoder from hanlp.components.parsers.ud.tag_decoder import TagDecoder from hanlp.layers.embeddings.contextual_word_embedding import ContextualWordEmbeddingModule from hanlp.layers.scalar_mix import ScalarMixWithDropout class UniversalDependenciesModel(torch.nn.Module): def __init__(self, encoder: ContextualWordEmbeddingModule, n_mlp_arc, n_mlp_rel, mlp_dropout, num_rels, num_lemmas, num_upos, num_feats, mix_embedding: int = 13, layer_dropout: int = 0.0): super().__init__() self.encoder = encoder self.decoder = UniversalDependenciesDecoder( encoder.get_output_dim(), n_mlp_arc, n_mlp_rel, mlp_dropout, num_rels, num_lemmas, num_upos, num_feats, mix_embedding, layer_dropout ) def forward(self, batch: Dict[str, torch.Tensor], mask, ): hidden = self.encoder(batch) return self.decoder(hidden, batch=batch, mask=mask) class UniversalDependenciesDecoder(torch.nn.Module): def __init__(self, hidden_size, n_mlp_arc, n_mlp_rel, mlp_dropout, num_rels, num_lemmas, num_upos, num_feats, mix_embedding: int = 13, layer_dropout: int = 0.0, ) -> None: super(UniversalDependenciesDecoder, self).__init__() # decoders self.decoders = torch.nn.ModuleDict({ 'lemmas': TagDecoder(hidden_size, num_lemmas, label_smoothing=0.03, adaptive=True), 'upos': TagDecoder(hidden_size, num_upos, label_smoothing=0.03, adaptive=True), 'deps': BiaffineDecoder(hidden_size, n_mlp_arc, n_mlp_rel, mlp_dropout, num_rels), 'feats': TagDecoder(hidden_size, num_feats, label_smoothing=0.03, adaptive=True), }) self.gold_keys = { 'lemmas': 'lemma_id', 'upos': 'pos_id', 'feats': 'feat_id', } if mix_embedding: self.scalar_mix = torch.nn.ModuleDict({ task: ScalarMixWithDropout((1, mix_embedding), do_layer_norm=False, dropout=layer_dropout) for task in self.decoders }) else: self.scalar_mix = None def forward(self, hidden, batch: Dict[str, torch.Tensor], mask) -> Dict[str, Any]: mask_without_root = mask.clone() mask_without_root[:, 0] = False logits = {} class_probabilities = {} output_dict = {"logits": logits, "class_probabilities": class_probabilities} loss = 0 arc = batch.get('arc', None) # Run through each of the tasks on the shared encoder and save predictions for task in self.decoders: if self.scalar_mix: decoder_input = self.scalar_mix[task](hidden, mask) else: decoder_input = hidden if task == "deps": s_arc, s_rel = self.decoders[task](decoder_input, mask) pred_output = {'class_probabilities': {'s_arc': s_arc, 's_rel': s_rel}} if arc is not None: # noinspection PyTypeChecker pred_output['loss'] = BiaffineDependencyParser.compute_loss(None, s_arc, s_rel, arc, batch['rel_id'], mask_without_root, torch.nn.functional.cross_entropy) else: pred_output = self.decoders[task](decoder_input, mask_without_root, batch.get(self.gold_keys[task], None)) if 'logits' in pred_output: logits[task] = pred_output["logits"] if 'class_probabilities' in pred_output: class_probabilities[task] = pred_output["class_probabilities"] if 'loss' in pred_output: # Keep track of the loss if we have the gold tags available loss += pred_output["loss"] if arc is not None: output_dict["loss"] = loss return output_dict def decode(self, output_dict: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]: for task in self.tasks: self.decoders[task].decode(output_dict) return output_dict
[ "jfservice@126.com" ]
jfservice@126.com
34da4c02c5e9aef4bb76bf8ab68e179817b9db01
42a7b34bce1d2968079c6ea034d4e3f7bb5802ad
/ex3.py
da806348e797aa669ec5014ca90987dda6716f49
[]
no_license
linpan/LPTHW
45c9f11265b5e1ffe0387a56cec192fa12c6c4d5
227bfee3098e8ecb5f07ffc3a0b8e64a853106ce
refs/heads/master
2021-04-26T13:42:56.859644
2014-12-18T15:21:14
2014-12-18T15:21:14
null
0
0
null
null
null
null
UTF-8
Python
false
false
521
py
#! /usr/bin/env python #coding:utf-8 print "I will now count my chieckens." print "Hens", 25 + 30 / 6 print "Roosters", 100 - 25 * 3 % 4 print "Now I will count the eggs:" print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 +6 print "Is it true that 3 + 2 < 5 -7 ?" print 3 + 2 < 5 -7 print "What is 3 +2 ?", 3 + 2 print "What is 5 -7 ?", 5 - 7 print "Oh,that's why it's False." print "How about some more." print "Is it greater?", 5 > -2 print "is it greater or equal?", 5 >= -2 print "Is it less or equal?", 5 <= -2
[ "shine_forever@yeah.net" ]
shine_forever@yeah.net
753ebea727be64a72b3dfbff1b574f0a142ce574
b2968e2b2092971f6fd72f9c72b50b5faf304985
/zjazd_4/math_examples.py
e68d657f4a70ceb57b0ca23ad3216c6fa53cfe9c
[]
no_license
ArturoWest/pythonbootcamp
815d0a3d6b29f12efdbd47fc7b7b7dfd18bff24f
fa7b20dfc71dcd80c201f28c72086294e482b075
refs/heads/master
2020-03-31T02:55:15.574065
2018-12-02T14:35:01
2018-12-02T14:35:01
151,844,686
0
0
null
null
null
null
UTF-8
Python
false
false
470
py
import math print(math.sin(math.pi/2)) print(dir(math)) """ Stwórz klasę sfera s = Sfera(10) s.promien # 10 s.objetosc() # 4188.78... s.pole_powierzchni() # 1256.63... """ class Kula: def __init__(self, r): self.promien = r def objetosc(self): return (4/3) * math.pi * math.pow(self.promien, 3) def pole_powierzchni(self): return 4 * math.pi * self.promien ** 2 s = Kula(10) print(s.objetosc()) print(s.pole_powierzchni())
[ "you@example.com" ]
you@example.com
6e06d589ab36e4ea0c4a28dbb5f19654f5117e41
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_5636311922769920_0/Python/ricbit/fractiles.py
92d6025f44c5533c922023d088ce4a84b348b55a
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
Python
false
false
148
py
for case in xrange(input()): k,c,s = map(int, raw_input().split()) print "Case #%d: %s" % (case + 1, ' '.join(str(1+i) for i in xrange(k)))
[ "alexandra1.back@gmail.com" ]
alexandra1.back@gmail.com
7373a853fc106496505b63aa97cb81a3b4c74a2d
04740a66d98730afca496eb0cf5e7b5edea5f6e6
/backend/dataset/strStr/strmatch_16.py
9c00b55f82dfafeb143e4c6fb29fe88f22448f09
[]
no_license
mehulthakral/logic_detector
0c06fbd12d77a02c888d0bbe3e6776a18f2f46e3
f7a07a6d229b250da9e02d3fac1a12fa51be97e8
refs/heads/master
2023-04-12T12:45:29.370502
2021-05-05T17:15:02
2021-05-05T17:15:02
323,953,099
2
0
null
2021-05-03T16:50:44
2020-12-23T16:39:28
null
UTF-8
Python
false
false
250
py
class Solution: def strStr(self, haystack, needle): n, h = len(needle), len(haystack) hash_n = hash(needle) for i in range(h-n+1): if hash(haystack[i:i+n]) == hash_n: return i return -1
[ "mehul.thakral@gmail.com" ]
mehul.thakral@gmail.com
33d8103a2f341f6f29a3359b9fa3be7c61b5e3ca
caa7a39055c3451db43b39ffc5e70dc560749334
/contactus/models.py
ca5c45307ce64df354bddb41c95112374e65bc33
[]
no_license
OneStage-NITW/website
da2438e3857c03a0c38fa6db6a33619b330a3e0d
af86e38560f16f70a0b74bcf2aeab4d855fbdc74
refs/heads/master
2016-08-12T15:17:14.577895
2015-05-31T18:10:52
2015-05-31T18:10:52
36,546,131
0
0
null
null
null
null
UTF-8
Python
false
false
129
py
from django.db import models # Create your models here. class Supporter(models.Model): name=models.CharField(max_length=100)
[ "vivekhtc25@gmail.com" ]
vivekhtc25@gmail.com
954d4f04753e7d4fd2561471a3d7d2caf2b10d6c
93c7eebb83b88cd4bfb06b6e5695ad785c84f1d6
/tazebao/newsletter/migrations/0019_tracking_notes.py
60750c49486164f1f0ac14d3f046001e45690468
[]
no_license
otto-torino/tazebao
960e31a576f4acc7cd4572e589424f54a8e9b166
12db8605b5aa9c8bf4f735a03af90d0989018105
refs/heads/master
2023-08-09T02:06:14.749976
2023-07-28T07:20:23
2023-07-28T07:20:23
68,196,585
5
0
null
2022-12-08T05:25:04
2016-09-14T10:21:21
HTML
UTF-8
Python
false
false
493
py
# -*- coding: utf-8 -*- # Generated by Django 1.10.1 on 2016-09-27 12:06 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('newsletter', '0018_tracking_type'), ] operations = [ migrations.AddField( model_name='tracking', name='notes', field=models.CharField(blank=True, max_length=255, null=True, verbose_name='note'), ), ]
[ "abidibo@gmail.com" ]
abidibo@gmail.com
ffa7006b45dc4d4246f63987a54c2535ec95a7de
68ea05d0d276441cb2d1e39c620d5991e0211b94
/2144.py
bb654c8a0b7125606aa402a02d74bd202336952f
[]
no_license
mcavalca/uri-python
286bc43aa157d3a6880dc222e0136c80cf079565
e22875d2609fe7e215f9f3ed3ca73a1bc2cf67be
refs/heads/master
2021-11-23T08:35:17.614443
2021-10-05T13:26:03
2021-10-05T13:26:03
131,339,175
50
27
null
2021-11-22T12:21:59
2018-04-27T19:54:09
Python
UTF-8
Python
false
false
618
py
final = 0.0 total = 0 while True: w1, w2, r = [int(x) for x in input().split()] if w1 == w2 == r == 0: break media = float(((w1 * (1 + r/30))+(w2 * (1 + r/30))))/2.0 final += media total += 1 if media < 13: print('Nao vai da nao') elif media < 14: print('E 13') elif media < 40: print('Bora, hora do show! BIIR!') elif media < 60: print('Ta saindo da jaula o monstro!') else: print('AQUI E BODYBUILDER!!') final = final/float(total) if final > 40: print() print('Aqui nois constroi fibra rapaz! Nao e agua com musculo!')
[ "m.cavalca@hotmail.com" ]
m.cavalca@hotmail.com
34c124b3a7647f01806bfe8477086b68f63e78b5
4a7092876b5057867a1290114e29dfd9fb1c0820
/fastccd_support_ioc/utils/python2-version/setFCRIC-Normal.py
28cf771b07ad1017c253270d147325d411a39a06
[ "BSD-3-Clause" ]
permissive
ihumphrey/fastccd_support_ioc
2380a9c23037ccb552d00efdb0235b7116e6ea19
7cd844102f042bea2fa5a31217e15fd72731b523
refs/heads/master
2023-03-03T04:34:39.827326
2021-02-08T19:47:09
2021-02-08T19:47:09
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,696
py
#! /usr/bin/python # -*- coding: utf-8 -*- import cin_constants import cin_register_map import cin_functions # Mask Triggers & turn off Bias # import setTriggerSW # cin_functions.setCameraOff() # Clamp Mode registers # Write clampr cin_functions.WriteReg("821D", "A000", 0) cin_functions.WriteReg("821E", "0048", 0) cin_functions.WriteReg("821F", "00C7", 0) cin_functions.WriteReg("8001", "0105", 0) cin_functions.WriteReg("821D", "A000", 0) cin_functions.WriteReg("821E", "0049", 0) cin_functions.WriteReg("821F", "004C", 0) cin_functions.WriteReg("8001", "0105", 0) # Write clamp cin_functions.WriteReg("821D", "A000", 0) cin_functions.WriteReg("821E", "0050", 0) cin_functions.WriteReg("821F", "00B4", 0) cin_functions.WriteReg("8001", "0105", 0) cin_functions.WriteReg("821D", "A000", 0) cin_functions.WriteReg("821E", "0051", 0) cin_functions.WriteReg("821F", "0002", 0) cin_functions.WriteReg("8001", "0105", 0) # Write ac on cin_functions.WriteReg("821D", "A000", 0) cin_functions.WriteReg("821E", "0058", 0) cin_functions.WriteReg("821F", "0001", 0) cin_functions.WriteReg("8001", "0105", 0) cin_functions.WriteReg("821D", "A000", 0) cin_functions.WriteReg("821E", "0059", 0) cin_functions.WriteReg("821F", "004C", 0) cin_functions.WriteReg("8001", "0105", 0) cin_functions.WriteReg("821D", "A000", 0) cin_functions.WriteReg("821E", "005A", 0) cin_functions.WriteReg("821F", "0064", 0) cin_functions.WriteReg("8001", "0105", 0) cin_functions.WriteReg("821D", "A000", 0) cin_functions.WriteReg("821E", "005B", 0) cin_functions.WriteReg("821F", "005B", 0) cin_functions.WriteReg("8001", "0105", 0) # Bias On & allow Ext Triggers # cin_functions.setCameraOn() # import setTrigger0
[ "ronpandolfi@gmail.com" ]
ronpandolfi@gmail.com
afa1dd6b0f679aa6df6a0a0250b61aa5007a4a21
08f5dd97433ce84868dbd95020e49f795e8e3f42
/website/migrations/0011_auto_20150726_2337.py
1c3b5f116150b0b516139ab4f7af13d2afd1e2d9
[]
no_license
katur/forthebirds
f76e9d78f8b71f5cb13f22f3c417e737f6048896
2118fabebd8780cd3151f5ddd88245de402590e9
refs/heads/master
2023-08-08T18:57:55.722516
2023-03-28T03:04:19
2023-03-28T03:04:19
22,771,365
2
1
null
2023-07-25T21:23:49
2014-08-08T20:56:20
Python
UTF-8
Python
false
false
1,219
py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('website', '0010_auto_20150104_1404'), ] operations = [ migrations.AddField( model_name='userprofile', name='speaking_keynotes', field=models.TextField(default='', help_text=b'Use Markdown syntax for italics, bullets, etc. See <a href="http://www.darkcoding.net/software/markdown-quick-reference">a quick reference</a>, <a href="http://www.markdowntutorial.com/">a tutorial</a>, or practice <a href="http://dillinger.io/">here</a>. ', blank=True), preserve_default=False, ), migrations.AddField( model_name='userprofile', name='speaking_testimonials', field=models.TextField(default='', help_text=b'Use Markdown syntax for italics, bullets, etc. See <a href="http://www.darkcoding.net/software/markdown-quick-reference">a quick reference</a>, <a href="http://www.markdowntutorial.com/">a tutorial</a>, or practice <a href="http://dillinger.io/">here</a>. ', blank=True), preserve_default=False, ), ]
[ "katherine.erickson@gmail.com" ]
katherine.erickson@gmail.com
d3e761fd33793aa11b6438e8a85ee6b8d49d9f26
bd02997a44218468b155eda45dd9dd592bb3d124
/baekjoon_1149.py
4e0e23db2a3600c59ccc9ab1de7704622b137d4c
[]
no_license
rheehot/ProblemSolving_Python
88b1eb303ab97624ae6c97e05393352695038d14
4d6dc6aea628f0e6e96530646c66216bf489427f
refs/heads/master
2023-02-13T03:30:07.039231
2021-01-04T06:04:11
2021-01-04T06:04:11
null
0
0
null
null
null
null
UTF-8
Python
false
false
912
py
''' Problem Solving Baekjoon 1149 Author: Injun Son Date: September 23, 2020 ''' import sys import copy from itertools import combinations from collections import deque import math N = int(input()) cost = [] for _ in range(N): r, g, v = map(int, input().split()) cost.append([r, g, v]) ''' dp[i][0] = i번째 집을 r로 칠할 때 최소 값 = cost[i][0]+ min(dp[i-1][1], dp[i-1][2] ) dp[i][1] = i번째 집을 g로 칠할 때 최소 값 = cost[i][1]+ min(dp[i-1][0], dp[i-1][2] ) dp[i][2] = i번째 집을 b로 칠할 때 최소 값 = cost[i][2]+ min(dp[i-1][0], dp[i-1][1] ) ''' dp = [ [0,0,0] for _ in range(N+1)] dp[0][0] = cost[0][0] dp[0][1] = cost[0][1] dp[0][2] = cost[0][2] for i in range(1, N): dp[i][0] = min(dp[i-1][1], dp[i-1][2])+cost[i][0] dp[i][1] = min(dp[i - 1][0], dp[i - 1][2]) + cost[i][1] dp[i][2] = min(dp[i - 1][0], dp[i - 1][1]) + cost[i][2] print(min(dp[N-1]))
[ "ison@sfu.ca" ]
ison@sfu.ca
6298ae66b2659ba754329d0314f6849ce42e0261
0995f4b2a0db3fe88e68862c4e3125becfb5f8af
/scripts/generate_pairs2_cacd.py
dfa29e0f924d62d97e13bde82bb8b16490216b2b
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
phymhan/face-aging
db010df62b281befeb1149085ba865382637e3f8
2970793d85f2502929222ca7269fb427afee71c1
refs/heads/master
2020-03-22T00:33:19.686177
2018-09-18T13:17:48
2018-09-18T13:17:48
139,252,060
4
0
null
null
null
null
UTF-8
Python
false
false
1,730
py
# datafile: A B 0/1/2 # label: 0: A < B, 1: A == B, 2: A > B import os import random import argparse random.seed(0) parser = argparse.ArgumentParser() parser.add_argument('--mode', type=str, default='train') parser.add_argument('--N', type=int, default=140000) parser.add_argument('--margin', type=int, default=10) opt = parser.parse_args() def parse_age_label(fname, binranges): strlist = fname.split('_') age = int(strlist[0]) l = None for l in range(len(binranges)-1): if (age >= binranges[l]) and (age < binranges[l+1]): break return l def parse_age(fname): strlist = fname.split('_') age = int(strlist[0]) return age # root = '/media/ligong/Toshiba/Datasets/CACD/CACD_cropped2_400' mode = opt.mode src = '../sourcefiles/CACD_'+mode+'_10k.txt' N = opt.N with open(src, 'r') as f: fnames = f.readlines() fnames = [fname.rstrip('\n') for fname in fnames] def label_fn(a1, a2, m): if abs(a1-a2) <= m: return 1 elif a1 < a2: return 0 else: return 2 cnt = [0, 0, 0] random.shuffle(fnames) with open(mode+'_pairs_m%d_cacd_10k2.txt'%opt.margin, 'w') as f: for _ in range(N): # idx = _ % N # name1 = fnames[idx] # name2 = random.choice(fnames) # if random.random() < 0.5: # tmp = name1 # name1 = name2 # name2 = tmp ss = random.sample(fnames, 2) name1 = ss[0].rstrip('\n') name2 = ss[1].rstrip('\n') label = label_fn(parse_age(name1), parse_age(name2), opt.margin) cnt[label] += 1 f.write('%s %s %d\n' % (name1, name2, label)) w = [] for c in cnt: w.append(1.0 * sum(cnt) / c) print([x/sum(w) for x in w])
[ "hanligong@gmail.com" ]
hanligong@gmail.com
fcf5cdd7421b4f2532a2e661e5f029b817329d95
dd681dd7874c80c2804ca8d66cdbfdf2abec537e
/Python/venv/Lib/site-packages/tensorflow/keras/datasets/boston_housing/__init__.py
53ffc7b9cca8e7eac1826d4cf34ba9db26f68fff
[]
no_license
khaled147/Koneked
cbbaec78cf3828575e835445f45b9dd72c39d808
98bdc701a3d126c742e076ee3ad34719a0ac5309
refs/heads/main
2023-04-03T11:37:07.941179
2021-04-14T02:09:35
2021-04-14T02:09:35
345,202,202
2
0
null
null
null
null
UTF-8
Python
false
false
348
py
# This file is MACHINE GENERATED! Do not edit. # Generated by: tensorflow/python/tools/api/generator/create_python_api.py script. """Boston housing price regression dataset. """ from __future__ import print_function as _print_function import sys as _sys from tensorflow.python.keras.datasets.boston_housing import load_data del _print_function
[ "elmalawanykhaled@gmail.com" ]
elmalawanykhaled@gmail.com
8f53c74814241b9df893b923178de00b3e5b2f16
ec0fb2acbe70d3d7f399aea42038221298c8268e
/part010/ch05_shapely/sec6_interop/test_3_geo_inter_x_x.py
6d92bbb779c365957775521a98a907196adfb01c
[]
no_license
GAIMJKP/book_python_gis
fa09567337bfccd4ab968228d4890ec0538ada50
cd09be08df4cf4d3e06cf7c43d0b80cc76976a7e
refs/heads/master
2022-11-07T18:32:22.340481
2020-06-20T13:22:58
2020-06-20T13:22:58
null
0
0
null
null
null
null
UTF-8
Python
false
false
805
py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ############################################################################### from shapely.geometry import asShape d = {"type": "Point", "coordinates": (0.0, 0.0)} shape = asShape(d) shape.geom_type tuple(shape.coords) list(shape.coords) ############################################################################### class GeoThing(object): def __init__(self, d): self.__geo_interface__ = d ############################################################################### thing = GeoThing(d) shape = asShape(thing) shape.geom_type tuple(shape.coords) list(shape.coords) ############################################################################### from shapely.geometry import mapping thing = GeoThing(d) m = mapping(thing) type(m) m['type']
[ "bukun@osgeo.cn" ]
bukun@osgeo.cn
0134f050e7db3b58bc21acea96931a03d5ce5775
a26ae51a1d84249c31c58b90231b7ec23e1aa74d
/flask_app.py
e75e4e1d9083d00221068309ed9821d50809fb02
[]
no_license
Yaomingqing/Image-Super-Resolution
b5e975f08d9cec0d1ba71ec3489e388c6ef69a2a
631b2af81d012ff58c9d7a91f37e3e1d31377222
refs/heads/master
2021-08-10T13:05:44.662484
2017-11-12T15:58:48
2017-11-12T15:58:48
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,187
py
from keras.models import load_model from flask import Flask, request, render_template, flash, redirect, url_for from werkzeug.utils import secure_filename import models import os import tensorflow as tf upload_folder = 'data/' if not os.path.exists(upload_folder): os.makedirs(upload_folder) ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'bmp'} model = load_model('keras_models/RNSR_model.h5') with tf.device('/cpu:0'): m = models.ResNetSR(2) app = Flask(__name__) app.config['UPLOAD_FOLDER'] = upload_folder app.secret_key = 'WTF_I_already*Installed^%Open%&$CV' def allowed_file(filename): return '.' in filename and \ filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS @app.route('/', methods=['GET', 'POST']) def root(): if request.method == 'POST': # check if the post request has the file part if 'file' not in request.files: flash('No file part') return redirect(request.url) file = request.files['file'] # if user does not select file, browser also # submit a empty part without filename if file.filename == '': flash('No selected file') return redirect(request.url) if file and allowed_file(file.filename): filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) return redirect(url_for('uploaded_file', filename=filename)) return render_template('index.html', title='Image Super Resolution') @app.route('/uploaded_file/<string:filename>') def uploaded_file(filename): path = upload_folder + filename try: m.upscale(path, save_intermediate=False, mode="fast") ext = filename.rsplit('.', 1)[1] path = upload_folder + filename.rsplit('.', 1)[0] + "_scaled(2x)." + ext return redirect(url_for('image', filename=path)) except: flash("Image is too large !") return redirect('/') @app.route('/image/<filename>', methods=['POST']) def image(filename): return render_template('disp.html', image=filename) if __name__ == "__main__": app.run(port=8888)
[ "titu1994@gmail.com" ]
titu1994@gmail.com
12654f11056f73cda0eb1e3ff7d062af58f8d11c
90fb55320c81259cb199b9a8900e11b2ba63da4f
/232/gold.py
2b2c82b71ecab0bffd80f1f0592f28ec519fc32d
[]
no_license
pogross/bitesofpy
f9bd8ada790d56952026a938b1a34c20562fdd38
801f878f997544382e0d8650fa6b6b1b09fa5b81
refs/heads/master
2020-05-19T07:31:44.556896
2020-01-26T12:48:28
2020-01-26T12:48:28
184,899,394
1
1
null
null
null
null
UTF-8
Python
false
false
2,068
py
from itertools import tee from dataclasses import dataclass # https://pkgstore.datahub.io/core/gold-prices/annual_csv/data/343f626dd4f7bae813cfaac23fccd1bc/annual_csv.csv gold_prices = """ 1950-12,34.720 1951-12,34.660 1952-12,34.790 1953-12,34.850 1954-12,35.040 1955-12,34.970 1956-12,34.900 1957-12,34.990 1958-12,35.090 1959-12,35.050 1960-12,35.540 1961-12,35.150 1962-12,35.080 1963-12,35.080 1964-12,35.120 1965-12,35.130 1966-12,35.180 1967-12,35.190 1968-12,41.113 1969-12,35.189 1970-12,37.434 1971-12,43.455 1972-12,63.779 1973-12,106.236 1974-12,183.683 1975-12,139.279 1976-12,133.674 1977-12,160.480 1978-12,207.895 1979-12,463.666 1980-12,596.712 1981-12,410.119 1982-12,444.776 1983-12,388.060 1984-12,319.622 1985-12,321.985 1986-12,391.595 1987-12,487.079 1988-12,419.248 1989-12,409.655 1990-12,378.161 1991-12,361.875 1992-12,334.657 1993-12,383.243 1994-12,379.480 1995-12,387.445 1996-12,369.338 1997-12,288.776 1998-12,291.357 1999-12,283.743 2000-12,271.892 2001-12,275.992 2002-12,333.300 2003-12,407.674 2004-12,442.974 2005-12,509.423 2006-12,629.513 2007-12,803.618 2008-12,819.940 2009-12,1135.012 2010-12,1393.512 2011-12,1652.725 2012-12,1687.342 2013-12,1221.588 2014-12,1200.440 2015-12,1068.317 2016-12,1152.165 2017-12,1265.674 2018-12,1249.887 """ # noqa E501 @dataclass class GoldPrice: year: int price: float change: float = 0 def pairwise(iterable): a, b = tee(iterable) next(b, None) return zip(a, b) def years_gold_value_decreased(gold_prices: str = gold_prices) -> (int, int): """Analyze gold_prices returning a tuple of the year the gold price decreased the most and the year the gold price increased the most. """ prices = [ GoldPrice(year=int(entry.split(",")[0][:4]), price=float(entry.split(",")[1])) for entry in " ".join(gold_prices.splitlines()).strip().split(" ") ] for first, second in pairwise(prices): second.change = first.price - second.price prices.sort(key=lambda x: x.change) return prices[-1].year, prices[0].year
[ "p.gross@tu-bs.de" ]
p.gross@tu-bs.de
157d1915be5de8fd962c5458f9608cfa50c53211
35b58dedc97622b1973456d907ede6ab86c0d966
/Test/2020年6月20日/selenium爬取动态加载数据.py
75b922d51f77c8fd0aec94d57a25352626e16274
[]
no_license
GithubLucasSong/PythonProject
7bb2bcc8af2de725b2ed9cc5bfedfd64a9a56635
e3602b4cb8af9391c6dbeaebb845829ffb7ab15f
refs/heads/master
2022-11-23T05:32:44.622532
2020-07-24T08:27:12
2020-07-24T08:27:12
282,165,132
0
0
null
null
null
null
UTF-8
Python
false
false
710
py
from selenium import webdriver from lxml import etree from time import sleep bro = webdriver.Chrome(executable_path='chromedriver') # bro = webdriver.Edge(executable_path='./msedgedriver') bro.get('http://125.35.6.84:81/xk/') sleep(1) # 获取页面源码内容 page_text = bro.page_source all_page_text = [page_text] for i in range(5): next_page_btn = bro.find_element_by_xpath('//*[@id="pageIto_next"]') next_page_btn.click() sleep(1) all_page_text.append(bro.page_source) for page_text in all_page_text: tree = etree.HTML(page_text) li_list = tree.xpath('//*[@id="gzlist"]/li') for li in li_list: title = li.xpath('./dl/@title')[0] print(title) bro.quit()
[ "1433880147@qq.com" ]
1433880147@qq.com
abfcd32e8c71bff43c8a98c626c2fe7d9afc2b6c
8fc7635b84b42e61b7efb9eaf7215394b5b5790a
/aliennor-backend copy/aliennorDjangoBackend/aliennorDjangoBackend/settings.py
cb042666939a3793989e062b84e22ccf1baf9c76
[]
no_license
phamcong/aliennor-platform
f1e8470aab7ed634859e071f6028931f576ddf3e
e1d71532426ac9414d2158d50ee34c32257618f0
refs/heads/master
2021-05-14T17:08:08.629564
2018-02-17T23:35:07
2018-02-17T23:35:07
116,038,495
0
0
null
null
null
null
UTF-8
Python
false
false
4,851
py
""" Django settings for aliennorDjangoBackend project. Generated by 'django-admin startproject' using Django 2.0. For more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ """ import os import base64 import sys from urllib import parse # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'sqqh)7k)(q1jl7t(1^em(_1c*!2_tf(d66s79vhn_*qd21gx&_' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False if 'DATABASE_URL' in os.environ else True ALLOWED_HOSTS = [ 'localhost' ] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'ecocases', 'rest_framework', 'crispy_forms', 'tinymce', 'corsheaders', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', # 'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'aliennorDjangoBackend.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'aliennorDjangoBackend.wsgi.application' # Database # https://docs.djangoproject.com/en/2.0/ref/settings/#databases # DATABASES = { # 'default': { # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), # } # } # Setup for MySQL connection DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'aliennor', 'USER': 'root', 'PASSWORD': 'root', 'HOST': '127.0.0.1' } } # Password validation # https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.0/howto/static-files/ STATIC_URL = '/static/' CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True CSRF_COOKIE_SECURE = False CSRF_TRUSTED_ORIGINS = ['django-angular2-movies.firebaseapp.com'] # custom settings JWT_SECRET = base64.b64encode(b'ScaredCherriesEatSurelySimpleVulcansParticipateIntensely') # heroku database settings # Register database schemes in URLs. parse.uses_netloc.append('mysql') try: # Check to make sure DATABASES is set in settings.py file. # If not default to {} if 'DATABASES' not in locals(): DATABASES = {} if 'DATABASE_URL' in os.environ: url = parse.urlparse(os.environ['DATABASE_URL']) # Ensure default database exists. DATABASES['default'] = DATABASES.get('default', {}) # Update with environment configuration. DATABASES['default'].update({ 'NAME': url.path[1:], 'USER': url.username, 'PASSWORD': url.password, 'HOST': url.hostname, 'PORT': url.port, }) if url.scheme == 'mysql': DATABASES['default']['ENGINE'] = 'django.db.backends.mysql' except Exception: print('Unexpected error:', sys.exc_info()) CORS_ORIGIN_WHITELIST = ( 'localhost:3000', 'localhost:4200' )
[ "ccuong.ph@gmail.com" ]
ccuong.ph@gmail.com
5b1f9fa94e913fb8469bb608f7aff55cd882ab1f
c227735e87fe9da845e81c994f5a0c4cc410abf9
/Python/ReverseString.py
378dd1708951b66f59c8040961793d275e8f5106
[ "MIT" ]
permissive
ani03sha/potd
816d5a25c9658eb38dda46352d7518d999a807f2
05ca25039c5462b68dae9d83e856dd4c66e7ab63
refs/heads/main
2023-02-02T18:14:43.273677
2020-12-18T15:31:06
2020-12-18T15:31:06
315,034,076
0
0
null
null
null
null
UTF-8
Python
false
false
633
py
""" Given a string, reverse all of its characters and return the resulting string. """ from typing import List class ReverseString: def reverseString(self, s: List[str]) -> List: # Reversed string reversedString = "" # Loop for all characters in the string for i in s: reversedString = i + reversedString return reversedString if __name__ == "__main__": r = ReverseString() print(r.reverseString("Cat")) print(r.reverseString("Program of the day")) print(r.reverseString("red quark")) print(r.reverseString("level")) print(r.reverseString(""))
[ "anirudh03sharma@gmail.com" ]
anirudh03sharma@gmail.com
f374671883af08c4b50ac4f41ea90214c848b1a7
c380976b7c59dadaccabacf6b541124c967d2b5a
/.history/src/data/data_20191018141356.py
20f7b6d5858a6e20347e611529877edb27123cb8
[ "MIT" ]
permissive
bkraft4257/kaggle_titanic
b83603563b4a3c995b631e8142fe72e1730a0e2e
f29ea1773773109a867278c001dbd21a9f7b21dd
refs/heads/master
2020-08-17T12:45:28.653402
2019-11-15T16:20:04
2019-11-15T16:20:04
215,667,760
0
0
null
null
null
null
UTF-8
Python
false
false
3,042
py
import pandas as pd from typing import Union from pathlib import Path from nameparser import HumanName class ExtractData: title_translator = { "Mlle.": "Mrs.", "Mme.": "Mrs.", "Sir.": "Mr.", "Ms.": "Mrs.", "": "Mr.", "Col.": "Mr.", "Capt.": "Mr.", "Lady.": "Mrs.", "the Countess. of": "Mrs.", } def __init__(self, filename: Union[str, Path], drop_columns=None): # """Extract Training Data from file or Path # Arguments: # filename {[str]} -- Filename of CSV data file containing data. # drop_columns -- Columns in dataframe that should be dropped. # """ if drop_columns is None: drop_columns = ["age", "cabin", "name", "ticket"] self.filename = filename self.drop_columns = drop_columns self.all_label_columns = ["survived"] self.all_feature_columns = [ "pclass", "name", "sex", "age", "sibsp", "parch", "ticket", "fare", "cabin", "embarked", ] self.Xy_raw = None self.Xy = None self.extract_raw() self.Xy = self.Xy_raw.copy() self.extract_title() self.extract_last_name() def extract_raw(self): """ Extracts data from a CSV file. Returns: pd.DataFrame -- [description] """ Xy_raw = pd.read_csv(self.filename) Xy_raw.columns = Xy_raw.columns.str.lower().str.replace(" ", "_") Xy_raw = Xy_raw.rename(columns={'age':'age_known'}) Xy_raw["pclass"] = Xy_raw["pclass"].astype("category") self.Xy_raw = Xy_raw.set_index("passengerid") def extract_cabin_prefix(self): Xy['cabin_number'] = Xy.ticket.str.extract('(\d+)$') Xy['cabin_prefix'] = Xy.ticket.str.extract('^(.+) ') def extract_title(self): """[summary] """ self.Xy["title"] = ( self.Xy.name.apply(lambda x: HumanName(x).title) .replace(self.title_translator) .replace({"\.": ""}, regex=True) ) def extract_last_name(self): self.Xy["last_name"] = self.Xy.name.apply(lambda x: HumanName(x).last) def clean(self,): """Clean data to remove missing data and "unnecessary" features. Arguments: in_raw_df {pd.DataFrame} -- Dataframe containing all columns and rows Kaggle Titanic Training Data set """ self.Xy = self.Xy_raw.drop(self.drop_columns, axis=1) def estimate_age(in_df, groupby=['sex','title']): Xy_age_estimate = in_df.groupby(['sex','title']).age_known.mean().to_frame().round(1) Xy_age_estimate = Xy_age_estimate.rename(columns ={'age_known':'age_estimate'}) out_df = in_df.reset_index().merge(Xy_age_estimate, on=['sex', 'title']) out_df['age'] = out_df['age_known'].fillna(out_df['age_estimate']) return out_df
[ "bob.kraft@infiniteleap.net" ]
bob.kraft@infiniteleap.net
75201fde37f7cebb6c0b276f4e6f89c588af812a
238e46a903cf7fac4f83fa8681094bf3c417d22d
/VTK/vtk_7.1.1_x64_Debug/lib/python2.7/site-packages/twisted/cred/portal.py
23e48739cfb924a7a71886e884eb010098d27305
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
baojunli/FastCAE
da1277f90e584084d461590a3699b941d8c4030b
a3f99f6402da564df87fcef30674ce5f44379962
refs/heads/master
2023-02-25T20:25:31.815729
2021-02-01T03:17:33
2021-02-01T03:17:33
268,390,180
1
0
BSD-3-Clause
2020-06-01T00:39:31
2020-06-01T00:39:31
null
UTF-8
Python
false
false
5,460
py
# -*- test-case-name: twisted.test.test_newcred -*- # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ The point of integration of application and authentication. """ from twisted.internet import defer from twisted.internet.defer import maybeDeferred from twisted.python import failure, reflect from twisted.cred import error from zope.interface import providedBy, Interface class IRealm(Interface): """ The realm connects application-specific objects to the authentication system. """ def requestAvatar(avatarId, mind, *interfaces): """ Return avatar which provides one of the given interfaces. @param avatarId: a string that identifies an avatar, as returned by L{ICredentialsChecker.requestAvatarId<twisted.cred.checkers.ICredentialsChecker.requestAvatarId>} (via a Deferred). Alternatively, it may be C{twisted.cred.checkers.ANONYMOUS}. @param mind: usually None. See the description of mind in L{Portal.login}. @param interfaces: the interface(s) the returned avatar should implement, e.g. C{IMailAccount}. See the description of L{Portal.login}. @returns: a deferred which will fire a tuple of (interface, avatarAspect, logout), or the tuple itself. The interface will be one of the interfaces passed in the 'interfaces' argument. The 'avatarAspect' will implement that interface. The 'logout' object is a callable which will detach the mind from the avatar. """ class Portal: """ A mediator between clients and a realm. A portal is associated with one Realm and zero or more credentials checkers. When a login is attempted, the portal finds the appropriate credentials checker for the credentials given, invokes it, and if the credentials are valid, retrieves the appropriate avatar from the Realm. This class is not intended to be subclassed. Customization should be done in the realm object and in the credentials checker objects. """ def __init__(self, realm, checkers=()): """ Create a Portal to a L{IRealm}. """ self.realm = realm self.checkers = {} for checker in checkers: self.registerChecker(checker) def listCredentialsInterfaces(self): """ Return list of credentials interfaces that can be used to login. """ return self.checkers.keys() def registerChecker(self, checker, *credentialInterfaces): if not credentialInterfaces: credentialInterfaces = checker.credentialInterfaces for credentialInterface in credentialInterfaces: self.checkers[credentialInterface] = checker def login(self, credentials, mind, *interfaces): """ @param credentials: an implementor of L{twisted.cred.credentials.ICredentials} @param mind: an object which implements a client-side interface for your particular realm. In many cases, this may be None, so if the word 'mind' confuses you, just ignore it. @param interfaces: list of interfaces for the perspective that the mind wishes to attach to. Usually, this will be only one interface, for example IMailAccount. For highly dynamic protocols, however, this may be a list like (IMailAccount, IUserChooser, IServiceInfo). To expand: if we are speaking to the system over IMAP, any information that will be relayed to the user MUST be returned as an IMailAccount implementor; IMAP clients would not be able to understand anything else. Any information about unusual status would have to be relayed as a single mail message in an otherwise-empty mailbox. However, in a web-based mail system, or a PB-based client, the ``mind'' object inside the web server (implemented with a dynamic page-viewing mechanism such as a Twisted Web Resource) or on the user's client program may be intelligent enough to respond to several ``server''-side interfaces. @return: A deferred which will fire a tuple of (interface, avatarAspect, logout). The interface will be one of the interfaces passed in the 'interfaces' argument. The 'avatarAspect' will implement that interface. The 'logout' object is a callable which will detach the mind from the avatar. It must be called when the user has conceptually disconnected from the service. Although in some cases this will not be in connectionLost (such as in a web-based session), it will always be at the end of a user's interactive session. """ for i in self.checkers: if i.providedBy(credentials): return maybeDeferred(self.checkers[i].requestAvatarId, credentials ).addCallback(self.realm.requestAvatar, mind, *interfaces ) ifac = providedBy(credentials) return defer.fail(failure.Failure(error.UnhandledCredentials( "No checker for %s" % ', '.join(map(reflect.qual, ifac)))))
[ "l”ibaojunqd@foxmail.com“" ]
l”ibaojunqd@foxmail.com“
9050b0975c3054ac27ea2a22854e52f9441d1b2b
5a16e8cec8cc3900096dd9d6914482f63e81b01f
/conf/settings.py
add336da760b26daeb00f9e74195126b40bd040f
[]
no_license
chenrun666/FR-
8c3f8181781274e2b895c21c95c9ee731dd3f5ce
5614c2ca469f2ac9529d83b902ce3411416f13c3
refs/heads/master
2020-04-22T19:58:36.785285
2019-02-14T02:58:36
2019-02-14T02:58:36
170,626,214
0
0
null
null
null
null
UTF-8
Python
false
false
1,327
py
# 测试环境 TEST = True CHOOSESITE = False # 回填结果 result = { "accountPassword":"", "accountType":"", "accountUsername":"", "cardName": "", "cardNumber": "", "checkStatus": True, "clientType": "",# 跑单的客户端码 "createTaskStatus": True, "linkEmail": "", "linkEmailPassword": "", "linkPhone": "", "machineCode": "58.57.62.229:20181",# 跑单客户端ip "nameList": [],# 如果支持乘客分开出,nameList里放本次跑单成功的乘客姓名,单个也是集合 "payTaskId": 0, "pnr": "ZTY2TG",# 跑单成功的pnr "price": 0.00, # 支付的机票含税总价 "baggagePrice":0.00,# 支付行李总价 "sourceCur": "CNY", "errorMessage":"", "status": 0, # 350 保留成功,301 保留失败, 450 支付成功 ,401 支付失败 "targetCur": "MYR", "promo":"使用的优惠码", "creditEmail":"信用账号邮箱", "creditEmailCost":"信用账号花费", } bookStatus = { "BookingFail" : 301, #301, "预定失败" "PriceVerifyFail" : 340, #340, "跑单失败,执行下一条规则" "BookingSuccess" : 350, #350, "预定成功" "PayFail" : 401, #401, "支付失败" "PayFailAfterSubmitCard" : 440, #440, "提交卡号后失败" "PaySuccess" : 450 #450, "支付成功" }
[ "17610780919@163.com" ]
17610780919@163.com
5b94d7cb3c951405797f09f7785cf0ac70ee2123
07c75f8717683b9c84864c446a460681150fb6a9
/back_cursor/S-scrapy/zhilianspider2/zhilianspider2/settings.py
76979aa5a98fe2c2624dddecb681be245fbf0fda
[]
no_license
laomu/py_1709
987d9307d9025001bd4386381899eb3778f9ccd6
80630e6ac3ed348a2a6445e90754bb6198cfe65a
refs/heads/master
2021-05-11T09:56:45.382526
2018-01-19T07:08:00
2018-01-19T07:08:00
118,088,974
0
0
null
null
null
null
UTF-8
Python
false
false
3,160
py
# -*- coding: utf-8 -*- # Scrapy settings for zhilianspider2 project # # For simplicity, this file contains only settings considered important or # commonly used. You can find more settings consulting the documentation: # # https://doc.scrapy.org/en/latest/topics/settings.html # https://doc.scrapy.org/en/latest/topics/downloader-middleware.html # https://doc.scrapy.org/en/latest/topics/spider-middleware.html BOT_NAME = 'zhilianspider2' SPIDER_MODULES = ['zhilianspider2.spiders'] NEWSPIDER_MODULE = 'zhilianspider2.spiders' # Crawl responsibly by identifying yourself (and your website) on the user-agent #USER_AGENT = 'zhilianspider2 (+http://www.yourdomain.com)' # Obey robots.txt rules ROBOTSTXT_OBEY = True # Configure maximum concurrent requests performed by Scrapy (default: 16) #CONCURRENT_REQUESTS = 32 # Configure a delay for requests for the same website (default: 0) # See https://doc.scrapy.org/en/latest/topics/settings.html#download-delay # See also autothrottle settings and docs #DOWNLOAD_DELAY = 3 # The download delay setting will honor only one of: #CONCURRENT_REQUESTS_PER_DOMAIN = 16 #CONCURRENT_REQUESTS_PER_IP = 16 # Disable cookies (enabled by default) #COOKIES_ENABLED = False # Disable Telnet Console (enabled by default) #TELNETCONSOLE_ENABLED = False # Override the default request headers: #DEFAULT_REQUEST_HEADERS = { # 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', # 'Accept-Language': 'en', #} # Enable or disable spider middlewares # See https://doc.scrapy.org/en/latest/topics/spider-middleware.html #SPIDER_MIDDLEWARES = { # 'zhilianspider2.middlewares.Zhilianspider2SpiderMiddleware': 543, #} # Enable or disable downloader middlewares # See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html #DOWNLOADER_MIDDLEWARES = { # 'zhilianspider2.middlewares.Zhilianspider2DownloaderMiddleware': 543, #} # Enable or disable extensions # See https://doc.scrapy.org/en/latest/topics/extensions.html #EXTENSIONS = { # 'scrapy.extensions.telnet.TelnetConsole': None, #} # Configure item pipelines # See https://doc.scrapy.org/en/latest/topics/item-pipeline.html #ITEM_PIPELINES = { # 'zhilianspider2.pipelines.Zhilianspider2Pipeline': 300, #} # Enable and configure the AutoThrottle extension (disabled by default) # See https://doc.scrapy.org/en/latest/topics/autothrottle.html #AUTOTHROTTLE_ENABLED = True # The initial download delay #AUTOTHROTTLE_START_DELAY = 5 # The maximum download delay to be set in case of high latencies #AUTOTHROTTLE_MAX_DELAY = 60 # The average number of requests Scrapy should be sending in parallel to # each remote server #AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0 # Enable showing throttling stats for every response received: #AUTOTHROTTLE_DEBUG = False # Enable and configure HTTP caching (disabled by default) # See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings #HTTPCACHE_ENABLED = True #HTTPCACHE_EXPIRATION_SECS = 0 #HTTPCACHE_DIR = 'httpcache' #HTTPCACHE_IGNORE_HTTP_CODES = [] #HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'
[ "1007821300@qq.com" ]
1007821300@qq.com
307f587d31cc07e174370678eb26c5487377e342
157cf9d7327499d86162eb0170684f4b02a9804a
/scrapylib/proxy.py
8f19e099c4210fe2780818d83ace596d2a39f9ed
[]
no_license
alepharchives/scrapylib
8f59f6f1abe075adb49fbd28a6f575851cab3099
9d84cca95952a19d85c3229df7105502649d99e0
refs/heads/master
2021-01-24T01:58:45.568968
2012-11-07T20:13:38
2012-11-07T20:13:38
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,322
py
import base64 from urllib import unquote from urllib2 import _parse_proxy from urlparse import urlunparse from scrapy.conf import settings class SelectiveProxyMiddleware(object): """A middleware to enable http proxy to selected spiders only. Settings: HTTP_PROXY -- proxy uri. e.g.: http://user:pass@proxy.host:port PROXY_SPIDERS -- all requests from these spiders will be routed through the proxy """ def __init__(self): self.proxy = self.parse_proxy(settings.get('HTTP_PROXY'), 'http') self.proxy_spiders = set(settings.getlist('PROXY_SPIDERS', [])) def parse_proxy(self, url, orig_type): proxy_type, user, password, hostport = _parse_proxy(url) proxy_url = urlunparse((proxy_type or orig_type, hostport, '', '', '', '')) if user and password: user_pass = '%s:%s' % (unquote(user), unquote(password)) creds = base64.b64encode(user_pass).strip() else: creds = None return creds, proxy_url def process_request(self, request, spider): if spider.name in self.proxy_spiders: creds, proxy = self.proxy request.meta['proxy'] = proxy if creds: request.headers['Proxy-Authorization'] = 'Basic ' + creds
[ "pablo@pablohoffman.com" ]
pablo@pablohoffman.com
3baf8e9914792b2d398347aa85e55b038c491263
89fea7d230e282b3bd3cf2d7db1b003e572e6fa8
/genconf/views.py
34042b1fcf0916e223d81ec77069c612f784a390
[]
no_license
madron/genconf
45abaf66010944e2df9ca1bdaa32328267c62584
99c7d82d55b5075299940adfeaff903b0c70bc8b
refs/heads/master
2020-12-04T11:51:16.029577
2016-01-15T09:35:01
2016-01-15T09:35:01
231,754,213
0
0
null
null
null
null
UTF-8
Python
false
false
224
py
from django.views.generic import DetailView from . import models class ConfigurationView(DetailView): http_method_names = ['get'] model = models.Router template_name = 'genconf/configuration/configuration.txt'
[ "massimiliano.ravelli@gmail.com" ]
massimiliano.ravelli@gmail.com
78f02da277f4298af340f876baf26f6f0f8ce38a
9b2255e0a474555d8a4d90f586e280d40224a181
/apps/common/urls.py
b60c575f1aeced024158b7e6f3fbde0719d8e8eb
[]
no_license
rogeriofalcone/redirector
85f496f7c3a3c755b2d9f86f90d25ace783842e4
8255be80ce4e3245317864dcc580a1ef68a7c244
refs/heads/master
2020-04-08T07:03:19.053680
2012-08-12T19:13:35
2012-08-12T19:13:35
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,259
py
from django.conf.urls.defaults import patterns, url from django.views.generic.simple import direct_to_template from django.conf import settings urlpatterns = patterns('common.views', url(r'^about/$', direct_to_template, {'template': 'about.html'}, 'about_view'), url(r'^changelog/$', 'changelog_view', (), 'changelog_view'), url(r'^license/$', 'license_view', (), 'license_view'), url(r'^password/change/done/$', 'password_change_done', (), name='password_change_done'), url(r'^object/multiple/action/$', 'multi_object_action_view', (), name='multi_object_action_view'), url(r'^user/$', 'current_user_details', (), 'current_user_details'), url(r'^user/edit/$', 'current_user_edit', (), 'current_user_edit'), url(r'^login/$', 'login_view', (), name='login_view'), ) urlpatterns += patterns('', url(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': '/top_redirect/'}, name='logout_view'), url(r'^password/change/$', 'django.contrib.auth.views.password_change', {'template_name': 'password_change_form.html', 'post_change_redirect': '/password/change/done/'}, name='password_change_view'), url(r'^password/reset/$', 'django.contrib.auth.views.password_reset', {'email_template_name': 'password_reset_email.html', 'template_name': 'password_reset_form.html', 'post_reset_redirect': '/password/reset/done'}, name='password_reset_view'), url(r'^password/reset/confirm/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/$', 'django.contrib.auth.views.password_reset_confirm', {'template_name': 'password_reset_confirm.html', 'post_reset_redirect': '/password/reset/complete/'}, name='password_reset_confirm_view'), url(r'^password/reset/complete/$', 'django.contrib.auth.views.password_reset_complete', {'template_name': 'password_reset_complete.html'}, name='password_reset_complete_view'), url(r'^password/reset/done/$', 'django.contrib.auth.views.password_reset_done', {'template_name': 'password_reset_done.html'}, name='password_reset_done_view'), # (r'^favicon\.ico$', 'django.views.generic.simple.redirect_to', {'url': '%s%s' % (settings.STATIC_URL, 'images/favicon.ico')}), ) urlpatterns += patterns('', url(r'^set_language/$', 'django.views.i18n.set_language', name='set_language'), )
[ "Roberto.Rosario.Gonzalez@gmail.com" ]
Roberto.Rosario.Gonzalez@gmail.com
0b66f6ab3a183691b0308c29dabfc36e889109a5
997c82f5d9684945fb2f5d5481dc4d251a93755f
/famapy/core/operations/products.py
70f4b1107b28b43b64401baecdbb3814a6c47f11
[]
no_license
jmhorcas/famapy-aafms
a6e45b5fff2c820037daf95151df5bc6895b1611
bcc80f7061bed4d6bfd536f9d53cf195bffa01e6
refs/heads/main
2023-08-24T05:51:47.337325
2021-10-15T10:18:20
2021-10-15T10:18:20
389,559,981
1
0
null
null
null
null
UTF-8
Python
false
false
270
py
from abc import abstractmethod from typing import Any from famapy.core.operations import Operation class Products(Operation): @abstractmethod def __init__(self) -> None: pass @abstractmethod def get_products(self) -> list[Any]: pass
[ "jhorcas@us.es" ]
jhorcas@us.es
8fd4193624ed4b3ec5193cdc4ac863af4ddabfdf
50b77b527b95659c6ac8484a1091a70b4ad25d73
/2019/19/aoc19.py
fdfbb0fd8a49953dc81279bd988da641306ef860
[]
no_license
cjuub/advent-of-code
d3a4569dd0b7bf7e10dc6a76a1ffe569df4e93a2
bb92d8ae96cde8c3e57abed26019e692fa6e168f
refs/heads/master
2023-01-10T00:32:56.847184
2023-01-02T20:46:57
2023-01-02T20:46:57
160,243,333
0
0
null
null
null
null
UTF-8
Python
false
false
5,337
py
#!/usr/bin/env python3 from typing import List class IntCodeComputer: OP_ADD = 1 OP_MUL = 2 OP_LOAD = 3 OP_STORE = 4 OP_JUMP_IF_TRUE = 5 OP_JUMP_IF_FALSE = 6 OP_LESS_THAN = 7 OP_EQUALS = 8 OP_REL_BASE = 9 OP_HALT = 99 class HaltException(Exception): pass def __init__(self, memory: List[int]): self._memory = memory[:] + [0] * 100000 self._pc = 0 self._input = [] self._inputs_read = 0 self._output = 0 self._rel_base = 0 self._instructions = {IntCodeComputer.OP_ADD: self._add, IntCodeComputer.OP_MUL: self._mul, IntCodeComputer.OP_LOAD: self._load, IntCodeComputer.OP_STORE: self._store, IntCodeComputer.OP_JUMP_IF_TRUE: self._jump_if_true, IntCodeComputer.OP_JUMP_IF_FALSE: self._jump_if_false, IntCodeComputer.OP_LESS_THAN: self._less_than, IntCodeComputer.OP_EQUALS: self._equals, IntCodeComputer.OP_REL_BASE: self._change_rel_base} def _add(self, op1, op2, res): self._memory[res] = op1 + op2 self._pc += 4 def _mul(self, op1, op2, res): self._memory[res] = op1 * op2 self._pc += 4 def _load(self, op1, op2, res): self._memory[op1] = self._input[self._inputs_read] self._inputs_read += 1 self._pc += 2 def _store(self, op1, op2, res): self._output = op1 self._pc += 2 return self._output def _jump_if_true(self, op1, op2, res): if op1 != 0: self._pc = op2 else: self._pc += 3 def _jump_if_false(self, op1, op2, res): if op1 == 0: self._pc = op2 else: self._pc += 3 def _less_than(self, op1, op2, res): if op1 < op2: self._memory[res] = 1 else: self._memory[res] = 0 self._pc += 4 def _equals(self, op1, op2, res): if op1 == op2: self._memory[res] = 1 else: self._memory[res] = 0 self._pc += 4 def _change_rel_base(self, op1, op2, res): self._rel_base += op1 self._pc += 2 def execute(self) -> int: while True: op_code_str = str(self._memory[self._pc]).rjust(5, '0') op_code = int(op_code_str[-2:]) op1_mode = int(op_code_str[2]) op2_mode = int(op_code_str[1]) op3_mode = int(op_code_str[0]) if op_code == IntCodeComputer.OP_HALT: raise IntCodeComputer.HaltException(self._output) if op1_mode == 0: # Only instruction with write on op1 if op_code == IntCodeComputer.OP_LOAD: op1 = self._memory[self._pc + 1] else: op1 = self._memory[self._memory[self._pc + 1]] elif op1_mode == 1: op1 = self._memory[self._pc + 1] else: if op_code == IntCodeComputer.OP_LOAD: op1 = self._rel_base + self._memory[self._pc + 1] else: op1 = self._memory[self._rel_base + self._memory[self._pc + 1]] if op2_mode == 0: op2 = self._memory[self._memory[self._pc + 2]] elif op2_mode == 1: op2 = self._memory[self._pc + 2] else: op2 = self._memory[self._rel_base + self._memory[self._pc + 2]] if op3_mode == 0: res = self._memory[self._pc + 3] elif op3_mode == 1: res = self._pc + 3 else: res = self._rel_base + self._memory[self._pc + 3] ret = self._instructions[op_code](op1, op2, res) if ret is not None: return int(ret) def set_input(self, value): self._input = value with open('input.txt') as fp: code = list(map(int, fp.readline().strip().split(","))) grid = [['' for y3 in range(100)] for x3 in range(100)] cnt = 0 for y2 in range(50): for x2 in range(50): x = 0 y = 0 comp = IntCodeComputer(code) comp.set_input([x2, y2]) try: while True: out = comp.execute() grid[y2][x2] = out if out == 1: cnt += 1 except IntCodeComputer.HaltException: pass for y2 in range(50): for x2 in range(50): print(grid[y2][x2], end='') print() print('Part 1: ' + str(cnt)) grid = [['.' for y3 in range(200)] for x3 in range(100)] for y2 in range(100): for x2 in range(200): comp = IntCodeComputer(code) # lol, found it by trial and error and manual binary search comp.set_input([x2 + 650, y2 + 1097]) try: while True: out = comp.execute() if out == 1: grid[y2][x2] = '#' except IntCodeComputer.HaltException: pass for y2 in range(100): for x2 in range(200): print(grid[y2][x2], end='') print() print('Part 2: ' + str((650 + 17) * 10000 + 1097))
[ "cjuuub@gmail.com" ]
cjuuub@gmail.com
7f6bd6db1950bb212336a9d800d41cf1c6515222
27556d221db5669fd74dd57344ded4cf2942c0ae
/contact/views.py
b49b69a35b79e8d1d331c3b66fb8e75ee39ac4b8
[]
no_license
edzen12/sendEmail
60a9dce424ec80c41b68b1092a55259154c4e080
eb2a8feb609d9034695674a94308ed70ea600bcd
refs/heads/master
2023-08-25T03:36:38.538297
2021-10-12T08:45:11
2021-10-12T08:45:11
416,253,922
0
1
null
null
null
null
UTF-8
Python
false
false
277
py
from rest_framework import viewsets, mixins from contact.models import Person from contact.serializers import PersonSerializer class PersonViewSet(mixins.CreateModelMixin, viewsets.GenericViewSet): queryset = Person.objects.all() serializer_class = PersonSerializer
[ "oichiev.edzen@gmail.com" ]
oichiev.edzen@gmail.com
7a05fadb04f7095039de7c80f514ced4dad3eeb8
8033688716c7b120d8105fb98152467c515d7d03
/makeScalingFunctionPlot.py
edde28e4600681d9c21512f107d64dfddf7b3b24
[]
no_license
jonathon-langford/EFT-Fitter
68214a8f46e9817dc7add99d16e3260ae5d1617d
1cebdef80497bb66ac2d262e2347c4d8100f94b8
refs/heads/master
2023-05-20T06:51:21.341971
2021-02-12T19:35:12
2021-02-12T19:35:12
338,414,103
0
2
null
null
null
null
UTF-8
Python
false
false
7,914
py
import os, sys import json import re from optparse import OptionParser from collections import OrderedDict as od from importlib import import_module import pickle import ROOT import numpy as np def get_options(): parser = OptionParser() parser.add_option('--pois', dest='pois', default='params.HEL', help="Name of json file storing pois") parser.add_option('--functions', dest='functions', default='functions.HEL_STXS', help="Name of json file storing functions") parser.add_option('--inputs', dest='inputs', default='', help="Comma separated list of input files") parser.add_option("--translateBins", dest="translateBins", default=None, help="Translate STXS bins") return parser.parse_args() (opt,args) = get_options() # Functions for translations def Translate(name, ndict): return ndict[name] if name in ndict else name def LoadTranslations(jsonfilename): with open(jsonfilename) as jsonfile: return json.load(jsonfile) translateBins = {} if opt.translateBins is None else LoadTranslations(opt.translateBins) # Load parameters of interest pois = import_module(opt.pois).pois # Load functions functions = import_module(opt.functions).functions # Load input measurements inputs = [] for i in opt.inputs.split(","): _cfg = import_module(i) _input = od() _input['name'] = _cfg.name _input['X'] = _cfg.X _input['rho'] = _cfg.rho inputs.append(_input) from tools.fitter import * fit = fitter(pois,functions,inputs,False) #stxs_bins = ['ttH'] stxs_bins = ['ZH_lep_PTV_0_75','ZH_lep_PTV_75_150','ZH_lep_PTV_150_250_0J','ZH_lep_PTV_150_250_GE1J','ZH_lep_PTV_GT250','ZH_lep'] scaling = od() for stxs_bin in stxs_bins: scaling[stxs_bin] = od() for poi in pois.keys(): scaling[stxs_bin][poi] = od() # Quadratic fit.setLinearOnly(False) for poi in pois.keys(): scaling[stxs_bin][poi]['quad'] = od() c, mu = fit.scaling1D(poi,stxs_bin,npoints=1000) scaling[stxs_bin][poi]['quad']['c'] = c scaling[stxs_bin][poi]['quad']['mu'] = mu # Linear fit.setLinearOnly() for poi in pois.keys(): scaling[stxs_bin][poi]['lin'] = od() c,mu = fit.scaling1D(poi,stxs_bin,npoints=1000) scaling[stxs_bin][poi]['lin']['c'] = c scaling[stxs_bin][poi]['lin']['mu'] = mu # Mage graphs grs = od() for stxs_bin in stxs_bins: for poi in pois.keys(): grs['%s_vs_%s_quad'%(stxs_bin,poi)] = ROOT.TGraph() grs['%s_vs_%s_lin'%(stxs_bin,poi)] = ROOT.TGraph() for i in range(len(scaling[stxs_bin][poi]['quad']['c'])): grs['%s_vs_%s_quad'%(stxs_bin,poi)].SetPoint( grs['%s_vs_%s_quad'%(stxs_bin,poi)].GetN(),scaling[stxs_bin][poi]['quad']['c'][i], scaling[stxs_bin][poi]['quad']['mu'][i] ) for i in range(len(scaling[stxs_bin][poi]['lin']['c'])): grs['%s_vs_%s_lin'%(stxs_bin,poi)].SetPoint( grs['%s_vs_%s_lin'%(stxs_bin,poi)].GetN(),scaling[stxs_bin][poi]['lin']['c'][i], scaling[stxs_bin][poi]['lin']['mu'][i] ) # Make plot styleMap = od() styleMap['quad'] = {'LineWidth':3,'LineStyle':1,'MarkerSize':0} styleMap['quad_dummy'] = {'LineWidth':3,'LineStyle':1,'MarkerSize':0} styleMap['lin'] = {'LineWidth':2, 'LineStyle':2,'MarkerSize':0} styleMap['lin_dummy'] = {'LineColor':12, 'LineWidth':2, 'LineStyle':2,'MarkerSize':0} #styleMap['lin_dummy'] = {'LineColor':ROOT.kMagenta-7, 'LineWidth':2, 'LineStyle':2,'MarkerSize':0} colorMap = od() colorMap['ZH_lep'] = {'LineColor':ROOT.kRed-4,'MarkerColor':ROOT.kRed-4} colorMap['ZH_lep_PTV_0_75'] = {'LineColor':ROOT.kGreen-8,'MarkerColor':ROOT.kGreen-8} colorMap['ZH_lep_PTV_75_150'] = {'LineColor':ROOT.kGreen-7,'MarkerColor':ROOT.kGreen-7} colorMap['ZH_lep_PTV_150_250_0J'] = {'LineColor':ROOT.kGreen+1,'MarkerColor':ROOT.kGreen+1} colorMap['ZH_lep_PTV_150_250_GE1J'] = {'LineColor':ROOT.kGreen+3,'MarkerColor':ROOT.kGreen+3} colorMap['ZH_lep_PTV_GT250'] = {'LineColor':ROOT.kBlack,'MarkerColor':ROOT.kBlack} colorMap['ttH'] = {'LineColor':ROOT.kMagenta-7,'MarkerColor':ROOT.kMagenta-7} # POI str poi = "cWWMinuscB" hmax = 2.5 import math m = "%g"%math.log(1/pois[poi]['multiplier'],10) if m == '1': m = '' if poi == "cWWMinuscB": pstr_stripped = "c_{WW} #minus c_{B}" pstr = "(c_{WW} #minus c_{B}) x 10^{%s}"%m else: pstr_stripped = "c_{%s}"%poi.split("c")[-1] pstr = "c_{%s} x 10^{%s}"%(poi.split("c")[-1],m) ROOT.gROOT.SetBatch(True) ROOT.gStyle.SetOptStat(0) canv = ROOT.TCanvas("canv_%s"%poi,"canv_%s"%poi,700,500) #canv = ROOT.TCanvas("canv_%s"%poi,"canv_%s"%poi,900,500) canv.SetBottomMargin(0.15) canv.SetTickx() canv.SetTicky() prange = pois[poi]['range'][1]-pois[poi]['range'][0] h_axes = ROOT.TH1F("haxes","",100, pois[poi]['range'][0]-0.1*prange, pois[poi]['range'][1]+0.1*prange ) h_axes.SetMaximum(hmax) h_axes.SetMinimum(-0.2) h_axes.SetTitle("") h_axes.GetXaxis().SetTitle(pstr) h_axes.GetXaxis().SetTitleSize(0.05) h_axes.GetXaxis().SetLabelSize(0.035) h_axes.GetYaxis().SetTitle("#mu^{i}_{prod}(%s)"%pstr_stripped) h_axes.GetYaxis().SetTitleSize(0.05) h_axes.GetYaxis().SetTitleOffset(0.8) h_axes.GetYaxis().SetLabelSize(0.035) h_axes.GetYaxis().SetLabelOffset(0.007) h_axes.GetYaxis().CenterTitle() h_axes.SetLineWidth(0) h_axes.Draw() for stxs_bin in stxs_bins: for k, v in colorMap[stxs_bin].iteritems(): getattr(grs["%s_vs_%s_quad"%(stxs_bin,poi)],"Set%s"%k)(v) getattr(grs["%s_vs_%s_lin"%(stxs_bin,poi)],"Set%s"%k)(v) for k, v in styleMap['quad'].iteritems(): getattr(grs["%s_vs_%s_quad"%(stxs_bin,poi)],"Set%s"%k)(v) for k, v in styleMap['lin'].iteritems(): getattr(grs["%s_vs_%s_lin"%(stxs_bin,poi)],"Set%s"%k)(v) grs["%s_vs_%s_quad"%(stxs_bin,poi)].Draw("Same C") grs["%s_vs_%s_lin"%(stxs_bin,poi)].Draw("Same C") # Lines hlines = {} yvals = [0,1] for i in range(len(yvals)): yval = yvals[i] hlines['hline_%g'%i] = ROOT.TLine(pois[poi]['range'][0]-0.1*prange,yval,pois[poi]['range'][1]+0.1*prange,yval) hlines['hline_%g'%i].SetLineColorAlpha(15,0.5) hlines['hline_%g'%i].SetLineStyle(2) hlines['hline_%g'%i].SetLineWidth(1) hlines['hline_%g'%i].Draw("SAME") vlines = {} xvals = [pois[poi]['range'][0],0,pois[poi]['range'][1]] for i in range(len(xvals)): xval = xvals[i] vlines['vline_%g'%i] = ROOT.TLine(xval,-0.2,xval,hmax) vlines['vline_%g'%i].SetLineColorAlpha(15,0.5) vlines['vline_%g'%i].SetLineStyle(2) vlines['vline_%g'%i].SetLineWidth(1) vlines['vline_%g'%i].Draw("SAME") # Text lat0 = ROOT.TLatex() lat0.SetTextFont(42) lat0.SetTextAlign(11) lat0.SetNDC() lat0.SetTextSize(0.045) lat0.DrawLatex(0.1,0.92,"HEL UFO") lat1 = ROOT.TLatex() lat1.SetTextFont(42) lat1.SetTextAlign(23) lat1.SetTextSize(0.03) xpos = pois[poi]['range'][0]-0.05*prange lat1.DrawLatex(xpos,1.,"'#color[15]{#sigma = #sigma_{SM}}") lat1.DrawLatex(xpos,0.,"#color[15]{#sigma = 0}") lat2 = ROOT.TLatex() lat2.SetTextFont(42) lat2.SetTextAlign(23) lat2.SetTextAngle(90) lat2.SetTextSize(0.045) lat2.SetTextAlign(21) lat2.DrawLatex(pois[poi]['range'][0]-0.02*prange,0.9*hmax,"#color[15]{c_{min}}") lat2.SetTextAlign(23) lat2.DrawLatex(pois[poi]['range'][1]+0.01*prange,0.9*hmax,"#color[15]{c_{max}}") # Legend # Create dummy graph for linear gr_lin_dummy = ROOT.TGraph() for k,v in styleMap['lin_dummy'].iteritems(): getattr(gr_lin_dummy,"Set%s"%k)(v) leg = ROOT.TLegend(0.55,0.22,0.8,0.48) #leg = ROOT.TLegend(0.63,0.28,0.8,0.38) leg.SetFillStyle(0) leg.SetLineColor(0) leg.SetTextSize(0.0275) #leg.SetTextSize(0.035) for stxs_bin in stxs_bins: leg.AddEntry( grs["%s_vs_%s_quad"%(stxs_bin,poi)], Translate(stxs_bin,translateBins), "L") leg.AddEntry(gr_lin_dummy,"(Lin. terms only)","L") leg.Draw("Same") canv.Update() canv.SaveAs("/eos/home-j/jlangfor/www/CMS/thesis/chapter7/scaling_functions/ZH_lep_vs_%s.png"%poi) canv.SaveAs("/eos/home-j/jlangfor/www/CMS/thesis/chapter7/scaling_functions/ZH_lep_vs_%s.pdf"%poi) #canv.SaveAs("/eos/home-j/jlangfor/www/CMS/thesis/chapter7/scaling_functions/ttH_vs_%s.png"%poi) #canv.SaveAs("/eos/home-j/jlangfor/www/CMS/thesis/chapter7/scaling_functions/ttH_vs_%s.pdf"%poi)
[ "jl2117@ic.ac.uk" ]
jl2117@ic.ac.uk
e12d6762e76b184388535c634d9a135c76ad728f
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p02400/s312694229.py
0e3f00ee5086355e387498233f562d240a9c9fa5
[]
no_license
Aasthaengg/IBMdataset
7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901
f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8
refs/heads/main
2023-04-22T10:22:44.763102
2021-05-13T17:27:22
2021-05-13T17:27:22
367,112,348
0
0
null
null
null
null
UTF-8
Python
false
false
168
py
import sys import math def main(): r = float(sys.stdin.readline()) print(math.pi * r**2, 2 * math.pi * r) return if __name__ == '__main__': main()
[ "66529651+Aastha2104@users.noreply.github.com" ]
66529651+Aastha2104@users.noreply.github.com
a950c831386ddc3bd2049db23e626695c198bb3a
6b5572557c4a0785c4b727ee024790ec066ad6f2
/Baekjoon/동적계획법 1/1, 2, 3 더하기.py
c018911cffa41fdf3bdb10a60894fd54e9209e12
[]
no_license
easternpillar/AlgorithmTraining
5be38998dc062d1d02933f61eaca3265e1b73981
c8f05eda86161a7dbacab99154be1af292e7db8a
refs/heads/master
2023-04-29T11:13:34.984005
2023-04-08T07:12:29
2023-04-08T07:12:29
231,875,419
1
0
null
null
null
null
UTF-8
Python
false
false
419
py
# Problem: # Reference: https://www.acmicpc.net/problem/9095 # My Solution: import sys dp = [0 for _ in range(11)] dp[0] = 1 for i in range(1, 4, 1): for j in range(1,11): tot = 0 for k in range(j - i, j, 1): if k >= 0: tot += dp[k] dp[j] = tot for _ in range(int(sys.stdin.readline().rstrip())): num = int(sys.stdin.readline().rstrip()) print(dp[num])
[ "roh941129@gmail.com" ]
roh941129@gmail.com
3fae578b5162e7f5acb831c405be63172c98b6df
2aace9bb170363e181eb7520e93def25f38dbe5c
/build/idea-sandbox/system/python_stubs/cache/300a07a56fa3435d495e1ce8762b25d84931bfae7c2899c2825326bcc799b818/typing/re.py
2336d186762e5e40248962573d6c349ef6e6ffaa
[]
no_license
qkpqkp/PlagCheck
13cb66fd2b2caa2451690bb72a2634bdaa07f1e6
d229904674a5a6e46738179c7494488ca930045e
refs/heads/master
2023-05-28T15:06:08.723143
2021-06-09T05:36:34
2021-06-09T05:36:34
375,235,940
1
0
null
null
null
null
UTF-8
Python
false
false
1,495
py
# encoding: utf-8 # module typing.re # from C:\Users\Doly\Anaconda3\lib\site-packages\statsmodels\tsa\statespace\_representation.cp37-win_amd64.pyd # by generator 1.147 """ Wrapper namespace for re type aliases. """ # no imports # functions def Match(*args, **kwargs): # real signature unknown """ The central part of internal API. This represents a generic version of type 'origin' with type arguments 'params'. There are two kind of these aliases: user defined and special. The special ones are wrappers around builtin collections and ABCs in collections.abc. These must have 'name' always set. If 'inst' is False, then the alias can't be instantiated, this is used by e.g. typing.List and typing.Dict. """ pass def Pattern(*args, **kwargs): # real signature unknown """ The central part of internal API. This represents a generic version of type 'origin' with type arguments 'params'. There are two kind of these aliases: user defined and special. The special ones are wrappers around builtin collections and ABCs in collections.abc. These must have 'name' always set. If 'inst' is False, then the alias can't be instantiated, this is used by e.g. typing.List and typing.Dict. """ pass # no classes # variables with complex values __all__ = [ 'Pattern', 'Match', ] __weakref__ = None # (!) real value is "<attribute '__weakref__' of 'typing.re' objects>"
[ "qinkunpeng2015@163.com" ]
qinkunpeng2015@163.com
167439e261d55b4a6013812c4b86be943e29dd30
16e8129f7a12239ed49aabfa04549d90419bb12e
/old_explore.py
1b2cf18e07a1f4df23eb6398cb62957b72fd8c45
[]
no_license
Seanny123/hrl_analysis
0a5a4ff8b672d05760e39ec5558557220d71459d
7ccf2beea6090c1493c4dce95630ef251f9c6548
refs/heads/master
2020-05-18T20:59:29.098987
2015-01-07T23:18:56
2015-01-07T23:18:56
28,878,160
0
0
null
null
null
null
UTF-8
Python
false
false
146
py
not_equal = [] count = 0 for i,j in zip(file_list[0], file_list[1]): if(i != j ): not_equal.append(1) count += 1 else: not_equal.append(0)
[ "saubin@uwaterloo.ca" ]
saubin@uwaterloo.ca
48d4b9fe1ff3432fc5ef22a33a9d4014933c5d2c
53983c1dbd4e27d918237d22287f1838ae42cc92
/tools/txtIO.py
03e55b006916f7db35cb202eb15e7466473f3329
[]
no_license
xshii/MDAOXS
da5060ea6b6ac600b3b85dddbb7460f62ab4a684
d4c54b79d7c84740bf01d8e8573e54522de2e6d0
refs/heads/master
2021-09-24T10:35:31.295574
2018-10-08T10:54:44
2018-10-08T10:54:44
108,884,304
0
1
null
null
null
null
UTF-8
Python
false
false
873
py
import numpy as np def stlTxtToNpArray(path): path = r"/Users/gakki/Downloads/SU2_mesh_point_clouds/Optimale_orig_points.txt" mesh = np.empty([1,3]) with open(path) as fp: for line in fp: if line.__len__()<5: continue line = line.strip().split(';') line = list(map(str.strip, line)) if line[1].startswith('-'): if line[1].count('-') == 2: line[1] = line[1].replace('-','e-')[1:] else: line[1] = line[1].replace('-','e-') mesh = np.vstack([mesh,np.array(line,dtype='float')]) mesh = mesh[1:,:] return mesh if __name__=='__main__': path = r"/Users/gakki/Downloads/SU2_mesh_point_clouds/Optimale_orig_points.txt" mesh = stlTxtToNpArray(path=path) np.savetxt('new_mesh.txt',mesh,delimiter=';')
[ "xshi@kth.se" ]
xshi@kth.se
1a37d2f7a618537fb84f62c141d88105e25238a2
42c48f3178a48b4a2a0aded547770027bf976350
/google/ads/google_ads/v4/services/ad_group_service_client_config.py
1931ef3dfd64f9494a515ac86c2f1db21526b546
[ "Apache-2.0" ]
permissive
fiboknacky/google-ads-python
e989464a85f28baca1f28d133994c73759e8b4d6
a5b6cede64f4d9912ae6ad26927a54e40448c9fe
refs/heads/master
2021-08-07T20:18:48.618563
2020-12-11T09:21:29
2020-12-11T09:21:29
229,712,514
0
0
Apache-2.0
2019-12-23T08:44:49
2019-12-23T08:44:49
null
UTF-8
Python
false
false
964
py
config = { "interfaces": { "google.ads.googleads.v4.services.AdGroupService": { "retry_codes": { "idempotent": [ "DEADLINE_EXCEEDED", "UNAVAILABLE" ], "non_idempotent": [] }, "retry_params": { "default": { "initial_retry_delay_millis": 5000, "retry_delay_multiplier": 1.3, "max_retry_delay_millis": 60000, "initial_rpc_timeout_millis": 3600000, "rpc_timeout_multiplier": 1.0, "max_rpc_timeout_millis": 3600000, "total_timeout_millis": 3600000 } }, "methods": { "GetAdGroup": { "timeout_millis": 60000, "retry_codes_name": "idempotent", "retry_params_name": "default" }, "MutateAdGroups": { "timeout_millis": 60000, "retry_codes_name": "non_idempotent", "retry_params_name": "default" } } } } }
[ "noreply@github.com" ]
fiboknacky.noreply@github.com
d6ea747b5957732d583916c70b4f80bc1cdb39b4
51f887286aa3bd2c3dbe4c616ad306ce08976441
/pybind/slxos/v17s_1_02/brocade_mpls_rpc/show_mpls_ldp_fec_prefix_prefix/input/__init__.py
414039c71bac5dac5968fee3843019053441ab0c
[ "Apache-2.0" ]
permissive
b2220333/pybind
a8c06460fd66a97a78c243bf144488eb88d7732a
44c467e71b2b425be63867aba6e6fa28b2cfe7fb
refs/heads/master
2020-03-18T09:09:29.574226
2018-04-03T20:09:50
2018-04-03T20:09:50
null
0
0
null
null
null
null
UTF-8
Python
false
false
6,492
py
from operator import attrgetter import pyangbind.lib.xpathhelper as xpathhelper from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType from pyangbind.lib.base import PybindBase from decimal import Decimal from bitarray import bitarray import __builtin__ class input(PybindBase): """ This class was auto-generated by the PythonClass plugin for PYANG from YANG module brocade-mpls - based on the path /brocade_mpls_rpc/show-mpls-ldp-fec-prefix-prefix/input. Each member element of the container is represented as a class variable - with a specific YANG type. """ __slots__ = ('_pybind_generated_by', '_path_helper', '_yang_name', '_rest_name', '_extmethods', '__ldp_fec_prefix',) _yang_name = 'input' _rest_name = 'input' _pybind_generated_by = 'container' def __init__(self, *args, **kwargs): path_helper_ = kwargs.pop("path_helper", None) if path_helper_ is False: self._path_helper = False elif path_helper_ is not None and isinstance(path_helper_, xpathhelper.YANGPathHelper): self._path_helper = path_helper_ elif hasattr(self, "_parent"): path_helper_ = getattr(self._parent, "_path_helper", False) self._path_helper = path_helper_ else: self._path_helper = False extmethods = kwargs.pop("extmethods", None) if extmethods is False: self._extmethods = False elif extmethods is not None and isinstance(extmethods, dict): self._extmethods = extmethods elif hasattr(self, "_parent"): extmethods = getattr(self._parent, "_extmethods", None) self._extmethods = extmethods else: self._extmethods = False self.__ldp_fec_prefix = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_dict={'pattern': u'(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])/(([0-9])|([1-2][0-9])|(3[0-2]))'}), is_leaf=True, yang_name="ldp-fec-prefix", rest_name="ldp-fec-prefix", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='inet:ipv4-prefix', is_config=True) load = kwargs.pop("load", None) if args: if len(args) > 1: raise TypeError("cannot create a YANG container with >1 argument") all_attr = True for e in self._pyangbind_elements: if not hasattr(args[0], e): all_attr = False break if not all_attr: raise ValueError("Supplied object did not have the correct attributes") for e in self._pyangbind_elements: nobj = getattr(args[0], e) if nobj._changed() is False: continue setmethod = getattr(self, "_set_%s" % e) if load is None: setmethod(getattr(args[0], e)) else: setmethod(getattr(args[0], e), load=load) def _path(self): if hasattr(self, "_parent"): return self._parent._path()+[self._yang_name] else: return [u'brocade_mpls_rpc', u'show-mpls-ldp-fec-prefix-prefix', u'input'] def _rest_path(self): if hasattr(self, "_parent"): if self._rest_name: return self._parent._rest_path()+[self._rest_name] else: return self._parent._rest_path() else: return [u'show-mpls-ldp-fec-prefix-prefix', u'input'] def _get_ldp_fec_prefix(self): """ Getter method for ldp_fec_prefix, mapped from YANG variable /brocade_mpls_rpc/show_mpls_ldp_fec_prefix_prefix/input/ldp_fec_prefix (inet:ipv4-prefix) YANG Description: IP address/Subnet mask length """ return self.__ldp_fec_prefix def _set_ldp_fec_prefix(self, v, load=False): """ Setter method for ldp_fec_prefix, mapped from YANG variable /brocade_mpls_rpc/show_mpls_ldp_fec_prefix_prefix/input/ldp_fec_prefix (inet:ipv4-prefix) If this variable is read-only (config: false) in the source YANG file, then _set_ldp_fec_prefix is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_ldp_fec_prefix() directly. YANG Description: IP address/Subnet mask length """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=unicode, restriction_dict={'pattern': u'(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])/(([0-9])|([1-2][0-9])|(3[0-2]))'}), is_leaf=True, yang_name="ldp-fec-prefix", rest_name="ldp-fec-prefix", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='inet:ipv4-prefix', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """ldp_fec_prefix must be of a type compatible with inet:ipv4-prefix""", 'defined-type': "inet:ipv4-prefix", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_dict={'pattern': u'(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])/(([0-9])|([1-2][0-9])|(3[0-2]))'}), is_leaf=True, yang_name="ldp-fec-prefix", rest_name="ldp-fec-prefix", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='inet:ipv4-prefix', is_config=True)""", }) self.__ldp_fec_prefix = t if hasattr(self, '_set'): self._set() def _unset_ldp_fec_prefix(self): self.__ldp_fec_prefix = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_dict={'pattern': u'(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])/(([0-9])|([1-2][0-9])|(3[0-2]))'}), is_leaf=True, yang_name="ldp-fec-prefix", rest_name="ldp-fec-prefix", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='inet:ipv4-prefix', is_config=True) ldp_fec_prefix = __builtin__.property(_get_ldp_fec_prefix, _set_ldp_fec_prefix) _pyangbind_elements = {'ldp_fec_prefix': ldp_fec_prefix, }
[ "badaniya@brocade.com" ]
badaniya@brocade.com
5f4d4cbae4be77f5c897b06ef5e96f1d6c45ff12
4f875744ccae8fa9225318ce16fc483b7bf2735e
/amazon/missingNumber.py
51bc4b88b741139e123462001c9eba084a29d249
[]
no_license
nguyenngochuy91/companyQuestions
62c0821174bb3cb33c7af2c5a1e83a60e4a29977
c937fe19be665ba7ac345e1729ff531f370f30e8
refs/heads/master
2020-07-27T05:58:36.794033
2020-04-10T20:57:15
2020-04-10T20:57:15
208,893,527
1
0
null
null
null
null
UTF-8
Python
false
false
378
py
# -*- coding: utf-8 -*- """ Created on Wed Jan 1 23:59:19 2020 @author: huyn """ #Missing Number #Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array. from typing import List class Solution: def missingNumber(self, nums: List[int]) -> int: size = len(nums) return size*(size+1)//2-sum(nums)
[ "huyn@cvm6h4zv52.cvm.iastate.edu" ]
huyn@cvm6h4zv52.cvm.iastate.edu
e7ccb286539047d1d436e032546a3938ddce7bf1
0b86600e0288c0fefc081a0f428277a68b14882e
/binaire/binaire_II.py
b861b63f8209d81b2dbc50518fcc23ce46f0cebc
[]
no_license
Byliguel/python1-exo7
9ede37a8d2b8f384d1ebe3d612e8c25bbe47a350
fbf6b08f4c1e94dd9f170875eee871a84849399e
refs/heads/master
2020-09-22T10:16:34.044141
2019-12-01T11:52:51
2019-12-01T11:52:51
225,152,986
1
0
null
2019-12-01T11:51:37
2019-12-01T11:51:36
null
UTF-8
Python
false
false
5,199
py
############################## # Binaire - partie II ############################## from binaire_I import * ############################## # Activité 1 - Palindrome en binaire ############################## ## Question 1 ## def est_palindrome_1(liste): p = len(liste) drapeau = True for i in range(p): if liste[i] != liste[p-1-i]: drapeau = False return drapeau # Version optimisée : def est_palindrome_1_bis(liste): p = len(liste) for i in range(p//2): if liste[i] != liste[p-1-i]: return False return True def est_palindrome_2(liste): liste_inverse = list(reversed(liste)) return liste == liste_inverse # Test print("--- Test d'un palindrome ---") liste = [1,0,1,0,0,1,0,1] print(est_palindrome_1(liste)) print(est_palindrome_1_bis(liste)) print(est_palindrome_2(liste)) ## Question 2 ## def cherche_palindrome_binaire(N): num = 0 for n in range(N): liste_binaire = entier_vers_binaire(n) if est_palindrome_1(liste_binaire) == True: num = num + 1 print(num,":",n,"=",entier_vers_binaire(n)) return # Test print("--- Palindromes binaires ---") cherche_palindrome_binaire(1000) # Le 1000ème palindrome en binaire est : #249903 = [1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1] ## Question 3 ## def cherche_palindrome_decimale(N): num = 0 for n in range(N): liste_decimale = entier_vers_decimale(n) if est_palindrome_1(liste_decimale) == True: num = num + 1 print(num,":",n) return # Test print("--- Palindromes avec décimales ---") cherche_palindrome_decimale(1000) # Le 1000ème palindrome en décimales est : # 90009 ## Question 4 ## def cherche_bi_palindrome(N): num = 0 for n in range(N): liste_binaire = entier_vers_binaire(n) liste_decimale = entier_vers_decimale(n) if est_palindrome_1(liste_binaire) == True and est_palindrome_1(liste_decimale): num = num + 1 print(num,":",n,"=",entier_vers_binaire(n)) return # Test print("--- Bi-palindromes ---") cherche_bi_palindrome(1000) # Le 20ème bi-palindrome est # 585585 = [1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1] ############################## # Activité 2 - Opérations logiques ############################## ## Question 1 ## def OUeg(l1,l2): n = len(l1) l = [] for i in range(n): if l1[i]==1 or l2[i]==1: l = l + [1] else: l = l + [0] return l def ETeg(l1,l2): n = len(l1) l = [] for i in range(n): if l1[i]==1 and l2[i]==1: l = l + [1] else: l = l + [0] return l def NON(l1): l = [] for b in l1: if b==1: l = l + [0] else: l = l + [1] return l # Test print("--- Opérations logiques (même longueur) ---") l1 = [1,0,1,0,1,0,1] l2 = [1,0,0,1,0,0,1] print(l1) print(l2) print(OUeg(l1,l2)) print(ETeg(l1,l2)) print(NON(l1)) ## Question 2 ## # Rajouter des zéros non significatifs si besoins def ajouter_zeros(liste,p): while len(liste)< p: liste = [0] + liste return liste # Test print("--- Zeros non significatifs ---") print(ajouter_zeros([1,0,1,1],8)) ## Question 3 ## # Opérations logiques avec des listes de tailles différentes def OU(l1,l2): p = len(l1) q = len(l2) if p>q: ll2 = ajouter_zeros(l2,p) return OUeg(l1,ll2) else: ll1 = ajouter_zeros(l1,q) return OUeg(ll1,l2) def ET(l1,l2): p = len(l1) q = len(l2) if p>q: ll2 = ajouter_zeros(l2,p) return ETeg(l1,ll2) else: ll1 = ajouter_zeros(l1,q) return ETeg(ll1,l2) # Test print("--- Opérations logiques (cas général) ---") l1 = [1,0,1,0,1,0,1] l2 = [1,0,0,1,0,] print(l1) print(l2) print(OU(l1,l2)) print(ET(l1,l2)) ############################## # Activité 3 - Loi de Morgan ############################## ## Question 1 ## def tous_les_binaires(p): liste_p = [] for n in range(2**p): liste_p = liste_p + [entier_vers_binaire(n)] return liste_p # Test print("--- Tous les binaires ---") print(tous_les_binaires(3)) ## Question 2 ## def toutes_les_listes(p): if p == 0: return [] if p == 1: return [[0],[1]] liste_p_1 = toutes_les_listes(p-1) liste_p = [ [0] + l for l in liste_p_1] + [ [1] + l for l in liste_p_1] return liste_p # Test print("--- Toutes les listes ---") print(toutes_les_listes(3)) ## Question 3 ## # Lois de Morgan def test_loi_de_morgan(p): liste_tous = [ajouter_zeros(l,p) for l in tous_les_binaires(p)] #liste_tous = toutes_les_listes(p) for l1 in liste_tous: for l2 in liste_tous: non_l1_ou_l2 = NON(OU(l1,l2)) non_l1_et_non_l2 = ET(NON(l1),NON(l2)) if non_l1_ou_l2 == non_l1_et_non_l2: print("Vrai") # pass else: print("Faux",l1,l2) return # Test print("--- Test loi de Morgan ---") test_loi_de_morgan(2)
[ "arnaud.bodin@math.univ-lille1.fr" ]
arnaud.bodin@math.univ-lille1.fr
5f7da7fa319f1cc207012d4a7c768df8dbb81213
b096dbccb31d3bd181259e930816964c71034ff4
/tests/test_asynchronous/test_task.py
73017b8eafee20bb87f1953d01201f1490e7e409
[]
no_license
cosphere-org/lily
b68f95720381a69ce0caa5f47fca461b3f5242a9
f6a8281e10eedcccb86fcf3a26aaf282d91f70f4
refs/heads/master
2023-02-18T13:49:03.568989
2022-06-30T09:58:23
2022-06-30T09:58:23
175,789,374
6
0
null
2023-02-15T18:49:10
2019-03-15T09:28:05
Python
UTF-8
Python
false
false
369
py
from unittest import TestCase from lily.asynchronous import AsyncTask class AsyncTaskTestCase(TestCase): def test_init(self): def fn(): pass task = AsyncTask(callback=fn, args=[9, 1]) assert task.callback == fn assert task.args == [9, 1] assert task.successful is False assert task.result is None
[ "maciej@cosphere.org" ]
maciej@cosphere.org
3ba8f7fac04d4e7b45bfe7128eff82a0fb4248dc
974d04d2ea27b1bba1c01015a98112d2afb78fe5
/test/ipu/test_gelu_op_ipu.py
5877341afb1264b0ffe18dd0fbecc822be5d9904
[ "Apache-2.0" ]
permissive
PaddlePaddle/Paddle
b3d2583119082c8e4b74331dacc4d39ed4d7cff0
22a11a60e0e3d10a3cf610077a3d9942a6f964cb
refs/heads/develop
2023-08-17T21:27:30.568889
2023-08-17T12:38:22
2023-08-17T12:38:22
65,711,522
20,414
5,891
Apache-2.0
2023-09-14T19:20:51
2016-08-15T06:59:08
C++
UTF-8
Python
false
false
2,151
py
# Copyright (c) 2021 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 unittest import numpy as np from op_test_ipu import IPUOpTest import paddle import paddle.static class TestBase(IPUOpTest): def setUp(self): self.set_atol() self.set_training() self.set_data_feed() self.set_feed_attr() self.set_op_attrs() def set_data_feed(self): data = np.random.uniform(size=[1, 3, 10, 10]) self.feed_fp32 = {'in_0': data.astype(np.float32)} self.feed_fp16 = {'in_0': data.astype(np.float16)} def set_feed_attr(self): self.feed_shape = [x.shape for x in self.feed_fp32.values()] self.feed_list = list(self.feed_fp32.keys()) def set_op_attrs(self): self.attrs = {"approximate": False} @IPUOpTest.static_graph def build_model(self): x = paddle.static.data( name=self.feed_list[0], shape=self.feed_shape[0], dtype='float32' ) out = paddle.nn.functional.gelu(x, **self.attrs) self.fetch_list = [out.name] def run_model(self, exec_mode): self.run_op_test(exec_mode) def test(self): for m in IPUOpTest.ExecutionMode: if not self.skip_mode(m): self.build_model() self.run_model(m) self.check() class TestCase1(TestBase): def set_atol(self): self.atol = 1e-10 self.rtol = 1e-6 self.atol_fp16 = 2e-3 self.rtol_fp16 = 1e-3 def set_op_attrs(self): self.attrs = {"approximate": True} if __name__ == "__main__": unittest.main()
[ "noreply@github.com" ]
PaddlePaddle.noreply@github.com
cd11f4c013bbbf9e2770dc15bde51f95098d6eac
a43cf3cacf518096737dd39833fd39624f8cf543
/tests/test_csv_adapters.py
071ac85a5c6f6098d645e145a468f026e11bcd6a
[ "Apache-2.0" ]
permissive
Mickey1964/antevents-python
f6ad4f9b056550055a223f7d4a7d34bc030c1dfb
5b9226813583141986014fc83f6f74342a5f271e
refs/heads/master
2021-06-15T11:23:56.253643
2017-03-31T05:25:59
2017-03-31T05:25:59
null
0
0
null
null
null
null
UTF-8
Python
false
false
5,236
py
# Copyright 2016 by MPI-SWS and Data-Ken Research. # Licensed under the Apache 2.0 License. """Verify the csv reader/writer through a round trip """ import unittest import time from tempfile import NamedTemporaryFile import os import asyncio import datetime from antevents.base import Scheduler, IterableAsPublisher, SensorEvent from antevents.adapters.csv import CsvReader, default_event_mapper import antevents.linq.dispatch from utils import make_test_publisher, CaptureSubscriber, \ SensorEventValidationSubscriber NUM_EVENTS=5 class TestCases(unittest.TestCase): def test_default_mapper(self): """Verify the class that maps between an event and a sensor """ event = SensorEvent(ts=time.time(), sensor_id=1, val=123.456) row = default_event_mapper.event_to_row(event) event2 = default_event_mapper.row_to_event(row) self.assertEqual(event2, event, "Round-tripped event does not match original event") def test_file_write_read(self): tf = NamedTemporaryFile(mode='w', delete=False) tf.close() try: sensor = make_test_publisher(1, stop_after_events=NUM_EVENTS) capture = CaptureSubscriber() sensor.subscribe(capture) sensor.csv_writer(tf.name) scheduler = Scheduler(asyncio.get_event_loop()) scheduler.schedule_recurring(sensor) print("Writing sensor events to temp file") scheduler.run_forever() self.assertTrue(capture.completed, "CaptureSubscriber did not complete") self.assertEqual(len(capture.events), NUM_EVENTS, "number of events captured did not match generated events") reader = CsvReader(tf.name) vs = SensorEventValidationSubscriber(capture.events, self) reader.subscribe(vs) scheduler.schedule_recurring(reader) print("reading sensor events back from temp file") scheduler.run_forever() self.assertTrue(vs.completed, "ValidationSubscriber did not complete") finally: os.remove(tf.name) # data for rollover test ROLLING_FILE1 = 'dining-room-2015-01-01.csv' ROLLING_FILE2 = 'dining-room-2015-01-02.csv' FILES = [ROLLING_FILE1, ROLLING_FILE2] def make_ts(day, hr, minute): return (datetime.datetime(2015, 1, day, hr, minute) - datetime.datetime(1970,1,1)).total_seconds() EVENTS = [SensorEvent('dining-room', make_ts(1, 11, 1), 1), SensorEvent('dining-room', make_ts(1, 11, 2), 2), SensorEvent('dining-room', make_ts(2, 11, 1), 3), SensorEvent('dining-room', make_ts(2, 11, 2), 4)] # data for dispatch test sensor_ids = ['dining-room', 'living-room'] ROLLING_FILE3 = 'living-room-2015-01-01.csv' ROLLING_FILE4 = 'living-room-2015-01-02.csv' FILES2 = [ROLLING_FILE1, ROLLING_FILE2, ROLLING_FILE3, ROLLING_FILE4] EVENTS2 = [SensorEvent('dining-room', make_ts(1, 11, 1), 1), SensorEvent('living-room', make_ts(1, 11, 2), 2), SensorEvent('living-room', make_ts(2, 11, 1), 3), SensorEvent('dining-room', make_ts(2, 11, 2), 4)] def make_rule(sensor_id): return (lambda evt: evt.sensor_id==sensor_id, sensor_id) dispatch_rules = [make_rule(s) for s in sensor_ids] class TestRollingCsvWriter(unittest.TestCase): def _cleanup(self): for f in FILES2: if os.path.exists(f): os.remove(f) def setUp(self): self._cleanup() def tearDown(self): self._cleanup() def test_rollover(self): def generator(): for e in EVENTS: yield e sensor = IterableAsPublisher(generator(), name='sensor') sensor.rolling_csv_writer('.', 'dining-room') vs = SensorEventValidationSubscriber(EVENTS, self) sensor.subscribe(vs) scheduler = Scheduler(asyncio.get_event_loop()) scheduler.schedule_recurring(sensor) scheduler.run_forever() for f in FILES: self.assertTrue(os.path.exists(f), 'did not find file %s' % f) print("found log file %s" % f) def test_dispatch(self): """Test a scenario where we dispatch to one of several writers depending on the sensor id. """ def generator(): for e in EVENTS2: yield e sensor = IterableAsPublisher(generator(), name='sensor') dispatcher = sensor.dispatch(dispatch_rules) for s in sensor_ids: dispatcher.rolling_csv_writer('.', s, sub_topic=s) dispatcher.subscribe(lambda x: self.assertTrue(False, "bad dispatch of %s" % x)) scheduler = Scheduler(asyncio.get_event_loop()) scheduler.schedule_recurring(sensor) scheduler.run_forever() for f in FILES2: self.assertTrue(os.path.exists(f), 'did not find file %s' % f) cnt = 0 with open(f, 'r') as fobj: for line in fobj: cnt +=1 self.assertEqual(2, cnt, "File %s did not have 2 lines" % f) print("found log file %s" % f) if __name__ == '__main__': unittest.main()
[ "jeff@data-ken.org" ]
jeff@data-ken.org
8c9c6f86415414eac65099b6ad036d598482a6ef
cc88beafd7a59a832fecff45f436490f805ba000
/demos/json_schema.py
72f3cf8eec40655d6dac240792698b62d8a3ff2c
[ "BSD-3-Clause" ]
permissive
RobSpectre/structures
6ead59bf37ef02e3c3d2181dc941a2e60f98becb
5345fb63658eecdc59e08882372294f13b0df889
refs/heads/master
2020-12-25T04:29:11.389945
2012-08-25T17:45:15
2012-08-25T17:45:15
null
0
0
null
null
null
null
UTF-8
Python
false
false
819
py
#!/usr/bin/env python """{'type': 'object', 'properties': {'personal_thoughts': {'type': 'string', 'id': 'personal_thoughts', 'maxLength': 255}, 'title': {'type': 'string', 'id': 'title', 'maxLength': 40}, 'id': {'type': 'string'}, 'year': {'minimum': 1950, 'type': 'integer', 'id': 'year', 'maximum': 2011}}} """ import datetime from structures.models import Model from structures.types import StringType, IntType ### ### The base class ### class Movie(Model): """Simple model that has one StringType member """ title = StringType(max_length=40) year = IntType(min_value=1950, max_value=datetime.datetime.now().year) personal_thoughts = StringType(max_length=255) m = Movie(title='Some Movie', year=2011, personal_thoughts='It was pretty good') print m.for_jsonschema()
[ "jd@j2labs.net" ]
jd@j2labs.net
449c3c5e309070e99dc56af5ec86f50dc0f73458
5292b03998384c0d2bb5858058892d7e45c5365b
/Hack.lu/2020/right-spot/run.py
8c7042ab7fb76f17d7a1c5a6d887097b60883e2d
[ "MIT" ]
permissive
TheusZer0/ctf-archives
430ef80d367b44fd81449bcb108e367842cb8e39
033ccf8dab0abdbdbbaa4f0092ab589288ddb4bd
refs/heads/main
2023-09-04T17:56:24.416820
2021-11-21T06:51:27
2021-11-21T06:51:27
430,603,430
1
0
MIT
2021-11-22T07:24:08
2021-11-22T07:24:07
null
UTF-8
Python
false
false
2,998
py
#!/usr/bin/env python3 import zlib import sys import os import subprocess import io import bz2 import sys from flag import flag COMPRESSED_LIMIT = 2**20 # 1 MB compressed DECOMPRESSED_LIMIT = 30*2**20 # 30 MB uncompressed EXPECTED_STRING = b"pwned!\n" NUM_TESTS = 4 def compress(data): if len(data) > DECOMPRESSED_LIMIT: print('ERROR: File size limit exceeded!') exit(0) return bz2.compress(data, compresslevel=9) def decompress(data): bz2d = bz2.BZ2Decompressor() output = bz2d.decompress(data, max_length=DECOMPRESSED_LIMIT) if bz2d.needs_input == True: print('ERROR: File size limit exceeded!') exit(0) return output print(f"Welcome! Please send bz2 compressed binary data. How many bytes will you send (MAX: {COMPRESSED_LIMIT})?", flush=True) try: num_bytes = int(sys.stdin.readline()) except ValueError: print("A valid number, please") exit(0) if not (0 < num_bytes <= COMPRESSED_LIMIT): print("Bad number of bytes. Bye!") exit(0) print("What is your calculated CRC of the compressed data (hex)?", flush=True) try: crc = int(sys.stdin.readline(), 16) except ValueError: print("A valid hex crc, please") exit(0) print(f"Okay got CRC: {crc:x}, please start sending data", flush=True) compressed_payload = sys.stdin.buffer.read(num_bytes) while len(compressed_payload) < num_bytes: compressed_payload += sys.stdin.buffer.read(0, num_bytes - len(compressed_payload)) print(f"Read {len(compressed_payload)} bytes") calc_crc = zlib.crc32(compressed_payload) if crc == calc_crc: print("[+] CRC Checks out, all good.", flush=True) else: print(f"CRC mismatch. Calculated CRC: {calc_crc:x}, expected: {crc:x}") exit(0) payload = decompress(compressed_payload) if len(payload) > DECOMPRESSED_LIMIT: print(f"Payload too long. Got: {len(payload)} bytes. Limit: {DECOMPRESSED_LIMIT}") exit(0) print("[+] Decompressed payload", flush=True) for seed in range(1 << 5): print(f"Trying seed: 0x{seed:x}", flush=True) for i in range(1, NUM_TESTS + 1): print(f"Try #{i}", flush=True) try: p = subprocess.Popen(["./right_spot", str(seed)], stdin=subprocess.PIPE, stdout=subprocess.PIPE) stdout_output, stderr_output = p.communicate(input=payload, timeout=5) if stdout_output != EXPECTED_STRING: print("[-] Mh, not the correct output.") print(f"Output was: {stdout_output}") exit(0) if p.returncode != 0: print(f"[-] Did not return success status code. Status was: {p.returncode}") exit(0) except subprocess.TimeoutExpired as e: print("[-] Process timed out") p.kill() exit(0) except Exception as e: print("Something unforeseen went wrong...") print(e) p.kill() exit(0) print(f"Congrats, here is your flag: {flag}", flush=True)
[ "sajjadium@google.com" ]
sajjadium@google.com
4ffb855b13fd38f3ff0bf76db89c7a878afc1c77
e210c28eeed9d38eb78c14b3a6388eca1e0e85d8
/examples/advanced/sklearn-svm/jobs/sklearn_svm_base/app/custom/svm_learner.py
070ceb832d5e6448975001a4a6fd155dcae0fea3
[ "Apache-2.0" ]
permissive
NVIDIA/NVFlare
5a2d2e4c85a3fd0948e25f1ba510449727529a15
1433290c203bd23f34c29e11795ce592bc067888
refs/heads/main
2023-08-03T09:21:32.779763
2023-07-05T21:17:16
2023-07-05T21:17:16
388,876,833
442
140
Apache-2.0
2023-09-14T19:12:35
2021-07-23T17:26:12
Python
UTF-8
Python
false
false
3,884
py
# Copyright (c) 2023, NVIDIA CORPORATION. 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 typing import Optional, Tuple from sklearn.metrics import roc_auc_score from sklearn.svm import SVC from nvflare.apis.fl_context import FLContext from nvflare.app_common.abstract.learner_spec import Learner from nvflare.app_opt.sklearn.data_loader import load_data_for_range class SVMLearner(Learner): def __init__( self, data_path: str, train_start: int, train_end: int, valid_start: int, valid_end: int, ): super().__init__() self.data_path = data_path self.train_start = train_start self.train_end = train_end self.valid_start = valid_start self.valid_end = valid_end self.train_data = None self.valid_data = None self.n_samples = None self.svm = None self.kernel = None self.params = {} def load_data(self) -> dict: train_data = load_data_for_range(self.data_path, self.train_start, self.train_end) valid_data = load_data_for_range(self.data_path, self.valid_start, self.valid_end) return {"train": train_data, "valid": valid_data} def initialize(self, fl_ctx: FLContext): data = self.load_data() self.train_data = data["train"] self.valid_data = data["valid"] # train data size, to be used for setting # NUM_STEPS_CURRENT_ROUND for potential use in aggregation self.n_samples = data["train"][-1] # model will be created after receiving global parameter of kernel def train(self, curr_round: int, global_param: Optional[dict], fl_ctx: FLContext) -> Tuple[dict, dict]: if curr_round == 0: # only perform training on the first round (x_train, y_train, train_size) = self.train_data self.kernel = global_param["kernel"] self.svm = SVC(kernel=self.kernel) # train model self.svm.fit(x_train, y_train) # get support vectors index = self.svm.support_ local_support_x = x_train[index] local_support_y = y_train[index] self.params = {"support_x": local_support_x, "support_y": local_support_y} elif curr_round > 1: self.system_panic("Federated SVM only performs training for one round, system exiting.", fl_ctx) return self.params, self.svm def validate(self, curr_round: int, global_param: Optional[dict], fl_ctx: FLContext) -> Tuple[dict, dict]: # local validation with global support vectors # fit a standalone SVM with the global support vectors svm_global = SVC(kernel=self.kernel) support_x = global_param["support_x"] support_y = global_param["support_y"] svm_global.fit(support_x, support_y) # validate global model (x_valid, y_valid, valid_size) = self.valid_data y_pred = svm_global.predict(x_valid) auc = roc_auc_score(y_valid, y_pred) self.log_info(fl_ctx, f"AUC {auc:.4f}") metrics = {"AUC": auc} return metrics, svm_global def finalize(self, fl_ctx: FLContext) -> None: # freeing resources in finalize del self.train_data del self.valid_data self.log_info(fl_ctx, "Freed training resources")
[ "noreply@github.com" ]
NVIDIA.noreply@github.com
5097b846d08047afa9caae82e49275ea9f3c46fa
af8f42e890126aa9af0535991e7c7109db1cedf7
/hw1/reports/sec2plot.py
b3a31adb9c253b6768e3e192addbcc8116a3fcb0
[ "MIT" ]
permissive
mwhittaker/homework
1c482a346a85c0eb9364185cb90ab5efdc67d632
2faa90662ea0b256625bd07d0d26de39b4e9a455
refs/heads/master
2021-01-22T07:39:51.446384
2017-10-18T17:31:05
2017-10-18T17:31:05
102,309,475
4
0
null
2017-09-04T02:16:25
2017-09-04T02:16:25
null
UTF-8
Python
false
false
378
py
import matplotlib.pyplot as plt import numpy as np def main(): X = np.genfromtxt("sec2.txt", delimiter=" ") steps = X[:,0] loss = X[:,1] plt.figure() plt.semilogy(steps, loss) plt.grid() plt.xlabel("Training iteration") plt.ylabel("Training loss (average mean squared error)") plt.savefig("sec2.pdf") if __name__ == "__main__": main()
[ "mjwhittaker@berkeley.edu" ]
mjwhittaker@berkeley.edu
8ed04321cc923a0b0cf6b320d0b25f6205625691
b50c44ad44f95035332f371517808406e4a756d0
/cbvSerializers/cbvApp/migrations/0001_initial.py
3af20fe7c5f546e1c79919b7d44819cc546f7478
[]
no_license
anandkumar-design/api1
d970e336f15b46dceb07ef480aa57fd544a3bd93
ae767463828138b97f4cf5ef6f7ac2ae4ac33afa
refs/heads/main
2023-04-25T00:18:13.406364
2021-05-13T12:43:35
2021-05-13T12:43:35
367,045,192
0
0
null
null
null
null
UTF-8
Python
false
false
531
py
# Generated by Django 3.2 on 2021-05-04 08:16 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Student', fields=[ ('id', models.IntegerField(primary_key=True, serialize=False)), ('name', models.CharField(max_length=20)), ('score', models.DecimalField(decimal_places=10, max_digits=19)), ], ), ]
[ "you@example.com" ]
you@example.com
68ea1dea2939203e6f537230def02ae234372113
e13c98f36c362717fdf22468b300321802346ef5
/documents/migrations/0002_auto_20161206_1643.py
a5421c43dfb9d72c97c9d451bbe268874e6e6229
[]
no_license
alexmon1989/libraries_portal
2415cc49de33459266a9f18ed8bb34ac99d3eb7c
277081e09f6347c175775337bffba074a35f3b92
refs/heads/master
2021-01-23T07:25:53.884795
2018-12-25T14:29:29
2018-12-25T14:29:29
80,501,603
0
0
null
null
null
null
UTF-8
Python
false
false
1,158
py
# -*- coding: utf-8 -*- # Generated by Django 1.10.3 on 2016-12-06 14:43 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('documents', '0001_initial'), ] operations = [ migrations.AlterModelOptions( name='anotherperson', options={'verbose_name': 'Другая персоны', 'verbose_name_plural': 'Другие персоны'}, ), migrations.AlterModelOptions( name='document', options={'verbose_name': 'Документ', 'verbose_name_plural': 'Документы'}, ), migrations.AlterModelOptions( name='documenttype', options={'verbose_name': 'Тип документа', 'verbose_name_plural': 'Типы документов'}, ), migrations.AddField( model_name='document', name='catalog_number', field=models.CharField(default=1, max_length=255, verbose_name='Шифр хранения (№ в каталоге)'), preserve_default=False, ), ]
[ "alex.mon1989@gmail.com" ]
alex.mon1989@gmail.com
0135a94e64c60142d8c29bfdaba4788908690526
376150fe6b4dd5d8c3caa65714aa47bc35e31784
/nintendo/games.py
dd8c5a5db2e8ac06d7e378a4ab5f9226ca8181f6
[ "MIT" ]
permissive
tenda-gumi/NintendoClients
977d5de576a0216a2e6c894bfa5de1658f8ef5de
67f2600f68e441980187932e8521d6dcc69dcc24
refs/heads/master
2020-06-17T14:33:52.314419
2019-07-10T04:19:38
2019-07-10T04:19:38
195,951,685
0
0
null
2019-07-09T07:03:23
2019-07-09T07:03:23
null
UTF-8
Python
false
false
1,320
py
#===== Wii U Games =====# class Friends: TITLE_ID_EUR = 0x10001C00 TITLE_ID_USA = 0x10001C00 TITLE_ID_JAP = 0x10001C00 LATEST_VERSION = 0 GAME_SERVER_ID = 0x3200 ACCESS_KEY = "ridfebb9" NEX_VERSION = 20000 class DKCTF: TITLE_ID_EUR = 0x0005000010138300 TITLE_ID_USA = 0x0005000010137F00 TITLE_ID_JAP = 0x0005000010144800 LATEST_VERSION = 17 GAME_SERVER_ID = 0x10144800 ACCESS_KEY = "7fcf384a" NEX_VERSION = 30400 #3.4.0 SERVER_VERSION = 3 class MK8: TITLE_ID_EUR = 0x000500001010ED00 TITLE_ID_USA = 0x000500001010EC00 TITLE_ID_JAP = 0x000500001010EB00 LATEST_VERSION = 64 GAME_SERVER_ID = 0x1010EB00 ACCESS_KEY = "25dbf96a" NEX_VERSION = 30504 #3.5.4 (AMK patch) SERVER_VERSION = 2002 class SMM: TITLE_ID_EUR = 0x000500001018DD00 TITLE_ID_USA = 0x000500001018DC00 TITLE_ID_JAP = 0x000500001018DB00 LATEST_VERSION = 272 GAME_SERVER_ID = 0x1018DB00 ACCESS_KEY = "9f2b4678" NEX_VERSION = 30810 #3.8.10 (AMA patch) SERVER_VERSION = 3017 #===== Switch Games =====# class MK8Deluxe: GAME_SERVER_ID = 0x2B309E01 ACCESS_KEY = "09c1c475" NEX_VERSION = 40007 #4.0.7 (apptrbs) class SMO: GAME_SERVER_ID = 0x255BA201 ACCESS_KEY = "afef0ecf" NEX_VERSION = 40302 #4.3.2 class SMM2: GAME_SERVER_ID = 0x22306D00 ACCESS_KEY = "fdf6617f" NEX_VERSION = 40601 #4.6.15 (appslop)
[ "ymarchand@me.com" ]
ymarchand@me.com
4b27e8803d48b26d90c568aa778d7eec4c44dc85
2210a763aa4679283b8d3b59e862caf691d4d5af
/projects/migrations/0003_userprofile.py
b8d9373aa4b9f3d471c16018d1fdfdf8b3e7faea
[ "BSD-2-Clause" ]
permissive
dymaxionlabs/analytics-backend
21c7dd4579188b20214c7c8ac92db26ca04348f8
fb801b184e4e510d54e8addb283fd202c9dfe7b1
refs/heads/master
2022-05-10T23:30:35.958044
2022-04-24T13:58:59
2022-04-24T13:58:59
192,096,995
0
0
BSD-3-Clause
2022-04-24T13:59:11
2019-06-15T15:55:28
Python
UTF-8
Python
false
false
863
py
# Generated by Django 2.1.5 on 2019-01-21 03:23 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('projects', '0002_auto_20181130_1704'), ] operations = [ migrations.CreateModel( name='UserProfile', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('location', models.CharField(blank=True, max_length=120)), ('phone', models.CharField(blank=True, max_length=40)), ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), ]
[ "munshkr@gmail.com" ]
munshkr@gmail.com
eef8ad3df7f2867949338d395c89c8fdc5d64834
1058984cbca36552120092af1f849cea27662c50
/rebench/tests/interop/time_adapter_test.py
a73f964d66ac61d2533d516993e656b4d65258f5
[ "MIT" ]
permissive
smarr/ReBench
21437c7a348a1821f8c5e5016539211376439447
fd8fa6beeac13c87e848ea76efb1243d1e6ee3ae
refs/heads/master
2023-08-28T00:38:18.378579
2023-08-06T15:11:50
2023-08-06T15:11:50
1,263,079
71
19
MIT
2023-08-06T15:11:52
2011-01-17T10:43:28
Python
UTF-8
Python
false
false
2,355
py
# Copyright (c) 2016 Stefan Marr <http://www.stefan-marr.de/> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish, distribute, sublicense, and/or # sell copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. from unittest import TestCase from ...interop.adapter import OutputNotParseable from ...interop.time_adapter import TimeAdapter, TimeManualAdapter class _TestRunId(object): def cmdline_for_next_invocation(self): return "FOO" class TimeAdapterTest(TestCase): def test_acquire_command(self): adapter = TimeAdapter(False, None) cmd = adapter.acquire_command(_TestRunId()) self.assertRegex(cmd, r"^/.*/bin/g?time") def test_parse_data(self): data = """real 11.00 user 5.00 sys 1.00""" adapter = TimeAdapter(False, None) TimeAdapter._use_formatted_time = False data = adapter.parse_data(data, None, 1) self.assertEqual(1, len(data)) measurements = data[0].get_measurements() self.assertEqual(3, len(measurements)) self.assertEqual(11000, data[0].get_total_value()) def test_parse_no_data(self): adapter = TimeAdapter(False, None) self.assertRaises(OutputNotParseable, adapter.parse_data, "", None, 1) def test_manual_adapter(self): adapter = TimeManualAdapter(False, None) cmd = adapter.acquire_command(_TestRunId()) self.assertEqual("FOO", cmd)
[ "git@stefan-marr.de" ]
git@stefan-marr.de
aca386663ee2b7bb52e07fbc3da653ace55ccb39
fa3e527114cd5799dddb0a25067da4923eae354e
/FastSim/JUNO/reco/reco_test_v1.py
44cb6f1977fa86490d524b1432e2d1ebb9f8a52f
[]
no_license
wenxingfang/FastSim_ML
e64c6b56ce2afd703d1ddda0ada2de6f65fde049
d2f1abbb2f6879313d5f4f137b64c4d8bf10fe83
refs/heads/master
2022-11-28T01:35:39.727895
2020-08-03T15:47:37
2020-08-03T15:47:37
284,734,310
0
0
null
null
null
null
UTF-8
Python
false
false
4,898
py
import math import yaml import h5py import json import argparse import numpy as np from keras.models import model_from_json from keras.models import model_from_yaml from keras.models import load_model from sklearn.utils import shuffle def get_parser(): parser = argparse.ArgumentParser( description='Run CalGAN training. ' 'Sensible defaults come from [arXiv/1511.06434]', formatter_class=argparse.ArgumentDefaultsHelpFormatter ) parser.add_argument('--batch-size', action='store', type=int, default=2, help='batch size per update') parser.add_argument('--disc-lr', action='store', type=float, default=2e-5, help='Adam learning rate for discriminator') parser.add_argument('--gen-lr', action='store', type=float, default=2e-4, help='Adam learning rate for generator') parser.add_argument('--adam-beta', action='store', type=float, default=0.5, help='Adam beta_1 parameter') parser.add_argument('--prog-bar', action='store_true', help='Whether or not to use a progress bar') parser.add_argument('--no-attn', action='store_true', help='Whether to turn off the layer to layer attn.') parser.add_argument('--debug', action='store_true', help='Whether to run debug level logging') parser.add_argument('--model-in', action='store',type=str, default='', help='input of trained reg model') parser.add_argument('--weight-in', action='store',type=str, default='', help='input of trained reg weight') parser.add_argument('--datafile', action='store', type=str, help='yaml file with particles and HDF5 paths (see ' 'github.com/hep-lbdl/CaloGAN/blob/master/models/' 'particles.yaml)') parser.add_argument('--output', action='store',type=str, default='', help='output of result real vs reco') return parser if __name__ == '__main__': parser = get_parser() parse_args = parser.parse_args() model = load_model(parse_args.model_in) d = h5py.File(parse_args.datafile, 'r') first = np.expand_dims(d['firstHitTimeByPMT'][:], -1) second = np.expand_dims(d['nPEByPMT'][:], -1) infoMuon = d['infoMuon'][:,:4] d.close() print('infoMuon dtype',infoMuon.dtype) infoMuon = infoMuon.astype(float) print('infoMuon dtype',infoMuon.dtype) ### normalize muon info ############## infoMuon[:,0]=(infoMuon[:,0])/math.pi infoMuon[:,1]=(infoMuon[:,1])/math.pi infoMuon[:,2]=(infoMuon[:,2])/math.pi infoMuon[:,3]=(infoMuon[:,3])/math.pi #infoMuon[:,4]=(infoMuon[:,4])/18000#17700.0 first, second, infoMuon = shuffle(first, second, infoMuon, random_state=0) nBatch = int(first.shape[0]/parse_args.batch_size) iBatch = np.random.randint(nBatch, size=1) iBatch = iBatch[0] input_first = first [iBatch*parse_args.batch_size:(iBatch+1)*parse_args.batch_size] input_second = second[iBatch*parse_args.batch_size:(iBatch+1)*parse_args.batch_size] result = model.predict([input_first, input_second], verbose=True) ptheta = result[0] pphi = result[1] rtheta = result[2] rphi = result[3] print('ptheta:',ptheta[:10]) print('pphi:' ,pphi [:10]) print('rtheta:',rtheta[:10]) print('rphi:' ,rphi [:10]) result = np.concatenate((ptheta, pphi, rtheta, rphi),axis=-1) real = infoMuon[iBatch*parse_args.batch_size:(iBatch+1)*parse_args.batch_size] result1= model.test_on_batch([input_first, input_second],[real[:,0], real[:,1], real[:,2], real[:,3]]) result2= model.predict_on_batch([input_first, input_second]) print('test_on_batch:', result1) print('predict_on_batch:', result2) print('choose batch:', iBatch) print('pred:\n',result) print('real:\n',real) print('diff:\n',result - real) ######### transfer to actual value ####### real[:,0] = real[:,0]*math.pi real[:,1] = real[:,1]*math.pi real[:,2] = real[:,2]*math.pi real[:,3] = real[:,3]*math.pi #real[:,4] = real[:,4]*18000 result[:,0] = result[:,0]*math.pi result[:,1] = result[:,1]*math.pi result[:,2] = result[:,2]*math.pi result[:,3] = result[:,3]*math.pi #result[:,4] = result[:,4]*18000 abs_diff = np.abs(result - real) print('abs error:\n', abs_diff) print('mean abs error:\n',np.mean(abs_diff, axis=0)) print('std abs error:\n',np.std (abs_diff, axis=0)) ###### save ########## hf = h5py.File(parse_args.output, 'w') hf.create_dataset('input_info', data=real) hf.create_dataset('reco_info' , data=result) hf.close() print ('Done')
[ "1473717798@qq.com" ]
1473717798@qq.com
958e66963b687952abe54f34a00c7cef057ef540
8afb5afd38548c631f6f9536846039ef6cb297b9
/MY_REPOS/Lambda-Resource-Static-Assets/2-resources/_External-learning-resources/02-pyth/Python-master/ciphers/hill_cipher.py
bc8f5b41b624ca389e5279c713516e329ed4da0f
[ "MIT" ]
permissive
bgoonz/UsefulResourceRepo2.0
d87588ffd668bb498f7787b896cc7b20d83ce0ad
2cb4b45dd14a230aa0e800042e893f8dfb23beda
refs/heads/master
2023-03-17T01:22:05.254751
2022-08-11T03:18:22
2022-08-11T03:18:22
382,628,698
10
12
MIT
2022-10-10T14:13:54
2021-07-03T13:58:52
null
UTF-8
Python
false
false
7,549
py
""" Hill Cipher: The 'HillCipher' class below implements the Hill Cipher algorithm which uses modern linear algebra techniques to encode and decode text using an encryption key matrix. Algorithm: Let the order of the encryption key be N (as it is a square matrix). Your text is divided into batches of length N and converted to numerical vectors by a simple mapping starting with A=0 and so on. The key is then multiplied with the newly created batch vector to obtain the encoded vector. After each multiplication modular 36 calculations are performed on the vectors so as to bring the numbers between 0 and 36 and then mapped with their corresponding alphanumerics. While decrypting, the decrypting key is found which is the inverse of the encrypting key modular 36. The same process is repeated for decrypting to get the original message back. Constraints: The determinant of the encryption key matrix must be relatively prime w.r.t 36. Note: This implementation only considers alphanumerics in the text. If the length of the text to be encrypted is not a multiple of the break key(the length of one batch of letters), the last character of the text is added to the text until the length of the text reaches a multiple of the break_key. So the text after decrypting might be a little different than the original text. References: https://apprendre-en-ligne.net/crypto/hill/Hillciph.pdf https://www.youtube.com/watch?v=kfmNeskzs2o https://www.youtube.com/watch?v=4RhLNDqcjpA """ import string import numpy def greatest_common_divisor(a: int, b: int) -> int: """ >>> greatest_common_divisor(4, 8) 4 >>> greatest_common_divisor(8, 4) 4 >>> greatest_common_divisor(4, 7) 1 >>> greatest_common_divisor(0, 10) 10 """ return b if a == 0 else greatest_common_divisor(b % a, a) class HillCipher: key_string = string.ascii_uppercase + string.digits # This cipher takes alphanumerics into account # i.e. a total of 36 characters # take x and return x % len(key_string) modulus = numpy.vectorize(lambda x: x % 36) to_int = numpy.vectorize(lambda x: round(x)) def __init__(self, encrypt_key: numpy.ndarray) -> None: """ encrypt_key is an NxN numpy array """ self.encrypt_key = self.modulus(encrypt_key) # mod36 calc's on the encrypt key self.check_determinant() # validate the determinant of the encryption key self.break_key = encrypt_key.shape[0] def replace_letters(self, letter: str) -> int: """ >>> hill_cipher = HillCipher(numpy.array([[2, 5], [1, 6]])) >>> hill_cipher.replace_letters('T') 19 >>> hill_cipher.replace_letters('0') 26 """ return self.key_string.index(letter) def replace_digits(self, num: int) -> str: """ >>> hill_cipher = HillCipher(numpy.array([[2, 5], [1, 6]])) >>> hill_cipher.replace_digits(19) 'T' >>> hill_cipher.replace_digits(26) '0' """ return self.key_string[round(num)] def check_determinant(self) -> None: """ >>> hill_cipher = HillCipher(numpy.array([[2, 5], [1, 6]])) >>> hill_cipher.check_determinant() """ det = round(numpy.linalg.det(self.encrypt_key)) if det < 0: det = det % len(self.key_string) req_l = len(self.key_string) if greatest_common_divisor(det, len(self.key_string)) != 1: raise ValueError( f"determinant modular {req_l} of encryption key({det}) is not co prime " f"w.r.t {req_l}.\nTry another key." ) def process_text(self, text: str) -> str: """ >>> hill_cipher = HillCipher(numpy.array([[2, 5], [1, 6]])) >>> hill_cipher.process_text('Testing Hill Cipher') 'TESTINGHILLCIPHERR' >>> hill_cipher.process_text('hello') 'HELLOO' """ chars = [char for char in text.upper() if char in self.key_string] last = chars[-1] while len(chars) % self.break_key != 0: chars.append(last) return "".join(chars) def encrypt(self, text: str) -> str: """ >>> hill_cipher = HillCipher(numpy.array([[2, 5], [1, 6]])) >>> hill_cipher.encrypt('testing hill cipher') 'WHXYJOLM9C6XT085LL' >>> hill_cipher.encrypt('hello') '85FF00' """ text = self.process_text(text.upper()) encrypted = "" for i in range(0, len(text) - self.break_key + 1, self.break_key): batch = text[i : i + self.break_key] vec = [self.replace_letters(char) for char in batch] batch_vec = numpy.array([vec]).T batch_encrypted = self.modulus(self.encrypt_key.dot(batch_vec)).T.tolist()[ 0 ] encrypted_batch = "".join( self.replace_digits(num) for num in batch_encrypted ) encrypted += encrypted_batch return encrypted def make_decrypt_key(self) -> numpy.ndarray: """ >>> hill_cipher = HillCipher(numpy.array([[2, 5], [1, 6]])) >>> hill_cipher.make_decrypt_key() array([[ 6, 25], [ 5, 26]]) """ det = round(numpy.linalg.det(self.encrypt_key)) if det < 0: det = det % len(self.key_string) det_inv = None for i in range(len(self.key_string)): if (det * i) % len(self.key_string) == 1: det_inv = i break inv_key = ( det_inv * numpy.linalg.det(self.encrypt_key) * numpy.linalg.inv(self.encrypt_key) ) return self.to_int(self.modulus(inv_key)) def decrypt(self, text: str) -> str: """ >>> hill_cipher = HillCipher(numpy.array([[2, 5], [1, 6]])) >>> hill_cipher.decrypt('WHXYJOLM9C6XT085LL') 'TESTINGHILLCIPHERR' >>> hill_cipher.decrypt('85FF00') 'HELLOO' """ decrypt_key = self.make_decrypt_key() text = self.process_text(text.upper()) decrypted = "" for i in range(0, len(text) - self.break_key + 1, self.break_key): batch = text[i : i + self.break_key] vec = [self.replace_letters(char) for char in batch] batch_vec = numpy.array([vec]).T batch_decrypted = self.modulus(decrypt_key.dot(batch_vec)).T.tolist()[0] decrypted_batch = "".join( self.replace_digits(num) for num in batch_decrypted ) decrypted += decrypted_batch return decrypted def main() -> None: N = int(input("Enter the order of the encryption key: ")) hill_matrix = [] print("Enter each row of the encryption key with space separated integers") for _ in range(N): row = [int(x) for x in input().split()] hill_matrix.append(row) hc = HillCipher(numpy.array(hill_matrix)) print("Would you like to encrypt or decrypt some text? (1 or 2)") option = input("\n1. Encrypt\n2. Decrypt\n") if option == "1": text_e = input("What text would you like to encrypt?: ") print("Your encrypted text is:") print(hc.encrypt(text_e)) elif option == "2": text_d = input("What text would you like to decrypt?: ") print("Your decrypted text is:") print(hc.decrypt(text_d)) if __name__ == "__main__": import doctest doctest.testmod() main()
[ "bryan.guner@gmail.com" ]
bryan.guner@gmail.com
4f6b1dc211e4bc1cc3ec122d5bc8cba70661d87d
f11600b9a256bf6a2b584d127faddc27a0f0b474
/normal/1401.py
52bff56683cf923937222e17b79a7c0999757b14
[]
no_license
longhao54/leetcode
9c1f0ce4ca505ec33640dd9b334bae906acd2db5
d156c6a13c89727f80ed6244cae40574395ecf34
refs/heads/master
2022-10-24T07:40:47.242861
2022-10-20T08:50:52
2022-10-20T08:50:52
196,952,603
0
0
null
null
null
null
UTF-8
Python
false
false
1,121
py
class Solution: def checkOverlap(self, radius: int, x_center: int, y_center: int, x1: int, y1: int, x2: int, y2: int) -> bool: # 条件 1:首先判断圆心是否在矩形内 if x1 <= x_center <= x2 and y1 <= y_center <= y2: return True # 条件 2:圆心位于矩形的上下左右四个区域 elif x_center > x2 and y1 <= y_center <= y2: # 右 return radius >= x_center - x2 elif y_center < y1 and x1 <= x_center <= x2: # 下 return radius >= y1 - y_center elif x_center < x1 and y1<= y_center <= y2: # 左 return radius >= x1 - x_center elif y_center > y2 and x1 <= x_center <= x2: # 上 return radius >= y_center - y2 else: # 条件 3:判断矩形的四个顶点是否在圆的内部 return min((x1 - x_center) ** 2 + (y2 - y_center) ** 2,\ (x2 - x_center) ** 2 + (y2 - y_center) ** 2, \ (x2 - x_center) ** 2 + (y1 - y_center) ** 2, \ (x1 - x_center) ** 2 + (y1 - y_center) ** 2) <= radius ** 2
[ "jinlha@jiedaibao.com" ]
jinlha@jiedaibao.com
af24b9455252c6b9b58c9672b4c0a8a22e0657eb
334fafa9d87fdd13cc549a662a0cf35c47f2d5e3
/backend/data/bahn/bahnscript/bahn2.py
9738bfe0b9f26768f010e9a577d6262182208138
[]
no_license
Jugendhackt/apartmapp
27cd7c17e808a6948f017043e61ebd5480e87c89
0fded8e1da75a021547b53d68e88e9db524b088e
refs/heads/master
2021-01-15T14:31:43.959035
2014-06-08T12:10:04
2014-06-08T12:10:04
null
0
0
null
null
null
null
UTF-8
Python
false
false
530
py
import json, psycopg2 filename = "plankgeo_data.json" def trains(filename): con = psycopg2.connect(database='appartmapp', user='postgres') cur = con.cursor() with open(filename, "r") as data: json_encoded = json.loads(data.read()) data.close() # print to screen print json_encoded[0]['lat'] for entry in json_encoded: cur.execute("INSERT INTO items(name, type, picture, lat, lng)VALUES(%s, 'dbstop', 'dbstop.jpg', %s, %s)", (entry['id'], entry['lat'], entry['lon'])) con.commit() con.close() trains(filename)
[ "me@me.com" ]
me@me.com
9a7032fb4a6c3a4c73af2c3f8c631ba5100585c7
638b207f3c7706cb0cb9dd1d6cf112ab91f69837
/0x11-python-network_1/5-hbtn_header.py
c0286a8b9aaaf86889e63216152a5918919ad69c
[]
no_license
NasserAbuchaibe/holbertonschool-higher_level_programming
c30a066dfd4525e936b4121f930c3a63e6d911d6
5b0c11423e11bd9201cc057775c099eb0259f305
refs/heads/master
2022-12-16T17:15:57.775143
2020-09-25T03:00:56
2020-09-25T03:00:56
259,379,453
1
0
null
null
null
null
UTF-8
Python
false
false
204
py
#!/usr/bin/python3 """ Response header value """ import requests from sys import argv if __name__ == "__main__": """ok """ r = requests.get(argv[1]) print(r.headers.get('X-Request-Id'))
[ "nasser_abuchaibe@hotmail.com" ]
nasser_abuchaibe@hotmail.com
684bb9b634cf46ead79b715049cf84129c8f2ed3
4bc25aaf986e481a533e22a7d74e963a18499593
/Chapitre_5/visionneuse_1.py
84b18735cbfc634e5f5e849a5feb1d38c636cf5d
[]
no_license
EditionsENI/python-raspberrypi-3e-edition
c5dd3be2cbc7e52793361f2a601b100011ea535d
f189aefc5ea0b265fd664c8a47dcde6cd110a8b0
refs/heads/master
2023-04-10T18:59:35.922958
2021-04-19T21:47:29
2021-04-19T21:47:29
317,060,608
0
0
null
null
null
null
UTF-8
Python
false
false
3,780
py
#!/usr/bin/env python3 import glob import sys import os from tkinter import PhotoImage from tkinter import Message from tkinter import Button from tkinter import Frame from tkinter import Label from tkinter import Tk from tkinter import BOTTOM from tkinter import LEFT from tkinter import BOTH from tkinter import YES class PiVision(Tk): def __init__(self, images): Tk.__init__(self) self.creer_composants() if len(images) > 0: self.initialiser_images() self.afficher_image() else: self.afficher_erreur() self.mainloop() def initialiser_images(self): liste_image = [(PhotoImage(file=image), os.path.basename(image)) for image in sorted(images)] premiere = derniere = VImage(info=liste_image.pop(0)) for image in liste_image: derniere = derniere.ajout(info=image) derniere.suivante = premiere premiere.precedente = derniere self.image_courante = premiere def creer_composants(self): self.composant_image = Label(self) self.composant_image.pack(expand=YES, fill=BOTH) self.bouton_frame = Frame(self) self.bouton_frame.pack(side=BOTTOM) self.bouton_precedent = Button( self.bouton_frame, text="Précédent", command=lambda: self.image_precedente()) self.bouton_precedent.pack(side=LEFT) self.bouton_suivant = Button( self.bouton_frame, text="Suivant", command=lambda: self.image_suivante()) self.bouton_suivant.pack(side=LEFT) self.bouton_fermer = Button( self.bouton_frame, text="Fermer", command=self.destroy) self.bouton_fermer.pack(side=LEFT) self.bind("<Left>", lambda ev: self.image_precedente()) self.bind("<Right>", lambda ev: self.image_suivante()) self.bind("<Escape>", lambda ev: self.destroy()) def image_suivante(self): self.image_courante = self.image_courante.suivante self.afficher_image() def image_precedente(self): self.image_courante = self.image_courante.precedente self.afficher_image() def afficher_image(self): image, nom_image = self.image_courante.info self.composant_image.config(image=image) self.title("%s - %s " % (self.__class__.__name__, nom_image)) self.update() def afficher_erreur(self): self.bouton_precedent.configure(state="disable") self.bouton_suivant.configure(state="disable") self.unbind("<Left>") self.unbind("<Right>") self.erreur = Message(self.composant_image, text="Aucune image n'a été trouvée !", pady=25, padx=25, aspect=800) self.erreur.config(font=("courier", 14, "bold")) self.erreur.pack(expand=YES, fill=BOTH) self.title("Erreur !") self.update() class VImage: def __init__(self, info, suivante=None, precedente=None): self.info = info self.suivante = suivante self.precedente = precedente def ajout(self, info): self.suivante = VImage(info, None, self) return self.suivante if __name__ == "__main__": def usage(message=""): print(message) sys.exit(1) if len(sys.argv) != 2: usage("Veuillez indiquer un répertoire!") repertoire = sys.argv[1] if not os.path.isdir(repertoire): usage(f"\"{repertoire}\" n'est pas un répertoire!") extensions = "png jpg jpeg gif".split() extensions = extensions + list(map(str.upper, extensions)) images = [] for ext in extensions: images.append(glob.glob(f"{repertoire}/*.{ext}")) images = sum(images, []) PiVision(images)
[ "monsieurp@gentoo.org" ]
monsieurp@gentoo.org
a29bbe7d2c8cb74beba2552e92cb4abc19df3926
b773ff8595421fb743e55f7bc0190791f2ece7a2
/backend/home/migrations/0002_load_initial_data.py
eb446cfe1a0a9a986553ca35b2a5b469e122a3f3
[]
no_license
crowdbotics-apps/msm-tc208-fzjohztpg-12768
d68746372f604aa5ec805c7c4c480eb451d2b96d
016bfac5d6497dbd88b49eddc4b8f74788161c83
refs/heads/master
2022-12-28T04:01:12.567205
2020-10-06T05:28:05
2020-10-06T05:28:05
301,622,954
0
0
null
null
null
null
UTF-8
Python
false
false
1,333
py
from django.db import migrations def create_customtext(apps, schema_editor): CustomText = apps.get_model("home", "CustomText") customtext_title = "MSM-TC208-fzjohztpgt" CustomText.objects.create(title=customtext_title) def create_homepage(apps, schema_editor): HomePage = apps.get_model("home", "HomePage") homepage_body = """ <h1 class="display-4 text-center">MSM-TC208-fzjohztpgt</h1> <p class="lead"> This is the sample application created and deployed from the Crowdbotics app. You can view list of packages selected for this application below. </p>""" HomePage.objects.create(body=homepage_body) def create_site(apps, schema_editor): Site = apps.get_model("sites", "Site") custom_domain = "msm-tc208-fzjohztpg-12768.botics.co" site_params = { "name": "MSM-TC208-fzjohztpgt", } if custom_domain: site_params["domain"] = custom_domain Site.objects.update_or_create(defaults=site_params, id=1) class Migration(migrations.Migration): dependencies = [ ("home", "0001_initial"), ("sites", "0002_alter_domain_unique"), ] operations = [ migrations.RunPython(create_customtext), migrations.RunPython(create_homepage), migrations.RunPython(create_site), ]
[ "team@crowdbotics.com" ]
team@crowdbotics.com
7d5d3566f8081503f4981349ffda1b3bdbd985ce
469456a0bf4c7c040a8136b111195a82de17cc6b
/rgb_module.py
40e20d6431581e0f70174a91bfb45c03869c9133
[]
no_license
6reg/function_fun
d2e73387e78396618d074c97a2b0088647693b4e
64bf2d6211f9bdcc030922a7f5292c37a31eddd9
refs/heads/main
2023-07-07T23:42:46.426225
2021-08-07T22:10:47
2021-08-07T22:10:47
370,854,414
0
1
null
2021-07-07T02:20:18
2021-05-25T23:39:07
Python
UTF-8
Python
false
false
666
py
DATA_FILE = "./rgb_values.txt" def load_data(): data = {} file = open(DATA_FILE) n_colors = 0 for line in file: line = line.strip() add_color(data, line) n_colors += 1 print(len(data), n_colors) file.close() return data def add_color(data, line): parts = line.split(',') color_name = parts[0] color_rgb = color_from_line(line) if color_name not in data: data[color_name] = [] data[color_name].append(color_rgb) def color_from_line(line): parts = line.split(',') print(parts) r = int(parts[1]) g = int(parts[2]) b = int(parts[3]) return [r, g, b] load_data()
[ "mathiasgreg@gmail.com" ]
mathiasgreg@gmail.com
fe75aa03e43019e1066a7e638a69ca2612f323d6
91ca2b4215b74c3b3f2517baab9205997c9bcf62
/maps/migrations/0009_auto_20180205_1945.py
319e4b341f7faee495ba53495621ba57b938524c
[ "Apache-2.0" ]
permissive
swiftlabUAS/SwiftUTM
ae0ca347058563a040c24b740a5760187e507879
caf40195b017ab980323cf88bf95e671e38a2676
refs/heads/master
2022-12-16T00:02:01.766221
2020-09-22T14:27:12
2020-09-22T14:27:12
297,254,220
0
1
MIT
2020-09-22T14:27:14
2020-09-21T06:55:30
null
UTF-8
Python
false
false
487
py
# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2018-02-05 16:45 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('maps', '0008_locationpoints_shortcode'), ] operations = [ migrations.AlterField( model_name='locationpoints', name='shortcode', field=models.CharField(blank=True, max_length=3, null=True), ), ]
[ "geoffreynyagak@gmail.com" ]
geoffreynyagak@gmail.com
83a06f4dcd736336f0501d6bd4aa3a13a87113b8
7024d0fab7adee2937ddab28a2b69481ef76f9a8
/llvm-archive/hlvm/build/bytecode.py
e21978e91a6f32943d5ac37306068592af7b29a3
[]
no_license
WeilerWebServices/LLVM
5b7927da69676a7c89fc612cfe54009852675450
1f138562730a55380ea3185c7aae565d7bc97a55
refs/heads/master
2022-12-22T09:05:27.803365
2020-09-24T02:50:38
2020-09-24T02:50:38
297,533,828
0
0
null
null
null
null
UTF-8
Python
false
false
2,843
py
from SCons.Environment import Environment as Environment import re,fileinput,os from string import join as sjoin from os.path import join as pjoin def AsmFromBytecodeMessage(target,source,env): return "Generating Native Assembly From LLVM Bytecode" + source[0].path def AsmFromBytecodeAction(target,source,env): theAction = env.Action(env['with_llc'] + ' -f -fast -o ' + target[0].path + ' ' + source[0].path) env.Depends(target,env['with_llc']) return env.Execute(theAction) def BytecodeFromAsmMessage(target,source,env): return "Generating Bytecode From LLVM Assembly " + source[0].path def BytecodeFromAsmAction(target,source,env): theAction = env.Action(env['with_llvmas'] + ' -f -o ' + target[0].path + ' ' + source[0].path + ' ' + env['LLVMASFLAGS']) env.Depends(target,env['with_llvmas']) return env.Execute(theAction); def BytecodeFromCppMessage(target,source,env): return "Generating Bytecode From C++ Source " + source[0].path def BytecodeFromCppAction(target,source,env): includes = "" for inc in env['CPPPATH']: if inc[0] == '#': inc = env['AbsSrcRoot'] + inc[1:] includes += " -I" + inc defines = "" for d in env['CPPDEFINES'].keys(): if env['CPPDEFINES'][d] == None: defines += " -D" + d else: defines += " -D" + d + "=" + env['CPPDEFINES'][d] src = source[0].path tgt = target[0].path theAction = env.Action( env['with_llvmgxx'] + ' $CXXFLAGS ' + includes + defines + " -c -emit-llvm -g -O3 -x c++ " + src + " -o " + tgt ) env.Depends(target,env['with_llvmgxx']) return env.Execute(theAction); def BytecodeArchiveMessage(target,source,env): return "Generating Bytecode Archive From Bytecode Modules" def BytecodeArchiveAction(target,source,env): sources = '' for src in source: sources += ' ' + src.path theAction = env.Action( env['with_llvmar'] + ' cr ' + target[0].path + sources) env.Depends(target[0],env['with_llvmar']) return env.Execute(theAction); def Bytecode(env): bc2s = env.Action(AsmFromBytecodeAction,AsmFromBytecodeMessage) ll2bc = env.Action(BytecodeFromAsmAction,BytecodeFromAsmMessage) cpp2bc = env.Action(BytecodeFromCppAction,BytecodeFromCppMessage) arch = env.Action(BytecodeArchiveAction,BytecodeArchiveMessage) bc2s_bldr = env.Builder(action=bc2s,suffix='s',src_suffix='bc', single_source=1) ll2bc_bldr = env.Builder(action=ll2bc,suffix='bc',src_suffix='ll', single_source=1) cpp2bc_bldr = env.Builder(action=cpp2bc,suffix='bc',src_suffix='cpp', single_source=1) arch_bldr = env.Builder(action=arch,suffix='bca',src_suffix='bc', src_builder=[ cpp2bc_bldr,ll2bc_bldr]) env.Append(BUILDERS = { 'll2bc':ll2bc_bldr, 'cpp2bc':cpp2bc_bldr, 'bc2s':bc2s_bldr, 'BytecodeArchive':arch_bldr }) return 1
[ "nateweiler84@gmail.com" ]
nateweiler84@gmail.com
56f7c3b75781176c8c211e3d1a86345e6544e8be
ae74e9e03e9b8ba1d407bd5907d3fe197ce47a44
/ggplot/04-graphs.py
8d7d9c715bd502c503e9f71fb44de994503d773c
[]
no_license
dylanjorgensen/modules
3f937298df6b1da0851cfbc4cbf6f046b81b303c
9296284d3acdb0f899ad19f013fff4d73d0fcc0b
refs/heads/master
2021-01-11T03:23:11.591989
2016-10-22T01:21:53
2016-10-22T01:21:53
71,014,891
1
0
null
null
null
null
UTF-8
Python
false
false
1,055
py
from ggplot import * import pandas as pd import numpy as np # Generate data df = pd.read_csv("baseball-pitches-clean.csv") df = df[['pitch_time', 'inning', 'pitcher_name', 'hitter_name', 'pitch_type', 'px', 'pz', 'pitch_name', 'start_speed', 'end_speed', 'type_confidence']] print df.head() # print df.dtypes # Strike "scatterplot" # print ggplot(df, aes(x='px', y='pz')) + geom_point() # Basic "histogram" print ggplot(df, aes(x='start_speed')) + geom_histogram() # Basic "facet wrap" # print ggplot(aes(x='start_speed'), data=df) + geom_histogram() + facet_wrap('pitch_name') # Basic "bar graph" # print ggplot(aes(x='pitch_type'), data=df) + geom_bar() # Basic "facet grid" # This lines up the grid for comparison # print ggplot(aes(x='start_speed'), data=df) + geom_histogram() + facet_grid('pitch_type') # Basic "geom density" # To compare various categorical frequency's in the same field # print ggplot(df, aes(x='start_speed')) + geom_density() # print ggplot(df, aes(x='start_speed', color='pitch_name')) + geom_density()
[ "dylan@dylanjorgensen.com" ]
dylan@dylanjorgensen.com
6de8a8e58c7239a48d420c9f23e548175002d66e
44eb40bf7bbd006f441b22d149dbb06eebe97506
/src/chap05/gradient_check.py
f9819365dec71b653a1702cc28bc95aa3ac59923
[]
no_license
hoonest/Deep_Learning
56939f983c81e75b79d5474c11649dd57bf7107b
dd94f46ff886f20a47b09a54593e5fd2d53f0ed4
refs/heads/master
2020-04-19T22:52:03.640247
2019-02-19T03:34:16
2019-02-19T03:34:16
168,481,590
0
0
null
null
null
null
UTF-8
Python
false
false
769
py
# coding: utf-8 import sys, os sys.path.append(os.pardir) # 부모 디렉터리의 파일을 가져올 수 있도록 설정 import numpy as np from src.dataset.mnist import load_mnist from src.chap05.two_layer_net import TwoLayerNet # 데이터 읽기 (x_train, t_train), (x_test, t_test) = load_mnist(normalize=True, one_hot_label=True) network = TwoLayerNet(input_size=784, hidden_size=50, output_size=10) x_batch = x_train[:3] t_batch = t_train[:3] grad_numerical = network.numerical_gradient(x_batch, t_batch) grad_backprop = network.gradient(x_batch, t_batch) # 각 가중치의 절대 오차의 평균을 구한다. for key in grad_numerical.keys(): diff = np.average( np.abs(grad_backprop[key] - grad_numerical[key]) ) print(key + ":" + str(diff))
[ "hoonest01@gmail.com" ]
hoonest01@gmail.com
beda1750d055f278c7feba99c51342ec22251e02
2d4e020e6ab48c46e0a19cb69048d9e8d26e46a6
/Job_Portal/job_portal/main/migrations/0005_auto_20210202_0143.py
94b50b03f39910c2733310db1be8d839c9c1ae73
[]
no_license
IsmailTitas1815/Learning
a92476fcf7bcd28a7dc1ab2f4eb3a5c27034728f
207eaf4101a6d161c1044310f4b3cc54e9c514eb
refs/heads/master
2023-07-04T20:13:07.263331
2021-08-07T20:07:39
2021-08-07T20:07:39
293,100,950
0
0
null
2021-05-07T16:55:29
2020-09-05T15:18:46
Python
UTF-8
Python
false
false
577
py
# Generated by Django 3.1.5 on 2021-02-01 19:43 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('main', '0004_auto_20210202_0138'), ] operations = [ migrations.RemoveField( model_name='candidate', name='tag', ), migrations.AddField( model_name='candidate', name='tag', field=models.OneToOneField(null=True, on_delete=django.db.models.deletion.CASCADE, to='main.tag'), ), ]
[ "titas.sarker1234@gmail.com" ]
titas.sarker1234@gmail.com
cf08ddf5aa4fd4f0d5bbd4c4f17f8720aa26e1c0
bb0f5ec6ee0ed99afb09087ff0ea9bfe32b7ea49
/utills/amount.py
87463e68aad88f653aba56ac9ab975e44a5ea3b3
[]
no_license
persontianshuang/lottery_admin
49f3386d75671d0b2c43dfea3987e7fa8df84c9b
d8ebc7cf778cac24055a709886fbaa3b03325a69
refs/heads/master
2021-09-03T10:04:40.151502
2018-01-08T08:09:50
2018-01-08T08:09:50
111,886,585
0
0
null
null
null
null
UTF-8
Python
false
false
1,423
py
import random,time from datetime import datetime class AmountCommon(): def __init__(self,db): self.db = db def sum_amount(self, db): return sum([x.amount for x in db]) def all(self): return str(self.sum_amount(self.db)) def today(self): t = time.localtime(time.time()) time1 = time.mktime(time.strptime(time.strftime('%Y-%m-%d 00:00:00', t), '%Y-%m-%d %H:%M:%S')) today_zero = int(time1) now = int(time.time()) tdb = self.db.filter(created__range=(today_zero, now)) return str(self.sum_amount(tdb)) def this_month(self): d = datetime.now() b = '{0}-{1}-1 00:00:00'.format(d.year, d.month) month_zero = int(time.mktime(time.strptime(b, "%Y-%m-%d %H:%M:%S"))) now = int(time.time()) tdb = self.db.filter(created__range=(month_zero, now)) return str(self.sum_amount(tdb)) def time_formater(self,year,month,day): b = '{0}-{1}-{2} 00:00:00'.format(year, month, day) month_zero = int(time.mktime(time.strptime(b, "%Y-%m-%d %H:%M:%S"))) return month_zero def time_range(self,last,now): tlast = self.time_formater(last[0], last[1], last[2]) tnow = self.time_formater(now[0], now[1], now[2]) tdb = self.db.filter(created__range=(tlast, tnow)) return str(self.sum_amount(tdb))
[ "mengyouhan@gmail.com" ]
mengyouhan@gmail.com
d0cca4222c8b6367b193a93bbb16784b03bdbf6d
0bd3e809967ce2e02353a1c5559725bf3c9b6a7e
/update_bind_conf_gw.py
dc4273fb723c2b745ee9c0d667b3be3768301f8e
[]
no_license
ka-ba/backend-scripts
79ea992852d4afaf24c1cd60146be1e3df06aa20
87ddce68d224a13f7062d8ec3825a46fb98fa343
refs/heads/master
2021-01-20T03:01:53.095776
2015-04-21T13:13:27
2015-04-21T13:13:27
27,978,828
0
0
null
2015-04-21T12:49:20
2014-12-14T00:50:09
Python
UTF-8
Python
false
false
1,114
py
#!/usr/bin/env python3 def update_bind_conf(): from photon.util.files import read_file from common import pinit photon, settings = pinit('update_bind_conf', verbose=True) for repo in ['scripts', 'meta']: photon.git_handler( settings['icvpn']['icdns'][repo]['local'], remote_url=settings['icvpn']['icdns'][repo]['remote'] )._pull() bind_conf = photon.template_handler('${config_content}') config_content=photon.m( 'genarating bind conf', cmdd=dict( cmd='./mkdns -f bind -s %s -x mainz -x wiesbaden' %(settings['icvpn']['icdns']['meta']['local']), cwd=settings['icvpn']['icdns']['scripts']['local']\ ) ).get('out') bind_conf.sub = dict(config_content=config_content) conf = settings['icvpn']['icdns']['conf'] if bind_conf.sub != read_file(conf): bind_conf.write(conf, append=False) photon.m( 'reloading bind daemon', cmdd=dict( cmd='sudo rndc reload' ) ) if __name__ == '__main__': update_bind_conf()
[ "frieder.griesshammer@der-beweis.de" ]
frieder.griesshammer@der-beweis.de
54aa72c6ca565b7aa1d189e7744b9fcb0f24dd40
d09c6ff7114f69a9326883c5b9fcc70fa994e8a2
/_pycharm_skeletons/renderdoc/GLVertexAttribute.py
add4c7232eea14baa06e4a12c24a237ae897c01a
[ "MIT" ]
permissive
Lex-DRL/renderdoc-py-stubs
3dd32d23c0c8219bb66387e6078244cff453cd83
75d280e4f500ded506f3315a49fc432b37ab4fa6
refs/heads/master
2020-08-22T16:55:39.336657
2019-11-03T01:21:26
2019-11-03T01:21:26
216,441,308
0
0
null
null
null
null
UTF-8
Python
false
false
2,700
py
# encoding: utf-8 # module renderdoc # from P:\1-Scripts\_Python\Py-Autocomplete\renderdoc.pyd # by generator 1.146 # no doc # imports import enum as __enum from .SwigPyObject import SwigPyObject class GLVertexAttribute(SwigPyObject): """ Describes the configuration for a single vertex attribute. .. note:: If old-style vertex attrib pointer setup was used for the vertex attributes then it will be decomposed into 1:1 attributes and buffers. """ def __eq__(self, *args, **kwargs): # real signature unknown """ Return self==value. """ pass def __ge__(self, *args, **kwargs): # real signature unknown """ Return self>=value. """ pass def __gt__(self, *args, **kwargs): # real signature unknown """ Return self>value. """ pass def __hash__(self, *args, **kwargs): # real signature unknown """ Return hash(self). """ pass def __init__(self, *args, **kwargs): # real signature unknown pass def __le__(self, *args, **kwargs): # real signature unknown """ Return self<=value. """ pass def __lt__(self, *args, **kwargs): # real signature unknown """ Return self<value. """ pass @staticmethod # known case of __new__ def __new__(*args, **kwargs): # real signature unknown """ Create and return a new object. See help(type) for accurate signature. """ pass def __ne__(self, *args, **kwargs): # real signature unknown """ Return self!=value. """ pass byteOffset = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """ The byte offset from the start of the vertex data in the vertex buffer from :data:`vertexBufferSlot`. """ enabled = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """``True`` if this vertex attribute is enabled.""" format = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """The :class:`ResourceFormat` of the vertex attribute.""" genericValue = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """A :class:`PixelValue` containing the generic value of a vertex attribute.""" this = property(lambda self: object(), lambda self, v: None, lambda self: None) # default thisown = property(lambda self: object(), lambda self, v: None, lambda self: None) # default vertexBufferSlot = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """The vertex buffer input slot where the data is sourced from.""" __dict__ = None # (!) real value is ''
[ "drl.i3x@gmail.com" ]
drl.i3x@gmail.com
a68196f031bbeb0ba2c2698e025995cba76ce678
44a724fbac833f10c73a70f140d6c6692d4c758e
/website/registration/forms.py
da51b193f26f02d67afbf28c947ebf07d916cf8e
[]
no_license
Nussy/owf2014
856598b414a58ef5065481dad66841fb9fb01f7d
09224a3ab82d5ceabe286678bae77967be42537c
refs/heads/master
2020-12-24T11:33:49.230217
2014-07-08T12:15:04
2014-07-08T12:15:18
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,126
py
from flask.ext.wtf import Form, BooleanField, TextField, TextAreaField, required, email from flask.ext.wtf.html5 import EmailField from flask.ext.babel import lazy_gettext as _l from website.registration.models import Track __all__ = ['RegistrationForm'] def make_mixin_class(): class DynamicMixin(object): pass for track in Track.query.all(): label = "%s: %s" % (track.theme, track.title) name = "track_%d" % track.id field = BooleanField(label=label) setattr(DynamicMixin, name, field) return DynamicMixin def make_registration_form_class(): mixin_class = make_mixin_class() class RegistrationForm(mixin_class, Form): email = EmailField(label=_l(u"Your email address"), validators=[required(), email()]) coming_on_oct_3 = BooleanField(label=_l(u"Will you come on Oct. 3th? (Thursday)")) coming_on_oct_4 = BooleanField(label=_l(u"Will you come on Oct. 4th? (Friday)")) coming_on_oct_5 = BooleanField(label=_l(u"Will you come on Oct. 5th? (Saturday)")) return RegistrationForm def make_confirmation_form_class(): mixin_class = make_mixin_class() class ConfirmationForm(mixin_class, Form): email = EmailField(label=_l(u"Your email address"), validators=[required(), email()]) coming_on_oct_3 = BooleanField(label=_l(u"Will you come on Oct. 3th? (Thursday)")) coming_on_oct_4 = BooleanField(label=_l(u"Will you come on Oct. 4th? (Friday)")) coming_on_oct_5 = BooleanField(label=_l(u"Will you come on Oct. 5th? (Saturday)")) first_name = TextField(label=_l("First name")) last_name = TextField(label=_l("Last name")) organization = TextField(label=_l("Organization")) url = TextField(label=_l("URL")) url = TextAreaField(label=_l("Biography")) # twitter_handle = Column(UnicodeText(100), default="", nullable=False) # github_handle = Column(UnicodeText(200), default="", nullable=False) # sourceforge_handle = Column(UnicodeText(200), default="", nullable=False) # linkedin_url = Column(UnicodeText(200), default="", nullable=False) return ConfirmationForm
[ "sf@fermigier.com" ]
sf@fermigier.com
51fa016e1c1e8f8413a36b5d13b3ac5e585a1ade
aaddc9b334b4d265d61cd97464d9ff73f32d9bec
/12_DRF_API_ModalViewSet/DRF_API_ModalViewSet/wsgi.py
59140f929e09da11239464ede2ab10ba8c216e53
[]
no_license
DharmendraB/DRF-Django-RestFramework-API
f3549955e53d43f7dad2a78468ad0792ebfb70d5
4f12ab84ca5f69cf2bb8e392b5490247d5f00e0e
refs/heads/main
2023-05-30T20:59:46.635078
2021-06-11T04:32:52
2021-06-11T04:32:52
375,905,264
0
0
null
null
null
null
UTF-8
Python
false
false
417
py
""" WSGI config for DRF_API_ModalViewSet project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'DRF_API_ModalViewSet.settings') application = get_wsgi_application()
[ "ghldharmendra@gmail.com" ]
ghldharmendra@gmail.com
1a12b7c2d2f69df76cef3e44e1259cdf614dfc4d
927e8a9390d219a14fce6922ab054e2521a083d3
/tree/largest bst.py
a70af6bfda90d12ff4c3307819dc8596461b2aa9
[]
no_license
RavinderSinghPB/data-structure-and-algorithm
19e7784f24b3536e29486ddabf4830f9eb578005
f48c759fc347471a44ac4bb4362e99efacdd228b
refs/heads/master
2023-08-23T21:07:28.704498
2020-07-18T09:44:04
2020-07-18T09:44:04
265,993,890
0
0
null
null
null
null
UTF-8
Python
false
false
3,794
py
from mathpro.math import inf from collections import deque import sys sys.setrecursionlimit(10000) class Node1: def __init__(self,isBst,size,mini,maxi): self.isBst = isBst self.size = size self.mini = mini self.maxi = maxi def bst(root): if not root: x=Node1(True,0,1000000,0) return x left=bst(root.left) right=bst(root.right) if left.isBst and right.isBst and root.data>left.maxi and root.data<right.mini: x= Node1(True,1+left.size+right.size,min(root.data,left.mini),max(root.data,right.maxi)) else: x= Node1(False,max(left.size,right.size),1000000,0) return x def largestBSTBT(root): return bst(root).size def largestBSTBT(root): # Base cases : When tree is empty or it has # one child. if (root == None): return 0, -inf, inf, 0, True if (root.left == None and root.right == None): return 1, root.data, root.data, 1, True # Recur for left subtree and right subtrees l = largestBSTBT(root.left) r = largestBSTBT(root.right) # Create a return variable and initialize its # size. ret = [0, 0, 0, 0, 0] ret[0] = (1 + l[0] + r[0]) # If whole tree rooted under current root is # BST. if (l[4] and r[4] and l[1] < root.data and r[2] > root.data): ret[2] = min(l[2], min(r[2], root.data)) ret[1] = max(r[1], max(l[1], root.data)) # Update answer for tree rooted under # current 'root' ret[3] = ret[0] ret[4] = True return ret # If whole tree is not BST, return maximum # of left and right subtrees ret[3] = max(l[3], r[3]) ret[4] = False return ret # Tree Node class Node: def __init__(self, val): self.right = None self.data = val self.left = None def InOrder(root): ''' :param root: root of the given tree. :return: None, print the space separated in order Traversal of the given tree. ''' if root is None: # check if the root is none return InOrder(root.left) # do in order of left child print(root.data, end=" ") # print root of the given tree InOrder(root.right) # do in order of right child # Function to Build Tree def buildTree(s): # Corner Case if (len(s) == 0 or s[0] == "N"): return None # Creating list of strings from input # string after spliting by space ip = list(map(str, s.split())) # Create the root of the tree root = Node(int(ip[0])) size = 0 q = deque() # Push the root to the queue q.append(root) size = size + 1 # Starting from the second element i = 1 while size > 0 and i < len(ip): # Get and remove the front of the queue currNode = q[0] q.popleft() size = size - 1 # Get the current node's value from the string currVal = ip[i] # If the left child is not null if (currVal != "N"): # Create the left child for the current node currNode.left = Node(int(currVal)) # Push it to the queue q.append(currNode.left) size = size + 1 # For the right child i = i + 1 if (i >= len(ip)): break currVal = ip[i] # If the right child is not null if (currVal != "N"): # Create the right child for the current node currNode.right = Node(int(currVal)) # Push it to the queue q.append(currNode.right) size = size + 1 i = i + 1 return root if __name__ == "__main__": t = int(input()) for _ in range(0, t): s = input() root = buildTree(s) print(largestBSTBT(root)[3])
[ "ravindersingh.gfg@gmail.com" ]
ravindersingh.gfg@gmail.com
81a2872d9a9c25af764af1274d957578a126869a
9743d5fd24822f79c156ad112229e25adb9ed6f6
/xai/brain/wordbase/otherforms/_gripped.py
b9c9b15141f34bec76fa0ae3fbe86ef380965360
[ "MIT" ]
permissive
cash2one/xai
de7adad1758f50dd6786bf0111e71a903f039b64
e76f12c9f4dcf3ac1c7c08b0cc8844c0b0a104b6
refs/heads/master
2021-01-19T12:33:54.964379
2017-01-28T02:00:50
2017-01-28T02:00:50
null
0
0
null
null
null
null
UTF-8
Python
false
false
218
py
#calss header class _GRIPPED(): def __init__(self,): self.name = "GRIPPED" self.definitions = grip self.parents = [] self.childen = [] self.properties = [] self.jsondata = {} self.basic = ['grip']
[ "xingwang1991@gmail.com" ]
xingwang1991@gmail.com
2719ecdb0d3f55cf2a59d28875a664afed9e14ec
45de7d905486934629730945619f49281ad19359
/xlsxwriter/test/comparison/test_chart_legend06.py
f10d00e6bc314ead1c5752aad9c675cf4fe559c5
[ "BSD-2-Clause" ]
permissive
jmcnamara/XlsxWriter
599e1d225d698120ef931a776a9d93a6f60186ed
ab13807a1be68652ffc512ae6f5791d113b94ee1
refs/heads/main
2023-09-04T04:21:04.559742
2023-08-31T19:30:52
2023-08-31T19:30:52
7,433,211
3,251
712
BSD-2-Clause
2023-08-28T18:52:14
2013-01-04T01:07:06
Python
UTF-8
Python
false
false
1,405
py
############################################################################### # # Tests for XlsxWriter. # # SPDX-License-Identifier: BSD-2-Clause # Copyright (c), 2013-2023, John McNamara, jmcnamara@cpan.org # from ..excel_comparison_test import ExcelComparisonTest from ...workbook import Workbook class TestCompareXLSXFiles(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_legend06.xlsx") def test_create_file(self): """Test the creation of an XlsxWriter file with legend options.""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() chart = workbook.add_chart({"type": "line"}) chart.axis_ids = [79972224, 79973760] data = [ [1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15], ] worksheet.write_column("A1", data[0]) worksheet.write_column("B1", data[1]) worksheet.write_column("C1", data[2]) chart.add_series({"values": "=Sheet1!$A$1:$A$5"}) chart.add_series({"values": "=Sheet1!$B$1:$B$5"}) chart.add_series({"values": "=Sheet1!$C$1:$C$5"}) chart.set_legend({"fill": {"color": "yellow"}}) worksheet.insert_chart("E9", chart) workbook.close() self.assertExcelEqual()
[ "jmcnamara@cpan.org" ]
jmcnamara@cpan.org