blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
616
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
777 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
149 values
src_encoding
stringclasses
26 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
3
10.2M
extension
stringclasses
188 values
content
stringlengths
3
10.2M
authors
listlengths
1
1
author_id
stringlengths
1
132
24f91adc550d123a98239a57ae27ac6345f382ab
cd44f9f6d97e54886352353da9c45d9e6c291928
/newspaper/admin.py
d347faa1a852e2b8fbe3b1fd52357e2b88adaebb
[]
no_license
MaksimFelchuck/Felnews
c480f045dc21d6f40e10d233a011fb05522f53f9
a3411f10230b7cecdac4a49cb7e83c03d1c89444
refs/heads/master
2023-02-17T08:13:21.413801
2021-01-16T14:55:03
2021-01-16T14:55:03
330,102,149
1
0
null
null
null
null
UTF-8
Python
false
false
171
py
from django.contrib import admin from newspaper.models import * # Register your models here. @admin.register(News, Image) class PersonAdmin(admin.ModelAdmin): pass
fa870428c18812b9d152127aa4df6cc4092bdbff
e967290f67437c0afcbb4597e9ba6020761f2a45
/github.com/ceph/ceph-deploy/ceph_deploy/util/wrappers.py
4bff77b5657b6ea0ac484359fb93d3a804362451
[ "MIT" ]
permissive
mp-rheinrich/mp-fs-sandbox
77bf40a27a0d6c2b38cbc7562023a92fca8751c0
35c38ac9d4d7ad941facfd24ab0a068630c57bdf
refs/heads/master
2020-05-31T11:13:13.474102
2013-08-21T12:59:11
2013-08-21T12:59:11
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,052
py
""" In a lot of places we need to make system calls, mainly through subprocess. Here we define them and reuse them with the added functionality of getting logging and remote execution. This allows us to only remote-execute the actual calls, not whole functions. """ from ceph_deploy.util.decorators import remote_compile from ceph_deploy.util import context def check_call(conn, logger, args, *a, **kw): """ Wraps ``subprocess.check_call`` for a remote call via ``pushy`` doing all the capturing and logging nicely upon failure/success The mangling of the traceback when an exception ocurrs, is because the caller gets eating up by not being executed in the actual function of a given module (e.g. ``centos/install.py``) but rather here, where the stack trace is no longer relevant. :param args: The args to be passed onto ``check_call`` """ command = ' '.join(args) patch = kw.pop('patch', True) # Always patch unless explicitly told to logger.info('Running command: %s' % command) def remote_call(args, *a, **kw): import subprocess subprocess.check_call( args, *a, **kw ) with context.remote(conn, logger, remote_call, mangle_exc=False, patch=patch) as call: try: return call(args, *a, **kw) except Exception as err: import inspect stack = inspect.getframeinfo(inspect.currentframe().f_back) if hasattr(err, 'remote_traceback'): logger.error('Traceback (most recent call last):') logger.error(' File "%s", line %s, in %s' % ( stack[0], stack[1], stack[2]) ) err.remote_traceback.pop(0) for line in err.remote_traceback: if line: logger.error(line) raise RuntimeError('Failed to execute command: %s' % ' '.join(args)) else: raise err
59ab3b8c00e340f686e72893e1533b2c4bc80c26
14ec9fc9aee69d54701168c069df4fe46a27b811
/makeDigikeyBOM.py
67fa76a4e374de9b7f2442ed9f00517b1d4886b5
[]
no_license
BitKnitting/MakeDigikeyBOM
1af6e79b9c9bb86590425ec06bbacc63fa2cbb60
ef12a92dec3abbd86571b40d6ea7ea72fa6e60b1
refs/heads/master
2021-01-13T00:59:15.063713
2017-02-20T18:30:42
2017-02-20T18:30:42
53,728,672
10
0
null
null
null
null
UTF-8
Python
false
false
841
py
# # The main entry point to making a digikey Bom CSV file from the output of bom2csv # as discussed in the bitknitting blog post: https://bitknitting.wordpress.com/2016/03/05/from-kicad-to-digikey-generating-a-bom-based-on-esteem-overview/ # import logging logger = logging.getLogger(__name__) from replaceJellyBeanParts import replaceJellyBeanParts from makeDigikeyFile import makeDigikeyFile from getParts import getParts def makeDigikeyBOM(outputFrom_bom2csv,jellyBeanFile,outDir,numProcesses): modifiedBOM2csvFile = replaceJellyBeanParts(outputFrom_bom2csv=outputFrom_bom2csv,jellyBeanFile=jellyBeanFile) components_by_part_number = getParts(modifiedBOM2csvFile=modifiedBOM2csvFile) if not makeDigikeyFile(components_by_part_number,outDir): logger.error("Could not make the Digikey file. Check output from logger.")
8ebd576a5c0651eb84ceff4de6e7daa1b0798574
5ec06dab1409d790496ce082dacb321392b32fe9
/clients/python/generated/test/test_com_adobe_granite_repository_hc_impl_authorizable_node_name_health_check_properties.py
3a604357918c8edc66ecdea80b46d7424d41f966
[ "Apache-2.0" ]
permissive
shinesolutions/swagger-aem-osgi
e9d2385f44bee70e5bbdc0d577e99a9f2525266f
c2f6e076971d2592c1cbd3f70695c679e807396b
refs/heads/master
2022-10-29T13:07:40.422092
2021-04-09T07:46:03
2021-04-09T07:46:03
190,217,155
3
3
Apache-2.0
2022-10-05T03:26:20
2019-06-04T14:23:28
null
UTF-8
Python
false
false
1,487
py
# coding: utf-8 """ Adobe Experience Manager OSGI config (AEM) API Swagger AEM OSGI is an OpenAPI specification for Adobe Experience Manager (AEM) OSGI Configurations API # noqa: E501 The version of the OpenAPI document: 1.0.0 Contact: [email protected] Generated by: https://openapi-generator.tech """ from __future__ import absolute_import import unittest import swaggeraemosgi from swaggeraemosgi.models.com_adobe_granite_repository_hc_impl_authorizable_node_name_health_check_properties import ComAdobeGraniteRepositoryHcImplAuthorizableNodeNameHealthCheckProperties # noqa: E501 from swaggeraemosgi.rest import ApiException class TestComAdobeGraniteRepositoryHcImplAuthorizableNodeNameHealthCheckProperties(unittest.TestCase): """ComAdobeGraniteRepositoryHcImplAuthorizableNodeNameHealthCheckProperties unit test stubs""" def setUp(self): pass def tearDown(self): pass def testComAdobeGraniteRepositoryHcImplAuthorizableNodeNameHealthCheckProperties(self): """Test ComAdobeGraniteRepositoryHcImplAuthorizableNodeNameHealthCheckProperties""" # FIXME: construct object with mandatory attributes with example values # model = swaggeraemosgi.models.com_adobe_granite_repository_hc_impl_authorizable_node_name_health_check_properties.ComAdobeGraniteRepositoryHcImplAuthorizableNodeNameHealthCheckProperties() # noqa: E501 pass if __name__ == '__main__': unittest.main()
1a164b7d02c2408775c790313f51483c12f60fa3
0124528676ee3bbaec60df5d6950b408e6da37c8
/Projects/QTPy/adafruit-circuitpython-bundle-7.x-mpy-20220601/examples/pct2075_high_temp_alert_example.py
2ec4e88196a8c47dfe88b6d038fdaac9fc2e1030
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
land-boards/lb-boards
8127658dc537dcfde0bb59a5018ab75c3f0087f6
eeb98cc2003dac1924845d949f6f5bd387376568
refs/heads/master
2023-06-07T15:44:46.110742
2023-06-02T22:53:24
2023-06-02T22:53:24
4,847,305
10
12
null
null
null
null
UTF-8
Python
false
false
591
py
# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries # SPDX-License-Identifier: MIT import time import board import adafruit_pct2075 i2c = board.I2C() # uses board.SCL and board.SDA pct = adafruit_pct2075.PCT2075(i2c) pct.high_temperature_threshold = 35.5 pct.temperature_hysteresis = 30.0 pct.high_temp_active_high = False print("High temp alert active high? %s" % pct.high_temp_active_high) # Attach an LED with the Cathode to the INT pin and Anode to 3.3V with a current limiting resistor while True: print("Temperature: %.2f C" % pct.temperature) time.sleep(0.5)
893ef9476b1476a4529208a0c1475e6749d452e7
6d1728bf105a7d6481d0bbca2b88f4478e0632d9
/beautifulsoup/start/sibling.py
e0e1b3167becdb2101cb9e5f656394b366a1fa76
[]
no_license
Phantomn/Python
00c63aceb2d4aa0db71fe5e33fe8b5159b41aadd
12808adf4b52c60cfe94befb6daa1e8187224beb
refs/heads/Python
2022-11-09T16:49:49.165884
2019-08-05T07:30:07
2019-08-05T07:30:07
44,149,995
0
0
null
null
null
null
UTF-8
Python
false
false
259
py
from urllib import urlopen from bs4 import BeautifulSoup html = urlopen("http://www.pythonscraping.com/pages/page3.html") bsObj = BeautifulSoup(html, "html.parser") for sibling in bsObj.find("table", {"id":"giftList"}).tr.next_siblings: print(sibling)
09b3a389b1084df14d4c4a8c2f0930a95a481b25
44a7330dfa4fe321eb432ee57a32328578dec109
/milk/tests/test_pca.py
e543aff8ebdf2506e861097e21e31271cf4bb07d
[ "MIT" ]
permissive
tzuryby/milk
7cb6760fad600e9e0d0c9216dc749db289b596fb
a7159b748414d4d095741978fb994c4affcf6b9b
refs/heads/master
2020-12-29T02:45:33.044864
2011-03-15T20:23:29
2011-03-15T20:25:11
1,485,748
2
0
null
null
null
null
UTF-8
Python
false
false
472
py
import numpy.random import milk.unsupervised.pca import numpy as np def test_pca(): numpy.random.seed(123) X = numpy.random.rand(10,4) X[:,1] += numpy.random.rand(10)**2*X[:,0] X[:,1] += numpy.random.rand(10)**2*X[:,0] X[:,2] += numpy.random.rand(10)**2*X[:,0] Y,V = milk.unsupervised.pca(X) Xn = milk.unsupervised.normalise.zscore(X) assert X.shape == Y.shape assert ((np.dot(V[:4].T,Y[:,:4].T).T-Xn)**2).sum()/(Xn**2).sum() < .3
62ca945793b8ded662bede34c74e0fa6bba7a0dd
3d7039903da398ae128e43c7d8c9662fda77fbdf
/database/LeetCode/juejin_177.py
66305002a453b443f0d8c1698db9ad711222a8ac
[]
no_license
ChenYongChang1/spider_study
a9aa22e6ed986193bf546bb567712876c7be5e15
fe5fbc1a5562ff19c70351303997d3df3af690db
refs/heads/master
2023-08-05T10:43:11.019178
2021-09-18T01:30:22
2021-09-18T01:30:22
406,727,214
0
0
null
null
null
null
UTF-8
Python
false
false
67,057
py
{"err_no": 0, "err_msg": "success", "data": [{"article_id": "6998707022577270798", "article_info": {"article_id": "6998707022577270798", "user_id": "3175804198200456", "category_id": "6809637767543259144", "tag_ids": [6809640398105870343, 6809641039037464589], "visible_level": 0, "link_url": "", "cover_image": "https://p9-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/1c61aeeaab454bf78df10f818e5653f2~tplv-k3u1fbpfcp-watermark.image", "is_gfw": 0, "title": "「链表」leetcode 237.删除链表中的节点(简单)", "brief_content": "一、了解题目 附上原题链接:237. 删除链表中的节点 请编写一个函数,使其可以删除某个链表中给定的(非末尾)节点。传入函数的唯一参数为 要被删除的节点 。 示例: 现有一个链表 -- head = ", "is_english": 0, "is_original": 1, "user_index": 0, "original_type": 0, "original_author": "", "content": "", "ctime": "1629513492", "mtime": "1629538948", "rtime": "1629524147", "draft_id": "6998705842656641031", "view_count": 68, "collect_count": 0, "digg_count": 0, "comment_count": 0, "hot_index": 3, "is_hot": 0, "rank_index": 0.00074255, "status": 2, "verify_status": 1, "audit_status": 2, "mark_content": ""}, "author_user_info": {"user_id": "3175804198200456", "user_name": "清风伴我行", "company": "", "job_title": "", "avatar_large": "https://sf6-ttcdn-tos.pstatp.com/img/user-avatar/91d1e39b3893315e220a6e34a8a0c916~300x300.image", "level": 1, "description": "周一的知识宝库", "followee_count": 1, "follower_count": 1, "post_article_count": 23, "digg_article_count": 0, "got_digg_count": 10, "got_view_count": 1082, "post_shortmsg_count": 0, "digg_shortmsg_count": 0, "isfollowed": false, "favorable_author": 0, "power": 20, "study_point": 0, "university": {"university_id": "0", "name": "", "logo": ""}, "major": {"major_id": "0", "parent_id": "0", "name": ""}, "student_status": 0, "select_event_count": 0, "select_online_course_count": 0, "identity": 0, "is_select_annual": false, "select_annual_rank": 0, "annual_list_type": 0, "extraMap": {}, "is_logout": 0}, "category": {"category_id": "6809637767543259144", "category_name": "前端", "category_url": "frontend", "rank": 2, "back_ground": "https://lc-mhke0kuv.cn-n1.lcfile.com/8c95587526f346c0.png", "icon": "https://lc-mhke0kuv.cn-n1.lcfile.com/1c40f5eaba561e32.png", "ctime": 1457483942, "mtime": 1432503190, "show_type": 3, "item_type": 2, "promote_tag_cap": 4, "promote_priority": 2}, "tags": [{"id": 2546519, "tag_id": "6809640398105870343", "tag_name": "JavaScript", "color": "#616161", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/5d70fd6af940df373834.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1435884803, "mtime": 1631692583, "id_type": 9, "tag_alias": "", "post_article_count": 67405, "concern_user_count": 398956}, {"id": 2546983, "tag_id": "6809641039037464589", "tag_name": "LeetCode", "color": "#000000", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/155748584224691639f51dce773ead8d4233400c24546.jpg~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1489518382, "mtime": 1631692819, "id_type": 9, "tag_alias": "", "post_article_count": 6296, "concern_user_count": 11301}], "user_interact": {"id": 6998707022577270798, "omitempty": 2, "user_id": 0, "is_digg": false, "is_follow": false, "is_collect": false}, "org": {"org_info": null, "org_user": null, "is_followed": false}, "req_id": "2021091516023101020405304626004CE7"}, {"article_id": "6844903889771167752", "article_info": {"article_id": "6844903889771167752", "user_id": "3403743728515246", "category_id": "6809637767543259144", "tag_ids": [6809641039037464589, 6809640499062767624], "visible_level": 0, "link_url": "", "cover_image": "", "is_gfw": 0, "title": "LeetCode 攻略 - 2019 年 7 月上半月汇总(55 题攻略)", "brief_content": "自 2019-05-16 开始,jsliang 每天折腾一道及以上 LeetCode 题目,并将其解题思路记录成文章,发布到 GitHub 和 微信公众号。 2019/08/15 前。LeetCode 简单难度题目 - 完成 100 道简单 LeetCode 题目的题解。 20…", "is_english": 0, "is_original": 1, "user_index": 0, "original_type": 0, "original_author": "", "content": "", "ctime": "1563171733", "mtime": "1604316971", "rtime": "1563171733", "draft_id": "6845076375024435208", "view_count": 3858, "collect_count": 75, "digg_count": 68, "comment_count": 11, "hot_index": 271, "is_hot": 0, "rank_index": 0.00074102, "status": 2, "verify_status": 1, "audit_status": 2, "mark_content": ""}, "author_user_info": {"user_id": "3403743728515246", "user_name": "jsliang", "company": "金山办公软件", "job_title": "联系方式看个人主页", "avatar_large": "https://sf1-ttcdn-tos.pstatp.com/img/user-avatar/fae2936a68be7eac2c5477f18a875fb2~300x300.image", "level": 6, "description": "不折腾的前端,跟咸鱼有什么区别", "followee_count": 20, "follower_count": 15078, "post_article_count": 108, "digg_article_count": 512, "got_digg_count": 13744, "got_view_count": 814343, "post_shortmsg_count": 12, "digg_shortmsg_count": 12, "isfollowed": false, "favorable_author": 1, "power": 21911, "study_point": 0, "university": {"university_id": "0", "name": "", "logo": ""}, "major": {"major_id": "0", "parent_id": "0", "name": ""}, "student_status": 0, "select_event_count": 0, "select_online_course_count": 0, "identity": 0, "is_select_annual": false, "select_annual_rank": 0, "annual_list_type": 0, "extraMap": {}, "is_logout": 0}, "category": {"category_id": "6809637767543259144", "category_name": "前端", "category_url": "frontend", "rank": 2, "back_ground": "https://lc-mhke0kuv.cn-n1.lcfile.com/8c95587526f346c0.png", "icon": "https://lc-mhke0kuv.cn-n1.lcfile.com/1c40f5eaba561e32.png", "ctime": 1457483942, "mtime": 1432503190, "show_type": 3, "item_type": 2, "promote_tag_cap": 4, "promote_priority": 2}, "tags": [{"id": 2546983, "tag_id": "6809641039037464589", "tag_name": "LeetCode", "color": "#000000", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/155748584224691639f51dce773ead8d4233400c24546.jpg~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1489518382, "mtime": 1631692819, "id_type": 9, "tag_alias": "", "post_article_count": 6296, "concern_user_count": 11301}, {"id": 2546592, "tag_id": "6809640499062767624", "tag_name": "算法", "color": "#60ADFF", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/68a1097944c7fa1d7961.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1439503293, "mtime": 1631692675, "id_type": 9, "tag_alias": "", "post_article_count": 23471, "concern_user_count": 310821}], "user_interact": {"id": 6844903889771167752, "omitempty": 2, "user_id": 0, "is_digg": false, "is_follow": false, "is_collect": false}, "org": {"org_info": null, "org_user": null, "is_followed": false}, "req_id": "2021091516023101020405304626004CE7"}, {"article_id": "6994069448957116424", "article_info": {"article_id": "6994069448957116424", "user_id": "3790771823848935", "category_id": "6809637767543259144", "tag_ids": [6809640398105870343, 6809641039037464589], "visible_level": 0, "link_url": "", "cover_image": "https://p1-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/bda05ced978d450083bae9b3bdc5946d~tplv-k3u1fbpfcp-watermark.image", "is_gfw": 0, "title": "前端Leetcode系列|13. 罗马数字转整数", "brief_content": "今天来和小伙伴们一起打卡力扣第13题:罗马数字转整数。 一、题目描述 罗马数字包含以下七种字符: I, V, X, L例如, 罗马数字 2 写做 II ,即为两个并列的 1。12 写做 XII ,即为", "is_english": 0, "is_original": 1, "user_index": 0, "original_type": 0, "original_author": "", "content": "", "ctime": "1628433831", "mtime": "1628504086", "rtime": "1628480884", "draft_id": "6994065730035515400", "view_count": 92, "collect_count": 0, "digg_count": 1, "comment_count": 0, "hot_index": 5, "is_hot": 0, "rank_index": 0.00073858, "status": 2, "verify_status": 1, "audit_status": 2, "mark_content": ""}, "author_user_info": {"user_id": "3790771823848935", "user_name": "芒果啊", "company": "[email protected]", "job_title": "前端ing", "avatar_large": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/2019/11/19/16e8255bc0f64b7f~tplv-t2oaga2asx-image.image", "level": 2, "description": "Endless knowledge, endless learning", "followee_count": 17, "follower_count": 10, "post_article_count": 34, "digg_article_count": 57, "got_digg_count": 81, "got_view_count": 6060, "post_shortmsg_count": 16, "digg_shortmsg_count": 7, "isfollowed": false, "favorable_author": 0, "power": 141, "study_point": 0, "university": {"university_id": "0", "name": "", "logo": ""}, "major": {"major_id": "0", "parent_id": "0", "name": ""}, "student_status": 0, "select_event_count": 0, "select_online_course_count": 0, "identity": 0, "is_select_annual": false, "select_annual_rank": 0, "annual_list_type": 0, "extraMap": {}, "is_logout": 0}, "category": {"category_id": "6809637767543259144", "category_name": "前端", "category_url": "frontend", "rank": 2, "back_ground": "https://lc-mhke0kuv.cn-n1.lcfile.com/8c95587526f346c0.png", "icon": "https://lc-mhke0kuv.cn-n1.lcfile.com/1c40f5eaba561e32.png", "ctime": 1457483942, "mtime": 1432503190, "show_type": 3, "item_type": 2, "promote_tag_cap": 4, "promote_priority": 2}, "tags": [{"id": 2546519, "tag_id": "6809640398105870343", "tag_name": "JavaScript", "color": "#616161", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/5d70fd6af940df373834.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1435884803, "mtime": 1631692583, "id_type": 9, "tag_alias": "", "post_article_count": 67405, "concern_user_count": 398956}, {"id": 2546983, "tag_id": "6809641039037464589", "tag_name": "LeetCode", "color": "#000000", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/155748584224691639f51dce773ead8d4233400c24546.jpg~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1489518382, "mtime": 1631692819, "id_type": 9, "tag_alias": "", "post_article_count": 6296, "concern_user_count": 11301}], "user_interact": {"id": 6994069448957116424, "omitempty": 2, "user_id": 0, "is_digg": false, "is_follow": false, "is_collect": false}, "org": {"org_info": null, "org_user": null, "is_followed": false}, "req_id": "2021091516023101020405304626004CE7"}, {"article_id": "6936441872113991693", "article_info": {"article_id": "6936441872113991693", "user_id": "2462537381852910", "category_id": "6809637767543259144", "tag_ids": [6809641039037464589], "visible_level": 0, "link_url": "", "cover_image": "", "is_gfw": 0, "title": "[leetCode 94.二叉树的中序遍历]|刷题打卡", "brief_content": "给定一个二叉树的根节点 root ,返回它的 中序 遍历。 使用递归解题是该题最简单的解法,我写一个函数,传入需要遍历的二叉树的根节点,函数中判断root是否为空结点,是就直接返回一个空数组[],不是空结点就进行操作。操作中分为三部分,第一部分使其定位到最左下的结点(直到空),…", "is_english": 0, "is_original": 1, "user_index": 7.388384878619027, "original_type": 0, "original_author": "", "content": "", "ctime": "1615016312", "mtime": "1615021308", "rtime": "1615021308", "draft_id": "6936372347716780046", "view_count": 298, "collect_count": 1, "digg_count": 17, "comment_count": 4, "hot_index": 35, "is_hot": 0, "rank_index": 0.00072919, "status": 2, "verify_status": 1, "audit_status": 2, "mark_content": ""}, "author_user_info": {"user_id": "2462537381852910", "user_name": "蟹黄同学", "company": "", "job_title": "前端 @ 未来全栈工程师", "avatar_large": "https://sf1-ttcdn-tos.pstatp.com/img/user-avatar/1548bec913c0a1720de68d7c26fe1ded~300x300.image", "level": 3, "description": "蟹黄吃到饱,前端搞的好,一个梦想能吃蟹黄吃到饱的前端程序员", "followee_count": 48, "follower_count": 238, "post_article_count": 12, "digg_article_count": 171, "got_digg_count": 1679, "got_view_count": 42714, "post_shortmsg_count": 3, "digg_shortmsg_count": 3, "isfollowed": false, "favorable_author": 0, "power": 2108, "study_point": 0, "university": {"university_id": "0", "name": "", "logo": ""}, "major": {"major_id": "0", "parent_id": "0", "name": ""}, "student_status": 0, "select_event_count": 0, "select_online_course_count": 0, "identity": 0, "is_select_annual": false, "select_annual_rank": 0, "annual_list_type": 0, "extraMap": {}, "is_logout": 0}, "category": {"category_id": "6809637767543259144", "category_name": "前端", "category_url": "frontend", "rank": 2, "back_ground": "https://lc-mhke0kuv.cn-n1.lcfile.com/8c95587526f346c0.png", "icon": "https://lc-mhke0kuv.cn-n1.lcfile.com/1c40f5eaba561e32.png", "ctime": 1457483942, "mtime": 1432503190, "show_type": 3, "item_type": 2, "promote_tag_cap": 4, "promote_priority": 2}, "tags": [{"id": 2546983, "tag_id": "6809641039037464589", "tag_name": "LeetCode", "color": "#000000", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/155748584224691639f51dce773ead8d4233400c24546.jpg~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1489518382, "mtime": 1631692819, "id_type": 9, "tag_alias": "", "post_article_count": 6296, "concern_user_count": 11301}], "user_interact": {"id": 6936441872113991693, "omitempty": 2, "user_id": 0, "is_digg": false, "is_follow": false, "is_collect": false}, "org": {"org_info": null, "org_user": null, "is_followed": false}, "req_id": "2021091516023101020405304626004CE7"}, {"article_id": "6989789225268805639", "article_info": {"article_id": "6989789225268805639", "user_id": "3773179638847261", "category_id": "6809637767543259144", "tag_ids": [6809640499062767624, 6809641039037464589], "visible_level": 0, "link_url": "", "cover_image": "https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/592e86e445464eef8453a6cb02a4f9ef~tplv-k3u1fbpfcp-watermark.image", "is_gfw": 0, "title": "算法(leetode,附思维导图 + 全部解法)300题之(3)无重复字符的最长子串", "brief_content": "标题:算法(leetode,附思维导图 + 全部解法)300题之(3)无重复字符的最长子串 一 题目描述 二 解法总览(思维导图) 三 全部解法 1 方案1 1)代码: 2 方案2 1)代码: 3 方", "is_english": 0, "is_original": 1, "user_index": 2.089693646737103, "original_type": 0, "original_author": "", "content": "", "ctime": "1627437136", "mtime": "1627443036", "rtime": "1627443036", "draft_id": "6989787166981242894", "view_count": 92, "collect_count": 0, "digg_count": 1, "comment_count": 0, "hot_index": 5, "is_hot": 0, "rank_index": 0.00072567, "status": 2, "verify_status": 1, "audit_status": 2, "mark_content": ""}, "author_user_info": {"user_id": "3773179638847261", "user_name": "码农三少", "company": "百度", "job_title": "百度前端工程师", "avatar_large": "https://sf6-ttcdn-tos.pstatp.com/img/user-avatar/8301f5ea3bfc02a837cd4d1d7eefd0bd~300x300.image", "level": 1, "description": "前端(主攻数据可视化);半年内实现了个人公众号从0到5.8K+的增长;数独", "followee_count": 49, "follower_count": 7, "post_article_count": 24, "digg_article_count": 17, "got_digg_count": 33, "got_view_count": 2106, "post_shortmsg_count": 0, "digg_shortmsg_count": 4, "isfollowed": false, "favorable_author": 0, "power": 54, "study_point": 0, "university": {"university_id": "0", "name": "", "logo": ""}, "major": {"major_id": "0", "parent_id": "0", "name": ""}, "student_status": 0, "select_event_count": 0, "select_online_course_count": 0, "identity": 0, "is_select_annual": false, "select_annual_rank": 0, "annual_list_type": 0, "extraMap": {}, "is_logout": 0}, "category": {"category_id": "6809637767543259144", "category_name": "前端", "category_url": "frontend", "rank": 2, "back_ground": "https://lc-mhke0kuv.cn-n1.lcfile.com/8c95587526f346c0.png", "icon": "https://lc-mhke0kuv.cn-n1.lcfile.com/1c40f5eaba561e32.png", "ctime": 1457483942, "mtime": 1432503190, "show_type": 3, "item_type": 2, "promote_tag_cap": 4, "promote_priority": 2}, "tags": [{"id": 2546592, "tag_id": "6809640499062767624", "tag_name": "算法", "color": "#60ADFF", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/68a1097944c7fa1d7961.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1439503293, "mtime": 1631692675, "id_type": 9, "tag_alias": "", "post_article_count": 23471, "concern_user_count": 310821}, {"id": 2546983, "tag_id": "6809641039037464589", "tag_name": "LeetCode", "color": "#000000", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/155748584224691639f51dce773ead8d4233400c24546.jpg~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1489518382, "mtime": 1631692819, "id_type": 9, "tag_alias": "", "post_article_count": 6296, "concern_user_count": 11301}], "user_interact": {"id": 6989789225268805639, "omitempty": 2, "user_id": 0, "is_digg": false, "is_follow": false, "is_collect": false}, "org": {"org_info": null, "org_user": null, "is_followed": false}, "req_id": "2021091516023101020405304626004CE7"}, {"article_id": "7000932485362090014", "article_info": {"article_id": "7000932485362090014", "user_id": "3175804198200456", "category_id": "6809637767543259144", "tag_ids": [6809641039037464589], "visible_level": 0, "link_url": "", "cover_image": "https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/6d7ad6f2fb614e8285a4bd3bbd6c366f~tplv-k3u1fbpfcp-watermark.image", "is_gfw": 0, "title": "「字符串」leetcode 9.判断是否是回文数(简单)", "brief_content": "一、了解题目 附上原题链接:9. 回文数 给你一个整数 x ,如果 x 是一个回文整数,返回 true ;否则,返回 false 。 回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。例如", "is_english": 0, "is_original": 1, "user_index": 0, "original_type": 0, "original_author": "", "content": "", "ctime": "1630031637", "mtime": "1630056524", "rtime": "1630056524", "draft_id": "6999904991586549768", "view_count": 59, "collect_count": 0, "digg_count": 0, "comment_count": 0, "hot_index": 2, "is_hot": 0, "rank_index": 0.0007145, "status": 2, "verify_status": 1, "audit_status": 2, "mark_content": ""}, "author_user_info": {"user_id": "3175804198200456", "user_name": "清风伴我行", "company": "", "job_title": "", "avatar_large": "https://sf6-ttcdn-tos.pstatp.com/img/user-avatar/91d1e39b3893315e220a6e34a8a0c916~300x300.image", "level": 1, "description": "周一的知识宝库", "followee_count": 1, "follower_count": 1, "post_article_count": 23, "digg_article_count": 0, "got_digg_count": 10, "got_view_count": 1082, "post_shortmsg_count": 0, "digg_shortmsg_count": 0, "isfollowed": false, "favorable_author": 0, "power": 20, "study_point": 0, "university": {"university_id": "0", "name": "", "logo": ""}, "major": {"major_id": "0", "parent_id": "0", "name": ""}, "student_status": 0, "select_event_count": 0, "select_online_course_count": 0, "identity": 0, "is_select_annual": false, "select_annual_rank": 0, "annual_list_type": 0, "extraMap": {}, "is_logout": 0}, "category": {"category_id": "6809637767543259144", "category_name": "前端", "category_url": "frontend", "rank": 2, "back_ground": "https://lc-mhke0kuv.cn-n1.lcfile.com/8c95587526f346c0.png", "icon": "https://lc-mhke0kuv.cn-n1.lcfile.com/1c40f5eaba561e32.png", "ctime": 1457483942, "mtime": 1432503190, "show_type": 3, "item_type": 2, "promote_tag_cap": 4, "promote_priority": 2}, "tags": [{"id": 2546983, "tag_id": "6809641039037464589", "tag_name": "LeetCode", "color": "#000000", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/155748584224691639f51dce773ead8d4233400c24546.jpg~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1489518382, "mtime": 1631692819, "id_type": 9, "tag_alias": "", "post_article_count": 6296, "concern_user_count": 11301}], "user_interact": {"id": 7000932485362090014, "omitempty": 2, "user_id": 0, "is_digg": false, "is_follow": false, "is_collect": false}, "org": {"org_info": null, "org_user": null, "is_followed": false}, "req_id": "2021091516023101020405304626004CE7"}, {"article_id": "6994435150604042247", "article_info": {"article_id": "6994435150604042247", "user_id": "1371820633892071", "category_id": "6809637767543259144", "tag_ids": [6809640499062767624, 6809641039037464589], "visible_level": 0, "link_url": "", "cover_image": "", "is_gfw": 0, "title": "算法题-顺时针打印矩阵", "brief_content": "题目描述 输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。 分析:矩阵可以用二维数组来模拟。 示例 : 题解 方法一:模拟打印", "is_english": 0, "is_original": 1, "user_index": 1.526738543039035, "original_type": 0, "original_author": "", "content": "", "ctime": "1628518839", "mtime": "1628565734", "rtime": "1628565734", "draft_id": "6994434429179396109", "view_count": 53, "collect_count": 0, "digg_count": 1, "comment_count": 0, "hot_index": 3, "is_hot": 0, "rank_index": 0.00069257, "status": 2, "verify_status": 1, "audit_status": 2, "mark_content": ""}, "author_user_info": {"user_id": "1371820633892071", "user_name": "山人Ll", "company": "", "job_title": "前端", "avatar_large": "https://sf1-ttcdn-tos.pstatp.com/img/user-avatar/19a42ba89b6e00ce91d75457218e78ae~300x300.image", "level": 2, "description": "", "followee_count": 8, "follower_count": 4, "post_article_count": 56, "digg_article_count": 111, "got_digg_count": 72, "got_view_count": 3920, "post_shortmsg_count": 2, "digg_shortmsg_count": 1, "isfollowed": false, "favorable_author": 0, "power": 111, "study_point": 0, "university": {"university_id": "0", "name": "", "logo": ""}, "major": {"major_id": "0", "parent_id": "0", "name": ""}, "student_status": 0, "select_event_count": 0, "select_online_course_count": 0, "identity": 0, "is_select_annual": false, "select_annual_rank": 0, "annual_list_type": 0, "extraMap": {}, "is_logout": 0}, "category": {"category_id": "6809637767543259144", "category_name": "前端", "category_url": "frontend", "rank": 2, "back_ground": "https://lc-mhke0kuv.cn-n1.lcfile.com/8c95587526f346c0.png", "icon": "https://lc-mhke0kuv.cn-n1.lcfile.com/1c40f5eaba561e32.png", "ctime": 1457483942, "mtime": 1432503190, "show_type": 3, "item_type": 2, "promote_tag_cap": 4, "promote_priority": 2}, "tags": [{"id": 2546592, "tag_id": "6809640499062767624", "tag_name": "算法", "color": "#60ADFF", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/68a1097944c7fa1d7961.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1439503293, "mtime": 1631692675, "id_type": 9, "tag_alias": "", "post_article_count": 23471, "concern_user_count": 310821}, {"id": 2546983, "tag_id": "6809641039037464589", "tag_name": "LeetCode", "color": "#000000", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/155748584224691639f51dce773ead8d4233400c24546.jpg~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1489518382, "mtime": 1631692819, "id_type": 9, "tag_alias": "", "post_article_count": 6296, "concern_user_count": 11301}], "user_interact": {"id": 6994435150604042247, "omitempty": 2, "user_id": 0, "is_digg": false, "is_follow": false, "is_collect": false}, "org": {"org_info": null, "org_user": null, "is_followed": false}, "req_id": "2021091516023101020405304626004CE7"}, {"article_id": "6995819745953988644", "article_info": {"article_id": "6995819745953988644", "user_id": "3175804198200456", "category_id": "6809637767543259144", "tag_ids": [6809640398105870343, 6809641039037464589], "visible_level": 0, "link_url": "", "cover_image": "https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/5f37154c029440cfa0f653f4605c1bf0~tplv-k3u1fbpfcp-watermark.image", "is_gfw": 0, "title": "「栈」leetcode 155.取出最小栈", "brief_content": "一、了解题目 附上原题链接:155. 最小栈 设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。 push(x) —— 将元素 x 推入栈中。 pop() —— 删", "is_english": 0, "is_original": 1, "user_index": 0, "original_type": 0, "original_author": "", "content": "", "ctime": "1628841227", "mtime": "1628845230", "rtime": "1628845219", "draft_id": "6995818719293210631", "view_count": 78, "collect_count": 0, "digg_count": 1, "comment_count": 0, "hot_index": 4, "is_hot": 0, "rank_index": 0.000692, "status": 2, "verify_status": 1, "audit_status": 2, "mark_content": ""}, "author_user_info": {"user_id": "3175804198200456", "user_name": "清风伴我行", "company": "", "job_title": "", "avatar_large": "https://sf6-ttcdn-tos.pstatp.com/img/user-avatar/91d1e39b3893315e220a6e34a8a0c916~300x300.image", "level": 1, "description": "周一的知识宝库", "followee_count": 1, "follower_count": 1, "post_article_count": 23, "digg_article_count": 0, "got_digg_count": 10, "got_view_count": 1082, "post_shortmsg_count": 0, "digg_shortmsg_count": 0, "isfollowed": false, "favorable_author": 0, "power": 20, "study_point": 0, "university": {"university_id": "0", "name": "", "logo": ""}, "major": {"major_id": "0", "parent_id": "0", "name": ""}, "student_status": 0, "select_event_count": 0, "select_online_course_count": 0, "identity": 0, "is_select_annual": false, "select_annual_rank": 0, "annual_list_type": 0, "extraMap": {}, "is_logout": 0}, "category": {"category_id": "6809637767543259144", "category_name": "前端", "category_url": "frontend", "rank": 2, "back_ground": "https://lc-mhke0kuv.cn-n1.lcfile.com/8c95587526f346c0.png", "icon": "https://lc-mhke0kuv.cn-n1.lcfile.com/1c40f5eaba561e32.png", "ctime": 1457483942, "mtime": 1432503190, "show_type": 3, "item_type": 2, "promote_tag_cap": 4, "promote_priority": 2}, "tags": [{"id": 2546519, "tag_id": "6809640398105870343", "tag_name": "JavaScript", "color": "#616161", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/5d70fd6af940df373834.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1435884803, "mtime": 1631692583, "id_type": 9, "tag_alias": "", "post_article_count": 67405, "concern_user_count": 398956}, {"id": 2546983, "tag_id": "6809641039037464589", "tag_name": "LeetCode", "color": "#000000", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/155748584224691639f51dce773ead8d4233400c24546.jpg~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1489518382, "mtime": 1631692819, "id_type": 9, "tag_alias": "", "post_article_count": 6296, "concern_user_count": 11301}], "user_interact": {"id": 6995819745953988644, "omitempty": 2, "user_id": 0, "is_digg": false, "is_follow": false, "is_collect": false}, "org": {"org_info": null, "org_user": null, "is_followed": false}, "req_id": "2021091516023101020405304626004CE7"}, {"article_id": "6992970434635366437", "article_info": {"article_id": "6992970434635366437", "user_id": "2181848597012078", "category_id": "6809637767543259144", "tag_ids": [6809641039037464589, 6809640499062767624], "visible_level": 0, "link_url": "", "cover_image": "", "is_gfw": 0, "title": "LeetCode 42 Trapping Rain Water (Tag:Array Difficulty:Hard)", "brief_content": "这是我参与8月更文挑战的第5天,活动详情查看:8月更文挑战 前言 关于 LeetCode 数组类型题目的相关解法,可见LeetCode 数组类型题目做前必看,分类别解法总结了题目,可以用来单项提高。觉", "is_english": 0, "is_original": 1, "user_index": 2.147726993971304, "original_type": 0, "original_author": "", "content": "", "ctime": "1628177838", "mtime": "1628233597", "rtime": "1628233597", "draft_id": "6992943741807886366", "view_count": 44, "collect_count": 0, "digg_count": 1, "comment_count": 0, "hot_index": 3, "is_hot": 0, "rank_index": 0.00068993, "status": 2, "verify_status": 1, "audit_status": 2, "mark_content": ""}, "author_user_info": {"user_id": "2181848597012078", "user_name": "AllenLMN", "company": "", "job_title": "前端工程师", "avatar_large": "https://sf3-ttcdn-tos.pstatp.com/img/user-avatar/4d4ee02816f30af451bdf84282e122d9~300x300.image", "level": 1, "description": "会点NLP的前端开发萌新,目标是 瘦十斤换头像", "followee_count": 40, "follower_count": 3, "post_article_count": 34, "digg_article_count": 15, "got_digg_count": 29, "got_view_count": 3623, "post_shortmsg_count": 0, "digg_shortmsg_count": 0, "isfollowed": false, "favorable_author": 0, "power": 65, "study_point": 0, "university": {"university_id": "0", "name": "", "logo": ""}, "major": {"major_id": "0", "parent_id": "0", "name": ""}, "student_status": 0, "select_event_count": 0, "select_online_course_count": 0, "identity": 0, "is_select_annual": false, "select_annual_rank": 0, "annual_list_type": 0, "extraMap": {}, "is_logout": 0}, "category": {"category_id": "6809637767543259144", "category_name": "前端", "category_url": "frontend", "rank": 2, "back_ground": "https://lc-mhke0kuv.cn-n1.lcfile.com/8c95587526f346c0.png", "icon": "https://lc-mhke0kuv.cn-n1.lcfile.com/1c40f5eaba561e32.png", "ctime": 1457483942, "mtime": 1432503190, "show_type": 3, "item_type": 2, "promote_tag_cap": 4, "promote_priority": 2}, "tags": [{"id": 2546983, "tag_id": "6809641039037464589", "tag_name": "LeetCode", "color": "#000000", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/155748584224691639f51dce773ead8d4233400c24546.jpg~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1489518382, "mtime": 1631692819, "id_type": 9, "tag_alias": "", "post_article_count": 6296, "concern_user_count": 11301}, {"id": 2546592, "tag_id": "6809640499062767624", "tag_name": "算法", "color": "#60ADFF", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/68a1097944c7fa1d7961.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1439503293, "mtime": 1631692675, "id_type": 9, "tag_alias": "", "post_article_count": 23471, "concern_user_count": 310821}], "user_interact": {"id": 6992970434635366437, "omitempty": 2, "user_id": 0, "is_digg": false, "is_follow": false, "is_collect": false}, "org": {"org_info": null, "org_user": null, "is_followed": false}, "req_id": "2021091516023101020405304626004CE7"}, {"article_id": "6967153378098937870", "article_info": {"article_id": "6967153378098937870", "user_id": "2559318802828711", "category_id": "6809637767543259144", "tag_ids": [6809641039037464589, 6809640407484334093, 6809640398105870343], "visible_level": 0, "link_url": "", "cover_image": "https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/ff3ed96779ff4852af36ed2088f82e9a~tplv-k3u1fbpfcp-watermark.image", "is_gfw": 0, "title": "HOT100——寻找两个正序数组的中位数(JS实现)", "brief_content": "题目描述 解题思路 本题采用双指针的解题方法。 一个指针指向数组1。 一个指针指向数组2。 依次比较两个指针指向的元素的大小,谁小谁加到排序好的数组中,直到一方遍历完,将没遍历完的全部加到排序好的数组", "is_english": 0, "is_original": 1, "user_index": 0, "original_type": 0, "original_author": "", "content": "", "ctime": "1622166882", "mtime": "1622442618", "rtime": "1622442618", "draft_id": "6967151050621091853", "view_count": 259, "collect_count": 0, "digg_count": 6, "comment_count": 0, "hot_index": 18, "is_hot": 0, "rank_index": 0.00066713, "status": 2, "verify_status": 1, "audit_status": 2, "mark_content": ""}, "author_user_info": {"user_id": "2559318802828711", "user_name": "Always_positive", "company": "西安电子科技大学", "job_title": "终身学习者", "avatar_large": "https://sf6-ttcdn-tos.pstatp.com/img/user-avatar/517e82e4420199f579614e9a85b16cf6~300x300.image", "level": 3, "description": "自律、学习", "followee_count": 111, "follower_count": 466, "post_article_count": 521, "digg_article_count": 733, "got_digg_count": 1325, "got_view_count": 53315, "post_shortmsg_count": 17, "digg_shortmsg_count": 24, "isfollowed": false, "favorable_author": 0, "power": 1859, "study_point": 0, "university": {"university_id": "0", "name": "", "logo": ""}, "major": {"major_id": "0", "parent_id": "0", "name": ""}, "student_status": 0, "select_event_count": 0, "select_online_course_count": 0, "identity": 0, "is_select_annual": false, "select_annual_rank": 0, "annual_list_type": 0, "extraMap": {}, "is_logout": 0}, "category": {"category_id": "6809637767543259144", "category_name": "前端", "category_url": "frontend", "rank": 2, "back_ground": "https://lc-mhke0kuv.cn-n1.lcfile.com/8c95587526f346c0.png", "icon": "https://lc-mhke0kuv.cn-n1.lcfile.com/1c40f5eaba561e32.png", "ctime": 1457483942, "mtime": 1432503190, "show_type": 3, "item_type": 2, "promote_tag_cap": 4, "promote_priority": 2}, "tags": [{"id": 2546983, "tag_id": "6809641039037464589", "tag_name": "LeetCode", "color": "#000000", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/155748584224691639f51dce773ead8d4233400c24546.jpg~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1489518382, "mtime": 1631692819, "id_type": 9, "tag_alias": "", "post_article_count": 6296, "concern_user_count": 11301}, {"id": 2546526, "tag_id": "6809640407484334093", "tag_name": "前端", "color": "#60ADFF", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/bac28828a49181c34110.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 1, "ctime": 1435971546, "mtime": 1631692835, "id_type": 9, "tag_alias": "", "post_article_count": 88827, "concern_user_count": 527704}, {"id": 2546519, "tag_id": "6809640398105870343", "tag_name": "JavaScript", "color": "#616161", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/5d70fd6af940df373834.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1435884803, "mtime": 1631692583, "id_type": 9, "tag_alias": "", "post_article_count": 67405, "concern_user_count": 398956}], "user_interact": {"id": 6967153378098937870, "omitempty": 2, "user_id": 0, "is_digg": false, "is_follow": false, "is_collect": false}, "org": {"org_info": null, "org_user": null, "is_followed": false}, "req_id": "2021091516023101020405304626004CE7"}, {"article_id": "6992586885902106638", "article_info": {"article_id": "6992586885902106638", "user_id": "2181848597012078", "category_id": "6809637767543259144", "tag_ids": [6809641039037464589, 6809640499062767624], "visible_level": 0, "link_url": "", "cover_image": "", "is_gfw": 0, "title": "LeetCode 41 First Missing Positive (Tag:Array Difficulty:Hard)", "brief_content": "这是我参与8月更文挑战的第4天,活动详情查看:8月更文挑战 前言 关于 LeetCode 数组类型题目的相关解法,可见LeetCode 数组类型题目做前必看,分类别解法总结了题目,可以用来单项提高。觉", "is_english": 0, "is_original": 1, "user_index": 2.171231765800281, "original_type": 0, "original_author": "", "content": "", "ctime": "1628088582", "mtime": "1628132875", "rtime": "1628132875", "draft_id": "6992575962252591135", "view_count": 75, "collect_count": 0, "digg_count": 0, "comment_count": 0, "hot_index": 3, "is_hot": 0, "rank_index": 0.00065989, "status": 2, "verify_status": 1, "audit_status": 2, "mark_content": ""}, "author_user_info": {"user_id": "2181848597012078", "user_name": "AllenLMN", "company": "", "job_title": "前端工程师", "avatar_large": "https://sf3-ttcdn-tos.pstatp.com/img/user-avatar/4d4ee02816f30af451bdf84282e122d9~300x300.image", "level": 1, "description": "会点NLP的前端开发萌新,目标是 瘦十斤换头像", "followee_count": 40, "follower_count": 3, "post_article_count": 34, "digg_article_count": 15, "got_digg_count": 29, "got_view_count": 3623, "post_shortmsg_count": 0, "digg_shortmsg_count": 0, "isfollowed": false, "favorable_author": 0, "power": 65, "study_point": 0, "university": {"university_id": "0", "name": "", "logo": ""}, "major": {"major_id": "0", "parent_id": "0", "name": ""}, "student_status": 0, "select_event_count": 0, "select_online_course_count": 0, "identity": 0, "is_select_annual": false, "select_annual_rank": 0, "annual_list_type": 0, "extraMap": {}, "is_logout": 0}, "category": {"category_id": "6809637767543259144", "category_name": "前端", "category_url": "frontend", "rank": 2, "back_ground": "https://lc-mhke0kuv.cn-n1.lcfile.com/8c95587526f346c0.png", "icon": "https://lc-mhke0kuv.cn-n1.lcfile.com/1c40f5eaba561e32.png", "ctime": 1457483942, "mtime": 1432503190, "show_type": 3, "item_type": 2, "promote_tag_cap": 4, "promote_priority": 2}, "tags": [{"id": 2546983, "tag_id": "6809641039037464589", "tag_name": "LeetCode", "color": "#000000", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/155748584224691639f51dce773ead8d4233400c24546.jpg~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1489518382, "mtime": 1631692819, "id_type": 9, "tag_alias": "", "post_article_count": 6296, "concern_user_count": 11301}, {"id": 2546592, "tag_id": "6809640499062767624", "tag_name": "算法", "color": "#60ADFF", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/68a1097944c7fa1d7961.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1439503293, "mtime": 1631692675, "id_type": 9, "tag_alias": "", "post_article_count": 23471, "concern_user_count": 310821}], "user_interact": {"id": 6992586885902106638, "omitempty": 2, "user_id": 0, "is_digg": false, "is_follow": false, "is_collect": false}, "org": {"org_info": null, "org_user": null, "is_followed": false}, "req_id": "2021091516023101020405304626004CE7"}, {"article_id": "6995175994487210020", "article_info": {"article_id": "6995175994487210020", "user_id": "3025489497950094", "category_id": "6809637767543259144", "tag_ids": [6809640499062767624, 6809641039037464589], "visible_level": 0, "link_url": "", "cover_image": "https://p9-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/aeb15127921a42ba842febd8d3b778d2~tplv-k3u1fbpfcp-watermark.image", "is_gfw": 0, "title": "「前端刷题」11. 盛最多水的容器", "brief_content": "给你 n 个非负整数 a1,a2,...,a``n,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i", "is_english": 0, "is_original": 1, "user_index": 0, "original_type": 0, "original_author": "", "content": "", "ctime": "1628691460", "mtime": "1628738305", "rtime": "1628738305", "draft_id": "6995175153990795301", "view_count": 60, "collect_count": 0, "digg_count": 1, "comment_count": 0, "hot_index": 4, "is_hot": 0, "rank_index": 0.00065931, "status": 2, "verify_status": 1, "audit_status": 2, "mark_content": ""}, "author_user_info": {"user_id": "3025489497950094", "user_name": "明无生", "company": "武林", "job_title": "侠客", "avatar_large": "https://sf3-ttcdn-tos.pstatp.com/img/user-avatar/2d4deb94951dc1809fbb962839fc092f~300x300.image", "level": 1, "description": "无怨无悔我走我路,走不尽天涯路。", "followee_count": 0, "follower_count": 0, "post_article_count": 31, "digg_article_count": 2, "got_digg_count": 12, "got_view_count": 1807, "post_shortmsg_count": 0, "digg_shortmsg_count": 0, "isfollowed": false, "favorable_author": 0, "power": 30, "study_point": 0, "university": {"university_id": "0", "name": "", "logo": ""}, "major": {"major_id": "0", "parent_id": "0", "name": ""}, "student_status": 0, "select_event_count": 0, "select_online_course_count": 0, "identity": 0, "is_select_annual": false, "select_annual_rank": 0, "annual_list_type": 0, "extraMap": {}, "is_logout": 0}, "category": {"category_id": "6809637767543259144", "category_name": "前端", "category_url": "frontend", "rank": 2, "back_ground": "https://lc-mhke0kuv.cn-n1.lcfile.com/8c95587526f346c0.png", "icon": "https://lc-mhke0kuv.cn-n1.lcfile.com/1c40f5eaba561e32.png", "ctime": 1457483942, "mtime": 1432503190, "show_type": 3, "item_type": 2, "promote_tag_cap": 4, "promote_priority": 2}, "tags": [{"id": 2546592, "tag_id": "6809640499062767624", "tag_name": "算法", "color": "#60ADFF", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/68a1097944c7fa1d7961.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1439503293, "mtime": 1631692675, "id_type": 9, "tag_alias": "", "post_article_count": 23471, "concern_user_count": 310821}, {"id": 2546983, "tag_id": "6809641039037464589", "tag_name": "LeetCode", "color": "#000000", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/155748584224691639f51dce773ead8d4233400c24546.jpg~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1489518382, "mtime": 1631692819, "id_type": 9, "tag_alias": "", "post_article_count": 6296, "concern_user_count": 11301}], "user_interact": {"id": 6995175994487210020, "omitempty": 2, "user_id": 0, "is_digg": false, "is_follow": false, "is_collect": false}, "org": {"org_info": null, "org_user": null, "is_followed": false}, "req_id": "2021091516023101020405304626004CE7"}, {"article_id": "6964541421487390734", "article_info": {"article_id": "6964541421487390734", "user_id": "2559318802828711", "category_id": "6809637767543259144", "tag_ids": [6809641039037464589], "visible_level": 0, "link_url": "", "cover_image": "https://p6-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/b3e40c67f2364fb9bd95b7728248da46~tplv-k3u1fbpfcp-watermark.image", "is_gfw": 0, "title": "剑指Offer——把字符串转换成整数(JS实现)", "brief_content": "题目描述 解题思路 本题需要考虑的一是数值是由范围的,其次就是正则表达式怎么写,当然本题也可以不使用正则表达式,但是本次题解采用的是正则,因为这样简单易懂。 首先去除字符串两侧的空格。 使用正则表达式", "is_english": 0, "is_original": 1, "user_index": 0, "original_type": 0, "original_author": "", "content": "", "ctime": "1621558736", "mtime": "1621578897", "rtime": "1621578897", "draft_id": "6964539746294956046", "view_count": 317, "collect_count": 0, "digg_count": 5, "comment_count": 0, "hot_index": 20, "is_hot": 0, "rank_index": 0.00065754, "status": 2, "verify_status": 1, "audit_status": 2, "mark_content": ""}, "author_user_info": {"user_id": "2559318802828711", "user_name": "Always_positive", "company": "西安电子科技大学", "job_title": "终身学习者", "avatar_large": "https://sf6-ttcdn-tos.pstatp.com/img/user-avatar/517e82e4420199f579614e9a85b16cf6~300x300.image", "level": 3, "description": "自律、学习", "followee_count": 111, "follower_count": 466, "post_article_count": 521, "digg_article_count": 733, "got_digg_count": 1325, "got_view_count": 53315, "post_shortmsg_count": 17, "digg_shortmsg_count": 24, "isfollowed": false, "favorable_author": 0, "power": 1859, "study_point": 0, "university": {"university_id": "0", "name": "", "logo": ""}, "major": {"major_id": "0", "parent_id": "0", "name": ""}, "student_status": 0, "select_event_count": 0, "select_online_course_count": 0, "identity": 0, "is_select_annual": false, "select_annual_rank": 0, "annual_list_type": 0, "extraMap": {}, "is_logout": 0}, "category": {"category_id": "6809637767543259144", "category_name": "前端", "category_url": "frontend", "rank": 2, "back_ground": "https://lc-mhke0kuv.cn-n1.lcfile.com/8c95587526f346c0.png", "icon": "https://lc-mhke0kuv.cn-n1.lcfile.com/1c40f5eaba561e32.png", "ctime": 1457483942, "mtime": 1432503190, "show_type": 3, "item_type": 2, "promote_tag_cap": 4, "promote_priority": 2}, "tags": [{"id": 2546983, "tag_id": "6809641039037464589", "tag_name": "LeetCode", "color": "#000000", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/155748584224691639f51dce773ead8d4233400c24546.jpg~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1489518382, "mtime": 1631692819, "id_type": 9, "tag_alias": "", "post_article_count": 6296, "concern_user_count": 11301}], "user_interact": {"id": 6964541421487390734, "omitempty": 2, "user_id": 0, "is_digg": false, "is_follow": false, "is_collect": false}, "org": {"org_info": null, "org_user": null, "is_followed": false}, "req_id": "2021091516023101020405304626004CE7"}, {"article_id": "6983929411657531423", "article_info": {"article_id": "6983929411657531423", "user_id": "2568097069536599", "category_id": "6809637767543259144", "tag_ids": [6809640499062767624, 6809641039037464589], "visible_level": 0, "link_url": "", "cover_image": "", "is_gfw": 0, "title": "LeetCode第86题:分隔链表", "brief_content": "题干 给你一个链表的头节点 head 和一个特定值 x ,请你对链表进行分隔,使得所有 小于 x 的节点都出现在 大于或等于 x 的节点之前。 你应当 保留 两个分区中每个节点的初始相对位置。 实例1", "is_english": 0, "is_original": 1, "user_index": 2.234293227019025, "original_type": 0, "original_author": "", "content": "", "ctime": "1626072831", "mtime": "1626081795", "rtime": "1626081795", "draft_id": "6983929318850658340", "view_count": 100, "collect_count": 1, "digg_count": 2, "comment_count": 0, "hot_index": 7, "is_hot": 0, "rank_index": 0.00065723, "status": 2, "verify_status": 1, "audit_status": 2, "mark_content": ""}, "author_user_info": {"user_id": "2568097069536599", "user_name": "奥奥奥", "company": ".", "job_title": "💰端开发", "avatar_large": "https://sf1-ttcdn-tos.pstatp.com/img/user-avatar/1a54c595972706e5b0bc897159879404~300x300.image", "level": 2, "description": "", "followee_count": 7, "follower_count": 20, "post_article_count": 134, "digg_article_count": 189, "got_digg_count": 239, "got_view_count": 13812, "post_shortmsg_count": 0, "digg_shortmsg_count": 0, "isfollowed": false, "favorable_author": 0, "power": 377, "study_point": 0, "university": {"university_id": "0", "name": "", "logo": ""}, "major": {"major_id": "0", "parent_id": "0", "name": ""}, "student_status": 0, "select_event_count": 0, "select_online_course_count": 0, "identity": 0, "is_select_annual": false, "select_annual_rank": 0, "annual_list_type": 0, "extraMap": {}, "is_logout": 0}, "category": {"category_id": "6809637767543259144", "category_name": "前端", "category_url": "frontend", "rank": 2, "back_ground": "https://lc-mhke0kuv.cn-n1.lcfile.com/8c95587526f346c0.png", "icon": "https://lc-mhke0kuv.cn-n1.lcfile.com/1c40f5eaba561e32.png", "ctime": 1457483942, "mtime": 1432503190, "show_type": 3, "item_type": 2, "promote_tag_cap": 4, "promote_priority": 2}, "tags": [{"id": 2546592, "tag_id": "6809640499062767624", "tag_name": "算法", "color": "#60ADFF", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/68a1097944c7fa1d7961.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1439503293, "mtime": 1631692675, "id_type": 9, "tag_alias": "", "post_article_count": 23471, "concern_user_count": 310821}, {"id": 2546983, "tag_id": "6809641039037464589", "tag_name": "LeetCode", "color": "#000000", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/155748584224691639f51dce773ead8d4233400c24546.jpg~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1489518382, "mtime": 1631692819, "id_type": 9, "tag_alias": "", "post_article_count": 6296, "concern_user_count": 11301}], "user_interact": {"id": 6983929411657531423, "omitempty": 2, "user_id": 0, "is_digg": false, "is_follow": false, "is_collect": false}, "org": {"org_info": null, "org_user": null, "is_followed": false}, "req_id": "2021091516023101020405304626004CE7"}, {"article_id": "6991837040962699277", "article_info": {"article_id": "6991837040962699277", "user_id": "2181848597012078", "category_id": "6809637767543259144", "tag_ids": [6809641039037464589], "visible_level": 0, "link_url": "", "cover_image": "", "is_gfw": 0, "title": "LeetCode 39 Combination Sum (Tag:Array Difficulty:Medium)|8月更文挑战", "brief_content": "前言 关于 LeetCode 数组类型题目的相关解法,可见LeetCode 数组类型题目做前必看,分类别解法总结了题目,可以用来单项提高。觉得有帮助的话,记得多多点赞关注哦,感谢! 题目描述 给定一个", "is_english": 0, "is_original": 1, "user_index": 2.356581185211474, "original_type": 0, "original_author": "", "content": "", "ctime": "1627913940", "mtime": "1627962203", "rtime": "1627962203", "draft_id": "6991823327430098951", "view_count": 65, "collect_count": 0, "digg_count": 0, "comment_count": 0, "hot_index": 3, "is_hot": 0, "rank_index": 0.00065027, "status": 2, "verify_status": 1, "audit_status": 2, "mark_content": ""}, "author_user_info": {"user_id": "2181848597012078", "user_name": "AllenLMN", "company": "", "job_title": "前端工程师", "avatar_large": "https://sf3-ttcdn-tos.pstatp.com/img/user-avatar/4d4ee02816f30af451bdf84282e122d9~300x300.image", "level": 1, "description": "会点NLP的前端开发萌新,目标是 瘦十斤换头像", "followee_count": 40, "follower_count": 3, "post_article_count": 34, "digg_article_count": 15, "got_digg_count": 29, "got_view_count": 3623, "post_shortmsg_count": 0, "digg_shortmsg_count": 0, "isfollowed": false, "favorable_author": 0, "power": 65, "study_point": 0, "university": {"university_id": "0", "name": "", "logo": ""}, "major": {"major_id": "0", "parent_id": "0", "name": ""}, "student_status": 0, "select_event_count": 0, "select_online_course_count": 0, "identity": 0, "is_select_annual": false, "select_annual_rank": 0, "annual_list_type": 0, "extraMap": {}, "is_logout": 0}, "category": {"category_id": "6809637767543259144", "category_name": "前端", "category_url": "frontend", "rank": 2, "back_ground": "https://lc-mhke0kuv.cn-n1.lcfile.com/8c95587526f346c0.png", "icon": "https://lc-mhke0kuv.cn-n1.lcfile.com/1c40f5eaba561e32.png", "ctime": 1457483942, "mtime": 1432503190, "show_type": 3, "item_type": 2, "promote_tag_cap": 4, "promote_priority": 2}, "tags": [{"id": 2546983, "tag_id": "6809641039037464589", "tag_name": "LeetCode", "color": "#000000", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/155748584224691639f51dce773ead8d4233400c24546.jpg~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1489518382, "mtime": 1631692819, "id_type": 9, "tag_alias": "", "post_article_count": 6296, "concern_user_count": 11301}], "user_interact": {"id": 6991837040962699277, "omitempty": 2, "user_id": 0, "is_digg": false, "is_follow": false, "is_collect": false}, "org": {"org_info": null, "org_user": null, "is_followed": false}, "req_id": "2021091516023101020405304626004CE7"}, {"article_id": "6987217727769280519", "article_info": {"article_id": "6987217727769280519", "user_id": "2181848597012078", "category_id": "6809637767543259144", "tag_ids": [6809641039037464589, 6809640499062767624], "visible_level": 0, "link_url": "", "cover_image": "", "is_gfw": 0, "title": "LeetCode 34 Find First and Last Position of Element (Tag:Array Difficulty:Mid)", "brief_content": "前言 关于 LeetCode 数组类型题目的相关解法,可见LeetCode 数组类型题目做前必看,分类别解法总结了题目,可以用来单项提高。觉得有帮助的话,记得多多点赞关注哦,感谢! 题目描述 给定一个", "is_english": 0, "is_original": 1, "user_index": 2.390835950622662, "original_type": 0, "original_author": "", "content": "", "ctime": "1626838466", "mtime": "1626849913", "rtime": "1626849913", "draft_id": "6986944101065162760", "view_count": 100, "collect_count": 0, "digg_count": 0, "comment_count": 0, "hot_index": 5, "is_hot": 0, "rank_index": 0.00063765, "status": 2, "verify_status": 1, "audit_status": 2, "mark_content": ""}, "author_user_info": {"user_id": "2181848597012078", "user_name": "AllenLMN", "company": "", "job_title": "前端工程师", "avatar_large": "https://sf3-ttcdn-tos.pstatp.com/img/user-avatar/4d4ee02816f30af451bdf84282e122d9~300x300.image", "level": 1, "description": "会点NLP的前端开发萌新,目标是 瘦十斤换头像", "followee_count": 40, "follower_count": 3, "post_article_count": 34, "digg_article_count": 15, "got_digg_count": 29, "got_view_count": 3623, "post_shortmsg_count": 0, "digg_shortmsg_count": 0, "isfollowed": false, "favorable_author": 0, "power": 65, "study_point": 0, "university": {"university_id": "0", "name": "", "logo": ""}, "major": {"major_id": "0", "parent_id": "0", "name": ""}, "student_status": 0, "select_event_count": 0, "select_online_course_count": 0, "identity": 0, "is_select_annual": false, "select_annual_rank": 0, "annual_list_type": 0, "extraMap": {}, "is_logout": 0}, "category": {"category_id": "6809637767543259144", "category_name": "前端", "category_url": "frontend", "rank": 2, "back_ground": "https://lc-mhke0kuv.cn-n1.lcfile.com/8c95587526f346c0.png", "icon": "https://lc-mhke0kuv.cn-n1.lcfile.com/1c40f5eaba561e32.png", "ctime": 1457483942, "mtime": 1432503190, "show_type": 3, "item_type": 2, "promote_tag_cap": 4, "promote_priority": 2}, "tags": [{"id": 2546983, "tag_id": "6809641039037464589", "tag_name": "LeetCode", "color": "#000000", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/155748584224691639f51dce773ead8d4233400c24546.jpg~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1489518382, "mtime": 1631692819, "id_type": 9, "tag_alias": "", "post_article_count": 6296, "concern_user_count": 11301}, {"id": 2546592, "tag_id": "6809640499062767624", "tag_name": "算法", "color": "#60ADFF", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/68a1097944c7fa1d7961.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1439503293, "mtime": 1631692675, "id_type": 9, "tag_alias": "", "post_article_count": 23471, "concern_user_count": 310821}], "user_interact": {"id": 6987217727769280519, "omitempty": 2, "user_id": 0, "is_digg": false, "is_follow": false, "is_collect": false}, "org": {"org_info": null, "org_user": null, "is_followed": false}, "req_id": "2021091516023101020405304626004CE7"}, {"article_id": "6971696625462984711", "article_info": {"article_id": "6971696625462984711", "user_id": "2559318802828711", "category_id": "6809637767543259144", "tag_ids": [6809641039037464589, 6809640407484334093], "visible_level": 0, "link_url": "", "cover_image": "https://p9-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/db6e9c9f6dab4cfe9e4318fa830ccd60~tplv-k3u1fbpfcp-watermark.image", "is_gfw": 0, "title": "HOT100——括号生成(JS实现)", "brief_content": "题目描述 解题思路 本题采用DFS的思想。 只要有左括号剩余的时候,就将左括号剩余数量-1,然后继续投入DFS。 当左括号的长度小于有括号的长度时,将右括号剩余数量-1,然后继续投入DFS。 实现代码", "is_english": 0, "is_original": 1, "user_index": 0, "original_type": 0, "original_author": "", "content": "", "ctime": "1623224786", "mtime": "1623305940", "rtime": "1623305940", "draft_id": "6971680263206076452", "view_count": 245, "collect_count": 0, "digg_count": 3, "comment_count": 0, "hot_index": 15, "is_hot": 0, "rank_index": 0.0006289, "status": 2, "verify_status": 1, "audit_status": 2, "mark_content": ""}, "author_user_info": {"user_id": "2559318802828711", "user_name": "Always_positive", "company": "西安电子科技大学", "job_title": "终身学习者", "avatar_large": "https://sf6-ttcdn-tos.pstatp.com/img/user-avatar/517e82e4420199f579614e9a85b16cf6~300x300.image", "level": 3, "description": "自律、学习", "followee_count": 111, "follower_count": 466, "post_article_count": 521, "digg_article_count": 733, "got_digg_count": 1325, "got_view_count": 53315, "post_shortmsg_count": 17, "digg_shortmsg_count": 24, "isfollowed": false, "favorable_author": 0, "power": 1859, "study_point": 0, "university": {"university_id": "0", "name": "", "logo": ""}, "major": {"major_id": "0", "parent_id": "0", "name": ""}, "student_status": 0, "select_event_count": 0, "select_online_course_count": 0, "identity": 0, "is_select_annual": false, "select_annual_rank": 0, "annual_list_type": 0, "extraMap": {}, "is_logout": 0}, "category": {"category_id": "6809637767543259144", "category_name": "前端", "category_url": "frontend", "rank": 2, "back_ground": "https://lc-mhke0kuv.cn-n1.lcfile.com/8c95587526f346c0.png", "icon": "https://lc-mhke0kuv.cn-n1.lcfile.com/1c40f5eaba561e32.png", "ctime": 1457483942, "mtime": 1432503190, "show_type": 3, "item_type": 2, "promote_tag_cap": 4, "promote_priority": 2}, "tags": [{"id": 2546983, "tag_id": "6809641039037464589", "tag_name": "LeetCode", "color": "#000000", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/155748584224691639f51dce773ead8d4233400c24546.jpg~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1489518382, "mtime": 1631692819, "id_type": 9, "tag_alias": "", "post_article_count": 6296, "concern_user_count": 11301}, {"id": 2546526, "tag_id": "6809640407484334093", "tag_name": "前端", "color": "#60ADFF", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/bac28828a49181c34110.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 1, "ctime": 1435971546, "mtime": 1631692835, "id_type": 9, "tag_alias": "", "post_article_count": 88827, "concern_user_count": 527704}], "user_interact": {"id": 6971696625462984711, "omitempty": 2, "user_id": 0, "is_digg": false, "is_follow": false, "is_collect": false}, "org": {"org_info": null, "org_user": null, "is_followed": false}, "req_id": "2021091516023101020405304626004CE7"}, {"article_id": "6994821895350648863", "article_info": {"article_id": "6994821895350648863", "user_id": "2181848597012078", "category_id": "6809637767543259144", "tag_ids": [6809641039037464589], "visible_level": 0, "link_url": "", "cover_image": "", "is_gfw": 0, "title": "LeetCode 51 N-Queens (Tag:Array Difficulty:Hard)", "brief_content": "这是我参与8月更文挑战的第10天,活动详情查看:8月更文挑战 前言 关于 LeetCode 数组类型题目的相关解法,可见LeetCode 数组类型题目做前必看,分类别解法总结了题目,可以用来单项提高。", "is_english": 0, "is_original": 1, "user_index": 1.915155642176354, "original_type": 0, "original_author": "", "content": "", "ctime": "1628608957", "mtime": "1628656839", "rtime": "1628656839", "draft_id": "6994808610542845960", "view_count": 45, "collect_count": 0, "digg_count": 0, "comment_count": 0, "hot_index": 2, "is_hot": 0, "rank_index": 0.00062269, "status": 2, "verify_status": 1, "audit_status": 2, "mark_content": ""}, "author_user_info": {"user_id": "2181848597012078", "user_name": "AllenLMN", "company": "", "job_title": "前端工程师", "avatar_large": "https://sf3-ttcdn-tos.pstatp.com/img/user-avatar/4d4ee02816f30af451bdf84282e122d9~300x300.image", "level": 1, "description": "会点NLP的前端开发萌新,目标是 瘦十斤换头像", "followee_count": 40, "follower_count": 3, "post_article_count": 34, "digg_article_count": 15, "got_digg_count": 29, "got_view_count": 3623, "post_shortmsg_count": 0, "digg_shortmsg_count": 0, "isfollowed": false, "favorable_author": 0, "power": 65, "study_point": 0, "university": {"university_id": "0", "name": "", "logo": ""}, "major": {"major_id": "0", "parent_id": "0", "name": ""}, "student_status": 0, "select_event_count": 0, "select_online_course_count": 0, "identity": 0, "is_select_annual": false, "select_annual_rank": 0, "annual_list_type": 0, "extraMap": {}, "is_logout": 0}, "category": {"category_id": "6809637767543259144", "category_name": "前端", "category_url": "frontend", "rank": 2, "back_ground": "https://lc-mhke0kuv.cn-n1.lcfile.com/8c95587526f346c0.png", "icon": "https://lc-mhke0kuv.cn-n1.lcfile.com/1c40f5eaba561e32.png", "ctime": 1457483942, "mtime": 1432503190, "show_type": 3, "item_type": 2, "promote_tag_cap": 4, "promote_priority": 2}, "tags": [{"id": 2546983, "tag_id": "6809641039037464589", "tag_name": "LeetCode", "color": "#000000", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/155748584224691639f51dce773ead8d4233400c24546.jpg~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1489518382, "mtime": 1631692819, "id_type": 9, "tag_alias": "", "post_article_count": 6296, "concern_user_count": 11301}], "user_interact": {"id": 6994821895350648863, "omitempty": 2, "user_id": 0, "is_digg": false, "is_follow": false, "is_collect": false}, "org": {"org_info": null, "org_user": null, "is_followed": false}, "req_id": "2021091516023101020405304626004CE7"}, {"article_id": "6941172390973931557", "article_info": {"article_id": "6941172390973931557", "user_id": "3711585972125896", "category_id": "6809637767543259144", "tag_ids": [6809641039037464589], "visible_level": 0, "link_url": "", "cover_image": "", "is_gfw": 0, "title": "leetcode : 3无重复字符最长子串(中等)", "brief_content": "给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。", "is_english": 0, "is_original": 1, "user_index": 0, "original_type": 0, "original_author": "", "content": "", "ctime": "1616117653", "mtime": "1616135281", "rtime": "1616135281", "draft_id": "6941147270951731237", "view_count": 233, "collect_count": 1, "digg_count": 21, "comment_count": 1, "hot_index": 33, "is_hot": 0, "rank_index": 0.00062004, "status": 2, "verify_status": 1, "audit_status": 2, "mark_content": ""}, "author_user_info": {"user_id": "3711585972125896", "user_name": "YU_yu", "company": "东华理工菜鸟公司", "job_title": "大三学生", "avatar_large": "https://sf1-ttcdn-tos.pstatp.com/img/user-avatar/1dbe84270742d689fb5cf84549fb4145~300x300.image", "level": 2, "description": "前端划水小菜鸡", "followee_count": 13, "follower_count": 23, "post_article_count": 8, "digg_article_count": 63, "got_digg_count": 175, "got_view_count": 4473, "post_shortmsg_count": 0, "digg_shortmsg_count": 0, "isfollowed": false, "favorable_author": 0, "power": 219, "study_point": 0, "university": {"university_id": "0", "name": "", "logo": ""}, "major": {"major_id": "0", "parent_id": "0", "name": ""}, "student_status": 0, "select_event_count": 0, "select_online_course_count": 0, "identity": 0, "is_select_annual": false, "select_annual_rank": 0, "annual_list_type": 0, "extraMap": {}, "is_logout": 0}, "category": {"category_id": "6809637767543259144", "category_name": "前端", "category_url": "frontend", "rank": 2, "back_ground": "https://lc-mhke0kuv.cn-n1.lcfile.com/8c95587526f346c0.png", "icon": "https://lc-mhke0kuv.cn-n1.lcfile.com/1c40f5eaba561e32.png", "ctime": 1457483942, "mtime": 1432503190, "show_type": 3, "item_type": 2, "promote_tag_cap": 4, "promote_priority": 2}, "tags": [{"id": 2546983, "tag_id": "6809641039037464589", "tag_name": "LeetCode", "color": "#000000", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/155748584224691639f51dce773ead8d4233400c24546.jpg~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1489518382, "mtime": 1631692819, "id_type": 9, "tag_alias": "", "post_article_count": 6296, "concern_user_count": 11301}], "user_interact": {"id": 6941172390973931557, "omitempty": 2, "user_id": 0, "is_digg": false, "is_follow": false, "is_collect": false}, "org": {"org_info": null, "org_user": null, "is_followed": false}, "req_id": "2021091516023101020405304626004CE7"}, {"article_id": "6999988010993319949", "article_info": {"article_id": "6999988010993319949", "user_id": "3025489497950094", "category_id": "6809637767543259144", "tag_ids": [6809640499062767624, 6809641039037464589], "visible_level": 0, "link_url": "", "cover_image": "https://p1-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/256c911e6f4e4415afdbbe078d3e5c5b~tplv-k3u1fbpfcp-watermark.image", "is_gfw": 0, "title": "「前端刷题」23. 合并K个升序链表", "brief_content": "给你一个链表数组,每个链表都已经按升序排列。 请你将所有链表合并到一个升序链表中,返回合并后的链表。   示例 1: 输入: lis", "is_english": 0, "is_original": 1, "user_index": 0, "original_type": 0, "original_author": "", "content": "", "ctime": "1629811803", "mtime": "1629860490", "rtime": "1629860490", "draft_id": "6999986695672184839", "view_count": 42, "collect_count": 0, "digg_count": 0, "comment_count": 0, "hot_index": 2, "is_hot": 0, "rank_index": 0.00061825, "status": 2, "verify_status": 1, "audit_status": 2, "mark_content": ""}, "author_user_info": {"user_id": "3025489497950094", "user_name": "明无生", "company": "武林", "job_title": "侠客", "avatar_large": "https://sf3-ttcdn-tos.pstatp.com/img/user-avatar/2d4deb94951dc1809fbb962839fc092f~300x300.image", "level": 1, "description": "无怨无悔我走我路,走不尽天涯路。", "followee_count": 0, "follower_count": 0, "post_article_count": 31, "digg_article_count": 2, "got_digg_count": 12, "got_view_count": 1807, "post_shortmsg_count": 0, "digg_shortmsg_count": 0, "isfollowed": false, "favorable_author": 0, "power": 30, "study_point": 0, "university": {"university_id": "0", "name": "", "logo": ""}, "major": {"major_id": "0", "parent_id": "0", "name": ""}, "student_status": 0, "select_event_count": 0, "select_online_course_count": 0, "identity": 0, "is_select_annual": false, "select_annual_rank": 0, "annual_list_type": 0, "extraMap": {}, "is_logout": 0}, "category": {"category_id": "6809637767543259144", "category_name": "前端", "category_url": "frontend", "rank": 2, "back_ground": "https://lc-mhke0kuv.cn-n1.lcfile.com/8c95587526f346c0.png", "icon": "https://lc-mhke0kuv.cn-n1.lcfile.com/1c40f5eaba561e32.png", "ctime": 1457483942, "mtime": 1432503190, "show_type": 3, "item_type": 2, "promote_tag_cap": 4, "promote_priority": 2}, "tags": [{"id": 2546592, "tag_id": "6809640499062767624", "tag_name": "算法", "color": "#60ADFF", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/68a1097944c7fa1d7961.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1439503293, "mtime": 1631692675, "id_type": 9, "tag_alias": "", "post_article_count": 23471, "concern_user_count": 310821}, {"id": 2546983, "tag_id": "6809641039037464589", "tag_name": "LeetCode", "color": "#000000", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/155748584224691639f51dce773ead8d4233400c24546.jpg~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1489518382, "mtime": 1631692819, "id_type": 9, "tag_alias": "", "post_article_count": 6296, "concern_user_count": 11301}], "user_interact": {"id": 6999988010993319949, "omitempty": 2, "user_id": 0, "is_digg": false, "is_follow": false, "is_collect": false}, "org": {"org_info": null, "org_user": null, "is_followed": false}, "req_id": "2021091516023101020405304626004CE7"}], "cursor": "eyJ2IjoiNzAwNzYyNzUzMTk4MTQyMjYyOCIsImkiOjI0MH0=", "count": 552, "has_more": true}
76d1807da6e30de90b7fc8d7ae5c3f2be4b808a3
c10f20abec372f81dbd6468ead208543f60940f1
/learning/20.BayesianNetwork/20.1.Iris_GaussianNB.py
8cd96f72d7add1efc07bd0c634a76cf4b1150c0f
[]
no_license
alenzhd/meachineLearning
64876e7a6c0b8b39a63a9eb586d306a3489b4447
1b66ce2f73b226548f07e45c8537b8286635a048
refs/heads/master
2021-08-24T10:55:52.056439
2017-12-09T10:26:37
2017-12-09T10:26:37
112,688,163
1
0
null
null
null
null
UTF-8
Python
false
false
2,854
py
#!/usr/bin/python # -*- coding:utf-8 -*- import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib as mpl from sklearn.preprocessing import StandardScaler, MinMaxScaler, PolynomialFeatures from sklearn.naive_bayes import GaussianNB, MultinomialNB from sklearn.pipeline import Pipeline from sklearn.metrics import accuracy_score from sklearn.model_selection import train_test_split from sklearn.neighbors import KNeighborsClassifier def iris_type(s): it = {'Iris-setosa': 0, 'Iris-versicolor': 1, 'Iris-virginica': 2} return it[s] if __name__ == "__main__": data = pd.read_csv('..\\8.Regression\\iris.data', header=None) x, y = data[np.arange(4)], data[4] y = pd.Categorical(values=y).codes feature_names = u'花萼长度', u'花萼宽度', u'花瓣长度', u'花瓣宽度' features = [0,1] x = x[features] x, x_test, y, y_test = train_test_split(x, y, train_size=0.7, random_state=0) priors = np.array((1,2,4), dtype=float) priors /= priors.sum() gnb = Pipeline([ ('sc', StandardScaler()), ('poly', PolynomialFeatures(degree=1)), ('clf', GaussianNB(priors=priors))]) # 由于鸢尾花数据是样本均衡的,其实不需要设置先验值 # gnb = KNeighborsClassifier(n_neighbors=3).fit(x, y.ravel()) gnb.fit(x, y.ravel()) y_hat = gnb.predict(x) print ('训练集准确度: %.2f%%' % (100 * accuracy_score(y, y_hat))) y_test_hat = gnb.predict(x_test) print ('测试集准确度:%.2f%%' % (100 * accuracy_score(y_test, y_test_hat))) # 画图 N, M = 500, 500 # 横纵各采样多少个值 x1_min, x2_min = x.min() x1_max, x2_max = x.max() t1 = np.linspace(x1_min, x1_max, N) t2 = np.linspace(x2_min, x2_max, M) x1, x2 = np.meshgrid(t1, t2) # 生成网格采样点 x_grid = np.stack((x1.flat, x2.flat), axis=1) # 测试点 mpl.rcParams['font.sans-serif'] = [u'simHei'] mpl.rcParams['axes.unicode_minus'] = False cm_light = mpl.colors.ListedColormap(['#77E0A0', '#FF8080', '#A0A0FF']) cm_dark = mpl.colors.ListedColormap(['g', 'r', 'b']) y_grid_hat = gnb.predict(x_grid) # 预测值 y_grid_hat = y_grid_hat.reshape(x1.shape) plt.figure(facecolor='w') plt.pcolormesh(x1, x2, y_grid_hat, cmap=cm_light) # 预测值的显示 plt.scatter(x[features[0]], x[features[1]], c=y, edgecolors='k', s=50, cmap=cm_dark) plt.scatter(x_test[features[0]], x_test[features[1]], c=y_test, marker='^', edgecolors='k', s=120, cmap=cm_dark) plt.xlabel(feature_names[features[0]], fontsize=13) plt.ylabel(feature_names[features[1]], fontsize=13) plt.xlim(x1_min, x1_max) plt.ylim(x2_min, x2_max) plt.title(u'GaussianNB对鸢尾花数据的分类结果', fontsize=18) plt.grid(True) plt.show()
fa3f7ccbf4b282e0ed863b3a8fc5815164a62dd5
48bba3541896587cd96112ff4a814d5d8ec6414c
/codes/infer_video1.py
e01911f5f5ff92f0c6a5d5b8471da8590f406570
[ "BSD-2-Clause" ]
permissive
Bala93/Digital-pathology
f056ebb42c7592fdca400ee0e832fb5225b91085
6be5f8a75d9ace9035e915b02244cf97af25ec96
refs/heads/master
2021-09-19T10:23:54.459477
2018-07-26T18:18:45
2018-07-26T18:18:45
102,435,574
2
0
null
null
null
null
UTF-8
Python
false
false
78
py
/media/htic/NewVolume1/murali/Object_detection/models/research/infer_video1.py
c63fff8d99a3dc4b7fc547ac13a5fde5ce61b21f
8a25ada37271acd5ea96d4a4e4e57f81bec221ac
/home/pi/GrovePi/Software/Python/others/temboo/Library/Fitbit/Social/CreateInvite.py
ad0fa7c6517b0cc3e0e04b248b8071b8d35346b8
[ "MIT", "Apache-2.0" ]
permissive
lupyuen/RaspberryPiImage
65cebead6a480c772ed7f0c4d0d4e08572860f08
664e8a74b4628d710feab5582ef59b344b9ffddd
refs/heads/master
2021-01-20T02:12:27.897902
2016-11-17T17:32:30
2016-11-17T17:32:30
42,438,362
7
8
null
null
null
null
UTF-8
Python
false
false
5,095
py
# -*- coding: utf-8 -*- ############################################################################### # # CreateInvite # Invites a user to become friends with authorized user. # # Python versions 2.6, 2.7, 3.x # # Copyright 2014, Temboo Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, # either express or implied. See the License for the specific # language governing permissions and limitations under the License. # # ############################################################################### from temboo.core.choreography import Choreography from temboo.core.choreography import InputSet from temboo.core.choreography import ResultSet from temboo.core.choreography import ChoreographyExecution import json class CreateInvite(Choreography): def __init__(self, temboo_session): """ Create a new instance of the CreateInvite Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. """ super(CreateInvite, self).__init__(temboo_session, '/Library/Fitbit/Social/CreateInvite') def new_input_set(self): return CreateInviteInputSet() def _make_result_set(self, result, path): return CreateInviteResultSet(result, path) def _make_execution(self, session, exec_id, path): return CreateInviteChoreographyExecution(session, exec_id, path) class CreateInviteInputSet(InputSet): """ An InputSet with methods appropriate for specifying the inputs to the CreateInvite Choreo. The InputSet object is used to specify input parameters when executing this Choreo. """ def set_AccessTokenSecret(self, value): """ Set the value of the AccessTokenSecret input for this Choreo. ((required, string) The Access Token Secret retrieved during the OAuth process.) """ super(CreateInviteInputSet, self)._set_input('AccessTokenSecret', value) def set_AccessToken(self, value): """ Set the value of the AccessToken input for this Choreo. ((required, string) The Access Token retrieved during the OAuth process.) """ super(CreateInviteInputSet, self)._set_input('AccessToken', value) def set_ConsumerKey(self, value): """ Set the value of the ConsumerKey input for this Choreo. ((required, string) The Consumer Key provided by Fitbit.) """ super(CreateInviteInputSet, self)._set_input('ConsumerKey', value) def set_ConsumerSecret(self, value): """ Set the value of the ConsumerSecret input for this Choreo. ((required, string) The Consumer Secret provided by Fitbit.) """ super(CreateInviteInputSet, self)._set_input('ConsumerSecret', value) def set_InvitedUserEmail(self, value): """ Set the value of the InvitedUserEmail input for this Choreo. ((conditional, string) The email address of the user to invite; user can be a Fitbit member already. Required unless providing the InvitedUserID.) """ super(CreateInviteInputSet, self)._set_input('InvitedUserEmail', value) def set_InvitedUserID(self, value): """ Set the value of the InvitedUserID input for this Choreo. ((conditional, string) The Fitbit user id of the user to send an invite to. Required unless providing the InvitedUserEmail.) """ super(CreateInviteInputSet, self)._set_input('InvitedUserID', value) def set_ResponseFormat(self, value): """ Set the value of the ResponseFormat input for this Choreo. ((optional, string) The format that you want the response to be in: xml or json. Defaults to json.) """ super(CreateInviteInputSet, self)._set_input('ResponseFormat', value) def set_UserID(self, value): """ Set the value of the UserID input for this Choreo. ((optional, string) The user's encoded id. Defaults to "-" (dash) which will return data for the user associated with the token credentials provided.) """ super(CreateInviteInputSet, self)._set_input('UserID', value) class CreateInviteResultSet(ResultSet): """ A ResultSet with methods tailored to the values returned by the CreateInvite Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. """ def getJSONFromString(self, str): return json.loads(str) def get_Response(self): """ Retrieve the value for the "Response" output from this Choreo execution. (The response from Fitbit.) """ return self._output.get('Response', None) class CreateInviteChoreographyExecution(ChoreographyExecution): def _make_result_set(self, response, path): return CreateInviteResultSet(response, path)
eba383154f45d3e7af31022c4c2cb7368e4e1f19
75e03232591b263a50523d7cfef4041db36caf01
/VMWsolutions/at2-vclient-032/cft/stress_random_loop.py
9838ee1acd308fedd0e76ae9218942c2a0100af3
[]
no_license
adamkittel/src
aaf157062d069998a8d18841895e7362cf868ff9
11e3927bd990b885eba595346694de2d2601d5c9
refs/heads/master
2021-01-11T16:13:14.592894
2017-01-25T18:29:09
2017-01-25T18:29:09
80,040,934
0
0
null
null
null
null
UTF-8
Python
false
false
8,389
py
""" This action will run random stress tests in a loop When run as a script, the following options/env variables apply: --mvip The managementVIP of the cluster SFMVIP env var --user The cluster admin username SFUSER env var --pass The cluster admin password SFPASS env var --emailTo List of addresses to send email to --iterations how many times to loop over the stress tests, 0=forever """ import sys import time from optparse import OptionParser import lib.libsf as libsf from lib.libsf import mylog import logging import lib.sfdefaults as sfdefaults from lib.action_base import ActionBase import send_email import random import stress_netbounce_sequential import stress_nodefail_sequential import stress_reboot_master import stress_reboot_random import stress_reboot_sequential import stress_volume_rebalance import get_active_nodes class StressRandomLoopAction(ActionBase): class Events: """ Events that this action defines """ FAILURE = "FAILURE" def __init__(self): super(self.__class__, self).__init__(self.__class__.Events) def ValidateArgs(self, args): libsf.ValidateArgs({"mvip" : libsf.IsValidIpv4Address, "username" : None, "password" : None, "iterationCount" : libsf.IsInteger, "emailTo" : None}, args) def Execute(self, mvip=sfdefaults.mvip, username=sfdefaults.username, password=sfdefaults.password, iterationCount=100, emailTo=None, debug=False): self.ValidateArgs(locals()) if debug: mylog.console.setLevel(logging.DEBUG) if iterationCount == 0: mylog.warning("Looping Forever") count = 10 else: count = iterationCount stress_test = ["stress_netbounce_sequential", "stress_nodefail_sequential", "stress_reboot_master", "stress_reboot_random", "stress_reboot_sequential", "stress_volume_rebalance"] nodes_list = get_active_nodes.Get(mvip=mvip, username=username, password=password) if nodes_list == False: mylog.error("Could not get the list of active nodes") return False start_time = time.time() for i in xrange(0, count): random_index = random.randint(0, len(stress_test) - 1) random_iteration = random.randint(1,10) if iterationCount == 0: mylog.banner("Starting " + stress_test[random_index].replace("_", " ").title() + " on " + mvip + " with " + str(random_iteration) + " iterations" + "\nIteration " + str(i) + " of infinity") else: mylog.banner("Starting " + stress_test[random_index].replace("_", " ").title() + " on " + mvip + " with " + str(random_iteration) + " iterations" + "\nIteration " + str(i) + " of " + str(iterationCount)) try: if stress_test[random_index] == "stress_netbounce_sequential": stress_netbounce_sequential.Execute(mvip=mvip, username=username, password=password, iteration=random_iteration, emailTo=emailTo) #mvip=sfdefaults.mvip, username=sfdefaults.username, password=sfdefaults.password, emailTo=None, iteration=1 if stress_test[random_index] == "stress_nodefail_sequential": if len(nodes_list) <=3: mylog.banner("Skipping Stress Nodefail Sequential because there are not enough nodes") else: stress_nodefail_sequential.Execute(mvip=mvip, username=username, password=password, iteration=random_iteration, emailTo=emailTo) #mvip=sfdefaults.mvip, username=sfdefaults.username, password=sfdefaults.password, emailTo=None, iteration=1 elif stress_test[random_index] == "stress_reboot_master": stress_reboot_master.Execute(mvip=mvip, username=username, password=password, iteration=random_iteration, emailTo=emailTo) #mvip=sfdefaults.mvip, username=sfdefaults.username, password=sfdefaults.password, emailTo=None, iteration=1 elif stress_test[random_index] == "stress_reboot_random": stress_reboot_random.Execute(mvip=mvip, username=username, password=password, iteration=random_iteration, emailTo=emailTo) #mvip=sfdefaults.mvip, username=sfdefaults.username, password=sfdefaults.password, emailTo=None, iteration=1 elif stress_test[random_index] == "stress_reboot_sequential": stress_reboot_sequential.Execute(mvip=mvip, username=username, password=password, iteration=random_iteration, emailTo=emailTo) #mvip=sfdefaults.mvip, username=sfdefaults.username, password=sfdefaults.password, emailTo=None, iteration=1 elif stress_test[random_index] == "stress_volume_rebalance": stress_volume_rebalance.Execute(mvip=mvip, username=username, password=password, iteration=random_iteration, emailTo=emailTo) except Exception as e: mylog.error("Could not preform " + stress_test[random_index].replace("_", " ").title()) send_email.Execute(emailTo=emailTo, emailSubject="Test " + stress_test[random_index].replace("_", " ").title() + " failed", emailBody=str(e)) mylog.step("Waiting 2 minutes") time.sleep(120) #if loopfoever then increase iterationCount by 1 each time so we never end the for loop if iterationCount == 0: count += 1 end_time = time.time() delta_time = libsf.SecondsToElapsedStr(end_time - start_time) ave_time_per_iteration = (end_time - start_time) / (i + 1) ave_time_per_iteration = libsf.SecondsToElapsedStr(ave_time_per_iteration) mylog.info("\tTotal Time: " + delta_time) mylog.info("\tNumber of Iterations: " + str(i + 1)) mylog.info("\tAverage Time Per Iteration: " + ave_time_per_iteration) emailBody = "The stress tests ran for " + delta_time + "\nTotal Iterations " + str(i + 1) + "\nAverage Time Per Iteration " + ave_time_per_iteration send_email.Execute(emailTo=emailTo, emailSubject="The Testing Finished", emailBody=emailBody) mylog.passed("Passed " + str(iterationCount) + " iterations of random stress testing") return True # Instantate the class and add its attributes to the module # This allows it to be executed simply as module_name.Execute libsf.PopulateActionModule(sys.modules[__name__]) if __name__ == '__main__': mylog.debug("Starting " + str(sys.argv)) # Parse command line arguments parser = OptionParser(option_class=libsf.ListOption, description=libsf.GetFirstLine(sys.modules[__name__].__doc__)) parser.add_option("-m", "--mvip", type="string", dest="mvip", default=sfdefaults.mvip, help="the management IP of the cluster") parser.add_option("-u", "--user", type="string", dest="username", default=sfdefaults.username, help="the admin account for the cluster") parser.add_option("-p", "--pass", type="string", dest="password", default=sfdefaults.password, help="the admin password for the cluster") parser.add_option("--iterations", type="int", dest="iterations", default=100, help="How many iterations to loop over. 0 = Forever") parser.add_option("--email_to", type="string", dest="email_to", default=None, help="The email account to send the results / updates to") parser.add_option("--debug", action="store_true", dest="debug", default=False, help="display more verbose messages") (options, extra_args) = parser.parse_args() try: timer = libsf.ScriptTimer() if Execute(options.mvip, options.username, options.password, options.iterations, options.email_to, options.debug): sys.exit(0) else: sys.exit(1) except libsf.SfArgumentError as e: mylog.error("Invalid arguments - \n" + str(e)) sys.exit(1) except SystemExit: raise except KeyboardInterrupt: mylog.warning("Aborted by user") Abort() exit(1) except: mylog.exception("Unhandled exception") exit(1) exit(0)
0b130d34300f0d54fda9186249d00d2196464eda
d2ada8e9dea0a59476dbbdcfdebc3b8eed951271
/CH02/bh_sshserver.py
5046e3f12011c7357d50aa4e84956dbebd0307ea
[]
no_license
sadavoya/bhp
dccf211f4bd95f5eaf69e44c3bfee8f7d07af688
6fbf1be8ca0f83363234d9c95170bdd770716c28
refs/heads/master
2021-01-13T14:51:13.347114
2017-02-21T01:39:57
2017-02-21T01:39:57
76,486,946
0
0
null
null
null
null
UTF-8
Python
false
false
2,325
py
#!/usr/bin/env python '''SSH''' import socket import threading import paramiko import sys # using the demo keys in the paramiko demo files host_key = paramiko.RSAKey(filename='test_rsa.key') #print host_key.get_base64() class Server(paramiko.ServerInterface): def __init__(self): self.event = threading.Event() def check_channel_request(self, kind, chanid): if kind == 'session': return paramiko.OPEN_SUCCEEDED return paramiko.OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED def check_auth_password(self, username, password): if (username == 'joker') and (password == 'joker'): return paramiko.AUTH_SUCCESSFUL return paramiko.AUTH_FAILED def main(): '''Main''' server = sys.argv[1] ssh_port = int(sys.argv[2]) try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind((server, ssh_port)) sock.listen(100) print '[+] Listening for connection...' client, addr = sock.accept() except Exception, e: print '[-] Listen failed: ' + str(e) sys.exit(1) #print '[+] Got a connection to %s:%d!' % (addr[1], addr[2]) try: bh_session = paramiko.Transport(client) bh_session.add_server_key(host_key) server = Server() try: bh_session.start_server(server=server) except paramiko.SSHException, x: print '[-] SSH negotiation failed.' chan = bh_session.accept(20) print '[+] Authenticated!' print chan.recv(1024) chan.send('Welcome to bh_ssh') while True: try: command = raw_input("Enter command: ").strip('\n') if command != 'exit': chan.send(command) print chan.recv(1024) + '\n' else: chan.send('exit') print 'exiting' bh_session.close() raise Exception('exit') except KeyboardInterrupt: bh_session.close() except Exception, e: print '[-] Caught exception: ' + str(e) try: bh_session.close() except: pass sys.exit(1) main()
e89d6dc70ef70ba87520aa3295eb41f07cb4aaa9
2a3606551a4d850a7b4d6a4e08089c51108ef7be
/plugin.video.mrknow/resources/lib/crypto/keyedHash/pbkdf2.py
cf79523b747c13cbeb4fb110e54813a48c123a41
[ "Apache-2.0" ]
permissive
rrosajp/filmkodi
a6bb1823f4ed45453c8b8e54ffbd6a7b49f44450
0162cde9ae25ddbf4a69330948714833ff2f78c9
refs/heads/master
2021-09-18T06:03:17.561062
2018-06-22T23:28:53
2018-06-22T23:28:53
234,768,781
1
0
Apache-2.0
2021-06-03T20:33:07
2020-01-18T17:11:57
null
WINDOWS-1252
Python
false
false
1,571
py
# -*- coding: iso-8859-1 -*- """ crypto.keyedHash.pbkdf2 Password Based Key Derivation Function 2 References: RFC2898, B. Kaliski, September 2000, PKCS #5 This function is used for IEEE 802.11/WPA passphrase to key hashing Copyright © (c) 2002 by Paul A. Lambert Read LICENSE.txt for license information. """ from ..keyedHash.hmacHash import HMAC_SHA1 from ..common import xor from math import ceil from struct import pack def pbkdf2(password, salt, iterations, keySize, PRF=HMAC_SHA1): """ Create key of size keySize from password and salt """ if len(password)>63: raise 'Password too long for pbkdf2' #if len(password)<8 : raise 'Password too short for pbkdf2' if (keySize > 10000): # spec says >4294967295L*digestSize raise 'keySize too long for PBKDF2' prf = PRF(key=password) # HMAC_SHA1 numBlocks = int(ceil(1.*keySize/prf.digest_size)) # ceiling function key = '' for block in range(1,numBlocks+1): # Calculate F(P, salt, iterations, i) F = prf(salt+pack('>i',block)) # i is packed into 4 big-endian bytes U = prf(salt+pack('>i',block)) # i is packed into 4 big-endian bytes for count in range(2,iterations+1): U = prf(U) F = xor(F,U) key = key + F return key[:keySize] def dot11PassPhraseToPSK(passPhrase,ssid): """ The 802.11 TGi recommended pass-phrase-to-preshared-key mapping. This function simply uses pbkdf2 with interations=4096 and keySize=32 """ assert( 7<len(passPhrase)<64 ), 'Passphrase must be greater than 7 or less than 64 characters' return pbkdf2(passPhrase, ssid, iterations=4096, keySize=32)
91956ba4d19b41720a01993ac3acbd491ad295d4
cd5746f8cc7aee1f20606a65b4fae0d5e8ee78dc
/Python Books/PythonTesting-BeginnersGuide/code/tests/test_chapter5/test_pid.py
72b93cd1bcd67c97b5266912ef867908e2d9e800
[]
no_license
theGreenJedi/Path
df24fca355590efef0c6cb5c52e7216c6b5d2464
b5ed2805dbb046480929e49e550bfd8af5bb4d6f
refs/heads/master
2023-07-27T14:23:37.694546
2021-07-16T01:38:55
2021-07-16T01:38:55
87,686,563
8
2
null
2023-07-11T22:49:03
2017-04-09T05:57:30
Jupyter Notebook
UTF-8
Python
false
false
2,718
py
from unittest import TestCase, main from mocker import Mocker import pid class test_pid_constructor(TestCase): def test_without_when(self): mocker = Mocker() mock_time = mocker.replace('time.time') mock_time() mocker.result(1.0) mocker.replay() controller = pid.PID(P = 0.5, I = 0.5, D = 0.5, setpoint = 0, initial = 12) mocker.restore() mocker.verify() self.assertEqual(controller.gains, (0.5, 0.5, 0.5)) self.assertAlmostEqual(controller.setpoint[0], 0.0) self.assertEqual(len(controller.setpoint), 1) self.assertAlmostEqual(controller.previous_time, 1.0) self.assertAlmostEqual(controller.previous_error, -12.0) self.assertAlmostEqual(controller.integrated_error, 0) def test_with_when(self): controller = pid.PID(P = 0.5, I = 0.5, D = 0.5, setpoint = 1, initial = 12, when = 43) self.assertEqual(controller.gains, (0.5, 0.5, 0.5)) self.assertAlmostEqual(controller.setpoint[0], 1.0) self.assertEqual(len(controller.setpoint), 1) self.assertAlmostEqual(controller.previous_time, 43.0) self.assertAlmostEqual(controller.previous_error, -11.0) self.assertAlmostEqual(controller.integrated_error, 0) class test_calculate_response(TestCase): def test_without_when(self): mocker = Mocker() mock_time = mocker.replace('time.time') mock_time() mocker.result(1.0) mock_time() mocker.result(2.0) mock_time() mocker.result(3.0) mock_time() mocker.result(4.0) mock_time() mocker.result(5.0) mocker.replay() controller = pid.PID(P = 0.5, I = 0.5, D = 0.5, setpoint = 0, initial = 12) self.assertEqual(controller.calculate_response(6), -3) self.assertEqual(controller.calculate_response(3), -4.5) self.assertEqual(controller.calculate_response(-1.5), -0.75) self.assertEqual(controller.calculate_response(-2.25), -1.125) mocker.restore() mocker.verify() def test_with_when(self): controller = pid.PID(P = 0.5, I = 0.5, D = 0.5, setpoint = 0, initial = 12, when = 1) self.assertEqual(controller.calculate_response(6, 2), -3) self.assertEqual(controller.calculate_response(3, 3), -4.5) self.assertEqual(controller.calculate_response(-1.5, 4), -0.75) self.assertEqual(controller.calculate_response(-2.25, 5), -1.125) if __name__ == '__main__': main()
0e00d7b9dfd12f62cf14341e65cd37786e0b1482
f687b45b061a0a4ed849d5d56e265a3423c95f56
/mime_gen_both.py
9f8121e8b8ff5edba0344a98ab758923591037af
[]
no_license
wwwlwscom/python
45e52529fffccf161a0cff8aaf2d19a149ac2056
5478329f068f9a4eff5c07eee8005318b41b6440
refs/heads/master
2021-01-20T10:06:17.251976
2015-10-20T20:03:34
2015-10-20T20:03:34
41,769,993
0
0
null
null
null
null
UTF-8
Python
false
false
1,479
py
#!/usr/bin/env python from email.MIMEText import MIMEText from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email import Utils, Encoders import mimetypes, sys def genpart(data, contenttype): maintype, subtype = contenttype.split('/') if maintype == 'text': retval = MIMEText(data, _subtype=subtype) else: retval = MIMEBase(maintype, subtype) retval.set_payload(data) Encoders.encode_base64(retval) return retval def attachment(filename): fd = open(filename, 'rb') mimetype, mimeencoding = mimetypes.guess_type(filename) if mimeencoding or (mimetype is None): mimetype = 'application/octet-stream' retval = genpart(fd.read(), mimetype) retval.add_header('Content-Disposition', 'attachment', filename = filename) fd.close() return retval message = """Hello, This is a test message from Rock. I hope you enjoy it! --Anonymous""" messagehtml = """Hello,<P> This is a <B>great</B>test message from Rock. I hope you enjoy it!<P> --<I>Anonymous<I>""" msg = MIMEMultipart() msg['To'] = '[email protected]' msg['From'] = 'Test Sender <[email protected]>' msg['Subject'] = 'Test Message, Rock' msg['Date'] = Utils.formatdate(localtime = 1) msg['Message-ID'] = Utils.make_msgid() body = MIMEMultipart('alternative') body.attach(genpart(message, 'text/plain')) body.attach(genpart(messagehtml, 'text/html')) msg.attach(body) for filename in sys.argv[1:]: msg.attach(attachment(filename)) print msg.as_string()
7da317e87cb08431320105068322690d71269402
a1092fecf5057e45f1df4e738a14be210dadbc83
/gen.py
3d26eb5062cedb3108e425576485a5c6bc7d741c
[]
no_license
robert-giaquinto/baum-welch
ba45b3c80e839ae7fd5b8b5a00ee07dd9228b61a
b57fb2bd64ed3fdfed1552a6ea5afd9c7c120cfc
refs/heads/master
2021-01-15T09:09:29.267399
2014-05-31T21:17:42
2014-05-31T21:17:42
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,008
py
import random import numpy as np N_SEQ = 10 START = 0 BEFORE = 1 AFTER = 2 END = 3 def gen_seq(): seq = [] state = START while state != END: if state == START: state = BEFORE seq.append('S') if state == BEFORE: n, l, r = np.random.multinomial(1, [0.96, 0.036, 0.004]) if n: seq.append('N') elif l: seq.append('L') else: seq.append('R') state += np.random.binomial(1, 1/5000.) if state == AFTER: n, l, r = np.random.multinomial(1, [0.96, 0.004, 0.036]) if n: seq.append('N') elif l: seq.append('L') else: seq.append('R') state += np.random.binomial(1, 1/5000.) seq.append('E') return seq if __name__ == '__main__': random.seed(42) for i in xrange(N_SEQ): seq = gen_seq() print ''.join(seq)
6ee7e72ba92ecde352fbe7130382ee1d2873e524
d5f080543d3004f560c1ae636900080f1c7e8b31
/configs/D2Det/D2Det_detection_r101_fpn_2x.py
4e184d8220699043f302581714e52140c0c3b0ba
[ "MIT" ]
permissive
Randl/D2Det
dc7bd395b8c538e96f390d7ce5c396f87ee89bd8
5e35b218d9de824e73e0a49953af25a0c6984e74
refs/heads/master
2022-09-25T13:52:21.141590
2020-06-11T09:08:47
2020-06-11T09:08:47
271,498,684
0
0
MIT
2020-06-11T08:56:15
2020-06-11T08:56:15
null
UTF-8
Python
false
false
5,685
py
# model settings model = dict( type='D2Det', pretrained='torchvision://resnet101', backbone=dict( type='ResNet', depth=101, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, style='pytorch'), neck=dict( type='FPN', in_channels=[256, 512, 1024, 2048], out_channels=256, num_outs=5), rpn_head=dict( type='RPNHead', in_channels=256, feat_channels=256, anchor_scales=[8], anchor_ratios=[0.5, 1.0, 2.0], anchor_strides=[4, 8, 16, 32, 64], target_means=[.0, .0, .0, .0], target_stds=[1.0, 1.0, 1.0, 1.0], loss_cls=dict( type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0)), bbox_roi_extractor=dict( type='SingleRoIExtractor', roi_layer=dict( type='DeformRoIPoolingPack', out_size=7, sample_per_part=1, out_channels=256, no_trans=False, group_size=1, trans_std=0.1), out_channels=256, featmap_strides=[4, 8, 16, 32]), bbox_head=dict( type='SharedFCBBoxHead', with_reg=False, num_fcs=2, in_channels=256, fc_out_channels=1024, roi_feat_size=7, num_classes=81, target_means=[0., 0., 0., 0.], target_stds=[0.1, 0.1, 0.2, 0.2], reg_class_agnostic=False, loss_cls=dict( type='CrossEntropyLoss', use_sigmoid=False, loss_weight=2.0)), reg_roi_extractor=dict( type='SingleRoIExtractor', roi_layer=dict(type='RoIAlign', out_size=14, sample_num=2), out_channels=256, featmap_strides=[4, 8, 16, 32]), D2Det_head=dict( type='D2DetHead', num_convs=8, in_channels=256, norm_cfg=dict(type='GN', num_groups=36), MASK_ON=False)) # model training and testing settings train_cfg = dict( rpn=dict( assigner=dict( type='MaxIoUAssigner', pos_iou_thr=0.7, neg_iou_thr=0.3, min_pos_iou=0.3, ignore_iof_thr=-1), sampler=dict( type='RandomSampler', num=256, pos_fraction=0.5, neg_pos_ub=-1, add_gt_as_proposals=False), allowed_border=0, pos_weight=-1, debug=False), rpn_proposal=dict( nms_across_levels=False, nms_pre=2000, nms_post=2000, max_num=2000, nms_thr=0.7, min_bbox_size=0), rcnn=dict( assigner=dict( type='MaxIoUAssigner', pos_iou_thr=0.5, neg_iou_thr=0.5, min_pos_iou=0.5, ignore_iof_thr=-1), sampler=dict( type='RandomSampler', num=512, pos_fraction=0.25, neg_pos_ub=-1, add_gt_as_proposals=True), pos_radius=1, pos_weight=-1, max_num_grid=192, debug=False)) test_cfg = dict( rpn=dict( nms_across_levels=False, nms_pre=1000, nms_post=1000, max_num=1000, nms_thr=0.7, min_bbox_size=0), rcnn=dict( score_thr=0.03, nms=dict(type='nms', iou_thr=0.5), max_per_img=125)) # dataset settings dataset_type = 'CocoDataset' data_root = 'data/coco/' img_norm_cfg = dict( mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) train_pipeline = [ dict(type='LoadImageFromFile'), dict(type='LoadAnnotations', with_bbox=True), dict(type='Resize', img_scale=(1333, 800), keep_ratio=True), dict(type='RandomFlip', flip_ratio=0.5), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']), ] test_pipeline = [ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(1333, 800), flip=False, transforms=[ dict(type='Resize', keep_ratio=True), dict(type='RandomFlip'), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']), ]) ] data = dict( imgs_per_gpu=2, workers_per_gpu=2, train=dict( type=dataset_type, ann_file=data_root + 'annotations/instances_train2017.json', img_prefix=data_root + 'train2017/', pipeline=train_pipeline), val=dict( type=dataset_type, ann_file=data_root + 'annotations/instances_val2017.json', img_prefix=data_root + 'val2017/', pipeline=test_pipeline), test=dict( type=dataset_type, ann_file=data_root + 'annotations/instances_val2017.json', img_prefix=data_root + 'val2017/', pipeline=test_pipeline)) evaluation = dict(interval=1, metric='bbox') # optimizer optimizer = dict(type='SGD', lr=0.02, momentum=0.9, weight_decay=0.0001) optimizer_config = dict(grad_clip=None) # learning policy lr_config = dict( policy='step', warmup='linear', warmup_iters=1000, warmup_ratio=1.0 / 80, step=[20, 23]) checkpoint_config = dict(interval=1) # yapf:disable log_config = dict( interval=50, hooks=[ dict(type='TextLoggerHook'), # dict(type='TensorboardLoggerHook') ]) # yapf:enable # runtime settings total_epochs = 24 dist_params = dict(backend='nccl') log_level = 'INFO' work_dir = './work_dirs/D2Det_detection_r101_fpn_2x' load_from = None resume_from = None workflow = [('train', 1)]
7d812592e10d2a0d003e3156aef68f26c0796648
601adbb343313e7cce71b9b8d06620f541f349e5
/tests/test_ci/test_runners/test_BaseRunner.py
4545078bf38683e3c939099329a8ad2f0d27d15f
[]
no_license
jgsogo/conan-sword-and-sorcery
f3ff2c9b739410a7fb6eb97c49470d585fd1ab4c
143f05d8b469a3afc9c807ec87fbe2dcbe63dab3
refs/heads/master
2021-04-06T06:23:40.584031
2018-08-15T16:50:43
2018-08-15T16:50:43
124,441,534
1
0
null
null
null
null
UTF-8
Python
false
false
6,120
py
# -*- coding: utf-8 -*- import os import unittest try: from unittest import mock except ImportError: import mock from conan_sword_and_sorcery.ci.runners import AppveyorRunner from conan_sword_and_sorcery.ci.runners.base_runner import SUCCESS, FAIL, DRY_RUN, BaseRunner from conan_sword_and_sorcery.parsers.settings import get_settings from conan_sword_and_sorcery.utils.environ import context_env from conan_sword_and_sorcery.parsers.profile import profile_for from tests.utils import TestCaseEnvClean class JobGeneratorClass4Testing: def __init__(self, *args, **kwargs): pass class BaseRunner4Testing(BaseRunner): job_generator_class = JobGeneratorClass4Testing class TestBaseRunnerStableBranch(TestCaseEnvClean): def setUp(self): self.settings = get_settings() # Dummy (but valid) conanfile me = os.path.dirname(__file__) self.conanfile = os.path.join(me, '..', '..', 'files', 'single', 'conanfile01.py') def test_enumerate_jobs(self): runner = AppveyorRunner(conanfile=self.conanfile, settings=self.settings, osys="Windows") with context_env(CONAN_VISUAL_VERSIONS="12", CONAN_VISUAL_RUNTIMES="MT"): self.assertTrue(len(list(runner.enumerate_jobs())) != 0) def test_is_pull_request(self): runner = BaseRunner4Testing(conanfile=self.conanfile, settings=self.settings, osys="Windows") with self.assertRaises(NotImplementedError): runner.is_pull_request() def test_get_branch_name(self): runner = BaseRunner4Testing(conanfile=self.conanfile, settings=self.settings, osys="Windows") with self.assertRaises(NotImplementedError): runner.get_branch_name() def test_dry_run(self): runner = AppveyorRunner(conanfile=self.conanfile, settings=self.settings, osys="Windows", dry_run=True) with context_env(CONAN_GCC_VERSIONS="6", CONAN_ARCHS='x86', CONAN_BUILD_PACKAGES='pckg1'): compiler, options = list(runner.enumerate_jobs())[0] with profile_for(compiler=compiler) as profile_file: runner.set_compiler(compiler) runner.set_profile(profile_file) r = runner.run(options={'shared': True}, username='test', channel='testing') self.assertEqual(r, DRY_RUN) def test_run_fail(self): runner = AppveyorRunner(conanfile=self.conanfile, settings=self.settings, osys="Windows") with context_env(CONAN_GCC_VERSIONS="6", CONAN_ARCHS='x86', CONAN_BUILD_PACKAGES='pckg1'): compiler, options = list(runner.enumerate_jobs())[0] with profile_for(compiler=compiler) as profile_file: runner.set_compiler(compiler) runner.set_profile(profile_file) with mock.patch('conan_sword_and_sorcery.ci.runners.base_runner.cmd', return_value=1) as mocked_cmd: r = runner.run(options={'shared': True}, username='test', channel='testing') self.assertEqual(r, FAIL) def test_run_success(self): runner = AppveyorRunner(conanfile=self.conanfile, settings=self.settings, osys="Windows") with context_env(CONAN_GCC_VERSIONS="6", CONAN_ARCHS='x86', CONAN_BUILD_PACKAGES='pckg1'): compiler, options = list(runner.enumerate_jobs())[0] with profile_for(compiler=compiler) as profile_file: runner.set_compiler(compiler) runner.set_profile(profile_file) with mock.patch('conan_sword_and_sorcery.ci.runners.base_runner.cmd', return_value=0) as mocked_cmd: r = runner.run(options={'shared': True}, username='test', channel='testing') self.assertEqual(r, SUCCESS) args, kwargs = mocked_cmd.call_args self.assertEqual(len(args), 0) # All arguments are passed with name self.assertEqual(kwargs['exception'], None) command = kwargs.get('command') self.assertIn('--build=pckg1', command) self.assertIn('--build=outdated', command) self.assertIn('--build={}'.format(runner.recipe.name), command) self.assertIn('--profile {}'.format(profile_file), command) self.assertIn('-o {}:shared=True'.format(runner.recipe.name), command) def test_is_upload_requested(self): runner = AppveyorRunner(conanfile=self.conanfile, settings=self.settings, osys="Windows") with context_env(CONAN_UPLOAD_ONLY_WHEN_STABLE="True", APPVEYOR_REPO_BRANCH='non-stable-branch'): self.assertFalse(runner.is_stable_branch()) self.assertFalse(runner.is_upload_requested()) with context_env(CONAN_UPLOAD_ONLY_WHEN_STABLE="False", APPVEYOR_REPO_BRANCH='non-stable-branch'): self.assertFalse(runner.is_stable_branch()) self.assertTrue(runner.is_upload_requested()) with context_env(CONAN_UPLOAD_ONLY_WHEN_STABLE="False", APPVEYOR_REPO_BRANCH='stable/v1.2.3'): self.assertTrue(runner.is_stable_branch()) self.assertTrue(runner.is_upload_requested()) with context_env(CONAN_UPLOAD_ONLY_WHEN_STABLE="True", APPVEYOR_REPO_BRANCH='stable/v1.2.3'): self.assertTrue(runner.is_stable_branch()) self.assertTrue(runner.is_upload_requested()) def test_upload(self): runner = AppveyorRunner(conanfile=self.conanfile, settings=self.settings, osys="Windows") with mock.patch('conan_sword_and_sorcery.ci.runners.base_runner.upload', return_value=0) as mocked_upload: with context_env(CONAN_UPLOAD_ONLY_WHEN_STABLE="True", APPVEYOR_REPO_BRANCH='non-stable-branch'): runner.upload(username='test', channel='testing') with context_env(CONAN_UPLOAD_ONLY_WHEN_STABLE="False", APPVEYOR_REPO_BRANCH='non-stable-branch'): runner.upload(username='test', channel='testing') args, kwargs = mocked_upload.call_args self.assertEqual(kwargs['username'], 'test')
602ecb7bb83ddd5c367c45eeaec4531e135d6824
f87dc2227f9539ce9f87b8eb417d28f487ea2eac
/이진탐색/부품찾기.py
b3627efacbce4f210bf7ebc9dc2784e06dd4977a
[]
no_license
jjangsungwon/python-for-coding-test
fb1e019a2e68e426bb4f6770bffdc6289a647b4a
8d9bf8de5de2a9724f75b35ea04dd9bcc40dec86
refs/heads/master
2022-12-16T02:53:55.967070
2020-08-26T08:41:14
2020-08-26T08:41:14
285,842,867
2
0
null
null
null
null
UTF-8
Python
false
false
895
py
def binary_search(target, start, end): if start > end: return None while start <= end: mid = (start + end) // 2 if array[mid] == target: # 일치 return "yes" elif array[mid] > target: # 중간값이 찾고자 하는 값보다 클 때 end = mid - 1 else: start = mid + 1 return None # 일치하는 값이 없을 때 if __name__ == "__main__": # 입력 N = int(input()) array = list(map(int, input().split())) M = int(input()) find = list(map(int, input().split())) # 이진 탐색을 하기 위해서 정렬 array.sort() # find에서 값을 하나씩 읽는다. for data in find: # 이진 탐색 result = binary_search(data, 0, N - 1) if result is not None: print('yes', end=" ") else: print('no', end=" ")
d8ca730c49e849faef22bb61d6e7c1ea1853c890
694d57c3e512ce916269411b51adef23532420cd
/python/chapter-1/lab4-exec1.2.py
00e1dd5356363c18fb8e1045f63f53286f0a515a
[]
no_license
clovery410/mycode
5541c3a99962d7949832a0859f18819f118edfba
e12025e754547d18d5bb50a9dbe5e725fd03fd9c
refs/heads/master
2021-05-16T02:46:47.996748
2017-05-10T23:43:50
2017-05-10T23:43:50
39,235,141
1
1
null
null
null
null
UTF-8
Python
false
false
541
py
def gcb_recur(a, b): smaller_para = min(a, b) larger_para = max(a, b) remainder = larger_para % smaller_para if smaller_para % remainder == 0: return remainder return gcb_recur(smaller_para, remainder) print(gcb_recur(50, 35)) def gcb_itera(a, b): smaller_para = min(a, b) larger_para = max(a, b) remainder = larger_para % smaller_para while not smaller_para % remainder == 0: smaller_para, remainder = remainder, smaller_para % remainder return remainder print(gcb_itera(50, 35))
3b98e43e2f3dc2377b74432e9fe99c572da37f2a
4904acd900496b4883c2f5b4aa6b45d1ef6654c0
/graphgallery/gallery/nodeclas/tensorflow/__init__.py
1cf21d123e086ed846bcb034e8d4271c9735498d
[ "MIT" ]
permissive
blindSpoter01/GraphGallery
aee039edd759be9272d123463b0ad73a57e561c7
e41caeb32a07da95364f15b85cad527a67763255
refs/heads/master
2023-06-17T11:42:27.169751
2021-07-15T03:07:39
2021-07-15T03:07:39
null
0
0
null
null
null
null
UTF-8
Python
false
false
782
py
from .gcn import GCN from .gat import GAT from .clustergcn import ClusterGCN from .sgc import SGC from .gwnn import GWNN from .robustgcn import RobustGCN from .graphsage import GraphSAGE from .fastgcn import FastGCN from .chebynet import ChebyNet from .densegcn import DenseGCN from .lgcn import LGCN from .BVAT.obvat import OBVAT from .BVAT.sbvat import SBVAT from .gmnn import GMNN from .dagnn import DAGNN from .mlp import MLP from .tagcn import TAGCN from .appnp import APPNP, PPNP from .ssgc import SSGC from .agnn import AGNN from .arma import ARMA # experimental model from .experimental.edgeconv import EdgeGCN from .experimental.s_obvat import SimplifiedOBVAT from .experimental.gcn_mix import GCN_MIX from .experimental.gcna import GCNA from .experimental.sat import SAT
7d6e7442b32fe58141787e6063cf7b0ae35a74b7
d49fbd7874b70a93cbc551afed1b87e3e47617a8
/django/example/repositories/__init__.py
1efb28043ae95783f5bde83b3415bcedaf028594
[]
no_license
gitter-badger/tutorials-4
bbdbb673e978118f9fec3212baa13f6f99226be0
3ce1cdb7c6d26f6df4d6bb94e82f83e8cab9389b
refs/heads/master
2020-04-04T20:52:28.181616
2018-10-28T22:05:17
2018-10-28T22:05:17
156,264,177
0
0
null
2018-11-05T18:32:17
2018-11-05T18:32:16
null
UTF-8
Python
false
false
528
py
from .category import load_categories, load_category # noqa from .entry import load_entries # noqa from .notification import create_notification, load_notifications # noqa from .price import ( # noqa cheapest_price_by_category, load_price, prices_for_category, ) from .profile import ( # noqa add_balance, create_profile, del_balance, load_profile, save_profile, ) from .subscription import create_subscription, load_subscription # noqa from .user import create_user, save_password # noqa
ff3e75465d6bc74082977d0011083bd7cb9d2fa1
8dc745854d73e362aa60747b3ab1b5a0dd975902
/demo/funs/varying_args.py
95be35fceef5366dfe3c457b3dac4f7b9e356ad3
[]
no_license
srikanthpragada/PYTHON_27_AUG_2020
08a5898fe1a0ae110b74897ce6cce6595bdfce45
af2aebbb0d83c5e8f381cdda844ab66d2362019c
refs/heads/master
2022-12-30T10:12:56.688671
2020-10-09T14:20:43
2020-10-09T14:20:43
291,730,514
0
0
null
null
null
null
UTF-8
Python
false
false
149
py
def wish(*names, message="Hi"): for n in names: print(message, n) wish("Bill", "Steve", message="Hello") wish("Bill", "Steve", "Mike")
aae0e6098f5fffd6f5df5e9109899e0ddfcf5d9b
5de3f612df0dbda712b39403dbafb0617e597651
/devel/lib/python2.7/dist-packages/pal_control_msgs/__init__.py
e21ec5fdbefcfd4eaadd1be96174a29e086c69d8
[]
no_license
AdriiTrujillo/tiago_public_ws
1bd62d51c2eb694d07db83738f7bebd582d8126c
6eaeabd1ec177df837b81fd9f42887318128766b
refs/heads/main
2023-04-03T13:09:09.749190
2021-04-01T10:05:43
2021-04-01T10:05:43
350,026,041
0
0
null
null
null
null
UTF-8
Python
false
false
116
py
/home/adrii/tiago_public_ws/devel/.private/pal_control_msgs/lib/python2.7/dist-packages/pal_control_msgs/__init__.py
e25fb293e8841b87c8979b159fe4daadf9eed51e
8ed215ee731bc8c55eabdc66ee028a43771510bc
/tasks-deploy/rsa/check.py
5bac71f193f848b84031ce3a62e0ff96d6fb6acd
[ "MIT" ]
permissive
irdkwmnsb/lkshl-ctf
c6c0b0ae58653d3d7c427073221043d2adea212c
e5c0200ddc8ba73df5f321b87b9763fb1bbaba57
refs/heads/master
2020-03-23T22:22:23.499985
2019-02-22T13:29:51
2019-02-22T13:29:51
142,172,055
3
0
null
null
null
null
UTF-8
Python
false
false
8,868
py
def check(attempt, context): if attempt.answer == flags[attempt.participant.id % len(flags)]: return Checked(True) if attempt.answer in flags: return CheckedPlagiarist(False, flags.index(attempt.answer)) return Checked(False) flags = ['LKL{RSA_is_s0metimes_insecur3_3Udjwqg6}', 'LKL{RSA_is_s0metimes_insecur3_UibEbfRa}', 'LKL{RSA_is_s0metimes_insecur3_wGqZy5DF}', 'LKL{RSA_is_s0metimes_insecur3_2LYyyNWF}', 'LKL{RSA_is_s0metimes_insecur3_l9d809Zg}', 'LKL{RSA_is_s0metimes_insecur3_BneTxPca}', 'LKL{RSA_is_s0metimes_insecur3_NfEFCIRX}', 'LKL{RSA_is_s0metimes_insecur3_4WAEvVxt}', 'LKL{RSA_is_s0metimes_insecur3_wQ800lk0}', 'LKL{RSA_is_s0metimes_insecur3_HedQD1vE}', 'LKL{RSA_is_s0metimes_insecur3_pKXxALJn}', 'LKL{RSA_is_s0metimes_insecur3_YZhZvmqN}', 'LKL{RSA_is_s0metimes_insecur3_v1iaaHxu}', 'LKL{RSA_is_s0metimes_insecur3_fm0xHYvf}', 'LKL{RSA_is_s0metimes_insecur3_wKGk99KZ}', 'LKL{RSA_is_s0metimes_insecur3_AycXpexc}', 'LKL{RSA_is_s0metimes_insecur3_H27gGhFt}', 'LKL{RSA_is_s0metimes_insecur3_ipXKDpyl}', 'LKL{RSA_is_s0metimes_insecur3_bDVeeCSu}', 'LKL{RSA_is_s0metimes_insecur3_IOIowsHu}', 'LKL{RSA_is_s0metimes_insecur3_X1J51z2g}', 'LKL{RSA_is_s0metimes_insecur3_qwcBeb7f}', 'LKL{RSA_is_s0metimes_insecur3_BYvIBQl3}', 'LKL{RSA_is_s0metimes_insecur3_lWRmz5AJ}', 'LKL{RSA_is_s0metimes_insecur3_EI4quULK}', 'LKL{RSA_is_s0metimes_insecur3_sILihSt0}', 'LKL{RSA_is_s0metimes_insecur3_Jf1mS2A4}', 'LKL{RSA_is_s0metimes_insecur3_rEpoUHFc}', 'LKL{RSA_is_s0metimes_insecur3_3aOzjiDi}', 'LKL{RSA_is_s0metimes_insecur3_2X4LGivB}', 'LKL{RSA_is_s0metimes_insecur3_E3XpMQ4Z}', 'LKL{RSA_is_s0metimes_insecur3_JkmfbPhc}', 'LKL{RSA_is_s0metimes_insecur3_gSjumGpD}', 'LKL{RSA_is_s0metimes_insecur3_MBvtPPKA}', 'LKL{RSA_is_s0metimes_insecur3_WWn9Txw8}', 'LKL{RSA_is_s0metimes_insecur3_12kavBoH}', 'LKL{RSA_is_s0metimes_insecur3_vkw0O9rB}', 'LKL{RSA_is_s0metimes_insecur3_Remqp7Tc}', 'LKL{RSA_is_s0metimes_insecur3_cJpQlr6K}', 'LKL{RSA_is_s0metimes_insecur3_CnXN72KW}', 'LKL{RSA_is_s0metimes_insecur3_w8Fdsu7b}', 'LKL{RSA_is_s0metimes_insecur3_zwetRh2m}', 'LKL{RSA_is_s0metimes_insecur3_2XDisW1d}', 'LKL{RSA_is_s0metimes_insecur3_nI12YHMk}', 'LKL{RSA_is_s0metimes_insecur3_Zc7yKWN7}', 'LKL{RSA_is_s0metimes_insecur3_UM0NCS7b}', 'LKL{RSA_is_s0metimes_insecur3_FvLHJZwH}', 'LKL{RSA_is_s0metimes_insecur3_jBkK1mgy}', 'LKL{RSA_is_s0metimes_insecur3_ah7tGRm3}', 'LKL{RSA_is_s0metimes_insecur3_V9x3rTk7}', 'LKL{RSA_is_s0metimes_insecur3_72Zr73Q0}', 'LKL{RSA_is_s0metimes_insecur3_MGXTz8Xk}', 'LKL{RSA_is_s0metimes_insecur3_GKCnGHrk}', 'LKL{RSA_is_s0metimes_insecur3_Ar9ok9d7}', 'LKL{RSA_is_s0metimes_insecur3_whpfREVI}', 'LKL{RSA_is_s0metimes_insecur3_UDBDalbH}', 'LKL{RSA_is_s0metimes_insecur3_U1FH7Cf1}', 'LKL{RSA_is_s0metimes_insecur3_KIaqedik}', 'LKL{RSA_is_s0metimes_insecur3_dqPmGn0z}', 'LKL{RSA_is_s0metimes_insecur3_bEusmfrG}', 'LKL{RSA_is_s0metimes_insecur3_wjgfHTeI}', 'LKL{RSA_is_s0metimes_insecur3_CLTG1Vhx}', 'LKL{RSA_is_s0metimes_insecur3_MRX7svAE}', 'LKL{RSA_is_s0metimes_insecur3_6TBCIJY6}', 'LKL{RSA_is_s0metimes_insecur3_kVxzzxLQ}', 'LKL{RSA_is_s0metimes_insecur3_Vkv2woLM}', 'LKL{RSA_is_s0metimes_insecur3_Bo8VUtVU}', 'LKL{RSA_is_s0metimes_insecur3_6GrvaoC1}', 'LKL{RSA_is_s0metimes_insecur3_YibIEvsP}', 'LKL{RSA_is_s0metimes_insecur3_ba9YkBff}', 'LKL{RSA_is_s0metimes_insecur3_x2B0KLjH}', 'LKL{RSA_is_s0metimes_insecur3_JiWBzSRv}', 'LKL{RSA_is_s0metimes_insecur3_QyLDwokQ}', 'LKL{RSA_is_s0metimes_insecur3_nZZ8tb0Z}', 'LKL{RSA_is_s0metimes_insecur3_CnHFcLbS}', 'LKL{RSA_is_s0metimes_insecur3_izNJOHO2}', 'LKL{RSA_is_s0metimes_insecur3_9ukX4Uxy}', 'LKL{RSA_is_s0metimes_insecur3_n0YiGB82}', 'LKL{RSA_is_s0metimes_insecur3_T5VYsfc5}', 'LKL{RSA_is_s0metimes_insecur3_UQ6KvIZB}', 'LKL{RSA_is_s0metimes_insecur3_mEIdKYee}', 'LKL{RSA_is_s0metimes_insecur3_I3rpSyie}', 'LKL{RSA_is_s0metimes_insecur3_Zi0ClOtB}', 'LKL{RSA_is_s0metimes_insecur3_JAVcK2UU}', 'LKL{RSA_is_s0metimes_insecur3_1Tx3Crkx}', 'LKL{RSA_is_s0metimes_insecur3_2FbkNKnk}', 'LKL{RSA_is_s0metimes_insecur3_YRhonqdT}', 'LKL{RSA_is_s0metimes_insecur3_gQkoA50I}', 'LKL{RSA_is_s0metimes_insecur3_axRX4qyw}', 'LKL{RSA_is_s0metimes_insecur3_IFCOj1V7}', 'LKL{RSA_is_s0metimes_insecur3_k4gHI5D8}', 'LKL{RSA_is_s0metimes_insecur3_zFThpVTM}', 'LKL{RSA_is_s0metimes_insecur3_iYDJPaN7}', 'LKL{RSA_is_s0metimes_insecur3_awzaYVZK}', 'LKL{RSA_is_s0metimes_insecur3_aSYyVYud}', 'LKL{RSA_is_s0metimes_insecur3_CEzWlUdO}', 'LKL{RSA_is_s0metimes_insecur3_PSHlcp35}', 'LKL{RSA_is_s0metimes_insecur3_c2NhDpw8}', 'LKL{RSA_is_s0metimes_insecur3_0l3UwHlF}', 'LKL{RSA_is_s0metimes_insecur3_WQeRwaPM}', 'LKL{RSA_is_s0metimes_insecur3_4N7mzVAG}', 'LKL{RSA_is_s0metimes_insecur3_9nkGZpXA}', 'LKL{RSA_is_s0metimes_insecur3_FWB38tRG}', 'LKL{RSA_is_s0metimes_insecur3_TvZshh5M}', 'LKL{RSA_is_s0metimes_insecur3_odkN2hAr}', 'LKL{RSA_is_s0metimes_insecur3_diN6caou}', 'LKL{RSA_is_s0metimes_insecur3_rIrFBQB9}', 'LKL{RSA_is_s0metimes_insecur3_A2bAzEpF}', 'LKL{RSA_is_s0metimes_insecur3_39Uo9bYj}', 'LKL{RSA_is_s0metimes_insecur3_klWefkMl}', 'LKL{RSA_is_s0metimes_insecur3_iWWOVbZZ}', 'LKL{RSA_is_s0metimes_insecur3_ETJzDjaj}', 'LKL{RSA_is_s0metimes_insecur3_xSNZYFhJ}', 'LKL{RSA_is_s0metimes_insecur3_k9Xse4cs}', 'LKL{RSA_is_s0metimes_insecur3_EXZC95Kh}', 'LKL{RSA_is_s0metimes_insecur3_pmodkyrx}', 'LKL{RSA_is_s0metimes_insecur3_gwTzucl7}', 'LKL{RSA_is_s0metimes_insecur3_Hx1bvm1Z}', 'LKL{RSA_is_s0metimes_insecur3_7v8eLOwZ}', 'LKL{RSA_is_s0metimes_insecur3_DxbDPG5X}', 'LKL{RSA_is_s0metimes_insecur3_lobjFfcF}', 'LKL{RSA_is_s0metimes_insecur3_LLLmbRNO}', 'LKL{RSA_is_s0metimes_insecur3_kI6EKTOF}', 'LKL{RSA_is_s0metimes_insecur3_5HSnyTLH}', 'LKL{RSA_is_s0metimes_insecur3_M4ofvfwP}', 'LKL{RSA_is_s0metimes_insecur3_coLWPtfu}', 'LKL{RSA_is_s0metimes_insecur3_qxkvUSRP}', 'LKL{RSA_is_s0metimes_insecur3_2MmsVqUg}', 'LKL{RSA_is_s0metimes_insecur3_Yc52WnBP}', 'LKL{RSA_is_s0metimes_insecur3_yGt1uPiG}', 'LKL{RSA_is_s0metimes_insecur3_qFjrX5Ji}', 'LKL{RSA_is_s0metimes_insecur3_gSebOWUT}', 'LKL{RSA_is_s0metimes_insecur3_XARUHTcG}', 'LKL{RSA_is_s0metimes_insecur3_51QDUC7l}', 'LKL{RSA_is_s0metimes_insecur3_i6p6iiUH}', 'LKL{RSA_is_s0metimes_insecur3_kzUSlkav}', 'LKL{RSA_is_s0metimes_insecur3_2RBFT2GT}', 'LKL{RSA_is_s0metimes_insecur3_ByOtjihb}', 'LKL{RSA_is_s0metimes_insecur3_cLKBCVZ2}', 'LKL{RSA_is_s0metimes_insecur3_Trq7k1wI}', 'LKL{RSA_is_s0metimes_insecur3_Q60qbGcZ}', 'LKL{RSA_is_s0metimes_insecur3_Fp37ejF6}', 'LKL{RSA_is_s0metimes_insecur3_tLBJ6Gix}', 'LKL{RSA_is_s0metimes_insecur3_U7tBKrpB}', 'LKL{RSA_is_s0metimes_insecur3_XDAt8LAu}', 'LKL{RSA_is_s0metimes_insecur3_m60Nw97g}', 'LKL{RSA_is_s0metimes_insecur3_krYk40zo}', 'LKL{RSA_is_s0metimes_insecur3_V3WWrrlx}', 'LKL{RSA_is_s0metimes_insecur3_KsybMcjy}', 'LKL{RSA_is_s0metimes_insecur3_yVWR00Sp}', 'LKL{RSA_is_s0metimes_insecur3_Rt1IFAr8}', 'LKL{RSA_is_s0metimes_insecur3_aHkXSnfe}', 'LKL{RSA_is_s0metimes_insecur3_zEp1mZc1}', 'LKL{RSA_is_s0metimes_insecur3_zv0ffkZ2}', 'LKL{RSA_is_s0metimes_insecur3_ueVY4ipK}', 'LKL{RSA_is_s0metimes_insecur3_ocDnu8u6}', 'LKL{RSA_is_s0metimes_insecur3_pPnTgD60}', 'LKL{RSA_is_s0metimes_insecur3_2rnwVTJ4}', 'LKL{RSA_is_s0metimes_insecur3_20ZEcGl8}', 'LKL{RSA_is_s0metimes_insecur3_fL9Ympb5}', 'LKL{RSA_is_s0metimes_insecur3_3GwYLaqg}', 'LKL{RSA_is_s0metimes_insecur3_qiXClm4E}', 'LKL{RSA_is_s0metimes_insecur3_d2en2vz6}', 'LKL{RSA_is_s0metimes_insecur3_SOLo31WB}', 'LKL{RSA_is_s0metimes_insecur3_OB9dtc4j}', 'LKL{RSA_is_s0metimes_insecur3_98FGOfT9}', 'LKL{RSA_is_s0metimes_insecur3_xM10cADQ}', 'LKL{RSA_is_s0metimes_insecur3_hpMKiswj}', 'LKL{RSA_is_s0metimes_insecur3_FTjpdffi}', 'LKL{RSA_is_s0metimes_insecur3_1iEMCbA4}', 'LKL{RSA_is_s0metimes_insecur3_yEH5gk0l}', 'LKL{RSA_is_s0metimes_insecur3_LhYemwow}', 'LKL{RSA_is_s0metimes_insecur3_PJBY7kTD}', 'LKL{RSA_is_s0metimes_insecur3_Y2RZ1YTf}', 'LKL{RSA_is_s0metimes_insecur3_FQPmnfg5}', 'LKL{RSA_is_s0metimes_insecur3_hNBb63ry}', 'LKL{RSA_is_s0metimes_insecur3_RJ8slmjb}', 'LKL{RSA_is_s0metimes_insecur3_xSodLxm0}', 'LKL{RSA_is_s0metimes_insecur3_HDxXhB9X}', 'LKL{RSA_is_s0metimes_insecur3_vPOiIRZA}', 'LKL{RSA_is_s0metimes_insecur3_mYdW9rli}', 'LKL{RSA_is_s0metimes_insecur3_B1gHPXjt}', 'LKL{RSA_is_s0metimes_insecur3_om7BTmLD}', 'LKL{RSA_is_s0metimes_insecur3_6z9ZUc5z}', 'LKL{RSA_is_s0metimes_insecur3_RvxykO1G}', 'LKL{RSA_is_s0metimes_insecur3_k0Le2xyX}', 'LKL{RSA_is_s0metimes_insecur3_0GRj9QWU}', 'LKL{RSA_is_s0metimes_insecur3_23Kx2a9O}', 'LKL{RSA_is_s0metimes_insecur3_PSAiCs7Z}', 'LKL{RSA_is_s0metimes_insecur3_v6aG3j0B}', 'LKL{RSA_is_s0metimes_insecur3_xXxmsOuX}', 'LKL{RSA_is_s0metimes_insecur3_92Pe84C8}', 'LKL{RSA_is_s0metimes_insecur3_Dx0qMgaA}', 'LKL{RSA_is_s0metimes_insecur3_OaUGvuMU}', 'LKL{RSA_is_s0metimes_insecur3_c2zHPwlu}', 'LKL{RSA_is_s0metimes_insecur3_UJIh7nj1}', 'LKL{RSA_is_s0metimes_insecur3_fexW2IIJ}', 'LKL{RSA_is_s0metimes_insecur3_FxVr8Y7Q}', 'LKL{RSA_is_s0metimes_insecur3_Zgvph30I}', 'LKL{RSA_is_s0metimes_insecur3_8aezHJSp}']
333b3e57b03c06635723ab136380a76d369174b0
edfcd96f0010ea068a4c046bdcf7067ff92d3f9b
/Modules/datetime/1.py
3dcb2607e4524fae4299e4d4cb1d07b43e896777
[]
no_license
afsanehshu/python-project
a99ff558f375c1f5e17ea6ffc13af9216ec4733f
48905cfd24df6d1f48460d421ed774f19403cf53
refs/heads/main
2023-08-03T01:53:32.812949
2021-09-22T19:36:25
2021-09-22T19:36:25
409,303,454
0
0
null
null
null
null
UTF-8
Python
false
false
83
py
import datetime datetime_object = datetime.datetime.now() print(datetime_object)
560ff9f3f493317e04240dcf5f75f3fb3c0b41e7
500bca3e22bd0c30c79b74918e9847742b3c428e
/sdk/python/endpoints/online/mlflow/sklearn-diabetes/src/score.py
4e2c269f5cb447804f693d12932e283e9219e83f
[ "MIT" ]
permissive
Azure/azureml-examples
2304c862fd2e36e6640ecc4d09f69c5ed93b48ab
e5f7b247d4753f115a8f7da30cbe25294f71f9d7
refs/heads/main
2023-08-31T00:10:14.107509
2023-08-30T17:29:22
2023-08-30T17:29:22
289,334,021
1,219
1,074
MIT
2023-09-14T16:00:55
2020-08-21T18:04:26
Jupyter Notebook
UTF-8
Python
false
false
979
py
import logging import os import json import mlflow from io import StringIO from mlflow.pyfunc.scoring_server import infer_and_parse_json_input, predictions_to_json def init(): global model global input_schema # "model" is the path of the mlflow artifacts when the model was registered. For automl # models, this is generally "mlflow-model". model_path = os.path.join(os.getenv("AZUREML_MODEL_DIR"), "model") model = mlflow.pyfunc.load_model(model_path) input_schema = model.metadata.get_input_schema() def run(raw_data): json_data = json.loads(raw_data) if "input_data" not in json_data.keys(): raise Exception("Request must contain a top level key named 'input_data'") serving_input = json.dumps(json_data["input_data"]) data = infer_and_parse_json_input(serving_input, input_schema) predictions = model.predict(data) result = StringIO() predictions_to_json(predictions, result) return result.getvalue()
3ec15a885991693045ca69757489420fd2440bc1
ee22ec2076a79e8de3011377fe205bc87163ab9f
/src/algo-p5/0828/q27/player.py
1631f0c162cd5940c1385e5e74a4e95c3ea58bec
[]
no_license
n18018/programming-term2
039a95c67372a38a34e2aa8c5975045a9fc731be
86c455269eed312def529604e1ac3b00f476226c
refs/heads/master
2020-03-22T08:59:29.545280
2018-08-29T07:57:37
2018-08-29T07:57:37
139,806,131
0
0
null
2018-07-05T06:42:11
2018-07-05T06:42:11
null
UTF-8
Python
false
false
12,069
py
import field_map import sys import random from enemy import Enemy class Player: def __init__(self, name): """ コンストラクタ Parameters ---------- name : str プレイヤーの名前 Returns ------- 自分自身のインスタンス """ self.name = name self.cur_pos = 0 self.hp = 100 self.max_hp = 100 self.min_damage = 4 self.max_damage = 7 self.freq = 10 self.plant_nums = 10 self.exp = 0 self.level = 1 def choose_action_in_field(self): """ フィールド中での操作を選択する Parameters ---------- なし Returns ------- なし """ # 見やすさのために、空白行を表示 print() # 「何をしますか?」を表示 print("何をしますか?") # 「1:サイコロを振る、2:現在の状態を確認する、3:薬草を使う、9:ゲームを終了する>> 」を表示し、入力待ちにする cmd_num = input("1:サイコロを振る、2:現在の状態を確認する、3:薬草を使う、9:ゲームを終了する>> ") # cmd_numの値によって条件分岐 if cmd_num == "1": # その場から動く self.move() elif cmd_num == "2": # 状態を表示する self.show_status() elif cmd_num == "3": # 薬草を使う self.use_plants() elif cmd_num == "9": # ゲームを終了する self.quit_game() def move(self): """ 動く(サイコロを振る行為を含む) Parameters ---------- なし Returns ------- なし """ # サイコロを振る dice_num = field_map.shake_dice() # 出た目の数だけ前に進む self.go_forward(dice_num) def go_forward(self, cells): """ 前に進む Parameters ---------- cells : int 進むマス目の数 Returns ------- なし """ # 引数のマス目だけ進む self.cur_pos += cells # 現在位置を表示 print("現在位置は" + str(self.cur_pos) + "です。") # 止まったマス目のイベントを取得する event_nm = field_map.get_event(self.cur_pos) if event_nm == "BattleVsZako": # ザコキャラ「スラスラ」と戦う zako = Enemy("スラスラ") self.battle(zako) elif event_nm == "GoMoreForward": # 2マスさらに前に進む self.go_more_forward(2) elif event_nm == "GoBack": # 3マス戻る self.go_back(3) elif event_nm == "GoBackToStart": # 振り出しに戻る self.go_back_to_start() elif event_nm == "HealingLake": # event_nmが"HealingLake"の場合、新たに定義したself.healed_in_lake()を呼び出してください。 self.healed_in_lake() elif event_nm == "PoisonSwamp": # event_nmが"PoisonSwamp"の場合、新たに定義したself.poisoned_in_swamp()を呼び出してください。 self.poisoned_in_swamp() def go_more_forward(self, cells): """ 出た目の分さらに前に進む Parameters ---------- cells : int 進むマス目の数 Returns ------- なし """ print("イベント発生!" + str(cells) + "マスさらに進みます。") # 引数で渡された目の分だけ前に進む self.go_forward(cells) def go_back(self, cells): """ 出た目の分後ろに戻る Parameters ---------- cells : int 戻るマス目の数 Returns ------- なし """ print("イベント発生!" + str(cells) + "マス後ろに戻ります。") # 引数で出た目の分だけ前に戻る(引数に-1を掛けることで戻る動作をしている) self.go_forward((cells * -1)) def go_back_to_start(self): """ 出た目の分後ろに戻る Parameters ---------- なし Returns ------- なし """ print("イベント発生!振り出しに戻ってしまいます!") # 引数で出た目の分だけ前に戻る(引数に-1を掛けることで戻る動作をしている) self.go_forward((self.cur_pos * -1)) def show_status(self): """ 現在の状態を表示する Parameters ---------- なし Returns ------- なし """ # 状態を表示する print(self.name + "の現在位置は" + str(self.cur_pos) + "、HPは" + str(self.hp) + "です。") # 薬草の枚数も表示する。 print("薬草を" + str(self.plant_nums) + "枚持っています。") def battle(self, enemy): """ 敵とたたかう Parameters ---------- enemy : Enemy 敵のオブジェクト Returns ------- なし """ # イベント発生メッセージ print("イベント発生!" + enemy.name + "があらわれた!") # 敵が倒されるまで戦い続ける while enemy.hp > 0: # 見やすさのために空行を表示 print() # ガイドメッセージを表示 print("どうする?") # 「1:攻撃する、3:薬草を使う、9:逃げる>> 」を表示し、入力待ちにする cmd_num = input("1:攻撃する、3:薬草を使う、9:逃げる>> ") if cmd_num == "1": # プレイヤーが敵を攻撃。倒したらループを抜ける if self.attack(enemy): break elif cmd_num == "3": # 薬草を使う self.use_plants() elif cmd_num == "9": # 逃げる print(self.name + "は逃げ出した!") return # 敵がプレイヤーを攻撃。倒されたらゲームオーバー if not enemy.attack(self): print(self.name + "はしんでしまった!世界は闇に包まれてしまった...") sys.exit() # バトル終了 print(self.name + "は" + enemy.name + "を倒した!") def attack(self, enemy): """ 敵を攻撃する Parameters ---------- enemy : Enemy 敵のオブジェクト Returns ------- bool True:敵を倒した、False:敵がまだ生きている """ # ダメージを最小〜最大の範囲でランダムに取得 damage = random.randint(self.min_damage, self.max_damage) is_critical = False # 「かいしんのいちげき」かどうか # 1/(self.freq)の確率で「かいしんのいちげき」を出す rand_num = random.randint(1, self.freq) if rand_num % self.freq == 0: is_critical = True # 自分のターンのメッセージ表示 print(self.name + "のこうげき!") # かいしんのいちげきの場合、ダメージを倍にする if is_critical: print("かいしんのいちげき!!") damage *= 2 # 相手にダメージを与える enemy.hp -= damage if enemy.hp > 0: print(enemy.name + "に" + str(damage) + "のダメージを与えた!" + enemy.name + "のHPは" + str(enemy.hp) + "です。") return False else: print(enemy.name + "に" + str(damage) + "のダメージを与えた!" + enemy.name + "のHPは0です。") return True def use_plants(self): """ 薬草を使う Parameters ---------- なし Returns ------- なし """ # 薬草を持っていなければ、その旨表示して終了 if self.plant_nums <= 0: print(self.name + "は薬草を持っていない") return # メッセージ表示 print(self.name + "は薬草を使った!") # HPを30ポイント回復 self.hp += 30 # HPが最大を超えないように調整 if self.hp > self.max_hp: self.hp = self.max_hp # 持っている薬草を1枚減らす self.plant_nums -= 1 # 回復したHPの状態を表示 print(self.name + "のHPが" + str(self.hp) + "に回復した!") # healed_in_lakeメソッドを定義します。引数はselfのみです。 def healed_in_lake(self): """ 湖でHPを回復される Parameters ---------- なし Returns ------- なし """ # 「イベント発生!癒しの湖で身を清めます。」を表示してください。 print("イベント発生!癒しの湖で身を清めます。") # HPを最大まで回復します。self.hpにself.max_hpを代入してください。 self.hp = self.max_hp # 「(self.name)のHPが全回復した!現在のHPは(self.hp)です。」を表示してください。 print(self.name, "のHPは全回復した!現在のHPは", self.hp, "です。") # poisoned_in_swampメソッドを定義します。引数はselfのみです。 def poisoned_in_swamp(self): """ 沼で毒に冒される Parameters ---------- なし Returns ------- なし """ # 「イベント発生!沼で毒に冒されました。」を表示してください。 print("イベント発生!沼で毒に冒されました。") # 20のダメージを受けます。self.hpから20を引いて(self.hpに再代入して)ください。 self.hp = self.hp - 20 if self.hp > 0: # self.hpが0より大きい場合、「(self.name)は20のダメージを受けた!現在のHPは(self.hp)です。」を表示してください。 print(self.name, "は20のダメージを受けた!現在のHPは", self.hp, "です。") else: # 上記以外の場合、「(self.name)は20のダメージを受けた!(self.name)はしんでしまった!世界は闇に包まれてしまった...」を表示してください。 print(self.name, "は20のダメージを受けた!", self.name, "はしんでしまった!世界は闇に包まれてしまった...") # ゲームオーバーなので終了です。1つ前のメッセージに続けて、sys.exit()を呼び出してください。 sys.exit() def quit_game(self): """ ゲームを終了する Parameters ---------- なし Returns ------- なし """ # 終了するかどうかの確認メッセージを表示 cmd_str = input("ゲームの状態はセーブされません。終了しますか?(y/n) ") # Yが押されたら終了 if cmd_str.upper() == "Y": sys.exit() # 以下メイン処理 if __name__ == '__main__': # プレイヤーのオブジェクトを作成 kevin = Player("ケビン") # 敵のオブジェクトを作成 enemy = Enemy("スラスラ") # ケビンとスラスラが戦う kevin.battle(enemy) # バトル後のケビンのステータスを表示 kevin.show_status()
0dec940c8d9ee73e47f55d49a771aebb21beec6d
55d560fe6678a3edc9232ef14de8fafd7b7ece12
/tools/build/test/rescan_header.py
36a007eb406fa403704cb5091d42f2606d7901ce
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
stardog-union/boost
ec3abeeef1b45389228df031bf25b470d3d123c5
caa4a540db892caa92e5346e0094c63dea51cbfb
refs/heads/stardog/develop
2021-06-25T02:15:10.697006
2020-11-17T19:50:35
2020-11-17T19:50:35
148,681,713
0
0
BSL-1.0
2020-11-17T19:50:36
2018-09-13T18:38:54
C++
UTF-8
Python
false
false
5,653
py
#!/usr/bin/python # Copyright 2012 Steven Watanabe # Distributed under the Boost Software License, Version 1.0. # (See accompanying file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) import BoostBuild t = BoostBuild.Tester(use_test_config=False) # Test a header loop that depends on (but does not contain) a generated header. t.write("test.cpp", '#include "header1.h"\n') t.write("header1.h", """\ #ifndef HEADER1_H #define HEADER1_H #include "header2.h" #endif """) t.write("header2.h", """\ #ifndef HEADER2_H #define HEADER2_H #include "header1.h" #include "header3.h" #endif """) t.write("header3.in", "/* empty file */\n") t.write("jamroot.jam", """\ import common ; make header3.h : header3.in : @common.copy ; obj test : test.cpp : <implicit-dependency>header3.h ; """) t.run_build_system(["-j2"]) t.expect_addition("bin/header3.h") t.expect_addition("bin/$toolset/debug*/test.obj") t.expect_nothing_more() t.rm(".") # Test a linear sequence of generated headers. t.write("test.cpp", '#include "header1.h"\n') t.write("header1.in", """\ #ifndef HEADER1_H #define HEADER1_H #include "header2.h" #endif """) t.write("header2.in", """\ #ifndef HEADER2_H #define HEADER2_H #include "header3.h" #endif """) t.write("header3.in", "/* empty file */\n") t.write("jamroot.jam", """\ import common ; make header1.h : header1.in : @common.copy ; make header2.h : header2.in : @common.copy ; make header3.h : header3.in : @common.copy ; obj test : test.cpp : <implicit-dependency>header1.h <implicit-dependency>header2.h <implicit-dependency>header3.h ; """) t.run_build_system(["-j2", "test"]) t.expect_addition("bin/header1.h") t.expect_addition("bin/header2.h") t.expect_addition("bin/header3.h") t.expect_addition("bin/$toolset/debug*/test.obj") t.expect_nothing_more() t.rm(".") # Test a loop in generated headers. t.write("test.cpp", '#include "header1.h"\n') t.write("header1.in", """\ #ifndef HEADER1_H #define HEADER1_H #include "header2.h" #endif """) t.write("header2.in", """\ #ifndef HEADER2_H #define HEADER2_H #include "header3.h" #endif """) t.write("header3.in", """\ #ifndef HEADER2_H #define HEADER2_H #include "header1.h" #endif """) t.write("jamroot.jam", """\ import common ; actions copy { sleep 1 cp $(>) $(<) } make header1.h : header1.in : @common.copy ; make header2.h : header2.in : @common.copy ; make header3.h : header3.in : @common.copy ; obj test : test.cpp : <implicit-dependency>header1.h <implicit-dependency>header2.h <implicit-dependency>header3.h ; """) t.run_build_system(["-j2", "test"]) t.expect_addition("bin/header1.h") t.expect_addition("bin/header2.h") t.expect_addition("bin/header3.h") t.expect_addition("bin/$toolset/debug*/test.obj") t.expect_nothing_more() t.rm(".") # Test that all the dependencies of a loop are updated before any of the # dependents. t.write("test1.cpp", '#include "header1.h"\n') t.write("test2.cpp", """\ #include "header2.h" int main() {} """) t.write("header1.h", """\ #ifndef HEADER1_H #define HEADER1_H #include "header2.h" #endif """) t.write("header2.h", """\ #ifndef HEADER2_H #define HEADER2_H #include "header1.h" #include "header3.h" #endif """) t.write("header3.in", "\n") t.write("sleep.bat", """\ ::@timeout /T %1 /NOBREAK >nul @ping 127.0.0.1 -n 2 -w 1000 >nul @ping 127.0.0.1 -n %1 -w 1000 >nul @exit /B 0 """) t.write("jamroot.jam", """\ import common ; import os ; if [ os.name ] = NT { SLEEP = call sleep.bat ; } else { SLEEP = sleep ; } rule copy { common.copy $(<) : $(>) ; } actions copy { $(SLEEP) 1 } make header3.h : header3.in : @copy ; exe test : test2.cpp test1.cpp : <implicit-dependency>header3.h ; """) t.run_build_system(["-j2", "test"]) t.expect_addition("bin/header3.h") t.expect_addition("bin/$toolset/debug*/test1.obj") t.expect_addition("bin/$toolset/debug*/test2.obj") t.expect_addition("bin/$toolset/debug*/test.exe") t.expect_nothing_more() t.touch("header3.in") t.run_build_system(["-j2", "test"]) t.expect_touch("bin/header3.h") t.expect_touch("bin/$toolset/debug*/test1.obj") t.expect_touch("bin/$toolset/debug*/test2.obj") t.expect_touch("bin/$toolset/debug*/test.exe") t.expect_nothing_more() t.rm(".") # Test a loop that includes a generated header t.write("test1.cpp", '#include "header1.h"\n') t.write("test2.cpp", """\ #include "header2.h" int main() {} """) t.write("header1.h", """\ #ifndef HEADER1_H #define HEADER1_H #include "header2.h" #endif """) t.write("header2.in", """\ #ifndef HEADER2_H #define HEADER2_H #include "header3.h" #endif """) t.write("header3.h", """\ #ifndef HEADER3_H #define HEADER3_H #include "header1.h" #endif """) t.write("sleep.bat", """\ ::@timeout /T %1 /NOBREAK >nul @ping 127.0.0.1 -n 2 -w 1000 >nul @ping 127.0.0.1 -n %1 -w 1000 >nul @exit /B 0 """) t.write("jamroot.jam", """\ import common ; import os ; if [ os.name ] = NT { SLEEP = call sleep.bat ; } else { SLEEP = sleep ; } rule copy { common.copy $(<) : $(>) ; } actions copy { $(SLEEP) 1 } make header2.h : header2.in : @copy ; exe test : test2.cpp test1.cpp : <implicit-dependency>header2.h <include>. ; """) t.run_build_system(["-j2", "test"]) t.expect_addition("bin/header2.h") t.expect_addition("bin/$toolset/debug*/test1.obj") t.expect_addition("bin/$toolset/debug*/test2.obj") t.expect_addition("bin/$toolset/debug*/test.exe") t.expect_nothing_more() t.cleanup()
87329ac75e0a03161d9c4ec7e50671e1a8c5b0d0
22299195d67f887d8de9f8764e8a85680cd3416c
/class7 (Color Filtering - OpenCV with Python for Image and Video Analysis 7)/main.py
e4430a318df1dc716db227d2a786414f7b6eb3ff
[]
no_license
EnggQasim/PythonOpenCV
71268cb9bfa603b9aec1e239756f515f9693f74c
2f1cd61df0fd520dbdc0e41a52ebfc4da410c771
refs/heads/master
2021-01-01T15:29:14.768477
2017-07-18T18:11:19
2017-07-18T18:11:19
97,629,494
3
0
null
null
null
null
UTF-8
Python
false
false
500
py
import cv2 import numpy as np cap = cv2.VideoCapture(1) while True: _, frame = cap.read() hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) #hsv hue sat value lower_red = np.array([150,150,50]) upper_red = np.array([180, 255, 150]) mask = cv2.inRange(hsv, lower_red, upper_red) res = cv2.bitwise_and(frame, frame, mask=mask) cv2.imshow('Frame', frame) cv2.imshow('Mask', mask) cv2.imshow('Result', res) k = cv2.waitKey(5) & 0xFF if k == 27: break cv2.destroyAllWindows() cv2.release()
51fe296f9a06966e6e243a907c4209236b1137e9
0c66e605e6e4129b09ea14dbb6aa353d18aaa027
/diventi/ebooks/migrations/0007_auto_20190429_1732.py
3b567492131adb79f3e21d1f851220e0b4b14f01
[ "Apache-2.0" ]
permissive
flavoi/diventi
58fbc8c947f387cbcc1ce607878a59a6f2b72313
c0b1efe2baa3ff816d6ee9a8e86623f297973ded
refs/heads/master
2023-07-20T09:32:35.897661
2023-07-11T19:44:26
2023-07-11T19:44:26
102,959,477
2
1
Apache-2.0
2023-02-08T01:03:17
2017-09-09T14:10:51
Python
UTF-8
Python
false
false
1,340
py
# Generated by Django 2.1.7 on 2019-04-29 15:32 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('ebooks', '0006_auto_20190429_1727'), ] operations = [ migrations.AddField( model_name='chapter', name='description_en', field=models.TextField(null=True, verbose_name='description'), ), migrations.AddField( model_name='chapter', name='description_it', field=models.TextField(null=True, verbose_name='description'), ), migrations.AddField( model_name='chapter', name='slug_en', field=models.SlugField(null=True, unique=True, verbose_name='slug'), ), migrations.AddField( model_name='chapter', name='slug_it', field=models.SlugField(null=True, unique=True, verbose_name='slug'), ), migrations.AddField( model_name='chapter', name='title_en', field=models.CharField(max_length=50, null=True, verbose_name='title'), ), migrations.AddField( model_name='chapter', name='title_it', field=models.CharField(max_length=50, null=True, verbose_name='title'), ), ]
a4c78496e3e6c0ca7c8343f03b0e455be84de413
585fcfd09bcc37ad73c6f301cb8b16261a93df7e
/projects/pyDOE-master/pyDOE/build_regression_matrix.py
5ea2c2f53342a023823a115a04a403407c9ccc3d
[ "MIT", "BSD-3-Clause" ]
permissive
louisXW/Surrogate-Model
e9e8de3ab892eed2f8ed424e09b770e67126c1f3
65ec8a89c1b7a19d4c04c62e2c988340c96c69f8
refs/heads/master
2021-07-21T09:37:41.045898
2017-10-30T11:49:35
2017-10-30T11:49:35
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,909
py
""" This code was originally published by the following individuals for use with Scilab: Copyright (C) 2012 - 2013 - Michael Baudin Copyright (C) 2012 - Maria Christopoulou Copyright (C) 2010 - 2011 - INRIA - Michael Baudin Copyright (C) 2009 - Yann Collette Copyright (C) 2009 - CEA - Jean-Marc Martinez website: forge.scilab.org/index.php/p/scidoe/sourcetree/master/macros Much thanks goes to these individuals. It has been converted to Python by Abraham Lee. """ import numpy as np def grep(haystack, needle): start = 0 while True: start = haystack.find(needle, start) if start == -1: return yield start start += len(needle) def build_regression_matrix(H, model, build=None): """ Build a regression matrix using a DOE matrix and a list of monomials. Parameters ---------- H : 2d-array model : str build : bool-array Returns ------- R : 2d-array """ ListOfTokens = model.split(' ') if H.shape[1] == 1: size_index = len(str(H.shape[0])) else: size_index = len(str(H.shape[1])) if build is None: build = [True] * len(ListOfTokens) # Test if the vector has the wrong direction (lines instead of columns) if H.shape[0] == 1: H = H.T # Collect the list of monomials Monom_Index = [] for i in range(len(ListOfTokens)): if build[i]: Monom_Index += [grep(ListOfTokens, 'x' + str(0) * (size_index - \ len(str(i))) + str(i))] Monom_Index = -np.sort(-Monom_Index) Monom_Index = np.unique(Monom_Index) if H.shape[1] == 1: nb_var = H.shape[0] # vector "mode": the number of vars is equal to the number of lines of H VectorMode = True for i in range(nb_var): for j in range(ListOfTokens.shape[0]): ListOfTokens[j] = ListOfTokens[j].replace( 'x' + str(0) * (size_index - len(str(i))) + str(i), 'H(' + str(i) + ')') else: nb_var = H.shape[0] # matrix "mode": the number of vars is equal to the number of columns of H VectorMode = False for i in range(nb_var): for j in range(ListOfTokens.shape[0]): ListOfTokens[j] = ListOfTokens[j].replace( 'x' + str(0) * (size_index - len(str(i))) + str(i), 'H[i,' + str(i) + ')') # Now build the regression matrix if VectorMode: R = np.zeros((len(ListOfTokens), 1)) for j in range(len(ListOfTokens)): R[j, 0] = eval(ListOfTokens[j]) else: R = np.zeros((H.shape[0], len(ListOfTokens))) for i in range(H.shape[0]): for j in range(len(ListOfTokens)): R[i, j] = eval(ListOfTokens[j]) return R
21258aa7598c5f930fe4eaed3af4d0a499b648d9
98efe1aee73bd9fbec640132e6fb2e54ff444904
/loldib/getratings/models/NA/na_ornn/na_ornn_top.py
2ca0d07a4824d85d8de49a6105daf5c1b67f4de7
[ "Apache-2.0" ]
permissive
koliupy/loldib
be4a1702c26546d6ae1b4a14943a416f73171718
c9ab94deb07213cdc42b5a7c26467cdafaf81b7f
refs/heads/master
2021-07-04T03:34:43.615423
2017-09-21T15:44:10
2017-09-21T15:44:10
104,359,388
0
0
null
null
null
null
UTF-8
Python
false
false
6,269
py
from getratings.models.ratings import Ratings class NA_Ornn_Top_Aatrox(Ratings): pass class NA_Ornn_Top_Ahri(Ratings): pass class NA_Ornn_Top_Akali(Ratings): pass class NA_Ornn_Top_Alistar(Ratings): pass class NA_Ornn_Top_Amumu(Ratings): pass class NA_Ornn_Top_Anivia(Ratings): pass class NA_Ornn_Top_Annie(Ratings): pass class NA_Ornn_Top_Ashe(Ratings): pass class NA_Ornn_Top_AurelionSol(Ratings): pass class NA_Ornn_Top_Azir(Ratings): pass class NA_Ornn_Top_Bard(Ratings): pass class NA_Ornn_Top_Blitzcrank(Ratings): pass class NA_Ornn_Top_Brand(Ratings): pass class NA_Ornn_Top_Braum(Ratings): pass class NA_Ornn_Top_Caitlyn(Ratings): pass class NA_Ornn_Top_Camille(Ratings): pass class NA_Ornn_Top_Cassiopeia(Ratings): pass class NA_Ornn_Top_Chogath(Ratings): pass class NA_Ornn_Top_Corki(Ratings): pass class NA_Ornn_Top_Darius(Ratings): pass class NA_Ornn_Top_Diana(Ratings): pass class NA_Ornn_Top_Draven(Ratings): pass class NA_Ornn_Top_DrMundo(Ratings): pass class NA_Ornn_Top_Ekko(Ratings): pass class NA_Ornn_Top_Elise(Ratings): pass class NA_Ornn_Top_Evelynn(Ratings): pass class NA_Ornn_Top_Ezreal(Ratings): pass class NA_Ornn_Top_Fiddlesticks(Ratings): pass class NA_Ornn_Top_Fiora(Ratings): pass class NA_Ornn_Top_Fizz(Ratings): pass class NA_Ornn_Top_Galio(Ratings): pass class NA_Ornn_Top_Gangplank(Ratings): pass class NA_Ornn_Top_Garen(Ratings): pass class NA_Ornn_Top_Gnar(Ratings): pass class NA_Ornn_Top_Gragas(Ratings): pass class NA_Ornn_Top_Graves(Ratings): pass class NA_Ornn_Top_Hecarim(Ratings): pass class NA_Ornn_Top_Heimerdinger(Ratings): pass class NA_Ornn_Top_Illaoi(Ratings): pass class NA_Ornn_Top_Irelia(Ratings): pass class NA_Ornn_Top_Ivern(Ratings): pass class NA_Ornn_Top_Janna(Ratings): pass class NA_Ornn_Top_JarvanIV(Ratings): pass class NA_Ornn_Top_Jax(Ratings): pass class NA_Ornn_Top_Jayce(Ratings): pass class NA_Ornn_Top_Jhin(Ratings): pass class NA_Ornn_Top_Jinx(Ratings): pass class NA_Ornn_Top_Kalista(Ratings): pass class NA_Ornn_Top_Karma(Ratings): pass class NA_Ornn_Top_Karthus(Ratings): pass class NA_Ornn_Top_Kassadin(Ratings): pass class NA_Ornn_Top_Katarina(Ratings): pass class NA_Ornn_Top_Kayle(Ratings): pass class NA_Ornn_Top_Kayn(Ratings): pass class NA_Ornn_Top_Kennen(Ratings): pass class NA_Ornn_Top_Khazix(Ratings): pass class NA_Ornn_Top_Kindred(Ratings): pass class NA_Ornn_Top_Kled(Ratings): pass class NA_Ornn_Top_KogMaw(Ratings): pass class NA_Ornn_Top_Leblanc(Ratings): pass class NA_Ornn_Top_LeeSin(Ratings): pass class NA_Ornn_Top_Leona(Ratings): pass class NA_Ornn_Top_Lissandra(Ratings): pass class NA_Ornn_Top_Lucian(Ratings): pass class NA_Ornn_Top_Lulu(Ratings): pass class NA_Ornn_Top_Lux(Ratings): pass class NA_Ornn_Top_Malphite(Ratings): pass class NA_Ornn_Top_Malzahar(Ratings): pass class NA_Ornn_Top_Maokai(Ratings): pass class NA_Ornn_Top_MasterYi(Ratings): pass class NA_Ornn_Top_MissFortune(Ratings): pass class NA_Ornn_Top_MonkeyKing(Ratings): pass class NA_Ornn_Top_Mordekaiser(Ratings): pass class NA_Ornn_Top_Morgana(Ratings): pass class NA_Ornn_Top_Nami(Ratings): pass class NA_Ornn_Top_Nasus(Ratings): pass class NA_Ornn_Top_Nautilus(Ratings): pass class NA_Ornn_Top_Nidalee(Ratings): pass class NA_Ornn_Top_Nocturne(Ratings): pass class NA_Ornn_Top_Nunu(Ratings): pass class NA_Ornn_Top_Olaf(Ratings): pass class NA_Ornn_Top_Orianna(Ratings): pass class NA_Ornn_Top_Ornn(Ratings): pass class NA_Ornn_Top_Pantheon(Ratings): pass class NA_Ornn_Top_Poppy(Ratings): pass class NA_Ornn_Top_Quinn(Ratings): pass class NA_Ornn_Top_Rakan(Ratings): pass class NA_Ornn_Top_Rammus(Ratings): pass class NA_Ornn_Top_RekSai(Ratings): pass class NA_Ornn_Top_Renekton(Ratings): pass class NA_Ornn_Top_Rengar(Ratings): pass class NA_Ornn_Top_Riven(Ratings): pass class NA_Ornn_Top_Rumble(Ratings): pass class NA_Ornn_Top_Ryze(Ratings): pass class NA_Ornn_Top_Sejuani(Ratings): pass class NA_Ornn_Top_Shaco(Ratings): pass class NA_Ornn_Top_Shen(Ratings): pass class NA_Ornn_Top_Shyvana(Ratings): pass class NA_Ornn_Top_Singed(Ratings): pass class NA_Ornn_Top_Sion(Ratings): pass class NA_Ornn_Top_Sivir(Ratings): pass class NA_Ornn_Top_Skarner(Ratings): pass class NA_Ornn_Top_Sona(Ratings): pass class NA_Ornn_Top_Soraka(Ratings): pass class NA_Ornn_Top_Swain(Ratings): pass class NA_Ornn_Top_Syndra(Ratings): pass class NA_Ornn_Top_TahmKench(Ratings): pass class NA_Ornn_Top_Taliyah(Ratings): pass class NA_Ornn_Top_Talon(Ratings): pass class NA_Ornn_Top_Taric(Ratings): pass class NA_Ornn_Top_Teemo(Ratings): pass class NA_Ornn_Top_Thresh(Ratings): pass class NA_Ornn_Top_Tristana(Ratings): pass class NA_Ornn_Top_Trundle(Ratings): pass class NA_Ornn_Top_Tryndamere(Ratings): pass class NA_Ornn_Top_TwistedFate(Ratings): pass class NA_Ornn_Top_Twitch(Ratings): pass class NA_Ornn_Top_Udyr(Ratings): pass class NA_Ornn_Top_Urgot(Ratings): pass class NA_Ornn_Top_Varus(Ratings): pass class NA_Ornn_Top_Vayne(Ratings): pass class NA_Ornn_Top_Veigar(Ratings): pass class NA_Ornn_Top_Velkoz(Ratings): pass class NA_Ornn_Top_Vi(Ratings): pass class NA_Ornn_Top_Viktor(Ratings): pass class NA_Ornn_Top_Vladimir(Ratings): pass class NA_Ornn_Top_Volibear(Ratings): pass class NA_Ornn_Top_Warwick(Ratings): pass class NA_Ornn_Top_Xayah(Ratings): pass class NA_Ornn_Top_Xerath(Ratings): pass class NA_Ornn_Top_XinZhao(Ratings): pass class NA_Ornn_Top_Yasuo(Ratings): pass class NA_Ornn_Top_Yorick(Ratings): pass class NA_Ornn_Top_Zac(Ratings): pass class NA_Ornn_Top_Zed(Ratings): pass class NA_Ornn_Top_Ziggs(Ratings): pass class NA_Ornn_Top_Zilean(Ratings): pass class NA_Ornn_Top_Zyra(Ratings): pass
9b1a400d3281860f99c1cb1c0f0a9b1c2006bf90
2d191eb46ed804c9029801832ff4016aeaf8d31c
/configs/_base_/models/deeplabv3_sep_r50-d8.py
bb8c92051e538c75132eb8666ccb1d1cc8698ffc
[ "Apache-2.0" ]
permissive
openseg-group/mmsegmentation
df99ac2c3510b7f2dff92405aae25026d1023d98
23939f09d2b0bd30fc26eb7f8af974f1f5441210
refs/heads/master
2023-03-02T07:49:23.652558
2021-02-15T04:16:28
2021-02-15T04:16:28
278,537,243
2
2
null
2020-07-10T04:24:16
2020-07-10T04:24:15
null
UTF-8
Python
false
false
1,330
py
# model settings norm_cfg = dict(type='SyncBN', requires_grad=True) model = dict( type='EncoderDecoder', pretrained='open-mmlab://resnet50_v1c', backbone=dict( type='ResNetV1c', depth=50, num_stages=4, out_indices=(0, 1, 2, 3), dilations=(1, 1, 2, 4), strides=(1, 2, 1, 1), norm_cfg=norm_cfg, norm_eval=False, style='pytorch', contract_dilation=True), decode_head=dict( type='DepthwiseSeparableASPPHead', in_channels=2048, in_index=3, channels=512, dilations=(1, 12, 24, 36), c1_in_channels=0, c1_channels=0, dropout_ratio=0.1, num_classes=19, norm_cfg=norm_cfg, align_corners=False, loss_decode=dict( type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0)), auxiliary_head=dict( type='FCNHead', in_channels=1024, in_index=2, channels=256, num_convs=1, concat_input=False, dropout_ratio=0.1, num_classes=19, norm_cfg=norm_cfg, align_corners=False, loss_decode=dict( type='CrossEntropyLoss', use_sigmoid=False, loss_weight=0.4))) # model training and testing settings train_cfg = dict() test_cfg = dict(mode='whole')
ad77f04ce6810e07fd8407db9354c5b4139ab67e
17dca703eed28a859bba4984eba5b039b900e3d7
/.history/nomina/views_20200227181321.py
a9f9c322cb015feead3955c66ebab05f4727ad27
[]
no_license
alexogch1/SistemaOperaciones
1a34872daf0e151672edd202a5089ee754805203
ac72f6e3284061e240aebec6a3300ff463a3544c
refs/heads/master
2021-01-03T15:32:45.470642
2020-03-03T07:47:27
2020-03-03T07:47:27
240,133,319
0
1
null
2020-02-28T05:21:57
2020-02-12T23:02:36
Python
UTF-8
Python
false
false
5,733
py
from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render from django.urls import reverse_lazy from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.messages.views import SuccessMessageMixin #from .filters import NominaFiltro from dateutil.parser import parse from django.views import generic from generales.views import SinPrivilegios from .form import NominaEncForm, NominaDetForm, DetalleNominaFormSet from .models import NominaEnc, NominaDet class NominaCompletaList(generic.ListView): template_name='nomina/nomina_completa.html' context_object_name='nomina' queryset = NominaEnc.objects.all() def get_context_data(self, **kwargs): context = super(NominaCompletaList, self).get_context_data(**kwargs) context['detalles'] = NominaDet.objects.all() context['encabezado'] = self.queryset return context class NominaList( generic.ListView): model=NominaEnc template_name='nomina/nomina_list.html' context_object_name='nomina' """ def get_context_data(self, **kwargs): context = super(NominaList, self).get_context_data(**kwargs) initial_date = self.request.GET.get('fecha_inicial') final_date = self.request.GET.get('fecha_final') if not initial_date or not final_date: context ['nomina'] = NominaEnc.objects.order_by('fecha_nomina') else: initial_date = parse(initial_date) final_date = parse(final_date) context['nomina'] = NominaEnc.objects.filter(fecha_nomina__gte=initial_date, fecha_nomina__lte=final_date ) return context """ #def get_context_data(self, **kwargs): #context = super().get_context_data(**kwargs) #context['filter']=NominaFiltro(self.request.GET, queryset=self.get_queryset()) #return context class NominaNew(SinPrivilegios, generic.CreateView): permission_required='nomina.add_nominaenc' model=NominaEnc login_url='generales:home' template_name='nomina/nomina_form.html' form_class=NominaEncForm success_url=reverse_lazy('nomina:nomina_list') def get(self, request, *args, **kwargs): self.object=None form_class=self.get_form_class() form=self.get_form(form_class) detalle_nomina_formset=DetalleNominaFormSet() return self.render_to_response( self.get_context_data( form=form, detalle_nomina = detalle_nomina_formset ) ) def post(self, request, *args, **kwargs): form_class=self.get_form_class() form=self.get_form(form_class) detalle_nomina=DetalleNominaFormSet(request.POST) if form.is_valid() and detalle_nomina.is_valid(): return self.form_valid(form, detalle_nomina) else: return self.form_invalid(form, detalle_nomina) def form_valid(self, form, detalle_nomina): self.object=form.save() detalle_nomina.instance=self.object detalle_nomina.save() return HttpResponseRedirect(self.success_url) def form_invalid(self, form, detalle_nomina): return self.render_to_response( self.get_context_data( form=form, detalle_nomina=detalle_nomina ) ) class NominaEdit(SinPrivilegios,generic.UpdateView): permission_required='nomina.change_nominaenc' model=NominaEnc login_url='generales:home' template_name='nomina/nomina_form.html' form_class=NominaEncForm success_url=reverse_lazy('nomina:nomina_list') def get_success_url(self): from django.urls import reverse return reverse ('nomina:nomina_edit', kwargs={'pk':self.get_object().id}) def get (self, request, *args, **kwargs): self.object = self.get_object() form_class = self.get_form_class() form = self.get_form(form_class) detalles =NominaDet.objects.filter(nomina=self.object).order_by('pk') detalles_data = [] for detalle in detalles: d={ 'concepto':detalle.concepto, 'cantidad':detalle.cantidad } detalles_data.append(d) detalle_nomina = DetalleNominaFormSet(initial=detalles_data) detalle_nomina.extra += len(detalles_data) return self.render_to_response( self.get_context_data( form=form, detalle_nomina = detalle_nomina ) ) def post(self,request, *args, **kwargs): self.object = self.get_object() form_class = self.get_form_class() form=self.get_form(form_class) detalle_nomina = DetalleNominaFormSet(request.POST) if form.is_valid() and detalle_nomina.is_valid(): return self.form_valid(form, detalle_nomina) else: return self.form_valid(form, detalle_nomina) def form_valid(self, form, detalle_nomina): self.object = form.save() detalle_nomina.instance =self.object NominaDet.objects.filter(nomina=self.object).delete() detalle_nomina.save() return HttpResponseRedirect(self.get_success_url()) def form_invalid(self, form, detalle_nomina): return self.render_to_response( self.get_context_data( form=form, detalle_nomina=detalle_nomina ) ) class NominaDel(SinPrivilegios,generic.DeleteView): permission_required='nomina:delete_nominaenc' model= NominaEnc template_name = 'nomina/nomina_del.html' context_object_name='obj' success_url=reverse_lazy('nomina:nomina_list')
5a0772e1a8a55625488fe06642e451fb792dad75
b0129214b1d493bdec6fc4658727775fb4066a5e
/addons/todo_user/__manifest__.py
373e3f23f73a060a7b0267b94f628db4cc01f954
[]
no_license
gitstalker/docker_odoo
9875636e4f1bf60a8e55c7a66e8c85abf5f61661
c049d93586f1c35300563fc77685da22d9cc4e14
refs/heads/master
2020-05-02T01:10:45.705337
2018-10-20T12:03:20
2018-10-20T12:03:20
null
0
0
null
null
null
null
UTF-8
Python
false
false
177
py
{ 'name':'Multiuser To-Do', 'description': 'Extend the To-Do app to multiuser.', 'depends': ['website'], 'data':['views/templates.xml'], 'author': 'hdwolf' }
8d2db0e03577849c03ffa9b296d5a266ea0fb0d7
f576f0ea3725d54bd2551883901b25b863fe6688
/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_replicas_operations.py
ed2a170e523af5c4bd570d0b9b817e6a9a04d6ce
[ "LicenseRef-scancode-generic-cla", "MIT", "LGPL-2.1-or-later" ]
permissive
Azure/azure-sdk-for-python
02e3838e53a33d8ba27e9bcc22bd84e790e4ca7c
c2ca191e736bb06bfbbbc9493e8325763ba990bb
refs/heads/main
2023-09-06T09:30:13.135012
2023-09-06T01:08:06
2023-09-06T01:08:06
4,127,088
4,046
2,755
MIT
2023-09-14T21:48:49
2012-04-24T16:46:12
Python
UTF-8
Python
false
false
5,650
py
# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models from ..._vendor import _convert_request from ...operations._replicas_operations import build_list_by_server_request from .._vendor import MySQLManagementClientMixinABC T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class ReplicasOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.rdbms.mysql.aio.MySQLManagementClient`'s :attr:`replicas` attribute. """ models = _models def __init__(self, *args, **kwargs) -> None: input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list_by_server( self, resource_group_name: str, server_name: str, **kwargs: Any ) -> AsyncIterable["_models.Server"]: """List all the replicas for a given server. :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str :param server_name: The name of the server. Required. :type server_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Server or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql.models.Server] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) cls: ClsType[_models.ServerListResult] = kwargs.pop("cls", None) error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_list_by_server_request( resource_group_name=resource_group_name, server_name=server_name, subscription_id=self._config.subscription_id, api_version=api_version, template_url=self.list_by_server.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("ServerListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) # type: ignore return None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) list_by_server.metadata = { "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/replicas" }
05ccf6e2d5d1a9e66261f6829dcff9f2468cbea3
124bdbf417117fe23168f043dd265f88b3bd6e70
/lib/datasets/__init__.py
e62bcd2b434d9f62ee2b19a9875c4c64db1d00e6
[]
no_license
tonyonifo/anytime
943f56ebd4759f0f5181607d8030d50eabb8d38b
86bba7a334fc65899da01b30d925437163c1dede
refs/heads/master
2023-08-02T21:32:42.977184
2021-10-05T16:58:35
2021-10-05T16:58:35
null
0
0
null
null
null
null
UTF-8
Python
false
false
158
py
from __future__ import absolute_import from __future__ import division from __future__ import print_function from .cityscapes import Cityscapes as cityscapes
c73ca1e3ae1851e55b801e24ff6219b8ff872295
59eccb126e4efd0f39bab0b00683a9fbdd9b5e69
/tests/test_core.py
a1a01024c77cd89be8debe19e4246d704d0f3971
[ "BSD-3-Clause" ]
permissive
Deepomatic/channels_redis
c694ca7ab711937e2c3c245c5f817cdf06549640
54d935beb6842333ba4f3e6c29cbe86c4307cf16
refs/heads/master
2020-03-09T20:07:54.566703
2018-04-03T16:05:44
2018-04-03T16:05:44
128,975,901
0
0
null
2018-04-10T18:08:14
2018-04-10T18:08:13
null
UTF-8
Python
false
false
9,624
py
import asyncio import async_timeout import pytest from async_generator import async_generator, yield_ from asgiref.sync import async_to_sync from channels_redis.core import ChannelFull, RedisChannelLayer TEST_HOSTS = [("localhost", 6379)] MULTIPLE_TEST_HOSTS = [ "redis://localhost:6379/0", "redis://localhost:6379/1", "redis://localhost:6379/2", "redis://localhost:6379/3", "redis://localhost:6379/4", "redis://localhost:6379/5", "redis://localhost:6379/6", "redis://localhost:6379/7", "redis://localhost:6379/8", "redis://localhost:6379/9", ] @pytest.fixture() @async_generator async def channel_layer(): """ Channel layer fixture that flushes automatically. """ channel_layer = RedisChannelLayer(hosts=TEST_HOSTS, capacity=3) await yield_(channel_layer) await channel_layer.flush() @pytest.fixture() @async_generator async def channel_layer_multiple_hosts(): """ Channel layer fixture that flushes automatically. """ channel_layer = RedisChannelLayer(hosts=MULTIPLE_TEST_HOSTS, capacity=3) await yield_(channel_layer) await channel_layer.flush() @pytest.mark.asyncio async def test_send_receive(channel_layer): """ Makes sure we can send a message to a normal channel then receive it. """ await channel_layer.send( "test-channel-1", { "type": "test.message", "text": "Ahoy-hoy!", }, ) message = await channel_layer.receive("test-channel-1") assert message["type"] == "test.message" assert message["text"] == "Ahoy-hoy!" @pytest.mark.parametrize("channel_layer", [None]) # Fixture can't handle sync def test_double_receive(channel_layer): """ Makes sure we can receive from two different event loops using process-local channel names. """ channel_layer = RedisChannelLayer(hosts=TEST_HOSTS, capacity=3) channel_name_1 = async_to_sync(channel_layer.new_channel)() channel_name_2 = async_to_sync(channel_layer.new_channel)() async_to_sync(channel_layer.send)(channel_name_1, {"type": "test.message.1"}) async_to_sync(channel_layer.send)(channel_name_2, {"type": "test.message.2"}) # Make things to listen on the loops async def listen1(): message = await channel_layer.receive(channel_name_1) assert message["type"] == "test.message.1" async def listen2(): message = await channel_layer.receive(channel_name_2) assert message["type"] == "test.message.2" # Run them inside threads async_to_sync(listen2)() async_to_sync(listen1)() # Clean up async_to_sync(channel_layer.flush)() @pytest.mark.asyncio async def test_send_capacity(channel_layer): """ Makes sure we get ChannelFull when we hit the send capacity """ await channel_layer.send("test-channel-1", {"type": "test.message"}) await channel_layer.send("test-channel-1", {"type": "test.message"}) await channel_layer.send("test-channel-1", {"type": "test.message"}) with pytest.raises(ChannelFull): await channel_layer.send("test-channel-1", {"type": "test.message"}) @pytest.mark.asyncio async def test_send_specific_capacity(channel_layer): """ Makes sure we get ChannelFull when we hit the send capacity on a specific channel """ custom_channel_layer = RedisChannelLayer(hosts=TEST_HOSTS, capacity=3, channel_capacity={"one": 1}) await custom_channel_layer.send("one", {"type": "test.message"}) with pytest.raises(ChannelFull): await custom_channel_layer.send("one", {"type": "test.message"}) await custom_channel_layer.flush() @pytest.mark.asyncio async def test_process_local_send_receive(channel_layer): """ Makes sure we can send a message to a process-local channel then receive it. """ channel_name = await channel_layer.new_channel() await channel_layer.send( channel_name, { "type": "test.message", "text": "Local only please", }, ) message = await channel_layer.receive(channel_name) assert message["type"] == "test.message" assert message["text"] == "Local only please" @pytest.mark.asyncio async def test_multi_send_receive(channel_layer): """ Tests overlapping sends and receives, and ordering. """ channel_layer = RedisChannelLayer(hosts=TEST_HOSTS) await channel_layer.send("test-channel-3", {"type": "message.1"}) await channel_layer.send("test-channel-3", {"type": "message.2"}) await channel_layer.send("test-channel-3", {"type": "message.3"}) assert (await channel_layer.receive("test-channel-3"))["type"] == "message.1" assert (await channel_layer.receive("test-channel-3"))["type"] == "message.2" assert (await channel_layer.receive("test-channel-3"))["type"] == "message.3" @pytest.mark.asyncio async def test_reject_bad_channel(channel_layer): """ Makes sure sending/receiving on an invalic channel name fails. """ with pytest.raises(TypeError): await channel_layer.send("=+135!", {"type": "foom"}) with pytest.raises(TypeError): await channel_layer.receive("=+135!") @pytest.mark.asyncio async def test_reject_bad_client_prefix(channel_layer): """ Makes sure receiving on a non-prefixed local channel is not allowed. """ with pytest.raises(AssertionError): await channel_layer.receive("not-client-prefix!local_part") @pytest.mark.asyncio async def test_groups_basic(channel_layer): """ Tests basic group operation. """ channel_layer = RedisChannelLayer(hosts=TEST_HOSTS) channel_name1 = await channel_layer.new_channel(prefix="test-gr-chan-1") channel_name2 = await channel_layer.new_channel(prefix="test-gr-chan-2") channel_name3 = await channel_layer.new_channel(prefix="test-gr-chan-3") await channel_layer.group_add("test-group", channel_name1) await channel_layer.group_add("test-group", channel_name2) await channel_layer.group_add("test-group", channel_name3) await channel_layer.group_discard("test-group", channel_name2) await channel_layer.group_send("test-group", {"type": "message.1"}) # Make sure we get the message on the two channels that were in async with async_timeout.timeout(1): assert (await channel_layer.receive(channel_name1))["type"] == "message.1" assert (await channel_layer.receive(channel_name3))["type"] == "message.1" # Make sure the removed channel did not get the message with pytest.raises(asyncio.TimeoutError): async with async_timeout.timeout(1): await channel_layer.receive(channel_name2) @pytest.mark.asyncio async def test_groups_channel_full(channel_layer): """ Tests that group_send ignores ChannelFull """ channel_layer = RedisChannelLayer(hosts=TEST_HOSTS) await channel_layer.group_add("test-group", "test-gr-chan-1") await channel_layer.group_send("test-group", {"type": "message.1"}) await channel_layer.group_send("test-group", {"type": "message.1"}) await channel_layer.group_send("test-group", {"type": "message.1"}) await channel_layer.group_send("test-group", {"type": "message.1"}) await channel_layer.group_send("test-group", {"type": "message.1"}) @pytest.mark.asyncio async def test_groups_multiple_hosts(channel_layer_multiple_hosts): """ Tests advanced group operation with multiple hosts. """ channel_layer = RedisChannelLayer(hosts=MULTIPLE_TEST_HOSTS, capacity=100) channel_name1 = await channel_layer.new_channel(prefix="channel1") channel_name2 = await channel_layer.new_channel(prefix="channel2") channel_name3 = await channel_layer.new_channel(prefix="channel3") await channel_layer.group_add("test-group", channel_name1) await channel_layer.group_add("test-group", channel_name2) await channel_layer.group_add("test-group", channel_name3) await channel_layer.group_discard("test-group", channel_name2) await channel_layer.group_send("test-group", {"type": "message.1"}) await channel_layer.group_send("test-group", {"type": "message.1"}) # Make sure we get the message on the two channels that were in async with async_timeout.timeout(1): assert (await channel_layer.receive(channel_name1))["type"] == "message.1" assert (await channel_layer.receive(channel_name3))["type"] == "message.1" with pytest.raises(asyncio.TimeoutError): async with async_timeout.timeout(1): await channel_layer.receive(channel_name2) @pytest.mark.parametrize("num_channels,timeout", [ (1, 1), # Edge cases - make sure we can send to a single channel (10, 1), (100, 10), ]) @pytest.mark.asyncio async def test_groups_multiple_hosts_performance( channel_layer_multiple_hosts, num_channels, timeout ): """ Tests advanced group operation: can send efficiently to multiple channels with multiple hosts within a certain timeout """ channel_layer = RedisChannelLayer(hosts=MULTIPLE_TEST_HOSTS, capacity=100) channels = [] for i in range(0, num_channels): channel = await channel_layer.new_channel(prefix="channel%s" % i) await channel_layer.group_add("test-group", channel) channels.append(channel) async with async_timeout.timeout(timeout): await channel_layer.group_send("test-group", {"type": "message.1"}) # Make sure we get the message all the channels async with async_timeout.timeout(timeout): for channel in channels: assert (await channel_layer.receive(channel))["type"] == "message.1"
5e0c3d672b3b5efb05aa6b2d2e55bd0e758f27e2
7c3ccfe8fdcbe05d04444da071b9b3469b11f351
/.github/scripts/filter_test_configs.py
96dff128572d4ee665a4731138827d928f152d84
[ "BSD-2-Clause", "LicenseRef-scancode-secret-labs-2011", "BSD-3-Clause", "LicenseRef-scancode-generic-cla", "BSL-1.0", "Apache-2.0" ]
permissive
nihui/pytorch
ad4df723672300d5bd4290d6bc4e2e66a5ff2f0f
999bae0f54108ffc5b7cf2524a02a83901554b16
refs/heads/master
2023-07-07T06:35:37.886490
2023-05-30T05:07:59
2023-05-30T05:07:59
177,545,801
3
2
NOASSERTION
2019-03-25T08:33:23
2019-03-25T08:33:23
null
UTF-8
Python
false
false
14,809
py
#!/usr/bin/env python3 import json import os import re import sys import warnings from typing import Any, Callable, Dict, List, Optional, Set from urllib.request import Request, urlopen import yaml PREFIX = "test-config/" # Same as shard names VALID_TEST_CONFIG_LABELS = { f"{PREFIX}{label}" for label in { "backwards_compat", "crossref", "default", "deploy", "distributed", "docs_tests", "dynamo", "force_on_cpu", "functorch", "inductor", "inductor_distributed", "inductor_huggingface", "inductor_timm", "inductor_torchbench", "jit_legacy", "multigpu", "nogpu_AVX512", "nogpu_NO_AVX2", "slow", "tsan", "xla", } } def is_cuda_or_rocm_job(job_name: Optional[str]) -> bool: if not job_name: return False return "cuda" in job_name or "rocm" in job_name # Supported modes when running periodically. Only applying the mode when # its lambda condition returns true SUPPORTED_PERIODICAL_MODES: Dict[str, Callable[[Optional[str]], bool]] = { # Memory leak check is only needed for CUDA and ROCm jobs which utilize GPU memory "mem_leak_check": is_cuda_or_rocm_job, "rerun_disabled_tests": lambda job_name: True, } # The link to the published list of disabled jobs DISABLED_JOBS_URL = "https://ossci-metrics.s3.amazonaws.com/disabled-jobs.json" # Some constants used to remove disabled jobs JOB_NAME_SEP = "/" BUILD_JOB_NAME = "build" TEST_JOB_NAME = "test" BUILD_AND_TEST_JOB_NAME = "build-and-test" JOB_NAME_CFG_REGEX = re.compile(r"(?P<job>[\w-]+)\s+\((?P<cfg>[\w-]+)\)") EXCLUDED_BRANCHES = ["nightly"] def parse_args() -> Any: from argparse import ArgumentParser parser = ArgumentParser( "Filter all test configurations and keep only requested ones" ) parser.add_argument( "--test-matrix", type=str, required=True, help="the original test matrix" ) parser.add_argument( "--workflow", type=str, help="the name of the current workflow, i.e. pull" ) parser.add_argument( "--job-name", type=str, help="the name of the current job, i.e. linux-focal-py3.8-gcc7 / build", ) parser.add_argument("--pr-number", type=str, help="the pull request number") parser.add_argument("--tag", type=str, help="the associated tag if it exists") parser.add_argument( "--event-name", type=str, help="name of the event that triggered the job (pull, schedule, etc)", ) parser.add_argument( "--schedule", type=str, help="cron schedule that triggered the job", ) parser.add_argument( "--branch", type=str, default="main", help="the branch name", ) return parser.parse_args() def get_labels(pr_number: int) -> Set[str]: """ Dynamical get the latest list of labels from the pull request """ # From https://docs.github.com/en/actions/learn-github-actions/environment-variables pytorch_repo = os.environ.get("GITHUB_REPOSITORY", "pytorch/pytorch") pytorch_github_api = f"https://api.github.com/repos/{pytorch_repo}" github_token = os.environ["GITHUB_TOKEN"] headers = { "Accept": "application/vnd.github.v3+json", "Authorization": f"token {github_token}", } json_response = download_json( url=f"{pytorch_github_api}/issues/{pr_number}/labels", headers=headers, ) if not json_response: warnings.warn(f"Failed to get the labels for #{pr_number}") return set() return {label.get("name") for label in json_response if label.get("name")} def filter(test_matrix: Dict[str, List[Any]], labels: Set[str]) -> Dict[str, List[Any]]: """ Select the list of test config to run from the test matrix. The logic works as follows: If the PR has one or more labels as specified in the VALID_TEST_CONFIG_LABELS set, only these test configs will be selected. This also works with ciflow labels, for example, if a PR has both ciflow/trunk and test-config/functorch, only trunk functorch builds and tests will be run If the PR has none of the test-config label, all tests are run as usual. """ filtered_test_matrix: Dict[str, List[Any]] = {"include": []} for entry in test_matrix.get("include", []): config_name = entry.get("config", "") if not config_name: continue label = f"{PREFIX}{config_name.strip()}" if label in labels: print( f"Select {config_name} because label {label} is presented in the pull request by the time the test starts" ) filtered_test_matrix["include"].append(entry) valid_test_config_labels = labels.intersection(VALID_TEST_CONFIG_LABELS) if not filtered_test_matrix["include"] and not valid_test_config_labels: # Found no valid label and the filtered test matrix is empty, return the same # test matrix as before so that all tests can be run normally return test_matrix else: # When the filter test matrix contain matches or if a valid test config label # is found in the PR, return the filtered test matrix return filtered_test_matrix def set_periodic_modes( test_matrix: Dict[str, List[Any]], job_name: Optional[str] ) -> Dict[str, List[Any]]: """ Apply all periodic modes when running under a schedule """ scheduled_test_matrix: Dict[str, List[Any]] = { "include": [], } for config in test_matrix.get("include", []): for mode, cond in SUPPORTED_PERIODICAL_MODES.items(): if not cond(job_name): continue cfg = config.copy() cfg[mode] = mode scheduled_test_matrix["include"].append(cfg) return scheduled_test_matrix def remove_disabled_jobs( workflow: str, job_name: str, test_matrix: Dict[str, List[Any]] ) -> Dict[str, List[Any]]: """ Check the list of disabled jobs, remove the current job and all its dependents if it exists in the list. The list of disabled jobs is as follows: { "WORKFLOW / PLATFORM / JOB (CONFIG)": [ AUTHOR, ISSUE_NUMBER, ISSUE_URL, WORKFLOW, PLATFORM, JOB (CONFIG), ], "pull / linux-bionic-py3.8-clang9 / test (dynamo)": [ "pytorchbot", "94861", "https://github.com/pytorch/pytorch/issues/94861", "pull", "linux-bionic-py3.8-clang9", "test (dynamo)", ], } """ try: # The job name from github is in the PLATFORM / JOB (CONFIG) format, so breaking # it into its two components first current_platform, _ = [n.strip() for n in job_name.split(JOB_NAME_SEP, 1) if n] except ValueError as error: warnings.warn(f"Invalid job name {job_name}, returning") return test_matrix # The result will be stored here filtered_test_matrix: Dict[str, List[Any]] = {"include": []} for _, record in download_json(url=DISABLED_JOBS_URL, headers={}).items(): ( author, _, disabled_url, disabled_workflow, disabled_platform, disabled_job_cfg, ) = record if disabled_workflow != workflow: # The current workflow is not disabled by this record continue cleanup_regex = rf"(-{BUILD_JOB_NAME}|-{TEST_JOB_NAME})$" # There is an exception here for binary build workflows in which the platform # names have the build and test suffix. For example, we have a build job called # manywheel-py3-cuda11_8-build / build and its subsequent test job called # manywheel-py3-cuda11_8-test / test. So they are linked, but their suffixes # are different disabled_platform_no_suffix = re.sub(cleanup_regex, "", disabled_platform) current_platform_no_suffix = re.sub(cleanup_regex, "", current_platform) if ( disabled_platform != current_platform and disabled_platform_no_suffix != current_platform_no_suffix ): # The current platform is not disabled by this record continue # The logic after this is fairly complicated: # # - If the disabled record doesn't have the optional job (config) name, # i.e. pull / linux-bionic-py3.8-clang9, all build and test jobs will # be skipped # # - If the disabled record has the job name and it's a build job, i.e. # pull / linux-bionic-py3.8-clang9 / build, all build and test jobs # will be skipped, because the latter requires the former # # - If the disabled record has the job name and it's a test job without # the config part, i.e. pull / linux-bionic-py3.8-clang9 / test, all # test jobs will be skipped. TODO: At the moment, the script uses the # short-circuiting logic to skip the build job automatically when there # is no test job assuming that it would be a waste of effort building # for nothing. This might not be the desirable behavior, and could be # fixed later if needed # # - If the disabled record has the job (config) name, only that test config # will be skipped, i.e. pull / linux-bionic-py3.8-clang9 / test (dynamo) if not disabled_job_cfg: print( f"Issue {disabled_url} created by {author} has disabled all CI jobs for {workflow} / {job_name}" ) return filtered_test_matrix if disabled_job_cfg == BUILD_JOB_NAME: print( f"Issue {disabled_url} created by {author} has disabled the build job for {workflow} / {job_name}" ) return filtered_test_matrix if disabled_job_cfg in (TEST_JOB_NAME, BUILD_AND_TEST_JOB_NAME): print( f"Issue {disabled_url} created by {author} has disabled all the test jobs for {workflow} / {job_name}" ) return filtered_test_matrix m = JOB_NAME_CFG_REGEX.match(disabled_job_cfg) if m: disabled_job = m.group("job") # Make sure that the job name is a valid test job name first before checking the config if disabled_job in (TEST_JOB_NAME, BUILD_AND_TEST_JOB_NAME): disabled_cfg = m.group("cfg") # Remove the disabled config from the test matrix filtered_test_matrix["include"] = [ r for r in test_matrix["include"] if r.get("config", "") != disabled_cfg ] return filtered_test_matrix warnings.warn( f"Found a matching disabled issue {disabled_url} for {workflow} / {job_name}, " f"but the name {disabled_job_cfg} is invalid" ) # Found no matching disabled issue, return the same input test matrix return test_matrix def download_json(url: str, headers: Dict[str, str], num_retries: int = 3) -> Any: for _ in range(num_retries): try: req = Request(url=url, headers=headers) content = urlopen(req, timeout=5).read().decode("utf-8") return json.loads(content) except Exception as e: warnings.warn(f"Could not download {url}: {e}") warnings.warn(f"All {num_retries} retries exhausted, downloading {url} failed") return {} def set_output(name: str, val: Any) -> None: if os.getenv("GITHUB_OUTPUT"): with open(str(os.getenv("GITHUB_OUTPUT")), "a") as env: print(f"{name}={val}", file=env) else: print(f"::set-output name={name}::{val}") def main() -> None: args = parse_args() # Load the original test matrix set by the workflow. Its format, however, # doesn't follow the strict JSON format, so we load it using yaml here for # its more relaxed syntax test_matrix = yaml.safe_load(args.test_matrix) if test_matrix is None: warnings.warn(f"Invalid test matrix input '{args.test_matrix}', exiting") # We handle invalid test matrix gracefully by marking it as empty set_output("is-test-matrix-empty", True) sys.exit(0) pr_number = args.pr_number tag = args.tag # If the tag matches, we can get the PR number from it, this is from ciflow # workflow dispatcher tag_regex = re.compile(r"^ciflow/\w+/(?P<pr_number>\d+)$") labels = set() if pr_number: # If a PR number is set, query all the labels from that PR labels = get_labels(int(pr_number)) # Then filter the test matrix and keep only the selected ones filtered_test_matrix = filter(test_matrix, labels) elif tag: m = tag_regex.match(tag) if m: pr_number = m.group("pr_number") # The PR number can also come from the tag in ciflow tag event labels = get_labels(int(pr_number)) # Filter the test matrix and keep only the selected ones filtered_test_matrix = filter(test_matrix, labels) else: # There is a tag but it isn't ciflow, so there is nothing left to do filtered_test_matrix = test_matrix else: # No PR number, no tag, we can just return the test matrix as it is filtered_test_matrix = test_matrix if args.event_name == "schedule" and args.schedule == "29 8 * * *": # we don't want to run the mem leak check or disabled tests on normal # periodically scheduled jobs, only the ones at this time filtered_test_matrix = set_periodic_modes(filtered_test_matrix, args.job_name) if args.workflow and args.job_name and args.branch not in EXCLUDED_BRANCHES: # If both workflow and job name are available, we will check if the current job # is disabled and remove it and all its dependants from the test matrix filtered_test_matrix = remove_disabled_jobs( args.workflow, args.job_name, filtered_test_matrix ) # Set the filtered test matrix as the output set_output("test-matrix", json.dumps(filtered_test_matrix)) filtered_test_matrix_len = len(filtered_test_matrix.get("include", [])) # and also put a flag if the test matrix is empty, so subsequent jobs can # quickly check it without the need to parse the JSON string set_output("is-test-matrix-empty", filtered_test_matrix_len == 0) set_output("keep-going", "keep-going" in labels) if __name__ == "__main__": main()
192513b2ebb9f2f9c07d84b4cdb0e2c0f10f8099
2db7597686f33a0d700f7082e15fa41f830a45f0
/Python/coding/longestPalindromicSubstring.py
5b5cc4e5f9239e189fda40d29fb79084b668ae13
[]
no_license
Leahxuliu/Data-Structure-And-Algorithm
04e0fc80cd3bb742348fd521a62bc2126879a70e
56047a5058c6a20b356ab20e52eacb425ad45762
refs/heads/master
2021-07-12T23:54:17.785533
2021-05-17T02:04:41
2021-05-17T02:04:41
246,514,421
2
0
null
null
null
null
UTF-8
Python
false
false
862
py
''' 5. Longest Palindromic Substring 注意题目的return是什么 ''' def longestPalindrome(self, s: str) -> str: if s == '': return '' n = len(s) dp = [[False] * n for _ in range(n)] max_len = 1 start = 0 for i in range(n - 1, -1, -1): for j in range(i, n): if i == j: dp[i][j] = True elif j - i == 1: if s[i] == s[j]: dp[i][j] = True if max_len < 2: max_len = 2 start = i else: if s[i] == s[j] and dp[i + 1][j - 1] == True: dp[i][j] = True if max_len < j - i + 1: max_len = j - i + 1 start = i return s[start:start + max_len]
6aa5472a81eb982be6841fecca028c9450d0bc71
64653a5a2a64cd0a18643ea3c537dd21c3122167
/ohmyeye/urls.py
5b9c0c4129965443f6f886b43d7f8ad8bd26d616
[]
no_license
baidoosik/ohmyeye
52662341701c3905efe5c7cf329fbe6e400022de
1619f981f9f4e4e84b4577df28e769e9340ba06a
refs/heads/master
2021-04-27T02:47:45.497702
2018-02-24T22:25:37
2018-02-24T22:25:37
122,702,407
1
0
null
null
null
null
UTF-8
Python
false
false
948
py
"""ohmyeye URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^accounts/', include('allauth.urls')), url(r'^admin/', admin.site.urls), url(r'^', include('home.urls', namespace='home')), url(r'^accounts/', include('accounts.urls', namespace='accounts')) ]
d4df58f2c24bda82a67205c1ec1ae96f54522fc9
1817aca734cda258cbbfd9e13fbf040d76824621
/aliyun-python-sdk-domain/aliyunsdkdomain/__init__.py
03e753e73534f3d3d1530c2b89ec0fb5458f2aaa
[ "Apache-2.0" ]
permissive
sdk-team/aliyun-openapi-python-sdk
4bd770718e70e31f19e1e322727c27ba74d9fb80
996cb07bfcf010fe3ab65daa73d26df2f3b6e97f
refs/heads/master
2022-08-04T13:11:56.729215
2022-07-25T10:01:10
2022-07-25T10:01:10
183,356,741
0
0
null
2019-04-25T04:33:24
2019-04-25T04:33:24
null
UTF-8
Python
false
false
22
py
__version__ = "3.13.0"
0d0ea308d017f4b52fbf4a8bf89f384d26247131
4e96f383d4703ad8ee58869ed91a0c8432c8a051
/Cura/Cura/tests/TestBuildVolume.py
6ccb3d0fb7e1ed0702e8179aad7653553b069d72
[ "LGPL-3.0-only", "GPL-3.0-only" ]
permissive
flight7788/3d-printing-with-moveo-1
b2dba26010c4fa31815bc1d2d0966161a8600081
7fcb9c6b5da9245d54ac917de8c2a7f5148e42b0
refs/heads/Feature_Marlin_with_AlanBoy
2022-08-30T18:36:44.785058
2020-05-30T07:52:58
2020-05-30T07:52:58
212,583,912
0
0
MIT
2020-05-16T07:39:47
2019-10-03T13:13:01
C
UTF-8
Python
false
false
18,454
py
from unittest.mock import MagicMock, patch from UM.Math.AxisAlignedBox import AxisAlignedBox import pytest from UM.Math.Polygon import Polygon from UM.Math.Vector import Vector from cura.BuildVolume import BuildVolume, PRIME_CLEARANCE import numpy @pytest.fixture def build_volume() -> BuildVolume: mocked_application = MagicMock() mocked_platform = MagicMock(name="platform") with patch("cura.BuildVolume.Platform", mocked_platform): return BuildVolume(mocked_application) def test_buildVolumeSetSizes(build_volume): build_volume.setWidth(10) assert build_volume.getDiagonalSize() == 10 build_volume.setWidth(0) build_volume.setHeight(100) assert build_volume.getDiagonalSize() == 100 build_volume.setHeight(0) build_volume.setDepth(200) assert build_volume.getDiagonalSize() == 200 def test_buildMesh(build_volume): mesh = build_volume._buildMesh(0, 100, 0, 100, 0, 100, 1) result_vertices = numpy.array([[0., 0., 0.], [100., 0., 0.], [0., 0., 0.], [0., 100., 0.], [0., 100., 0.], [100., 100., 0.], [100., 0., 0.], [100., 100., 0.], [0., 0., 100.], [100., 0., 100.], [0., 0., 100.], [0., 100., 100.], [0., 100., 100.], [100., 100., 100.], [100., 0., 100.], [100., 100., 100.], [0., 0., 0.], [0., 0., 100.], [100., 0., 0.], [100., 0., 100.], [0., 100., 0.], [0., 100., 100.], [100., 100., 0.], [100., 100., 100.]], dtype=numpy.float32) assert numpy.array_equal(result_vertices, mesh.getVertices()) def test_buildGridMesh(build_volume): mesh = build_volume._buildGridMesh(0, 100, 0, 100, 0, 100, 1) result_vertices = numpy.array([[0., -1., 0.], [100., -1., 100.], [100., -1., 0.], [0., -1., 0.], [0., -1., 100.], [100., -1., 100.]]) assert numpy.array_equal(result_vertices, mesh.getVertices()) def test_clamp(build_volume): assert build_volume._clamp(0, 0, 200) == 0 assert build_volume._clamp(0, -200, 200) == 0 assert build_volume._clamp(300, -200, 200) == 200 class TestCalculateBedAdhesionSize: setting_property_dict = {"adhesion_type": {"value": "brim"}, "skirt_brim_line_width": {"value": 0}, "initial_layer_line_width_factor": {"value": 0}, "brim_line_count": {"value": 0}, "machine_width": {"value": 200}, "machine_depth": {"value": 200}, "skirt_line_count": {"value": 0}, "skirt_gap": {"value": 0}, "raft_margin": {"value": 0} } def getPropertySideEffect(*args, **kwargs): properties = TestCalculateBedAdhesionSize.setting_property_dict.get(args[1]) if properties: return properties.get(args[2]) def createAndSetGlobalStack(self, build_volume): mocked_stack = MagicMock() mocked_stack.getProperty = MagicMock(side_effect=self.getPropertySideEffect) build_volume._global_container_stack = mocked_stack def test_noGlobalStack(self, build_volume: BuildVolume): assert build_volume._calculateBedAdhesionSize([]) is None @pytest.mark.parametrize("setting_dict, result", [ ({}, 0), ({"adhesion_type": {"value": "skirt"}}, 0), ({"adhesion_type": {"value": "raft"}}, 0), ({"adhesion_type": {"value": "none"}}, 0), ({"adhesion_type": {"value": "skirt"}, "skirt_line_count": {"value": 2}, "initial_layer_line_width_factor": {"value": 1}, "skirt_brim_line_width": {"value": 2}}, 0.02), # Even though it's marked as skirt, it should behave as a brim as the prime tower has a brim (skirt line count is still at 0!) ({"adhesion_type": {"value": "skirt"}, "prime_tower_brim_enable": {"value": True}, "skirt_brim_line_width": {"value": 2}, "initial_layer_line_width_factor": {"value": 3}}, -0.06), ({"brim_line_count": {"value": 1}, "skirt_brim_line_width": {"value": 2}, "initial_layer_line_width_factor": {"value": 3}}, 0), ({"brim_line_count": {"value": 2}, "skirt_brim_line_width": {"value": 2}, "initial_layer_line_width_factor": {"value": 3}}, 0.06), ({"brim_line_count": {"value": 9000000}, "skirt_brim_line_width": {"value": 90000}, "initial_layer_line_width_factor": {"value": 9000}}, 100), # Clamped at half the max size of buildplate ]) def test_singleExtruder(self, build_volume: BuildVolume, setting_dict, result): self.createAndSetGlobalStack(build_volume) patched_dictionary = self.setting_property_dict.copy() patched_dictionary.update(setting_dict) with patch.dict(self.setting_property_dict, patched_dictionary): assert build_volume._calculateBedAdhesionSize([]) == result def test_unknownBedAdhesion(self, build_volume: BuildVolume): self.createAndSetGlobalStack(build_volume) patched_dictionary = self.setting_property_dict.copy() patched_dictionary.update({"adhesion_type": {"value": "OMGZOMGBBQ"}}) with patch.dict(self.setting_property_dict, patched_dictionary): with pytest.raises(Exception): build_volume._calculateBedAdhesionSize([]) class TestComputeDisallowedAreasStatic: setting_property_dict = {"machine_disallowed_areas": {"value": [[[-200, 112.5], [ -82, 112.5], [ -84, 102.5], [-115, 102.5]]]}, "machine_width": {"value": 200}, "machine_depth": {"value": 200}, } def getPropertySideEffect(*args, **kwargs): properties = TestComputeDisallowedAreasStatic.setting_property_dict.get(args[1]) if properties: return properties.get(args[2]) def test_computeDisallowedAreasStaticNoExtruder(self, build_volume: BuildVolume): mocked_stack = MagicMock() mocked_stack.getProperty = MagicMock(side_effect=self.getPropertySideEffect) build_volume._global_container_stack = mocked_stack assert build_volume._computeDisallowedAreasStatic(0, []) == {} def test_computeDisalowedAreasStaticSingleExtruder(self, build_volume: BuildVolume): mocked_stack = MagicMock() mocked_stack.getProperty = MagicMock(side_effect=self.getPropertySideEffect) mocked_extruder = MagicMock() mocked_extruder.getProperty = MagicMock(side_effect=self.getPropertySideEffect) mocked_extruder.getId = MagicMock(return_value = "zomg") build_volume._global_container_stack = mocked_stack with patch("cura.Settings.ExtruderManager.ExtruderManager.getInstance"): result = build_volume._computeDisallowedAreasStatic(0, [mocked_extruder]) assert result == {"zomg": [Polygon([[-84.0, 102.5], [-115.0, 102.5], [-200.0, 112.5], [-82.0, 112.5]])]} def test_computeDisalowedAreasMutliExtruder(self, build_volume): mocked_stack = MagicMock() mocked_stack.getProperty = MagicMock(side_effect=self.getPropertySideEffect) mocked_extruder = MagicMock() mocked_extruder.getProperty = MagicMock(side_effect=self.getPropertySideEffect) mocked_extruder.getId = MagicMock(return_value="zomg") extruder_manager = MagicMock() extruder_manager.getActiveExtruderStacks = MagicMock(return_value = [mocked_stack]) build_volume._global_container_stack = mocked_stack with patch("cura.Settings.ExtruderManager.ExtruderManager.getInstance", MagicMock(return_value = extruder_manager)): result = build_volume._computeDisallowedAreasStatic(0, [mocked_extruder]) assert result == {"zomg": [Polygon([[-84.0, 102.5], [-115.0, 102.5], [-200.0, 112.5], [-82.0, 112.5]])]} class TestUpdateRaftThickness: setting_property_dict = {"raft_base_thickness": {"value": 1}, "raft_interface_thickness": {"value": 1}, "raft_surface_layers": {"value": 1}, "raft_surface_thickness": {"value": 1}, "raft_airgap": {"value": 1}, "layer_0_z_overlap": {"value": 1}, "adhesion_type": {"value": "raft"}} def getPropertySideEffect(*args, **kwargs): properties = TestUpdateRaftThickness.setting_property_dict.get(args[1]) if properties: return properties.get(args[2]) def createMockedStack(self): mocked_global_stack = MagicMock(name="mocked_global_stack") mocked_global_stack.getProperty = MagicMock(side_effect=self.getPropertySideEffect) extruder_stack = MagicMock() mocked_global_stack.extruders = {"0": extruder_stack} return mocked_global_stack def test_simple(self, build_volume: BuildVolume): build_volume.raftThicknessChanged = MagicMock() mocked_global_stack = self.createMockedStack() build_volume._global_container_stack = mocked_global_stack assert build_volume.getRaftThickness() == 0 build_volume._updateRaftThickness() assert build_volume.getRaftThickness() == 3 assert build_volume.raftThicknessChanged.emit.call_count == 1 def test_adhesionIsNotRaft(self, build_volume: BuildVolume): patched_dictionary = self.setting_property_dict.copy() patched_dictionary["adhesion_type"] = {"value": "not_raft"} mocked_global_stack = self.createMockedStack() build_volume._global_container_stack = mocked_global_stack assert build_volume.getRaftThickness() == 0 with patch.dict(self.setting_property_dict, patched_dictionary): build_volume._updateRaftThickness() assert build_volume.getRaftThickness() == 0 def test_noGlobalStack(self, build_volume: BuildVolume): build_volume.raftThicknessChanged = MagicMock() assert build_volume.getRaftThickness() == 0 build_volume._updateRaftThickness() assert build_volume.getRaftThickness() == 0 assert build_volume.raftThicknessChanged.emit.call_count == 0 class TestComputeDisallowedAreasPrimeBlob: setting_property_dict = {"machine_width": {"value": 50}, "machine_depth": {"value": 100}, "prime_blob_enable": {"value": True}, "extruder_prime_pos_x": {"value": 25}, "extruder_prime_pos_y": {"value": 50}, "machine_center_is_zero": {"value": True}, } def getPropertySideEffect(*args, **kwargs): properties = TestComputeDisallowedAreasPrimeBlob.setting_property_dict.get(args[1]) if properties: return properties.get(args[2]) def test_noGlobalContainer(self, build_volume: BuildVolume): # No global container and no extruders, so we expect no blob areas assert build_volume._computeDisallowedAreasPrimeBlob(12, []) == {} def test_noExtruders(self, build_volume: BuildVolume): mocked_stack = MagicMock() mocked_stack.getProperty = MagicMock(side_effect=self.getPropertySideEffect) build_volume._global_container_stack = mocked_stack # No extruders, so still expect that we get no area assert build_volume._computeDisallowedAreasPrimeBlob(12, []) == {} def test_singleExtruder(self, build_volume: BuildVolume): mocked_global_stack = MagicMock(name = "mocked_global_stack") mocked_global_stack.getProperty = MagicMock(side_effect=self.getPropertySideEffect) mocked_extruder_stack = MagicMock(name = "mocked_extruder_stack") mocked_extruder_stack.getId = MagicMock(return_value = "0") mocked_extruder_stack.getProperty = MagicMock(side_effect=self.getPropertySideEffect) build_volume._global_container_stack = mocked_global_stack # Create a polygon that should be the result resulting_polygon = Polygon.approximatedCircle(PRIME_CLEARANCE) # Since we want a blob of size 12; resulting_polygon = resulting_polygon.getMinkowskiHull(Polygon.approximatedCircle(12)) # In the The translation result is 25, -50 (due to the settings used) resulting_polygon = resulting_polygon.translate(25, -50) assert build_volume._computeDisallowedAreasPrimeBlob(12, [mocked_extruder_stack]) == {"0": [resulting_polygon]} class TestCalculateExtraZClearance: setting_property_dict = {"retraction_hop": {"value": 12}, "retraction_hop_enabled": {"value": True}} def getPropertySideEffect(*args, **kwargs): properties = TestCalculateExtraZClearance.setting_property_dict.get(args[1]) if properties: return properties.get(args[2]) def test_noContainerStack(self, build_volume: BuildVolume): assert build_volume._calculateExtraZClearance([]) is 0 def test_withRetractionHop(self, build_volume: BuildVolume): mocked_global_stack = MagicMock(name="mocked_global_stack") mocked_extruder = MagicMock() mocked_extruder.getProperty = MagicMock(side_effect=self.getPropertySideEffect) build_volume._global_container_stack = mocked_global_stack # It should be 12 because we have the hop enabled and the hop distance is set to 12 assert build_volume._calculateExtraZClearance([mocked_extruder]) == 12 def test_withoutRetractionHop(self, build_volume: BuildVolume): mocked_global_stack = MagicMock(name="mocked_global_stack") mocked_extruder = MagicMock() mocked_extruder.getProperty = MagicMock(side_effect=self.getPropertySideEffect) build_volume._global_container_stack = mocked_global_stack patched_dictionary = self.setting_property_dict.copy() patched_dictionary["retraction_hop_enabled"] = {"value": False} with patch.dict(self.setting_property_dict, patched_dictionary): # It should be 12 because we have the hop enabled and the hop distance is set to 12 assert build_volume._calculateExtraZClearance([mocked_extruder]) == 0 class TestRebuild: def test_zeroWidthHeightDepth(self, build_volume: BuildVolume): build_volume.rebuild() assert build_volume.getMeshData() is None def test_engineIsNotRead(self, build_volume: BuildVolume): build_volume.setWidth(10) build_volume.setHeight(10) build_volume.setDepth(10) build_volume.rebuild() assert build_volume.getMeshData() is None def test_noGlobalStack(self, build_volume: BuildVolume): build_volume.setWidth(10) build_volume.setHeight(10) build_volume.setDepth(10) # Fake the the "engine is created callback" build_volume._onEngineCreated() build_volume.rebuild() assert build_volume.getMeshData() is None def test_updateBoundingBox(self, build_volume: BuildVolume): build_volume.setWidth(10) build_volume.setHeight(10) build_volume.setDepth(10) mocked_global_stack = MagicMock() build_volume._global_container_stack = mocked_global_stack build_volume.getEdgeDisallowedSize = MagicMock(return_value = 0) build_volume.updateNodeBoundaryCheck = MagicMock() # Fake the the "engine is created callback" build_volume._onEngineCreated() build_volume.rebuild() bounding_box = build_volume.getBoundingBox() assert bounding_box.minimum == Vector(-5.0, -1.0, -5.0) assert bounding_box.maximum == Vector(5.0, 10.0, 5.0) class TestUpdateMachineSizeProperties: setting_property_dict = {"machine_width": {"value": 50}, "machine_depth": {"value": 100}, "machine_height": {"value": 200}, "machine_shape": {"value": "DERP!"}} def getPropertySideEffect(*args, **kwargs): properties = TestUpdateMachineSizeProperties.setting_property_dict.get(args[1]) if properties: return properties.get(args[2]) def test_noGlobalStack(self, build_volume: BuildVolume): build_volume._updateMachineSizeProperties() assert build_volume._width == 0 assert build_volume._height == 0 assert build_volume._depth == 0 assert build_volume._shape == "" def test_happy(self, build_volume: BuildVolume): mocked_global_stack = MagicMock(name="mocked_global_stack") mocked_global_stack.getProperty = MagicMock(side_effect=self.getPropertySideEffect) build_volume._global_container_stack = mocked_global_stack build_volume._updateMachineSizeProperties() assert build_volume._width == 50 assert build_volume._height == 200 assert build_volume._depth == 100 assert build_volume._shape == "DERP!" class TestGetEdgeDisallowedSize: setting_property_dict = {} bed_adhesion_size = 1 @pytest.fixture() def build_volume(self, build_volume): build_volume._calculateBedAdhesionSize = MagicMock(return_value = 1) return build_volume def getPropertySideEffect(*args, **kwargs): properties = TestGetEdgeDisallowedSize.setting_property_dict.get(args[1]) if properties: return properties.get(args[2]) def createMockedStack(self): mocked_global_stack = MagicMock(name="mocked_global_stack") mocked_global_stack.getProperty = MagicMock(side_effect=self.getPropertySideEffect) return mocked_global_stack def test_noGlobalContainer(self, build_volume: BuildVolume): assert build_volume.getEdgeDisallowedSize() == 0 def test_unknownAdhesion(self, build_volume: BuildVolume): build_volume._global_container_stack = self.createMockedStack() with patch("cura.Settings.ExtruderManager.ExtruderManager.getInstance"): #with pytest.raises(Exception): # Since we don't have any adhesion set, this should break. build_volume.getEdgeDisallowedSize() def test_oneAtATime(self, build_volume: BuildVolume): build_volume._global_container_stack = self.createMockedStack() with patch("cura.Settings.ExtruderManager.ExtruderManager.getInstance"): with patch.dict(self.setting_property_dict, {"print_sequence": {"value": "one_at_a_time"}}): assert build_volume.getEdgeDisallowedSize() == 0.1
79926eb4ed7b1cb24b624dd9df42ddf2c75ac463
6188f8ef474da80c9e407e8040de877273f6ce20
/examples/docs_snippets/docs_snippets/concepts/assets/asset_input_managers_numpy.py
41c6a5aa55fde72067e0e687ff7d0816f51b530f
[ "Apache-2.0" ]
permissive
iKintosh/dagster
99f2a1211de1f3b52f8bcf895dafaf832b999de2
932a5ba35263deb7d223750f211c2ddfa71e6f48
refs/heads/master
2023-01-24T15:58:28.497042
2023-01-20T21:51:35
2023-01-20T21:51:35
276,410,978
1
0
Apache-2.0
2020-07-01T15:19:47
2020-07-01T15:13:56
null
UTF-8
Python
false
false
1,511
py
import os import pandas as pd from dagster import AssetIn, Definitions, IOManager, asset, io_manager from .asset_input_managers import ( load_numpy_array, load_pandas_dataframe, store_pandas_dataframe, ) # start_numpy_example class PandasAssetIOManager(IOManager): def handle_output(self, context, obj): file_path = self._get_path(context) store_pandas_dataframe(name=file_path, table=obj) def _get_path(self, context): return os.path.join( "storage", f"{context.asset_key.path[-1]}.csv", ) def load_input(self, context): file_path = self._get_path(context) return load_pandas_dataframe(name=file_path) @io_manager def pandas_asset_io_manager(): return PandasAssetIOManager() class NumpyAssetIOManager(PandasAssetIOManager): def load_input(self, context): file_path = self._get_path(context) return load_numpy_array(name=file_path) @io_manager def numpy_asset_io_manager(): return NumpyAssetIOManager() @asset(io_manager_key="pandas_manager") def upstream_asset(): return pd.DataFrame([1, 2, 3]) @asset( ins={"upstream": AssetIn(key_prefix="public", input_manager_key="numpy_manager")} ) def downstream_asset(upstream): return upstream.shape defs = Definitions( assets=[upstream_asset, downstream_asset], resources={ "pandas_manager": pandas_asset_io_manager, "numpy_manager": numpy_asset_io_manager, }, ) # end_numpy_example
f69d5a2c855b376f97d582465cd8c179d5452fa9
ad570312a736a84e96c5178bc1af91c6c0b898fb
/pyth/linkedListCoppy.py
4c1a565b380f1db25973401fb73c746e6d86da3f
[]
no_license
pritamSarkar123/Compitative20_21
ad813d189b7388ea2179bb96f64eaa88ba75db32
d5474b02487dc759c47e3da1047154533dc7b641
refs/heads/master
2023-01-14T12:04:51.756085
2020-11-26T09:31:02
2020-11-26T09:31:02
296,670,667
0
0
null
null
null
null
UTF-8
Python
false
false
1,551
py
#problem description #https://www.youtube.com/watch?v=xbpUHSKoALg&t=784s # algorithm: # #create intermediate nodes # p=head # q=NULL # while p!=NULL: # q=p # p=p->next # t=copy(q) # q->next=t # t->next=p # #connecting new linked list # p=head # q=NULL # while p!=NULL: # q=p # p=p->next->next # q->next->random=q->random->next # q=q->next # if p!=NULL: # q->next=p->next # else: # q->next=NULLa # #changing head pointer # head=head->next class Node: def __init__(self,value): self.value=value self.next=None self.random=None self.message="Original" class LinkedList: def __init__(self): self.head=Node(1) temp=self.head temp.next=Node(2) temp=temp.next temp.next=Node(3) temp=temp.next temp=self.head temp.random=temp.next.next #1->3 temp=temp.next temp.random=self.head #2->1 temp=temp.next temp.random=temp #3->3 def show_list(self): temp=self.head while temp: print(temp.value,temp.message,temp.random.value) temp=temp.next def copy_list(self): #create intermediate nodes p=self.head q=None while p: q=p p=p.next temp=Node(q.value);temp.message="Coppied" q.next=temp temp.next=p #connecting new linked list p=self.head q=None while p: q=p p=p.next.next q.next.random=q.random.next q=q.next if p: q.next=p.next else: q.next=None #changing head pointer self.head=self.head.next self.show_list() if __name__=="__main__": myList=LinkedList() myList.show_list() myList.copy_list()
68e264f1175e4500758f875b6b021e66b4625bc8
9f1b8a1ada57198e2a06d88ddcdc0eda0c683df7
/submission - Homework1/HW1 - Alex/index_nested_list.py
bbb999230c523e6e8d132b64459550cc015955c5
[]
no_license
sendurr/spring-grading
90dfdced6327ddfb5c311ae8f42ae1a582768b63
2cc280ee3e0fba02e95b6e9f45ad7e13bc7fad54
refs/heads/master
2020-04-15T17:42:10.781884
2016-08-29T20:38:17
2016-08-29T20:38:17
50,084,068
0
0
null
null
null
null
UTF-8
Python
false
false
445
py
# Alexis Thompson-Klemish # q = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h']] # print the letter a print q[0][0] # print the list ['d', 'e', 'f'] print q[1] # print the last element h print q[-1][-1] #print the d element print q[1][0] #explain why q[-1][-2] has the value g print "negative indexes count from the right, not the left so q[-1] produces the rightmost list and q[-1][-2] produces the second to last element in the last list"
cf4b67c14d7a1b9856437ecb6e313e98a2c15a74
30c23852ae41a7808e2a202280e973ff1a4bbe2b
/OP/op.py
9217ca651fa7b0366b9ae90cc341da5a83482f7b
[]
no_license
rohe/oidc-oob-federation
050ce05a1bd373795bc74c63287edeccbf1c3129
53517decc43f4d58aa7b825feb8c97704de8822f
refs/heads/master
2020-03-18T04:04:10.383031
2018-06-07T12:15:55
2018-06-07T12:15:55
134,267,953
0
0
null
null
null
null
UTF-8
Python
false
false
4,153
py
import logging import cherrypy from cryptojwt import as_bytes from oidcmsg.oauth2 import is_error_message from oidcmsg.oauth2 import AuthorizationRequest from oidcendpoint.sdb import AuthnEvent logger = logging.getLogger(__name__) class OpenIDProvider(object): def __init__(self, config, endpoint_context): self.config = config self.endpoint_context = endpoint_context def do_response(self, endpoint, req_args, **args): info = endpoint.do_response(request=req_args, **args) for key, value in info['http_headers']: cherrypy.response.headers[key] = value try: _response_placement = info['response_placement'] except KeyError: _response_placement = endpoint.response_placement if _response_placement == 'body': logger.info('Response: {}'.format(info['response'])) return as_bytes(info['response']) elif _response_placement == 'url': logger.info('Redirect to: {}'.format(info['response'])) raise cherrypy.HTTPRedirect(info['response']) @cherrypy.expose def service_endpoint(self, name, **kwargs): logger.info(kwargs) logger.info('At the {} endpoint'.format(name)) endpoint = self.endpoint_context.endpoint[name] try: authn = cherrypy.request.headers['Authorization'] except KeyError: pr_args = {} else: pr_args = {'auth': authn} if endpoint.request_placement == 'body': if cherrypy.request.process_request_body is True: _request = cherrypy.request.body.read() else: raise cherrypy.HTTPError(400, 'Missing HTTP body') if not _request: _request = kwargs req_args = endpoint.parse_request(_request, **pr_args) else: req_args = endpoint.parse_request(kwargs, **pr_args) logger.info('request: {}'.format(req_args)) if is_error_message(req_args): return as_bytes(req_args.to_json()) args = endpoint.process_request(req_args) return self.do_response(endpoint, req_args, **args) @cherrypy.expose def authn_verify(self, url_endpoint, **kwargs): """ Authentication verification :param authn_method: Which authn method that was used :param kwargs: response arguments :return: HTTP redirect """ authn_method = self.endpoint_context.endpoint_to_authn_method[url_endpoint] username = authn_method.verify(**kwargs) if not username: cherrypy.HTTPError(403, message='Authentication failed') auth_args = authn_method.unpack_token(kwargs['token']) request = AuthorizationRequest().from_urlencoded(auth_args['query']) # uid, salt, valid=3600, authn_info=None, time_stamp=0, authn_time=None, # valid_until=None authn_event = AuthnEvent(username, 'salt', authn_info=auth_args['authn_class_ref'], authn_time=auth_args['iat']) endpoint = self.endpoint_context.endpoint['authorization'] args = endpoint.post_authentication(request, user=username, authn_event=authn_event) return self.do_response(endpoint, request, **args) def _cp_dispatch(self, vpath): # Only get here if vpath != None ent = cherrypy.request.remote.ip logger.info('ent:{}, vpath: {}'.format(ent, vpath)) if len(vpath) == 2 and vpath[0] == 'verify': a = vpath.pop(0) b = vpath.pop(0) cherrypy.request.params['url_endpoint'] = '/'.join(['', a, b]) return self.authn_verify for name, instance in self.endpoint_context.endpoint.items(): if vpath == instance.vpath: cherrypy.request.params['name'] = name for n in range(len(vpath)): vpath.pop() return self.service_endpoint return self
1e5810523ea93878d26b6ef00317399d8e25aa25
1005a4290bca16dcf4c6b3415662e134044305bd
/python/Sources/gensource_Z2Jets_muhad_cfi.py
1d71fe0e0d4998bc6ab78e9176740d7f2eb3bcf3
[]
no_license
cms-analysis/TauAnalysis-GenSimTools
2652bb713107bb1d459882581237662d229d3906
b787b784ee3598c4428c4883c04cdc525eb54eb6
refs/heads/master
2020-12-24T15:58:14.392883
2013-06-28T20:10:42
2013-06-28T20:10:42
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,238
py
import FWCore.ParameterSet.Config as cms # The Alpgen Source. It reads unweighted alpgen files source = cms.Source("AlpgenSource", # use an input file name without extension unw fileNames = cms.untracked.vstring( 'file:/home/cbernet/ALPGEN/v213/zjetwork/z2j' ) ) # The Alpgen Producer. from GeneratorInterface.AlpgenInterface.generator_cfi import * generator.comEnergy = 14000.0 generator.pythiaHepMCVerbosity = False generator.maxEventsToPrint = 0 # Set the jet matching parameters as you see fit. generator.jetMatching.applyMatching = True generator.jetMatching.exclusive = True generator.jetMatching.etMin = 20.0 generator.jetMatching.drMin = 0.5 # for every process including tau should be use TAUOLA from GeneratorInterface.ExternalDecays.TauolaSettings_cff import * generator.ExternalDecays = cms.PSet( Tauola = cms.untracked.PSet( TauolaPolar, InputCards = cms.PSet( pjak1 = cms.int32(0), pjak2 = cms.int32(0), #mdtau = cms.int32(116) #mdtau = 0 all decays mdtau = cms.int32(116) #mdtau = 116 - ONE mu+-, other taus -> all channels ) ), parameterSets = cms.vstring('Tauola') ) ProductionFilterSequence = cms.Sequence(generator)
f50fbf295e7c63db3184c8adcae01d3500afaf12
600df3590cce1fe49b9a96e9ca5b5242884a2a70
/tools/grit/grit/format/policy_templates/writers/ios_plist_writer_unittest.py
0fdecb1d1ef33336fc052bf6c32b3b97d6f1800a
[ "BSD-3-Clause", "LGPL-2.0-or-later", "LicenseRef-scancode-unknown-license-reference", "GPL-2.0-only", "Apache-2.0", "LicenseRef-scancode-unknown", "MIT" ]
permissive
metux/chromium-suckless
efd087ba4f4070a6caac5bfbfb0f7a4e2f3c438a
72a05af97787001756bae2511b7985e61498c965
refs/heads/orig
2022-12-04T23:53:58.681218
2017-04-30T10:59:06
2017-04-30T23:35:58
89,884,931
5
3
BSD-3-Clause
2022-11-23T20:52:53
2017-05-01T00:09:08
null
UTF-8
Python
false
false
6,923
py
#!/usr/bin/env python # Copyright (c) 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. '''Unit tests for grit.format.policy_templates.writers.ios_plist_writer''' import base64 import functools import os import plistlib import sys if __name__ == '__main__': sys.path.append(os.path.join(os.path.dirname(__file__), '../../../..')) import unittest try: import Cocoa except: Cocoa = None from grit.format.policy_templates.writers import writer_unittest_common class IOSPListWriterUnittest(writer_unittest_common.WriterUnittestCommon): '''Unit tests for IOSPListWriter.''' def _ParseWithPython(self, decode, text): '''Parses a serialized Plist, using Python's plistlib. If |decode| is true then |text| is decoded as Base64 before being deserialized as a Plist.''' if decode: text = base64.b64decode(text) return plistlib.readPlistFromString(text) def _ParseWithCocoa(self, decode, text): '''Parses a serialized Plist, using Cocoa's python bindings. If |decode| is true then |text| is decoded as Base64 before being deserialized as a Plist.''' if decode: data = Cocoa.NSData.alloc().initWithBase64EncodedString_options_(text, 0) else: data = Cocoa.NSData.alloc().initWithBytes_length_(text, len(text)) result = Cocoa.NSPropertyListSerialization. \ propertyListFromData_mutabilityOption_format_errorDescription_( data, Cocoa.NSPropertyListImmutable, None, None) return result[0] def _VerifyGeneratedOutputWithParsers(self, templates, expected_output, parse, decode_and_parse): _defines = { '_chromium': '1', 'mac_bundle_id': 'com.example.Test', 'version': '39.0.0.0' } # Generate the grit output for |templates|. output = self.GetOutput( self.PrepareTest(templates), 'fr', _defines, 'ios_plist', 'en') # Parse it as a Plist. plist = parse(output) self.assertEquals(len(plist), 2) self.assertTrue('ChromePolicy' in plist) self.assertTrue('EncodedChromePolicy' in plist) # Get the 2 expected fields. chrome_policy = plist['ChromePolicy'] encoded_chrome_policy = plist['EncodedChromePolicy'] # Verify the ChromePolicy. self.assertEquals(chrome_policy, expected_output) # Decode the EncodedChromePolicy and verify it. decoded_chrome_policy = decode_and_parse(encoded_chrome_policy) self.assertEquals(decoded_chrome_policy, expected_output) def _VerifyGeneratedOutput(self, templates, expected): # plistlib is available on all Python platforms. parse = functools.partial(self._ParseWithPython, False) decode_and_parse = functools.partial(self._ParseWithPython, True) self._VerifyGeneratedOutputWithParsers( templates, expected, parse, decode_and_parse) # The Cocoa bindings are available on Mac OS X only. if Cocoa: parse = functools.partial(self._ParseWithCocoa, False) decode_and_parse = functools.partial(self._ParseWithCocoa, True) self._VerifyGeneratedOutputWithParsers( templates, expected, parse, decode_and_parse) def _MakeTemplate(self, name, type, example, extra=''): return ''' { 'policy_definitions': [ { 'name': '%s', 'type': '%s', 'desc': '', 'caption': '', 'supported_on': ['ios:35-'], 'example_value': %s, %s }, ], 'placeholders': [], 'messages': {}, } ''' % (name, type, example, extra) def testEmpty(self): templates = ''' { 'policy_definitions': [], 'placeholders': [], 'messages': {}, } ''' expected = {} self._VerifyGeneratedOutput(templates, expected) def testEmptyVersion(self): templates = ''' { 'policy_definitions': [], 'placeholders': [], 'messages': {}, } ''' expected = {} self._VerifyGeneratedOutput(templates, expected) def testBoolean(self): templates = self._MakeTemplate('BooleanPolicy', 'main', 'True') expected = { 'BooleanPolicy': True, } self._VerifyGeneratedOutput(templates, expected) def testString(self): templates = self._MakeTemplate('StringPolicy', 'string', '"Foo"') expected = { 'StringPolicy': 'Foo', } self._VerifyGeneratedOutput(templates, expected) def testStringEnum(self): templates = self._MakeTemplate( 'StringEnumPolicy', 'string-enum', '"Foo"', ''' 'items': [ { 'name': 'Foo', 'value': 'Foo', 'caption': '' }, { 'name': 'Bar', 'value': 'Bar', 'caption': '' }, ], ''') expected = { 'StringEnumPolicy': 'Foo', } self._VerifyGeneratedOutput(templates, expected) def testInt(self): templates = self._MakeTemplate('IntPolicy', 'int', '42') expected = { 'IntPolicy': 42, } self._VerifyGeneratedOutput(templates, expected) def testIntEnum(self): templates = self._MakeTemplate( 'IntEnumPolicy', 'int-enum', '42', ''' 'items': [ { 'name': 'Foo', 'value': 100, 'caption': '' }, { 'name': 'Bar', 'value': 42, 'caption': '' }, ], ''') expected = { 'IntEnumPolicy': 42, } self._VerifyGeneratedOutput(templates, expected) def testStringList(self): templates = self._MakeTemplate('StringListPolicy', 'list', '["a", "b"]') expected = { 'StringListPolicy': [ "a", "b" ], } self._VerifyGeneratedOutput(templates, expected) def testStringEnumList(self): templates = self._MakeTemplate('StringEnumListPolicy', 'string-enum-list', '["a", "b"]', ''' 'items': [ { 'name': 'Foo', 'value': 'a', 'caption': '' }, { 'name': 'Bar', 'value': 'b', 'caption': '' }, ], ''') expected = { 'StringEnumListPolicy': [ "a", "b" ], } self._VerifyGeneratedOutput(templates, expected) def testListOfDictionary(self): templates = self._MakeTemplate( 'ManagedBookmarks', 'dict', ''' [ { "name": "Google Search", "url": "www.google.com", }, { "name": "Youtube", "url": "www.youtube.com", } ] ''') expected = { 'ManagedBookmarks': [ { "name": "Google Search", "url": "www.google.com" }, { "name": "Youtube", "url": "www.youtube.com" }, ], } self._VerifyGeneratedOutput(templates, expected) if __name__ == '__main__': unittest.main()
17182f5cae79f76332304a2abd4a7f9acf5a1442
d41d18d3ea6edd2ec478b500386375a8693f1392
/plotly/validators/layout/ternary/aaxis/_showticksuffix.py
2a1b061ea73eecf6d8c074e3d8662b7cb67f3748
[ "MIT" ]
permissive
miladrux/plotly.py
38921dd6618650d03be9891d6078e771ffccc99a
dbb79e43e2cc6c5762251537d24bad1dab930fff
refs/heads/master
2020-03-27T01:46:57.497871
2018-08-20T22:37:38
2018-08-20T22:37:38
145,742,203
1
0
MIT
2018-08-22T17:37:07
2018-08-22T17:37:07
null
UTF-8
Python
false
false
533
py
import _plotly_utils.basevalidators class ShowticksuffixValidator( _plotly_utils.basevalidators.EnumeratedValidator ): def __init__( self, plotly_name='showticksuffix', parent_name='layout.ternary.aaxis', **kwargs ): super(ShowticksuffixValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type='plot', role='style', values=['all', 'first', 'last', 'none'], **kwargs )
9bf714a6abbcdb0385038e4cdee96b601cece13d
06a7dc7cc93d019e4a9cbcf672b23a0bbacf8e8b
/2013_adni/MMSE-AD-CTL/01_build_dataset.py
f9049d7b28f1fc1da3d70f12b740317ca04ad28d
[]
no_license
neurospin/scripts
6c06cd218a5f32de9c3c2b7d1d8bda3f3d107458
f14a2c9cf2cd7f5fbea767b017c3faf36d170bdb
refs/heads/master
2021-07-11T22:55:46.567791
2021-07-02T13:08:02
2021-07-02T13:08:02
10,549,286
2
2
null
null
null
null
UTF-8
Python
false
false
6,376
py
# -*- coding: utf-8 -*- """ @author: [email protected] Compute mask, concatenate masked non-smoothed images for all the subjects. Build X, y, and mask INPUT: - subject_list.txt: - population.csv OUTPUT: - mask.nii.gz - y.npy - X.npy = intercept + Age + Gender + Voxel """ import os import numpy as np import glob import pandas as pd import nibabel import brainomics.image_atlas import shutil #import proj_classif_config GENDER_MAP = {'Female': 0, 'Male': 1} BASE_PATH = "/neurospin/brainomics/2013_adni" #INPUT_CLINIC_FILENAME = os.path.join(BASE_PATH, "clinic", "adnimerge_baseline.csv") INPUT_SUBJECTS_LIST_FILENAME = os.path.join(BASE_PATH, "templates", "template_FinalQC", "subject_list.txt") INPUT_IMAGEFILE_FORMAT = os.path.join(BASE_PATH, "templates", "template_FinalQC", "registered_images", "mw{PTID}*_Nat_dartel_greyProba.nii") INPUT_CSV = os.path.join(BASE_PATH, "MMSE-AD-CTL", "population.csv") OUTPUT = os.path.join(BASE_PATH, "MMSE-AD-CTL") OUTPUT_CS = os.path.join(BASE_PATH, "MMSE-AD-CTL_cs") #OUTPUT_ATLAS = os.path.join(BASE_PATH, "MMSE-AD-CTL_gtvenet") #OUTPUT_CS_ATLAS = os.path.join(BASE_PATH, "MMSE-AD-CTL_cs_gtvenet") if not os.path.exists(OUTPUT): os.makedirs(OUTPUT) if not os.path.exists(OUTPUT_CS): os.makedirs(OUTPUT_CS) #os.makedirs(OUTPUT_ATLAS) #os.makedirs(OUTPUT_CS_ATLAS) # Read input subjects input_subjects = pd.read_table(INPUT_SUBJECTS_LIST_FILENAME, sep=" ", header=None) input_subjects = [x[:10] for x in input_subjects[1]] # Read pop csv pop = pd.read_csv(INPUT_CSV) pop['PTGENDER.num'] = pop["PTGENDER"].map(GENDER_MAP) ############################################################################# # Read images n = len(pop) assert n == 242 Z = np.zeros((n, 3)) # Intercept + Age + Gender Z[:, 0] = 1 # Intercept y = np.zeros((n, 1)) # DX images = list() for i, PTID in enumerate(pop['PTID']): cur = pop[pop.PTID == PTID] print cur imagefile_pattern = INPUT_IMAGEFILE_FORMAT.format(PTID=PTID) imagefile_name = glob.glob(imagefile_pattern) if len(imagefile_name) != 1: raise ValueError("Found %i files" % len(imagefile_name)) babel_image = nibabel.load(imagefile_name[0]) images.append(babel_image.get_data().ravel()) Z[i, 1:] = np.asarray(cur[["AGE", "PTGENDER.num"]]).ravel() y[i, 0] = cur["MMSE"] shape = babel_image.get_data().shape ############################################################################# # Compute mask # Implicit Masking involves assuming that a lower than a givent threshold # at some voxel, in any of the images, indicates an unknown and is # excluded from the analysis. Xtot = np.vstack(images) mask = (np.min(Xtot, axis=0) > 0.01) & (np.std(Xtot, axis=0) > 1e-6) mask = mask.reshape(shape) assert mask.sum() == 313734 ############################################################################# # Compute atlas mask babel_mask_atlas = brainomics.image_atlas.resample_atlas_harvard_oxford( ref=imagefile_name[0], output=os.path.join("/tmp", "mask.nii.gz")) mask_atlas = babel_mask_atlas.get_data() assert np.sum(mask_atlas != 0) == 638715 mask_atlas[np.logical_not(mask)] = 0 # apply implicit mask # smooth mask_atlas = brainomics.image_atlas.smooth_labels(mask_atlas, size=(3, 3, 3)) assert np.sum(mask_atlas != 0) == 285983 out_im = nibabel.Nifti1Image(mask_atlas, affine=babel_image.get_affine()) out_im.to_filename(os.path.join("/tmp", "mask.nii.gz")) im = nibabel.load(os.path.join("/tmp", "mask.nii.gz")) assert np.all(mask_atlas == im.get_data()) #shutil.copyfile(os.path.join(OUTPUT_ATLAS, "mask.nii.gz"), os.path.join(OUTPUT_CS_ATLAS, "mask.nii.gz")) ############################################################################# # Compute mask with atlas but binarized (not group tv) mask_bool = mask_atlas != 0 assert mask_bool.sum() == 285983 out_im = nibabel.Nifti1Image(mask_bool.astype("int16"), affine=babel_image.get_affine()) out_im.to_filename(os.path.join(OUTPUT, "mask.nii.gz")) babel_mask = nibabel.load(os.path.join(OUTPUT, "mask.nii.gz")) assert np.all(mask_bool == (babel_mask.get_data() != 0)) shutil.copyfile(os.path.join(OUTPUT, "mask.nii.gz"), os.path.join(OUTPUT_CS, "mask.nii.gz")) ############################################################################# # X X = Xtot[:, mask_bool.ravel()] X = np.hstack([Z, X]) assert X.shape == (242, 285986) n, p = X.shape np.save(os.path.join(OUTPUT, "X.npy"), X) fh = open(os.path.join(OUTPUT, "X.npy").replace("npy", "txt"), "w") fh.write('shape = (%i, %i): Intercept + Age + Gender + %i voxels' % \ (n, p, mask_bool.sum())) fh.close() # Xcs X = Xtot[:, mask_bool.ravel()] X = np.hstack([Z[:, 1:], X]) assert X.shape == (242, 285985) X -= X.mean(axis=0) X /= X.std(axis=0) n, p = X.shape np.save(os.path.join(OUTPUT_CS, "X.npy"), X) fh = open(os.path.join(OUTPUT_CS, "X.npy").replace("npy", "txt"), "w") fh.write('Centered and scaled data. Shape = (%i, %i): Age + Gender + %i voxels' % \ (n, p, mask_bool.sum())) fh.close() ## atlas #X = Xtot[:, (mask_atlas.ravel() != 0)] #X = np.hstack([Z, X]) #assert X.shape == (242, 285986) #n, p = X.shape #np.save(os.path.join(OUTPUT_ATLAS, "X.npy"), X) #fh = open(os.path.join(OUTPUT_ATLAS, "X.npy").replace("npy", "txt"), "w") #fh.write('shape = (%i, %i): Intercept + Age + Gender + %i voxels' % \ # (n, p, (mask_atlas.ravel() != 0).sum())) #fh.close() # ## atlas cs #X = Xtot[:, (mask_atlas.ravel() != 0)] #X = np.hstack([Z[:, 1:], X]) #assert X.shape == (242, 285985) #X -= X.mean(axis=0) #X /= X.std(axis=0) #n, p = X.shape #np.save(os.path.join(OUTPUT_CS_ATLAS, "X.npy"), X) #fh = open(os.path.join(OUTPUT_CS_ATLAS, "X.npy").replace("npy", "txt"), "w") #fh.write('Centered and scaled data. Shape = (%i, %i): Age + Gender + %i voxels' % \ # (n, p, (mask_atlas.ravel() != 0).sum())) #fh.close() np.save(os.path.join(OUTPUT, "y.npy"), y) y -= y.mean() y /= y.std() np.save(os.path.join(OUTPUT_CS, "y.npy"), y) #np.save(os.path.join(OUTPUT_ATLAS, "y.npy"), y) #np.save(os.path.join(OUTPUT_CS_ATLAS, "y.npy"), y)
2bb5e9136817920f0a118765a28bf286b13b41be
c86277d74266b90b64774bc924b041009d697b2e
/source/nextdoor/wsgi.py
2ae744a10344445edcd3ffe9adf052710f84605a
[]
no_license
rakeshsukla53/facebook-for-neighbours
dcd0c564530404e5415fa08b184398d10b1170ba
3d6c1430ab4f7ac8f668626c82705552da9f6566
refs/heads/master
2021-01-10T04:54:00.962831
2015-12-25T17:32:45
2015-12-25T17:32:45
46,942,279
2
0
null
null
null
null
UTF-8
Python
false
false
393
py
""" WSGI config for nextdoor 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/1.8/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "nextdoor.settings") application = get_wsgi_application()
7a78bab1a7c668a9b26dfe834a4c903b5273b3e3
d833e1643f799d8979ae385992be9f3012af23a5
/examples/c60_find_submit.py
848dd0dd9378059f4770fd68b09de99329f047ff
[ "BSD-3-Clause" ]
permissive
ZhouHUB/simdb
05906505d549cbf584dcdcc91c9cebe95c2d349b
33fa21ddcc683e1618dfb337f5f928363c902a1e
refs/heads/master
2020-04-01T22:32:36.665260
2016-04-15T19:20:46
2016-04-15T19:20:46
36,950,426
0
0
null
2018-07-24T19:56:44
2015-06-05T19:06:15
Python
UTF-8
Python
false
false
1,051
py
__author__ = 'christopher' import ase from simdb.insert import * from simdb.search import * from pyiid.utils import build_sphere_np from copy import deepcopy as dc target_config, = find_atomic_config_document(name='C60 DFT') parent_atoms = target_config.file_payload[-1] # find the combined Potential Energy Surface (PES) pes, = find_pes_document(name='C60 PDF Spring') # find the simulation parameters params, = find_simulation_parameter_document(name='T=1, iter=100, accept=.65') rattles = [.05, .07, .08, .1] for rattle in rattles: # find starting_config try: start_config, = find_atomic_config_document(name='C60' + str(rattle)) except ValueError: starting_atoms = dc(parent_atoms) starting_atoms.rattle(rattle, 42) # Add the atoms to the DB start_config = insert_atom_document('C60 ' + str(rattle), starting_atoms) # Finally create the simulation sim = insert_simulation('C60 rattle->DFT ' + str(rattle), params, start_config, pes) print 'simulation added, number ', sim.id
e2886ddba4caf4503f5d0cf9cf97f91e5c76cd44
3d0bb8d94a69237bf3c6ba6b2ccfdd0bc9cc162c
/addons/asterisk/agi-bin/states/get_fast_dial_destination_from_ibs.py
4521e2804bce47ffccda4b3c9723ff47c347a06f
[]
no_license
ha8sh/IBSng
69727a7c5476ecb8efa45b7393ffe51de37a8a10
596aa468f8264ab0129431e3ede6cc1282b1ebbd
refs/heads/main
2023-08-25T18:21:28.081153
2021-10-02T05:03:52
2021-10-02T05:03:52
412,687,955
1
0
null
null
null
null
UTF-8
Python
false
false
791
py
import xmlrpclib import ibs_agi from lib import request from lib.error import * def init(): ibs_agi.getStateMachine().registerState("GET_FAST_DIAL_DESTINATION_FROM_IBS",getFastDialIndexFromIBS) def getFastDialIndexFromIBS(_index): """ get fast dial index destination from ibs may raise an IBSException """ _index=int(_index) req=request.Request() try: destination=req.send("getFastDialDestination",True,index=_index) except xmlrpclib.Fault,e: logException() ibs_agi.getSelectedLanguage().sayPrompt("unknown_problem") raise IBSException(e.faultString) else: if ibs_agi.getConfig().getValue("debug"): toLog("getFastDialIndexFromIBS: %s"%destination) return destination
73c1cb0d4aa4a86afefeb3fd74e8241edec6456a
7620893c7d253a4d8c6f5aef2cfda6c72b777d49
/src/Camera/DisplayImage.py
8d1b1ee14891406071b40da9d5bf7f304a4aa7ad
[]
no_license
garridoH/cameraGUI
cacc549a9da0bcb6c3b9be04ef9783c653300118
cb6ac1d54dd8651da974ed058990c8212d145415
refs/heads/master
2021-01-17T22:38:53.398306
2012-06-12T20:41:44
2012-06-12T20:41:44
null
0
0
null
null
null
null
UTF-8
Python
false
false
800
py
''' Adapted from online sources, including http://www.blog.pythonlibrary.org/2010/03/26/creating-a-simple-photo-viewer-with-wxpython/ ''' import wx class displayImage(wx.App): def __init__(self, redirect=False): wx.App.__init__(self, redirect) self.frame = wx.Frame(None, title='Prosilica Viewer', pos=(100,300), size=(1360,1024)) self.panel = wx.Panel(self.frame) self.Image = wx.StaticBitmap(self.frame, bitmap=wx.EmptyBitmap(1360,1024)) #self.panel.Layout() self.frame.Show() def showImage(self, bmpImg): h=bmpImg.GetHeight() w=bmpImg.GetWidth() print "Image is " + str(h) + " x " + str(w) self.Image.SetBitmap(bmpImg) self.Image.Refresh() def OnClose(self, event): self.Destroy()
0c3d842557c9376a3e85eb48319735d211b4170d
487ce91881032c1de16e35ed8bc187d6034205f7
/codes/CodeJamCrawler/16_0_1/Naca/main.py
5645aca52186859c629e2d833d00d1e431940170
[]
no_license
DaHuO/Supergraph
9cd26d8c5a081803015d93cf5f2674009e92ef7e
c88059dc66297af577ad2b8afa4e0ac0ad622915
refs/heads/master
2021-06-14T16:07:52.405091
2016-08-21T13:39:13
2016-08-21T13:39:13
49,829,508
2
0
null
2021-03-19T21:55:46
2016-01-17T18:23:00
Python
UTF-8
Python
false
false
432
py
T = int(input()); data = []; for i in range(T) : data.append(int(input())); for i in range(T) : if (data[i] == 0) : print("Case #" + str(i + 1) + ": INSOMNIA"); else : digits = []; sumN = data[i]; while (len(digits) < 10) : tmp = sumN; while (tmp > 0) : if (tmp % 10 not in digits) : digits.append(tmp % 10); tmp //= 10; sumN += data[i]; print("Case #" + str(i + 1) + ": " + str(sumN - data[i]));
5c373349176db66ba2f7617dfca9fa2c18ee4d78
94724578994ab1438dcefb51b7ef4d8570da5d4c
/calibre/draveness.recipe
361ce64106650ddf8643557d49369ebfec882386
[]
no_license
PegasusWang/collection_python
6648d83203634abf44fd42c0b37b0bf7cc406d8f
9ef019a737a0817860d3184924c67a0833bd1252
refs/heads/master
2023-09-01T23:15:39.813635
2023-08-24T06:46:12
2023-08-24T06:46:12
43,693,872
130
90
null
2021-04-26T15:12:55
2015-10-05T15:28:15
JavaScript
UTF-8
Python
false
false
2,028
recipe
#!/usr/bin/python # encoding: utf-8 from calibre.web.feeds.recipes import BasicNewsRecipe # 引入 Recipe 基础类 """ 教程: - https://bookfere.com/tools#calibre - https://www.jianshu.com/p/0bcb92509309 - https://snowdreams1006.github.io/myGitbook/advance/export.html 命令: ebook-convert draveness.recipe draveness.mobi --output-profile=kindle """ class DravenessBlog(BasicNewsRecipe): # 继承 BasicNewsRecipe 类的新类名 # /////////////////// # 设置电子书元数据 # /////////////////// title = "draveness" # 电子书名 description = u"draveness的博客" # 电子书简介 # cover_url = '' # 电子书封面 # masthead_url = '' # 页头图片 __author__ = "draveness" # 作者 language = "zh" # 语言 encoding = "utf-8" # 编码 # /////////////////// # 抓取页面内容设置 # /////////////////// # keep_only_tags = [{ 'class': 'example' }] # 仅保留指定选择器包含的内容 no_stylesheets = True # 去除 CSS 样式 remove_javascript = True # 去除 JavaScript 脚本 auto_cleanup = True # 自动清理 HTML 代码 delay = 5 # 抓取页面间隔秒数 max_articles_per_feed = 100 # 抓取文章数量 timeout = 10 # /////////////////// # 页面内容解析方法 # /////////////////// def parse_index(self): site = "https://draveness.me/whys-the-design/" soup = self.index_to_soup(site) # 解析列表页返回 BeautifulSoup 对象 articles = [] # 定义空文章资源数组 ultag = soup.findAll("ul")[6] urls = ultag.findAll("li") urls.reverse() for link in urls: title = link.a.contents[0].strip() # 提取文章标题 url = link.a.get("href") # 提取文章链接 print(title, url) articles.append({"title": title, "url": url}) ans = [(self.title, articles)] # 组成最终的数据结构 return ans # 返回可供 Calibre 转换的数据结构
eec8efa198fdd6ce3ad3070fc8265762caf05d1c
58141d7fc37854efad4ad64c74891a12908192ed
/tests/test_storage2.py
b09918d1388d18d6fb7fb62fa653799306d5de22
[]
no_license
stanleylio/fishie
b028a93b2093f59a8ceee4f78b55a91bb1f69506
0685045c07e4105934d713a0fd58c4bc28821ed6
refs/heads/master
2022-08-14T13:08:55.548830
2022-07-29T01:32:28
2022-07-29T01:32:28
30,433,819
8
1
null
null
null
null
UTF-8
Python
false
false
569
py
import unittest,sys from os.path import expanduser sys.path.append(expanduser('~')) from node.storage.storage2 import storage class TestStorage2(unittest.TestCase): def test_read_latest_non_null(self): s = storage() self.assertTrue(s.read_latest_non_null('node-008', 'ReceptionTime', 'idx')) #self.assertTrue(parse_SeaFET(m) is not None) def test_read_last_N_minutes(self): s = storage() self.assertTrue(s.read_last_N_minutes('node-007', 'ReceptionTime', 1, 'T_280')) if __name__ == '__main__': unittest.main()
7f06aa3882b4fc1e0e5f3f8bc66e51bcb16b8038
5730e8d500a65992bb21094ffed26e21ccc7c0fd
/augment_dnase_pipeline_outputs/metadata/aggregate_ataqc.py
2963e434753969d97146b33d89c1eb86a8843a62
[]
no_license
kundajelab/atlas_resources
35f1df4c09356d7256a6667700b88020396d5642
89bcde11921526b9956be48bf367617db4974d31
refs/heads/master
2021-10-25T07:01:30.127405
2021-10-25T00:55:25
2021-10-25T00:55:25
160,546,622
2
1
null
null
null
null
UTF-8
Python
false
false
2,942
py
import argparse import collections import json import pdb def parse_args(): parser=argparse.ArgumentParser(description="aggregate ataqc metrics for all samples in a single report") parser.add_argument("--ataqc_files",default="/oak/stanford/groups/akundaje/projects/atlas/dnase_processed/aggregate_outputs/qc.json.txt") parser.add_argument("--outf",default="atlas.metadata.report.txt") parser.add_argument("--mitra_prefix",default="http://mitra.stanford.edu/kundaje/projects/atlas/") parser.add_argument("--prefix_to_drop_for_oak",default="/oak/stanford/groups/akundaje/projects/atlas/") parser.add_argument("--hash_to_id",default="/oak/stanford/groups/akundaje/projects/atlas/dnase_processed/processed_all.txt") parser.add_argument("--fname_hash_index",type=int,default=9) return parser.parse_args() def flatten(d, parent_key='', sep='.'): items = [] for k, v in d.items(): new_key = parent_key + sep + k if parent_key else k if isinstance(v, collections.MutableMapping): items.extend(flatten(v, new_key, sep=sep).items()) else: items.append((new_key, v)) return dict(items) def iterate_json(data,val_dict,all_keys,cur_id): flat_data=flatten(data) for key in flat_data: if key not in all_keys: all_keys.add(key) val_dict[cur_id][key]=flat_data[key] return val_dict,all_keys def main(): args=parse_args() ataqc_files=open(args.ataqc_files,'r').read().strip().split('\n') val_dict=dict() all_keys=set([]) outf=open(args.outf,'w') hash_to_id=open(args.hash_to_id,'r').read().strip().split('\n') hash_to_id_dict=dict() for line in hash_to_id: tokens=line.split('\t') cur_hash=tokens[0] cur_id=tokens[1] hash_to_id_dict[cur_hash]=cur_id for fname in ataqc_files: with open(fname,'r') as cur_f: data=json.load(cur_f) #get the report title report_title=fname.replace(args.prefix_to_drop_for_oak,args.mitra_prefix).replace(".json",".html") #get the hash cur_hash=fname.split('/')[args.fname_hash_index] cur_id=hash_to_id_dict[cur_hash] print(cur_id+" : "+report_title) val_dict[cur_id]=dict() val_dict[cur_id]['path']=report_title all_keys.add('path') #iterate through the json file recursively val_dict,all_keys=iterate_json(data,val_dict,all_keys,cur_id) outf.write('Dataset') all_keys=list(all_keys) for key in all_keys: outf.write('\t'+key) outf.write('\n') for dataset in val_dict: outf.write(dataset) for key in all_keys: if key in val_dict[dataset]: outf.write('\t'+str(val_dict[dataset][key])) else: outf.write('\tNA') outf.write('\n') outf.close() if __name__=="__main__": main()
f8de786a0f3c8b0ba99882fe7407050b11316930
55b57d64ec547869835334318f3059fbb507558c
/Fred2/Data/pssms/tepitopepan/mat/DRB5_0111_9.py
fd2bb78b87e863070732f2fef744ff47908e3877
[ "BSD-3-Clause" ]
permissive
FRED-2/Fred2
9845f6678d4011cb746c7a5a6f283eea68077a02
b3e54c8c4ed12b780b61f74672e9667245a7bb78
refs/heads/master
2021-07-12T05:05:54.515427
2020-05-25T06:56:25
2020-05-25T06:56:25
16,275,425
42
35
null
2021-07-07T12:05:11
2014-01-27T10:08:11
Python
UTF-8
Python
false
false
2,095
py
DRB5_0111_9 = {0: {'A': -999.0, 'E': -999.0, 'D': -999.0, 'G': -999.0, 'F': -0.004754, 'I': -0.99525, 'H': -999.0, 'K': -999.0, 'M': -0.99525, 'L': -0.99525, 'N': -999.0, 'Q': -999.0, 'P': -999.0, 'S': -999.0, 'R': -999.0, 'T': -999.0, 'W': -0.004754, 'V': -0.99525, 'Y': -0.004754}, 1: {'A': 0.0, 'E': 0.1, 'D': -1.3, 'G': 0.5, 'F': 0.8, 'I': 1.1, 'H': 0.8, 'K': 1.1, 'M': 1.1, 'L': 1.0, 'N': 0.8, 'Q': 1.2, 'P': -0.5, 'S': -0.3, 'R': 2.2, 'T': 0.0, 'W': -0.1, 'V': 2.1, 'Y': 0.9}, 2: {'A': 0.0, 'E': -1.2, 'D': -1.3, 'G': 0.2, 'F': 0.8, 'I': 1.5, 'H': 0.2, 'K': 0.0, 'M': 1.4, 'L': 1.0, 'N': 0.5, 'Q': 0.0, 'P': 0.3, 'S': 0.2, 'R': 0.7, 'T': 0.0, 'W': 0.0, 'V': 0.5, 'Y': 0.8}, 3: {'A': 0.0, 'E': -1.2876, 'D': -1.8782, 'G': -1.5864, 'F': -0.56917, 'I': 1.2917, 'H': -1.3705, 'K': -1.69, 'M': 1.6918, 'L': 0.60019, 'N': -1.6785, 'Q': -0.69644, 'P': -1.4887, 'S': -0.4961, 'R': -1.6837, 'T': 0.29244, 'W': -1.3798, 'V': 1.0861, 'Y': -0.57262}, 4: {'A': 0.0, 'E': 0.0, 'D': 0.0, 'G': 0.0, 'F': 0.0, 'I': 0.0, 'H': 0.0, 'K': 0.0, 'M': 0.0, 'L': 0.0, 'N': 0.0, 'Q': 0.0, 'P': 0.0, 'S': 0.0, 'R': 0.0, 'T': 0.0, 'W': 0.0, 'V': 0.0, 'Y': 0.0}, 5: {'A': 0.0, 'E': -2.0, 'D': -2.0, 'G': -0.30001, 'F': -1.7, 'I': -1.4, 'H': -1.2, 'K': -1.5, 'M': -1.5, 'L': -1.0, 'N': -1.3, 'Q': -1.4, 'P': 0.19998, 'S': -0.49997, 'R': -1.3, 'T': -0.79998, 'W': -1.7, 'V': -1.3, 'Y': -1.0}, 6: {'A': 0.0, 'E': -0.89606, 'D': -1.4918, 'G': 0.58996, 'F': 1.4949, 'I': 1.2005, 'H': 1.1907, 'K': 0.88503, 'M': 0.41266, 'L': 0.61161, 'N': 0.50177, 'Q': 0.68943, 'P': -0.59131, 'S': -0.1948, 'R': 1.2786, 'T': 0.29867, 'W': 0.39933, 'V': -0.29253, 'Y': 1.1918}, 7: {'A': 0.0, 'E': 0.0, 'D': 0.0, 'G': 0.0, 'F': 0.0, 'I': 0.0, 'H': 0.0, 'K': 0.0, 'M': 0.0, 'L': 0.0, 'N': 0.0, 'Q': 0.0, 'P': 0.0, 'S': 0.0, 'R': 0.0, 'T': 0.0, 'W': 0.0, 'V': 0.0, 'Y': 0.0}, 8: {'A': 0.0, 'E': -0.60069, 'D': -1.4932, 'G': 0.39612, 'F': 1.1915, 'I': 1.1912, 'H': 0.98443, 'K': 2.6667, 'M': 0.50264, 'L': 1.283, 'N': -0.0088368, 'Q': 0.69103, 'P': -0.79719, 'S': 0.70285, 'R': 2.4734, 'T': -0.20486, 'W': -0.70351, 'V': -0.19682, 'Y': 1.2852}}
58950f55ea5a2b7fae6b323bfc181434c02aaaee
305d25e1d2084761e889057077706b1ba3f9122d
/nmigen_boards/arty_z7.py
ba432b642cc9588c44c7e5037b12b600668f5a6b
[ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ]
permissive
nicolas-robin/nmigen-boards
d7d8fe29d788f8b1fdcf8da0cf7202a1f0fa741a
6fc91b491214b80c56b2b2d031da1a50c7254c56
refs/heads/master
2020-12-10T15:43:43.358008
2020-01-17T21:54:48
2020-01-17T21:54:48
233,314,458
0
0
NOASSERTION
2020-01-12T00:01:57
2020-01-12T00:01:57
null
UTF-8
Python
false
false
5,359
py
import os import subprocess from nmigen.build import * from nmigen.vendor.xilinx_7series import * from .resources import * __all__ = ["ArtyZ720Platform"] class ArtyZ720Platform(Xilinx7SeriesPlatform): device = "xc7z020" package = "clg400" speed = "1" default_clk = "clk125" resources = [ Resource("clk125", 0, Pins("H16", dir="i"), Clock(125e6), Attrs(IOSTANDARD="LVCMOS33")), *SwitchResources( pins="M20 M19", attrs=Attrs(IOSTANDARD="LVCMOS33")), RGBLEDResource(0, r="N15", g="G17", b="L15", # LD4 attrs=Attrs(IOSTANDARD="LVCMOS33")), RGBLEDResource(1, # LD5 r="M15", g="L14", b="G14", attrs=Attrs(IOSTANDARD="LVCMOS33")), *LEDResources( pins="R14 P14 N16 M14", attrs=Attrs(IOSTANDARD="LVCMOS33")), *ButtonResources( pins="D19 D20 L20 L19", attrs=Attrs(IOSTANDARD="LVCMOS33")), Resource("audio", 0, Subsignal("pwm", Pins("R18", dir="o")), Subsignal("sd", PinsN("T17", dir="o")), Attrs(IOSTANDARD="LVCMOS33")), Resource("crypto_sda", 0, # ATSHA204A Pins("J15", dir="io"), Attrs(IOSTANDARD="LVCMOS33")), Resource("hdmi_rx", 0, # J10 Subsignal("cec", Pins("H17", dir="io")), Subsignal("clk", DiffPairs("N18", "P19", dir="i"), Attrs(IO_TYPE="TMDS_33")), Subsignal("d", DiffPairs("V20 T20 N20", "W20 U20 P20", dir="i"), Attrs(IO_TYPE="TMDS_33")), Subsignal("hpd", Pins("T19", dir="o")), Subsignal("scl", Pins("U14", dir="io")), Subsignal("sda", Pins("U15", dir="io")), Attrs(IOSTANDARD="LVCMOS33")), Resource("hdmi_tx", 0, # J11 Subsignal("cec", Pins("G15", dir="io")), Subsignal("clk", DiffPairs("L16", "L17", dir="o"), Attrs(IO_TYPE="TMDS_33")), Subsignal("d", DiffPairs("K17 K19 J18", "K18 J19 H18", dir="o"), Attrs(IO_TYPE="TMDS_33")), Subsignal("hpd", PinsN("R19", dir="i")), Subsignal("scl", Pins("M17", dir="io")), Subsignal("sda", Pins("M18", dir="io")), Attrs(IOSTANDARD="LVCMOS33")) ] connectors = [ Connector("pmod", 0, "Y18 Y19 Y16 Y17 - - U18 U19 W18 W19 - -"), # JA Connector("pmod", 1, "Y14 W14 T10 T11 - - W16 V16 W13 V12 - -"), # JB Connector("ck_io", 0, { # Outer Digital Header "io0": "T14", "io1": "U12", "io2": "U13", "io3": "V13", "io4": "V15", "io5": "T15", "io6": "R16", "io7": "U17", "io8": "V17", "io9": "V18", "io10": "T16", "io11": "R17", "io12": "P18", "io13": "N17", # Inner Digital Header "io26": "U5", "io27": "V5", "io28": "V6", "io29": "U7", "io30": "V7", "io31": "U8", "io32": "V8", "io33": "V10", "io34": "W10", "io35": "W6", "io36": "Y6", "io37": "Y7", "io38": "W8", "io39": "Y8", "io40": "W9", "io41": "Y9", # Outer Analog Header as Digital IO "a0": "Y11", "a1": "Y12", "a2": "W11", "a3": "V11", "a4": "T5", "a5": "U10", # Inner Analog Header as Digital IO "a6": "F19", "a7": "F20", "a8": "C20", "a9": "B20", "a10": "B19", "a11": "A20", # Misc. "a": "Y13" }), Connector("ck_spi", 0, { "miso": "W15", "mosi": "T12", "sck": "H15", "ss": "F16" }), Connector("ck_i2c", 0, { "scl": "P16", "sda": "P15" }), Connector("xadc", 0, { # Outer Analog Header "vaux1_n": "D18", "vaux1_p": "E17", "vaux9_n": "E19", "vaux9_p": "E18", "vaux6_n": "J14", "vaux6_p": "K14", "vaux15_n": "J16", "vaux15_p": "K16", "vaux5_n": "H20", "vaux5_p": "J20", "vaux13_n": "G20", "vaux13_p": "G19", # Inner Analog Header "vaux12_n": "F20", "vaux12_p": "F19", "vaux0_n": "B20", "vaux0_p": "C20", "vaux8_n": "A20", "vaux8_p": "B19" }) ] def toolchain_program(self, products, name, **kwargs): xc3sprog = os.environ.get("XC3SPROG", "xc3sprog") with products.extract("{}.bit".format(name)) as bitstream_filename: subprocess.run([xc3sprog, "-c", "jtaghs1_fast", "-p", "1", bitstream_filename], check=True) if __name__ == "__main__": from .test.blinky import * ArtyZ720Platform().build(Blinky(), do_program=True)
c5c7c9fa51eaaec171b3b32e2cb18f6d63866966
8a82a83655f118208692e55d7804d9fa480ad4b6
/book/apress/Beginning.Python.Visualization.Crafting.Visual.Transformation.Scripts/Chapter04/src/read_ini.py
bf4374d1f2c6de9b410eea7d36a061bd6b2c38a7
[]
no_license
xenron/sandbox-da-python
0814159da9a91923e4b66c5e40057e381f765e96
ab8f1c0d57fdc6006355f613012b84165068c315
refs/heads/master
2020-04-12T05:41:33.182110
2016-12-14T22:57:33
2016-12-14T22:57:33
60,324,979
5
2
null
null
null
null
UTF-8
Python
false
false
292
py
# read an INI (config) file import ConfigParser read_opts=ConfigParser.ConfigParser() read_opts.read('../data/options.ini') # print parameters and values for section in read_opts.sections(): print "[%s]" % section for param in read_opts.items(section): print param
85ee743b57fa57b5f097d7c44528ca83bfbafbc4
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p03250/s433353636.py
15a9e1142e1ac04131cec60d4882b0b4d8b16ff5
[]
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
70
py
a=list(map(int,input().split())) a=sorted(a) print(a[-1]*10+a[1]+a[0])
db3596b8480850b3718c2c9d08671fd49db81831
0543faeee9f493260e8cbd8a9155a96a8cbb0df2
/main_app/migrations/0018_profile.py
9f188815d07ced745fd5193ceebf36edd8813264
[]
no_license
tanveerahmad1517/Treasuregram
134853f298628c161ebe741864cdb581ce80db8f
797e0ff1460eb50d90aa385f6fb25990ed7766fa
refs/heads/master
2020-03-10T13:58:43.912795
2018-04-13T14:32:31
2018-04-13T14:32:31
129,413,871
0
0
null
null
null
null
UTF-8
Python
false
false
697
py
# -*- coding: utf-8 -*- # Generated by Django 1.10 on 2018-02-13 13:10 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('main_app', '0017_remove_treasure_date'), ] operations = [ migrations.CreateModel( name='Profile', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('first_name', models.CharField(db_column='first_name', max_length=50)), ('last_name', models.CharField(db_column='last_name', max_length=50)), ], ), ]
53171e07178a012d3d4820a34f4a4926dbf039f9
909afe0216a37bdc19683d81e533fa6c094329c1
/python/fluent_python/17-futures/flags_threadpool.py
06c33a7643ddd6282576bba9507f4a1c595c79bf
[]
no_license
wxnacy/study
af7fdcd9915d668be73c6db81bdc961247e24c73
7bca9dc8ec211be15c12f89bffbb680d639f87bf
refs/heads/master
2023-04-08T17:57:40.801687
2023-03-29T08:02:20
2023-03-29T08:02:20
118,090,886
18
22
null
2022-12-16T03:11:43
2018-01-19T07:14:02
HTML
UTF-8
Python
false
false
481
py
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author: wxnacy([email protected]) # Description: 使用多线程下载 from concurrent.futures import ThreadPoolExecutor from flags import download_one, main MAX_WORKERS = 20 def download_many(suffixs): workers = min(MAX_WORKERS, len(suffixs)) with ThreadPoolExecutor(workers) as executor: res = executor.map(download_one, suffixs) return len(list(res)) if __name__ == "__main__": main(download_many)
1998f40d200a554665e76178c4a6f06101755f94
74d11e4000d99e43dc4c53c93ac59782ebbe1802
/portrait/deeplab/model_test.py
c586ccd0ea5c6626ab32562bec21e041fdf8b7cc
[ "Apache-2.0" ]
permissive
hiepgaf/portrait
f450971e8881e9bcd1f386966651a9a01c1d11ce
930a167cbb368cdc2cf906b06b70c035d87e6938
refs/heads/master
2020-03-19T00:14:06.916160
2018-05-14T05:57:29
2018-05-14T05:57:29
null
0
0
null
null
null
null
UTF-8
Python
false
false
941
py
"""Tests for encoder""" import numpy as np import tensorflow as tf from model import deeplab_v3_plus_model def create_test_inputs(batch, height, width, channels): """Create mock Images """ if None in [batch, height, width, channels]: return tf.placeholder(tf.float32, (batch, height, width, channels)) else: return tf.to_float( np.tile(np.reshape( np.reshape(np.arange(height), [height, 1]) + np.reshape(np.arange(width), [1, width]), [1, height, width, 1]), [batch, 1, 1, channels])) class DeepLabV3PlusTest(tf.test.TestCase): def testBuildDeepLabV3Plus(self): """"Encoder Constructor Test""" images = create_test_inputs(2, 224, 224, 3) encoded_features, _ = deeplab_v3_plus_model( images=images) self.assertListEqual( encoded_features.get_shape().as_list(), [2, 28, 28, 256]) if __name__ == '__main__': tf.test.main()
3091099fee02328c00c32ce85434caa6c2918a00
d2fdd6b10b0467913971d1408a9a4053f0be9ffb
/datahub/investment/project/migrations/0033_add_investment_document_permission.py
87a514117458d20c8bf84bc4f1155a3ce0c0b8eb
[]
no_license
jakub-kozlowski/data-hub-leeloo
fc5ecebb5e4d885c824fc7c85acad8837fcc5c76
7f033fcbcfb2f7c1c0e10bec51620742d3d929df
refs/heads/master
2020-05-18T13:29:14.145251
2019-04-30T12:12:50
2019-04-30T12:12:50
null
0
0
null
null
null
null
UTF-8
Python
false
false
728
py
# Generated by Django 2.0.1 on 2018-01-09 16:32 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('investment', '0032_investmentproject_comments'), ] operations = [ migrations.AlterModelOptions( name='investmentproject', options={'default_permissions': ('add', 'change_all', 'delete'), 'permissions': (('read_all_investmentproject', 'Can read all investment project'), ('read_associated_investmentproject', 'Can read associated investment project'), ('change_associated_investmentproject', 'Can change associated investment project'), ('read_investmentproject_document', 'Can read investment project document'))}, ), ]
4a2f9b5baa86079690190cf78a776554744e8271
c5cad31bfc771d3261d1eead8e31856c19eb5e74
/publishTool/assembleTest_D05_7.py
3bf657b7e122eea1a22d8512b50fc9ff0a277b9e
[]
no_license
alpha0080/mayaTool
61b649825d85b88de2d24e9260e23f5c5aa559cb
153da6e987d13fb7311ee55a2a3e635bc8c7afde
refs/heads/master
2021-01-19T11:52:03.715437
2018-05-07T10:30:23
2018-05-07T10:30:23
88,001,018
0
0
null
null
null
null
BIG5
Python
false
false
190,588
py
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'C:/Users/alpha.DESKTOP-1S1STEK/Documents/GitHub/mayaTool/publishTool/assembleTest_B01.ui' # # Created: Thu Jul 06 16:28:26 2017 # by: pyside2-uic running on PySide2 2.0.0~alpha0 # # WARNING! All changes made in this file will be lost! from PySide2 import QtCore, QtGui, QtWidgets import maya.cmds as cmds import pymel.core as pm import json import os #from pprint import pprint import datetime class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(650, 860) MainWindow.setMinimumSize(QtCore.QSize(650, 860)) palette = QtGui.QPalette() brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(41, 61, 55)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Button, brush) brush = QtGui.QBrush(QtGui.QColor(61, 91, 82)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Light, brush) brush = QtGui.QBrush(QtGui.QColor(51, 76, 68)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Midlight, brush) brush = QtGui.QBrush(QtGui.QColor(20, 30, 27)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Dark, brush) brush = QtGui.QBrush(QtGui.QColor(27, 40, 36)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Mid, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.BrightText, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ButtonText, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush) brush = QtGui.QBrush(QtGui.QColor(41, 61, 55)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Shadow, brush) brush = QtGui.QBrush(QtGui.QColor(20, 30, 27)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.AlternateBase, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 220)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ToolTipBase, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ToolTipText, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(41, 61, 55)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Button, brush) brush = QtGui.QBrush(QtGui.QColor(61, 91, 82)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Light, brush) brush = QtGui.QBrush(QtGui.QColor(51, 76, 68)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Midlight, brush) brush = QtGui.QBrush(QtGui.QColor(20, 30, 27)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Dark, brush) brush = QtGui.QBrush(QtGui.QColor(27, 40, 36)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Mid, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.BrightText, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ButtonText, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush) brush = QtGui.QBrush(QtGui.QColor(41, 61, 55)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Shadow, brush) brush = QtGui.QBrush(QtGui.QColor(20, 30, 27)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.AlternateBase, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 220)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ToolTipBase, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ToolTipText, brush) brush = QtGui.QBrush(QtGui.QColor(20, 30, 27)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(41, 61, 55)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Button, brush) brush = QtGui.QBrush(QtGui.QColor(61, 91, 82)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Light, brush) brush = QtGui.QBrush(QtGui.QColor(51, 76, 68)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Midlight, brush) brush = QtGui.QBrush(QtGui.QColor(20, 30, 27)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Dark, brush) brush = QtGui.QBrush(QtGui.QColor(27, 40, 36)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Mid, brush) brush = QtGui.QBrush(QtGui.QColor(20, 30, 27)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.BrightText, brush) brush = QtGui.QBrush(QtGui.QColor(20, 30, 27)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText, brush) brush = QtGui.QBrush(QtGui.QColor(41, 61, 55)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush) brush = QtGui.QBrush(QtGui.QColor(41, 61, 55)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Shadow, brush) brush = QtGui.QBrush(QtGui.QColor(41, 61, 55)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.AlternateBase, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 220)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ToolTipBase, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ToolTipText, brush) MainWindow.setPalette(palette) MainWindow.setAutoFillBackground(False) self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.frame_21 = QtWidgets.QFrame(self.centralwidget) self.frame_21.setGeometry(QtCore.QRect(590, 31, 56, 56)) palette = QtGui.QPalette() brush = QtGui.QBrush(QtGui.QColor(185, 198, 185)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(81, 121, 109)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Button, brush) brush = QtGui.QBrush(QtGui.QColor(121, 182, 164)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Light, brush) brush = QtGui.QBrush(QtGui.QColor(101, 151, 136)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Midlight, brush) brush = QtGui.QBrush(QtGui.QColor(40, 60, 54)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Dark, brush) brush = QtGui.QBrush(QtGui.QColor(54, 80, 72)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Mid, brush) brush = QtGui.QBrush(QtGui.QColor(185, 198, 185)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.BrightText, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ButtonText, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush) brush = QtGui.QBrush(QtGui.QColor(81, 121, 109)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Shadow, brush) brush = QtGui.QBrush(QtGui.QColor(40, 60, 54)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.AlternateBase, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 220)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ToolTipBase, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ToolTipText, brush) brush = QtGui.QBrush(QtGui.QColor(185, 198, 185)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(81, 121, 109)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Button, brush) brush = QtGui.QBrush(QtGui.QColor(121, 182, 164)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Light, brush) brush = QtGui.QBrush(QtGui.QColor(101, 151, 136)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Midlight, brush) brush = QtGui.QBrush(QtGui.QColor(40, 60, 54)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Dark, brush) brush = QtGui.QBrush(QtGui.QColor(54, 80, 72)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Mid, brush) brush = QtGui.QBrush(QtGui.QColor(185, 198, 185)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.BrightText, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ButtonText, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush) brush = QtGui.QBrush(QtGui.QColor(81, 121, 109)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Shadow, brush) brush = QtGui.QBrush(QtGui.QColor(40, 60, 54)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.AlternateBase, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 220)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ToolTipBase, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ToolTipText, brush) brush = QtGui.QBrush(QtGui.QColor(40, 60, 54)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(81, 121, 109)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Button, brush) brush = QtGui.QBrush(QtGui.QColor(121, 182, 164)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Light, brush) brush = QtGui.QBrush(QtGui.QColor(101, 151, 136)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Midlight, brush) brush = QtGui.QBrush(QtGui.QColor(40, 60, 54)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Dark, brush) brush = QtGui.QBrush(QtGui.QColor(54, 80, 72)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Mid, brush) brush = QtGui.QBrush(QtGui.QColor(40, 60, 54)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.BrightText, brush) brush = QtGui.QBrush(QtGui.QColor(40, 60, 54)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText, brush) brush = QtGui.QBrush(QtGui.QColor(81, 121, 109)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush) brush = QtGui.QBrush(QtGui.QColor(81, 121, 109)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Shadow, brush) brush = QtGui.QBrush(QtGui.QColor(81, 121, 109)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.AlternateBase, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 220)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ToolTipBase, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ToolTipText, brush) self.frame_21.setPalette(palette) self.frame_21.setFrameShape(QtWidgets.QFrame.Box) self.frame_21.setFrameShadow(QtWidgets.QFrame.Raised) self.frame_21.setLineWidth(1) self.frame_21.setMidLineWidth(0) self.frame_21.setObjectName("frame_21") self.pushButton_P3_changePageA = QtWidgets.QPushButton(self.frame_21) self.pushButton_P3_changePageA.setEnabled(True) self.pushButton_P3_changePageA.setGeometry(QtCore.QRect(2, 3, 25, 25)) self.pushButton_P3_changePageA.setText("") icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/connerA.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.pushButton_P3_changePageA.setIcon(icon) self.pushButton_P3_changePageA.setIconSize(QtCore.QSize(25, 25)) self.pushButton_P3_changePageA.setCheckable(True) self.pushButton_P3_changePageA.setAutoDefault(False) self.pushButton_P3_changePageA.setDefault(False) self.pushButton_P3_changePageA.setFlat(True) self.pushButton_P3_changePageA.setObjectName("pushButton_P3_changePageA") self.pushButton_P3_changePageB = QtWidgets.QPushButton(self.frame_21) self.pushButton_P3_changePageB.setEnabled(True) self.pushButton_P3_changePageB.setGeometry(QtCore.QRect(27, 3, 25, 25)) self.pushButton_P3_changePageB.setText("") icon1 = QtGui.QIcon() icon1.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/connerB.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.pushButton_P3_changePageB.setIcon(icon1) self.pushButton_P3_changePageB.setIconSize(QtCore.QSize(25, 25)) self.pushButton_P3_changePageB.setCheckable(True) self.pushButton_P3_changePageB.setAutoDefault(False) self.pushButton_P3_changePageB.setDefault(False) self.pushButton_P3_changePageB.setFlat(True) self.pushButton_P3_changePageB.setObjectName("pushButton_P3_changePageB") self.pushButton_P3_changePageC = QtWidgets.QPushButton(self.frame_21) self.pushButton_P3_changePageC.setEnabled(True) self.pushButton_P3_changePageC.setGeometry(QtCore.QRect(2, 28, 25, 25)) self.pushButton_P3_changePageC.setText("") icon2 = QtGui.QIcon() icon2.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/connerC.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.pushButton_P3_changePageC.setIcon(icon2) self.pushButton_P3_changePageC.setIconSize(QtCore.QSize(25, 25)) self.pushButton_P3_changePageC.setCheckable(True) self.pushButton_P3_changePageC.setAutoDefault(False) self.pushButton_P3_changePageC.setDefault(False) self.pushButton_P3_changePageC.setFlat(True) self.pushButton_P3_changePageC.setObjectName("pushButton_P3_changePageC") self.pushButton_P3_changePageD = QtWidgets.QPushButton(self.frame_21) self.pushButton_P3_changePageD.setEnabled(True) self.pushButton_P3_changePageD.setGeometry(QtCore.QRect(27, 28, 25, 25)) self.pushButton_P3_changePageD.setText("") icon3 = QtGui.QIcon() icon3.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/connerD.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.pushButton_P3_changePageD.setIcon(icon3) self.pushButton_P3_changePageD.setIconSize(QtCore.QSize(25, 25)) self.pushButton_P3_changePageD.setCheckable(True) self.pushButton_P3_changePageD.setAutoDefault(False) self.pushButton_P3_changePageD.setDefault(False) self.pushButton_P3_changePageD.setFlat(True) self.pushButton_P3_changePageD.setObjectName("pushButton_P3_changePageD") self.frame_5 = QtWidgets.QFrame(self.centralwidget) self.frame_5.setGeometry(QtCore.QRect(435, 32, 151, 56)) palette = QtGui.QPalette() brush = QtGui.QBrush(QtGui.QColor(185, 198, 185)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(81, 121, 109)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Button, brush) brush = QtGui.QBrush(QtGui.QColor(121, 182, 164)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Light, brush) brush = QtGui.QBrush(QtGui.QColor(101, 151, 136)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Midlight, brush) brush = QtGui.QBrush(QtGui.QColor(40, 60, 54)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Dark, brush) brush = QtGui.QBrush(QtGui.QColor(54, 80, 72)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Mid, brush) brush = QtGui.QBrush(QtGui.QColor(185, 198, 185)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.BrightText, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ButtonText, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush) brush = QtGui.QBrush(QtGui.QColor(81, 121, 109)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Shadow, brush) brush = QtGui.QBrush(QtGui.QColor(40, 60, 54)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.AlternateBase, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 220)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ToolTipBase, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ToolTipText, brush) brush = QtGui.QBrush(QtGui.QColor(185, 198, 185)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(81, 121, 109)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Button, brush) brush = QtGui.QBrush(QtGui.QColor(121, 182, 164)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Light, brush) brush = QtGui.QBrush(QtGui.QColor(101, 151, 136)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Midlight, brush) brush = QtGui.QBrush(QtGui.QColor(40, 60, 54)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Dark, brush) brush = QtGui.QBrush(QtGui.QColor(54, 80, 72)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Mid, brush) brush = QtGui.QBrush(QtGui.QColor(185, 198, 185)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.BrightText, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ButtonText, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush) brush = QtGui.QBrush(QtGui.QColor(81, 121, 109)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Shadow, brush) brush = QtGui.QBrush(QtGui.QColor(40, 60, 54)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.AlternateBase, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 220)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ToolTipBase, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ToolTipText, brush) brush = QtGui.QBrush(QtGui.QColor(40, 60, 54)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(81, 121, 109)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Button, brush) brush = QtGui.QBrush(QtGui.QColor(121, 182, 164)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Light, brush) brush = QtGui.QBrush(QtGui.QColor(101, 151, 136)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Midlight, brush) brush = QtGui.QBrush(QtGui.QColor(40, 60, 54)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Dark, brush) brush = QtGui.QBrush(QtGui.QColor(54, 80, 72)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Mid, brush) brush = QtGui.QBrush(QtGui.QColor(40, 60, 54)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.BrightText, brush) brush = QtGui.QBrush(QtGui.QColor(40, 60, 54)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText, brush) brush = QtGui.QBrush(QtGui.QColor(81, 121, 109)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush) brush = QtGui.QBrush(QtGui.QColor(81, 121, 109)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Shadow, brush) brush = QtGui.QBrush(QtGui.QColor(81, 121, 109)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.AlternateBase, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 220)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ToolTipBase, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ToolTipText, brush) self.frame_5.setPalette(palette) self.frame_5.setFrameShape(QtWidgets.QFrame.Box) self.frame_5.setFrameShadow(QtWidgets.QFrame.Raised) self.frame_5.setLineWidth(1) self.frame_5.setMidLineWidth(0) self.frame_5.setObjectName("frame_5") self.label_fileData_19 = QtWidgets.QLabel(self.frame_5) self.label_fileData_19.setGeometry(QtCore.QRect(50, 0, 20, 20)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(8) self.label_fileData_19.setFont(font) self.label_fileData_19.setAlignment(QtCore.Qt.AlignCenter) self.label_fileData_19.setObjectName("label_fileData_19") self.label_fileData_20 = QtWidgets.QLabel(self.frame_5) self.label_fileData_20.setGeometry(QtCore.QRect(15, 0, 20, 20)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(8) self.label_fileData_20.setFont(font) self.label_fileData_20.setAlignment(QtCore.Qt.AlignCenter) self.label_fileData_20.setObjectName("label_fileData_20") self.label_fileData_21 = QtWidgets.QLabel(self.frame_5) self.label_fileData_21.setGeometry(QtCore.QRect(85, 0, 20, 20)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(8) self.label_fileData_21.setFont(font) self.label_fileData_21.setAlignment(QtCore.Qt.AlignCenter) self.label_fileData_21.setObjectName("label_fileData_21") self.label_fileData_22 = QtWidgets.QLabel(self.frame_5) self.label_fileData_22.setGeometry(QtCore.QRect(120, 0, 20, 20)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(8) self.label_fileData_22.setFont(font) self.label_fileData_22.setAlignment(QtCore.Qt.AlignCenter) self.label_fileData_22.setObjectName("label_fileData_22") self.pushButton_P3_largeIcon = QtWidgets.QPushButton(self.frame_5) self.pushButton_P3_largeIcon.setEnabled(True) self.pushButton_P3_largeIcon.setGeometry(QtCore.QRect(10, 20, 30, 30)) palette = QtGui.QPalette() brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ButtonText, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ButtonText, brush) brush = QtGui.QBrush(QtGui.QColor(120, 120, 120)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(120, 120, 120)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(120, 120, 120)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText, brush) self.pushButton_P3_largeIcon.setPalette(palette) self.pushButton_P3_largeIcon.setAutoFillBackground(False) self.pushButton_P3_largeIcon.setText("") icon4 = QtGui.QIcon() icon4.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/sizeChoose_Large_Close.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) icon4.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/sizeChooseLarge.png"), QtGui.QIcon.Normal, QtGui.QIcon.On) icon4.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/sizeChooseLarge.png"), QtGui.QIcon.Selected, QtGui.QIcon.On) icon4.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/sizeChooseLarge.png"), QtGui.QIcon.Disabled, QtGui.QIcon.On) self.pushButton_P3_largeIcon.setIcon(icon4) self.pushButton_P3_largeIcon.setIconSize(QtCore.QSize(30, 30)) self.pushButton_P3_largeIcon.setCheckable(True) self.pushButton_P3_largeIcon.setChecked(False) self.pushButton_P3_largeIcon.setAutoRepeat(False) self.pushButton_P3_largeIcon.setAutoExclusive(False) self.pushButton_P3_largeIcon.setAutoDefault(False) self.pushButton_P3_largeIcon.setDefault(False) self.pushButton_P3_largeIcon.setFlat(True) self.pushButton_P3_largeIcon.setObjectName("pushButton_P3_largeIcon") self.pushButton_P3_MidIcon = QtWidgets.QPushButton(self.frame_5) self.pushButton_P3_MidIcon.setEnabled(True) self.pushButton_P3_MidIcon.setGeometry(QtCore.QRect(45, 20, 30, 30)) palette = QtGui.QPalette() brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ButtonText, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ButtonText, brush) brush = QtGui.QBrush(QtGui.QColor(120, 120, 120)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(120, 120, 120)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(120, 120, 120)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText, brush) self.pushButton_P3_MidIcon.setPalette(palette) self.pushButton_P3_MidIcon.setAutoFillBackground(False) self.pushButton_P3_MidIcon.setText("") icon5 = QtGui.QIcon() icon5.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/sizeChoose_Mid_Close.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) icon5.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/sizeChooseMid.png"), QtGui.QIcon.Normal, QtGui.QIcon.On) icon5.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/sizeChooseMid.png"), QtGui.QIcon.Active, QtGui.QIcon.On) icon5.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/sizeChooseMid.png"), QtGui.QIcon.Selected, QtGui.QIcon.On) icon5.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/sizeChooseMid.png"), QtGui.QIcon.Disabled, QtGui.QIcon.On) self.pushButton_P3_MidIcon.setIcon(icon5) self.pushButton_P3_MidIcon.setIconSize(QtCore.QSize(30, 30)) self.pushButton_P3_MidIcon.setCheckable(True) self.pushButton_P3_MidIcon.setChecked(False) self.pushButton_P3_MidIcon.setAutoRepeat(False) self.pushButton_P3_MidIcon.setAutoExclusive(False) self.pushButton_P3_MidIcon.setAutoDefault(False) self.pushButton_P3_MidIcon.setDefault(False) self.pushButton_P3_MidIcon.setFlat(True) self.pushButton_P3_MidIcon.setObjectName("pushButton_P3_MidIcon") self.pushButton_P3_smallIcon = QtWidgets.QPushButton(self.frame_5) self.pushButton_P3_smallIcon.setEnabled(True) self.pushButton_P3_smallIcon.setGeometry(QtCore.QRect(80, 20, 30, 30)) palette = QtGui.QPalette() brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ButtonText, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ButtonText, brush) brush = QtGui.QBrush(QtGui.QColor(120, 120, 120)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(120, 120, 120)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(120, 120, 120)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText, brush) self.pushButton_P3_smallIcon.setPalette(palette) self.pushButton_P3_smallIcon.setAutoFillBackground(False) self.pushButton_P3_smallIcon.setText("") icon6 = QtGui.QIcon() icon6.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/sizeChoose_Small_Close.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) icon6.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/sizeChooseSmall.png"), QtGui.QIcon.Normal, QtGui.QIcon.On) icon6.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/sizeChooseSmall.png"), QtGui.QIcon.Active, QtGui.QIcon.On) icon6.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/sizeChooseSmall.png"), QtGui.QIcon.Selected, QtGui.QIcon.On) icon6.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/sizeChooseSmall.png"), QtGui.QIcon.Disabled, QtGui.QIcon.On) self.pushButton_P3_smallIcon.setIcon(icon6) self.pushButton_P3_smallIcon.setIconSize(QtCore.QSize(30, 30)) self.pushButton_P3_smallIcon.setCheckable(True) self.pushButton_P3_smallIcon.setChecked(False) self.pushButton_P3_smallIcon.setAutoRepeat(False) self.pushButton_P3_smallIcon.setAutoExclusive(False) self.pushButton_P3_smallIcon.setAutoDefault(False) self.pushButton_P3_smallIcon.setDefault(False) self.pushButton_P3_smallIcon.setFlat(True) self.pushButton_P3_smallIcon.setObjectName("pushButton_P3_smallIcon") self.pushButton_P3_text = QtWidgets.QPushButton(self.frame_5) self.pushButton_P3_text.setEnabled(True) self.pushButton_P3_text.setGeometry(QtCore.QRect(115, 20, 30, 30)) palette = QtGui.QPalette() brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ButtonText, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ButtonText, brush) brush = QtGui.QBrush(QtGui.QColor(120, 120, 120)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(120, 120, 120)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(120, 120, 120)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText, brush) self.pushButton_P3_text.setPalette(palette) self.pushButton_P3_text.setAutoFillBackground(False) self.pushButton_P3_text.setText("") icon7 = QtGui.QIcon() icon7.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/sizeChoose_Text_Close.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) icon7.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/sizeChooseText.png"), QtGui.QIcon.Normal, QtGui.QIcon.On) icon7.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/sizeChooseText.png"), QtGui.QIcon.Selected, QtGui.QIcon.On) icon7.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/sizeChooseText.png"), QtGui.QIcon.Disabled, QtGui.QIcon.On) self.pushButton_P3_text.setIcon(icon7) self.pushButton_P3_text.setIconSize(QtCore.QSize(30, 30)) self.pushButton_P3_text.setCheckable(True) self.pushButton_P3_text.setChecked(False) self.pushButton_P3_text.setAutoRepeat(False) self.pushButton_P3_text.setAutoExclusive(False) self.pushButton_P3_text.setAutoDefault(False) self.pushButton_P3_text.setDefault(False) self.pushButton_P3_text.setFlat(True) self.pushButton_P3_text.setObjectName("pushButton_P3_text") self.frame_6 = QtWidgets.QFrame(self.centralwidget) self.frame_6.setGeometry(QtCore.QRect(5, 32, 221, 56)) palette = QtGui.QPalette() brush = QtGui.QBrush(QtGui.QColor(185, 198, 185)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(81, 121, 109)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Button, brush) brush = QtGui.QBrush(QtGui.QColor(121, 182, 164)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Light, brush) brush = QtGui.QBrush(QtGui.QColor(101, 151, 136)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Midlight, brush) brush = QtGui.QBrush(QtGui.QColor(40, 60, 54)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Dark, brush) brush = QtGui.QBrush(QtGui.QColor(54, 80, 72)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Mid, brush) brush = QtGui.QBrush(QtGui.QColor(185, 198, 185)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.BrightText, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ButtonText, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush) brush = QtGui.QBrush(QtGui.QColor(81, 121, 109)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Shadow, brush) brush = QtGui.QBrush(QtGui.QColor(40, 60, 54)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.AlternateBase, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 220)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ToolTipBase, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ToolTipText, brush) brush = QtGui.QBrush(QtGui.QColor(185, 198, 185)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(81, 121, 109)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Button, brush) brush = QtGui.QBrush(QtGui.QColor(121, 182, 164)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Light, brush) brush = QtGui.QBrush(QtGui.QColor(101, 151, 136)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Midlight, brush) brush = QtGui.QBrush(QtGui.QColor(40, 60, 54)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Dark, brush) brush = QtGui.QBrush(QtGui.QColor(54, 80, 72)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Mid, brush) brush = QtGui.QBrush(QtGui.QColor(185, 198, 185)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.BrightText, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ButtonText, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush) brush = QtGui.QBrush(QtGui.QColor(81, 121, 109)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Shadow, brush) brush = QtGui.QBrush(QtGui.QColor(40, 60, 54)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.AlternateBase, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 220)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ToolTipBase, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ToolTipText, brush) brush = QtGui.QBrush(QtGui.QColor(40, 60, 54)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(81, 121, 109)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Button, brush) brush = QtGui.QBrush(QtGui.QColor(121, 182, 164)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Light, brush) brush = QtGui.QBrush(QtGui.QColor(101, 151, 136)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Midlight, brush) brush = QtGui.QBrush(QtGui.QColor(40, 60, 54)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Dark, brush) brush = QtGui.QBrush(QtGui.QColor(54, 80, 72)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Mid, brush) brush = QtGui.QBrush(QtGui.QColor(40, 60, 54)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.BrightText, brush) brush = QtGui.QBrush(QtGui.QColor(40, 60, 54)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText, brush) brush = QtGui.QBrush(QtGui.QColor(81, 121, 109)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush) brush = QtGui.QBrush(QtGui.QColor(81, 121, 109)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Shadow, brush) brush = QtGui.QBrush(QtGui.QColor(81, 121, 109)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.AlternateBase, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 220)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ToolTipBase, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ToolTipText, brush) self.frame_6.setPalette(palette) self.frame_6.setFrameShape(QtWidgets.QFrame.Box) self.frame_6.setFrameShadow(QtWidgets.QFrame.Raised) self.frame_6.setLineWidth(1) self.frame_6.setMidLineWidth(0) self.frame_6.setObjectName("frame_6") self.pushButton_P3_deletSelectItem = QtWidgets.QPushButton(self.frame_6) self.pushButton_P3_deletSelectItem.setGeometry(QtCore.QRect(150, 20, 30, 30)) self.pushButton_P3_deletSelectItem.setText("") icon8 = QtGui.QIcon() icon8.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/deletePublishB.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.pushButton_P3_deletSelectItem.setIcon(icon8) self.pushButton_P3_deletSelectItem.setIconSize(QtCore.QSize(30, 30)) self.pushButton_P3_deletSelectItem.setFlat(True) self.pushButton_P3_deletSelectItem.setObjectName("pushButton_P3_deletSelectItem") self.pushButton_P3_selectItem = QtWidgets.QPushButton(self.frame_6) self.pushButton_P3_selectItem.setGeometry(QtCore.QRect(50, 15, 35, 35)) self.pushButton_P3_selectItem.setText("") icon9 = QtGui.QIcon() icon9.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/getSelectItemPublishB.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.pushButton_P3_selectItem.setIcon(icon9) self.pushButton_P3_selectItem.setIconSize(QtCore.QSize(35, 35)) self.pushButton_P3_selectItem.setFlat(True) self.pushButton_P3_selectItem.setObjectName("pushButton_P3_selectItem") self.label_fileData_43 = QtWidgets.QLabel(self.frame_6) self.label_fileData_43.setGeometry(QtCore.QRect(145, 0, 46, 20)) palette = QtGui.QPalette() brush = QtGui.QBrush(QtGui.QColor(248, 255, 235)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(248, 255, 235)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(85, 127, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush) self.label_fileData_43.setPalette(palette) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(8) self.label_fileData_43.setFont(font) self.label_fileData_43.setAlignment(QtCore.Qt.AlignCenter) self.label_fileData_43.setObjectName("label_fileData_43") self.label_fileData_40 = QtWidgets.QLabel(self.frame_6) self.label_fileData_40.setGeometry(QtCore.QRect(45, -3, 46, 20)) palette = QtGui.QPalette() brush = QtGui.QBrush(QtGui.QColor(248, 255, 235)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(248, 255, 235)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(85, 127, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush) self.label_fileData_40.setPalette(palette) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(8) self.label_fileData_40.setFont(font) self.label_fileData_40.setAlignment(QtCore.Qt.AlignCenter) self.label_fileData_40.setObjectName("label_fileData_40") self.pushButton_P3_refreshInputItem = QtWidgets.QPushButton(self.frame_6) self.pushButton_P3_refreshInputItem.setGeometry(QtCore.QRect(5, 15, 35, 35)) self.pushButton_P3_refreshInputItem.setText("") icon10 = QtGui.QIcon() icon10.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/refreshPublishB.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.pushButton_P3_refreshInputItem.setIcon(icon10) self.pushButton_P3_refreshInputItem.setIconSize(QtCore.QSize(35, 35)) self.pushButton_P3_refreshInputItem.setFlat(True) self.pushButton_P3_refreshInputItem.setObjectName("pushButton_P3_refreshInputItem") self.label_fileData_39 = QtWidgets.QLabel(self.frame_6) self.label_fileData_39.setGeometry(QtCore.QRect(0, -3, 46, 20)) palette = QtGui.QPalette() brush = QtGui.QBrush(QtGui.QColor(248, 255, 235)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(248, 255, 235)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(85, 127, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush) self.label_fileData_39.setPalette(palette) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(8) self.label_fileData_39.setFont(font) self.label_fileData_39.setAlignment(QtCore.Qt.AlignCenter) self.label_fileData_39.setObjectName("label_fileData_39") self.frame_8 = QtWidgets.QFrame(self.centralwidget) self.frame_8.setGeometry(QtCore.QRect(609, 90, 36, 531)) palette = QtGui.QPalette() brush = QtGui.QBrush(QtGui.QColor(185, 198, 185)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(81, 121, 109)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Button, brush) brush = QtGui.QBrush(QtGui.QColor(121, 182, 164)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Light, brush) brush = QtGui.QBrush(QtGui.QColor(101, 151, 136)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Midlight, brush) brush = QtGui.QBrush(QtGui.QColor(40, 60, 54)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Dark, brush) brush = QtGui.QBrush(QtGui.QColor(54, 80, 72)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Mid, brush) brush = QtGui.QBrush(QtGui.QColor(185, 198, 185)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.BrightText, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ButtonText, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush) brush = QtGui.QBrush(QtGui.QColor(81, 121, 109)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Shadow, brush) brush = QtGui.QBrush(QtGui.QColor(40, 60, 54)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.AlternateBase, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 220)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ToolTipBase, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ToolTipText, brush) brush = QtGui.QBrush(QtGui.QColor(185, 198, 185)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(81, 121, 109)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Button, brush) brush = QtGui.QBrush(QtGui.QColor(121, 182, 164)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Light, brush) brush = QtGui.QBrush(QtGui.QColor(101, 151, 136)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Midlight, brush) brush = QtGui.QBrush(QtGui.QColor(40, 60, 54)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Dark, brush) brush = QtGui.QBrush(QtGui.QColor(54, 80, 72)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Mid, brush) brush = QtGui.QBrush(QtGui.QColor(185, 198, 185)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.BrightText, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ButtonText, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush) brush = QtGui.QBrush(QtGui.QColor(81, 121, 109)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Shadow, brush) brush = QtGui.QBrush(QtGui.QColor(40, 60, 54)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.AlternateBase, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 220)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ToolTipBase, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ToolTipText, brush) brush = QtGui.QBrush(QtGui.QColor(40, 60, 54)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(81, 121, 109)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Button, brush) brush = QtGui.QBrush(QtGui.QColor(121, 182, 164)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Light, brush) brush = QtGui.QBrush(QtGui.QColor(101, 151, 136)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Midlight, brush) brush = QtGui.QBrush(QtGui.QColor(40, 60, 54)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Dark, brush) brush = QtGui.QBrush(QtGui.QColor(54, 80, 72)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Mid, brush) brush = QtGui.QBrush(QtGui.QColor(40, 60, 54)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.BrightText, brush) brush = QtGui.QBrush(QtGui.QColor(40, 60, 54)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText, brush) brush = QtGui.QBrush(QtGui.QColor(81, 121, 109)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush) brush = QtGui.QBrush(QtGui.QColor(81, 121, 109)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Shadow, brush) brush = QtGui.QBrush(QtGui.QColor(81, 121, 109)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.AlternateBase, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 220)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ToolTipBase, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ToolTipText, brush) self.frame_8.setPalette(palette) self.frame_8.setFrameShape(QtWidgets.QFrame.Box) self.frame_8.setFrameShadow(QtWidgets.QFrame.Raised) self.frame_8.setLineWidth(1) self.frame_8.setMidLineWidth(0) self.frame_8.setObjectName("frame_8") self.pushButton_P3_openBranchJson = QtWidgets.QPushButton(self.frame_8) self.pushButton_P3_openBranchJson.setEnabled(True) self.pushButton_P3_openBranchJson.setGeometry(QtCore.QRect(3, 472, 25, 25)) self.pushButton_P3_openBranchJson.setText("") icon11 = QtGui.QIcon() icon11.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/option2-512.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.pushButton_P3_openBranchJson.setIcon(icon11) self.pushButton_P3_openBranchJson.setIconSize(QtCore.QSize(25, 25)) self.pushButton_P3_openBranchJson.setCheckable(True) self.pushButton_P3_openBranchJson.setAutoDefault(False) self.pushButton_P3_openBranchJson.setDefault(False) self.pushButton_P3_openBranchJson.setFlat(True) self.pushButton_P3_openBranchJson.setObjectName("pushButton_P3_openBranchJson") self.pushButton_P3_loadFile = QtWidgets.QPushButton(self.frame_8) self.pushButton_P3_loadFile.setEnabled(True) self.pushButton_P3_loadFile.setGeometry(QtCore.QRect(3, 440, 25, 25)) self.pushButton_P3_loadFile.setText("") icon12 = QtGui.QIcon() icon12.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/load60.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.pushButton_P3_loadFile.setIcon(icon12) self.pushButton_P3_loadFile.setIconSize(QtCore.QSize(27, 25)) self.pushButton_P3_loadFile.setCheckable(True) self.pushButton_P3_loadFile.setAutoDefault(False) self.pushButton_P3_loadFile.setDefault(False) self.pushButton_P3_loadFile.setFlat(True) self.pushButton_P3_loadFile.setObjectName("pushButton_P3_loadFile") self.pushButton_P3_processModeling = QtWidgets.QPushButton(self.frame_8) self.pushButton_P3_processModeling.setEnabled(True) self.pushButton_P3_processModeling.setGeometry(QtCore.QRect(5, 5, 25, 25)) self.pushButton_P3_processModeling.setText("") icon13 = QtGui.QIcon() icon13.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/processMod_C_OFF.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) icon13.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/processMod_C_ON.png"), QtGui.QIcon.Normal, QtGui.QIcon.On) icon13.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/processMod_C_OFF.png"), QtGui.QIcon.Disabled, QtGui.QIcon.Off) icon13.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/processMod_C_ON.png"), QtGui.QIcon.Selected, QtGui.QIcon.On) icon13.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/processMod_C_OFF.png"), QtGui.QIcon.Disabled, QtGui.QIcon.On) self.pushButton_P3_processModeling.setIcon(icon13) self.pushButton_P3_processModeling.setIconSize(QtCore.QSize(25, 25)) self.pushButton_P3_processModeling.setCheckable(True) self.pushButton_P3_processModeling.setAutoDefault(False) self.pushButton_P3_processModeling.setDefault(False) self.pushButton_P3_processModeling.setFlat(True) self.pushButton_P3_processModeling.setObjectName("pushButton_P3_processModeling") self.pushButton_P3_processTexture = QtWidgets.QPushButton(self.frame_8) self.pushButton_P3_processTexture.setEnabled(True) self.pushButton_P3_processTexture.setGeometry(QtCore.QRect(5, 31, 25, 25)) self.pushButton_P3_processTexture.setText("") icon14 = QtGui.QIcon() icon14.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/processTex_C_ON.png"), QtGui.QIcon.Normal, QtGui.QIcon.On) icon14.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/processText_C_OFF.png"), QtGui.QIcon.Disabled, QtGui.QIcon.On) icon14.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/processText_C_OFF.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) icon14.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/processText_C_OFF.png"), QtGui.QIcon.Selected, QtGui.QIcon.Off) icon14.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/processText_C_OFF.png"), QtGui.QIcon.Disabled, QtGui.QIcon.Off) icon14.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/processTex_C_ON.png"), QtGui.QIcon.Selected, QtGui.QIcon.On) icon14.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/processTex_C_ON.png"), QtGui.QIcon.Active, QtGui.QIcon.On) self.pushButton_P3_processTexture.setIcon(icon14) self.pushButton_P3_processTexture.setIconSize(QtCore.QSize(25, 25)) self.pushButton_P3_processTexture.setCheckable(True) self.pushButton_P3_processTexture.setAutoDefault(False) self.pushButton_P3_processTexture.setDefault(False) self.pushButton_P3_processTexture.setFlat(True) self.pushButton_P3_processTexture.setObjectName("pushButton_P3_processTexture") self.pushButton_P3_processRigging = QtWidgets.QPushButton(self.frame_8) self.pushButton_P3_processRigging.setEnabled(True) self.pushButton_P3_processRigging.setGeometry(QtCore.QRect(5, 57, 25, 25)) self.pushButton_P3_processRigging.setText("") icon15 = QtGui.QIcon() icon15.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/processRig_C_ON.png"), QtGui.QIcon.Normal, QtGui.QIcon.On) icon15.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/processRig_C_OFF.png"), QtGui.QIcon.Disabled, QtGui.QIcon.On) icon15.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/processRig_C_OFF.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) icon15.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/processRig_C_OFF.png"), QtGui.QIcon.Selected, QtGui.QIcon.Off) icon15.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/processRig_C_OFF.png"), QtGui.QIcon.Disabled, QtGui.QIcon.Off) icon15.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/processRig_C_ON.png"), QtGui.QIcon.Selected, QtGui.QIcon.On) self.pushButton_P3_processRigging.setIcon(icon15) self.pushButton_P3_processRigging.setIconSize(QtCore.QSize(25, 25)) self.pushButton_P3_processRigging.setCheckable(True) self.pushButton_P3_processRigging.setAutoDefault(False) self.pushButton_P3_processRigging.setDefault(False) self.pushButton_P3_processRigging.setFlat(True) self.pushButton_P3_processRigging.setObjectName("pushButton_P3_processRigging") self.pushButton_P3_inputMayaOn = QtWidgets.QPushButton(self.frame_8) self.pushButton_P3_inputMayaOn.setEnabled(True) self.pushButton_P3_inputMayaOn.setGeometry(QtCore.QRect(3, 230, 25, 25)) palette = QtGui.QPalette() brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ButtonText, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ButtonText, brush) brush = QtGui.QBrush(QtGui.QColor(120, 120, 120)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(120, 120, 120)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(120, 120, 120)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText, brush) self.pushButton_P3_inputMayaOn.setPalette(palette) self.pushButton_P3_inputMayaOn.setAutoFillBackground(False) self.pushButton_P3_inputMayaOn.setText("") icon16 = QtGui.QIcon() icon16.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/InputOption_Maya_ON.png"), QtGui.QIcon.Normal, QtGui.QIcon.On) icon16.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/InputOption_maya_Off.png"), QtGui.QIcon.Active, QtGui.QIcon.Off) icon16.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/InputOption_maya_Off.png"), QtGui.QIcon.Selected, QtGui.QIcon.Off) icon16.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/InputOption_maya_Off.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) icon16.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/InputOption_Maya_ON.png"), QtGui.QIcon.Disabled, QtGui.QIcon.On) icon16.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/InputOption_maya_Off.png"), QtGui.QIcon.Disabled, QtGui.QIcon.Off) icon16.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/InputOption_Maya_ON.png"), QtGui.QIcon.Selected, QtGui.QIcon.On) icon16.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/InputOption_Maya_ON.png"), QtGui.QIcon.Active, QtGui.QIcon.On) self.pushButton_P3_inputMayaOn.setIcon(icon16) self.pushButton_P3_inputMayaOn.setIconSize(QtCore.QSize(25, 25)) self.pushButton_P3_inputMayaOn.setCheckable(True) self.pushButton_P3_inputMayaOn.setChecked(False) self.pushButton_P3_inputMayaOn.setAutoRepeat(False) self.pushButton_P3_inputMayaOn.setAutoExclusive(False) self.pushButton_P3_inputMayaOn.setAutoDefault(False) self.pushButton_P3_inputMayaOn.setDefault(False) self.pushButton_P3_inputMayaOn.setFlat(True) self.pushButton_P3_inputMayaOn.setObjectName("pushButton_P3_inputMayaOn") self.pushButton_P3_inputRibOn = QtWidgets.QPushButton(self.frame_8) self.pushButton_P3_inputRibOn.setEnabled(True) self.pushButton_P3_inputRibOn.setGeometry(QtCore.QRect(3, 265, 25, 25)) palette = QtGui.QPalette() brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ButtonText, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ButtonText, brush) brush = QtGui.QBrush(QtGui.QColor(120, 120, 120)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(120, 120, 120)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(120, 120, 120)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText, brush) self.pushButton_P3_inputRibOn.setPalette(palette) self.pushButton_P3_inputRibOn.setAutoFillBackground(False) self.pushButton_P3_inputRibOn.setText("") icon17 = QtGui.QIcon() icon17.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/InputOptionRIB_On.png"), QtGui.QIcon.Normal, QtGui.QIcon.On) icon17.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/InputOption_Rib_Off.png"), QtGui.QIcon.Active, QtGui.QIcon.Off) icon17.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/InputOption_Rib_Off.png"), QtGui.QIcon.Selected, QtGui.QIcon.Off) icon17.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/InputOption_Rib_Off.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) icon17.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/InputOptionRIB_On.png"), QtGui.QIcon.Disabled, QtGui.QIcon.On) icon17.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/InputOption_Rib_Off.png"), QtGui.QIcon.Disabled, QtGui.QIcon.Off) icon17.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/InputOptionRIB_On.png"), QtGui.QIcon.Selected, QtGui.QIcon.On) icon17.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/InputOptionRIB_On.png"), QtGui.QIcon.Active, QtGui.QIcon.On) self.pushButton_P3_inputRibOn.setIcon(icon17) self.pushButton_P3_inputRibOn.setIconSize(QtCore.QSize(25, 25)) self.pushButton_P3_inputRibOn.setCheckable(True) self.pushButton_P3_inputRibOn.setChecked(False) self.pushButton_P3_inputRibOn.setAutoRepeat(False) self.pushButton_P3_inputRibOn.setAutoExclusive(False) self.pushButton_P3_inputRibOn.setAutoDefault(False) self.pushButton_P3_inputRibOn.setDefault(False) self.pushButton_P3_inputRibOn.setFlat(True) self.pushButton_P3_inputRibOn.setObjectName("pushButton_P3_inputRibOn") self.pushButton_P3_NA = QtWidgets.QPushButton(self.frame_8) self.pushButton_P3_NA.setEnabled(True) self.pushButton_P3_NA.setGeometry(QtCore.QRect(5, 83, 25, 25)) self.pushButton_P3_NA.setText("") icon18 = QtGui.QIcon() icon18.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/processNA_C_ON.png"), QtGui.QIcon.Normal, QtGui.QIcon.On) icon18.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/processNA_C_OFF.png"), QtGui.QIcon.Disabled, QtGui.QIcon.On) icon18.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/processNA_C_OFF.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) icon18.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/processNA_C_OFF.png"), QtGui.QIcon.Selected, QtGui.QIcon.Off) icon18.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/processNA_C_OFF.png"), QtGui.QIcon.Disabled, QtGui.QIcon.Off) icon18.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/processNA_C_ON.png"), QtGui.QIcon.Selected, QtGui.QIcon.On) self.pushButton_P3_NA.setIcon(icon18) self.pushButton_P3_NA.setIconSize(QtCore.QSize(25, 25)) self.pushButton_P3_NA.setCheckable(True) self.pushButton_P3_NA.setAutoDefault(False) self.pushButton_P3_NA.setDefault(False) self.pushButton_P3_NA.setFlat(True) self.pushButton_P3_NA.setObjectName("pushButton_P3_NA") self.pushButton_P3_packageAll = QtWidgets.QPushButton(self.frame_8) self.pushButton_P3_packageAll.setGeometry(QtCore.QRect(3, 501, 25, 25)) self.pushButton_P3_packageAll.setText("") icon19 = QtGui.QIcon() icon19.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/package.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.pushButton_P3_packageAll.setIcon(icon19) self.pushButton_P3_packageAll.setIconSize(QtCore.QSize(25, 25)) self.pushButton_P3_packageAll.setFlat(True) self.pushButton_P3_packageAll.setObjectName("pushButton_P3_packageAll") self.comboBox = QtWidgets.QComboBox(self.centralwidget) self.comboBox.setGeometry(QtCore.QRect(360, 5, 286, 22)) palette = QtGui.QPalette() brush = QtGui.QBrush(QtGui.QColor(19, 29, 26)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Button, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush) brush = QtGui.QBrush(QtGui.QColor(14, 21, 19)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush) brush = QtGui.QBrush(QtGui.QColor(19, 29, 26)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Button, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush) brush = QtGui.QBrush(QtGui.QColor(14, 21, 19)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush) brush = QtGui.QBrush(QtGui.QColor(19, 29, 26)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Button, brush) brush = QtGui.QBrush(QtGui.QColor(14, 21, 19)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush) brush = QtGui.QBrush(QtGui.QColor(14, 21, 19)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush) self.comboBox.setPalette(palette) self.comboBox.setObjectName("comboBox") self.comboBox.addItem("") self.frame_11 = QtWidgets.QFrame(self.centralwidget) self.frame_11.setGeometry(QtCore.QRect(227, 32, 206, 56)) palette = QtGui.QPalette() brush = QtGui.QBrush(QtGui.QColor(185, 198, 185)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(81, 121, 109)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Button, brush) brush = QtGui.QBrush(QtGui.QColor(121, 182, 164)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Light, brush) brush = QtGui.QBrush(QtGui.QColor(101, 151, 136)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Midlight, brush) brush = QtGui.QBrush(QtGui.QColor(40, 60, 54)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Dark, brush) brush = QtGui.QBrush(QtGui.QColor(54, 80, 72)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Mid, brush) brush = QtGui.QBrush(QtGui.QColor(185, 198, 185)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.BrightText, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ButtonText, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush) brush = QtGui.QBrush(QtGui.QColor(81, 121, 109)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Shadow, brush) brush = QtGui.QBrush(QtGui.QColor(40, 60, 54)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.AlternateBase, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 220)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ToolTipBase, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ToolTipText, brush) brush = QtGui.QBrush(QtGui.QColor(185, 198, 185)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(81, 121, 109)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Button, brush) brush = QtGui.QBrush(QtGui.QColor(121, 182, 164)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Light, brush) brush = QtGui.QBrush(QtGui.QColor(101, 151, 136)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Midlight, brush) brush = QtGui.QBrush(QtGui.QColor(40, 60, 54)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Dark, brush) brush = QtGui.QBrush(QtGui.QColor(54, 80, 72)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Mid, brush) brush = QtGui.QBrush(QtGui.QColor(185, 198, 185)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.BrightText, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ButtonText, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush) brush = QtGui.QBrush(QtGui.QColor(81, 121, 109)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Shadow, brush) brush = QtGui.QBrush(QtGui.QColor(40, 60, 54)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.AlternateBase, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 220)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ToolTipBase, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ToolTipText, brush) brush = QtGui.QBrush(QtGui.QColor(40, 60, 54)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(81, 121, 109)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Button, brush) brush = QtGui.QBrush(QtGui.QColor(121, 182, 164)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Light, brush) brush = QtGui.QBrush(QtGui.QColor(101, 151, 136)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Midlight, brush) brush = QtGui.QBrush(QtGui.QColor(40, 60, 54)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Dark, brush) brush = QtGui.QBrush(QtGui.QColor(54, 80, 72)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Mid, brush) brush = QtGui.QBrush(QtGui.QColor(40, 60, 54)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.BrightText, brush) brush = QtGui.QBrush(QtGui.QColor(40, 60, 54)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText, brush) brush = QtGui.QBrush(QtGui.QColor(81, 121, 109)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush) brush = QtGui.QBrush(QtGui.QColor(81, 121, 109)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Shadow, brush) brush = QtGui.QBrush(QtGui.QColor(81, 121, 109)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.AlternateBase, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 220)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ToolTipBase, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ToolTipText, brush) self.frame_11.setPalette(palette) self.frame_11.setFrameShape(QtWidgets.QFrame.Box) self.frame_11.setFrameShadow(QtWidgets.QFrame.Raised) self.frame_11.setLineWidth(1) self.frame_11.setMidLineWidth(0) self.frame_11.setObjectName("frame_11") self.pushButton_page3_other = QtWidgets.QPushButton(self.frame_11) self.pushButton_page3_other.setEnabled(True) self.pushButton_page3_other.setGeometry(QtCore.QRect(170, 20, 30, 30)) self.pushButton_page3_other.setText("") icon20 = QtGui.QIcon() icon20.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/assetType_other_ON.png"), QtGui.QIcon.Normal, QtGui.QIcon.On) icon20.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/assetType_other_OFF.png"), QtGui.QIcon.Disabled, QtGui.QIcon.On) icon20.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/assetType_other_OFF.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) icon20.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/assetType_other_OFF.png"), QtGui.QIcon.Selected, QtGui.QIcon.Off) icon20.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/assetType_other_OFF.png"), QtGui.QIcon.Disabled, QtGui.QIcon.Off) icon20.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/assetType_other_ON.png"), QtGui.QIcon.Selected, QtGui.QIcon.On) self.pushButton_page3_other.setIcon(icon20) self.pushButton_page3_other.setIconSize(QtCore.QSize(30, 30)) self.pushButton_page3_other.setCheckable(True) self.pushButton_page3_other.setAutoDefault(False) self.pushButton_page3_other.setDefault(False) self.pushButton_page3_other.setFlat(True) self.pushButton_page3_other.setObjectName("pushButton_page3_other") self.pushButton_page3_vehicle = QtWidgets.QPushButton(self.frame_11) self.pushButton_page3_vehicle.setEnabled(True) self.pushButton_page3_vehicle.setGeometry(QtCore.QRect(77, 20, 30, 30)) self.pushButton_page3_vehicle.setText("") icon21 = QtGui.QIcon() icon21.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/assetType_veh_ON.png"), QtGui.QIcon.Normal, QtGui.QIcon.On) icon21.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/assetType_veh_OFF.png"), QtGui.QIcon.Active, QtGui.QIcon.Off) icon21.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/assetType_veh_OFF.png"), QtGui.QIcon.Selected, QtGui.QIcon.Off) icon21.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/assetType_veh_OFF.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) icon21.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/assetType_veh_OFF.png"), QtGui.QIcon.Disabled, QtGui.QIcon.On) icon21.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/assetType_veh_OFF.png"), QtGui.QIcon.Disabled, QtGui.QIcon.Off) icon21.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/assetType_veh_ON.png"), QtGui.QIcon.Selected, QtGui.QIcon.On) icon21.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/assetType_veh_ON.png"), QtGui.QIcon.Active, QtGui.QIcon.On) self.pushButton_page3_vehicle.setIcon(icon21) self.pushButton_page3_vehicle.setIconSize(QtCore.QSize(30, 30)) self.pushButton_page3_vehicle.setCheckable(True) self.pushButton_page3_vehicle.setAutoDefault(False) self.pushButton_page3_vehicle.setDefault(False) self.pushButton_page3_vehicle.setFlat(True) self.pushButton_page3_vehicle.setObjectName("pushButton_page3_vehicle") self.pushButton_page3_all = QtWidgets.QPushButton(self.frame_11) self.pushButton_page3_all.setEnabled(True) self.pushButton_page3_all.setGeometry(QtCore.QRect(10, 20, 30, 30)) self.pushButton_page3_all.setText("") icon22 = QtGui.QIcon() icon22.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/assetType_all_ON.png"), QtGui.QIcon.Normal, QtGui.QIcon.On) icon22.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/assetType_all_OFF.png"), QtGui.QIcon.Disabled, QtGui.QIcon.On) icon22.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/assetType_all_OFF.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) icon22.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/assetType_all_OFF.png"), QtGui.QIcon.Selected, QtGui.QIcon.Off) icon22.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/assetType_all_OFF.png"), QtGui.QIcon.Disabled, QtGui.QIcon.Off) icon22.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/assetType_all_ON.png"), QtGui.QIcon.Selected, QtGui.QIcon.On) self.pushButton_page3_all.setIcon(icon22) self.pushButton_page3_all.setIconSize(QtCore.QSize(30, 30)) self.pushButton_page3_all.setCheckable(True) self.pushButton_page3_all.setAutoDefault(False) self.pushButton_page3_all.setDefault(False) self.pushButton_page3_all.setFlat(True) self.pushButton_page3_all.setObjectName("pushButton_page3_all") self.pushButton_page3_props = QtWidgets.QPushButton(self.frame_11) self.pushButton_page3_props.setEnabled(True) self.pushButton_page3_props.setGeometry(QtCore.QRect(139, 20, 30, 30)) self.pushButton_page3_props.setText("") icon23 = QtGui.QIcon() icon23.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/assetType_prop_ON.png"), QtGui.QIcon.Normal, QtGui.QIcon.On) icon23.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/assetType_prop_OFF.png"), QtGui.QIcon.Disabled, QtGui.QIcon.On) icon23.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/assetType_prop_OFF.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) icon23.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/assetType_prop_OFF.png"), QtGui.QIcon.Selected, QtGui.QIcon.Off) icon23.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/assetType_prop_OFF.png"), QtGui.QIcon.Disabled, QtGui.QIcon.Off) icon23.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/assetType_prop_ON.png"), QtGui.QIcon.Selected, QtGui.QIcon.On) self.pushButton_page3_props.setIcon(icon23) self.pushButton_page3_props.setIconSize(QtCore.QSize(30, 30)) self.pushButton_page3_props.setCheckable(True) self.pushButton_page3_props.setAutoDefault(False) self.pushButton_page3_props.setDefault(False) self.pushButton_page3_props.setFlat(True) self.pushButton_page3_props.setObjectName("pushButton_page3_props") self.pushButton_page3_character = QtWidgets.QPushButton(self.frame_11) self.pushButton_page3_character.setEnabled(True) self.pushButton_page3_character.setGeometry(QtCore.QRect(46, 20, 30, 30)) palette = QtGui.QPalette() brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ButtonText, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ButtonText, brush) brush = QtGui.QBrush(QtGui.QColor(120, 120, 120)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(120, 120, 120)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(120, 120, 120)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText, brush) self.pushButton_page3_character.setPalette(palette) self.pushButton_page3_character.setAutoFillBackground(False) self.pushButton_page3_character.setText("") icon24 = QtGui.QIcon() icon24.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/assetType_cha_ON.png"), QtGui.QIcon.Normal, QtGui.QIcon.On) icon24.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/assetType_cha_OFF.png"), QtGui.QIcon.Active, QtGui.QIcon.Off) icon24.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/assetType_cha_OFF.png"), QtGui.QIcon.Selected, QtGui.QIcon.Off) icon24.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/assetType_cha_OFF.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) icon24.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/assetType_cha_OFF.png"), QtGui.QIcon.Disabled, QtGui.QIcon.On) icon24.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/assetType_cha_OFF.png"), QtGui.QIcon.Disabled, QtGui.QIcon.Off) icon24.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/assetType_cha_ON.png"), QtGui.QIcon.Selected, QtGui.QIcon.On) icon24.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/assetType_cha_ON.png"), QtGui.QIcon.Active, QtGui.QIcon.On) self.pushButton_page3_character.setIcon(icon24) self.pushButton_page3_character.setIconSize(QtCore.QSize(30, 30)) self.pushButton_page3_character.setCheckable(True) self.pushButton_page3_character.setChecked(False) self.pushButton_page3_character.setAutoRepeat(False) self.pushButton_page3_character.setAutoExclusive(False) self.pushButton_page3_character.setAutoDefault(False) self.pushButton_page3_character.setDefault(False) self.pushButton_page3_character.setFlat(True) self.pushButton_page3_character.setObjectName("pushButton_page3_character") self.pushButton_page3_set = QtWidgets.QPushButton(self.frame_11) self.pushButton_page3_set.setEnabled(True) self.pushButton_page3_set.setGeometry(QtCore.QRect(108, 20, 30, 30)) self.pushButton_page3_set.setText("") icon25 = QtGui.QIcon() icon25.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/assetType_set_OFF.png"), QtGui.QIcon.Disabled, QtGui.QIcon.On) icon25.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/assetType_set_OFF.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) icon25.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/assetType_set_OFF.png"), QtGui.QIcon.Selected, QtGui.QIcon.Off) icon25.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/assetType_set_OFF.png"), QtGui.QIcon.Disabled, QtGui.QIcon.Off) icon25.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/assetType_set_ON.png"), QtGui.QIcon.Selected, QtGui.QIcon.On) icon25.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/assetType_set_ON.png"), QtGui.QIcon.Active, QtGui.QIcon.On) self.pushButton_page3_set.setIcon(icon25) self.pushButton_page3_set.setIconSize(QtCore.QSize(30, 30)) self.pushButton_page3_set.setCheckable(True) self.pushButton_page3_set.setAutoDefault(False) self.pushButton_page3_set.setDefault(False) self.pushButton_page3_set.setFlat(True) self.pushButton_page3_set.setObjectName("pushButton_page3_set") self.plainTextEdit_assetMetaData = QtWidgets.QPlainTextEdit(self.centralwidget) self.plainTextEdit_assetMetaData.setGeometry(QtCore.QRect(226, 625, 381, 210)) self.plainTextEdit_assetMetaData.setObjectName("plainTextEdit_assetMetaData") self.tableWidget_AssetItemList = QtWidgets.QTableWidget(self.centralwidget) self.tableWidget_AssetItemList.setGeometry(QtCore.QRect(226, 90, 381, 530)) self.tableWidget_AssetItemList.setLayoutDirection(QtCore.Qt.LeftToRight) self.tableWidget_AssetItemList.setInputMethodHints(QtCore.Qt.ImhNone) self.tableWidget_AssetItemList.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn) self.tableWidget_AssetItemList.setDragEnabled(True) self.tableWidget_AssetItemList.setDragDropMode(QtWidgets.QAbstractItemView.DragOnly) self.tableWidget_AssetItemList.setSelectionMode(QtWidgets.QAbstractItemView.SingleSelection) self.tableWidget_AssetItemList.setIconSize(QtCore.QSize(60, 60)) self.tableWidget_AssetItemList.setTextElideMode(QtCore.Qt.ElideNone) self.tableWidget_AssetItemList.setRowCount(2) self.tableWidget_AssetItemList.setColumnCount(2) self.tableWidget_AssetItemList.setObjectName("tableWidget_AssetItemList") self.tableWidget_AssetItemList.setColumnCount(2) self.tableWidget_AssetItemList.setRowCount(2) item = QtWidgets.QTableWidgetItem() self.tableWidget_AssetItemList.setItem(0, 0, item) item = QtWidgets.QTableWidgetItem() self.tableWidget_AssetItemList.setItem(0, 1, item) item = QtWidgets.QTableWidgetItem() self.tableWidget_AssetItemList.setItem(1, 0, item) item = QtWidgets.QTableWidgetItem() self.tableWidget_AssetItemList.setItem(1, 1, item) self.tableWidget_AssetItemList.horizontalHeader().setVisible(False) self.tableWidget_AssetItemList.horizontalHeader().setCascadingSectionResizes(False) self.tableWidget_AssetItemList.horizontalHeader().setDefaultSectionSize(120) self.tableWidget_AssetItemList.horizontalHeader().setMinimumSectionSize(25) self.tableWidget_AssetItemList.horizontalHeader().setSortIndicatorShown(False) self.tableWidget_AssetItemList.horizontalHeader().setStretchLastSection(False) self.tableWidget_AssetItemList.verticalHeader().setVisible(False) self.tableWidget_AssetItemList.verticalHeader().setCascadingSectionResizes(False) self.tableWidget_AssetItemList.verticalHeader().setDefaultSectionSize(120) self.tableWidget_AssetItemList.verticalHeader().setHighlightSections(True) self.tableWidget_AssetItemList.verticalHeader().setMinimumSectionSize(25) self.frame_7 = QtWidgets.QFrame(self.centralwidget) self.frame_7.setGeometry(QtCore.QRect(5, 625, 220, 210)) palette = QtGui.QPalette() brush = QtGui.QBrush(QtGui.QColor(185, 198, 185)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(81, 121, 109)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Button, brush) brush = QtGui.QBrush(QtGui.QColor(121, 182, 164)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Light, brush) brush = QtGui.QBrush(QtGui.QColor(101, 151, 136)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Midlight, brush) brush = QtGui.QBrush(QtGui.QColor(40, 60, 54)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Dark, brush) brush = QtGui.QBrush(QtGui.QColor(54, 80, 72)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Mid, brush) brush = QtGui.QBrush(QtGui.QColor(185, 198, 185)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.BrightText, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ButtonText, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush) brush = QtGui.QBrush(QtGui.QColor(81, 121, 109)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Shadow, brush) brush = QtGui.QBrush(QtGui.QColor(40, 60, 54)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.AlternateBase, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 220)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ToolTipBase, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ToolTipText, brush) brush = QtGui.QBrush(QtGui.QColor(185, 198, 185)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(81, 121, 109)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Button, brush) brush = QtGui.QBrush(QtGui.QColor(121, 182, 164)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Light, brush) brush = QtGui.QBrush(QtGui.QColor(101, 151, 136)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Midlight, brush) brush = QtGui.QBrush(QtGui.QColor(40, 60, 54)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Dark, brush) brush = QtGui.QBrush(QtGui.QColor(54, 80, 72)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Mid, brush) brush = QtGui.QBrush(QtGui.QColor(185, 198, 185)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.BrightText, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ButtonText, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush) brush = QtGui.QBrush(QtGui.QColor(81, 121, 109)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Shadow, brush) brush = QtGui.QBrush(QtGui.QColor(40, 60, 54)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.AlternateBase, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 220)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ToolTipBase, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ToolTipText, brush) brush = QtGui.QBrush(QtGui.QColor(40, 60, 54)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(81, 121, 109)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Button, brush) brush = QtGui.QBrush(QtGui.QColor(121, 182, 164)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Light, brush) brush = QtGui.QBrush(QtGui.QColor(101, 151, 136)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Midlight, brush) brush = QtGui.QBrush(QtGui.QColor(40, 60, 54)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Dark, brush) brush = QtGui.QBrush(QtGui.QColor(54, 80, 72)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Mid, brush) brush = QtGui.QBrush(QtGui.QColor(40, 60, 54)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.BrightText, brush) brush = QtGui.QBrush(QtGui.QColor(40, 60, 54)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText, brush) brush = QtGui.QBrush(QtGui.QColor(81, 121, 109)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush) brush = QtGui.QBrush(QtGui.QColor(81, 121, 109)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Shadow, brush) brush = QtGui.QBrush(QtGui.QColor(81, 121, 109)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.AlternateBase, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 220)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ToolTipBase, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ToolTipText, brush) self.frame_7.setPalette(palette) self.frame_7.setFrameShape(QtWidgets.QFrame.Box) self.frame_7.setFrameShadow(QtWidgets.QFrame.Raised) self.frame_7.setLineWidth(1) self.frame_7.setMidLineWidth(0) self.frame_7.setObjectName("frame_7") self.label_showImage_2 = QtWidgets.QLabel(self.frame_7) self.label_showImage_2.setGeometry(QtCore.QRect(10, 0, 211, 191)) self.label_showImage_2.setText("") self.label_showImage_2.setPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/picture-01-150.png")) self.label_showImage_2.setObjectName("label_showImage_2") self.pushButton_P3addItemToLeftA = QtWidgets.QPushButton(self.centralwidget) self.pushButton_P3addItemToLeftA.setGeometry(QtCore.QRect(205, 90, 20, 60)) self.pushButton_P3addItemToLeftA.setText("") icon26 = QtGui.QIcon() icon26.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/addToLeftA.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.pushButton_P3addItemToLeftA.setIcon(icon26) self.pushButton_P3addItemToLeftA.setIconSize(QtCore.QSize(30, 120)) self.pushButton_P3addItemToLeftA.setFlat(True) self.pushButton_P3addItemToLeftA.setObjectName("pushButton_P3addItemToLeftA") self.pushButton_P3addItemToLeftB = QtWidgets.QPushButton(self.centralwidget) self.pushButton_P3addItemToLeftB.setGeometry(QtCore.QRect(205, 151, 20, 60)) self.pushButton_P3addItemToLeftB.setText("") icon27 = QtGui.QIcon() icon27.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/addToLeftB.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.pushButton_P3addItemToLeftB.setIcon(icon27) self.pushButton_P3addItemToLeftB.setIconSize(QtCore.QSize(25, 120)) self.pushButton_P3addItemToLeftB.setFlat(True) self.pushButton_P3addItemToLeftB.setObjectName("pushButton_P3addItemToLeftB") self.pushButton_P3addItemToLeftC = QtWidgets.QPushButton(self.centralwidget) self.pushButton_P3addItemToLeftC.setGeometry(QtCore.QRect(205, 212, 20, 60)) self.pushButton_P3addItemToLeftC.setText("") icon28 = QtGui.QIcon() icon28.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/addToLeftC.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.pushButton_P3addItemToLeftC.setIcon(icon28) self.pushButton_P3addItemToLeftC.setIconSize(QtCore.QSize(25, 120)) self.pushButton_P3addItemToLeftC.setFlat(True) self.pushButton_P3addItemToLeftC.setObjectName("pushButton_P3addItemToLeftC") self.pushButton_P3_addItem = QtWidgets.QPushButton(self.centralwidget) self.pushButton_P3_addItem.setGeometry(QtCore.QRect(205, 499, 20, 60)) self.pushButton_P3_addItem.setText("") icon29 = QtGui.QIcon() icon29.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/addB.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.pushButton_P3_addItem.setIcon(icon29) self.pushButton_P3_addItem.setIconSize(QtCore.QSize(20, 80)) self.pushButton_P3_addItem.setFlat(True) self.pushButton_P3_addItem.setObjectName("pushButton_P3_addItem") self.pushButton_P3_deleteItem = QtWidgets.QPushButton(self.centralwidget) self.pushButton_P3_deleteItem.setGeometry(QtCore.QRect(205, 560, 20, 60)) self.pushButton_P3_deleteItem.setText("") icon30 = QtGui.QIcon() icon30.addPixmap(QtGui.QPixmap("//mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/deleteB.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.pushButton_P3_deleteItem.setIcon(icon30) self.pushButton_P3_deleteItem.setIconSize(QtCore.QSize(20, 80)) self.pushButton_P3_deleteItem.setFlat(True) self.pushButton_P3_deleteItem.setObjectName("pushButton_P3_deleteItem") self.pushButton_P3_aux1 = QtWidgets.QPushButton(self.centralwidget) self.pushButton_P3_aux1.setGeometry(QtCore.QRect(205, 273, 20, 60)) self.pushButton_P3_aux1.setText("") self.pushButton_P3_aux1.setIcon(icon29) self.pushButton_P3_aux1.setIconSize(QtCore.QSize(20, 80)) self.pushButton_P3_aux1.setFlat(True) self.pushButton_P3_aux1.setObjectName("pushButton_P3_aux1") self.pushButton_P3_aux2 = QtWidgets.QPushButton(self.centralwidget) self.pushButton_P3_aux2.setGeometry(QtCore.QRect(205, 334, 20, 60)) self.pushButton_P3_aux2.setText("") self.pushButton_P3_aux2.setIcon(icon29) self.pushButton_P3_aux2.setIconSize(QtCore.QSize(20, 80)) self.pushButton_P3_aux2.setFlat(True) self.pushButton_P3_aux2.setObjectName("pushButton_P3_aux2") self.pushButton_P3_aux3 = QtWidgets.QPushButton(self.centralwidget) self.pushButton_P3_aux3.setGeometry(QtCore.QRect(205, 395, 20, 60)) self.pushButton_P3_aux3.setText("") self.pushButton_P3_aux3.setIcon(icon29) self.pushButton_P3_aux3.setIconSize(QtCore.QSize(20, 80)) self.pushButton_P3_aux3.setFlat(True) self.pushButton_P3_aux3.setObjectName("pushButton_P3_aux3") MainWindow.setCentralWidget(self.centralwidget) self.statusbar = QtWidgets.QStatusBar(MainWindow) self.statusbar.setObjectName("statusbar") MainWindow.setStatusBar(self.statusbar) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): MainWindow.setWindowTitle(QtWidgets.QApplication.translate("MainWindow", "MainWindow", None, -1)) self.label_fileData_19.setText(QtWidgets.QApplication.translate("MainWindow", "M", None, -1)) self.label_fileData_20.setText(QtWidgets.QApplication.translate("MainWindow", "L", None, -1)) self.label_fileData_21.setText(QtWidgets.QApplication.translate("MainWindow", "S", None, -1)) self.label_fileData_22.setText(QtWidgets.QApplication.translate("MainWindow", "T", None, -1)) self.label_fileData_43.setText(QtWidgets.QApplication.translate("MainWindow", "Delete", None, -1)) self.label_fileData_40.setText(QtWidgets.QApplication.translate("MainWindow", "Select", None, -1)) self.label_fileData_39.setText(QtWidgets.QApplication.translate("MainWindow", "Refresh", None, -1)) self.comboBox.setItemText(0, QtWidgets.QApplication.translate("MainWindow", "Select Asset Pref Table", None, -1)) __sortingEnabled = self.tableWidget_AssetItemList.isSortingEnabled() self.tableWidget_AssetItemList.setSortingEnabled(False) self.tableWidget_AssetItemList.item(0, 0).setText(QtWidgets.QApplication.translate("MainWindow", "a", None, -1)) self.tableWidget_AssetItemList.item(0, 1).setText(QtWidgets.QApplication.translate("MainWindow", "a", None, -1)) self.tableWidget_AssetItemList.item(1, 0).setText(QtWidgets.QApplication.translate("MainWindow", "a", None, -1)) self.tableWidget_AssetItemList.item(1, 1).setText(QtWidgets.QApplication.translate("MainWindow", "a", None, -1)) self.tableWidget_AssetItemList.setSortingEnabled(__sortingEnabled) # item = self.itemAt(event.pos()) #print item # QtWidgets.QTreeWidget.mousePressEvent(self, event) #if event.button() == QtCore.Qt.LeftButton: # print 'press' # selectItem = self.treeWidget_sceneAssembleTree.currentItem() # self.treeWidget_sceneAssembleTree.mousePressEvent(selectItem) # self.treeWidget_sceneAssembleTree.inde QtGui class mod_MainWindow(QtWidgets.QMainWindow, Ui_MainWindow): def __init__(self, parent= QtWidgets.QApplication.activeWindow()): super(mod_MainWindow, self).__init__(parent) #super(MyTreeWidget, self).__init__(parent) # MyTreeWidget.__init__(self) self.setupUi(self) # tree = self.treeWidget_sceneAssembleTree self.treeWidget_sceneAssembleTree = assetTreeInTheWorld(self) #dir( self.setupUi(self)) self.typeListAllowDict = {'transform':[255,255,255], #item list could be move and edit 'mesh':[100,190,70], 'RenderManArchive':[200,100,100], 'gpuCache':[30,230,230], 'moreThanOneItemTheSameName':[255,0,0] } self.topLayerItemIndexDict = {'0':'character', '1':'vehicle', '2':'set', '3':'prop', '4':'other', '5':'effect'} #self.treeWidget_sceneAssembleTree.itemClicked.connect(self.treeItemClick) #self.treeWidget_sceneAssembleTree.itemPressed.connect(self.treeItemClick) # self.pushButton_P3_largeIcon.clicked.connect(self.setLargeAssetIcon) self.pushButton_P3_MidIcon.clicked.connect(self.setMidAssetIcon) self.pushButton_P3_smallIcon.clicked.connect(self.setSmallAssetIcon) self.pushButton_P3_text.clicked.connect(self.setTextAssetMain) self.tableWidget_AssetItemList.itemClicked.connect(self.showAssetMetaDataFromSelect) self.itemDict ={} self.iconFile = QtGui.QIcon("//mcd-one/database/assets/scripts/maya_scripts///mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/NA120ENPTY.png") self.currentIconSize = 'large' #default set to large size icon #self.tableWidget_AssetItemList.setSortingEnabled(True) # self.tableWidget_AssetItemList.pressed.connect(self.dragTest) # drag = QtGui.QDrag(self) # # print'dragTest',drag.mimeData() ## printdrag,type(drag) # initial button checked self.pushButton_page3_all.setChecked(True) self.pushButton_P3_processModeling.setChecked(True) self.pushButton_P3_processTexture.setChecked(True) self.pushButton_P3_processRigging.setChecked(True) self.pushButton_P3_inputMayaOn.setChecked(True) self.pushButton_P3_NA.setChecked(False) self.clickAssetFilletAll() # self.allAssetClassFillet = ['character','vehicle','set','prop','other'] #button click sing self.pushButton_page3_all.clicked.connect(self.clickAssetFilletAll) self.pushButton_page3_character.clicked.connect(self.clickAssetFilletCharacter) self.pushButton_page3_vehicle.clicked.connect(self.clickAssetFilletVehicle) self.pushButton_page3_set.clicked.connect(self.clickAssetFilletSet) self.pushButton_page3_props.clicked.connect(self.clickAssetFilletProps) self.pushButton_page3_other.clicked.connect(self.clickAssetFilletOther) self.pushButton_P3_addItem.clicked.connect(self.addOutlineGroup) self.pushButton_P3_processModeling.clicked.connect(self.clickProcessFilletChange) self.pushButton_P3_processTexture.clicked.connect(self.clickProcessFilletChange) self.pushButton_P3_processRigging.clicked.connect(self.clickProcessFilletChange) self.pushButton_P3_NA.clicked.connect(self.clickProcessFilletChange) self.pushButton_P3_refreshInputItem.clicked.connect(self.reflashOutLinerTree) # self.pushButton_P3addItemToLeftA.clicked.connect(self.runBuildItemLevelTree) # self.pushButton_P3addItemToLeftB.clicked.connect(self.storeOutLineStructure) self.pushButton_P3addItemToLeftC.clicked.connect(self.ttt) ## modify treeWidget_sceneAssembleTree start---------------------------------------------------- #self.treeWidget_sceneAssembleTree.itemChanged.connect(self.itemChangedName) self.treeWidget_sceneAssembleTree.setColumnCount(1) self.treeWidget_sceneAssembleTree.header().setDefaultSectionSize(350) self.treeWidget_sceneAssembleTree.header().setMinimumSectionSize(25) self.storeOutLineStructure() # 整理 self.runBuildItemLevelTree() # 整理 itemCollapsed self.treeWidget_sceneAssembleTree.doubleClicked.connect(self.editItem) # self.treeWidget_sceneAssembleTree.itemEntered.connect(self.asdf) # self.treeWidget_sceneAssembleTree.itemPressed.connect(self.pressTest) self.pushButton_P3_deletSelectItem.clicked.connect(self.deleteSelectTreeItem) self.pushButton_P3_selectItem.clicked.connect(self.selectAssetTreeItem) #self.treeWidget_sceneAssembleTree.dra press ## modify treeWidget_sceneAssembleTree end---------------------------------------------------- self.setFontC() # pressItem = QtWidgets.QTreeWidgetItem(self.treeWidget_sceneAssembleTree) # self.pushButton_P3_packageAll.clicked.connect(self.testTest) ''' class mod_MainWindow(QtWidgets.QMainWindow, Ui_MainWindow): def __init__(self, parent= QtWidgets.QApplication.activeWindow()): super(mod_MainWindow, self).__init__(parent) self.setupUi(self) ''' def selectAssetTreeItem(self) : # print 'selectAssetTreeItem' selectItem = self.treeWidget_sceneAssembleTree.selectItems() print selectItem cmds.select(cl=True) for i in selectItem: print i cmds.select(i,tgl=True) ''' if self.treeWidget_sceneAssembleTree.indexOfTopLevelItem(selectItem) == -1: selectItemFullNameList = [selectItem.text(0)] while self.treeWidget_sceneAssembleTree.indexOfTopLevelItem(selectItem) == -1: selectItem = selectItem.parent() selectItemFullNameList.append(selectItem.text(0).split('__')[0]) selectItemInOutLiner = '|'.join(reversed(selectItemFullNameList)) else: topLayerItemIndex = self.treeWidget_sceneAssembleTree.indexOfTopLevelItem(selectItem) selectItemInOutLiner = self.topLayerItemIndexDict[str(topLayerItemIndex)] cmds.select(selectItemInOutLiner) ''' def deleteSelectTreeItem(self): selectItem = self.treeWidget_sceneAssembleTree.selectItems() print selectItem for i in selectItem: print i cmds.delete(i) self.reflashOutLinerTree() def getFullName(self,childItem): # print'getFullName' if self.treeWidget_sceneAssembleTree.indexOfTopLevelItem(childItem) == -1: parentItem = childItem.parent() parentItemName = childItem.parent().text(0) self.selectItemFullNameLis.append(parentItemName) else: pass def reflashOutLinerTree(self): # print'reflash tree' self.storeItemDateInDict (3) #self.treeWidget_sceneAssembleTree.clear() self.storeOutLineStructure() self.runBuildItemLevelTree() def runChangeItemName(self): # print'runChangeItemName' try: if self.treeWidget_sceneAssembleTree.currentItem().text(0) == self.newGroupName: pass else: self.itemChangedName() except: pass def treeItemClick(self): # self.treeWidget_sceneAssembleTree = QtWidgets.QTreeWidget(self.frame_9) selectItem = self.treeWidget_sceneAssembleTree.currentItem() # self.treeWidget_sceneAssembleTree.mouseMoveEvent(QtGui.QMouseEvent(selectItem)) # print selectItem #self.treeWidget_sceneAssembleTree. # print selectItem.text(0) # print QtCore.QMimeData(selectItem).text() # print self.treeWidget_sceneAssembleTree.dropMimeData(0,'ef',1,2) # self.treeWidget_sceneAssembleTree.itemChanged.connect(self.itemMove) #PySide2.QtWidgets.QTreeWidget.dropMimeData(PySide2.QtWidgets.QTreeWidgetItem, int, PySide2.QtCore.QMimeData, PySide2.QtCore.Qt.DropAction) # self.dropEvent() #def mouseMoveEvent(self, event): # print 'cc' ''' def mouseMoveEvent(self, event): mimeData = QtCore.QMimeData() mimeData.setText(self.mimeText) drag = QtGui.QDrag(self) drag.setMimeData(mimeData) drag.exec_(QtCore.Qt.CopyAction | QtCore.Qt.MoveAction, QtCore.Qt.CopyAction) # print 'gggg' ''' # self.treeWidget_sceneAssembleTree = QtWidgets.QTreeWidget(self.frame_9) # def mousePressEvent(treeWidget_sceneAssembleTree): # print 'sds' # selectItem = self.treeWidget_sceneAssembleTree.currentItem() # print selectItem.text(0) def itemMove(self): print 'bbbbb' selectItem = self.treeWidget_sceneAssembleTree.currentItem() print selectItem.parent().text(0) def treeItemClickB(self): # print'check 01' # print'treeItemClick' takeItem = self.treeWidget_sceneAssembleTree.currentItem() ## printself.treeWidget_sceneAssembleTree.currentItem().text(0) self.getTreeLocation(takeItem) def getTreeLocation(self,takeItem): # print'check 02' # print'run getTreeLocation' # printtakeItem.text(0)#.currentColumn() getTopLayerIndex = self.treeWidget_sceneAssembleTree.indexOfTopLevelItem(takeItem) # get toplayerIndex if getTopLayerIndex == -1: getParent = takeItem.parent().text(0) else: getParent = 'none' print takeItem.childCount() print getParent #cmds.select('aa4') def runBuildItemLevelTree(self): # print'check 03' # self.storeOutLineStructure() # self.getOutLinerStructure() # print'start to build itemTree' # self.addOutlineGroup() # self.storeOutLineStructure() self.treeWidget_sceneAssembleTree.clear() self.buildDefaultTopLayerItem() # print'build tree' totalIteCount = len(self.allAssetGrpDepthDict.keys()) # get how many items in self.allAssetGrpDepthDict ,獲得outline中所有層級的名稱總數量 self.errorItem = {'character':{'0':[]},'vehicle':{'1':[]},'set':{'2':[]},'prop':{'3':[]},'other':{'4':[]},'effect':{'5':[]}} for i in range(0,totalIteCount): # # printi eachItemFullName = self.allAssetGrpDepthDict.keys()[i] #獲得每個層級group名稱,fullName 完整名稱 eachItemShortName = eachItemFullName.split('|')[-1] eachItemDepthList = self.allAssetGrpDepthDict[self.allAssetGrpDepthDict.keys()[i]] #獲得每個層級group 所對應的層級List eachItemFullDepth = len(eachItemDepthList) #獲得物件所在層級, 每個物件的總層級 topLayerItemIndex = int(eachItemDepthList[0]) topLayerItemSelect = self.treeWidget_sceneAssembleTree.topLevelItem(topLayerItemIndex) parentItem = topLayerItemSelect parentItemForSetName = topLayerItemSelect for depth in range(1,eachItemFullDepth): # # print'depth',depth currentCount = parentItem.childCount() maxCount = int(eachItemDepthList[depth])+1 placeIndex = int(eachItemDepthList[depth]) delta = maxCount - currentCount if delta <= 0: parentItem = parentItem.child(placeIndex) else: self.createChildItem(delta,currentCount,parentItem,eachItemShortName) #try: parentItem = self.childItem.parent().child(placeIndex) #回傳在第幾個分支 moreThanOne = 0 self.checkIsMoreThanOne(eachItemShortName) # # print'moreThanOne',self.moreThanOne # self.defineItemAddress(parentItemForSetName,eachItemDepthList,eachItemShortName,topLayerItemSelect,topLayerItemIndex) # printself.errorItem self.changeTopLayerItemName() def changeTopLayerItemName(self): # print'check 04' for i in range(0,len(self.errorItem.keys())): # printself.errorItem[self.errorItem.keys()[i]]#.keys()[0]#,self.errorItem[self.errorItem.keys()[i]] topLayerItem = self.treeWidget_sceneAssembleTree.topLevelItem(i) errorCount = len(self.errorItem[topLayerItem.text(0)][self.errorItem[topLayerItem.text(0)].keys()[0]]) newTopLayerItemName = topLayerItem.text(0) +'__('+str(errorCount)+')' # printnewTopLayerItemName # # printtopLayerItem.text(0) topLayerItem.setText(0,newTopLayerItemName) #self.treeWidget_sceneAssembleTree.itemChanged.connect(self.itemChangedName) # # printself.errorItem[topLayerItem.text(0)][self.errorItem[topLayerItem.text(0)].keys()[0]] def checkIsMoreThanOne(self,eachItemShortName): # print'check 05' # # print'checkIsMoreThanOne' checkList = cmds.ls(eachItemShortName) # # printcheckList if len(checkList) >1 : self.moreThanOne = 1 else: self.moreThanOne = 0 # return moreThanOne # # printmoreThanOne errorCount def defineItemAddress(self,parentItemForSetName,eachItemDepthList,eachItemShortName,topLayerItemSelect,topLayerItemIndex): #定義物件的位置,如果是有重複名稱的物件會顯示紅色 # print'check 06' depthLength = len(eachItemDepthList) itemSelect = parentItemForSetName for childIndex in range(1,depthLength): itemSelect = itemSelect.child(int(eachItemDepthList[childIndex])) itemSelect.setText(0,eachItemShortName) if self.moreThanOne == 0: pass else: itemTypeColor = self.typeListAllowDict['moreThanOneItemTheSameName'] itemSelect.setForeground(0,QtGui.QBrush(QtGui.QColor(int(itemTypeColor[0]), int(itemTypeColor[1]), int(itemTypeColor[2]))))#.setFont(0,self.fontLevelThree) # # printitemSelect.topLayerItem() # # printself.treeWidget_sceneAssembleTree.topLevelWidget(itemSelect) # # print'topLayerItem',topLayerItemSelect.text(0),topLayerItemIndex self.errorItem[topLayerItemSelect.text(0)][self.errorItem[topLayerItemSelect.text(0)].keys()[0]].append(eachItemShortName) def buildDefaultTopLayerItem(self): # print'check 07' defaultTopLayerItem = ['character','vehicle','set','prop','other','effect'] for i in defaultTopLayerItem: #itemName = defaultTopLayerItem[i] topLayerItem = QtWidgets.QTreeWidgetItem(self.treeWidget_sceneAssembleTree) topLayerItem.setFlags(QtCore.Qt.ItemIsSelectable|QtCore.Qt.ItemIsDropEnabled|QtCore.Qt.ItemIsUserCheckable|QtCore.Qt.ItemIsEnabled) topLayerItem.setText(0,'%s'%i) def createChildItem(self,delta,currentCount,parentItem,eachItemShortName): # maxCount 為該層級需要創建幾個物件 # print'check 08' for i in range(0,delta): self.childItem = QtWidgets.QTreeWidgetItem(parentItem) self.childItem.setText(0,eachItemShortName) def getOutLinerStructure(self,searchAsset): # print'check 09' tempBuildDefaultGrpList = [] tempBuildDefaultGrpList.append(searchAsset) countList= [] allInTransformGrp = cmds.listRelatives(searchAsset, children=True, pa=True,ad=True) if allInTransformGrp == None: pass else: for j in allInTransformGrp: grpLingName = cmds.ls(j,l=True)[0] tempBuildDefaultGrpList.append(grpLingName) countList.append(len(grpLingName.split('|'))) maxDepth = sorted(countList)[-1]-1 elementEveryLevelCount = {} itemHierarchy = {} depthDict = {} for i in range(0, maxDepth): depthDict.update({i:{}}) for i in range(1,maxDepth): elementEveryLevelCount.update({i:[]}) allItemReleationShipDist = {} refChildDict = {} for i in tempBuildDefaultGrpList: refChild = cmds.listRelatives(i, children=True, pa=True,ad=0) refChildList = [] try: refMaxCount= len(refChild) for j in range(0,refMaxCount): indexOfItem = refChild[j].split('|')[-1]+'.'+str(j) refChildList.append(indexOfItem) objNodeType = cmds.nodeType(refChild[j]) self.itemLevelDict.update({refChild[j].split('|')[-1]:[str(j),objNodeType]}) refChildDict.update({i.split('|')[-1]:refChildList}) except: refMaxCount = 'none' refChildDict.update({i.split('|')[-1]:'None'}) refParent = cmds.listRelatives(i, children=True, p=True,ad=0) refChildSerNum = [] def getItemStructure(self,searchAsset,assetIndex): # print'check 10' allItemInTopLayerItem = cmds.listRelatives(searchAsset, children=True, pa=True,ad=True,f=True) for i in allItemInTopLayerItem: tempItemLevelList = [assetIndex] #check i not in except list nodeTypeExceptList= ['joint','airField','nucleus','vortexField','turbulenceField','pointEmitter','dragField','gravityField','newtonField','uniformField','volumeAxisField'] if i in nodeTypeExceptList: pass else: for j in i.split('|'): try: getPartDepthLevel = self.itemLevelDict[j][0] #get index of each depth level #itemLevelDict tempItemLevelList.append(str(getPartDepthLevel)) except: pass self.allAssetGrpDepthDict.update({i:tempItemLevelList}) def storeOutLineStructure(self): # print'check 12' # # print'aaaa' self.itemLevelDict = {} #create empty itemLevelDict ,item dictionary self.allAssetGrpDepthDict = {} #create empty dict, that reference group depth and index to each item and grp self.defaultAssetBuildDict = {'character':'0','vehicle':'1','set':'2','prop':'3','other':'4','effect':'5'} for i in self.defaultAssetBuildDict: try: self.getOutLinerStructure(i) ## printi except: pass # print'itemLevelDict',self.itemLevelDict for i in self.defaultAssetBuildDict.keys(): try: self.getItemStructure(i,self.defaultAssetBuildDict[i]) except: pass # print'self.allAssetGrpDepthDict', self.allAssetGrpDepthDict def getOutLinerStructure(self,searchAsset): # print'check 13' tempBuildDefaultGrpList = [] tempBuildDefaultGrpList.append(searchAsset) countList= [] allInTransformGrp = cmds.listRelatives(searchAsset, children=True, pa=True,ad=True) if allInTransformGrp == None: pass else: for j in allInTransformGrp: grpLingName = cmds.ls(j,l=True)[0] tempBuildDefaultGrpList.append(grpLingName) # # printgrpLingName countList.append(len(grpLingName.split('|'))) maxDepth = sorted(countList)[-1]-1 # # print'maxDepth',maxDepth elementEveryLevelCount = {} itemHierarchy = {} depthDict = {} for i in range(0, maxDepth): depthDict.update({i:{}}) ## printdepthDict for i in range(1,maxDepth): elementEveryLevelCount.update({i:[]}) allItemReleationShipDist = {} #for i in tempBuildDefaultGrpList: # # printi refChildDict = {} for i in tempBuildDefaultGrpList: # # printi #chaList = i.split('|') refChild = cmds.listRelatives(i, children=True, pa=True,ad=0) ## print'refChild',refChild,type(refChild) refChildList = [] try: refMaxCount= len(refChild) # # print'refMaxCount',refMaxCount for j in range(0,refMaxCount): indexOfItem = refChild[j].split('|')[-1]+'.'+str(j) ## printj ,refChild[j] # # printindexOfItem refChildList.append(indexOfItem) objNodeType = cmds.nodeType(refChild[j]) # # printobjNodeType self.itemLevelDict.update({refChild[j].split('|')[-1]:[str(j),objNodeType]}) refChildDict.update({i.split('|')[-1]:refChildList}) except: refMaxCount = 'none' refChildDict.update({i.split('|')[-1]:'None'}) refParent = cmds.listRelatives(i, children=True, p=True,ad=0) refChildSerNum = [] ##--------------get info from maya group structure END --------------------------------------------------------------------------------------------------------------------- def setFontC(self): # print'check 14' self.fontC = QtGui.QFont() self.fontC.setFamily("Calibri") self.fontC.setPointSize(10) self.brushC = QtGui.QBrush(QtGui.QColor(255, 0, 0)) self.brushC.setStyle(QtCore.Qt.NoBrush) def addOutlineGroup(self): # print'check 15' # print'addOutlineGroup' currentSelectItem = self.treeWidget_sceneAssembleTree.currentItem() newItemTheSameNameList = [] for i in cmds.ls(typ= 'transform'): ## printi[0:7] if i[0:7] == 'newItem': # printi newItemTheSameNameList.append(i) # print'newItemTheSameNameList',newItemTheSameNameList newItemTheSameNameCount = len(newItemTheSameNameList) newItemName = 'newItem'+'%04d'%(newItemTheSameNameCount+1) # print'newItemName '+ newItemName # # print'newItemTheSameNameCount', newItemTheSameNameCount # cmd if currentSelectItem.isSelected() == False: # print'create A new Group in TopLayer' allTopLayerCount = int(self.treeWidget_sceneAssembleTree.topLevelItemCount()) # printallTopLayerCount newItem = QtWidgets.QTreeWidgetItem(self.treeWidget_sceneAssembleTree) newItemInOutLine = self.treeWidget_sceneAssembleTree.topLevelItem(allTopLayerCount).setText(0, QtWidgets.QApplication.translate("MainWindow", newItemName, None, -1)) if newItemName not in self.allTopLayerItemsInOutline: cmds.createNode('transform', n=newItemName) self.allTopLayerItemsInOutline.append(newItemName) else: pass #self.allTopLayerItemsInOutline else: # printcurrentSelectItem.text(0) # printself.treeWidget_sceneAssembleTree.indexOfTopLevelItem(currentSelectItem) #get selectItem topLayerIndex if self.treeWidget_sceneAssembleTree.indexOfTopLevelItem(currentSelectItem) == -1: print'currentSelectItem.parent()',currentSelectItem.parent().text(0) else: pass def editItem(self): ## modify item name in tree ,修改物件名稱 doubleClick run # print'check 17' checkTopLayerIndex = self.treeWidget_sceneAssembleTree.indexOfTopLevelItem(self.treeWidget_sceneAssembleTree.currentItem()) if checkTopLayerIndex == -1 : # 檢查是否為第一層物件 item = self.treeWidget_sceneAssembleTree.itemFromIndex(self.treeWidget_sceneAssembleTree.selectedIndexes()[0]) #get select Item Name self.origialGroupName = item.text(0) item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsDragEnabled | QtCore.Qt.ItemIsEditable) # self.newGroupName = self.treeWidget_sceneAssembleTree.currentItem().text(0) # # printself.origialGroupName # self.moreThanOneList = cmds.ls(self.newGroupName) # self.moreThanOneListCount = len(self.moreThanOneList) else: # print'it count not change name' pass # self.runBuildItemLevelTree() self.newGroupName = self.treeWidget_sceneAssembleTree.currentItem().text(0) self.treeWidget_sceneAssembleTree.itemChanged.connect(self.runChangeItemName) def itemChangedName(self): # print'check 18' # print'chaned item Name' # self.newGroupName = self.treeWidget_sceneAssembleTree.currentItem().text(0) self.moreThanOneList = cmds.ls(self.newGroupName) # print'self.moreThanOneList',self.moreThanOneList self.moreThanOneListCount = len(self.moreThanOneList) # print'self.moreThanOneListCount',self.moreThanOneListCount if self.moreThanOneListCount > 1: #tempName = self.newGroupName tempName = self.treeWidget_sceneAssembleTree.currentItem().text(0) for i in range(0,self.moreThanOneListCount): self.origialGroupName = self.moreThanOneList[i] self.newGroupName = tempName + '_' +'%04d'%i # print'self.origialGroupName,self.newGroupName',self.origialGroupName,self.newGroupName cmds.rename(self.origialGroupName,self.newGroupName) else: self.newGroupName = self.treeWidget_sceneAssembleTree.currentItem().text(0) # print'self.origialGroupName,self.newGroupName',self.origialGroupName,self.newGroupName cmds.rename(self.origialGroupName,self.newGroupName) # except: # pass # self.runBuildItemLevelTree() # self.runBuildItemLevelTree()itemChangedName def ttt(self): print 'check 19' # # printself.treeWidget_sceneAssembleTree.currentItem().text(1) # # printself.treeWidget_sceneAssembleTree.currentItem().text(0) # # printself.treeWidget_sceneAssembleTree.currentItem().text(2) # # printself.treeWidget_sceneAssembleTree.currentItem().icon(0).name() # # printself.treeWidget_sceneAssembleTree.currentItem().icon(0) # printself.treeWidget_sceneAssembleTree.currentItem().text(0) # iconFile =QtGui.QIcon('//mcd-one/database/assets/scripts/maya_scripts///mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/NA120B.png') # self.tableWidget_AssetItemList.item(row, column).setIcon(iconFile) def dragTest(self): # print'check 21' ## printself.treeWidget_sceneAssembleTree.currentItem #searchKey = self.tableWidget_AssetItemList.currentItem().text() selectedAssetItemColumn = self.tableWidget_AssetItemList.currentColumn() selectedAssetItemRow = self.tableWidget_AssetItemList.currentRow() searchKey = str(selectedAssetItemColumn)+'_._'+str(selectedAssetItemRow) # # printsearchKey data = self.tableItemListInfoDict[searchKey] # # printdata.keys()[0] #mimeData = QtCore.QMimeData() # # printmimeData. # drag = QtGui.QDrag(self) self.itemDrag = self.tableWidget_AssetItemList.currentItem().text() ## printself.treeWidget_sceneAssembleTree.findItems(itemDrag) # # printitemDrag #self.treeWidget_sceneAssembleTree.indexFromItem(itemDrag,0) # # printself.treeWidget_sceneAssembleTree.findItems(itemDrag,QtCore.Qt.MatchExactly) #self.table.findItems( #self.edit.text(), QtCore.Qt.MatchExactly) def test(self): print'check 22' # printself.pushButton_P3_processModeling.isChecked() # printself.pushButton_P3_processTexture.isChecked() # printself.pushButton_P3_processRigging.isChecked() # printself.pushButton_P3_NA.isChecked() def clickProcessFilletChange(self): # print'check 23_0' self.clickAssetClass(self.assetClassSelectMode) def clickAssetFilletAll(self): # print'check 23_0' self.assetClassSelectMode = 'all' self.clickAssetClass('all') def clickAssetFilletCharacter(self): # print'check 23_0' self.clickAssetClass('character') self.assetClassSelectMode = 'character' def clickAssetFilletVehicle(self): # print'check 23_0' self.clickAssetClass('vehicle') self.assetClassSelectMode = 'vehicle' def clickAssetFilletSet(self): # print'check 23_0' self.clickAssetClass('set') self.assetClassSelectMode = 'set' def clickAssetFilletProps(self): # print'check 23_0' self.clickAssetClass('props') self.assetClassSelectMode = 'props' def clickAssetFilletOther(self): # print'check 23_0' self.clickAssetClass('other') self.assetClassSelectMode = 'other' def clickAssetClass(self,classMode): # print'check 23' # printclassMode self.pushButton_page3_all.setChecked(False) self.pushButton_page3_character.setChecked(False) self.pushButton_page3_vehicle.setChecked(False) self.pushButton_page3_set.setChecked(False) self.pushButton_page3_props.setChecked(False) self.pushButton_page3_other.setChecked(False) if classMode == 'all': self.pushButton_page3_all.setChecked(True) self.allAssetClassFillet = ['character','vehicle','set','prop','other'] if classMode == 'character': self.pushButton_page3_character.setChecked(True) self.allAssetClassFillet = ['character'] if classMode == 'vehicle': self.pushButton_page3_vehicle.setChecked(True) self.allAssetClassFillet = ['vehicle'] if classMode == 'set': self.pushButton_page3_set.setChecked(True) self.allAssetClassFillet = ['set'] if classMode == 'props': self.pushButton_page3_props.setChecked(True) self.allAssetClassFillet = ['prop'] if classMode == 'other': self.pushButton_page3_other.setChecked(True) self.allAssetClassFillet = ['other'] self.loadPublishedData() if self.currentIconSize == 'large': self.setLargeAssetIcon() if self.currentIconSize == 'mid': self.setMidAssetIcon() if self.currentIconSize == 'small': self.setSmallAssetIcon() if self.currentIconSize == 'text': self.setTextAssetMain() def showAssetMetaDataFromSelect(self): # print'check 24' # print'showAssetMetaDataFromSelect start' #searchKey = self.tableWidget_AssetItemList.currentItem().text() selectedAssetItemColumn = self.tableWidget_AssetItemList.currentColumn() selectedAssetItemRow = self.tableWidget_AssetItemList.currentRow() searchKey = str(selectedAssetItemColumn)+'_._'+str(selectedAssetItemRow) # printsearchKey data = self.tableItemListInfoDict[searchKey] # printdata # for i in data showItemName = 'asset Name : %s'%data.keys()[0].split('.')[0] +'\n' showItemAssetType = 'asset Type : %s'%data.keys()[0].split('.')[1] +'\n' showItemAssetProcessNow = 'asset Progress Now : %s'%data.keys()[0].split('.')[2] +'\n'+'\n' showFileName = 'asset File Name : %s'%data[data.keys()[0]]['fileName'] +'\n'+'\n' showAssetCreator = 'asset Creator :%s'%data[data.keys()[0]]['user'] +'\n' filePublishTime = 'asset Publish Time :%s'%datetime.datetime.fromtimestamp(os.path.getmtime(data[data.keys()[0]]['fileName']))+'\n' showRibArchive = 'asset RibArchive :%s'%data[data.keys()[0]]['ribArchive']['ribArchivePath'] +'\n' showRibArchive = 'asset RibArchive :%s'%data[data.keys()[0]]['ribArchive']['ribArchivePath'] +'\n' publishTimeFromFile = str(datetime.datetime.fromtimestamp(os.path.getmtime(data[data.keys()[0]]['fileName']))) filePublishTime = 'asset Publish Time :%s'%publishTimeFromFile.split('.')[0]+'\n' iconFileName = data[data.keys()[0]]['fileIcon'] ## printfilePublishTime,type(filePublishTime) self.checkFileSize(data[data.keys()[0]]['fileName']) # printself.fileSize showAssetMayaFileSize = 'asset mayaFileSize :%s'%self.fileSize +'\n' # self.checkFileSize(data[data.keys()[0]]['fileName']) showList = [showItemName,showItemAssetType,showItemAssetProcessNow,showFileName,showAssetCreator,filePublishTime,showAssetMayaFileSize,showRibArchive] showInPlainText = '' for i in showList: showInPlainText = showInPlainText +i # printshowInPlainText self.plainTextEdit_assetMetaData.setPlainText(showInPlainText) self.label_showImage_2.setGeometry(QtCore.QRect(5, 5, 200, 200)) self.label_showImage_2.setPixmap(QtGui.QPixmap(iconFileName)) def checkFileSize(self,fileName): # print'check 25' fileSizeBt = os.stat(fileName).st_size /1024 if fileSizeBt < 1024: fileSize = str(fileSizeBt) +'KB' elif fileSizeBt <1024*1024: fileSize = '%.3f'%(fileSizeBt/1024.0) +'MB' else: fileSize='%.3f'%(fileSizeBt/1024.0/1024.0) +'GB' self.fileSize = fileSize def loadPublishedData(self): # print'check 26' file = '//mcd-one/3d_project/ocean_world_2016_cf/publish/global/ocean_world_2016_cf_publishAnnonce.json' with open(file) as data_file: data = json.load(data_file) # self.allAssetClassFillet = ['character','vehicle','set','prop','other'] #allAssetClass allProcesType = ['layout','animation','lighting','effects','simulation'] allItemDict = {} assetTempDict ={} shotTempDict = {} for i in self.allAssetClassFillet: for j in data['assets'][i].keys(): # # print'jjjjj',j if len(data['assets'][i][j]) == 0: assetTempDict.update({j+'.'+'not available':{}}) else: for k in data['assets'][i][j].keys(): assetTempDict.update({j+'.'+k:data['assets'][i][j][k]['state']}) for i in data['shot'].keys(): #shotName.shot.processType:{} for j in allProcesType: if len(data['shot'][i]) == 0: itemKey = i +'.shot.not available' shotTempDict.update({itemKey:{}}) else: itemKey = i + '.shot.'+ j if j in data['shot'][i].keys(): shotTempDict.update({itemKey:data['shot'][i][j]['state']}) allItemDict.update(assetTempDict) # allItemDict.update(shotTempDict) #if want to show shot use this line ## print'allItemDict',allItemDict #is 'texture','model','rigging' icon is checked textureTempDict = {} for i in allItemDict.keys(): if i.split('.')[2] == 'texture': textureTempDict.update({i:allItemDict[i]}) modelTempDict = {} for i in allItemDict.keys(): if i.split('.')[2] == 'model': modelTempDict.update({i:allItemDict[i]}) riggingTempDict = {} for i in allItemDict.keys(): if i.split('.')[2] == 'rigging': riggingTempDict.update({i:allItemDict[i]}) NATempDict = {} for i in allItemDict.keys(): if i.split('.')[2] == 'not available': NATempDict.update({i:allItemDict[i]}) ## print'hjghfjg',self.pushButton_P3_processModeling.isChecked() # self.pushButton_P3_processModeling ## print'self.pushButton_P3_NA.isChecked()',self.pushButton_P3_NA.isChecked() #self.test() newItemDict={} if self.pushButton_P3_processModeling.isChecked() == True: newItemDict.update(modelTempDict) if self.pushButton_P3_processTexture.isChecked() == True: newItemDict.update(textureTempDict) if self.pushButton_P3_processRigging.isChecked() == True: newItemDict.update(riggingTempDict) if self.pushButton_P3_NA.isChecked() == True: newItemDict.update(NATempDict) self.itemDict = newItemDict self.totalItemCount = len(self.itemDict) # # print'self.itemDict',self.itemDict # # print'newItemDict',newItemDict ## printsorted(newItemDict) def storeItemDateInDict(self,cloumnCount): # print'check 27' # print'storeItemDateInDict start' infoSearchList = ['fileName','fileIcon','gpuCache','ribArchive','user','publishTime','metaData'] rowCount = 0 self.tableItemListInfoDict= {} tempItemInDictList = [] notAvailableItem = [] # # print'self.itemDict.keys()',self.itemDict.keys() for i in self.itemDict.keys(): if i.split('.')[2] == 'not available': notAvailableItem.append(i) else: tempItemInDictList.append(i) sortedTempItemList = sorted(tempItemInDictList) + notAvailableItem # # print'sortedTempItemList',sortedTempItemList for i in range(0,self.totalItemCount ): self.tempInfoDictPreItem = {} if cloumnCount == 1: column = 2 row = i else: column = i % cloumnCount row = i/cloumnCount *2 tempKey = str(column) +'_._'+ str(row) # # print'tempKey',tempKey item = sortedTempItemList[i] # # print'item',item tempItemList = {} for j in infoSearchList: try: secondItem = self.itemDict[sortedTempItemList[i]][j] except: secondItem = {} tempItemList.update({j:secondItem}) # # print'secondItem',secondItem self.tableItemListInfoDict.update({tempKey:{item:tempItemList}}) # # print'self.tableItemListInfoDict',self.tableItemListInfoDict if cloumnCount == 1: rowSize = 30 columnSize =400 textRowSize =30 if cloumnCount == 3: rowSize = 120 columnSize =120 textRowSize =20 if cloumnCount == 4: rowSize = 80 columnSize =80 textRowSize =20 if cloumnCount == 6: rowSize = 60 columnSize =60 textRowSize =20 #setItemText(self,cloumnCount,rowSize,columnSize) self.setItemIcon(columnSize,rowSize) self.setItemText(cloumnCount,columnSize,textRowSize) def setItemIcon(self,columnSize,rowSize): # print'check 28' # print'setItemIcon start' ## print'self.tableItemListInfoDict',self.tableItemListInfoDict tempIconFileDict={} for i in self.tableItemListInfoDict.keys(): row = int(i.split('_._')[1]) column = int(i.split('_._')[0]) if len(self.tableItemListInfoDict[i][self.tableItemListInfoDict[i].keys()[0]]['fileIcon']) == 0: iconFile =QtGui.QIcon('//mcd-one/database/assets/scripts/maya_scripts///mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/NA120B.png') else: iconFile = QtGui.QIcon(self.tableItemListInfoDict[i][self.tableItemListInfoDict[i].keys()[0]]['fileIcon'])#.keys() item = QtWidgets.QTableWidgetItem() itemName = self.tableItemListInfoDict[i].keys()[0] item.setText(itemName) self.tableWidget_AssetItemList.setItem(row, column, item) self.tableWidget_AssetItemList.horizontalHeader().setDefaultSectionSize(columnSize) self.tableWidget_AssetItemList.verticalHeader().setDefaultSectionSize(rowSize) self.tableWidget_AssetItemList.item(row, column).setIcon(iconFile) def setItemText(self,cloumnCount,columnSize,textRowSize): # print'check 29' ## printself.tableItemListInfoDict.keys() ## print'cloumnCount',cloumnCount for i in self.tableItemListInfoDict.keys(): # # print'self.tableItemListInfoDict.keys()',self.tableItemListInfoDict.keys() if cloumnCount == 1: row = int(i.split('_._')[1]) column = 0 else: row = int(i.split('_._')[1])+1 ## print'row',row column = int(i.split('_._')[0]) itemName = str(self.tableItemListInfoDict[i].keys()[0]).split('.')[0] # # print'itemText',i,self.tableItemListInfoDict[i] ## printitemName ## printrow ,column item = QtWidgets.QTableWidgetItem() self.tableWidget_AssetItemList.setItem(row, column, item) # self.tableWidget_AssetItemList.setRowHeight(100,60) #set text row height # self.tableWidget_AssetItemList.setIconSize(QtCore.QSize(40,40)) #self.tableWidget_AssetItemList.horizontalHeader().setDefaultSectionSize(columnSize) #self.tableWidget_AssetItemList.verticalHeader().setDefaultSectionSize(rowSize) self.tableWidget_AssetItemList.setRowHeight(row,textRowSize) #set text row height self.tableWidget_AssetItemList.item(row, column).setText(QtWidgets.QApplication.translate("MainWindow",'aaa', None,-1)) self.tableWidget_AssetItemList.item(row, column).setText(QtWidgets.QApplication.translate("MainWindow",itemName, None,-1)) def setTextMode(self): # print'check 30' self.tableWidget_AssetItemList.clear() self.pushButton_P3_largeIcon.setChecked(True) self.pushButton_P3_MidIcon.setChecked(False) self.pushButton_P3_smallIcon.setChecked(False) self.pushButton_P3_text.setChecked(False) setRow = self.totalItemCount +1 self.tableWidget_AssetItemList.setColumnCount(3) self.tableWidget_AssetItemList.setRowCount(setRow) def setLargeAssetIcon(self): # print'check 31' self.tableWidget_AssetItemList.clear() self.pushButton_P3_largeIcon.setChecked(True) self.pushButton_P3_MidIcon.setChecked(False) self.pushButton_P3_smallIcon.setChecked(False) self.pushButton_P3_text.setChecked(False) # print'setLargeAssetIcon' self.tableWidget_AssetItemList.clear() self.pushButton_P3_largeIcon.setChecked(True) self.pushButton_P3_MidIcon.setChecked(False) self.pushButton_P3_smallIcon.setChecked(False) self.pushButton_P3_text.setChecked(False) if self.totalItemCount%3 == 0: setRow = ((self.totalItemCount / 3) *2) +1 else: setRow = ((self.totalItemCount / 3) *2) +2 # # printsetRow #setRow = self.totalItemCount / 2 *2 +2 self.tableWidget_AssetItemList.setColumnCount(3) self.tableWidget_AssetItemList.setRowCount(setRow) #self.tableWidget_AssetItemList.horizontalHeader().setDefaultSectionSize(120) #self.tableWidget_AssetItemList.verticalHeader().setDefaultSectionSize(120) iconFile = self.iconFile tableItemIndex={} for column in range(0,3): #set icon for row in range(0,setRow,2): self.createTableItem(column,row,iconFile,120) for column in range(0,3): for row in range(1,setRow,2): self.setTableItemText(column,row) self.storeItemDateInDict (3) # create Item Dict self.currentIconSize = 'large' def setMidAssetIcon(self): # print'check 32' # print'setMidAssetIcon' self.tableWidget_AssetItemList.clear() self.pushButton_P3_largeIcon.setChecked(False) self.pushButton_P3_MidIcon.setChecked(True) self.pushButton_P3_smallIcon.setChecked(False) self.pushButton_P3_text.setChecked(False) if self.totalItemCount%4 == 0: setRow = ((self.totalItemCount / 4) *2) +1 else: setRow = ((self.totalItemCount / 4) *2) +2 # # printsetRow # self.tableWidget_AssetItemList.setColumnCount(4) self.tableWidget_AssetItemList.setRowCount(setRow) # self.tableWidget_AssetItemList.horizontalHeader().setDefaultSectionSize(80) # self.tableWidget_AssetItemList.verticalHeader().setDefaultSectionSize(80) iconFile = self.iconFile for column in range(0,4): #set icon setItemText for row in range(0,setRow,2): # # printrow self.createTableItem(column,row,iconFile,80) for column in range(0,4): for row in range(1,setRow,2): # # printrow self.setTableItemText(column,row) self.storeItemDateInDict (4) self.currentIconSize = 'mid' def setSmallAssetIcon(self): # print'check 33' # print'setSmallAssetIcon' self.tableWidget_AssetItemList.clear() self.pushButton_P3_largeIcon.setChecked(False) self.pushButton_P3_MidIcon.setChecked(False) self.pushButton_P3_smallIcon.setChecked(True) self.pushButton_P3_text.setChecked(False) if self.totalItemCount%6 == 0: setRow = ((self.totalItemCount / 6) *2) +1 else: setRow = ((self.totalItemCount / 6) *2) +2 # # printsetRow self.tableWidget_AssetItemList.setColumnCount(6) self.tableWidget_AssetItemList.setRowCount(setRow) # self.tableWidget_AssetItemList.horizontalHeader().setDefaultSectionSize(60) # self.tableWidget_AssetItemList.verticalHeader().setDefaultSectionSize(60) iconFile = self.iconFile for column in range(0,6): #set icon for row in range(0,setRow,2): self.createTableItem(column,row,iconFile,60) for column in range(0,6): for row in range(1,setRow,2): # # printrow self.setTableItemText(column,row) self.storeItemDateInDict (6) self.currentIconSize = 'small' def setTextAssetMain(self): # print'check 34' self.setTextAsset(30) def setTextAsset(self,size): # print'check 35' # print'setTextAsset~~' self.tableWidget_AssetItemList.clear() self.pushButton_P3_largeIcon.setChecked(False) self.pushButton_P3_MidIcon.setChecked(False) self.pushButton_P3_smallIcon.setChecked(False) self.pushButton_P3_text.setChecked(True) setRow = self.totalItemCount #+ 1 self.tableWidget_AssetItemList.setColumnCount(3) self.tableWidget_AssetItemList.setRowCount(setRow) self.storeItemDateInDict(1) # # print'self.tableItemListInfoDict',self.tableItemListInfoDict.keys() iconFile =self.iconFile for row in range(0, setRow): item = QtWidgets.QTableWidgetItem() self.tableWidget_AssetItemList.setColumnWidth(0,size) #index ser number self.tableWidget_AssetItemList.setRowHeight(row , size) #set text row height self.tableWidget_AssetItemList.setItem(row, 0, item) self.tableWidget_AssetItemList.item(row, 0).setText(QtWidgets.QApplication.translate("MainWindow", "serNum", None,-1)) self.tableWidget_AssetItemList.item(row, 0).setText(QtWidgets.QApplication.translate("MainWindow", str(row), None,-1)) item = QtWidgets.QTableWidgetItem() self.tableWidget_AssetItemList.setColumnWidth(1,size) #index ser number self.tableWidget_AssetItemList.setRowHeight(row , size) #set text row height self.tableWidget_AssetItemList.setItem(row, 1, item) self.tableWidget_AssetItemList.item(row, 1).setIcon(iconFile) item = QtWidgets.QTableWidgetItem() self.tableWidget_AssetItemList.setColumnWidth(2,300) #index ser number # self.tableWidget_AssetItemList.setRowHeight(row , size) #set text row height self.tableWidget_AssetItemList.setItem(row, 2, item) self.tableWidget_AssetItemList.item(row, 2).setText(QtWidgets.QApplication.translate("MainWindow", "icon", None,-1)) for i in self.tableItemListInfoDict.keys() : row = int(i.split('_._')[1]) self.tableWidget_AssetItemList.setRowHeight(row , size) #set text row height itemName = str(self.tableItemListInfoDict[i].keys()[0]) self.tableWidget_AssetItemList.item(row, 2).setText(QtWidgets.QApplication.translate("MainWindow", itemName, None,-1)) for i in self.tableItemListInfoDict.keys() : row = int(i.split('_._')[1]) itemIconFile = str(self.tableItemListInfoDict[i][self.tableItemListInfoDict[i].keys()[0]]['fileIcon']) # itemIconFile='//mcd-one/database/assets/scripts/maya_scripts///mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/NA120B.png' if len(itemIconFile) == 2: # # print'itemIconFile','not available' itemIconFile = '//mcd-one/database/assets/scripts/maya_scripts///mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/NA120B.png' self.tableWidget_AssetItemList.item(row, 1).setIcon(QtGui.QIcon(itemIconFile)) self.tableWidget_AssetItemList.setIconSize(QtCore.QSize(size,size)) pass else: # # print'itemIconFile'itemIconFile # # print'itemIconFile',itemIconFile self.tableWidget_AssetItemList.item(row, 1).setIcon(QtGui.QIcon(itemIconFile)) self.tableWidget_AssetItemList.setIconSize(QtCore.QSize(size,size)) # for row in range(0, setRow): # item = QtWidgets.QTableWidgetItem() # self.tableWidget_AssetItemList.setColumnWidth(3,size) #index ser number # self.tableWidget_AssetItemList.setRowHeight(row , size) self.currentIconSize = 'text' def initialTableWidgetAssetList(self): # print'check 36' self.tableWidget_AssetItemList.clear() #self.tableWidget_AssetItemList.setRowCount(2) #self.tableWidget_AssetItemList.setColumnCount(2) self.tableWidget_AssetItemList.setColumnCount(3) self.tableWidget_AssetItemList.setRowCount(4) self.tableWidget_AssetItemList.horizontalHeader().setDefaultSectionSize(60) self.tableWidget_AssetItemList.verticalHeader().setDefaultSectionSize(60) def createTableItem(self,column,row,iconFile,iconSize): # print'check 37' item = QtWidgets.QTableWidgetItem() self.tableWidget_AssetItemList.setItem(row, column, item) self.tableWidget_AssetItemList.item(row, column).setText(QtWidgets.QApplication.translate("MainWindow", "ItemIconHere", None,-1)) self.tableWidget_AssetItemList.item(row, column).setIcon(iconFile) self.tableWidget_AssetItemList.setIconSize(QtCore.QSize(iconSize,iconSize)) def createItemB(self,column,row,iconFile): # print'check 38' # icon = QtGui.QIcon("C:/Program Files/Autodesk/Maya2017///mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/animation.png") #iconFile = QtGui.QIcon("C:/Program Files/Autodesk/Maya2017///mcd-one/database/assets/scripts/maya_scripts/icons/publishToolIcon/animation.png") item = QtWidgets.QTableWidgetItem() self.tableWidget_AssetItemList.setItem(row, column, item) #self.tableWidget_AssetItemList.item(row, column).setText(QtWidgets.QApplication.translate("MainWindow", "ItemIcon", None,-1)) self.tableWidget_AssetItemList.item(row, column).setIcon(iconFile) self.tableWidget_AssetItemList.setIconSize(QtCore.QSize(60,60)) # self.tableWidget.item(1, 2).setIconText('aaa') # item. # add text Item def setTableItemText(self,column,row): # print'check 39' item = QtWidgets.QTableWidgetItem() # textRow = row+1 self.tableWidget_AssetItemList.setRowHeight(row , 20) #set text row height self.tableWidget_AssetItemList.setItem(row, column, item) # self.tableWidget_AssetItemList.setIconSize(QtCore.QSize(40,40)) self.tableWidget_AssetItemList.item(row, column).setText(QtWidgets.QApplication.translate("MainWindow", "ItemName", None,-1)) #item.setTextAlignment(-20) # self.tableWidget.setRowHeight(1 , 20) class assetTreeInTheWorld(QtWidgets.QTreeWidget,mod_MainWindow): def __init__(self,parent= QtWidgets.QApplication.activeWindow()): super(assetTreeInTheWorld, self).__init__(parent) self.setAcceptDrops(True) #self.setHeaderLabels(["Select Members"]) self.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection) self.setGeometry(QtCore.QRect(5, 90, 200, 530)) self.setColumnCount(2) #self.mousePressPos = QtCore.QPoint(0,0) self.setObjectName("treeWidget_sceneAssembleTree") #self.header().setVisible(False) #self.header().setCascadingSectionResizes(False) #self.header().setDefaultSectionSize(150) #self.header().setHighlightSections(False) #self.header().setMinimumSectionSize(25) #self.setDragEnabled(True) #self.setDragDropOverwriteMode(True) #self.setDragDropMode(QtWidgets.QAbstractItemView.InternalMove) self.header().setHidden(True) self.setSelectionMode(self.ExtendedSelection) self.setDragDropMode(self.InternalMove) self.setDragEnabled(True) self.setDropIndicatorShown(True) # self.itemSelectionChanged.connect(self.selectItems) self.topLayerItemIndexDict = {'0':'character', '1':'vehicle', '2':'set', '3':'prop', '4':'other', '5':'effect'} #self.pushButton_P3_deletSelectItem.clicked.connect(self.asdf) def asdf(self): print 'asdf' def selectItems(self): print 'selectItems' treeItemName = [] treeItemFullNameList = [] treeItem = self.selectedItems() for i in treeItem: if self.indexOfTopLevelItem(i) == -1: treeItemName.append(i.text(0)) self.checkParentFullName(i) # print 'itemFullName',self.parentItemFullName treeItemFullNameList.append(self.parentItemFullName) else: print 'can not modify toplayer item' return treeItemFullNameList def dropEvent(self, event): print 'dropEvent' if event.source() == self: QtWidgets.QAbstractItemView.dropEvent(self, event) def dropMimeData(self, parent, row, data, action): print 'dropMimeData' if action == QtCore.Qt.MoveAction: #print self.moveSelection(parent, row) return self.moveSelection(parent, row) return False def checkParentFullName(self,parentItem): print 'checkParentFullName' # itemLevelIndexList = [] parentItemIndex = self.indexOfTopLevelItem(parentItem) # print 'parentItemIndex',parentItemIndex if parentItemIndex == -1: parentItemFullNameList = [parentItem.text(0)] while self.indexOfTopLevelItem(parentItem) == -1: parentItem = parentItem.parent() # print 'parentItem',parentItem.text(0) parentItemFullNameList.append(parentItem.text(0).split('__')[0]) parentItemFullName = '|'.join(reversed(parentItemFullNameList)) else: topLayerItemIndex = parentItemIndex parentItemFullName = self.topLayerItemIndexDict[str(topLayerItemIndex)] # print 'parentItemFullName',parentItemFullName self.parentItemFullName =parentItemFullName #return parentFullName #cmds.select(selectItemInOutLiner) def moveSelection(self, parent, position): print 'moveSelection' # save the selected items dragItem = self.selectItems() selection = [QtCore.QPersistentModelIndex(i) for i in self.selectedIndexes()] parent_index = self.indexFromItem(parent) if parent_index in selection: return False # save the drop location in case it gets moved target = self.model().index(position, 0, parent_index).row() if target < 0: target = position # remove the selected items taken = [] for index in reversed(selection): item = self.itemFromIndex(QtCore.QModelIndex(index)) if item is None or item.parent() is None: taken.append(self.takeTopLevelItem(index.row())) else: taken.append(item.parent().takeChild(index.row())) self.checkParentFullName(parent) dropTarget = self.parentItemFullName print 'dragItem',dragItem print 'dropTarget',dropTarget self.moveTreeItem(dragItem,dropTarget) while taken: if position == -1: # append the items if position not specified if parent_index.isValid(): parent.insertChild( parent.childCount(), taken.pop(0)) else: self.insertTopLevelItem( self.topLevelItemCount(), taken.pop(0)) else: # insert the items at the specified position if parent_index.isValid(): parent.insertChild(min(target, parent.childCount()), taken.pop(0)) else: self.insertTopLevelItem(min(target, self.topLevelItemCount()), taken.pop(0)) return True def moveTreeItem(self,dragItem,dropTarget): print 'moveTreeItem' for i in dragItem: cmds.parent(i,dropTarget) def main(): global ui app = QtWidgets.QApplication.instance() if app == None: app = QtWidgets.QApplication(sys.argv) try: ui.close() ui.deleteLater() except: pass ui = mod_MainWindow() ui.show() if __name__ == '__main__': main()
3e5b76060a8d08eb9c454a93b5bf91d108e6268c
e2e08d7c97398a42e6554f913ee27340226994d9
/pyautoTest-master(ICF-7.5.0)/test_case/scg_old/scg_obj_shell_2nd/test_c40343.py
3c334ff2e3e9d1098cbb335f5426d69ef272f5d0
[]
no_license
lizhuoya1111/Automated_testing_practice
88e7be512e831d279324ad710946232377fb4c01
b3a532d33ddeb8d01fff315bcd59b451befdef23
refs/heads/master
2022-12-04T08:19:29.806445
2020-08-14T03:51:20
2020-08-14T03:51:20
287,426,498
0
0
null
null
null
null
UTF-8
Python
false
false
1,783
py
import pytest import time import sys from page_obj.scg.scg_def import * from page_obj.scg.scg_def_obj import * from page_obj.scg.scg_def_log import * from page_obj.common.rail import * from os.path import dirname, abspath sys.path.insert(0, dirname(dirname(abspath(__file__)))) test_id = 40343 # 修改以subnet方式添加的一条addr obj,查看log def test_change_obj_wxw(browser): try: login_web(browser, url="10.2.2.81") # 先添加再修改 add_obj_address_wxw(browser, name='obj_add_343', desc='zhe是yi个描述1', subnetip='11.11.11.1', subnetmask='24') # 欲修改哪个参数可直接编辑 change_obj_address_wxw(browser, name='obj_add_343', desc='zhe是yi个描述2', subnetip='11.11.11.2', subnetmask='32') time.sleep(2) # 切换到默认frame browser.switch_to.default_content() get_log(browser, 管理日志) browser.switch_to.default_content() # 切换到左侧frame browser.switch_to.frame("content") loginfo = browser.find_element_by_xpath('//*[@id="namearea0"]').text try: assert "配置地址对象成功,修改内部对象 [obj_add_343]" in loginfo rail_pass(test_run_id, test_id) except: rail_fail(test_run_id, test_id) assert "配置地址对象成功,修改内部对象 [obj_add_343]" in loginfo except Exception as err: # 如果上面的步骤有报错,重新设备,恢复配置 reload(hostip="10.2.2.81") print(err) rail_fail(test_run_id, test_id) time.sleep(70) assert False if __name__ == '__main__': pytest.main(["-v", "-s", "test_c40343.py"])
dc3f80de3fed77fc2506bf296b04f63ce5dd996c
f19c5436c7173835a3f1d064541ee742178e213a
/mah/divide and conquer/[BOJ]1920_수 찾기.py
9bdd791f8797941a03f185c9f847b8104e5e9e83
[]
no_license
hongsungheejin/Algo-Study
f1c521d01147a6f74320dbc8efe3c1037e970e73
d6cb8a2cc6495ccfcfb3477330a3af95895fae32
refs/heads/main
2023-07-06T10:58:27.258128
2021-07-29T02:11:13
2021-07-29T02:11:13
379,269,918
2
0
null
null
null
null
UTF-8
Python
false
false
385
py
N = int(input()) nums = list(map(int, input().split())) nums.sort() M = int(input()) tars = list(map(int, input().split())) def binary_serach(tar): l, r = 0, len(nums) - 1 while l<=r: m = (l+r)//2 if nums[m] == tar: return 1 elif nums[m] < tar: l=m+1 else: r=m-1 return 0 for tar in tars: print(binary_serach(tar))
39e2d9dbdc83ea68defe4b575e5d0bee237f89bc
205be8d429df36e27cdfc048bfca9212c5a62a87
/icu/urls.py
ed2cf073014ebef72cfb33b59762ed1241b9df93
[]
no_license
KennyChrisUmurundi/HOsto
16c8f926282fc48c981532447f1685fbbc2b457c
33fa31524a08934f3deb8f622a1b1554d8ef1af4
refs/heads/master
2022-04-01T02:42:39.146227
2020-01-07T11:44:08
2020-01-07T11:44:08
193,458,881
0
0
null
null
null
null
UTF-8
Python
false
false
478
py
from django.urls import path from django.contrib.auth import views as auth_views from . import views as icu_views from django.conf.urls.static import static from django.conf import settings app_name = 'icu' urlpatterns = [ path('Medical Update/',icu_views.update_list,name="add-medical"), path('scan/',icu_views.ScanCode,name="ScanCode"), path('patient/<slug:code>',icu_views.patient,name="patient"), path('feedback/<slug:code>/<int:id>',icu_views.feedback,name="feedback"), ]
13daadc403ee347a1877bef70ef64461737e38cc
5a71ca1f5c964f803350e3c1238cb48986db565c
/coinlibbitfinex/coinlibbitfinex/streamapi.py
d6eb6285f6a324d0a46d8cc40959a345f9c959cd
[]
no_license
tetocode/coinliball
fd644cbc16039ecad7e43228ea4e287ead5c8e5f
41ebbac13c1fbba98aedaa766b9a505cb157f374
refs/heads/master
2022-09-28T21:58:08.130006
2020-06-04T03:00:56
2020-06-04T03:00:56
269,247,318
0
2
null
null
null
null
UTF-8
Python
false
false
3,624
py
import json import logging from typing import Hashable, Dict from websocket import WebSocket from coinlib.datatypes.streamdata import StreamData from coinlib.trade.websocketstreamapi import WebSocketStreamApi logger = logging.getLogger(__name__) class StreamApi(WebSocketStreamApi): URL = 'wss://api.bitfinex.com/ws' def __init__(self, **kwargs): super().__init__(**kwargs) self._subscriptions = {} self._channel_id_map: Dict[int, Hashable] = {} def _process_subscription_q(self, ws: WebSocket): # process one if len(self._subscription_q): op, (key, params) = self._subscription_q.popleft() if op == 'subscribe': self._subscriptions[key] = params self._subscribe_channel(params) logger.debug(f'subscribe {key} {params}') elif op == 'unsubscribe': params = self._subscriptions.pop(key, None) if params is not None: for channel_id, v in self._channel_id_map.items(): if v == key: self._unsubscribe_channel(channel_id) logger.debug(f'unsubscribe {key} {params} {channel_id}') break else: assert False, f'unknown operation={op}' def _subscribe_channel(self, params: dict): request = dict(event='subscribe') request.update(params) self.send_message(request) def _unsubscribe_channel(self, channel_id: int): self.send_message({ 'event': 'unsubscribe', 'chanId': channel_id, }) def on_message(self, message_data: str): message = json.loads(message_data) if isinstance(message, dict): event = message.get('event') if event == 'info': logger.debug(f'event info {message}') return elif event == 'subscribed': self.on_subscribed(message) return elif event == 'unsubscribed': self.on_unsubscribed(message) return elif event == 'error': self.on_error(message) return else: logger.warning(f'event unsupported {message}') return if isinstance(message, list): self.on_channel_data(message) return logger.warning(f'unknown message {message}') def on_subscribed(self, message: dict): channel_name = message['channel'] for key, params in self._subscriptions.items(): if channel_name == params.get('channel'): if channel_name == 'book': # TODO: distinguish between order_book and raw_order_book if message['pair'].upper() != params.get('pair', '').upper(): continue channel_id = int(message['chanId']) self._channel_id_map[channel_id] = key logger.debug(f'event subscribed {message}') return logger.warning('unknown event subscribe {message}') def on_unsubscribed(self, message: dict): _ = self logger.debug(f'event unsubscribed {message}') def on_error(self, message: dict): _ = self logger.error(f'event error {message}') def on_channel_data(self, data: list): channel_id = data[0] key = self._channel_id_map.get(channel_id) if key: self.on_raw_data(StreamData(key, data))
[ "_" ]
_
4272a7d781c422d78e27a838280b038082ef95ab
57fc5d54f5df359c7a53020fb903f36479d3a322
/controllers/.history/supervisor/supervisor_20201127194410.py
c91f5cc5bde9a494e19c7adadf4e75e4d0388496
[]
no_license
shenwuyue-xie/webots_testrobots
929369b127258d85e66c5275c9366ce1a0eb17c7
56e476356f3cf666edad6449e2da874bb4fb4da3
refs/heads/master
2023-02-02T11:17:36.017289
2020-12-20T08:22:59
2020-12-20T08:22:59
323,032,362
0
0
null
null
null
null
UTF-8
Python
false
false
25,059
py
import math import numpy as np from numpy import random from numpy.core.fromnumeric import size from numpy.lib.function_base import meshgrid import utilities as utils from deepbots.supervisor.controllers.supervisor_emitter_receiver import \ SupervisorCSV # # from deepbots.supervisor.wrappers.tensorboard_wrapper import TensorboardLogger from tensorboardX import SummaryWriter from models.networks import TD3 from controller import Keyboard import os Max_robotnum = 6 OBSERVATION_SPACE = (Max_robotnum-1) * 4 + 7 + 9 * Max_robotnum ACTION_SPACE = Max_robotnum * 2 + 3 MAX_DSNUM = (Max_robotnum-1) * 4 + 7 DIST_SENSORS_MM = {'min': 0, 'max': 1000} XPOSITION = {'min':-2, 'max':2} YPOSITION = {'min':-1.5 , 'max':1.5} ZPOSITION = {'min': -1, 'max' : 8} MAX_DISTANCE = {'min':0, 'max':10} MAX_ANGLE = {'min':-math.pi, 'max':math.pi} # import ptvsd # print("waiting for debugger attach") # ptvsd.enable_attach(address=("127.0.0.1",7788)) # ptvsd.wait_for_attach() class TaskDecisionSupervisor(SupervisorCSV): def __init__(self,robot,observation_space,log_dir,v_action,v_observation,v_reward,windows=[10,100,200]): super(TaskDecisionSupervisor,self).__init__() self.timestep = int(self.supervisor.getBasicTimeStep()) self.keyboard = Keyboard() self.keyboard.enable(self.timestep) self.emitter = self.supervisor.getEmitter('emitter') self.receiver = self.supervisor.getReceiver('receiver') self.robot_list = robot self.robot_handles = [] self.observation = [0 for i in range(observation_space)] self.findThreshold = 0.2 self.steps = 0 self.steps_threshold = 6000 self.endbattery = [50000 for i in range(Max_robotnum)] self.final_distance = [50 for i in range(Max_robotnum)] self.final_target = self.supervisor.getFromDef('final_target') self.should_done = False self.startbattery = 50000 self.setuprobots() self.step_cntr = 0 self.step_global = 0 self.step_reset = 0 self.score = 0 self.score_history = [] self.v_action = v_action self.v_observation = v_observation self.v_reward = v_reward self.windows = windows self.file_writer = SummaryWriter(log_dir, flush_secs=30) def setuprobots(self): for defname in self.robot_list: self.robot_handles.append(self.supervisor.getFromDef(defname)) def handle_receiver(self): message = [] for i in range(self.robot_num): if self.receiver.getQueueLength() > 0: string_message = self.receiver.getData().decode("utf-8") string_message = string_message.split(",") for ms in string_message: message.append(ms) self.receiver.nextPacket() return message def get_observations(self): self.ds_values = [] self.final_distance = [50 for i in range(Max_robotnum)] self.message = [1000 for i in range(MAX_DSNUM)] self.angles = [] observation = [] message = self.handle_receiver() self.angles = [0 for i in range(Max_robotnum)] if len(message) != 0: for i in range(len(message)): self.message[i] = float(message[i]) self.ds_values.append(float(message[i])) for j in range(MAX_DSNUM): observation.append(utils.normalize_to_range(float(self.message[j]),DIST_SENSORS_MM['min'],DIST_SENSORS_MM['max'], 0, 1)) for k in range(0,self.robot_num): robot_position = [] robot_position = self.robot_handles[k].getPosition() robot_rotation = [] robot_rotation = self.robot_handles[k].getOrientation() observation.append(utils.normalize_to_range(float(robot_position[0]),XPOSITION['min'],XPOSITION['max'],0,1)) observation.append(utils.normalize_to_range(float(robot_position[1]),YPOSITION['min'],YPOSITION['max'],0,1)) observation.append(utils.normalize_to_range(float(robot_position[2]),ZPOSITION['min'],ZPOSITION['max'],0,1)) observation.append(utils.normalize_to_range(float(robot_rotation[0]),-1,1,0,1)) observation.append(utils.normalize_to_range(float(robot_rotation[1]),-1,1,0,1)) observation.append(utils.normalize_to_range(float(robot_rotation[2]),-1,1,0,1)) observation.append(utils.normalize_to_range(float(robot_rotation[3]),-math.pi,math.pi,0,1)) self.final_distance[k] = utils.get_distance_from_target(self.robot_handles[k],self.final_target) observation.append(utils.normalize_to_range(float(self.final_distance[k]),MAX_DISTANCE['min'],MAX_DISTANCE['max'],0,1)) self.angles[k] = utils.get_angle_from_target(self.robot_handles[k],self.final_target) observation.append(utils.normalize_to_range(float(self.angles[k]),MAX_ANGLE['min'],MAX_ANGLE['max'],0,1)) for m in range(self.robot_num,Max_robotnum): for n in range(9): observation.append(0.5) else : observation = [0 for i in range(OBSERVATION_SPACE)] self.observation = observation return self.observation # robot_children = self.robot_handles[k].getField('children') # frontjoint_node = robot_children.getMFNode(3) # frontjoint = frontjoint_node.getField('jointParameters') # frontjoint = frontjoint.getSFNode() # para = frontjoint.getField('position') # front_hingeposition = para.getSFFloat() # observation.append(utils.normalize_to_range(float(front_hingeposition),-math.pi/2,math.pi/2,0,1)) # front_ep = frontjoint_node.getField('endPoint') # front_ep = front_ep.getSFNode() # frontrotation_field = front_ep.getField('rotation') # front_rotation = frontrotation_field.getSFRotation() # for f in range(3): # observation.append(utils.normalize_to_range(float(front_rotation[f]),-1,1,0,1)) # observation.append(utils.normalize_to_range(float(front_rotation[3]),-math.pi/2,math.pi/2,0,1)) # robot_children = self.robot_handles[k].getField('children') # rearjoint_node = robot_children.getMFNode(4) # rearjoint = rearjoint_node.getField('jointParameters') # rearjoint = rearjoint.getSFNode() # para = rearjoint.getField('position') # rear_hingeposition = para.getSFFloat() # observation.append(utils.normalize_to_range(float(rear_hingeposition),-math.pi/2,math.pi/2,0,1)) # rear_ep = rearjoint_node.getField('endPoint') # rear_ep = rear_ep.getSFNode() # rearrotation_field = rear_ep.getField('rotation') # rear_rotation = rearrotation_field.getSFRotation() # for r in range(3): # observation.append(utils.normalize_to_range(float(rear_rotation[r]),-1,1,0,1)) # observation.append(utils.normalize_to_range(float(rear_rotation[3]),-math.pi/2,math.pi/2,0,1)) # final_position = [] # final_position = self.final_target.getPosition() # observation.append(utils.normalize_to_range(float(final_position[0]),XPOSITION['min'],XPOSITION['max'],0,1)) # observation.append(utils.normalize_to_range(float(final_position[1]),YPOSITION['min'],YPOSITION['max'],0,1)) # observation.append(utils.normalize_to_range(float(final_position[2]),ZPOSITION['min'],ZPOSITION['max'],0,1)) # final_distance = [] # for d in range(self.robot_num): # final_distance.append(utils.get_distance_from_target(self.robot_handles[d],self.final_target)) # self.final_distance[d] = final_distance[d] def get_default_observation(self): self.observation = [0 for i in range(OBSERVATION_SPACE)] return self.observation def empty_queue(self): self.observation = [0 for i in range(OBSERVATION_SPACE)] # self.shockcount = 0 self.overrangecount = 0 # self.flagadd = False # self.flagreduce = False self.dscount = 0 while self.supervisor.step(self.timestep) != -1: if self.receiver.getQueueLength() > 0: self.receiver.nextPacket() else: break def get_reward(self,action): if (self.observation == [0 for i in range(OBSERVATION_SPACE)] or len(self.observation) == 0 ) : return 0 reward = 0 translations = [] for i in range(len(self.robot_handles)): translation = self.robot_handles[i].getField('translation').getSFVec3f() translations.append(translation) if self.steps >= self.steps_threshold: return -20 if np.min(self.ds_values) <= 50: reward = reward -2 self.dscount = self.dscount + 1 if self.dscount > 60: reward = reward -20 self.should_done = True if self.dscount > 30: reward = reward - 5 if np.min(self.ds_values) <= 150: reward = reward -1 for j in range(len(self.robot_handles)): if translations[j][2] <= ZPOSITION['min'] or translations[j][2] >= ZPOSITION['max']: reward = reward - 2 self.overrangecount = self.overrangecount + 1 if translations[j][0] <= XPOSITION['min'] or translations[j][0] >= ZPOSITION['max']: reward = reward - 2 self.overrangecount = self.overrangecount + 1 if self.overrangecount >40: reward = reward -20 self.should_done = True if min(self.final_distance) < self.findThreshold: reward = reward + 100 for m in range(Max_robotnum): consumption = self.startbattery - self.endbattery[m] reward = reward - float(consumption/self.startbattery) * 6 return reward else : reward = reward - float(min(self.final_distance)) return reward # """惩罚不停+-+-的行为 """ # if action[-1] > 0.9 : # if self.flagreduce == True: # self.shockcount = self.shockcount + 1 # self.flagadd = True # self.flagreduce = False # if action[-1] < 0.1: # if self.flagadd == True: # self.shockcount = self.shockcount + 1 # self.flagadd = False # self.flagreduce =True # if action[-1] >=0.1 and action[-1] <=0.9: # self.shockcount = self.shockcount - 1 # self.flagadd = False # self.flagreduce = False # if self.shockcount >= 8: # reward = reward - 4 # if self.shockcount >= 12: # reward = reward - 8 # self.should_done = True # """如果ban的动作值有十个值出现在动作区域,不稳定给负的reward,训练到100代左右时,模块几乎不再动自己的前后motor""" # count = 0 # for k in range(12,24): # action[k] = utils.normalize_to_range(float(action[k]),-0.2,1.2,0,1) # if action[k] > 0.95 or action[k] < 0.05: # count = count + 1 # if count > 9 : # reward = reward - 2 """something worse need to be modified""" """加机器人时还需要考虑rearmotor的位置,测试后发现是hingejoint的jointParameters域的position参数,需要找到这个参数""" """可以只改变相对应的hingejoint参数使两者结合,也可以改变模块位置和角度,但是改变模块位置和角度比较复杂""" # position = abs(get...) # 改变hingejoint,只需要改变front hingejoint的position参数 # 改变模块位置和角度 # deltax和deltaz可以根据position来计算,主要是rotation要更改,绕x轴旋转(1,0,0,rad) # 但是之前寻找模块的位置时已经修改过自己的rotation,所以不好更改,并且更改了rotation,translation也要更改,用这套体姿表征体系更改起来特别复杂 # 另外,因为是往后加模块,所以除非尾巴上翘,否则都不能这样加(陷到地底下了) # 况且,即便尾巴上翘,可以直接加到后ban上,可能也会因为重力原因把整个构型掀翻 # 综上所述,无论是可行性,还是稳定性原因,都建议只修改front_hingejoint的position值 def robot_step(self,action): # x = np.random.rand() # e = 0.8 + ep * 0.2/10000 # if x > e : # action[-1] = np.random.rand() if action[-1] > 0 and action[-1] <= 0.1 and self.robot_num < Max_robotnum: last_translation = self.robot_handles[-1].getField('translation').getSFVec3f() last_angle = self.robot_handles[-1].getField('rotation').getSFRotation()[3] last_rotation = self.robot_handles[-1].getField('rotation').getSFRotation() delta_z = 0.23 * math.cos(last_angle) delta_x = 0.23 * math.sin(last_angle) new_translation = [] new_translation.append(last_translation[0] - delta_x) new_translation.append(last_translation[1]) new_translation.append(last_translation[2] - delta_z) robot_children = self.robot_handles[-1].getField('children') rearjoint_node = robot_children.getMFNode(4) joint = rearjoint_node.getField('jointParameters') joint = joint.getSFNode() para = joint.getField('position') hingeposition = para.getSFFloat() if hingeposition > 0.8 or hingeposition < -0.8: delta = 0.03 - 0.03 * math.cos(hingeposition) delta_z = delta * math.cos(last_angle) delta_x = delta * math.sin(last_angle) new_translation[0] = new_translation[0] + delta_x new_translation[2] = new_translation[2] + delta_z new_rotation = [] for i in range(4): new_rotation.append(last_rotation[i]) flag_translation = False flag_rotation = False flag_front = False flag_frontposition = False flag_frontrotation = False battery_remain = float(self.endbattery[self.robot_num]) importname = "robot_" + str(self.robot_num) + '.wbo' new_file =[] with open(importname,'r') as f: lines = f.readlines() for line in lines: if "translation" in line: if flag_translation == False: replace = "translation " + str(new_translation[0]) + " " + str(new_translation[1]) + " " + str(new_translation[2]) line = "\t" + replace +'\n' flag_translation = True if "rotation" in line: if flag_rotation == False: replace = "rotation " + str(new_rotation[0]) + " " + str(new_rotation[1]) + " " + str(new_rotation[2]) + " " \ +str(new_rotation[3]) line = "\t" + replace +'\n' flag_rotation = True if 'front HingeJoint' in line: flag_front = True if 'position' in line: if flag_front == True and flag_frontposition ==False: repalce = "position "+ str(hingeposition) line = "\t\t\t\t" + repalce + '\n' flag_frontposition = True if 'rotation' in line : if flag_front == True and flag_frontrotation == False: replace = "rotation " + str(1)+ ' ' + str(0)+ ' ' + str(0) + ' ' + str(hingeposition) line if "50000" in line : line = "\t\t" + str(battery_remain) + "," + " " + str(50000) + '\n' new_file.append(line) with open(importname,'w') as f: for line in new_file: f.write(line) rootNode = self.supervisor.getRoot() childrenField = rootNode.getField('children') childrenField.importMFNode(-1,importname) defname = 'robot_' + str(self.robot_num) self.robot_handles.append(self.supervisor.getFromDef(defname)) self.robot_num = self.robot_num + 1 # new_translation_field = self.robot_handles[-1].getField('translation') # new_translation_field.setSFVec3f(new_translation) # new_rotation_field = self.robot_handles[-1].getField('rotation') # new_rotation_field.setSFRotation(new_rotation) # robot_children = self.robot_handles[-1].getField('children') # frontjoint_node = robot_children.getMFNode(3) # joint = frontjoint_node.getField('jointParameters') # joint = joint.getSFNode() # para = joint.getField('position') # para.setSFFloat(-hingeposition) # battery_remain = float(self.endbattery[self.robot_num - 1]) # battery_field = self.robot_handles[-1].getField('battery') # battery_field.setMFFloat(0,battery_remain) # battery_field.setMFFloat(1,self.startbattery) elif action[-1] >= 0.9 and action[-1] < 1 and self.robot_num >1: battery_field = self.robot_handles[-1].getField('battery') battery_remain = battery_field.getMFFloat(0) self.endbattery[self.robot_num - 1] = battery_remain removerobot = self.robot_handles[-1] removerobot.remove() self.robot_num = self.robot_num - 1 del(self.robot_handles[-1]) def step(self,action): if self.supervisor.step(self.timestep) == -1: exit() self.handle_emitter(action) key = self.keyboard.getKey() observation = self.get_observations() reward = self.get_reward(action) isdone = self.is_done() info = self.get_info() if key == Keyboard.CONTROL + ord("A"): print() print("Actions: ", action) if key == ord("R"): print() print("Rewards: ", reward) if key == Keyboard.CONTROL + ord("Y"): print() print("Observations: ", observation) if key == Keyboard.CONTROL + ord("M"): print() print("message", self.message) if (self.v_action > 1): self.file_writer.add_histogram( "Actions/Per Global Step", action, global_step=self.step_global) if (self.v_observation > 1): self.file_writer.add_histogram( "Observations/Per Global Step", observation, global_step=self.step_global) if (self.v_reward > 1): self.file_writer.add_scalar("Rewards/Per Global Step", reward, self.step_global) if (isdone): self.file_writer.add_scalar( "Is Done/Per Reset step", self.step_cntr, global_step=self.step_reset) self.file_writer.flush() self.score += reward self.step_cntr += 1 self.step_global += 1 return observation,reward,isdone,info def is_done(self): self.steps = self.steps + 1 self.file_writer.flush() if min(self.final_distance) <= self.findThreshold: print("======== + Solved + ========") return True if self.steps >= self.steps_threshold or self.should_done: return True # rotation_field = self.robot_handles[0].getField('rotation').getSFRotation() # """需要计算出模块完全侧边倒的rotation是多少,遇到这种情况直接进行下一次迭代""" # # if rotation_field[0] < -0.4 and rotation_field[1] > 0.4 and rotation_field[2] > 0.4 and rotation_field[3] < -1.5708: # # return True return False def reset(self): print("Reset simulation") self.respawnRobot() self.steps = 0 self.should_done = False self.robot_num = 1 """observation 源代码wrapper有问题""" self.score_history.append(self.score) if (self.v_reward > 0): self.file_writer.add_scalar( "Score/Per Reset", self.score, global_step=self.step_reset) for window in self.windows: if self.step_reset > window: self.file_writer.add_scalar( "Score/With Window {}".format(window), np.average(self.score_history[-window:]), global_step=self.step_reset - window) self.file_writer.flush() self.step_reset += 1 self.step_cntr = 0 self.score = 0 return self.get_default_observation() def flush(self): if self._file_writer is not None: self._file_writer.flush() def close(self): if self._file_writer is not None: self._file_writer.close() def get_info(self): pass def respawnRobot(self): for robot in self.robot_handles: robot.remove() rootNode = self.supervisor.getRoot() childrenField = rootNode.getField('children') childrenField.importMFNode(-1,"robot_0.wbo") # childrenField.importMFNode(-1,"robot_1.wbo") # childrenField.importMFNode(-1,"robot_2.wbo") # childrenField.importMFNode(-1,"robot_3.wbo") # childrenField.importMFNode(-1,"robot_4.wbo") # childrenField.importMFNode(-1,"robot_5.wbo") self.robot_handles = [] for defrobotname in self.robot_list: self.robot_handles.append(self.supervisor.getFromDef(defrobotname)) self.final_target = self.supervisor.getFromDef('final_target') self.supervisor.simulationResetPhysics() self._last_message = None robot_defnames = ['robot_0'] supervisor_env = TaskDecisionSupervisor(robot_defnames, observation_space=OBSERVATION_SPACE,log_dir="logs/results/ddpg", v_action=1,v_observation=1,v_reward=1,windows=[10,\ 10000, 2000]) agent = TD3(lr_actor=0.00025, lr_critic=0.0025, input_dims= OBSERVATION_SPACE, gamma=0.99, tau=0.001, env=supervisor_env, batch_size=512, layer1_size=400, layer2_size=300, layer3_size=200, layer4_size=400, layer5_size=300, layer6_size=200, n_actions=ACTION_SPACE, load_models=False, save_dir='./models/saved/ddpg/') score_history = [] np.random.seed(0) for i in range(1, 20000): done = False score = 0 obs = list(map(float, supervisor_env.reset())) supervisor_env.empty_queue() first_iter = True if i % 10000 == 0: print("================= TESTING =================") while not done: act = agent.choose_action_test(obs).tolist() supervisor_env.robot_step(act) new_state, _, done, _ = supervisor_env.step(act) obs = list(map(float, new_state)) else: print("================= TRAINING =================") while not done: if (not first_iter): act = agent.choose_action_train(obs).tolist() else: first_iter = False act = [0,0] for k in range(0,13): act.append(0.5) supervisor_env.robot_step(act) new_state, reward, done, info = supervisor_env.step(act) agent.remember(obs, act, reward, new_state, int(done)) agent.learn() score += reward obs = list(map(float, new_state)) score_history.append(score) print("===== Episode", i, "score %.2f" % score, "100 game average %.2f" % np.mean(score_history[-100:])) if i % 100 == 0: agent.save_models()
8af84a01d80c776522cf1031d8232f43427a9540
66bb3f65f0157a2b5475903c90a54d5173bc4f0a
/djthia/core/views.py
702cc124bdbc259bc6fdc7f8295d8de0cd43d8fa
[ "MIT" ]
permissive
carthage-college/django-djthia
691233049bcb05391fd82e390edb717f3bc0588a
52401592291a980c7226c0573d415e7cdb8c20d3
refs/heads/master
2023-03-04T08:22:03.055448
2023-02-24T18:33:12
2023-02-24T18:33:12
249,989,382
0
0
MIT
2023-02-24T18:33:56
2020-03-25T13:43:24
Python
UTF-8
Python
false
false
1,886
py
# -*- coding: utf-8 -*- import json import requests from datetime import datetime from django.conf import settings from django.core.cache import cache from django.http import HttpResponse from django.shortcuts import render from django.urls import reverse_lazy from django.utils.safestring import mark_safe from django.views.decorators.csrf import csrf_exempt from djauth.decorators import portal_auth_required from djthia.core.decorators import eligibility @portal_auth_required( session_var='DJTHIA_AUTH', redirect_url=reverse_lazy('access_denied'), ) @eligibility def home(request): """Application home.""" return render(request, 'home.html', {'year': datetime.now().year}) @csrf_exempt @portal_auth_required( session_var='DJTHIA_AUTH', redirect_url=reverse_lazy('access_denied'), ) def clear_cache(request, ctype='blurbs'): """Clear the cache for API content.""" cid = request.POST.get('cid') request_type = 'post' if not cid: cid = request.GET.get('cid') request_type = 'get' if cid: key = 'livewhale_{0}_{1}'.format(ctype, cid) cache.delete(key) timestamp = datetime.timestamp(datetime.now()) earl = '{0}/live/{1}/{2}@JSON?cache={3}'.format( settings.LIVEWHALE_API_URL, ctype, cid, timestamp, ) try: response = requests.get(earl, headers={'Cache-Control': 'no-cache'}) text = json.loads(response.text) cache.set(key, text) api_data = mark_safe(text['body']) except ValueError: api_data = "Cache was not cleared." if request_type == 'post': content_type = 'text/plain; charset=utf-8' else: content_type = 'text/html; charset=utf-8' else: api_data = "Requires a content ID" return HttpResponse(api_data, content_type=content_type)
15964455a90498f40c1b5832baba1979f60603a1
487ce91881032c1de16e35ed8bc187d6034205f7
/codes/CodeJamCrawler/16_0_3_neat/16_0_3_stanm_coin-jam.py
d03fbeb3caa801b73d052e9fa018ecc9ef309635
[]
no_license
DaHuO/Supergraph
9cd26d8c5a081803015d93cf5f2674009e92ef7e
c88059dc66297af577ad2b8afa4e0ac0ad622915
refs/heads/master
2021-06-14T16:07:52.405091
2016-08-21T13:39:13
2016-08-21T13:39:13
49,829,508
2
0
null
2021-03-19T21:55:46
2016-01-17T18:23:00
Python
UTF-8
Python
false
false
945
py
#! /usr/bin/python import sys def rinp(): one = input() _ = input().split(' ') N = int(_[0]) J = int(_[1]) return (N, J) def get_binary(num): return "{0:b}".format(num) def in_base(stng, base): return int(stng, base) def get_div(x): for d in range(2, x): if d * d > x: return 1 if x % d == 0: return d def check_num(x): bnry = get_binary(x) divs = [] for base in range(2, 11): t = in_base(bnry, base) div = get_div(t) if div == 1: return 0 divs.append(div) print (bnry, " ".join([str(d) for d in divs])) return 1 def main(): (N, J) = rinp() start = 2 ** (N - 1) + 1 end = 2 ** N - 1 print ("Case #1:") count = 0 for x in range(end, start, -2): get_binary(x) count += check_num(x) if count == J: break if __name__ == '__main__': main()
49876f9f114cb015c6ec0352ca7ce0cdded1edee
0393e64ac4ed8e3d745b31d44836b58571faaabb
/aefingar_forritun/daemi21-while.py
62b274d4f84b333ad325bb3863b604122476a8e9
[]
no_license
danielthorr18/forritun_git
c3647e1e6dd35cd55287bb2d51066d8ab55ea931
b544371664a15dd0660aef83cdf474e506e1b412
refs/heads/master
2020-03-28T00:04:50.700712
2018-11-15T15:26:42
2018-11-15T15:26:42
147,368,645
0
0
null
null
null
null
UTF-8
Python
false
false
197
py
turns = int(input("Sláðu inn tölu: ")) counter = 0 while counter < turns: pick = int(input("Sláðu inn tölu: ")) if pick % 2 == 1: print("þú valdir", pick) counter += 1
235bea81a7895dc78c4ca7bd704cd9fc6093faec
7c5fb33929116bb77b438de3ead93b3978b5af71
/alf/networks/action_encoder.py
16792ab6d227f26716c18cf61406688f1e6c33a0
[ "Apache-2.0" ]
permissive
HorizonRobotics/alf
d6dac891322a81ccb7e2a9749139627b1eda28cb
b00ff2fa5e660de31020338ba340263183fbeaa4
refs/heads/pytorch
2023-08-21T18:51:41.370566
2023-08-16T00:07:22
2023-08-16T00:07:22
178,459,453
288
57
Apache-2.0
2023-09-14T20:40:20
2019-03-29T18:44:07
Python
UTF-8
Python
false
false
2,719
py
# Copyright (c) 2019 Horizon Robotics. 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. """A simple parameterless action encoder.""" import numpy as np import torch import torch.nn.functional as F import alf from .network import Network class SimpleActionEncoder(Network): """A simple encoder for action. It encodes discrete action to one hot representation and use the original continous actions. The output is the concat of all of them after flattening. """ def __init__(self, action_spec): """ Args: action_spec (nested BoundedTensorSpec): spec for actions """ def check_supported_spec(spec): if spec.is_discrete: assert np.min(spec.minimum) == np.max(spec.minimum) == 0 assert np.min(spec.maximum) == np.max(spec.maximum) alf.nest.map_structure(check_supported_spec, action_spec) self._action_spec = action_spec super().__init__(input_tensor_spec=action_spec, name="ActionEncoder") def forward(self, inputs, state=()): """Generate encoded actions. Args: inputs (nested Tensor): action tensors. Returns: nested Tensor with the same structure as inputs. """ alf.nest.assert_same_structure(inputs, self._action_spec) actions = inputs outer_rank = alf.nest.utils.get_outer_rank(inputs, self._action_spec) def _encode_one_action(action, spec): if spec.is_discrete: num_actions = spec.maximum - spec.minimum + 1 if num_actions.ndim == 0: num_actions = int(num_actions) else: num_actions = int(num_actins[0]) a = F.one_hot(action, num_actions).to(torch.float32) else: a = action if outer_rank > 0: return a.reshape(*a.shape[:outer_rank], -1) else: return a.reshape(-1) actions = alf.nest.map_structure(_encode_one_action, actions, self._action_spec) return torch.cat(alf.nest.flatten(actions), dim=-1), ()
4c4e27e45b34e9331a3ec84ac79cfdf43b698848
f2543f7266cc6f6bebee3d14081daaa676a6f80a
/tensorflow_federated/python/research/optimization/emnist_ae/dataset_test.py
aa4b7a71a5ea7055bce4f6d2649dd8c65cb6a93a
[ "Apache-2.0" ]
permissive
matech96/federated
d497d24e64399f6b1da673a8457e88a18bc29473
b30a26d66162bd02a89a12f119e17925d161a26b
refs/heads/master
2022-11-12T10:20:34.483506
2020-06-11T21:13:02
2020-06-11T21:13:30
271,650,529
0
0
Apache-2.0
2020-06-11T21:31:51
2020-06-11T21:31:50
null
UTF-8
Python
false
false
1,962
py
# Copyright 2019, The TensorFlow Federated Authors. # # 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 tensorflow as tf from tensorflow_federated.python.research.optimization.emnist_ae import dataset TEST_BATCH_SIZE = dataset.TEST_BATCH_SIZE class DatasetTest(tf.test.TestCase): def test_emnist_dataset_structure(self): emnist_train, emnist_test = dataset.get_emnist_datasets( client_batch_size=10, client_epochs_per_round=1, only_digits=True) self.assertEqual(len(emnist_train.client_ids), 3383) sample_train_ds = emnist_train.create_tf_dataset_for_client( emnist_train.client_ids[0]) train_batch = next(iter(sample_train_ds)) train_batch_shape = train_batch[0].shape test_batch = next(iter(emnist_test)) test_batch_shape = test_batch[0].shape self.assertEqual(train_batch_shape.as_list(), [10, 28*28]) self.assertEqual(test_batch_shape.as_list(), [TEST_BATCH_SIZE, 28*28]) def test_global_emnist_dataset_structure(self): global_train, global_test = dataset.get_centralized_emnist_datasets( batch_size=32, only_digits=False) train_batch = next(iter(global_train)) train_batch_shape = train_batch[0].shape test_batch = next(iter(global_test)) test_batch_shape = test_batch[0].shape self.assertEqual(train_batch_shape.as_list(), [32, 28*28]) self.assertEqual(test_batch_shape.as_list(), [TEST_BATCH_SIZE, 28*28]) if __name__ == '__main__': tf.test.main()
caf01fee84b8f19a586c8dadd8b3aa0ec0be2030
be3f8a09a5b8859fffa07673cdfd17723e843b86
/src/Socket_Control/coordinate_collation_interface.py
61179a2af41d390603fb1d43dad2348078877ed4
[ "MIT" ]
permissive
SamKaiYang/2019_Hiwin_Shaking
88646a0a9ff87dfe96a3fb90ede44602bd413d53
d599f8c87dc4da89eae266990d12eb3a8b0f3e16
refs/heads/master
2020-07-22T13:25:21.063822
2019-09-09T03:29:11
2019-09-09T03:29:11
207,216,404
0
0
null
null
null
null
UTF-8
Python
false
false
7,413
py
#!/usr/bin/env python3 # license removed for brevity #encoding:utf-8 import tkinter as tk import shake_strategy_trigger as shake_trig import shake_strategy_content as shake_cont # interface for collation # ======================================================================= # =23/07/2019:add above pos_collation = # ======================================================================= collate_speed=15 def LeftCollate(): shake_cont.InitData(shake_cont.delt_z) # shake_cont.Left(shake_cont.Animation_Action) shake_cont.Left(shake_trig.Hiwin_Solo_Action) shake_cont.InitData(-shake_cont.delt_z) def RightCollate(): shake_cont.InitData(shake_cont.delt_z) # shake_cont.Right(shake_cont.Animation_Action) shake_cont.Right(shake_trig.Hiwin_Solo_Action) shake_cont.InitData(-shake_cont.delt_z) def ArmTestAct(): shake_cont.InitData(shake_cont.delt_z) # shake_cont.ArmTest(shake_cont.Animation_Action) shake_cont.ArmTest(shake_trig.Hiwin_Action) shake_cont.InitData(-shake_cont.delt_z) def CupCollate(): global collate_speed shake_cont.InitData(shake_cont.delt_z) # Action=shake_cont.Animation_Action Action=shake_trig.Hiwin_Solo_Action shake_cont.SpeedModeToggle(1) Action.ArmMove(shake_cont.Above_Shake_Pos,collate_speed,shake_cont.gp_stop,'移動至雪克杯上方') Action.ArmMove(shake_cont.Pre_Grip_Pos,collate_speed,shake_cont.gp_stop,'轉動') Action.ArmMove(shake_cont.Grip_Shake_For_Pour_Pos,collate_speed,shake_cont.gp_stop,'移動至雪克杯') tk.messagebox.showinfo(message='Shake OK?') Action.GripCtrl(shake_cont.Grip_Shake_For_Pour_Pos,collate_speed,shake_cont.gp_tight_catch,'移動至雪克杯','夾住雪克杯') tk.messagebox.showinfo(message='Shake OK?') Action.ArmMove(shake_cont.Lift_Up_Full_Shake_Pos,collate_speed,shake_cont.gp_stop,'移動至雪克杯空位上方') Action.ArmMove(shake_cont.Pour_Product_Ready_Pos,collate_speed,shake_cont.gp_stop,'準備倒飲料至手搖杯') Action.ArmMove(shake_cont.Pour_Product_Pour_Pos,collate_speed,shake_cont.gp_stop,'倒飲料至手搖杯') Action.ArmMove(shake_cont.Pour_Product_Down_Pos,collate_speed,shake_cont.gp_stop,'向下移動') tk.messagebox.showinfo(message='Cup OK?') Action.ArmMove(shake_cont.Pour_Product_Pour_Pos,collate_speed,shake_cont.gp_stop,'向上移動') Action.ArmMove(shake_cont.Pour_Product_Ready_Pos,collate_speed,shake_cont.gp_stop,'倒飲料至手搖杯結束') Action.ArmMove(shake_cont.Lift_Up_Full_Shake_Pos,collate_speed,shake_cont.gp_stop,'移動至雪克杯空位上方') Action.GripCtrl(shake_cont.Grip_Shake_For_Pour_Pos,collate_speed,shake_cont.gp_open,'放下雪克杯','鬆開雪克杯') tk.messagebox.showinfo(message='Cup OK?') Action.ArmMove(shake_cont.Pre_Grip_Pos,collate_speed,shake_cont.gp_stop,'移動至雪克杯上方') Action.ArmMove(shake_cont.Above_Shake_Pos,collate_speed,shake_cont.gp_stop,'轉動') tk.messagebox.showinfo(message='Collation Finished!') Action.ArmMove(shake_cont.Home_Pos,collate_speed,shake_cont.gp_stop,'移動至原位') shake_cont.InitData(-shake_cont.delt_z) def LidCollate(): shake_cont.InitData(shake_cont.delt_z) # Action=shake_cont.Animation_Action Action=shake_trig.Hiwin_Solo_Action shake_cont.SpeedModeToggle(1) Action.LimitArmMove(shake_cont.Above_Lid_Pos,collate_speed,5,shake_cont.gp_stop,'移動至雪克杯蓋上方') Action.GripCtrl(shake_cont.Lid_Pos,collate_speed,shake_cont.gp_tight_catch,'移動至雪克杯蓋','夾住雪克杯蓋') tk.messagebox.showinfo(message='Lid OK?') Action.ArmMove(shake_cont.Above_Lid_Pos,collate_speed,shake_cont.gp_stop,'拿起雪克杯蓋') Action.ArmMove(shake_cont.Above_Shake_Pos,collate_speed,shake_cont.gp_stop,'移動至雪克杯上方') Action.LimitArmMove(shake_cont.Collate_Lid_Pos,collate_speed,5,shake_cont.gp_stop,'蓋杯蓋') tk.messagebox.showinfo(message='Lid OK?') Action.ArmMove(shake_cont.Above_Shake_Pos,collate_speed,shake_cont.gp_stop,'移動至雪克杯上方') Action.ArmMove(shake_cont.Above_Lid_Pos,collate_speed,shake_cont.gp_stop,'移動至雪克杯蓋上方') Action.GripCtrl(shake_cont.Lid_Pos,collate_speed//2,shake_cont.gp_open,'放下雪克杯蓋','鬆開雪克杯蓋') tk.messagebox.showinfo(message='Collation Finished!') Action.ArmMove(shake_cont.Home_Pos,collate_speed,shake_cont.gp_stop,'移動至原位') shake_cont.InitData(-shake_cont.delt_z) def PosCollate(): shake_cont.InitData(shake_cont.delt_z) pos_list = [shake_cont.Home_Pos,shake_cont.Full_Ice_Pos,shake_cont.Above_Ice_Pos, shake_cont.Above_Duo_Duo_Pos,shake_cont.Duo_Duo_Pos,shake_cont.Above_Duo_Duo_Pos, shake_cont.Above_Dong_Gua_T_Pos,shake_cont.Dong_Gua_T_Pos,shake_cont.Above_Dong_Gua_T_Pos, shake_cont.Above_Blace_T_Pos,shake_cont.Blace_T_Pos,shake_cont.Above_Blace_T_Pos, shake_cont.Above_Green_T_Pos,shake_cont.Green_T_Pos,shake_cont.Above_Green_T_Pos, shake_cont.Above_Lid_Pos,shake_cont.Back_Sugar_Pos,shake_cont.Above_Sugar_Unspined_Pos, shake_cont.Above_Sugar_Unspined_Pos,shake_cont.Back_Sugar_Pos] pause_list=[1,4,7,10,13,18] shake_cont.SpeedModeToggle(1) for i in range(len(pos_list)): shake_trig.Hiwin_Action.ArmMove(pos_list[i],collate_speed,0,'test point({}/{})'.format(i+1,len(pos_list))) # shake_cont.Animation_Action.ArmMove(pos_list[i],20,0,'test point({}/{})'.format(i+1,len(pos_list))) if i in pause_list: tk.messagebox.showinfo(message='Next Point?') tk.messagebox.showinfo(message='Collation Finished!') # shake_cont.Home(shake_cont.Animation_Action) shake_cont.Home(shake_trig.Hiwin_Action) shake_cont.InitData(-shake_cont.delt_z) def Collation(): collate = tk.Toplevel() collate.title('Coordinate Collation') collate.geometry('620x355') collate.wm_attributes("-topmost",1) def CollateOK(): collate.destroy() # shake_cont.Home(shake_cont.Animation_Action) shake_cont.Home(shake_trig.Hiwin_Solo_Action) arm_test = tk.Button(collate,text='Arm Test',font=('Arial', 15),width=45,height=2,command=ArmTestAct) arm_test.place(x=50,y=35) left_collate = tk.Button(collate,text='Left',font=('Arial', 15),width=19,height=2,command=LeftCollate) left_collate.place(x=50,y=110) right_collate = tk.Button(collate,text='Right',font=('Arial', 15),width=19,height=2,command=RightCollate) right_collate.place(x=335,y=110) pos_collate = tk.Button(collate,text='Pos',font=('Arial', 15),width=12,height=2,command=PosCollate) pos_collate.place(x=50,y=185) cup_collate = tk.Button(collate,text='Cup',font=('Arial', 15),width=12,height=2,command=CupCollate) cup_collate.place(x=230,y=185) lid_collate = tk.Button(collate,text='Lid',font=('Arial', 15),width=12,height=2,command=LidCollate) lid_collate.place(x=410,y=185) collate_ok = tk.Button(collate,text='OK',font=('Arial', 15),width=45,height=2,command=CollateOK) collate_ok.place(x=50,y=260) def BackHome(): collate.destroy() # shake_cont.Home(shake_cont.Animation_Action) shake_cont.Home(shake_trig.Hiwin_Solo_Action) collate.protocol('WM_DELETE_WINDOW', BackHome) collate.mainloop()
23993e6b312f5319a07ecd4680effe7fcf0d9c67
0561e7ef249845903457870b50331977af95bb7c
/networks/pemp_stage2.py
63de0014b8370800d1d72b8f18b2ed17c6a45622
[ "MIT" ]
permissive
Jarvis73/PEMP
70412d5d600aaabf13eaedea9fe0af0f02d2785c
d7a300f8b7565efe478473ee4a7ee63bf0031c8c
refs/heads/main
2023-05-27T22:24:30.209445
2021-06-07T07:00:57
2021-06-07T07:00:57
372,802,221
8
1
null
null
null
null
UTF-8
Python
false
false
11,778
py
from collections import OrderedDict from pathlib import Path import torch import torch.nn as nn import torch.nn.functional as F from networks import backbones from networks.pemp_stage1 import net_ingredient, PEMPStage1, pretrained_weights, backbone_error PriorNet = PEMPStage1 @net_ingredient.config def priornet_config(): backbone2 = "resnet50" # str, structure of the feature extractor. Default to stage1's backbone. [vgg16, resnet50, resnet101] protos2 = 3 # int, number of prototypes per class drop_rate2 = 0.5 # float, drop rate used in the Dropout of the purifier cm = True # bool, use communication module class PEMPStage2(backbones.BaseModel, nn.Module): """ Stage 1 of the proposed Prior-Enhanced network with Meta-Prototypes. Parameters ---------- shot: int Number of support images in each episode query: int Number of query images in each episode. Fixed to 1. backbone, backbone2, init_channels, out_channels, protos2, drop_rate2, cm: [Config] Notes ----- Parameters denoted with '[Config]' are autofilled by sacred configuration and there is no need to manually input. """ @net_ingredient.capture def __init__(self, shot, query, logger, backbone, backbone2, init_channels, out_channels, protos2, drop_rate2, cm): super(PEMPStage2, self).__init__() if not backbone2: backbone2 = backbone pretrained = pretrained_weights[backbone2] if backbone2 == "vgg16": self.encoder = nn.Sequential(OrderedDict([ ('backbone', backbones.VGG16CM(init_channels + 1, pretrained=pretrained, lastRelu=False, shot_query=shot + query)) ])) self.__class__.__name__ = "PEMP_Stage2/VGG16" + cm * "+CM" elif backbone2 == "resnet50": self.encoder = nn.Sequential(OrderedDict([ ('backbone', backbones.ResNetCM(init_channels + 1, backbones.BottleNeck, layers=[3, 4, 6], freeze_bn=True, ret_features=False, pretrained=pretrained, shot_query=shot + query)), ('purifier', nn.Sequential( nn.Conv2d(1024, 256, kernel_size=1, stride=1, bias=True), nn.ReLU(), nn.Dropout2d(drop_rate2), nn.Conv2d(256, 256, kernel_size=3, stride=1, padding=1, bias=True), nn.ReLU(), nn.Dropout2d(drop_rate2), backbones.ASPP(inc=256, midc=256, outc=out_channels, drop_rate=drop_rate2))) ])) self.__class__.__name__ = f"PEMP_Stage2/Resnet50" + cm * "+CM" elif backbone2 == "resnet101": self.encoder = nn.Sequential(OrderedDict([ ('backbone', backbones.ResNetCM(init_channels + 1, backbones.BottleNeck, layers=[3, 4, 23], freeze_bn=True, ret_features=False, pretrained=pretrained, shot_query=shot + query)), ('purifier', nn.Sequential( nn.Conv2d(1024, 256, kernel_size=1, stride=1, bias=True), nn.ReLU(), nn.Dropout2d(drop_rate2), nn.Conv2d(256, 256, kernel_size=3, stride=1, padding=1, bias=True), nn.ReLU(), nn.Dropout2d(drop_rate2), backbones.ASPP(inc=256, midc=256, outc=out_channels, drop_rate=drop_rate2))) ])) self.__class__.__name__ = f"PEMP_Stage2/Resnet50" + cm * "+CM" else: raise ValueError(backbone_error.format(backbone2)) if protos2 > 0: self.ctr = torch.nn.Parameter(torch.rand(out_channels, protos2 * 2), requires_grad=True) else: self.ctr = None logger.info(f" ==> Model {self.__class__.__name__} created") def forward(self, sup_img, sup_mask, qry_img, qry_prior, out_shape=None, ret_ind=False): """ Parameters ---------- sup_img: torch.Tensor, Support images of the shape [B, S, 3, H, W] and dtype float32 sup_mask: torch.Tensor Support labels of the shape [B, S, 2, H, W] and dtype float32 qry_img: torch.Tensor Query images of the shape [B, Q, 3, H, W] and dtype float32 qry_prior: torch.Tensor Query prior of the shape [BQ, 1, H, W] width dtype float32 out_shape : tuple Output size of the prediction. A tuple of two integers. ret_ind: bool Return indices of prediction map for visualization. Notes ----- Boundary pixels (mask=255) are ignored during training/testing. Therefore sup_mask_fg and sup_mask_bg are not complementary and both of them need to be provided. """ B, S, channel, H, W = sup_img.size() Q = qry_img.size(1) # Input channel 1-3: Images img_cat = torch.cat((sup_img, qry_img), dim=1).view(B * (S + Q), channel, H, W) # Input channel 4: Pirors sup_prior = sup_mask[:, :, :1] # support masks used as the prior # [B, S, 1, H, W] qry_prior = qry_prior.view(B, Q, *qry_prior.shape[-3:]) # [B, Q, 1, H, W] prior_cat = torch.cat((sup_prior, qry_prior.float()), dim=1) prior_cat = prior_cat.view(B * (S + Q), 1, H, W) inputs = torch.cat((img_cat, prior_cat), dim=1) # [B(S + Q), 4, H, W] features = self.encoder((inputs, prior_cat)) # [B(S + Q), c, h, w] _, c, h, w = features.size() features = features.view(B, S + Q, c, h, w) # [B, S + Q, c, h, w] sup_fts = features[:, :S] # [B, S, c, h, w] qry_fts = features[:, S:] # [B, Q, c, h, w] sup_mask = sup_mask.view(B * S, 2, H, W) # [BS, 2, H, W] sup_mask = F.interpolate(sup_mask, (h, w), mode="nearest") # [BS, 2, h, w] sup_mask_fg, sup_mask_bg = sup_mask.unbind(dim=1) # [BS, h, w] pred = self.mpm(sup_fts, qry_fts, sup_mask_fg, sup_mask_bg, ret_ind) # [BQ, 2, h, w] if out_shape is None: out_shape = (H, W) if ret_ind: pred, response = pred output = F.interpolate(pred, out_shape, mode='bilinear', align_corners=True) # [BQ, 2, H, W] response = F.interpolate(response.unsqueeze(dim=1).float(), out_shape, mode='nearest') response = response.squeeze(dim=1).long() # [BQ, H, W] return output, response else: output = F.interpolate(pred, out_shape, mode='bilinear', align_corners=True) # [BQ, 2, H, W] return output @net_ingredient.capture def mpm(self, sup_fts, qry_fts, sup_fg, sup_bg, ret_ind, protos2): B, S, c, h, w = sup_fts.shape sup_fts = sup_fts.reshape(-1, c, h * w) qry_fts = qry_fts.reshape(-1, c, 1, h, w) sup_fg = sup_fg.view(-1, 1, h * w) # [BS, 1, hw] sup_bg = sup_bg.view(-1, 1, h * w) # [BS, 1, hw] if self.ctr is not None: ctr = self.ctr.view(1, c, protos2 * 2) # [1, c, 2p] mask = torch.stack((sup_fg, sup_bg), dim=1) # [BS, 2, 1, hw] D = -((sup_fts.unsqueeze(dim=2) - ctr.unsqueeze(dim=3)) ** 2).sum(dim=1) # [BS, 2p, hw] D = D.view(-1, 2, protos2, h * w) # [BS, 2, p, hw] D = (torch.softmax(D, dim=2) * mask).view(-1, 1, protos2 * 2, h * w) # [BS, 1, 2p, hw] masked_fts = sup_fts.view(-1, c, 1, h * w) * D # [BS, c, 2p, hw] ctr = (masked_fts.sum(dim=3) / (D.sum(dim=3) + 1e-6)).view(B, S, c, 2, protos2) # [B, S, c, 2, p] ctr = ctr.transpose(3, 4).reshape(B, S, c * protos2, 2) # [B, S, cp, 2] ctr = ctr.mean(dim=1) # [B, cp, 2] self.adaptive_p = ctr.view(B, c, protos2, 2).transpose(2, 3).reshape(B, c, -1) # [B, c, 2p] fg_proto, bg_proto = ctr.view(B, c, protos2, 2).unbind(dim=3) # [B, c, p] max_v = self.compute_similarity(fg_proto, bg_proto, qry_fts).max(dim=2) pred = max_v.values # [BQ, 2, h, w] if ret_ind: ind = max_v.indices # [BQ, 2, h, w] response = ind[:, 0].clone() # background select = pred.argmax(dim=1) == 1 response[select] = ind[:, 1][select] + 3 # foreground return pred, response else: fg_vecs = torch.sum(sup_fts * sup_fg, dim=-1) / (sup_fg.sum(dim=-1) + 1e-5) # [BS, c] bg_vecs = torch.sum(sup_fts * sup_bg, dim=-1) / (sup_bg.sum(dim=-1) + 1e-5) # [BS, c] fg_proto = fg_vecs.view(B, S, c).mean(dim=1) bg_proto = bg_vecs.view(B, S, c).mean(dim=1) pred = self.compute_similarity(fg_proto, bg_proto, qry_fts.view(-1, c, h, w)) # [BQ, 2, h, w] return pred @net_ingredient.capture def compute_similarity(self, fg_proto, bg_proto, qry_fts, dist_scalar): """ Make prediction on the query image according to the foreground prototype and the background prototype. Parameters ---------- fg_proto: torch.Tensor Foreground prototype with the shape of [B, c] bg_proto: torch.Tensor Background prototype with the shape of [B, c] qry_fts: torch.Tensor Query feature maps extracted from the backbone with the shape of [BQ, c, h, w] dist_scalar: float, int [Config] Distance scalar when computing similarity. Returns ------- pred: torch.Tensor Prediction of the query image segmentation with the shape of [BQ, 2, p, h, w] """ fg_distance = F.cosine_similarity( qry_fts, fg_proto[..., None, None], dim=1) * dist_scalar # [BQ, 3, h, w] bg_distance = F.cosine_similarity( qry_fts, bg_proto[..., None, None], dim=1) * dist_scalar # [BQ, 3, h, w] pred = torch.stack((bg_distance, fg_distance), dim=1) # [BQ, 2, 3, h, w] return pred ModelClass = PEMPStage2
7f824ee40e811bbb0b10b06bebe9de412a97a178
65e07d1e35598e5686e743e9bdefcdd5e1269a0d
/archiveit_redirect.py
51440f3afb3374425033df8ef6d544f7754a5e5a
[]
no_license
ale-gaeta/bentley_scripts
94dbf3e120c218ec0af8ed235bc304ca45b3518e
2ad4b986212715a495036697d78952dc53dad74c
refs/heads/master
2023-03-15T14:12:12.595590
2016-06-30T19:02:55
2016-06-30T19:02:55
null
0
0
null
null
null
null
UTF-8
Python
false
false
6,501
py
import os from os.path import join import requests from lxml import etree import csv import re import HTMLParser def get_redirect_metadata(redirect_dict, collection_id, redirect_dir): skip = ['createdDate','lastUpdatedDate','active','public','note','url'] starting_seeds = {} for seed in redirect_dict: starting_seeds[seed] = '' with requests.Session() as s: collection_feed = s.get('https://partner.archive-it.org/seam/resource/collectionFeed?accountId=934&collectionId=' + collection_id) collection_metadata = etree.fromstring(collection_feed.text.encode('utf-8')) tree = etree.ElementTree(collection_metadata) seeds = tree.xpath('//seed') for seed in seeds: url = seed.xpath('./url')[0].text if url in starting_seeds: starting_seeds[url] = tree.getpath(seed) redirect_metadata = [] add_deactivate = {} redirect_investigate = {} entity_parser = HTMLParser.HTMLParser() for seed in starting_seeds: if len(starting_seeds[seed]) > 0: new_seed = redirect_dict[seed] add_deactivate[seed] = new_seed seed_metadata = {} seed_path = starting_seeds[seed] seed_element = tree.xpath(seed_path)[0] for elem in seed_element.xpath('.//*'): if elem.text is not None and not elem.tag in skip and not 'name' in elem.attrib: elem_name = elem.tag elem_text = entity_parser.unescape(elem.text.replace('&#8220;','"').replace('&#8221;','"').replace('&#8217;',"'")) if elem_name not in seed_metadata: seed_metadata[elem_name] = [] seed_metadata[elem_name].append(elem_text.encode('utf-8')) elif 'name' in elem.attrib: if elem.attrib['name'] not in skip: elem_name = elem.attrib['name'] elem_text = entity_parser.unescape(elem.text.replace('&#8220;','"').replace('&#8221;','"').replace('&#8217;',"'")) if elem_name not in seed_metadata: seed_metadata[elem_name] = [] seed_metadata[elem_name].append(elem_text.encode('utf-8')) seed_metadata['url'] = [] seed_metadata['url'].append(new_seed) seed_metadata['Note'] = [] seed_metadata['Note'].append("QA NOTE: This seed was created as a result of the previous seed URL redirecting to this URL. Previous captures under seed URL " + seed) redirect_metadata.append(seed_metadata) else: redirect_investigate[seed] = redirect_dict[seed] with open(join(redirect_dir,'add_and_deactivate.csv'),'ab') as add_deactivate_csv: writer = csv.writer(add_deactivate_csv) writer.writerow(['Add','Deactivate','Deactivation Note']) for seed, new_seed in add_deactivate.items(): writer.writerow([new_seed, seed, 'QA NOTE: Seed deactivated. Seed URL redirects to ' + new_seed + '. A new seed with the redirected seed URL has been added.']) if len(redirect_investigate) > 0: with open(join(redirect_dir,'redirect_investigate.csv'),'ab') as investigate_csv: writer = csv.writer(investigate_csv) writer.writerow(['Seed URL','Redirect URL']) for seed, new_seed in redirect_investigate.items(): writer.writerow([seed, new_seed]) header_order = ['url','Title','Subject','Personal Creator','Corporate Creator','Coverage','Description','Publisher','Note'] redirect_csv = join(redirect_dir,'redirect_metadata.csv') header_counts = {} for seed in redirect_metadata: for element in seed: count = len(seed[element]) elem_lower = element.lower() if element not in header_counts: header_counts[element] = count elif count > header_counts[element]: header_counts[element] = count for element in header_order: elem_lower = element.lower() if element not in header_counts and elem_lower not in header_counts: header_counts[element] = 1 for seed in redirect_metadata: for element in header_counts: if element not in seed: seed[element] = [] for element in seed: current_count = len(seed[element]) header_count = header_counts[element] difference = header_count - current_count if difference > 0: seed[element].extend([''] * difference) header_row = [] header_counts_lower = {k.lower():v for k,v in header_counts.items()} for element in header_order: elem_lower = element.lower() header_row.extend([element] * header_counts_lower[elem_lower]) with open(redirect_csv,'ab') as csvfile: writer = csv.writer(csvfile) writer.writerow(header_row) for seed in redirect_metadata: row = [] for element in header_order: elem_lower = element.lower() if element in seed: row.extend([item for item in seed[element]]) elif elem_lower in seed: row.extend([item for item in seed[elem_lower]]) with open(redirect_csv,'ab') as csvfile: writer = csv.writer(csvfile) writer.writerow(row) def main(): job_numbers = raw_input('Enter a comma separated list of job numbers: ') base_dir = raw_input('Enter the directory in which job files are saved (e.g., U:/web_archives/jobs): ') jobs = [job.strip() for job in job_numbers.split(',')] for job in jobs: redirect_dict = {} job_dir = join(base_dir,job) with open(join(job_dir,'seedstatus.csv'),'rb') as csvfile: reader = csv.reader(csvfile) first_row = reader.next() collection_string = first_row[0] collection_id = re.findall(r'(\d+)\t',collection_string)[0] redirect_dir = join(job_dir,'redirects') redirect_csv = join(redirect_dir,'redirect_information.csv') with open(redirect_csv,'rb') as redirect_csv: reader = csv.reader(redirect_csv) next(reader,None) for row in reader: seed = row[0].strip() redirect = row[1].strip() redirect_dict[seed] = redirect get_redirect_metadata(redirect_dict,collection_id,redirect_dir) main()
310c8ae150190d6740b6121ace9773d0a661e430
54f352a242a8ad6ff5516703e91da61e08d9a9e6
/Source Codes/CodeJamData/11/32/13.py
c3ba2816bd0c1116751668d1ffb42f0e53b1d0e5
[]
no_license
Kawser-nerd/CLCDSA
5cbd8a4c3f65173e4e8e0d7ed845574c4770c3eb
aee32551795763b54acb26856ab239370cac4e75
refs/heads/master
2022-02-09T11:08:56.588303
2022-01-26T18:53:40
2022-01-26T18:53:40
211,783,197
23
9
null
null
null
null
UTF-8
Python
false
false
2,460
py
filename = "B-large.in" outputname = filename + "out.txt" inFile = open(filename, 'r') outFile = open(outputname, 'w') numCases = int(inFile.readline()) def getTime(fullGapList, ttb, numStations): currTime = 0 counter = 0 while currTime < ttb and counter < len(fullGapList): currTime += fullGapList[counter]*2 counter += 1 if counter == len(fullGapList): return sum(fullGapList)*2 newGapList = fullGapList[counter:] if currTime != ttb: newGapList += [(currTime - ttb)/2] newGapList.sort() newGapList.reverse() stations = newGapList[0:numStations] return sum(fullGapList)*2 - sum(stations) for i in range(numCases): print i nextLine = inFile.readline().split() numStations = int(nextLine[0]) timeToBuild = int(nextLine[1]) numStars = int(nextLine[2]) numGaps = int(nextLine[3]) gapList = [] for j in range(numGaps): gapList += [int(nextLine[4+j])] fullGapList = [] while len(fullGapList) < numStars: fullGapList += gapList fullGapList = fullGapList[0:numStars] answer = getTime(fullGapList, timeToBuild, numStations) outFile.write("Case #" + str(i+1) + ": " + str(answer) + "\n") inFile.close() outFile.close() def oneStation(fullGapList, pos, ttb): priorTime = sum(fullGapList[0:pos])*2 afterTime = sum(fullGapList[pos+1:])*2 if priorTime > ttb: return priorTime + fullGapList[pos] + afterTime elif priorTime + 2*fullGapList[pos] < ttb: return priorTime + 2*fullGapList[pos] + afterTime else: return priorTime + (ttb-priorTime)/2 + fullGapList[pos] + afterTime def twoStation(fullGapList, pos1, pos2, ttb): priorTime = sum(fullGapList[0:pos1])*2 if priorTime > ttb: afterBoost = priorTime + fullGapList[pos1] elif priorTime + 2*fullGapList[pos1] < ttb: afterBoost = priorTime + 2*fullGapList[pos1] else: afterBoost = priorTime + (ttb-priorTime)/2 + fullGapList[pos1] priorTime = afterBoost + sum(fullGapList[pos1+1:pos2])*2 if priorTime > ttb: afterBoost = priorTime + fullGapList[pos2] elif priorTime + 2*fullGapList[pos2] < ttb: afterBoost = priorTime + 2*fullGapList[pos2] else: afterBoost = priorTime + (ttb-priorTime)/2 + fullGapList[pos2] return afterBoost + sum(fullGapList[pos2+1:])*2
d521724116b490a6181f5b3f286c4bc901268838
93ff3a214354128910c5c77824c64678d78e556d
/downloads/views.py
cd885baeb2cf1ca88ff849bf9cbe45dc2e079bad
[ "LicenseRef-scancode-public-domain", "MIT" ]
permissive
samoKrajci/roots
1fc2c7f205ba9dc0d9026026253c7349c3a551aa
9c6bf6ed30e8e6ff9099e9dca6d56a2df2ef10b0
refs/heads/master
2021-09-23T02:20:17.927687
2017-01-01T19:05:22
2017-01-01T19:05:38
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,090
py
from sendfile import sendfile from django.conf import settings from django.core.exceptions import PermissionDenied from django.contrib.auth.decorators import login_required @login_required def download_protected_file(request, model_class, path_prefix, path): """ This view allows download of the file at the specified path, if the user is allowed to. This is checked by calling the model's can_access_files method. """ # filepath is the absolute path, mediapath is relative to media folder filepath = settings.SENDFILE_ROOT + path_prefix + path filepath_mediapath = path_prefix + path if request.user.is_authenticated(): # Superusers can access all files if request.user.is_superuser: return sendfile(request, filepath) else: # We need to check can_access_files on particular instance obj = model_class.get_by_filepath(filepath_mediapath) if obj is not None and obj.can_access_files(request.user): return sendfile(request, filepath) raise PermissionDenied
2578e88ce408cf417424eda2136335cf2eb1c5d0
a851830dbfd27d850e887d1cbc56c906512585d2
/AS0/ps0-4-code.py
7c37625f2438b193a9384e90e5fc0fc757b603e6
[]
no_license
AlexisDrch/Computer-Vision
d6861f1e11401b6c0b131026bc22a76433b74025
dc2687d53af73dd4e973bf969c48ae9f343bd49d
refs/heads/master
2021-01-25T11:55:47.316194
2018-04-06T06:15:49
2018-04-06T06:15:49
123,440,935
8
1
null
null
null
null
UTF-8
Python
false
false
2,549
py
# ### 4. Arithmetic and Geometric operations from scipy import misc from scipy import ndimage import numpy as np import matplotlib.pyplot as plt import matplotlib.image as mpimg # ### a. # input 2 pictures as numpy ndarray picture_1 = misc.imread('./pictures/ps0-1-a-1.jpg') picture_2 = misc.imread('./pictures/ps0-1-a-2.jpg') # set red and blue channel to value 0 mono_g_picture = picture_1.copy() mono_g_picture[:,:,0] = mono_g_picture[:,:,2] = 0 # In[40]: green_mg1_values = mono_g_picture[:,:,1].copy() min_g1_value = np.min(green_mg1_values) max_g1_value = np.max(green_mg1_values) mean_g1_value = np.mean(green_mg1_values) std_g1_value = np.std(green_mg1_values) print('From the MG1 pixel values : min = {} | max = {} | mean = {} | stand dev = {} ' .format(min_g1_value, max_g1_value, mean_g1_value, std_g1_value)) print('\n') print('To compute these values, it is necessary to consider the pixel values as a unique array,' + 'here : the green pixel value of all the instances in the picture (green channel). ' + 'Then, basic mathematic ops can be applied.') # #### b. Operations on mg1 # In[41]: # substracting the mean green_mg1_values = green_mg1_values - mean_g1_value # diving by the std green_mg1_values = green_mg1_values / std_g1_value # multiply by 10 green_mg1_values = green_mg1_values * 10 # add mean green_mg1_values = green_mg1_values + mean_g1_value # plot (for notebook) and output the resulting picture mono_g_picture_flat = mono_g_picture.copy() mono_g_picture_flat[:,:,1] = green_mg1_values #plt.imshow(mono_g_picture_flat) #plt.title('Flat M1g') #plt.show() mpimg.imsave('./output/ps0-4-b-1.jpg', mono_g_picture_flat) # #### c. Shift M1g # In[42]: shifted_mg1 = mono_g_picture.copy() #shift two pixels to the left, except two last columns for i in range(512): for j in range(510): shifted_mg1[i,j] = shifted_mg1[i, j+2] # plot (for notebook) and output resulting picture #plt.imshow(shifted_mg1) #plt.show() mpimg.imsave('./output/ps0-4-c-1.jpg', shifted_mg1) # #### d. M1g - shiftedM1g # In[47]: sub_m1g = mono_g_picture - shifted_mg1 # verif that green chanel has valid values (not < 0) verif_array = np.where(sub_m1g < 0) print(verif_array) # plot (for notebook) and output resulting picture #plt.imshow(sub_m1g) #plt.show() mpimg.imsave('./output/ps0-4-d-1.jpg', sub_m1g) # The value of a pixel represent its light intensity. Since negative light intensity doesn't exist, negative value for a pixel is a bug, and does not represent a physical quantity. exit()
3bb95ced81396f906f7822e77e1d040cd8901b31
d33b2ce08591d23b06ab466f5dd6e302e3d4af2f
/fgcz_biobeamer.py.bak
36ca192e64d75ab8a4deb5d3140b2ca66875ef94
[]
no_license
Python3pkg/BioBeamer
8b5fceb94664dbe7ce15603276f9628bbe6d25ca
61dc1299fb47ece91ff9a7d333149cb2bfd500f3
refs/heads/master
2021-01-21T09:28:49.967511
2017-05-18T06:10:05
2017-05-18T06:10:05
91,655,529
0
0
null
2017-05-18T06:10:03
2017-05-18T06:10:03
null
UTF-8
Python
false
false
1,595
bak
#!/usr/bin/python # -*- coding: latin1 -*- """ Copyright 2006-2015 Functional Genomics Center Zurich This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Author / Maintainer: Christian Panse <[email protected]>, Witold E. Wolski <[email protected]> """ # pip install PyFGCZ import biobeamer import sys import socket import time configuration_url = "http://fgcz-s-021.uzh.ch/config/" if __name__ == "__main__": print( "hostname is {0}.".format(socket.gethostname())) bio_beamer = biobeamer.Robocopy() biobeamer_xsd = "{0}/BioBeamer.xsd".format(configuration_url) biobeamer_xml = "{0}/BioBeamer.xml".format(configuration_url) bio_beamer.para_from_url(xsd=biobeamer_xsd, xml=biobeamer_xml) bio_beamer.run() time.sleep(5) BBChecker = biobeamer.Checker() BBChecker.para_from_url(xsd=biobeamer_xsd, xml=biobeamer_xml) BBChecker.run() sys.stdout.write("done. exit 0\n") time.sleep(5) sys.exit(0)
727bc0e499477df5820ad111e776f25fb0102e8f
a5c975a059b785a413c5f8b47bc7127e326c4382
/08_cell_line_prediction/nbconverted/plot_drug_response_classification.py
1ed4b814ad288e7bec2cfab83ce5de61e928c983
[ "BSD-3-Clause" ]
permissive
greenelab/pancancer-evaluation
a36d00c52ec1a6c44a1b3d7593adc107b546ea2c
7650b0ff18dfa466b74937cfcac3317443d01056
refs/heads/master
2023-08-29T00:32:32.524308
2023-08-15T18:51:41
2023-08-15T18:51:41
283,575,430
9
2
BSD-3-Clause
2023-08-15T18:51:42
2020-07-29T18:38:57
Jupyter Notebook
UTF-8
Python
false
false
8,622
py
#!/usr/bin/env python # coding: utf-8 # ## Analysis of drug response binary classification with held-out cancer types # In[1]: import os import sys import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import pancancer_evaluation.config as cfg import pancancer_evaluation.utilities.analysis_utilities as au get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') # In[2]: # analysis of results generated by script: # 08_cell_line_classification/run_drug_response_prediction.py # (with varying feature_selection parameters) # we ran two types of experiments, one where we hold out each individual # cancer type in CCLE and one where we pool liquid cancers and solid cancers # and hold them out together # here, we can choose which experiment we want to look at the results of stratify_by = 'liquid_or_solid' if stratify_by == 'cancer_type': single_cancer_dir = os.path.join('results', 'drug_response_binary', 'single_cancer') pancancer_dir = os.path.join('results', 'drug_response_binary_all', 'pancancer') pancancer_only_dir = os.path.join('results', 'drug_response_binary_all', 'all_other_cancers') elif stratify_by == 'liquid_or_solid': single_cancer_dir = os.path.join('results', 'drug_response_binary_liquid_or_solid', 'single_cancer') pancancer_dir = os.path.join('results', 'drug_response_binary_liquid_or_solid', 'pancancer') pancancer_only_dir = os.path.join('results', 'drug_response_binary_liquid_or_solid', 'all_other_cancers') # feature selection dimensions tested n_dims = [100, 250, 500, 1000, 5000] # feature selection methods tested fs_methods = [ 'mad', 'pancan_f_test', 'median_f_test', 'random' ] # drug to plot results for drug = 'Cisplatin' # metric to plot results for metric = 'aupr' delta_metric = 'delta_{}'.format(metric) # location to save plots to output_plots = False if metric == 'auroc': output_plots_dir = cfg.ccle_fs_plots_dir / 'drug_response_binary' / 'auroc' else: output_plots_dir = cfg.ccle_fs_plots_dir / 'drug_response_binary' # ### Load results # # We load the results of the single cancer, pan-cancer, and "pan-cancer only" (aka "all other cancers") experiments here. # In[3]: single_cancer_df = au.load_prediction_results_fs( single_cancer_dir, cfg.fs_methods ) single_cancer_df = single_cancer_df[single_cancer_df.n_dims.isin(n_dims)].copy() single_cancer_df['train_set'] = 'single_cancer' for n in n_dims: for fs_method in fs_methods: single_cancer_df.loc[ (single_cancer_df.fs_method == fs_method) & (single_cancer_df.n_dims == n), 'fs_method' ] = '{}.{}'.format(fs_method, n) single_cancer_df.rename(columns={'gene': 'drug'}, inplace=True) print(np.unique(single_cancer_df.seed)) print(np.unique(single_cancer_df.n_dims)) print(np.unique(single_cancer_df.fs_method)) print(single_cancer_df.shape) single_cancer_df.head() # In[4]: pancancer_df = au.load_prediction_results_fs( pancancer_dir, cfg.fs_methods ) pancancer_df = pancancer_df[pancancer_df.n_dims.isin(n_dims)].copy() pancancer_df['train_set'] = 'pancancer' for n in n_dims: for fs_method in fs_methods: pancancer_df.loc[ (pancancer_df.fs_method == fs_method) & (pancancer_df.n_dims == n), 'fs_method' ] = '{}.{}'.format(fs_method, n) pancancer_df.rename(columns={'gene': 'drug'}, inplace=True) print(np.unique(pancancer_df.seed)) print(np.unique(pancancer_df.fs_method)) print(pancancer_df.shape) pancancer_df.head() # In[5]: pancancer_only_df = au.load_prediction_results_fs( pancancer_only_dir, cfg.fs_methods ) pancancer_only_df = pancancer_only_df[pancancer_only_df.n_dims.isin(n_dims)].copy() pancancer_only_df['train_set'] = 'pancancer_only' for n in n_dims: for fs_method in fs_methods: pancancer_only_df.loc[ (pancancer_only_df.fs_method == fs_method) & (pancancer_only_df.n_dims == n), 'fs_method' ] = '{}.{}'.format(fs_method, n) pancancer_only_df.rename(columns={'gene': 'drug'}, inplace=True) print(np.unique(pancancer_only_df.seed)) print(np.unique(pancancer_only_df.fs_method)) print(pancancer_only_df.shape) pancancer_only_df.head() # In[6]: # get difference between true and shuffled models, split by # feature selection method and holdout cancer type def compare_from_experiment(experiment_df): compare_df = [] for fs_method in experiment_df.fs_method.unique(): for holdout_cancer_type in experiment_df.holdout_cancer_type.unique(): compare_df.append( au.compare_control_ind( experiment_df[ (experiment_df.fs_method == fs_method) & (experiment_df.holdout_cancer_type == holdout_cancer_type) ], identifier='drug', metric=metric, verbose=True) .assign(fs_method=fs_method, holdout_cancer_type=holdout_cancer_type) ) return pd.concat(compare_df) single_cancer_compare_df = compare_from_experiment(single_cancer_df) pancancer_compare_df = compare_from_experiment(pancancer_df) pancancer_only_compare_df = compare_from_experiment(pancancer_only_df) print(single_cancer_compare_df.shape, pancancer_compare_df.shape, pancancer_only_compare_df.shape) # In[7]: # split fs_method and n_dims so we can make a line plot # over different values of n_dims for compare_df in [ single_cancer_compare_df, pancancer_compare_df, pancancer_only_compare_df ]: compare_df[['fs_method', 'n_dims']] = compare_df.fs_method.str.split('.', 1, expand=True) compare_df['n_dims'] = compare_df.n_dims.astype(int) # In[8]: print(single_cancer_compare_df.fs_method.unique()) print(single_cancer_compare_df.n_dims.unique()) single_cancer_compare_df.head() # ### Plot average performance across cancer types and number of features selected # In[9]: print(single_cancer_compare_df.identifier.unique()) # In[10]: print(single_cancer_compare_df.fs_method.unique()) # In[11]: sns.set({'figure.figsize': (18, 6)}) sns.set_context('notebook') fig, axarr = plt.subplots(1, 3) dfs_to_plot = [ single_cancer_compare_df, pancancer_compare_df, pancancer_only_compare_df ] names_to_plot = [ 'Train single-cancer', 'Train pan-cancer', 'Train all other cancer types' ] fs_method_order = [ 'mad', 'pancan_f_test', 'median_f_test', 'random' ] for ix, compare_df in enumerate(dfs_to_plot): ax = axarr[ix] # averaged over cancer types plot_df = (compare_df[(compare_df.identifier == drug)] .sort_values(by='n_dims', ascending=True) ) sns.pointplot(data=plot_df, x='n_dims', y=delta_metric, hue='fs_method', hue_order=fs_method_order, ax=ax) ax.set_title(names_to_plot[ix]) ax.set_xlabel('Number of features selected') ax.set_ylim(-0.2, 1) plt.suptitle('{}, averaged over all holdout cancer types'.format(drug)) plt.tight_layout() print(plot_df.holdout_cancer_type.unique(), file=sys.stderr) if output_plots: output_plots_dir.mkdir(exist_ok=True) plt.savefig(output_plots_dir / '{}_response_classify_summary.png'.format(drug), dpi=200, bbox_inches='tight') # In[12]: sns.set({'figure.figsize': (16, 12)}) sns.set_context('notebook') fig, axarr = plt.subplots(3, 1) dfs_to_plot = [ single_cancer_compare_df, pancancer_compare_df, pancancer_only_compare_df ] names_to_plot = [ 'Train single-cancer', 'Train pan-cancer', 'Train all other cancer types' ] # max_n_dims = max(n_dims) max_n_dims = 1000 # split individual cancer types for ix, compare_df in enumerate(dfs_to_plot): ax = axarr[ix] plot_df = (compare_df[(compare_df.identifier == drug) & (compare_df.n_dims == max_n_dims)] .sort_values(by='holdout_cancer_type') ) sns.boxplot(data=plot_df, x='holdout_cancer_type', y=delta_metric, hue='fs_method', hue_order=fs_method_order, ax=ax) ax.set_title(names_to_plot[ix]) if ix == len(dfs_to_plot) - 1: ax.set_xlabel('Holdout cancer type') else: ax.set_xlabel('') ax.get_legend().remove() ax.set_ylim(-0.2, 1) plt.suptitle('{}, {} features, by test cancer type'.format(drug, max_n_dims), y=0.99) plt.tight_layout() if output_plots: plt.savefig(output_plots_dir / '{}_response_classify_by_cancer_type.png'.format(drug), dpi=200, bbox_inches='tight')
2a90475a226a8743f66d4c4e113d97af8b7e8754
2f737cb4ac4e00d7f850624d5a9fc94e7425155b
/interview/views.py
b577b8b321bbb2cc19bd49026e5b968117448b1b
[]
no_license
eppel81/testchallenge
bd3a789a37280d8471a04c19eb1b4bdcf319fea7
3dce0ac40e1acbe691659786e765e34eb15a0ede
refs/heads/master
2016-08-11T07:46:18.963408
2015-11-03T14:22:54
2015-11-03T14:22:54
43,557,586
0
0
null
null
null
null
UTF-8
Python
false
false
12,076
py
# -*- coding: utf-8 -*- from django.shortcuts import render, get_object_or_404, Http404, redirect from django.contrib import auth from django.core.context_processors import csrf from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse from django.contrib.auth.decorators import permission_required from django.forms.models import modelformset_factory, inlineformset_factory import random import forms import pdb from .models import Interview, InterElem, DoneInterview def message(request, mess_text): """ Для отображения сообщений """ return render(request, 'interview/message.html', {'title': mess_text}) def list_interviews(request): """ Выводит список всех существующих опросов """ c_dict = {} c_dict['title'] = 'Список всех опросов:' c_dict['user'] = auth.get_user(request) c_dict['interviews'] = Interview.objects.all().order_by('id') return render(request, 'interview/listinterviews.html', c_dict) # def edit_interview2(request, interview_id): # """ # Тут будет страница для редактирования конкретного опроса - сейчас не используется # """ # c_dict = {} # interview = get_object_or_404(Interview, pk=interview_id) # c_dict['interview'] = interview # return render(request, "interview/edit_interview.html", c_dict) def edit_interview(request, interview_id): """ Тут попробуем через наборы модельных форм modelformset_factory """ interview = get_object_or_404(Interview, pk=interview_id) ElemFormset = modelformset_factory(InterElem, exclude=('interview',), extra=1, can_delete=True) c_dict = {} c_dict.update(csrf(request)) c_dict['title'] = '"' + str(interview) + '"' if request.method == 'POST': inter_form = forms.FormEditInterview(request.POST, instance=interview) elem_formset = ElemFormset(request.POST, queryset=InterElem.objects.filter(interview=interview).order_by('position'), prefix='elems') if elem_formset.is_valid(): if inter_form.is_valid(): inter_form.save() # тут нужно еще досохранить объект интервью в каждой форме forms_list = elem_formset.save(commit=False) # удалим формы, помеченные для удаления (checkbox) for item in elem_formset.deleted_objects: item.delete() # досохраняем объект interview для правильной внешней ссылки for item in forms_list: item.interview = interview item.save() return HttpResponseRedirect(reverse('edit_interview', args=(interview_id,))) if inter_form.is_valid(): inter_form = forms.FormEditInterview(instance=interview) else: inter_form = forms.FormEditInterview(instance=interview) elem_formset = ElemFormset(queryset=InterElem.objects.filter(interview=interview).order_by('position'), prefix='elems') c_dict['inter_form'] = inter_form c_dict['elem_formset'] = elem_formset return render(request, "interview/edit_interview.html", c_dict) def pass_interview(request, interview_id): """ Функция-представление для голосования по конкретному опросу interview_id """ interview = Interview.objects.get(pk=interview_id) # выбираем элементы конкретного опроса elems = interview.interelem_set.order_by('position') if not elems: return render(request, 'interview/message.html', {'title': 'Вопросы пока не готовы. Спасибо за понимание)'}) # тут надо проверить access в interview (нужно авторизироваться или куки) user = auth.get_user(request) if int(interview.access) > 0 and user.is_anonymous(): return render(request, 'interview/message.html', {'title': 'Только для зарегистрированных пользователей'}) if user.is_anonymous(): # создадим id для уникальных юзеров user.id = random.randrange(100000001, 101000000) # проверяем не голосовал ли он ранее по куке if ('inter_%s' % interview_id) in request.COOKIES: return render(request, 'interview/message.html', {'title': 'Извините, но вы уже прошли этот опрос'}) else: # проверим есть ли у юзера ответ на верхний вопрос текущего опроса if DoneInterview.objects.filter(user_id=user.id, interelem=elems[0]).exists(): return render(request, 'interview/message.html', {'title': 'Извините, но вы уже прошли этот опрос'}) # готовим context для шаблона c_dict = {} c_dict['interview_id'] = interview_id c_dict['title'] = '"' + str(interview) + '"' c_dict.update(csrf(request)) if request.method != 'POST': form = forms.FormInterview(elems) c_dict['form'] = form else: form = forms.FormInterview(elems, request.POST) c_dict['form'] = form if form.is_valid(): cd = form.cleaned_data # тут сохраняем введенные юзером данные по перечню элементов опроса # можно потом вынести в FormInterview.save() for key in cd: interelem = get_object_or_404(InterElem, pk=int(key)) resp = cd[key] # если данные ответа - мультиселект if isinstance(resp, list): # pdb.set_trace() resp = ', '.join(resp) # если checkbox elif isinstance(resp, bool): resp = 'да' if resp else 'нет' user_meta = request.META['HTTP_USER_AGENT'] try: interelem.doneinterview_set.create(user_id=user.id, resp=resp, user_meta=user_meta) except: raise Http404('Не удалось сохранить ваши данные. Попробуйте еще разок.') response = render(request, 'interview/message.html', {'title': 'Спасибо, вы успешно прошли опрос'}) # если аноним, то ставим ему куку if user.is_anonymous(): response.set_cookie('inter_%s' % interview_id, 'done') return response # return HttpResponseRedirect(reverse('pass_interview', args=(interview_id, ))) return render(request, 'interview/passinterview.html', c_dict) # закрываем доступ для обычных (не staff) юзеров с переходом на список опросов #@permission_required('interview.add_interview', login_url='/interview/') def interview_results(request, interview_id): """ Вывод результатов конкретного опроса """ c_dict = {} interview = get_object_or_404(Interview, pk=interview_id) c_dict['descr'] = interview.description # оборачиваем list, чтобы выполнить запрос именно в этом месте elems = list(interview.interelem_set.order_by('position')) if elems: # выберем всех юзеров, которые голосовали по конкретному опросу # done_interview_users = DoneInterview.objects.filter(interelem__in=list(elems)).distinct('user_id') # distinct - почему-то не заработал done_interview_users = DoneInterview.objects.filter(interelem__in=elems) # здесь будем сохранять уникальных голосовавших пользователей users = [] for done_interview_user in done_interview_users: if done_interview_user.user_id not in users: users.append(done_interview_user.user_id) resps = [] questions = [] # формируем список вопросов-элементов интервью for elem in elems: questions.append(elem.text_before_elem) # проходим по перечню объектов результатов голосования с уникальными юзерами. # Это для того, чтобы отобразить в шаблоне таблицу, растущую вниз. for user in users: user_resps = [] for elem in elems: # нужно перехватить исключение, т.к. вопрос-элемент мог добавиться к опросу после # голосования каким-либо юзером и тогда просто не будет нужного объекта-результат голосования. try: elem_response = DoneInterview.objects.get(user_id=user, interelem=elem) tmp = elem_response.resp except Exception: tmp = '' user_resps.append(tmp) # добавляем в список кортеж ('юзер', [ответы...]) resps.append((user, user_resps)) # если есть ответы на вопросы интервью if resps: c_dict['title'] = 'Результаты голосования по опросу:' c_dict['questions'] = questions c_dict['resps'] = resps return render(request, 'interview/interviewresults_new.html', c_dict) # def interview_results_new(requerst, interview_id): # """ # Обновленная функция interview_result (см. выше). Тут немного подругому обращаемся к базе данных. # """ # c_dict = {} # interview = get_object_or_404(Interview, pk=interview_id) # elems = list(interview.interelem_set.order_by('position')) # # # тут список объектов-ответов всех юзеров по данному интервью # all_resps = list(DoneInterview.objects.filter(interelem__in=elems)) # # # выберем список юзеров # users_list = [] # for item in all_resps: # if item.user_id not in users_list: # users_list.append(item.user_id) # # # для каждого юзера вытащим нужный ответ # for item in all_resps: # pass # # return render(requerst, 'interview/interviewresults_new.html', c_dict) def add_interview(request): """ Тут добавляем новый опрос в базу """ c_dict = {} c_dict.update(csrf(request)) c_dict['title'] = 'Добавляем опрос' if request.POST: inter_form = forms.FormEditInterview(request.POST) if inter_form.is_valid(): interview_id = inter_form.save() # return redirect('interview/%s/edit' % interview_id) return HttpResponseRedirect(reverse('edit_interview', args=(interview_id.id, ))) else: inter_form = forms.FormEditInterview() c_dict['inter_form'] = inter_form return render(request, 'interview/edit_interview.html', c_dict)
7a024d0157cfc178d4f1771c56c94ee8a96ad515
fd41984178ffba0846fa7ab1f67c1a0843a5e3ff
/自动化办公与鼠标键盘模拟/2.读取PDF文件/读取PDF文件.py
f2f9dc6056b35277a8a88b16d765a546092ed2d4
[]
no_license
LasterSmithKim/Python-Base
23f17472ee80f7224e96a4185775c9cd05ac7a98
27756126d999ddabf53b6bdc7114903a297464a0
refs/heads/master
2020-03-28T08:00:11.156911
2018-11-28T09:54:51
2018-11-28T09:54:51
147,939,778
0
0
null
null
null
null
UTF-8
Python
false
false
2,066
py
import sys import importlib importlib.reload(sys) from pdfminer.pdfparser import PDFParser,PDFDocument from pdfminer.pdfinterp import PDFResourceManager,PDFPageInterpreter from pdfminer.converter import PDFPageAggregator from pdfminer.layout import LTTextBoxHorizontal,LAParams from pdfminer.pdfinterp import PDFTextExtractionNotAllowed def readPDF(path,toPath): #以二进制形式打开PDF文件 f = open(path,"rb") #创建管理器-pdf文档分析器 parser = PDFParser(f) #创建一个pdf文档 pdfFile = PDFDocument() #链接分析器与文档对象(分析器和文件双向链接) parser.set_document(pdfFile) pdfFile.set_parser(parser) #提供初始化密码 pdfFile.initialize() #检测文档是否提供txt转换 if not pdfFile.is_extractable: raise PDFTextExtractionNotAllowed else: #解析数据 #数据管理器 manager = PDFResourceManager() #创建一个PDF设备的对象 laparams = LAParams() device = PDFPageAggregator(manager,laparams=laparams) #创建解释器对象 interpreter = PDFPageInterpreter(manager,device) #开始循环处理,每次处理一页 for page in pdfFile.get_pages(): interpreter.process_page(page) #创建涂层,循环处理涂层 layout = device.get_result() for x in layout: #判断 x 是否是 LTTextBoxHorizontal类型的数据 if(isinstance(x,LTTextBoxHorizontal)): with open(toPath,"a") as f: str = x.get_text() #print(str) f.write(str+"\n") path = r"/Users/jinpeihua/PycharmProjects/Python语言基础视频课程/入门教程一/自动化办公与鼠标键盘模拟/2.读取PDF文件/LegalNotices.pdf" toPath = r"/Users/jinpeihua/PycharmProjects/Python语言基础视频课程/入门教程一/自动化办公与鼠标键盘模拟/2.读取PDF文件/a.txt" readPDF(path,toPath)
7b684337197c473ca2fbb5bd628978519553e9fb
2f07911e75ded21b80cae89ded82ce38f03a7931
/example.py
95c0f6863c126d023a70847fc9d9b552a45d593c
[]
no_license
benmaier/radial-distance-layout
2b1571c34dd167301bfb8ea9750a177ac420cda9
9be12e2906138e239e72eeb6082ebcd3d569b3dc
refs/heads/master
2022-02-23T08:09:58.174365
2022-02-12T21:44:41
2022-02-12T21:44:41
50,359,905
3
2
null
null
null
null
UTF-8
Python
false
false
806
py
from radial_distance_layout import radial_distance_layout import matplotlib.pyplot as pl import networkx as nx paths = [ [ 'a','b','c'] ] paths += [ [ 'a','b','d'] ] paths += [ [ 'a','e','f','g'] ] paths += [ [ 'a','e','f','h'] ] paths += [ [ 'a','e','i'] ] paths += [ [ 'a','j','k'] ] paths += [ [ 'a','j','l'] ] dists = {'a': 0, 'b':1.1, 'e': 1.2, 'j': 1.4, 'c':2.1, 'd': 2.2, 'f': 2.1, 'i': 2.34, 'k':3.8, 'l':2.5, 'g': 3.9, 'h': 3.8} T = nx.DiGraph() for p in paths: T.add_path(p) keystr = 'dist' nx.set_node_attributes(T,keystr,dists) fig,ax = pl.subplots(1,2,figsize=(15,8)) pos = radial_distance_layout(T,keystr,mode='soph') nx.draw_networkx(T,pos,ax=ax[0]) pos = radial_distance_layout(T,keystr,mode='normal') nx.draw_networkx(T,pos,ax=ax[1]) pl.show()
396fc78c6deed3bed86bd2e205d2cd7e3306ecc9
3c000380cbb7e8deb6abf9c6f3e29e8e89784830
/venv/Lib/site-packages/cobra/modelimpl/infra/rsvpcbndlgrp.py
1881c27187fd0259b96e7e54cb6987147cafcdb7
[]
no_license
bkhoward/aciDOM
91b0406f00da7aac413a81c8db2129b4bfc5497b
f2674456ecb19cf7299ef0c5a0887560b8b315d0
refs/heads/master
2023-03-27T23:37:02.836904
2021-03-26T22:07:54
2021-03-26T22:07:54
351,855,399
0
0
null
null
null
null
UTF-8
Python
false
false
9,141
py
# coding=UTF-8 # ********************************************************************** # Copyright (c) 2013-2020 Cisco Systems, Inc. All rights reserved # written by zen warriors, do not modify! # ********************************************************************** from cobra.mit.meta import ClassMeta from cobra.mit.meta import StatsClassMeta from cobra.mit.meta import CounterMeta from cobra.mit.meta import PropMeta from cobra.mit.meta import Category from cobra.mit.meta import SourceRelationMeta from cobra.mit.meta import NamedSourceRelationMeta from cobra.mit.meta import TargetRelationMeta from cobra.mit.meta import DeploymentPathMeta, DeploymentCategory from cobra.model.category import MoCategory, PropCategory, CounterCategory from cobra.mit.mo import Mo # ################################################## class RsVpcBndlGrp(Mo): """ A source relation to the bundle interface group. """ meta = SourceRelationMeta("cobra.model.infra.RsVpcBndlGrp", "cobra.model.infra.AccBndlGrp") meta.cardinality = SourceRelationMeta.N_TO_M meta.moClassName = "infraRsVpcBndlGrp" meta.rnFormat = "rsvpcBndlGrp-[%(tDn)s]" meta.category = MoCategory.RELATIONSHIP_TO_LOCAL meta.label = "PC/VPC Interface Policy Group" meta.writeAccessMask = 0x100000000001 meta.readAccessMask = 0x100000000001 meta.isDomainable = False meta.isReadOnly = True meta.isConfigurable = False meta.isDeletable = False meta.isContextRoot = False meta.childClasses.add("cobra.model.fabric.CreatedBy") meta.childClasses.add("cobra.model.health.Inst") meta.childClasses.add("cobra.model.fault.Counts") meta.childNamesAndRnPrefix.append(("cobra.model.fabric.CreatedBy", "source-")) meta.childNamesAndRnPrefix.append(("cobra.model.fault.Counts", "fltCnts")) meta.childNamesAndRnPrefix.append(("cobra.model.health.Inst", "health")) meta.parentClasses.add("cobra.model.infra.NodeCfg") meta.superClasses.add("cobra.model.reln.Inst") meta.superClasses.add("cobra.model.fabric.NodeToPolicy") meta.superClasses.add("cobra.model.reln.To") meta.rnPrefixes = [ ('rsvpcBndlGrp-', True), ] prop = PropMeta("str", "childAction", "childAction", 4, PropCategory.CHILD_ACTION) prop.label = "None" prop.isImplicit = True prop.isAdmin = True prop._addConstant("deleteAll", "deleteall", 16384) prop._addConstant("deleteNonPresent", "deletenonpresent", 8192) prop._addConstant("ignore", "ignore", 4096) meta.props.add("childAction", prop) prop = PropMeta("str", "deplSt", "deplSt", 15582, PropCategory.REGULAR) prop.label = "None" prop.isImplicit = True prop.isAdmin = True prop.defaultValue = 0 prop.defaultValueStr = "none" prop._addConstant("delivered", "delivered", 1) prop._addConstant("node-not-ready", "node-not-ready", 1073741824) prop._addConstant("none", "none", 0) prop._addConstant("not-registered-for-atg", "node-cannot-deploy-epg", 64) prop._addConstant("not-registered-for-fabric-ctrls", "node-not-controller", 16) prop._addConstant("not-registered-for-fabric-leafs", "node-not-leaf-for-fabric-policies", 4) prop._addConstant("not-registered-for-fabric-node-group", "node-not-registered-for-node-group-policies", 32) prop._addConstant("not-registered-for-fabric-oleafs", "node-not-capable-of-deploying-fabric-node-leaf-override", 2048) prop._addConstant("not-registered-for-fabric-ospines", "node-not-capable-of-deploying-fabric-node-spine-override", 4096) prop._addConstant("not-registered-for-fabric-pods", "node-has-not-joined-pod", 8) prop._addConstant("not-registered-for-fabric-spines", "node-not-spine", 2) prop._addConstant("not-registered-for-infra-leafs", "node-not-leaf-for-infra-policies", 128) prop._addConstant("not-registered-for-infra-oleafs", "node-not-capable-of-deploying-infra-node-leaf-override", 512) prop._addConstant("not-registered-for-infra-ospines", "node-not-capable-of-deploying-infra-node-spine-override", 1024) prop._addConstant("not-registered-for-infra-spines", "node-not-spine-for-infra-policies", 256) prop._addConstant("pod-misconfig", "node-belongs-to-different-pod", 8192) prop._addConstant("policy-deployment-failed", "policy-deployment-failed", 2147483648) meta.props.add("deplSt", prop) prop = PropMeta("str", "dn", "dn", 1, PropCategory.DN) prop.label = "None" prop.isDn = True prop.isImplicit = True prop.isAdmin = True prop.isCreateOnly = True meta.props.add("dn", prop) prop = PropMeta("str", "forceResolve", "forceResolve", 107, PropCategory.REGULAR) prop.label = "None" prop.isImplicit = True prop.isAdmin = True prop.defaultValue = True prop.defaultValueStr = "yes" prop._addConstant("no", None, False) prop._addConstant("yes", None, True) meta.props.add("forceResolve", prop) prop = PropMeta("str", "lcOwn", "lcOwn", 9, PropCategory.REGULAR) prop.label = "None" prop.isImplicit = True prop.isAdmin = True prop.defaultValue = 0 prop.defaultValueStr = "local" prop._addConstant("implicit", "implicit", 4) prop._addConstant("local", "local", 0) prop._addConstant("policy", "policy", 1) prop._addConstant("replica", "replica", 2) prop._addConstant("resolveOnBehalf", "resolvedonbehalf", 3) meta.props.add("lcOwn", prop) prop = PropMeta("str", "modTs", "modTs", 7, PropCategory.REGULAR) prop.label = "None" prop.isImplicit = True prop.isAdmin = True prop.defaultValue = 0 prop.defaultValueStr = "never" prop._addConstant("never", "never", 0) meta.props.add("modTs", prop) prop = PropMeta("str", "monPolDn", "monPolDn", 15611, PropCategory.REGULAR) prop.label = "Monitoring policy attached to this observable object" prop.isImplicit = True prop.isAdmin = True meta.props.add("monPolDn", prop) prop = PropMeta("str", "rType", "rType", 106, PropCategory.REGULAR) prop.label = "None" prop.isImplicit = True prop.isAdmin = True prop.defaultValue = 1 prop.defaultValueStr = "mo" prop._addConstant("local", "local", 3) prop._addConstant("mo", "mo", 1) prop._addConstant("service", "service", 2) meta.props.add("rType", prop) prop = PropMeta("str", "rn", "rn", 2, PropCategory.RN) prop.label = "None" prop.isRn = True prop.isImplicit = True prop.isAdmin = True prop.isCreateOnly = True meta.props.add("rn", prop) prop = PropMeta("str", "state", "state", 103, PropCategory.REGULAR) prop.label = "State" prop.isImplicit = True prop.isAdmin = True prop.defaultValue = 0 prop.defaultValueStr = "unformed" prop._addConstant("cardinality-violation", "cardinality-violation", 5) prop._addConstant("formed", "formed", 1) prop._addConstant("invalid-target", "invalid-target", 4) prop._addConstant("missing-target", "missing-target", 2) prop._addConstant("unformed", "unformed", 0) meta.props.add("state", prop) prop = PropMeta("str", "stateQual", "stateQual", 104, PropCategory.REGULAR) prop.label = "State Qualifier" prop.isImplicit = True prop.isAdmin = True prop.defaultValue = 0 prop.defaultValueStr = "none" prop._addConstant("default-target", "default-target", 2) prop._addConstant("mismatch-target", "mismatch-target", 1) prop._addConstant("none", "none", 0) meta.props.add("stateQual", prop) prop = PropMeta("str", "status", "status", 3, PropCategory.STATUS) prop.label = "None" prop.isImplicit = True prop.isAdmin = True prop._addConstant("created", "created", 2) prop._addConstant("deleted", "deleted", 8) prop._addConstant("modified", "modified", 4) meta.props.add("status", prop) prop = PropMeta("str", "tCl", "tCl", 13161, PropCategory.REGULAR) prop.label = "Target-class" prop.isImplicit = True prop.isAdmin = True prop.defaultValue = 4406 prop.defaultValueStr = "infraAccBndlGrp" prop._addConstant("infraAccBndlGrp", None, 4406) prop._addConstant("unspecified", "unspecified", 0) meta.props.add("tCl", prop) prop = PropMeta("str", "tDn", "tDn", 13160, PropCategory.REGULAR) prop.label = "Target-dn" prop.isConfig = True prop.isAdmin = True prop.isCreateOnly = True prop.isNaming = True meta.props.add("tDn", prop) prop = PropMeta("str", "tType", "tType", 105, PropCategory.REGULAR) prop.label = "None" prop.isImplicit = True prop.isAdmin = True prop.defaultValue = 1 prop.defaultValueStr = "mo" prop._addConstant("all", "all", 2) prop._addConstant("mo", "mo", 1) prop._addConstant("name", "name", 0) meta.props.add("tType", prop) meta.namingProps.append(getattr(meta.props, "tDn")) getattr(meta.props, "tDn").needDelimiter = True def __init__(self, parentMoOrDn, tDn, markDirty=True, **creationProps): namingVals = [tDn] Mo.__init__(self, parentMoOrDn, markDirty, *namingVals, **creationProps) # End of package file # ##################################################
3d4f973e6319ac02322d9c9e19a44bb5e11c4a74
360c777a2b77be466b1cf7c8fd74d6fd04f56b55
/nexus_auth/models/ping.py
7afa266c0b95f5154844d34bf4d67367e1726a27
[ "MIT" ]
permissive
hreeder/nexus-auth
790a3b2623ddf443138a4b0f0af1380dbc4db8ae
8d51aef01647e32ba4a284f02de73a2caad7cf49
refs/heads/master
2021-01-10T10:08:37.190558
2016-02-29T12:27:21
2016-02-29T12:27:21
52,789,087
0
0
null
null
null
null
UTF-8
Python
false
false
1,237
py
from nexus_auth import db from nexus_auth.models.groups import Group TYPE_SERVER = 0 TYPE_GROUP = 1 class PingServer(db.Model): id = db.Column(db.Integer, primary_key=True) servers = db.Column(db.Text) display_name = db.Column(db.String(64)) class PingTarget(db.Model): id = db.Column(db.Integer, primary_key=True) parent_group_id = db.Column(db.Integer, db.ForeignKey('group.id')) type = db.Column(db.SmallInteger) target = db.Column(db.Integer) def get_target_representation(self): if self.type == TYPE_SERVER: server = PingServer.query.filter_by(id=self.target).first() return "Server: " + server.display_name elif self.type == TYPE_GROUP: group = Group.query.filter_by(id=self.target).first() return "Group: " + group.name def get_target_name(self): if self.type == TYPE_SERVER: server = PingServer.query.filter_by(id=self.target).first() return server.display_name elif self.type == TYPE_GROUP: group = Group.query.filter_by(id=self.target).first() return group.name def get_group(self): return Group.query.filter_by(id=self.parent_group_id).first()
42e0edb633c9498ca865bd735ff7de4fec5a8333
e0045eec29aab56212c00f9293a21eb3b4b9fe53
/hr_payroll_account/models/hr_payroll_account.py
8b32bbc1e6f2d79fb1556864a63d4f9623022933
[]
no_license
tamam001/ALWAFI_P1
a3a9268081b9befc668a5f51c29ce5119434cc21
402ea8687c607fbcb5ba762c2020ebc4ee98e705
refs/heads/master
2020-05-18T08:16:50.583264
2019-04-30T14:43:46
2019-04-30T14:43:46
184,268,686
0
0
null
null
null
null
UTF-8
Python
false
false
7,589
py
#-*- coding:utf-8 -*- # Part of ALWAFI. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models, _ from odoo.exceptions import UserError from odoo.tools import float_compare, float_is_zero class HrPayslipLine(models.Model): _inherit = 'hr.payslip.line' def _get_partner_id(self, credit_account): """ Get partner_id of slip line to use in account_move_line """ # use partner of salary rule or fallback on employee's address register_partner_id = self.salary_rule_id.register_id.partner_id partner_id = register_partner_id.id or self.slip_id.employee_id.address_home_id.id if credit_account: if register_partner_id or self.salary_rule_id.account_credit.internal_type in ('receivable', 'payable'): return partner_id else: if register_partner_id or self.salary_rule_id.account_debit.internal_type in ('receivable', 'payable'): return partner_id return False class HrPayslip(models.Model): _inherit = 'hr.payslip' date = fields.Date('Date Account', states={'draft': [('readonly', False)]}, readonly=True, help="Keep empty to use the period of the validation(Payslip) date.") journal_id = fields.Many2one('account.journal', 'Salary Journal', readonly=True, required=True, states={'draft': [('readonly', False)]}, default=lambda self: self.env['account.journal'].search([('type', '=', 'general')], limit=1)) move_id = fields.Many2one('account.move', 'Accounting Entry', readonly=True, copy=False) @api.model def create(self, vals): if 'journal_id' in self.env.context: vals['journal_id'] = self.env.context.get('journal_id') return super(HrPayslip, self).create(vals) @api.onchange('contract_id') def onchange_contract(self): super(HrPayslip, self).onchange_contract() self.journal_id = self.contract_id.journal_id.id or (not self.contract_id and self.default_get(['journal_id'])['journal_id']) @api.multi def action_payslip_cancel(self): moves = self.mapped('move_id') moves.filtered(lambda x: x.state == 'posted').button_cancel() moves.unlink() return super(HrPayslip, self).action_payslip_cancel() @api.multi def action_payslip_done(self): res = super(HrPayslip, self).action_payslip_done() for slip in self: line_ids = [] debit_sum = 0.0 credit_sum = 0.0 date = slip.date or slip.date_to currency = slip.company_id.currency_id name = _('Payslip of %s') % (slip.employee_id.name) move_dict = { 'narration': name, 'ref': slip.number, 'journal_id': slip.journal_id.id, 'date': date, } for line in slip.details_by_salary_rule_category: amount = currency.round(slip.credit_note and -line.total or line.total) if currency.is_zero(amount): continue debit_account_id = line.salary_rule_id.account_debit.id credit_account_id = line.salary_rule_id.account_credit.id if debit_account_id: debit_line = (0, 0, { 'name': line.name, 'partner_id': line._get_partner_id(credit_account=False), 'account_id': debit_account_id, 'journal_id': slip.journal_id.id, 'date': date, 'debit': amount > 0.0 and amount or 0.0, 'credit': amount < 0.0 and -amount or 0.0, 'analytic_account_id': line.salary_rule_id.analytic_account_id.id, 'tax_line_id': line.salary_rule_id.account_tax_id.id, }) line_ids.append(debit_line) debit_sum += debit_line[2]['debit'] - debit_line[2]['credit'] if credit_account_id: credit_line = (0, 0, { 'name': line.name, 'partner_id': line._get_partner_id(credit_account=True), 'account_id': credit_account_id, 'journal_id': slip.journal_id.id, 'date': date, 'debit': amount < 0.0 and -amount or 0.0, 'credit': amount > 0.0 and amount or 0.0, 'analytic_account_id': line.salary_rule_id.analytic_account_id.id, 'tax_line_id': line.salary_rule_id.account_tax_id.id, }) line_ids.append(credit_line) credit_sum += credit_line[2]['credit'] - credit_line[2]['debit'] if currency.compare_amounts(credit_sum, debit_sum) == -1: acc_id = slip.journal_id.default_credit_account_id.id if not acc_id: raise UserError(_('The Expense Journal "%s" has not properly configured the Credit Account!') % (slip.journal_id.name)) adjust_credit = (0, 0, { 'name': _('Adjustment Entry'), 'partner_id': False, 'account_id': acc_id, 'journal_id': slip.journal_id.id, 'date': date, 'debit': 0.0, 'credit': currency.round(debit_sum - credit_sum), }) line_ids.append(adjust_credit) elif currency.compare_amounts(debit_sum, credit_sum) == -1: acc_id = slip.journal_id.default_debit_account_id.id if not acc_id: raise UserError(_('The Expense Journal "%s" has not properly configured the Debit Account!') % (slip.journal_id.name)) adjust_debit = (0, 0, { 'name': _('Adjustment Entry'), 'partner_id': False, 'account_id': acc_id, 'journal_id': slip.journal_id.id, 'date': date, 'debit': currency.round(credit_sum - debit_sum), 'credit': 0.0, }) line_ids.append(adjust_debit) move_dict['line_ids'] = line_ids move = self.env['account.move'].create(move_dict) slip.write({'move_id': move.id, 'date': date}) move.post() return res class HrSalaryRule(models.Model): _inherit = 'hr.salary.rule' analytic_account_id = fields.Many2one('account.analytic.account', 'Analytic Account') account_tax_id = fields.Many2one('account.tax', 'Tax') account_debit = fields.Many2one('account.account', 'Debit Account', domain=[('deprecated', '=', False)]) account_credit = fields.Many2one('account.account', 'Credit Account', domain=[('deprecated', '=', False)]) class HrContract(models.Model): _inherit = 'hr.contract' _description = 'Employee Contract' analytic_account_id = fields.Many2one('account.analytic.account', 'Analytic Account') journal_id = fields.Many2one('account.journal', 'Salary Journal') class HrPayslipRun(models.Model): _inherit = 'hr.payslip.run' journal_id = fields.Many2one('account.journal', 'Salary Journal', states={'draft': [('readonly', False)]}, readonly=True, required=True, default=lambda self: self.env['account.journal'].search([('type', '=', 'general')], limit=1))
8692c4889582e9c8f425306d8b5ac70d4ee7090e
e8cb5f716b064043708293f924ed1ba84005e417
/examples/Redfish/ex09_find_ilo_mac_address.py
d05e42bb446a1e7359fb7eeacd4a665968932786
[ "Apache-2.0" ]
permissive
injan0913/python-ilorest-library
9207caeab89038f7e6ae803c55de183bda02edb3
8507d96cf7b9604a30ae6548cafc0003d1098b72
refs/heads/master
2020-12-24T22:20:13.135325
2016-06-23T18:26:33
2016-06-23T18:26:33
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,598
py
# Copyright 2016 Hewlett Packard Enterprise Development LP # # 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 sys from redfishobject import RedfishObject from ilorest.rest.v1_helper import ServerDownOrUnreachableError def ex9_find_ilo_mac_address(redfishobj): sys.stdout.write("\nEXAMPLE 9: Find iLO's MAC Addresses\n") instances = redfishobj.search_for_type("Manager.") for instance in instances: tmp = redfishobj.redfish_get(instance["@odata.id"]) response = redfishobj.redfish_get(tmp.dict["EthernetInterfaces"]\ ["@odata.id"]) for entry in response.dict["Members"]: ethernet = redfishobj.redfish_get(entry["@odata.id"]) if "MACAddress" not in ethernet.dict: sys.stderr.write("\tNIC resource does not contain " \ "'MACAddress' property\n") else: sys.stdout.write("\t" + ethernet.dict["Name"] + " = " + \ ethernet.dict["MACAddress"] + "\t(" + \ ethernet.dict["Status"]["State"] + ")\n") if __name__ == "__main__": # When running on the server locally use the following commented values # iLO_host = "blobstore://." # iLO_account = "None" # iLO_password = "None" # When running remotely connect using the iLO address, iLO account name, # and password to send https requests iLO_host = "https://10.0.0.100" iLO_account = "admin" iLO_password = "password" # Create a REDFISH object try: REDFISH_OBJ = RedfishObject(iLO_host, iLO_account, iLO_password) except ServerDownOrUnreachableError, excp: sys.stderr.write("ERROR: server not reachable or doesn't support " \ "RedFish.\n") sys.exit() except Exception, excp: raise excp ex9_find_ilo_mac_address(REDFISH_OBJ)
08dde7520a5cc6318c6ea6a3daea7417cf1e7d49
8050168c08d5bb26f0da6784ca3d536950d43810
/activity/migrations/0009_auto_20190305_1508.py
b246aa4d037ae5a5422101d5dacb29818286457f
[]
no_license
qoutland/docent
043f945d8a3016fdc54ee113a108a608e58456dc
f4dffaa3b72d922dfb99e40e7f73155ad25a2509
refs/heads/master
2022-12-15T00:13:24.940849
2019-05-02T17:55:43
2019-05-02T17:55:43
164,701,946
1
0
null
2022-11-22T03:31:43
2019-01-08T17:41:28
Python
UTF-8
Python
false
false
386
py
# Generated by Django 2.1.3 on 2019-03-05 23:08 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('activity', '0008_auto_20190305_1507'), ] operations = [ migrations.AlterField( model_name='activity', name='pic_url', field=models.URLField(blank=True), ), ]
[ "=" ]
=
5a2ebd58eb237a8079aa77a1e5023bf20e50f182
4659f206098fdcaa72b059f1c5e4afe4c5fad3d5
/planemo-de/xenv/lib/python3.7/site-packages/galaxy/__init__.py
7653e9a409809c7918eef0427eacfbc2d38e427d
[]
no_license
Slugger70/galaxy-metabolomics
e1ef083316394ace66c1f69c313db0a0fc8c3dec
0cbee8fe9e7cf1cc37832751ffdd9f88ff363136
refs/heads/master
2020-09-19T21:51:16.177730
2019-11-26T23:54:43
2019-11-26T23:54:43
224,306,539
0
0
null
2019-11-26T23:45:53
2019-11-26T23:45:52
null
UTF-8
Python
false
false
370
py
# -*- coding: utf-8 -*- __version__ = '19.5.2' PROJECT_NAME = "galaxy-lib" PROJECT_OWNER = PROJECT_USERAME = "galaxyproject" PROJECT_URL = "https://github.com/galaxyproject/galaxy-lib" PROJECT_AUTHOR = 'Galaxy Project and Community' PROJECT_EMAIL = '[email protected]' RAW_CONTENT_URL = "https://raw.github.com/%s/%s/master/" % ( PROJECT_USERAME, PROJECT_NAME )
fff3e450967edd4d5d28de96357ed12b9db6ef16
c50e7eb190802d7849c0d0cea02fb4d2f0021777
/src/containerapp/azext_containerapp/tests/latest/test_containerapp_preview_scenario.py
c5bec1652214c86c622338ef87c1eb662d0ab5a8
[ "LicenseRef-scancode-generic-cla", "MIT" ]
permissive
Azure/azure-cli-extensions
c1615b19930bba7166c282918f166cd40ff6609c
b8c2cf97e991adf0c0a207d810316b8f4686dc29
refs/heads/main
2023-08-24T12:40:15.528432
2023-08-24T09:17:25
2023-08-24T09:17:25
106,580,024
336
1,226
MIT
2023-09-14T10:48:57
2017-10-11T16:27:31
Python
UTF-8
Python
false
false
9,214
py
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- import os import time from time import sleep from azure.cli.testsdk import (ScenarioTest, ResourceGroupPreparer, JMESPathCheck, live_only) from subprocess import run from .common import (write_test_file, TEST_LOCATION, clean_up_test_file) from .utils import create_containerapp_env TEST_DIR = os.path.abspath(os.path.join(os.path.abspath(__file__), '..')) class ContainerappPreviewScenarioTest(ScenarioTest): def __init__(self, method_name, config_file=None, recording_name=None, recording_processors=None, replay_processors=None, recording_patches=None, replay_patches=None, random_config_dir=False): super().__init__(method_name, config_file, recording_name, recording_processors, replay_processors, recording_patches, replay_patches, random_config_dir) cmd = ['azdev', 'extension', 'add', 'connectedk8s'] run(cmd, check=True) cmd = ['azdev', 'extension', 'add', 'k8s-extension'] run(cmd, check=True) # Wait for extensions to be installed # We mock time.sleep in azure-sdk-tools, that's why we need to use sleep here. sleep(120) @ResourceGroupPreparer(location="eastus", random_name_length=15) def test_containerapp_preview_environment_type(self, resource_group): self.cmd('configure --defaults location={}'.format(TEST_LOCATION)) aks_name = "my-aks-cluster" connected_cluster_name = "my-connected-cluster" custom_location_id = None try: self.cmd(f'aks create --resource-group {resource_group} --name {aks_name} --enable-aad --generate-ssh-keys --enable-cluster-autoscaler --min-count 4 --max-count 10 --node-count 4') self.cmd(f'aks get-credentials --resource-group {resource_group} --name {aks_name} --overwrite-existing --admin') self.cmd(f'connectedk8s connect --resource-group {resource_group} --name {connected_cluster_name}') connected_cluster = self.cmd(f'az connectedk8s show --resource-group {resource_group} --name {connected_cluster_name}').get_output_in_json() connected_cluster_id = connected_cluster.get('id') extension = self.cmd(f'az k8s-extension create' f' --resource-group {resource_group}' f' --name containerapp-ext' f' --cluster-type connectedClusters' f' --cluster-name {connected_cluster_name}' f' --extension-type "Microsoft.App.Environment" ' f' --release-train stable' f' --auto-upgrade-minor-version true' f' --scope cluster' f' --release-namespace appplat-ns' f' --configuration-settings "Microsoft.CustomLocation.ServiceAccount=default"' f' --configuration-settings "appsNamespace=appplat-ns"' f' --configuration-settings "clusterName={connected_cluster_name}"' f' --configuration-settings "envoy.annotations.service.beta.kubernetes.io/azure-load-balancer-resource-group={resource_group}"').get_output_in_json() custom_location_name = "my-custom-location" custom_location_id = self.cmd(f'az customlocation create -g {resource_group} -n {custom_location_name} -l {TEST_LOCATION} --host-resource-id {connected_cluster_id} --namespace appplat-ns -c {extension["id"]}').get_output_in_json()['id'] except Exception as e: pass # create connected environment with client or create a command for connected? sub_id = self.cmd('az account show').get_output_in_json()['id'] connected_env_name = 'my-connected-env' connected_env_resource_id = f"/subscriptions/{sub_id}/resourceGroups/{resource_group}/providers/Microsoft.App/connectedEnvironments/{connected_env_name}" file = f"{resource_group}.json" env_payload = '{{ "location": "{location}", "extendedLocation": {{ "name": "{custom_location_id}", "type": "CustomLocation" }}, "Properties": {{}}}}' \ .format(location=TEST_LOCATION, custom_location_id=custom_location_id) write_test_file(file, env_payload) self.cmd(f'az rest --method put --uri "{connected_env_resource_id}?api-version=2022-06-01-preview" --body "@{file}"') containerapp_env = self.cmd(f'az rest --method get --uri "{connected_env_resource_id}?api-version=2022-06-01-preview"').get_output_in_json() while containerapp_env["properties"]["provisioningState"].lower() != "succeeded": time.sleep(5) containerapp_env = self.cmd( f'az rest --method get --uri "{connected_env_resource_id}?api-version=2022-06-01-preview"').get_output_in_json() ca_name = self.create_random_name(prefix='containerapp', length=24) self.cmd( f'az containerapp create --name {ca_name} --resource-group {resource_group} --environment {connected_env_name} --image "mcr.microsoft.com/k8se/quickstart:latest" --environment-type connected', checks=[ JMESPathCheck('properties.environmentId', connected_env_resource_id), JMESPathCheck('properties.provisioningState', "Succeeded") ]) ca_name2 = self.create_random_name(prefix='containerapp', length=24) self.cmd( f'az containerapp create --name {ca_name2} --resource-group {resource_group} --environment {connected_env_resource_id} --image "mcr.microsoft.com/k8se/quickstart:latest" --environment-type connected', checks=[ JMESPathCheck('properties.environmentId', connected_env_resource_id), JMESPathCheck('properties.provisioningState', "Succeeded") ]) # test show/list/delete self.cmd('containerapp list -g {}'.format(resource_group), checks=[ JMESPathCheck('length(@)', 2) ]) self.cmd('containerapp list -g {} --environment-type {}'.format(resource_group, 'connected'), checks=[ JMESPathCheck('length(@)', 2) ]) self.cmd('containerapp list -g {} --environment-type {} --environment {}'.format(resource_group, 'connected', connected_env_name), checks=[ JMESPathCheck('length(@)', 2) ]) self.cmd('containerapp list -g {} --environment-type {}'.format(resource_group, 'managed'), checks=[ JMESPathCheck('length(@)', 0) ]) app2 = self.cmd('containerapp show -n {} -g {}'.format(ca_name2, resource_group)).get_output_in_json() self.cmd('containerapp delete --ids {} --yes'.format(app2['id'])) self.cmd('containerapp delete -n {} -g {} --yes'.format(ca_name, resource_group)) self.cmd('containerapp list -g {}'.format(resource_group), checks=[ JMESPathCheck('length(@)', 0) ]) clean_up_test_file(file) @ResourceGroupPreparer(location="eastus") def test_containerapp_preview_e2e(self, resource_group): self.cmd('configure --defaults location={}'.format(TEST_LOCATION)) env_name = self.create_random_name(prefix='containerapp-env', length=24) ca_name = self.create_random_name(prefix='containerapp', length=24) create_containerapp_env(self, env_name, resource_group) containerapp_env = self.cmd('containerapp env show -g {} -n {}'.format(resource_group, env_name)).get_output_in_json() self.cmd( f'az containerapp create --name {ca_name} --resource-group {resource_group} --environment {env_name} --image "mcr.microsoft.com/k8se/quickstart:latest" --environment-type managed', checks=[ JMESPathCheck('properties.environmentId', containerapp_env['id']), JMESPathCheck('properties.provisioningState', "Succeeded") ]) app = self.cmd( 'containerapp show -n {} -g {}'.format(ca_name, resource_group), checks=[ JMESPathCheck('properties.environmentId', containerapp_env['id']), JMESPathCheck('properties.provisioningState', "Succeeded"), JMESPathCheck('name', ca_name), ] ).get_output_in_json() self.cmd('containerapp list -g {}'.format(resource_group), checks=[ JMESPathCheck('length(@)', 1) ]) self.cmd('containerapp list -g {} --environment-type {}'.format(resource_group, 'managed'), checks=[ JMESPathCheck('length(@)', 1) ]) self.cmd('containerapp delete --ids {} --yes'.format(app['id'])) self.cmd('containerapp list -g {}'.format(resource_group), checks=[ JMESPathCheck('length(@)', 0) ])
8e3355f79679a4b37fc3d64860a4ce31c5548fa8
de8cfb5a1d39b40543e8e9d3f960f4b675781a08
/dask/dataframe/shuffle.py
4e85c7ce2194acd2302fb1ddeb476a43d0f86fd6
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
JDWarner/dask
8b5c676d9078ecc498deb8fd47a54e1676c00a5f
3dec8e3526520459668ced05f8e144fd7605d5ec
refs/heads/master
2021-01-18T21:02:18.344193
2015-07-15T20:00:51
2015-07-15T20:00:51
null
0
0
null
null
null
null
UTF-8
Python
false
false
7,141
py
from itertools import count from collections import Iterator from math import ceil from toolz import merge, accumulate, merge_sorted import toolz from operator import getitem, setitem import pandas as pd import numpy as np from .. import threaded from ..optimize import cull from .core import DataFrame, Series, get, _Frame, tokens from ..compatibility import unicode from ..utils import ignoring from .utils import (strip_categories, unique, shard_df_on_index, _categorize, get_categories) def set_index(df, index, npartitions=None, compute=True, **kwargs): """ Set DataFrame index to new column Sorts index and realigns Dataframe to new sorted order. This shuffles and repartitions your data. """ npartitions = npartitions or df.npartitions if not isinstance(index, Series): index2 = df[index] else: index2 = index divisions = (index2 .quantiles(np.linspace(0, 100, npartitions+1)) .compute()).tolist() return df.set_partition(index, divisions, compute=compute, **kwargs) def new_categories(categories, index): """ Flop around index for '.index' """ if index in categories: categories = categories.copy() categories['.index'] = categories.pop(index) return categories def set_partition(df, index, divisions, compute=False, **kwargs): """ Group DataFrame by index Sets a new index and partitions data along that index according to divisions. Divisions are often found by computing approximate quantiles. The function ``set_index`` will do both of these steps. Parameters ---------- df: DataFrame/Series Data that we want to re-partition index: string or Series Column to become the new index divisions: list Values to form new divisions between partitions See Also -------- set_index shuffle partd """ if isinstance(index, _Frame): assert df.divisions == index.divisions import partd p = ('zpartd' + next(tokens),) # Get Categories token = next(tokens) catname = 'set-partition--get-categories-old' + token catname_new = 'set-partition--get-categories-new' + token dsk1 = {catname: (get_categories, df._keys()[0]), p: (partd.PandasBlocks, (partd.Buffer, (partd.Dict,), (partd.File,))), catname_new: (new_categories, catname, index.name if isinstance(index, Series) else index)} # Partition data on disk name = 'set-partition--partition' + next(tokens) if isinstance(index, _Frame): dsk2 = dict(((name, i), (_set_partition, part, ind, divisions, p)) for i, (part, ind) in enumerate(zip(df._keys(), index._keys()))) else: dsk2 = dict(((name, i), (_set_partition, part, index, divisions, p)) for i, part in enumerate(df._keys())) # Barrier barrier_token = 'barrier' + next(tokens) dsk3 = {barrier_token: (barrier, list(dsk2))} if compute: dsk = merge(df.dask, dsk1, dsk2, dsk3) if isinstance(index, _Frame): dsk.update(index.dask) p, barrier_token = get(dsk, [p, barrier_token], **kwargs) # Collect groups name = 'set-partition--collect' + next(tokens) dsk4 = dict(((name, i), (_categorize, catname_new, (_set_collect, i, p, barrier_token))) for i in range(len(divisions) - 1)) dsk = merge(df.dask, dsk1, dsk2, dsk3, dsk4) if isinstance(index, _Frame): dsk.update(index.dask) if compute: dsk = cull(dsk, list(dsk4.keys())) return DataFrame(dsk, name, df.columns, divisions) def barrier(args): list(args) return 0 def _set_partition(df, index, divisions, p): """ Shard partition and dump into partd """ df = df.set_index(index) df = strip_categories(df) divisions = list(divisions) shards = shard_df_on_index(df, divisions[1:-1]) p.append(dict(enumerate(shards))) def _set_collect(group, p, barrier_token): """ Get new partition dataframe from partd """ try: return p.get(group) except ValueError: return pd.DataFrame() def shuffle(df, index, npartitions=None): """ Group DataFrame by index Hash grouping of elements. After this operation all elements that have the same index will be in the same partition. Note that this requires full dataset read, serialization and shuffle. This is expensive. If possible you should avoid shuffles. This does not preserve a meaningful index/partitioning scheme. See Also -------- set_index set_partition partd """ if isinstance(index, _Frame): assert df.divisions == index.divisions if npartitions is None: npartitions = df.npartitions import partd p = ('zpartd' + next(tokens),) dsk1 = {p: (partd.PandasBlocks, (partd.Buffer, (partd.Dict,), (partd.File,)))} # Partition data on disk name = 'shuffle-partition' + next(tokens) if isinstance(index, _Frame): dsk2 = dict(((name, i), (partition, part, ind, npartitions, p)) for i, (part, ind) in enumerate(zip(df._keys(), index._keys()))) else: dsk2 = dict(((name, i), (partition, part, index, npartitions, p)) for i, part in enumerate(df._keys())) # Barrier barrier_token = 'barrier' + next(tokens) dsk3 = {barrier_token: (barrier, list(dsk2))} # Collect groups name = 'shuffle-collect' + next(tokens) dsk4 = dict(((name, i), (collect, i, p, barrier_token)) for i in range(npartitions)) divisions = [None] * (npartitions + 1) dsk = merge(df.dask, dsk1, dsk2, dsk3, dsk4) if isinstance(index, _Frame): dsk.update(index.dask) return DataFrame(dsk, name, df.columns, divisions) def partition(df, index, npartitions, p): """ Partition a dataframe along a grouper, store partitions to partd """ rng = pd.Series(np.arange(len(df))) if isinstance(index, Iterator): index = list(index) if not isinstance(index, (pd.Index, pd.core.generic.NDFrame)): index = df[index] if isinstance(index, pd.Index): groups = rng.groupby([abs(hash(x)) % npartitions for x in index]) if isinstance(index, pd.Series): groups = rng.groupby(index.map(lambda x: abs(hash(x)) % npartitions).values) elif isinstance(index, pd.DataFrame): groups = rng.groupby(index.apply( lambda row: abs(hash(tuple(row))) % npartitions, axis=1).values) d = dict((i, df.iloc[groups.groups[i]]) for i in range(npartitions) if i in groups.groups) p.append(d) def collect(group, p, barrier_token): """ Collect partitions from partd, yield dataframes """ return p.get(group)
6284288aa94622d03c3f24e10f3eb63df2e27dd0
22bcb68759d516eea70d18116cd434fcd0a9d842
/scrap/infibeam_books_scrap1.py
0fbafc3b59b8a0f06df21d43016818f71ac9c0f6
[]
no_license
lovesh/abhiabhi-web-scrapper
1f5da38c873fea74870d59f61c3c4f52b50f1886
b66fcadc56377276f625530bdf8e739a01cbe16b
refs/heads/master
2021-01-01T17:16:51.577914
2014-10-18T15:56:42
2014-10-18T15:56:42
null
0
0
null
null
null
null
UTF-8
Python
false
false
6,183
py
import downloader import dom import urllib2 import re import time import math import pymongo from collections import defaultdict import datetime siteurl='http://www.infibeam.com' category_browser='http://www.infibeam.com/Books/BrowseCategories.action' subcategory_browser='http://www.infibeam.com/Books/BrowseCategories.action' books=[] book_urls=defaultdict(list) logfile=open('infibeam_books_log.txt','w') dl=downloader.Downloader() dl.addHeaders({'Origin':siteurl,'Referer':siteurl}) shipping_pattern = re.compile('in (\d+) business days', re.I) def getCategoryUrls(): category_page=dom.DOM(url=category_browser) category_path='//div[@id="allcategories"]//h3/a' category_urls=dict((link[0],'http://www.infibeam.com'+link[1]) for link in category_page.getLinksWithXpath(category_path)) return category_urls def getSubCategoryUrls(): category_page=dom.DOM(url=subcategory_browser) subcategory_path='//div[@id="allcategories"]//ul/li/a' subcategory_urls=set('http://www.infibeam.com'+link[1] for link in category_page.getLinksWithXpath(subcategory_path)) return subcategory_urls def getBookUrlsFromPage(html): book_url_path='//ul[@class="search_result"]//span[@class="title"]/h2/a' page_dom=dom.DOM(string=html) links=set(l[1] for l in page_dom.getLinksWithXpath(book_url_path)) return links def getBookUrlsOfCategory(cat,category_url): page=urllib2.urlopen(category_url) html=page.read() page.close() page=dom.DOM(string=html) urls=getBookUrlsFromPage(html) #get book urls from first page count_path='//div[@id="search_result"]/div/b[2]' count=int(page.getNodesWithXpath(count_path)[0].text.replace(',','')) print count if count>20: num_pages=int(math.ceil(count/20.0)) page_urls=set(category_url+'/search?page='+str(page) for page in xrange(2,num_pages)) print page_urls dl.putUrls(page_urls) result=dl.download() for r in result: status=result[r][0] html=result[r][1] if status > 199 and status < 400: urls.update(getBookUrlsFromPage(html)) url_dict={} for url in urls: url_dict[url]=cat return url_dict def getAllBookUrls(): global book_urls category_urls=getCategoryUrls() start=time.time() for cat in category_urls: print('Getting book urls of category %s\n\n'%cat) urls=getBookUrlsOfCategory(cat,category_urls[cat]) print('Witring book urls of category %s\n\n'%cat) logfile.write('Witring book urls of category %s\n\n'%cat) for url in urls: logfile.write(url+'\n') book_urls[url].append(urls[url]) logfile.write('\n\n\n\n') finish=time.time() print "All book urls(%s) fetched in %s\n\n",(len(book_urls),str(finish-start)) logfile.write("All book urls fetched in %s\n\n"%str(finish-start)) logfile.flush() return book_urls def parseBookPage(url=None,string=None): book={} print url if url: try: doc=dom.DOM(url=url) except urllib2.HTTPError: return False else: doc=dom.DOM(string=string) addBox=doc.getNodesWithXpath('//input[@class="buyimg "]') if url: book['url']=url if addBox: #availability check book['availability']=1 # availability 1 signals "in stock" m = shipping_pattern.search(doc.html) if m: book['shipping']=(int(m.group(1)), ) else: book['availability']=0 price_path = '//span[@class="infiPrice amount price"]' price = doc.getNodesWithXpath(price_path) if len(price) > 0: book['price']=int(price[0].text.replace(',', '')) img_path="//img[@id='imgMain']" book['img_url']=doc.getImgUrlWithXpath(img_path) tbody_path='//div[@id="ib_products"]/table/tbody' if len(doc.getNodesWithXpath(tbody_path)) == 0: tbody_path='//div[@id="ib_products"]/table' if len(doc.getNodesWithXpath(tbody_path)) == 0: tbody_path='//table[@style="color:#333; font:verdana,Arial,sans-serif;"]' data=doc.parseTBody(tbody_path) if data: if 'author' in data: data['author']=data['author'].split(',') if 'publish date' in data: m=re.search('(\d+)-(\d+)-(\d+)',data['publish date']) if m: data['pubdate']=datetime.date(int(m.group(1)),int(m.group(2)),int(m.group(3))) book.update(data) book['scraped_datetime']=datetime.datetime.now() book['last_modified_datetime']=datetime.datetime.now() book['site']='infibeam' product_history={} if 'price' in book: product_history['price']=book['price'] if 'shipping' in book: product_history['shipping']=book['shipping'] product_history['availability']=book['availability'] product_history['datetime']=book['last_modified_datetime'] book['product_history']=[product_history,] return book def go(): global books urls=getAllBookUrls() dl.putUrls(urls,10) start=time start=time.time() result=dl.download() finish=time.time() logfile.write("All books(%s) downloaded in %s"%(len(books),str(finish-start))) start=time.time() for r in result: status=result[r][0] html=result[r][1] if status > 199 and status < 400: book=parseBookPage(string=html) book['url']=r if r.find('/Books/') == -1: book['type']='ebook' else: book['type']='book' books.append(book) finish=time.time() logfile.write("All books parsed in %s"%str(finish-start)) return books def prepareXMLFeed(): books=go() root=dom.XMLNode('books') start=time.time() for book in books: child=root.createChildNode('book') child.createChildNodes(book) f=open('infibeam_books.xml','w') f.write(root.nodeToString()) f.close() finish=time.time() logfile.write("XML file created in %s"%str(finish-start))