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
48da04f61e056962abffa6aab149f7ef9965f6c3
b6bcfd935f7876fc65416e7340fda1c9b0516fd7
/examples/pbc/12-gamma_point_post_hf.py
38f775af31be359c38bccf0b98f07a92246a91a7
[ "Apache-2.0" ]
permissive
lzypotato/pyscf
62f849b9a3ec8480c3da63a5822ea780608796b2
94c21e2e9745800c7efc7256de0d628fc60afc36
refs/heads/master
2020-09-06T22:45:04.191935
2019-06-18T06:04:48
2019-06-18T06:04:48
220,578,540
1
0
Apache-2.0
2019-11-09T02:13:16
2019-11-09T02:13:15
null
UTF-8
Python
false
false
913
py
#!/usr/bin/env python ''' Gamma point post-HF calculation needs only real integrals. Methods implemented in finite-size system can be directly used here without any modification. ''' import numpy from pyscf.pbc import gto, scf cell = gto.M( a = numpy.eye(3)*3.5668, atom = '''C 0. 0. 0. C 0.8917 0.8917 0.8917 C 1.7834 1.7834 0. C 2.6751 2.6751 0.8917 C 1.7834 0. 1.7834 C 2.6751 0.8917 2.6751 C 0. 1.7834 1.7834 C 0.8917 2.6751 2.6751''', basis = '6-31g', verbose = 4, ) mf = scf.RHF(cell).density_fit() mf.with_df.mesh = [10]*3 mf.kernel() # # Import CC, TDDFT moduel from the molecular implementations # from pyscf import cc, tddft mycc = cc.CCSD(mf) mycc.kernel() mytd = tddft.TDHF(mf) mytd.nstates = 5 mytd.kernel()
[ "warlocat@zju.edu.cn" ]
warlocat@zju.edu.cn
bd55384ca7a0585407e1d2dfe91d875ad040fbdf
9b9f7546c9d4396bae7d9065b81b8c6c163b9a1d
/lectures/physics/old/NumericalIntegration003.py
04b881c55a92a5de32c593f54cd00e16b9b1b659
[]
no_license
geo7/csci321
60db9454fab00fc63624a4fc32c4dd47f02fda41
527744c8d76c5c4aceb07e23a1ec3127be305641
refs/heads/master
2020-12-28T14:50:17.267837
2015-06-03T19:18:53
2015-06-03T19:18:53
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,786
py
import numpy as N import pygame, time from pygame.locals import * from pygame.color import * import numpy as N from particlesystem import * #### Globals pygame.init() screen = pygame.display.set_mode((640,480)) background = pygame.Surface(screen.get_size()) background.fill((128,128,255)) myfont = pygame.font.Font(None, 24) ### Forces def drag(k): def func(psystem): for p in psystem.particles: p.force += -k*p.state[3:6] return func def spring(k, center = N.array((320.0, 240.0, 0.0))): def func(psystem): for p in psystem.particles: p.force += -k*(p.state[0:3] - center) return func def gravity(k): def func(psystem): for p in psystem.particles: for otherp in psystem.particles: if p != otherp: v = p.state[0:3] - otherp.state[0:3] p.force += -k*v/N.sqrt(N.dot(v,v)) return func #### Utilities def newParticle(size): m = N.random.random()*5.0 state = N.zeros(6) for i in range(3): state[i] = N.random.random()*size/2.0 + size/4.0 for i in range(3): state[i+3] = N.random.random()*2.0 return Particle(m, N.array(state)) def newSystem(n): w,h = screen.get_size() size = min(w,h) particles = [newParticle(size) for i in range(n)] return ParticleSystem(particles) def reset(n): screen.blit(background, (0,0)) return newSystem(n) def textout(ls): for i,txt in enumerate(ls): rtext = myfont.render(txt, 1, (0,0,0)) textrec = rtext.get_rect() textrec.topleft = (0, i*22) screen.blit(rtext, textrec) def main(): nParticles = 20 plotTime = False myforces = [spring(0.1)] mytext = ["spring(0.1)"] mysystem = newSystem(20) clock = pygame.time.Clock() running = 1 deltaT = 0.1 screen.blit(background, (0,0)) while running: clock.tick(60) for event in pygame.event.get(): if event.type == QUIT: running = 0 elif event.type == KEYDOWN: if event.key == K_ESCAPE: running = 0 elif event.key == K_F12: mysystem = reset(nParticles) plotTime = not plotTime elif event.key == K_F1: mysystem = reset(nParticles) myforces = [spring(0.1)] mytext = ['spring(0.1)'] elif event.key == K_F2: mysystem = reset(nParticles) myforces = [spring(0.1), drag(0.05)] mytext = ['spring(0.1)','drag(0.05)'] elif event.key == K_F3: mysystem = reset(nParticles) myforces = [gravity(5.0)] mytext = ['gravity(5.0)'] elif event.key == K_F4: mysystem = reset(nParticles) myforces = [gravity(2.0),drag(0.1)] mytext = ['gravity(2)','drag(0.1)'] elif event.key == K_F5: mysystem = reset(nParticles) myforces = [gravity(2.0),spring(0.2),drag(0.05)] mytext = ['gravity(2.0)','spring(0.2)','drag(0.05)'] EulerStep(mysystem, myforces, deltaT) if plotTime: mysystem.Draw(screen, time=True) else: screen.blit(background, (0,0)) mysystem.Draw(screen) textout(mytext) pygame.display.flip() if __name__ == "__main__": try: main() finally: pygame.quit()
[ "geoffrey.matthews@wwu.edu" ]
geoffrey.matthews@wwu.edu
feb125c8c1bdc5ba19a5cbac3035d3dc811bf671
4e5d078e21cccd8ad2793055ca79865c2bb4c10a
/crawler/julyedu_crawler/julyedu_crawler/settings.py
d8b27127827e007dcc8ffec5a361ee941877fd59
[]
no_license
gifts1912/PythonProject
13cabf395cd9efaebca19e2ea8519d39b772a3c6
e6bccdb37a60bee9c219eaf8f9514109074c3ce4
refs/heads/master
2021-01-09T09:37:47.114854
2017-04-01T07:45:09
2017-04-01T07:45:09
81,183,554
1
0
null
null
null
null
UTF-8
Python
false
false
3,206
py
# -*- coding: utf-8 -*- # Scrapy settings for julyedu_crawler project # # For simplicity, this file contains only settings considered important or # commonly used. You can find more settings consulting the documentation: # # http://doc.scrapy.org/en/latest/topics/settings.html # http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html # http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html BOT_NAME = 'julyedu_crawler' SPIDER_MODULES = ['julyedu_crawler.spiders'] NEWSPIDER_MODULE = 'julyedu_crawler.spiders' # Crawl responsibly by identifying yourself (and your website) on the user-agent #USER_AGENT = 'julyedu_crawler (+http://www.yourdomain.com)' # Obey robots.txt rules ROBOTSTXT_OBEY = True # Configure maximum concurrent requests performed by Scrapy (default: 16) #CONCURRENT_REQUESTS = 32 # Configure a delay for requests for the same website (default: 0) # See http://scrapy.readthedocs.org/en/latest/topics/settings.html#download-delay # See also autothrottle settings and docs #DOWNLOAD_DELAY = 3 # The download delay setting will honor only one of: #CONCURRENT_REQUESTS_PER_DOMAIN = 16 #CONCURRENT_REQUESTS_PER_IP = 16 # Disable cookies (enabled by default) #COOKIES_ENABLED = False # Disable Telnet Console (enabled by default) #TELNETCONSOLE_ENABLED = False # Override the default request headers: #DEFAULT_REQUEST_HEADERS = { # 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', # 'Accept-Language': 'en', #} # Enable or disable spider middlewares # See http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html #SPIDER_MIDDLEWARES = { # 'julyedu_crawler.middlewares.JulyeduCrawlerSpiderMiddleware': 543, #} # Enable or disable downloader middlewares # See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html #DOWNLOADER_MIDDLEWARES = { # 'julyedu_crawler.middlewares.MyCustomDownloaderMiddleware': 543, #} # Enable or disable extensions # See http://scrapy.readthedocs.org/en/latest/topics/extensions.html #EXTENSIONS = { # 'scrapy.extensions.telnet.TelnetConsole': None, #} # Configure item pipelines # See http://scrapy.readthedocs.org/en/latest/topics/item-pipeline.html #ITEM_PIPELINES = { # 'julyedu_crawler.pipelines.SomePipeline': 300, #} # Enable and configure the AutoThrottle extension (disabled by default) # See http://doc.scrapy.org/en/latest/topics/autothrottle.html #AUTOTHROTTLE_ENABLED = True # The initial download delay #AUTOTHROTTLE_START_DELAY = 5 # The maximum download delay to be set in case of high latencies #AUTOTHROTTLE_MAX_DELAY = 60 # The average number of requests Scrapy should be sending in parallel to # each remote server #AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0 # Enable showing throttling stats for every response received: #AUTOTHROTTLE_DEBUG = False # Enable and configure HTTP caching (disabled by default) # See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings #HTTPCACHE_ENABLED = True #HTTPCACHE_EXPIRATION_SECS = 0 #HTTPCACHE_DIR = 'httpcache' #HTTPCACHE_IGNORE_HTTP_CODES = [] #HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'
[ "hengyliu@hotmail.com" ]
hengyliu@hotmail.com
d7dfea7732fa3aeb28a4d33e5c072968ab7880a2
de0724c1b71dce624ae2fcef9044952a6360c8cf
/pca_masks/extract_signal_subrois.py
7733df08085d1f4ecf29433da676cda48a8c7937
[]
no_license
Gilles86/bias_task
8c52914c55dc7866d5d679305be2ad4fcb96dc5e
18cce163e662c7edf8d42d7f32e87f0ed644875d
refs/heads/master
2021-07-09T01:45:43.381063
2020-07-29T08:17:20
2020-07-29T08:17:20
168,526,219
0
0
null
null
null
null
UTF-8
Python
false
false
3,474
py
import argparse import os.path as op import nipype.pipeline.engine as pe import nipype.interfaces.io as nio import nipype.interfaces.utility as niu import nipype.interfaces.ants as ants from niworkflows.interfaces.bids import DerivativesDataSink def main(derivatives, ds): if ds == 'ds-01': subjects = ['{:02d}'.format(s) for s in range(1, 20)] elif ds == 'ds-02': subjects = ['{:02d}'.format(s) for s in range(1, 16)] subjects.pop(3) # Remove 4 subjects = subjects wf_folder = '/tmp/workflow_folders' templates = {'preproc':op.join(derivatives, ds, 'fmriprep', 'sub-{subject}', 'func', 'sub-{subject}_task-randomdotmotion_run-*_space-T1w_desc-preproc_bold.nii.gz')} templates['individual_mask'] = op.join(derivatives, ds, 'pca_masks', 'sub-{subject}', 'anat', 'sub-{subject}_desc-{mask}_space-T1w_subroi-{subroi}_roi.nii.gz') wf = pe.Workflow(name='extract_signal_submasks_{}'.format(ds), base_dir=wf_folder) mask_identity = pe.Node(niu.IdentityInterface(fields=['mask', 'subroi']), name='mask_identity') mask_identity.iterables = [('mask', ['stnl', 'stnr']), ('subroi', ['A', 'B', 'C'])] selector = pe.Node(nio.SelectFiles(templates), name='selector') selector.iterables = [('subject', subjects)] wf.connect(mask_identity, 'mask', selector, 'mask') wf.connect(mask_identity, 'subroi', selector, 'subroi') def extract_signal(preproc, mask): from nilearn import image from nilearn import input_data from nipype.utils.filemanip import split_filename import os.path as op import pandas as pd _, fn, ext = split_filename(preproc) masker = input_data.NiftiMasker(mask, standardize='psc') data = pd.DataFrame(masker.fit_transform(preproc)) new_fn = op.abspath('{}_signal.csv'.format(fn)) data.to_csv(new_fn) return new_fn extract_signal_node = pe.MapNode(niu.Function(function=extract_signal, input_names=['preproc', 'mask'], output_names=['signal']), iterfield=['preproc'], name='extract_signal_node') wf.connect(selector, 'preproc', extract_signal_node, 'preproc') wf.connect(selector, 'individual_mask', extract_signal_node, 'mask') datasink_signal = pe.MapNode(DerivativesDataSink(base_directory=op.join(derivatives, ds), out_path_base='extracted_signal'), iterfield=['source_file', 'in_file'], name='datasink_signal') wf.connect(selector, 'preproc', datasink_signal, 'source_file') wf.connect(extract_signal_node, 'signal', datasink_signal, 'in_file') wf.connect(mask_identity, 'mask', datasink_signal, 'desc') def get_subroi_suffix(subroi): return 'subroi-{}_roi'.format(subroi) wf.connect(mask_identity, ('subroi', get_subroi_suffix), datasink_signal, 'suffix') wf.run(plugin='MultiProc', plugin_args={'n_procs':4}) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('ds', type=str,) args = parser.parse_args() main('/home/shared/2018/subcortex/bias_task/', args.ds)
[ "Gilles.de.Hollander@gmail.com" ]
Gilles.de.Hollander@gmail.com
fd5617504c204afac765da96f70e358c59e59da4
fab14fae2b494068aa793901d76464afb965df7e
/benchmarks/ltl_maxplus/f3/maxplus_28_14.py
431fa8d3ba87d98f91220e70c6fcd890d93465fc
[ "MIT" ]
permissive
teodorov/F3
673f6f9ccc25acdfdecbfc180f439253474ba250
c863215c318d7d5f258eb9be38c6962cf6863b52
refs/heads/master
2023-08-04T17:37:38.771863
2021-09-16T07:38:28
2021-09-16T07:38:28
null
0
0
null
null
null
null
UTF-8
Python
false
false
80,926
py
from collections import Iterable from mathsat import msat_term, msat_env from mathsat import msat_make_true, msat_make_false from mathsat import msat_make_constant, msat_declare_function from mathsat import msat_get_rational_type from mathsat import msat_make_and as _msat_make_and from mathsat import msat_make_or as _msat_make_or from mathsat import msat_make_not from mathsat import msat_make_leq, msat_make_equal from mathsat import msat_make_number, msat_make_plus, msat_make_times from ltl.ltl import TermMap, LTLEncoder from utils import name_next def msat_make_and(menv: msat_env, *args): if len(args) == 0: return msat_make_true(menv) if len(args) == 1: return args[0] res = _msat_make_and(menv, args[0], args[1]) for arg in args[2:]: res = _msat_make_and(menv, res, arg) return res def msat_make_or(menv: msat_env, *args): if len(args) == 0: return msat_make_false(menv) if len(args) == 1: return args[0] res = _msat_make_or(menv, args[0], args[1]) for arg in args[2:]: res = _msat_make_or(menv, res, arg) return res def msat_make_minus(menv: msat_env, arg0: msat_term, arg1: msat_term): n_m1 = msat_make_number(menv, "-1") arg1 = msat_make_times(menv, arg1, n_m1) return msat_make_plus(menv, arg0, arg1) def msat_make_lt(menv: msat_env, arg0: msat_term, arg1: msat_term): geq = msat_make_geq(menv, arg0, arg1) return msat_make_not(menv, geq) def msat_make_geq(menv: msat_env, arg0: msat_term, arg1: msat_term): return msat_make_leq(menv, arg1, arg0) def msat_make_gt(menv: msat_env, arg0: msat_term, arg1: msat_term): leq = msat_make_leq(menv, arg0, arg1) return msat_make_not(menv, leq) def msat_make_impl(menv: msat_env, arg0: msat_term, arg1: msat_term): n_arg0 = msat_make_not(menv, arg0) return msat_make_or(menv, n_arg0, arg1) def check_ltl(menv: msat_env, enc: LTLEncoder) -> (Iterable, msat_term, msat_term, msat_term): assert menv assert isinstance(menv, msat_env) assert enc assert isinstance(enc, LTLEncoder) real_type = msat_get_rational_type(menv) names = ["x_0", "x_1", "x_2", "x_3", "x_4", "x_5", "x_6", "x_7", "x_8", "x_9", "x_10", "x_11", "x_12", "x_13", "x_14", "x_15", "x_16", "x_17", "x_18", "x_19", "x_20", "x_21", "x_22", "x_23", "x_24", "x_25", "x_26", "x_27"] xs = [msat_declare_function(menv, name, real_type) for name in names] xs = [msat_make_constant(menv, x) for x in xs] x_xs = [msat_declare_function(menv, name_next(name), real_type) for name in names] x_xs = [msat_make_constant(menv, x_x) for x_x in x_xs] curr2next = {x: x_x for x, x_x in zip(xs, x_xs)} n_10_0 = msat_make_number(menv, "10.0") n_11_0 = msat_make_number(menv, "11.0") n_12_0 = msat_make_number(menv, "12.0") n_13_0 = msat_make_number(menv, "13.0") n_14_0 = msat_make_number(menv, "14.0") n_15_0 = msat_make_number(menv, "15.0") n_16_0 = msat_make_number(menv, "16.0") n_17_0 = msat_make_number(menv, "17.0") n_18_0 = msat_make_number(menv, "18.0") n_19_0 = msat_make_number(menv, "19.0") n_1_0 = msat_make_number(menv, "1.0") n_20_0 = msat_make_number(menv, "20.0") n_2_0 = msat_make_number(menv, "2.0") n_3_0 = msat_make_number(menv, "3.0") n_4_0 = msat_make_number(menv, "4.0") n_5_0 = msat_make_number(menv, "5.0") n_6_0 = msat_make_number(menv, "6.0") n_7_0 = msat_make_number(menv, "7.0") n_8_0 = msat_make_number(menv, "8.0") n_9_0 = msat_make_number(menv, "9.0") init = msat_make_true(menv) trans = msat_make_true(menv) # transitions expr0 = msat_make_plus(menv, xs[0], n_10_0) expr1 = msat_make_plus(menv, xs[1], n_14_0) expr2 = msat_make_plus(menv, xs[3], n_10_0) expr3 = msat_make_plus(menv, xs[4], n_8_0) expr4 = msat_make_plus(menv, xs[6], n_4_0) expr5 = msat_make_plus(menv, xs[8], n_7_0) expr6 = msat_make_plus(menv, xs[12], n_5_0) expr7 = msat_make_plus(menv, xs[14], n_10_0) expr8 = msat_make_plus(menv, xs[18], n_17_0) expr9 = msat_make_plus(menv, xs[19], n_10_0) expr10 = msat_make_plus(menv, xs[23], n_15_0) expr11 = msat_make_plus(menv, xs[25], n_1_0) expr12 = msat_make_plus(menv, xs[26], n_7_0) expr13 = msat_make_plus(menv, xs[27], n_3_0) _t = msat_make_and(menv, msat_make_geq(menv, x_xs[0], expr0), msat_make_geq(menv, x_xs[0], expr1), msat_make_geq(menv, x_xs[0], expr2), msat_make_geq(menv, x_xs[0], expr3), msat_make_geq(menv, x_xs[0], expr4), msat_make_geq(menv, x_xs[0], expr5), msat_make_geq(menv, x_xs[0], expr6), msat_make_geq(menv, x_xs[0], expr7), msat_make_geq(menv, x_xs[0], expr8), msat_make_geq(menv, x_xs[0], expr9), msat_make_geq(menv, x_xs[0], expr10), msat_make_geq(menv, x_xs[0], expr11), msat_make_geq(menv, x_xs[0], expr12), msat_make_geq(menv, x_xs[0], expr13),) _t = msat_make_and(menv, _t, msat_make_or(menv, msat_make_equal(menv, x_xs[0], expr0), msat_make_equal(menv, x_xs[0], expr1), msat_make_equal(menv, x_xs[0], expr2), msat_make_equal(menv, x_xs[0], expr3), msat_make_equal(menv, x_xs[0], expr4), msat_make_equal(menv, x_xs[0], expr5), msat_make_equal(menv, x_xs[0], expr6), msat_make_equal(menv, x_xs[0], expr7), msat_make_equal(menv, x_xs[0], expr8), msat_make_equal(menv, x_xs[0], expr9), msat_make_equal(menv, x_xs[0], expr10), msat_make_equal(menv, x_xs[0], expr11), msat_make_equal(menv, x_xs[0], expr12), msat_make_equal(menv, x_xs[0], expr13),)) trans = msat_make_and(menv, trans, _t) expr0 = msat_make_plus(menv, xs[1], n_7_0) expr1 = msat_make_plus(menv, xs[2], n_2_0) expr2 = msat_make_plus(menv, xs[3], n_6_0) expr3 = msat_make_plus(menv, xs[9], n_19_0) expr4 = msat_make_plus(menv, xs[10], n_13_0) expr5 = msat_make_plus(menv, xs[11], n_5_0) expr6 = msat_make_plus(menv, xs[13], n_3_0) expr7 = msat_make_plus(menv, xs[16], n_13_0) expr8 = msat_make_plus(menv, xs[18], n_7_0) expr9 = msat_make_plus(menv, xs[21], n_20_0) expr10 = msat_make_plus(menv, xs[22], n_13_0) expr11 = msat_make_plus(menv, xs[24], n_19_0) expr12 = msat_make_plus(menv, xs[26], n_2_0) expr13 = msat_make_plus(menv, xs[27], n_5_0) _t = msat_make_and(menv, msat_make_geq(menv, x_xs[1], expr0), msat_make_geq(menv, x_xs[1], expr1), msat_make_geq(menv, x_xs[1], expr2), msat_make_geq(menv, x_xs[1], expr3), msat_make_geq(menv, x_xs[1], expr4), msat_make_geq(menv, x_xs[1], expr5), msat_make_geq(menv, x_xs[1], expr6), msat_make_geq(menv, x_xs[1], expr7), msat_make_geq(menv, x_xs[1], expr8), msat_make_geq(menv, x_xs[1], expr9), msat_make_geq(menv, x_xs[1], expr10), msat_make_geq(menv, x_xs[1], expr11), msat_make_geq(menv, x_xs[1], expr12), msat_make_geq(menv, x_xs[1], expr13),) _t = msat_make_and(menv, _t, msat_make_or(menv, msat_make_equal(menv, x_xs[1], expr0), msat_make_equal(menv, x_xs[1], expr1), msat_make_equal(menv, x_xs[1], expr2), msat_make_equal(menv, x_xs[1], expr3), msat_make_equal(menv, x_xs[1], expr4), msat_make_equal(menv, x_xs[1], expr5), msat_make_equal(menv, x_xs[1], expr6), msat_make_equal(menv, x_xs[1], expr7), msat_make_equal(menv, x_xs[1], expr8), msat_make_equal(menv, x_xs[1], expr9), msat_make_equal(menv, x_xs[1], expr10), msat_make_equal(menv, x_xs[1], expr11), msat_make_equal(menv, x_xs[1], expr12), msat_make_equal(menv, x_xs[1], expr13),)) trans = msat_make_and(menv, trans, _t) expr0 = msat_make_plus(menv, xs[2], n_7_0) expr1 = msat_make_plus(menv, xs[9], n_3_0) expr2 = msat_make_plus(menv, xs[10], n_14_0) expr3 = msat_make_plus(menv, xs[11], n_18_0) expr4 = msat_make_plus(menv, xs[12], n_20_0) expr5 = msat_make_plus(menv, xs[16], n_17_0) expr6 = msat_make_plus(menv, xs[17], n_4_0) expr7 = msat_make_plus(menv, xs[18], n_6_0) expr8 = msat_make_plus(menv, xs[19], n_11_0) expr9 = msat_make_plus(menv, xs[20], n_19_0) expr10 = msat_make_plus(menv, xs[21], n_7_0) expr11 = msat_make_plus(menv, xs[22], n_3_0) expr12 = msat_make_plus(menv, xs[23], n_9_0) expr13 = msat_make_plus(menv, xs[26], n_9_0) _t = msat_make_and(menv, msat_make_geq(menv, x_xs[2], expr0), msat_make_geq(menv, x_xs[2], expr1), msat_make_geq(menv, x_xs[2], expr2), msat_make_geq(menv, x_xs[2], expr3), msat_make_geq(menv, x_xs[2], expr4), msat_make_geq(menv, x_xs[2], expr5), msat_make_geq(menv, x_xs[2], expr6), msat_make_geq(menv, x_xs[2], expr7), msat_make_geq(menv, x_xs[2], expr8), msat_make_geq(menv, x_xs[2], expr9), msat_make_geq(menv, x_xs[2], expr10), msat_make_geq(menv, x_xs[2], expr11), msat_make_geq(menv, x_xs[2], expr12), msat_make_geq(menv, x_xs[2], expr13),) _t = msat_make_and(menv, _t, msat_make_or(menv, msat_make_equal(menv, x_xs[2], expr0), msat_make_equal(menv, x_xs[2], expr1), msat_make_equal(menv, x_xs[2], expr2), msat_make_equal(menv, x_xs[2], expr3), msat_make_equal(menv, x_xs[2], expr4), msat_make_equal(menv, x_xs[2], expr5), msat_make_equal(menv, x_xs[2], expr6), msat_make_equal(menv, x_xs[2], expr7), msat_make_equal(menv, x_xs[2], expr8), msat_make_equal(menv, x_xs[2], expr9), msat_make_equal(menv, x_xs[2], expr10), msat_make_equal(menv, x_xs[2], expr11), msat_make_equal(menv, x_xs[2], expr12), msat_make_equal(menv, x_xs[2], expr13),)) trans = msat_make_and(menv, trans, _t) expr0 = msat_make_plus(menv, xs[2], n_1_0) expr1 = msat_make_plus(menv, xs[6], n_12_0) expr2 = msat_make_plus(menv, xs[7], n_20_0) expr3 = msat_make_plus(menv, xs[8], n_15_0) expr4 = msat_make_plus(menv, xs[9], n_10_0) expr5 = msat_make_plus(menv, xs[12], n_15_0) expr6 = msat_make_plus(menv, xs[14], n_18_0) expr7 = msat_make_plus(menv, xs[15], n_17_0) expr8 = msat_make_plus(menv, xs[18], n_20_0) expr9 = msat_make_plus(menv, xs[19], n_17_0) expr10 = msat_make_plus(menv, xs[22], n_15_0) expr11 = msat_make_plus(menv, xs[23], n_11_0) expr12 = msat_make_plus(menv, xs[26], n_10_0) expr13 = msat_make_plus(menv, xs[27], n_5_0) _t = msat_make_and(menv, msat_make_geq(menv, x_xs[3], expr0), msat_make_geq(menv, x_xs[3], expr1), msat_make_geq(menv, x_xs[3], expr2), msat_make_geq(menv, x_xs[3], expr3), msat_make_geq(menv, x_xs[3], expr4), msat_make_geq(menv, x_xs[3], expr5), msat_make_geq(menv, x_xs[3], expr6), msat_make_geq(menv, x_xs[3], expr7), msat_make_geq(menv, x_xs[3], expr8), msat_make_geq(menv, x_xs[3], expr9), msat_make_geq(menv, x_xs[3], expr10), msat_make_geq(menv, x_xs[3], expr11), msat_make_geq(menv, x_xs[3], expr12), msat_make_geq(menv, x_xs[3], expr13),) _t = msat_make_and(menv, _t, msat_make_or(menv, msat_make_equal(menv, x_xs[3], expr0), msat_make_equal(menv, x_xs[3], expr1), msat_make_equal(menv, x_xs[3], expr2), msat_make_equal(menv, x_xs[3], expr3), msat_make_equal(menv, x_xs[3], expr4), msat_make_equal(menv, x_xs[3], expr5), msat_make_equal(menv, x_xs[3], expr6), msat_make_equal(menv, x_xs[3], expr7), msat_make_equal(menv, x_xs[3], expr8), msat_make_equal(menv, x_xs[3], expr9), msat_make_equal(menv, x_xs[3], expr10), msat_make_equal(menv, x_xs[3], expr11), msat_make_equal(menv, x_xs[3], expr12), msat_make_equal(menv, x_xs[3], expr13),)) trans = msat_make_and(menv, trans, _t) expr0 = msat_make_plus(menv, xs[2], n_10_0) expr1 = msat_make_plus(menv, xs[4], n_13_0) expr2 = msat_make_plus(menv, xs[6], n_5_0) expr3 = msat_make_plus(menv, xs[8], n_3_0) expr4 = msat_make_plus(menv, xs[9], n_3_0) expr5 = msat_make_plus(menv, xs[11], n_8_0) expr6 = msat_make_plus(menv, xs[12], n_19_0) expr7 = msat_make_plus(menv, xs[13], n_6_0) expr8 = msat_make_plus(menv, xs[14], n_13_0) expr9 = msat_make_plus(menv, xs[16], n_11_0) expr10 = msat_make_plus(menv, xs[18], n_15_0) expr11 = msat_make_plus(menv, xs[20], n_1_0) expr12 = msat_make_plus(menv, xs[23], n_1_0) expr13 = msat_make_plus(menv, xs[27], n_16_0) _t = msat_make_and(menv, msat_make_geq(menv, x_xs[4], expr0), msat_make_geq(menv, x_xs[4], expr1), msat_make_geq(menv, x_xs[4], expr2), msat_make_geq(menv, x_xs[4], expr3), msat_make_geq(menv, x_xs[4], expr4), msat_make_geq(menv, x_xs[4], expr5), msat_make_geq(menv, x_xs[4], expr6), msat_make_geq(menv, x_xs[4], expr7), msat_make_geq(menv, x_xs[4], expr8), msat_make_geq(menv, x_xs[4], expr9), msat_make_geq(menv, x_xs[4], expr10), msat_make_geq(menv, x_xs[4], expr11), msat_make_geq(menv, x_xs[4], expr12), msat_make_geq(menv, x_xs[4], expr13),) _t = msat_make_and(menv, _t, msat_make_or(menv, msat_make_equal(menv, x_xs[4], expr0), msat_make_equal(menv, x_xs[4], expr1), msat_make_equal(menv, x_xs[4], expr2), msat_make_equal(menv, x_xs[4], expr3), msat_make_equal(menv, x_xs[4], expr4), msat_make_equal(menv, x_xs[4], expr5), msat_make_equal(menv, x_xs[4], expr6), msat_make_equal(menv, x_xs[4], expr7), msat_make_equal(menv, x_xs[4], expr8), msat_make_equal(menv, x_xs[4], expr9), msat_make_equal(menv, x_xs[4], expr10), msat_make_equal(menv, x_xs[4], expr11), msat_make_equal(menv, x_xs[4], expr12), msat_make_equal(menv, x_xs[4], expr13),)) trans = msat_make_and(menv, trans, _t) expr0 = msat_make_plus(menv, xs[1], n_13_0) expr1 = msat_make_plus(menv, xs[2], n_16_0) expr2 = msat_make_plus(menv, xs[4], n_16_0) expr3 = msat_make_plus(menv, xs[6], n_11_0) expr4 = msat_make_plus(menv, xs[7], n_7_0) expr5 = msat_make_plus(menv, xs[8], n_1_0) expr6 = msat_make_plus(menv, xs[9], n_12_0) expr7 = msat_make_plus(menv, xs[10], n_17_0) expr8 = msat_make_plus(menv, xs[11], n_12_0) expr9 = msat_make_plus(menv, xs[13], n_16_0) expr10 = msat_make_plus(menv, xs[14], n_11_0) expr11 = msat_make_plus(menv, xs[16], n_16_0) expr12 = msat_make_plus(menv, xs[22], n_18_0) expr13 = msat_make_plus(menv, xs[27], n_15_0) _t = msat_make_and(menv, msat_make_geq(menv, x_xs[5], expr0), msat_make_geq(menv, x_xs[5], expr1), msat_make_geq(menv, x_xs[5], expr2), msat_make_geq(menv, x_xs[5], expr3), msat_make_geq(menv, x_xs[5], expr4), msat_make_geq(menv, x_xs[5], expr5), msat_make_geq(menv, x_xs[5], expr6), msat_make_geq(menv, x_xs[5], expr7), msat_make_geq(menv, x_xs[5], expr8), msat_make_geq(menv, x_xs[5], expr9), msat_make_geq(menv, x_xs[5], expr10), msat_make_geq(menv, x_xs[5], expr11), msat_make_geq(menv, x_xs[5], expr12), msat_make_geq(menv, x_xs[5], expr13),) _t = msat_make_and(menv, _t, msat_make_or(menv, msat_make_equal(menv, x_xs[5], expr0), msat_make_equal(menv, x_xs[5], expr1), msat_make_equal(menv, x_xs[5], expr2), msat_make_equal(menv, x_xs[5], expr3), msat_make_equal(menv, x_xs[5], expr4), msat_make_equal(menv, x_xs[5], expr5), msat_make_equal(menv, x_xs[5], expr6), msat_make_equal(menv, x_xs[5], expr7), msat_make_equal(menv, x_xs[5], expr8), msat_make_equal(menv, x_xs[5], expr9), msat_make_equal(menv, x_xs[5], expr10), msat_make_equal(menv, x_xs[5], expr11), msat_make_equal(menv, x_xs[5], expr12), msat_make_equal(menv, x_xs[5], expr13),)) trans = msat_make_and(menv, trans, _t) expr0 = msat_make_plus(menv, xs[1], n_15_0) expr1 = msat_make_plus(menv, xs[2], n_12_0) expr2 = msat_make_plus(menv, xs[4], n_15_0) expr3 = msat_make_plus(menv, xs[5], n_12_0) expr4 = msat_make_plus(menv, xs[8], n_4_0) expr5 = msat_make_plus(menv, xs[9], n_6_0) expr6 = msat_make_plus(menv, xs[10], n_8_0) expr7 = msat_make_plus(menv, xs[11], n_17_0) expr8 = msat_make_plus(menv, xs[14], n_19_0) expr9 = msat_make_plus(menv, xs[16], n_11_0) expr10 = msat_make_plus(menv, xs[17], n_2_0) expr11 = msat_make_plus(menv, xs[18], n_5_0) expr12 = msat_make_plus(menv, xs[25], n_18_0) expr13 = msat_make_plus(menv, xs[27], n_18_0) _t = msat_make_and(menv, msat_make_geq(menv, x_xs[6], expr0), msat_make_geq(menv, x_xs[6], expr1), msat_make_geq(menv, x_xs[6], expr2), msat_make_geq(menv, x_xs[6], expr3), msat_make_geq(menv, x_xs[6], expr4), msat_make_geq(menv, x_xs[6], expr5), msat_make_geq(menv, x_xs[6], expr6), msat_make_geq(menv, x_xs[6], expr7), msat_make_geq(menv, x_xs[6], expr8), msat_make_geq(menv, x_xs[6], expr9), msat_make_geq(menv, x_xs[6], expr10), msat_make_geq(menv, x_xs[6], expr11), msat_make_geq(menv, x_xs[6], expr12), msat_make_geq(menv, x_xs[6], expr13),) _t = msat_make_and(menv, _t, msat_make_or(menv, msat_make_equal(menv, x_xs[6], expr0), msat_make_equal(menv, x_xs[6], expr1), msat_make_equal(menv, x_xs[6], expr2), msat_make_equal(menv, x_xs[6], expr3), msat_make_equal(menv, x_xs[6], expr4), msat_make_equal(menv, x_xs[6], expr5), msat_make_equal(menv, x_xs[6], expr6), msat_make_equal(menv, x_xs[6], expr7), msat_make_equal(menv, x_xs[6], expr8), msat_make_equal(menv, x_xs[6], expr9), msat_make_equal(menv, x_xs[6], expr10), msat_make_equal(menv, x_xs[6], expr11), msat_make_equal(menv, x_xs[6], expr12), msat_make_equal(menv, x_xs[6], expr13),)) trans = msat_make_and(menv, trans, _t) expr0 = msat_make_plus(menv, xs[2], n_20_0) expr1 = msat_make_plus(menv, xs[4], n_3_0) expr2 = msat_make_plus(menv, xs[6], n_9_0) expr3 = msat_make_plus(menv, xs[7], n_12_0) expr4 = msat_make_plus(menv, xs[8], n_5_0) expr5 = msat_make_plus(menv, xs[9], n_14_0) expr6 = msat_make_plus(menv, xs[10], n_6_0) expr7 = msat_make_plus(menv, xs[14], n_13_0) expr8 = msat_make_plus(menv, xs[16], n_15_0) expr9 = msat_make_plus(menv, xs[19], n_9_0) expr10 = msat_make_plus(menv, xs[23], n_16_0) expr11 = msat_make_plus(menv, xs[24], n_5_0) expr12 = msat_make_plus(menv, xs[25], n_13_0) expr13 = msat_make_plus(menv, xs[27], n_18_0) _t = msat_make_and(menv, msat_make_geq(menv, x_xs[7], expr0), msat_make_geq(menv, x_xs[7], expr1), msat_make_geq(menv, x_xs[7], expr2), msat_make_geq(menv, x_xs[7], expr3), msat_make_geq(menv, x_xs[7], expr4), msat_make_geq(menv, x_xs[7], expr5), msat_make_geq(menv, x_xs[7], expr6), msat_make_geq(menv, x_xs[7], expr7), msat_make_geq(menv, x_xs[7], expr8), msat_make_geq(menv, x_xs[7], expr9), msat_make_geq(menv, x_xs[7], expr10), msat_make_geq(menv, x_xs[7], expr11), msat_make_geq(menv, x_xs[7], expr12), msat_make_geq(menv, x_xs[7], expr13),) _t = msat_make_and(menv, _t, msat_make_or(menv, msat_make_equal(menv, x_xs[7], expr0), msat_make_equal(menv, x_xs[7], expr1), msat_make_equal(menv, x_xs[7], expr2), msat_make_equal(menv, x_xs[7], expr3), msat_make_equal(menv, x_xs[7], expr4), msat_make_equal(menv, x_xs[7], expr5), msat_make_equal(menv, x_xs[7], expr6), msat_make_equal(menv, x_xs[7], expr7), msat_make_equal(menv, x_xs[7], expr8), msat_make_equal(menv, x_xs[7], expr9), msat_make_equal(menv, x_xs[7], expr10), msat_make_equal(menv, x_xs[7], expr11), msat_make_equal(menv, x_xs[7], expr12), msat_make_equal(menv, x_xs[7], expr13),)) trans = msat_make_and(menv, trans, _t) expr0 = msat_make_plus(menv, xs[3], n_17_0) expr1 = msat_make_plus(menv, xs[4], n_8_0) expr2 = msat_make_plus(menv, xs[6], n_1_0) expr3 = msat_make_plus(menv, xs[7], n_5_0) expr4 = msat_make_plus(menv, xs[8], n_6_0) expr5 = msat_make_plus(menv, xs[9], n_5_0) expr6 = msat_make_plus(menv, xs[12], n_5_0) expr7 = msat_make_plus(menv, xs[15], n_1_0) expr8 = msat_make_plus(menv, xs[16], n_20_0) expr9 = msat_make_plus(menv, xs[18], n_3_0) expr10 = msat_make_plus(menv, xs[20], n_20_0) expr11 = msat_make_plus(menv, xs[21], n_10_0) expr12 = msat_make_plus(menv, xs[25], n_8_0) expr13 = msat_make_plus(menv, xs[27], n_15_0) _t = msat_make_and(menv, msat_make_geq(menv, x_xs[8], expr0), msat_make_geq(menv, x_xs[8], expr1), msat_make_geq(menv, x_xs[8], expr2), msat_make_geq(menv, x_xs[8], expr3), msat_make_geq(menv, x_xs[8], expr4), msat_make_geq(menv, x_xs[8], expr5), msat_make_geq(menv, x_xs[8], expr6), msat_make_geq(menv, x_xs[8], expr7), msat_make_geq(menv, x_xs[8], expr8), msat_make_geq(menv, x_xs[8], expr9), msat_make_geq(menv, x_xs[8], expr10), msat_make_geq(menv, x_xs[8], expr11), msat_make_geq(menv, x_xs[8], expr12), msat_make_geq(menv, x_xs[8], expr13),) _t = msat_make_and(menv, _t, msat_make_or(menv, msat_make_equal(menv, x_xs[8], expr0), msat_make_equal(menv, x_xs[8], expr1), msat_make_equal(menv, x_xs[8], expr2), msat_make_equal(menv, x_xs[8], expr3), msat_make_equal(menv, x_xs[8], expr4), msat_make_equal(menv, x_xs[8], expr5), msat_make_equal(menv, x_xs[8], expr6), msat_make_equal(menv, x_xs[8], expr7), msat_make_equal(menv, x_xs[8], expr8), msat_make_equal(menv, x_xs[8], expr9), msat_make_equal(menv, x_xs[8], expr10), msat_make_equal(menv, x_xs[8], expr11), msat_make_equal(menv, x_xs[8], expr12), msat_make_equal(menv, x_xs[8], expr13),)) trans = msat_make_and(menv, trans, _t) expr0 = msat_make_plus(menv, xs[1], n_11_0) expr1 = msat_make_plus(menv, xs[5], n_7_0) expr2 = msat_make_plus(menv, xs[6], n_10_0) expr3 = msat_make_plus(menv, xs[9], n_3_0) expr4 = msat_make_plus(menv, xs[11], n_14_0) expr5 = msat_make_plus(menv, xs[13], n_5_0) expr6 = msat_make_plus(menv, xs[17], n_3_0) expr7 = msat_make_plus(menv, xs[18], n_4_0) expr8 = msat_make_plus(menv, xs[20], n_2_0) expr9 = msat_make_plus(menv, xs[22], n_12_0) expr10 = msat_make_plus(menv, xs[23], n_18_0) expr11 = msat_make_plus(menv, xs[24], n_6_0) expr12 = msat_make_plus(menv, xs[25], n_13_0) expr13 = msat_make_plus(menv, xs[27], n_17_0) _t = msat_make_and(menv, msat_make_geq(menv, x_xs[9], expr0), msat_make_geq(menv, x_xs[9], expr1), msat_make_geq(menv, x_xs[9], expr2), msat_make_geq(menv, x_xs[9], expr3), msat_make_geq(menv, x_xs[9], expr4), msat_make_geq(menv, x_xs[9], expr5), msat_make_geq(menv, x_xs[9], expr6), msat_make_geq(menv, x_xs[9], expr7), msat_make_geq(menv, x_xs[9], expr8), msat_make_geq(menv, x_xs[9], expr9), msat_make_geq(menv, x_xs[9], expr10), msat_make_geq(menv, x_xs[9], expr11), msat_make_geq(menv, x_xs[9], expr12), msat_make_geq(menv, x_xs[9], expr13),) _t = msat_make_and(menv, _t, msat_make_or(menv, msat_make_equal(menv, x_xs[9], expr0), msat_make_equal(menv, x_xs[9], expr1), msat_make_equal(menv, x_xs[9], expr2), msat_make_equal(menv, x_xs[9], expr3), msat_make_equal(menv, x_xs[9], expr4), msat_make_equal(menv, x_xs[9], expr5), msat_make_equal(menv, x_xs[9], expr6), msat_make_equal(menv, x_xs[9], expr7), msat_make_equal(menv, x_xs[9], expr8), msat_make_equal(menv, x_xs[9], expr9), msat_make_equal(menv, x_xs[9], expr10), msat_make_equal(menv, x_xs[9], expr11), msat_make_equal(menv, x_xs[9], expr12), msat_make_equal(menv, x_xs[9], expr13),)) trans = msat_make_and(menv, trans, _t) expr0 = msat_make_plus(menv, xs[0], n_3_0) expr1 = msat_make_plus(menv, xs[1], n_14_0) expr2 = msat_make_plus(menv, xs[2], n_15_0) expr3 = msat_make_plus(menv, xs[3], n_2_0) expr4 = msat_make_plus(menv, xs[5], n_2_0) expr5 = msat_make_plus(menv, xs[6], n_3_0) expr6 = msat_make_plus(menv, xs[12], n_8_0) expr7 = msat_make_plus(menv, xs[13], n_17_0) expr8 = msat_make_plus(menv, xs[15], n_11_0) expr9 = msat_make_plus(menv, xs[16], n_7_0) expr10 = msat_make_plus(menv, xs[19], n_1_0) expr11 = msat_make_plus(menv, xs[20], n_3_0) expr12 = msat_make_plus(menv, xs[24], n_12_0) expr13 = msat_make_plus(menv, xs[27], n_11_0) _t = msat_make_and(menv, msat_make_geq(menv, x_xs[10], expr0), msat_make_geq(menv, x_xs[10], expr1), msat_make_geq(menv, x_xs[10], expr2), msat_make_geq(menv, x_xs[10], expr3), msat_make_geq(menv, x_xs[10], expr4), msat_make_geq(menv, x_xs[10], expr5), msat_make_geq(menv, x_xs[10], expr6), msat_make_geq(menv, x_xs[10], expr7), msat_make_geq(menv, x_xs[10], expr8), msat_make_geq(menv, x_xs[10], expr9), msat_make_geq(menv, x_xs[10], expr10), msat_make_geq(menv, x_xs[10], expr11), msat_make_geq(menv, x_xs[10], expr12), msat_make_geq(menv, x_xs[10], expr13),) _t = msat_make_and(menv, _t, msat_make_or(menv, msat_make_equal(menv, x_xs[10], expr0), msat_make_equal(menv, x_xs[10], expr1), msat_make_equal(menv, x_xs[10], expr2), msat_make_equal(menv, x_xs[10], expr3), msat_make_equal(menv, x_xs[10], expr4), msat_make_equal(menv, x_xs[10], expr5), msat_make_equal(menv, x_xs[10], expr6), msat_make_equal(menv, x_xs[10], expr7), msat_make_equal(menv, x_xs[10], expr8), msat_make_equal(menv, x_xs[10], expr9), msat_make_equal(menv, x_xs[10], expr10), msat_make_equal(menv, x_xs[10], expr11), msat_make_equal(menv, x_xs[10], expr12), msat_make_equal(menv, x_xs[10], expr13),)) trans = msat_make_and(menv, trans, _t) expr0 = msat_make_plus(menv, xs[0], n_16_0) expr1 = msat_make_plus(menv, xs[1], n_8_0) expr2 = msat_make_plus(menv, xs[5], n_17_0) expr3 = msat_make_plus(menv, xs[6], n_13_0) expr4 = msat_make_plus(menv, xs[9], n_3_0) expr5 = msat_make_plus(menv, xs[11], n_7_0) expr6 = msat_make_plus(menv, xs[12], n_13_0) expr7 = msat_make_plus(menv, xs[14], n_13_0) expr8 = msat_make_plus(menv, xs[15], n_18_0) expr9 = msat_make_plus(menv, xs[19], n_11_0) expr10 = msat_make_plus(menv, xs[21], n_10_0) expr11 = msat_make_plus(menv, xs[23], n_15_0) expr12 = msat_make_plus(menv, xs[24], n_18_0) expr13 = msat_make_plus(menv, xs[27], n_17_0) _t = msat_make_and(menv, msat_make_geq(menv, x_xs[11], expr0), msat_make_geq(menv, x_xs[11], expr1), msat_make_geq(menv, x_xs[11], expr2), msat_make_geq(menv, x_xs[11], expr3), msat_make_geq(menv, x_xs[11], expr4), msat_make_geq(menv, x_xs[11], expr5), msat_make_geq(menv, x_xs[11], expr6), msat_make_geq(menv, x_xs[11], expr7), msat_make_geq(menv, x_xs[11], expr8), msat_make_geq(menv, x_xs[11], expr9), msat_make_geq(menv, x_xs[11], expr10), msat_make_geq(menv, x_xs[11], expr11), msat_make_geq(menv, x_xs[11], expr12), msat_make_geq(menv, x_xs[11], expr13),) _t = msat_make_and(menv, _t, msat_make_or(menv, msat_make_equal(menv, x_xs[11], expr0), msat_make_equal(menv, x_xs[11], expr1), msat_make_equal(menv, x_xs[11], expr2), msat_make_equal(menv, x_xs[11], expr3), msat_make_equal(menv, x_xs[11], expr4), msat_make_equal(menv, x_xs[11], expr5), msat_make_equal(menv, x_xs[11], expr6), msat_make_equal(menv, x_xs[11], expr7), msat_make_equal(menv, x_xs[11], expr8), msat_make_equal(menv, x_xs[11], expr9), msat_make_equal(menv, x_xs[11], expr10), msat_make_equal(menv, x_xs[11], expr11), msat_make_equal(menv, x_xs[11], expr12), msat_make_equal(menv, x_xs[11], expr13),)) trans = msat_make_and(menv, trans, _t) expr0 = msat_make_plus(menv, xs[1], n_1_0) expr1 = msat_make_plus(menv, xs[2], n_19_0) expr2 = msat_make_plus(menv, xs[6], n_18_0) expr3 = msat_make_plus(menv, xs[7], n_14_0) expr4 = msat_make_plus(menv, xs[8], n_20_0) expr5 = msat_make_plus(menv, xs[11], n_5_0) expr6 = msat_make_plus(menv, xs[15], n_9_0) expr7 = msat_make_plus(menv, xs[18], n_19_0) expr8 = msat_make_plus(menv, xs[20], n_14_0) expr9 = msat_make_plus(menv, xs[21], n_18_0) expr10 = msat_make_plus(menv, xs[22], n_8_0) expr11 = msat_make_plus(menv, xs[23], n_13_0) expr12 = msat_make_plus(menv, xs[26], n_9_0) expr13 = msat_make_plus(menv, xs[27], n_10_0) _t = msat_make_and(menv, msat_make_geq(menv, x_xs[12], expr0), msat_make_geq(menv, x_xs[12], expr1), msat_make_geq(menv, x_xs[12], expr2), msat_make_geq(menv, x_xs[12], expr3), msat_make_geq(menv, x_xs[12], expr4), msat_make_geq(menv, x_xs[12], expr5), msat_make_geq(menv, x_xs[12], expr6), msat_make_geq(menv, x_xs[12], expr7), msat_make_geq(menv, x_xs[12], expr8), msat_make_geq(menv, x_xs[12], expr9), msat_make_geq(menv, x_xs[12], expr10), msat_make_geq(menv, x_xs[12], expr11), msat_make_geq(menv, x_xs[12], expr12), msat_make_geq(menv, x_xs[12], expr13),) _t = msat_make_and(menv, _t, msat_make_or(menv, msat_make_equal(menv, x_xs[12], expr0), msat_make_equal(menv, x_xs[12], expr1), msat_make_equal(menv, x_xs[12], expr2), msat_make_equal(menv, x_xs[12], expr3), msat_make_equal(menv, x_xs[12], expr4), msat_make_equal(menv, x_xs[12], expr5), msat_make_equal(menv, x_xs[12], expr6), msat_make_equal(menv, x_xs[12], expr7), msat_make_equal(menv, x_xs[12], expr8), msat_make_equal(menv, x_xs[12], expr9), msat_make_equal(menv, x_xs[12], expr10), msat_make_equal(menv, x_xs[12], expr11), msat_make_equal(menv, x_xs[12], expr12), msat_make_equal(menv, x_xs[12], expr13),)) trans = msat_make_and(menv, trans, _t) expr0 = msat_make_plus(menv, xs[0], n_8_0) expr1 = msat_make_plus(menv, xs[2], n_16_0) expr2 = msat_make_plus(menv, xs[3], n_16_0) expr3 = msat_make_plus(menv, xs[4], n_16_0) expr4 = msat_make_plus(menv, xs[7], n_7_0) expr5 = msat_make_plus(menv, xs[8], n_10_0) expr6 = msat_make_plus(menv, xs[9], n_9_0) expr7 = msat_make_plus(menv, xs[10], n_1_0) expr8 = msat_make_plus(menv, xs[11], n_20_0) expr9 = msat_make_plus(menv, xs[12], n_11_0) expr10 = msat_make_plus(menv, xs[13], n_16_0) expr11 = msat_make_plus(menv, xs[22], n_14_0) expr12 = msat_make_plus(menv, xs[23], n_15_0) expr13 = msat_make_plus(menv, xs[25], n_16_0) _t = msat_make_and(menv, msat_make_geq(menv, x_xs[13], expr0), msat_make_geq(menv, x_xs[13], expr1), msat_make_geq(menv, x_xs[13], expr2), msat_make_geq(menv, x_xs[13], expr3), msat_make_geq(menv, x_xs[13], expr4), msat_make_geq(menv, x_xs[13], expr5), msat_make_geq(menv, x_xs[13], expr6), msat_make_geq(menv, x_xs[13], expr7), msat_make_geq(menv, x_xs[13], expr8), msat_make_geq(menv, x_xs[13], expr9), msat_make_geq(menv, x_xs[13], expr10), msat_make_geq(menv, x_xs[13], expr11), msat_make_geq(menv, x_xs[13], expr12), msat_make_geq(menv, x_xs[13], expr13),) _t = msat_make_and(menv, _t, msat_make_or(menv, msat_make_equal(menv, x_xs[13], expr0), msat_make_equal(menv, x_xs[13], expr1), msat_make_equal(menv, x_xs[13], expr2), msat_make_equal(menv, x_xs[13], expr3), msat_make_equal(menv, x_xs[13], expr4), msat_make_equal(menv, x_xs[13], expr5), msat_make_equal(menv, x_xs[13], expr6), msat_make_equal(menv, x_xs[13], expr7), msat_make_equal(menv, x_xs[13], expr8), msat_make_equal(menv, x_xs[13], expr9), msat_make_equal(menv, x_xs[13], expr10), msat_make_equal(menv, x_xs[13], expr11), msat_make_equal(menv, x_xs[13], expr12), msat_make_equal(menv, x_xs[13], expr13),)) trans = msat_make_and(menv, trans, _t) expr0 = msat_make_plus(menv, xs[0], n_17_0) expr1 = msat_make_plus(menv, xs[1], n_2_0) expr2 = msat_make_plus(menv, xs[3], n_19_0) expr3 = msat_make_plus(menv, xs[6], n_15_0) expr4 = msat_make_plus(menv, xs[7], n_15_0) expr5 = msat_make_plus(menv, xs[10], n_18_0) expr6 = msat_make_plus(menv, xs[12], n_4_0) expr7 = msat_make_plus(menv, xs[14], n_20_0) expr8 = msat_make_plus(menv, xs[16], n_19_0) expr9 = msat_make_plus(menv, xs[18], n_4_0) expr10 = msat_make_plus(menv, xs[20], n_4_0) expr11 = msat_make_plus(menv, xs[21], n_20_0) expr12 = msat_make_plus(menv, xs[24], n_19_0) expr13 = msat_make_plus(menv, xs[27], n_6_0) _t = msat_make_and(menv, msat_make_geq(menv, x_xs[14], expr0), msat_make_geq(menv, x_xs[14], expr1), msat_make_geq(menv, x_xs[14], expr2), msat_make_geq(menv, x_xs[14], expr3), msat_make_geq(menv, x_xs[14], expr4), msat_make_geq(menv, x_xs[14], expr5), msat_make_geq(menv, x_xs[14], expr6), msat_make_geq(menv, x_xs[14], expr7), msat_make_geq(menv, x_xs[14], expr8), msat_make_geq(menv, x_xs[14], expr9), msat_make_geq(menv, x_xs[14], expr10), msat_make_geq(menv, x_xs[14], expr11), msat_make_geq(menv, x_xs[14], expr12), msat_make_geq(menv, x_xs[14], expr13),) _t = msat_make_and(menv, _t, msat_make_or(menv, msat_make_equal(menv, x_xs[14], expr0), msat_make_equal(menv, x_xs[14], expr1), msat_make_equal(menv, x_xs[14], expr2), msat_make_equal(menv, x_xs[14], expr3), msat_make_equal(menv, x_xs[14], expr4), msat_make_equal(menv, x_xs[14], expr5), msat_make_equal(menv, x_xs[14], expr6), msat_make_equal(menv, x_xs[14], expr7), msat_make_equal(menv, x_xs[14], expr8), msat_make_equal(menv, x_xs[14], expr9), msat_make_equal(menv, x_xs[14], expr10), msat_make_equal(menv, x_xs[14], expr11), msat_make_equal(menv, x_xs[14], expr12), msat_make_equal(menv, x_xs[14], expr13),)) trans = msat_make_and(menv, trans, _t) expr0 = msat_make_plus(menv, xs[0], n_19_0) expr1 = msat_make_plus(menv, xs[2], n_14_0) expr2 = msat_make_plus(menv, xs[4], n_9_0) expr3 = msat_make_plus(menv, xs[8], n_4_0) expr4 = msat_make_plus(menv, xs[9], n_7_0) expr5 = msat_make_plus(menv, xs[10], n_9_0) expr6 = msat_make_plus(menv, xs[13], n_7_0) expr7 = msat_make_plus(menv, xs[14], n_18_0) expr8 = msat_make_plus(menv, xs[16], n_6_0) expr9 = msat_make_plus(menv, xs[18], n_5_0) expr10 = msat_make_plus(menv, xs[20], n_8_0) expr11 = msat_make_plus(menv, xs[23], n_16_0) expr12 = msat_make_plus(menv, xs[25], n_4_0) expr13 = msat_make_plus(menv, xs[26], n_13_0) _t = msat_make_and(menv, msat_make_geq(menv, x_xs[15], expr0), msat_make_geq(menv, x_xs[15], expr1), msat_make_geq(menv, x_xs[15], expr2), msat_make_geq(menv, x_xs[15], expr3), msat_make_geq(menv, x_xs[15], expr4), msat_make_geq(menv, x_xs[15], expr5), msat_make_geq(menv, x_xs[15], expr6), msat_make_geq(menv, x_xs[15], expr7), msat_make_geq(menv, x_xs[15], expr8), msat_make_geq(menv, x_xs[15], expr9), msat_make_geq(menv, x_xs[15], expr10), msat_make_geq(menv, x_xs[15], expr11), msat_make_geq(menv, x_xs[15], expr12), msat_make_geq(menv, x_xs[15], expr13),) _t = msat_make_and(menv, _t, msat_make_or(menv, msat_make_equal(menv, x_xs[15], expr0), msat_make_equal(menv, x_xs[15], expr1), msat_make_equal(menv, x_xs[15], expr2), msat_make_equal(menv, x_xs[15], expr3), msat_make_equal(menv, x_xs[15], expr4), msat_make_equal(menv, x_xs[15], expr5), msat_make_equal(menv, x_xs[15], expr6), msat_make_equal(menv, x_xs[15], expr7), msat_make_equal(menv, x_xs[15], expr8), msat_make_equal(menv, x_xs[15], expr9), msat_make_equal(menv, x_xs[15], expr10), msat_make_equal(menv, x_xs[15], expr11), msat_make_equal(menv, x_xs[15], expr12), msat_make_equal(menv, x_xs[15], expr13),)) trans = msat_make_and(menv, trans, _t) expr0 = msat_make_plus(menv, xs[0], n_19_0) expr1 = msat_make_plus(menv, xs[1], n_11_0) expr2 = msat_make_plus(menv, xs[3], n_4_0) expr3 = msat_make_plus(menv, xs[4], n_15_0) expr4 = msat_make_plus(menv, xs[5], n_7_0) expr5 = msat_make_plus(menv, xs[11], n_11_0) expr6 = msat_make_plus(menv, xs[13], n_14_0) expr7 = msat_make_plus(menv, xs[16], n_11_0) expr8 = msat_make_plus(menv, xs[17], n_1_0) expr9 = msat_make_plus(menv, xs[18], n_13_0) expr10 = msat_make_plus(menv, xs[20], n_13_0) expr11 = msat_make_plus(menv, xs[21], n_5_0) expr12 = msat_make_plus(menv, xs[24], n_10_0) expr13 = msat_make_plus(menv, xs[27], n_19_0) _t = msat_make_and(menv, msat_make_geq(menv, x_xs[16], expr0), msat_make_geq(menv, x_xs[16], expr1), msat_make_geq(menv, x_xs[16], expr2), msat_make_geq(menv, x_xs[16], expr3), msat_make_geq(menv, x_xs[16], expr4), msat_make_geq(menv, x_xs[16], expr5), msat_make_geq(menv, x_xs[16], expr6), msat_make_geq(menv, x_xs[16], expr7), msat_make_geq(menv, x_xs[16], expr8), msat_make_geq(menv, x_xs[16], expr9), msat_make_geq(menv, x_xs[16], expr10), msat_make_geq(menv, x_xs[16], expr11), msat_make_geq(menv, x_xs[16], expr12), msat_make_geq(menv, x_xs[16], expr13),) _t = msat_make_and(menv, _t, msat_make_or(menv, msat_make_equal(menv, x_xs[16], expr0), msat_make_equal(menv, x_xs[16], expr1), msat_make_equal(menv, x_xs[16], expr2), msat_make_equal(menv, x_xs[16], expr3), msat_make_equal(menv, x_xs[16], expr4), msat_make_equal(menv, x_xs[16], expr5), msat_make_equal(menv, x_xs[16], expr6), msat_make_equal(menv, x_xs[16], expr7), msat_make_equal(menv, x_xs[16], expr8), msat_make_equal(menv, x_xs[16], expr9), msat_make_equal(menv, x_xs[16], expr10), msat_make_equal(menv, x_xs[16], expr11), msat_make_equal(menv, x_xs[16], expr12), msat_make_equal(menv, x_xs[16], expr13),)) trans = msat_make_and(menv, trans, _t) expr0 = msat_make_plus(menv, xs[6], n_8_0) expr1 = msat_make_plus(menv, xs[7], n_3_0) expr2 = msat_make_plus(menv, xs[8], n_15_0) expr3 = msat_make_plus(menv, xs[10], n_11_0) expr4 = msat_make_plus(menv, xs[12], n_11_0) expr5 = msat_make_plus(menv, xs[14], n_10_0) expr6 = msat_make_plus(menv, xs[15], n_13_0) expr7 = msat_make_plus(menv, xs[16], n_19_0) expr8 = msat_make_plus(menv, xs[17], n_8_0) expr9 = msat_make_plus(menv, xs[18], n_17_0) expr10 = msat_make_plus(menv, xs[21], n_20_0) expr11 = msat_make_plus(menv, xs[22], n_7_0) expr12 = msat_make_plus(menv, xs[25], n_17_0) expr13 = msat_make_plus(menv, xs[27], n_3_0) _t = msat_make_and(menv, msat_make_geq(menv, x_xs[17], expr0), msat_make_geq(menv, x_xs[17], expr1), msat_make_geq(menv, x_xs[17], expr2), msat_make_geq(menv, x_xs[17], expr3), msat_make_geq(menv, x_xs[17], expr4), msat_make_geq(menv, x_xs[17], expr5), msat_make_geq(menv, x_xs[17], expr6), msat_make_geq(menv, x_xs[17], expr7), msat_make_geq(menv, x_xs[17], expr8), msat_make_geq(menv, x_xs[17], expr9), msat_make_geq(menv, x_xs[17], expr10), msat_make_geq(menv, x_xs[17], expr11), msat_make_geq(menv, x_xs[17], expr12), msat_make_geq(menv, x_xs[17], expr13),) _t = msat_make_and(menv, _t, msat_make_or(menv, msat_make_equal(menv, x_xs[17], expr0), msat_make_equal(menv, x_xs[17], expr1), msat_make_equal(menv, x_xs[17], expr2), msat_make_equal(menv, x_xs[17], expr3), msat_make_equal(menv, x_xs[17], expr4), msat_make_equal(menv, x_xs[17], expr5), msat_make_equal(menv, x_xs[17], expr6), msat_make_equal(menv, x_xs[17], expr7), msat_make_equal(menv, x_xs[17], expr8), msat_make_equal(menv, x_xs[17], expr9), msat_make_equal(menv, x_xs[17], expr10), msat_make_equal(menv, x_xs[17], expr11), msat_make_equal(menv, x_xs[17], expr12), msat_make_equal(menv, x_xs[17], expr13),)) trans = msat_make_and(menv, trans, _t) expr0 = msat_make_plus(menv, xs[3], n_4_0) expr1 = msat_make_plus(menv, xs[4], n_10_0) expr2 = msat_make_plus(menv, xs[5], n_20_0) expr3 = msat_make_plus(menv, xs[8], n_10_0) expr4 = msat_make_plus(menv, xs[10], n_9_0) expr5 = msat_make_plus(menv, xs[13], n_1_0) expr6 = msat_make_plus(menv, xs[14], n_20_0) expr7 = msat_make_plus(menv, xs[15], n_7_0) expr8 = msat_make_plus(menv, xs[18], n_19_0) expr9 = msat_make_plus(menv, xs[22], n_2_0) expr10 = msat_make_plus(menv, xs[23], n_2_0) expr11 = msat_make_plus(menv, xs[24], n_3_0) expr12 = msat_make_plus(menv, xs[26], n_3_0) expr13 = msat_make_plus(menv, xs[27], n_9_0) _t = msat_make_and(menv, msat_make_geq(menv, x_xs[18], expr0), msat_make_geq(menv, x_xs[18], expr1), msat_make_geq(menv, x_xs[18], expr2), msat_make_geq(menv, x_xs[18], expr3), msat_make_geq(menv, x_xs[18], expr4), msat_make_geq(menv, x_xs[18], expr5), msat_make_geq(menv, x_xs[18], expr6), msat_make_geq(menv, x_xs[18], expr7), msat_make_geq(menv, x_xs[18], expr8), msat_make_geq(menv, x_xs[18], expr9), msat_make_geq(menv, x_xs[18], expr10), msat_make_geq(menv, x_xs[18], expr11), msat_make_geq(menv, x_xs[18], expr12), msat_make_geq(menv, x_xs[18], expr13),) _t = msat_make_and(menv, _t, msat_make_or(menv, msat_make_equal(menv, x_xs[18], expr0), msat_make_equal(menv, x_xs[18], expr1), msat_make_equal(menv, x_xs[18], expr2), msat_make_equal(menv, x_xs[18], expr3), msat_make_equal(menv, x_xs[18], expr4), msat_make_equal(menv, x_xs[18], expr5), msat_make_equal(menv, x_xs[18], expr6), msat_make_equal(menv, x_xs[18], expr7), msat_make_equal(menv, x_xs[18], expr8), msat_make_equal(menv, x_xs[18], expr9), msat_make_equal(menv, x_xs[18], expr10), msat_make_equal(menv, x_xs[18], expr11), msat_make_equal(menv, x_xs[18], expr12), msat_make_equal(menv, x_xs[18], expr13),)) trans = msat_make_and(menv, trans, _t) expr0 = msat_make_plus(menv, xs[2], n_18_0) expr1 = msat_make_plus(menv, xs[3], n_16_0) expr2 = msat_make_plus(menv, xs[4], n_9_0) expr3 = msat_make_plus(menv, xs[8], n_3_0) expr4 = msat_make_plus(menv, xs[9], n_6_0) expr5 = msat_make_plus(menv, xs[11], n_9_0) expr6 = msat_make_plus(menv, xs[12], n_3_0) expr7 = msat_make_plus(menv, xs[13], n_2_0) expr8 = msat_make_plus(menv, xs[21], n_4_0) expr9 = msat_make_plus(menv, xs[22], n_6_0) expr10 = msat_make_plus(menv, xs[23], n_1_0) expr11 = msat_make_plus(menv, xs[25], n_10_0) expr12 = msat_make_plus(menv, xs[26], n_7_0) expr13 = msat_make_plus(menv, xs[27], n_2_0) _t = msat_make_and(menv, msat_make_geq(menv, x_xs[19], expr0), msat_make_geq(menv, x_xs[19], expr1), msat_make_geq(menv, x_xs[19], expr2), msat_make_geq(menv, x_xs[19], expr3), msat_make_geq(menv, x_xs[19], expr4), msat_make_geq(menv, x_xs[19], expr5), msat_make_geq(menv, x_xs[19], expr6), msat_make_geq(menv, x_xs[19], expr7), msat_make_geq(menv, x_xs[19], expr8), msat_make_geq(menv, x_xs[19], expr9), msat_make_geq(menv, x_xs[19], expr10), msat_make_geq(menv, x_xs[19], expr11), msat_make_geq(menv, x_xs[19], expr12), msat_make_geq(menv, x_xs[19], expr13),) _t = msat_make_and(menv, _t, msat_make_or(menv, msat_make_equal(menv, x_xs[19], expr0), msat_make_equal(menv, x_xs[19], expr1), msat_make_equal(menv, x_xs[19], expr2), msat_make_equal(menv, x_xs[19], expr3), msat_make_equal(menv, x_xs[19], expr4), msat_make_equal(menv, x_xs[19], expr5), msat_make_equal(menv, x_xs[19], expr6), msat_make_equal(menv, x_xs[19], expr7), msat_make_equal(menv, x_xs[19], expr8), msat_make_equal(menv, x_xs[19], expr9), msat_make_equal(menv, x_xs[19], expr10), msat_make_equal(menv, x_xs[19], expr11), msat_make_equal(menv, x_xs[19], expr12), msat_make_equal(menv, x_xs[19], expr13),)) trans = msat_make_and(menv, trans, _t) expr0 = msat_make_plus(menv, xs[0], n_3_0) expr1 = msat_make_plus(menv, xs[1], n_13_0) expr2 = msat_make_plus(menv, xs[3], n_17_0) expr3 = msat_make_plus(menv, xs[7], n_8_0) expr4 = msat_make_plus(menv, xs[8], n_13_0) expr5 = msat_make_plus(menv, xs[10], n_4_0) expr6 = msat_make_plus(menv, xs[12], n_8_0) expr7 = msat_make_plus(menv, xs[14], n_17_0) expr8 = msat_make_plus(menv, xs[16], n_6_0) expr9 = msat_make_plus(menv, xs[17], n_6_0) expr10 = msat_make_plus(menv, xs[18], n_10_0) expr11 = msat_make_plus(menv, xs[22], n_1_0) expr12 = msat_make_plus(menv, xs[26], n_6_0) expr13 = msat_make_plus(menv, xs[27], n_11_0) _t = msat_make_and(menv, msat_make_geq(menv, x_xs[20], expr0), msat_make_geq(menv, x_xs[20], expr1), msat_make_geq(menv, x_xs[20], expr2), msat_make_geq(menv, x_xs[20], expr3), msat_make_geq(menv, x_xs[20], expr4), msat_make_geq(menv, x_xs[20], expr5), msat_make_geq(menv, x_xs[20], expr6), msat_make_geq(menv, x_xs[20], expr7), msat_make_geq(menv, x_xs[20], expr8), msat_make_geq(menv, x_xs[20], expr9), msat_make_geq(menv, x_xs[20], expr10), msat_make_geq(menv, x_xs[20], expr11), msat_make_geq(menv, x_xs[20], expr12), msat_make_geq(menv, x_xs[20], expr13),) _t = msat_make_and(menv, _t, msat_make_or(menv, msat_make_equal(menv, x_xs[20], expr0), msat_make_equal(menv, x_xs[20], expr1), msat_make_equal(menv, x_xs[20], expr2), msat_make_equal(menv, x_xs[20], expr3), msat_make_equal(menv, x_xs[20], expr4), msat_make_equal(menv, x_xs[20], expr5), msat_make_equal(menv, x_xs[20], expr6), msat_make_equal(menv, x_xs[20], expr7), msat_make_equal(menv, x_xs[20], expr8), msat_make_equal(menv, x_xs[20], expr9), msat_make_equal(menv, x_xs[20], expr10), msat_make_equal(menv, x_xs[20], expr11), msat_make_equal(menv, x_xs[20], expr12), msat_make_equal(menv, x_xs[20], expr13),)) trans = msat_make_and(menv, trans, _t) expr0 = msat_make_plus(menv, xs[0], n_19_0) expr1 = msat_make_plus(menv, xs[1], n_19_0) expr2 = msat_make_plus(menv, xs[2], n_14_0) expr3 = msat_make_plus(menv, xs[3], n_15_0) expr4 = msat_make_plus(menv, xs[6], n_10_0) expr5 = msat_make_plus(menv, xs[9], n_15_0) expr6 = msat_make_plus(menv, xs[10], n_6_0) expr7 = msat_make_plus(menv, xs[15], n_10_0) expr8 = msat_make_plus(menv, xs[19], n_8_0) expr9 = msat_make_plus(menv, xs[22], n_7_0) expr10 = msat_make_plus(menv, xs[23], n_19_0) expr11 = msat_make_plus(menv, xs[25], n_11_0) expr12 = msat_make_plus(menv, xs[26], n_9_0) expr13 = msat_make_plus(menv, xs[27], n_20_0) _t = msat_make_and(menv, msat_make_geq(menv, x_xs[21], expr0), msat_make_geq(menv, x_xs[21], expr1), msat_make_geq(menv, x_xs[21], expr2), msat_make_geq(menv, x_xs[21], expr3), msat_make_geq(menv, x_xs[21], expr4), msat_make_geq(menv, x_xs[21], expr5), msat_make_geq(menv, x_xs[21], expr6), msat_make_geq(menv, x_xs[21], expr7), msat_make_geq(menv, x_xs[21], expr8), msat_make_geq(menv, x_xs[21], expr9), msat_make_geq(menv, x_xs[21], expr10), msat_make_geq(menv, x_xs[21], expr11), msat_make_geq(menv, x_xs[21], expr12), msat_make_geq(menv, x_xs[21], expr13),) _t = msat_make_and(menv, _t, msat_make_or(menv, msat_make_equal(menv, x_xs[21], expr0), msat_make_equal(menv, x_xs[21], expr1), msat_make_equal(menv, x_xs[21], expr2), msat_make_equal(menv, x_xs[21], expr3), msat_make_equal(menv, x_xs[21], expr4), msat_make_equal(menv, x_xs[21], expr5), msat_make_equal(menv, x_xs[21], expr6), msat_make_equal(menv, x_xs[21], expr7), msat_make_equal(menv, x_xs[21], expr8), msat_make_equal(menv, x_xs[21], expr9), msat_make_equal(menv, x_xs[21], expr10), msat_make_equal(menv, x_xs[21], expr11), msat_make_equal(menv, x_xs[21], expr12), msat_make_equal(menv, x_xs[21], expr13),)) trans = msat_make_and(menv, trans, _t) expr0 = msat_make_plus(menv, xs[1], n_16_0) expr1 = msat_make_plus(menv, xs[2], n_10_0) expr2 = msat_make_plus(menv, xs[3], n_2_0) expr3 = msat_make_plus(menv, xs[6], n_9_0) expr4 = msat_make_plus(menv, xs[9], n_20_0) expr5 = msat_make_plus(menv, xs[10], n_19_0) expr6 = msat_make_plus(menv, xs[12], n_20_0) expr7 = msat_make_plus(menv, xs[16], n_1_0) expr8 = msat_make_plus(menv, xs[17], n_9_0) expr9 = msat_make_plus(menv, xs[20], n_10_0) expr10 = msat_make_plus(menv, xs[21], n_3_0) expr11 = msat_make_plus(menv, xs[23], n_3_0) expr12 = msat_make_plus(menv, xs[25], n_3_0) expr13 = msat_make_plus(menv, xs[26], n_7_0) _t = msat_make_and(menv, msat_make_geq(menv, x_xs[22], expr0), msat_make_geq(menv, x_xs[22], expr1), msat_make_geq(menv, x_xs[22], expr2), msat_make_geq(menv, x_xs[22], expr3), msat_make_geq(menv, x_xs[22], expr4), msat_make_geq(menv, x_xs[22], expr5), msat_make_geq(menv, x_xs[22], expr6), msat_make_geq(menv, x_xs[22], expr7), msat_make_geq(menv, x_xs[22], expr8), msat_make_geq(menv, x_xs[22], expr9), msat_make_geq(menv, x_xs[22], expr10), msat_make_geq(menv, x_xs[22], expr11), msat_make_geq(menv, x_xs[22], expr12), msat_make_geq(menv, x_xs[22], expr13),) _t = msat_make_and(menv, _t, msat_make_or(menv, msat_make_equal(menv, x_xs[22], expr0), msat_make_equal(menv, x_xs[22], expr1), msat_make_equal(menv, x_xs[22], expr2), msat_make_equal(menv, x_xs[22], expr3), msat_make_equal(menv, x_xs[22], expr4), msat_make_equal(menv, x_xs[22], expr5), msat_make_equal(menv, x_xs[22], expr6), msat_make_equal(menv, x_xs[22], expr7), msat_make_equal(menv, x_xs[22], expr8), msat_make_equal(menv, x_xs[22], expr9), msat_make_equal(menv, x_xs[22], expr10), msat_make_equal(menv, x_xs[22], expr11), msat_make_equal(menv, x_xs[22], expr12), msat_make_equal(menv, x_xs[22], expr13),)) trans = msat_make_and(menv, trans, _t) expr0 = msat_make_plus(menv, xs[0], n_5_0) expr1 = msat_make_plus(menv, xs[7], n_4_0) expr2 = msat_make_plus(menv, xs[8], n_13_0) expr3 = msat_make_plus(menv, xs[9], n_2_0) expr4 = msat_make_plus(menv, xs[10], n_4_0) expr5 = msat_make_plus(menv, xs[11], n_7_0) expr6 = msat_make_plus(menv, xs[12], n_15_0) expr7 = msat_make_plus(menv, xs[13], n_1_0) expr8 = msat_make_plus(menv, xs[15], n_14_0) expr9 = msat_make_plus(menv, xs[17], n_7_0) expr10 = msat_make_plus(menv, xs[20], n_9_0) expr11 = msat_make_plus(menv, xs[22], n_10_0) expr12 = msat_make_plus(menv, xs[23], n_5_0) expr13 = msat_make_plus(menv, xs[27], n_12_0) _t = msat_make_and(menv, msat_make_geq(menv, x_xs[23], expr0), msat_make_geq(menv, x_xs[23], expr1), msat_make_geq(menv, x_xs[23], expr2), msat_make_geq(menv, x_xs[23], expr3), msat_make_geq(menv, x_xs[23], expr4), msat_make_geq(menv, x_xs[23], expr5), msat_make_geq(menv, x_xs[23], expr6), msat_make_geq(menv, x_xs[23], expr7), msat_make_geq(menv, x_xs[23], expr8), msat_make_geq(menv, x_xs[23], expr9), msat_make_geq(menv, x_xs[23], expr10), msat_make_geq(menv, x_xs[23], expr11), msat_make_geq(menv, x_xs[23], expr12), msat_make_geq(menv, x_xs[23], expr13),) _t = msat_make_and(menv, _t, msat_make_or(menv, msat_make_equal(menv, x_xs[23], expr0), msat_make_equal(menv, x_xs[23], expr1), msat_make_equal(menv, x_xs[23], expr2), msat_make_equal(menv, x_xs[23], expr3), msat_make_equal(menv, x_xs[23], expr4), msat_make_equal(menv, x_xs[23], expr5), msat_make_equal(menv, x_xs[23], expr6), msat_make_equal(menv, x_xs[23], expr7), msat_make_equal(menv, x_xs[23], expr8), msat_make_equal(menv, x_xs[23], expr9), msat_make_equal(menv, x_xs[23], expr10), msat_make_equal(menv, x_xs[23], expr11), msat_make_equal(menv, x_xs[23], expr12), msat_make_equal(menv, x_xs[23], expr13),)) trans = msat_make_and(menv, trans, _t) expr0 = msat_make_plus(menv, xs[1], n_20_0) expr1 = msat_make_plus(menv, xs[3], n_6_0) expr2 = msat_make_plus(menv, xs[4], n_2_0) expr3 = msat_make_plus(menv, xs[5], n_1_0) expr4 = msat_make_plus(menv, xs[6], n_3_0) expr5 = msat_make_plus(menv, xs[7], n_14_0) expr6 = msat_make_plus(menv, xs[9], n_2_0) expr7 = msat_make_plus(menv, xs[10], n_3_0) expr8 = msat_make_plus(menv, xs[13], n_17_0) expr9 = msat_make_plus(menv, xs[14], n_2_0) expr10 = msat_make_plus(menv, xs[16], n_18_0) expr11 = msat_make_plus(menv, xs[22], n_3_0) expr12 = msat_make_plus(menv, xs[24], n_10_0) expr13 = msat_make_plus(menv, xs[25], n_2_0) _t = msat_make_and(menv, msat_make_geq(menv, x_xs[24], expr0), msat_make_geq(menv, x_xs[24], expr1), msat_make_geq(menv, x_xs[24], expr2), msat_make_geq(menv, x_xs[24], expr3), msat_make_geq(menv, x_xs[24], expr4), msat_make_geq(menv, x_xs[24], expr5), msat_make_geq(menv, x_xs[24], expr6), msat_make_geq(menv, x_xs[24], expr7), msat_make_geq(menv, x_xs[24], expr8), msat_make_geq(menv, x_xs[24], expr9), msat_make_geq(menv, x_xs[24], expr10), msat_make_geq(menv, x_xs[24], expr11), msat_make_geq(menv, x_xs[24], expr12), msat_make_geq(menv, x_xs[24], expr13),) _t = msat_make_and(menv, _t, msat_make_or(menv, msat_make_equal(menv, x_xs[24], expr0), msat_make_equal(menv, x_xs[24], expr1), msat_make_equal(menv, x_xs[24], expr2), msat_make_equal(menv, x_xs[24], expr3), msat_make_equal(menv, x_xs[24], expr4), msat_make_equal(menv, x_xs[24], expr5), msat_make_equal(menv, x_xs[24], expr6), msat_make_equal(menv, x_xs[24], expr7), msat_make_equal(menv, x_xs[24], expr8), msat_make_equal(menv, x_xs[24], expr9), msat_make_equal(menv, x_xs[24], expr10), msat_make_equal(menv, x_xs[24], expr11), msat_make_equal(menv, x_xs[24], expr12), msat_make_equal(menv, x_xs[24], expr13),)) trans = msat_make_and(menv, trans, _t) expr0 = msat_make_plus(menv, xs[0], n_6_0) expr1 = msat_make_plus(menv, xs[2], n_9_0) expr2 = msat_make_plus(menv, xs[6], n_17_0) expr3 = msat_make_plus(menv, xs[8], n_15_0) expr4 = msat_make_plus(menv, xs[9], n_15_0) expr5 = msat_make_plus(menv, xs[11], n_15_0) expr6 = msat_make_plus(menv, xs[12], n_18_0) expr7 = msat_make_plus(menv, xs[13], n_1_0) expr8 = msat_make_plus(menv, xs[16], n_17_0) expr9 = msat_make_plus(menv, xs[17], n_14_0) expr10 = msat_make_plus(menv, xs[20], n_6_0) expr11 = msat_make_plus(menv, xs[21], n_3_0) expr12 = msat_make_plus(menv, xs[24], n_13_0) expr13 = msat_make_plus(menv, xs[26], n_3_0) _t = msat_make_and(menv, msat_make_geq(menv, x_xs[25], expr0), msat_make_geq(menv, x_xs[25], expr1), msat_make_geq(menv, x_xs[25], expr2), msat_make_geq(menv, x_xs[25], expr3), msat_make_geq(menv, x_xs[25], expr4), msat_make_geq(menv, x_xs[25], expr5), msat_make_geq(menv, x_xs[25], expr6), msat_make_geq(menv, x_xs[25], expr7), msat_make_geq(menv, x_xs[25], expr8), msat_make_geq(menv, x_xs[25], expr9), msat_make_geq(menv, x_xs[25], expr10), msat_make_geq(menv, x_xs[25], expr11), msat_make_geq(menv, x_xs[25], expr12), msat_make_geq(menv, x_xs[25], expr13),) _t = msat_make_and(menv, _t, msat_make_or(menv, msat_make_equal(menv, x_xs[25], expr0), msat_make_equal(menv, x_xs[25], expr1), msat_make_equal(menv, x_xs[25], expr2), msat_make_equal(menv, x_xs[25], expr3), msat_make_equal(menv, x_xs[25], expr4), msat_make_equal(menv, x_xs[25], expr5), msat_make_equal(menv, x_xs[25], expr6), msat_make_equal(menv, x_xs[25], expr7), msat_make_equal(menv, x_xs[25], expr8), msat_make_equal(menv, x_xs[25], expr9), msat_make_equal(menv, x_xs[25], expr10), msat_make_equal(menv, x_xs[25], expr11), msat_make_equal(menv, x_xs[25], expr12), msat_make_equal(menv, x_xs[25], expr13),)) trans = msat_make_and(menv, trans, _t) expr0 = msat_make_plus(menv, xs[1], n_17_0) expr1 = msat_make_plus(menv, xs[2], n_19_0) expr2 = msat_make_plus(menv, xs[4], n_7_0) expr3 = msat_make_plus(menv, xs[8], n_16_0) expr4 = msat_make_plus(menv, xs[9], n_5_0) expr5 = msat_make_plus(menv, xs[14], n_16_0) expr6 = msat_make_plus(menv, xs[16], n_7_0) expr7 = msat_make_plus(menv, xs[18], n_10_0) expr8 = msat_make_plus(menv, xs[20], n_5_0) expr9 = msat_make_plus(menv, xs[21], n_7_0) expr10 = msat_make_plus(menv, xs[22], n_2_0) expr11 = msat_make_plus(menv, xs[24], n_20_0) expr12 = msat_make_plus(menv, xs[25], n_9_0) expr13 = msat_make_plus(menv, xs[27], n_15_0) _t = msat_make_and(menv, msat_make_geq(menv, x_xs[26], expr0), msat_make_geq(menv, x_xs[26], expr1), msat_make_geq(menv, x_xs[26], expr2), msat_make_geq(menv, x_xs[26], expr3), msat_make_geq(menv, x_xs[26], expr4), msat_make_geq(menv, x_xs[26], expr5), msat_make_geq(menv, x_xs[26], expr6), msat_make_geq(menv, x_xs[26], expr7), msat_make_geq(menv, x_xs[26], expr8), msat_make_geq(menv, x_xs[26], expr9), msat_make_geq(menv, x_xs[26], expr10), msat_make_geq(menv, x_xs[26], expr11), msat_make_geq(menv, x_xs[26], expr12), msat_make_geq(menv, x_xs[26], expr13),) _t = msat_make_and(menv, _t, msat_make_or(menv, msat_make_equal(menv, x_xs[26], expr0), msat_make_equal(menv, x_xs[26], expr1), msat_make_equal(menv, x_xs[26], expr2), msat_make_equal(menv, x_xs[26], expr3), msat_make_equal(menv, x_xs[26], expr4), msat_make_equal(menv, x_xs[26], expr5), msat_make_equal(menv, x_xs[26], expr6), msat_make_equal(menv, x_xs[26], expr7), msat_make_equal(menv, x_xs[26], expr8), msat_make_equal(menv, x_xs[26], expr9), msat_make_equal(menv, x_xs[26], expr10), msat_make_equal(menv, x_xs[26], expr11), msat_make_equal(menv, x_xs[26], expr12), msat_make_equal(menv, x_xs[26], expr13),)) trans = msat_make_and(menv, trans, _t) expr0 = msat_make_plus(menv, xs[0], n_2_0) expr1 = msat_make_plus(menv, xs[4], n_12_0) expr2 = msat_make_plus(menv, xs[5], n_6_0) expr3 = msat_make_plus(menv, xs[9], n_1_0) expr4 = msat_make_plus(menv, xs[10], n_16_0) expr5 = msat_make_plus(menv, xs[12], n_3_0) expr6 = msat_make_plus(menv, xs[14], n_13_0) expr7 = msat_make_plus(menv, xs[15], n_9_0) expr8 = msat_make_plus(menv, xs[17], n_8_0) expr9 = msat_make_plus(menv, xs[18], n_17_0) expr10 = msat_make_plus(menv, xs[19], n_12_0) expr11 = msat_make_plus(menv, xs[24], n_12_0) expr12 = msat_make_plus(menv, xs[25], n_16_0) expr13 = msat_make_plus(menv, xs[26], n_2_0) _t = msat_make_and(menv, msat_make_geq(menv, x_xs[27], expr0), msat_make_geq(menv, x_xs[27], expr1), msat_make_geq(menv, x_xs[27], expr2), msat_make_geq(menv, x_xs[27], expr3), msat_make_geq(menv, x_xs[27], expr4), msat_make_geq(menv, x_xs[27], expr5), msat_make_geq(menv, x_xs[27], expr6), msat_make_geq(menv, x_xs[27], expr7), msat_make_geq(menv, x_xs[27], expr8), msat_make_geq(menv, x_xs[27], expr9), msat_make_geq(menv, x_xs[27], expr10), msat_make_geq(menv, x_xs[27], expr11), msat_make_geq(menv, x_xs[27], expr12), msat_make_geq(menv, x_xs[27], expr13),) _t = msat_make_and(menv, _t, msat_make_or(menv, msat_make_equal(menv, x_xs[27], expr0), msat_make_equal(menv, x_xs[27], expr1), msat_make_equal(menv, x_xs[27], expr2), msat_make_equal(menv, x_xs[27], expr3), msat_make_equal(menv, x_xs[27], expr4), msat_make_equal(menv, x_xs[27], expr5), msat_make_equal(menv, x_xs[27], expr6), msat_make_equal(menv, x_xs[27], expr7), msat_make_equal(menv, x_xs[27], expr8), msat_make_equal(menv, x_xs[27], expr9), msat_make_equal(menv, x_xs[27], expr10), msat_make_equal(menv, x_xs[27], expr11), msat_make_equal(menv, x_xs[27], expr12), msat_make_equal(menv, x_xs[27], expr13),)) trans = msat_make_and(menv, trans, _t) # ltl property: (X ((G (x_7 - x_8 >= -10)) U (x_1 - x_12 > -8))) ltl = enc.make_X(enc.make_U(enc.make_G(msat_make_geq(menv, msat_make_minus(menv, xs[7], xs[8]), msat_make_number(menv, "-10"))), msat_make_gt(menv, msat_make_minus(menv, xs[1], xs[12]), msat_make_number(menv, "-8")))) return TermMap(curr2next), init, trans, ltl
[ "en.magnago@gmail.com" ]
en.magnago@gmail.com
902e51bf7e36d601a8ba585d3269eb982f6f8d7c
a38670ee08ea64af33477899a68ee22936f70ce7
/luffy/第三模块/第6章网络编程/第6章每小节/5 文件传输/优化/服务端.py
d8ea33a935f6021bdfff842963a99952f97a3b17
[]
no_license
foremostxiao/d
40ed37215f411e8b081a4cb92c8ecbd335cd9d76
fe80672adc6b2406365b05d5cedd02c6abf66c11
refs/heads/master
2020-03-29T13:51:19.589004
2018-09-23T09:29:56
2018-09-23T09:29:56
149,985,622
0
0
null
null
null
null
UTF-8
Python
false
false
2,991
py
import socket import subprocess import struct import json import os,sys BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(BASE_DIR) from db import settings def get(conn,cmds): filename = cmds[1] header_dic = { 'filename': filename, 'md5': 'xxdxxx', 'file_size': os.path.getsize(os.path.join(settings.path_server, filename)) } header_json = json.dumps(header_dic) header_bytes = header_json.encode('utf-8') # 第二步:先发送报头的长度 conn.send(struct.pack('i', len(header_bytes))) # len(header_bytes)发送信息给客户端的字节长度 # 第三步:再发报头 conn.send(header_bytes) # 客户端发两次 with open(os.path.join(settings.path_server, filename), 'rb') as f: for line in f: conn.send(line) def put(conn): obj = conn.recv(4) # 接收服务端传来的 struct.pack('i',len(header_bytes)) header_size = struct.unpack('i', obj)[0] # 解包--得到服务端传给客户端 header_dic字典字节的长度 # 第二步:再收报头 header_bytes = conn.recv(header_size) # header_size为上一步已经算好的字典字节长度 # header_bytes 为 接收客户端第二次发过来的header_dic字典转化的成的字节数据 # 第三步:从报头中解析出对真实数据的描述信息 header_json = header_bytes.decode('utf-8') # class---> str类型 header_dic = json.loads(header_json) # 反序列化 服务端原先的 字典 print(header_dic) total_size = header_dic['file_size'] # 服务端的执行后返回给客户端的字节流长度 # 第四步:接收真实的数据 filename = header_dic['filename'] with open(os.path.join(settings.path_server, filename), 'wb') as f: recv_size = 0 while recv_size < total_size: line = conn.recv(1024) # 1024是一个坑 f.write(line) recv_size += len(line) print(f'总大小{total_size},已下载{recv_size}') def run(): phone=socket.socket(socket.AF_INET,socket.SOCK_STREAM) # phone.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) phone.bind(('127.0.0.1',9909)) #0-65535:0-1024给操作系统使用 phone.listen(5) print('starting...') while True: # 链接循环 conn,client_addr=phone.accept() print(client_addr) while True: #通信循环 try: #1、收命令 res=conn.recv(8096) # b'get 3.jpeg' if not res:break #2、解析命令,提取相应的命令参数 cmds = res.decode('utf-8').split() if cmds[0] == 'get': get(conn,cmds) if cmds[0] == 'put': put(conn) except ConnectionResetError: #适用于windows操作系统 break conn.close() phone.close() if __name__ == '__main__': run()
[ "foremostxiao@163.com" ]
foremostxiao@163.com
f27edaccdc64a506e287adb8921ebb20260c7a50
e0c00b126aecd06e0b914a6134c8c14f647ad620
/comment/models.py
43376e0cb71cc865babafdbc205c54541d018c96
[]
no_license
ssk1987/MyBlog_django
e658eb29504968fdf5659f8befbb598d039e721e
12d9e38b5f1b1460f3525fb4a57a0a73ceac1435
refs/heads/master
2023-03-28T09:47:08.446446
2021-03-26T06:52:46
2021-03-26T06:52:46
351,415,646
0
0
null
null
null
null
UTF-8
Python
false
false
1,548
py
from django.db import models from django.contrib.auth.models import User from article.models import ArticlePost from mptt.models import MPTTModel, TreeForeignKey from ckeditor.fields import RichTextField # 文章评论 class Comment(MPTTModel): # 被评论的文章 article = models.ForeignKey(ArticlePost, on_delete=models.CASCADE, related_name='comments') # 评论的发布者 user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='comments') # body = models.TextField() body = RichTextField() created_time = models.DateTimeField(auto_now_add=True) # mptt 树形结构 parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') # 记录二级评论回复给谁 str reply_to = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE, related_name='replyers') class MPTTMeta: order_insertion_by = ['created_time'] def __str__(self): return self.body[:20] # class Comment(models.Model): # # 被评论的文章 # article = models.ForeignKey(ArticlePost,on_delete=models.CASCADE,related_name='comments') # # 评论的发布者 # user = models.ForeignKey(User,on_delete=models.CASCADE,related_name='comments') # body = models.TextField() # created_time = models.DateTimeField(auto_now_add=True) # # class Meta: # ordering = ('created_time',) # # def __str__(self): # return self.body[:20]
[ "10293665@qq.com" ]
10293665@qq.com
b9464425e45d62a6f92da84b5b394988caf0a5a1
0c01446c765b9765b1dd1e95dfd1915e61e5d16d
/run.py
6191de1ff540b604c8b4e4269fa1b126ea901f0d
[ "MIT" ]
permissive
saeedbeiraki/Second_Order_Parsing
3cf3ff75d62297236432d3efec895ee7f6e99c04
333c2dc5a72b2018f3e3331a232dfe3cd63f9a37
refs/heads/main
2022-12-29T15:22:16.908353
2020-10-22T09:15:57
2020-10-22T09:15:57
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,364
py
# -*- coding: utf-8 -*- import argparse import os from parser.cmds import Evaluate, Predict, Train from parser.config import Config import torch import pdb if __name__ == '__main__': parser = argparse.ArgumentParser( description='Create the Biaffine Parser model.' ) subparsers = parser.add_subparsers(title='Commands', dest='mode') subcommands = { 'evaluate': Evaluate(), 'predict': Predict(), 'train': Train() } for name, subcommand in subcommands.items(): subparser = subcommand.add_subparser(name, subparsers) subparser.add_argument('--conf', '-c', default='config.ini', help='path to config file') # subparser.add_argument('--file', '-f', default='exp/ptb', # help='path to saved files') # subparser.add_argument('--preprocess', '-p', action='store_true', # help='whether to preprocess the data first') # subparser.add_argument('--seed', '-s', default=1, type=int, # help='seed for generating random numbers') # subparser.add_argument('--threads', '-t', default=16, type=int, # help='max num of threads') # subparser.add_argument('--tree', action='store_true', # help='whether to ensure well-formedness') # subparser.add_argument('--feat', default='tag', # choices=['tag', 'char', 'bert'], # help='choices of additional features') args = parser.parse_args() # os.environ['CUDA_VISIBLE_DEVICES'] = args.device args.device = 'cuda' if torch.cuda.is_available() else 'cpu' print(f"Override the default configs with parsed arguments") args = Config(args.conf).update(vars(args)) print(f"Set the max num of threads to {args.threads}") print(f"Set the seed for generating random numbers to {args.seed}") # print(f"Set the device with ID {args.device} visible") torch.set_num_threads(args.threads) torch.manual_seed(args.seed) args.fields = os.path.join(args.file, 'fields') args.model = os.path.join(args.file, 'model') print(args) print(f"Run the subcommand in mode {args.mode}") cmd = subcommands[args.mode] cmd(args)
[ "wangxy1@shanghaitech.edu.cn" ]
wangxy1@shanghaitech.edu.cn
0f6336a4696e6bd762d1b4c51b39b6aaca2b9344
3eed647ca50411ce28072085e50aaf83ea792539
/config.py
1fb9b937ded6c83b3ff2ec66e7fd7142b35075df
[]
no_license
valhuber/ApiLogicServerProto
132dcd6064b63fe0d02cb40e9c58ae191a3674f1
5425bf518e4201b103c7c943e23f18434284e6c7
refs/heads/main
2023-03-02T03:16:17.226783
2021-01-26T18:07:59
2021-01-26T18:07:59
328,511,148
1
1
null
2021-01-26T15:24:43
2021-01-11T00:46:32
Python
UTF-8
Python
false
false
1,794
py
"""Flask configuration variables.""" from os import environ, path import util from dotenv import load_dotenv # for complete flask_sqlachemy config parameters,session handling, # read: file flask_sqlalchemy/__init__.py AND flask/config.py ''' app.config.setdefault('SQLALCHEMY_DATABASE_URI', 'sqlite:///:memory:') app.config.setdefault('SQLALCHEMY_BINDS', None) app.config.setdefault('SQLALCHEMY_NATIVE_UNICODE', None) app.config.setdefault('SQLALCHEMY_ECHO', False) app.config.setdefault('SQLALCHEMY_RECORD_QUERIES', None) app.config.setdefault('SQLALCHEMY_POOL_SIZE', None) app.config.setdefault('SQLALCHEMY_POOL_TIMEOUT', None) app.config.setdefault('SQLALCHEMY_POOL_RECYCLE', None) app.config.setdefault('SQLALCHEMY_MAX_OVERFLOW', None) app.config.setdefault('SQLALCHEMY_COMMIT_ON_TEARDOWN', False) ''' basedir = path.abspath(path.dirname(__file__)) load_dotenv(path.join(basedir, "default.env")) class Config: """Set Flask configuration from .env file.""" # General Config SECRET_KEY = environ.get("SECRET_KEY") FLASK_APP = environ.get("FLASK_APP") FLASK_ENV = environ.get("FLASK_ENV") DEBUG = environ.get("DEBUG") # Database # SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \ # 'sqlite:///' + os.path.join(basedir, 'app.db') + '?check_same_thread=False' SQLALCHEMY_DATABASE_URI = "replace_db_url" """ FIXME what is this if 'sqlite' in SQLALCHEMY_DATABASE_URI: util.log('Basedir: '+basedir) SQLALCHEMY_DATABASE_URI = "sqlite:///" + path.join(basedir, "database/db.sqlite")+ '?check_same_thread=False' """ util.log(SQLALCHEMY_DATABASE_URI) # SQLALCHEMY_ECHO = environ.get("SQLALCHEMY_ECHO") SQLALCHEMY_TRACK_MODIFICATIONS = False PROPAGATE_EXCEPTIONS = False
[ "valjhuber@gmail.com" ]
valjhuber@gmail.com
692f0ccbe03319a9173e638c8c084eaaaa48af69
96c6060e49418f87f49625fa2e141324aa809b5a
/setup.py
e2e56cba82e8fc128873f37e444afd18132ff835
[]
no_license
paulosjd/aqrecs
9e08dc79b74d24610bfc2c360f6fafd988ec38e7
3ea59811aabfb9b67431ab971e7cc9630cfea920
refs/heads/master
2020-12-10T00:18:06.044062
2020-03-15T22:41:00
2020-03-15T22:41:00
233,456,167
0
0
null
null
null
null
UTF-8
Python
false
false
1,468
py
import os from setuptools import setup, find_packages here = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(here, 'README.md')) as f: README = f.read() requires = [ 'plaster_pastedeploy', 'pyramid', 'pyramid_mako', 'pyramid_debugtoolbar', 'waitress', 'alembic', 'pyramid_retry', 'pyramid_tm', 'psycopg2', 'bs4', 'lxml', 'pytz', 'requests', 'Celery', 'redis', 'SQLAlchemy', 'transaction', 'zope.sqlalchemy', 'graphene-sqlalchemy' ] tests_require = [ 'WebTest >= 1.3.1', 'pytest >= 3.7.4', 'pytest-cov', ] setup( name='aqrecs', version='1.3', description='aqrecs', long_description=README, classifiers=[ 'Programming Language :: Python', 'Framework :: Pyramid', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Internet :: WWW/HTTP :: WSGI :: Application', ], author='', author_email='', url='', keywords='web pyramid pylons', packages=find_packages(), include_package_data=True, zip_safe=False, extras_require={ 'testing': tests_require, }, install_requires=requires, entry_points={ 'paste.app_factory': [ 'main = aqrecs:main', ], 'console_scripts': [ 'initialize_aqrecs_db=aqrecs.scripts.initialize_db:main', 'aurn_hourly_create=aqrecs.scripts.aurn_hourly_create:main', ], }, )
[ "pjdavis@gmx.com" ]
pjdavis@gmx.com
2740018dd7730df6381dd6898796dac5699a78f5
a7d41aa056165fc33b0c1d8edd50b8557f642548
/Python/Map-1/map_ab3.py
b30e1d8ec495be592f788fc466020d41a6bd6c6e
[]
no_license
jemtca/CodingBat
3243ec9c5309f8581e1a54fba0b076069cec7d74
8545a70348dd621070c8b3efa280ca79a24f9d5a
refs/heads/master
2023-04-05T03:20:17.416495
2023-03-31T06:35:08
2023-03-31T06:35:08
147,287,514
0
0
null
null
null
null
UTF-8
Python
false
false
460
py
# modify and return the given map as follows: if exactly one of the keys "a" or "b" has a value in the map (but not both), set the other to have that same value in the map def map_ab3(d): if 'a' in d and not 'b' in d: d['b'] = d['a'] elif not 'a' in d and 'b' in d: d['a'] = d['b'] return d print(map_ab3({'a': 'aaa', 'c': 'cake'})) print(map_ab3({'b': 'bbb', 'c': 'cake'})) print(map_ab3({'a': 'aaa', 'b': 'bbb', 'c': 'cake'}))
[ "30645648+jemtca@users.noreply.github.com" ]
30645648+jemtca@users.noreply.github.com
6c5086766388009f89ca4345eeff2ece6a1c74b4
4e62fcb385d9e8a6af0c6c9ec315f803d6ea190b
/testsuite/modulegraph-dir/package/submod.py
b112d56513f15007d3381465df24169829b90d7b
[ "MIT" ]
permissive
ronaldoussoren/modulegraph2
8d8a18b472574acc158c5c293ae4ed7b88f06ba9
227954f5037e291edc91e666f21bda44fd66fcb2
refs/heads/master
2023-09-01T05:16:44.873049
2023-04-09T10:28:19
2023-04-09T10:28:19
231,953,118
12
7
MIT
2023-04-09T10:29:06
2020-01-05T17:36:35
C
UTF-8
Python
false
false
33
py
""" submod """ import no_imports
[ "ronaldoussoren@mac.com" ]
ronaldoussoren@mac.com
3ab1275b9cc38744553596af5a248053d6f0c3cc
e83e8a3b7ef31b36b2c590b37bf2d1df1487fe5a
/ninja/security/apikey.py
ef210d43560322ac2c455bd8552c365eca0a3299
[ "MIT" ]
permissive
duilio/django-ninja
19d66eae1b3b01f9910f3ea0f569ed6d3a561707
8dac3c981bcf431322d32acd34c8179564a3698d
refs/heads/master
2023-01-21T07:17:02.544071
2020-11-25T10:48:30
2020-11-25T10:48:30
316,243,580
0
0
MIT
2020-11-26T13:56:19
2020-11-26T13:45:12
null
UTF-8
Python
false
false
981
py
from ninja.security.base import AuthBase from ninja.compatibility.request import get_headers class APIKeyBase(AuthBase): openapi_type = "apiKey" param_name = "key" def __init__(self): self.openapi_name = self.param_name super().__init__() def __call__(self, request): key = self._get_key(request) return self.authenticate(request, key) def authenticate(self, request, key): raise NotImplementedError("Please implement authenticate(self, request, key)") class APIKeyQuery(APIKeyBase): openapi_in = "query" def _get_key(self, request): return request.GET.get(self.param_name) class APIKeyCookie(APIKeyBase): openapi_in = "cookie" def _get_key(self, request): return request.COOKIES.get(self.param_name) class APIKeyHeader(APIKeyBase): openapi_in = "header" def _get_key(self, request): headers = get_headers(request) return headers.get(self.param_name)
[ "ppr.vitaly@gmail.com" ]
ppr.vitaly@gmail.com
8dfd73233628b2b4e5705f550dd176e3c4993a6f
fd1612fb542fede6899c3f69ff124e7b2335ad95
/list/views.py
15db2a2bde30f4d531e2cf5ac7e5e847feec1fd7
[]
no_license
Shovon588/toDoList
821a7163caa6d6abb4c7f8e6ecea34e6249b1b87
bf037097a37734a106c959729c05d9beb0f503e6
refs/heads/master
2021-09-25T08:07:45.355541
2020-04-19T05:18:23
2020-04-19T05:18:23
231,726,869
0
0
null
2021-09-22T18:52:30
2020-01-04T07:37:16
JavaScript
UTF-8
Python
false
false
2,062
py
from django.shortcuts import render from list.models import Item, UserIP from django.http import HttpResponseRedirect from django.urls import reverse from django.contrib import messages from datetime import datetime # Create your views here. def index(request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') user = UserIP.objects.get_or_create(ip=ip)[0] items = Item.objects.filter(user=user).order_by('done', 'time') context = {'data': items} if request.method=='POST': item = request.POST.get("item") Item.objects.create(user=user, item=item) return HttpResponseRedirect(reverse('list:index')) return render(request, 'index.html', context=context) def update(request, pk): data = Item.objects.get(id=pk) if request.method == 'POST': item = request.POST.get('item') data.item = item data.save() messages.success(request, 'Updated Successfully!') return HttpResponseRedirect(reverse('list:index')) context = {'data': data} return render(request, 'update.html', context=context) def delete(request, pk): item = Item.objects.get(id=pk) context = {'item': item} if request.method == 'POST': if request.POST.get('yes'): item.delete() messages.success(request, 'Item Successfully Deleted!') return HttpResponseRedirect(reverse('list:index')) return render(request, 'delete.html', context=context) def mark(request, pk): item = Item.objects.get(id=pk) context = {'item': item} if request.method == 'POST': if request.POST.get('yes'): item.done=True item.save() else: item.done = False item.save() messages.success(request, 'Marker Updated!') return HttpResponseRedirect(reverse('list:index')) return render(request, 'mark.html', context=context)
[ "mainulislam588@gmail.com" ]
mainulislam588@gmail.com
83f5415c5e682e0e5c90fe418860953455cc7050
cebe89b09271deb0dfff1baa5e1beb8b5a4f95c4
/pycurve/parser.py
d74028c6b2e9ddaec1f1845561fc620f793867bb
[ "Apache-2.0" ]
permissive
thatch45/curve
1ff3bcd8f961e25cf6d6f38a6c509c287d98eb82
2684733ad2de51e0a0c78a46d99ae4442f879e87
refs/heads/master
2020-05-29T21:49:37.110085
2013-12-12T05:38:46
2013-12-12T05:38:46
null
0
0
null
null
null
null
UTF-8
Python
false
false
997
py
''' Parse command line options ''' import optparse def parse(): ''' Parse options for a server ''' parser = optparse.OptionParser() parser.add_option( '--server-ip', dest='server_ip', default='127.0.0.1', help='the server ip') parser.add_option( '--server-port', dest='server_port', default=4510, type='int', help='the server port') parser.add_option( '--ret-ip', dest='ret_ip', default='127.0.0.1', help='the ret ip') parser.add_option( '--ret-port', dest='ret_port', default=4511, type='int', help='the ret port') parser.add_option( '-m', '--message', dest='message', default='foo', help='The message to send') options, args = parser.parse_args() return options.__dict__
[ "thatch45@gmail.com" ]
thatch45@gmail.com
47c7333bc96d80de441ad9dfc8c33af56bea3437
03f32cdb30e6a44decd529f9112a6459c655b1ef
/2_FormNetAndSomeStatics/createnet.py
bcedbee39a9a6babce8a0838f2967829f15e8837
[]
no_license
curryli/AntiLanudry-Python
ee693480e0c62dc0795bd9b76499149cdec7a83a
4d69d911be5cea6aa30f6aeb263644614808cea2
refs/heads/master
2021-01-11T01:47:24.384978
2016-12-14T07:04:32
2016-12-14T07:04:32
70,667,232
0
0
null
null
null
null
UTF-8
Python
false
false
1,179
py
import sys import re import os def GetInOut(filein,fileout): r = re.compile('\s') with open(filein,'r') as FILEIN: with open(fileout,'w') as FILEOUT: for line in FILEIN.readlines(): ItemList = r.split(line) #in, out, money, location, date print>>FILEOUT,ItemList[0],ItemList[1] def createNet(filein,fileout): bset = set() r = re.compile('\s') with open(filein,'r') as FILEIN: for line in FILEIN.readlines(): ItemList = r.split(line) ItemPair = (ItemList[0], ItemList[1]) if ItemPair not in bset: bset.add(ItemPair) with open(fileout,'w') as FILEOUT: for x in bset: print>>FILEOUT,x[0]," ",x[1] if __name__ == '__main__': GetInOut('MappedInOut.txt','GetInOut.txt') createNet('GetInOut.txt','Net.txt')
[ "xurui.lee@msn.com" ]
xurui.lee@msn.com
cfeb943a74dbd748829d195b83c317c63c5c287f
d838bed08a00114c92b73982a74d96c15166a49e
/docs/data/learn/Bioinformatics/input/ch3_code/src/Stepik.3.10.CodeChallenge.GenerateContigsFromReads.py
9dac465815b57c2cd32dbeb1129b39899c5e4a18
[]
no_license
offbynull/offbynull.github.io
4911f53d77f6c59e7a453ee271b1e04e613862bc
754a85f43159738b89dd2bde1ad6ba0d75f34b98
refs/heads/master
2023-07-04T00:39:50.013571
2023-06-17T20:27:05
2023-06-17T23:27:00
308,482,936
1
0
null
null
null
null
UTF-8
Python
false
false
610
py
from FindContigs import find_maximal_non_branching_paths from Read import Read from ToDeBruijnGraph import to_debruijn_graph with open('/home/user/Downloads/dataset_240263_5.txt', mode='r', encoding='utf-8') as f: data = f.read() lines = data.split('\n') kmers = lines[:] kmers = [l.strip() for l in kmers] # get rid of whitespace kmers = [l for l in kmers if len(l) > 0] # get rid of empty lines reads = [Read(kmer) for kmer in kmers] graph = to_debruijn_graph(reads) contigs = find_maximal_non_branching_paths(graph) for contig in contigs: output = contig[0].stitch(contig) print(f'{output}')
[ "offbynull@gmail.com" ]
offbynull@gmail.com
cc46f4e6f27650f01b8dfc036fb07f4c738cc912
dc95dfb24f3cd12b823dfad2cca8607ab12e757b
/11-Lists-Mutation/Coding Exercises/while_testing.py
8fe180696ca79d5a7fb264b089e7bd7d79518111
[]
no_license
RandyG3/Python
06213a361deac2d653d4cd4734728838ed34e733
86068d81ae037beb6fd6114d93074a92c2f3108e
refs/heads/master
2023-01-06T15:18:43.173886
2020-11-08T03:03:34
2020-11-08T03:03:34
236,549,506
0
0
null
null
null
null
UTF-8
Python
false
false
171
py
def delete_all(strings, target): i = 0 while target in strings: strings.remove(target) i += 1 return strings print(delete_all([4, 4, 4], 4))
[ "40631249+RandyG3@users.noreply.github.com" ]
40631249+RandyG3@users.noreply.github.com
611565744823e16f64e1d21191a903a2c6a5d301
1f70e6c069074d848347cfb6674b1376a323aae2
/rich/rich_traceback.py
382f4424c6aad7f1c1e5e4e2547c69242b9adeed
[]
no_license
TalentBoy2333/python_study
5b3bf172a4bb04bd0ee05c24af7a223470ff78ca
703d2ff4d9fe18c9c5b801c3784e5e8f0845a3a7
refs/heads/master
2023-05-25T15:27:22.315664
2021-06-14T08:16:50
2021-06-14T08:16:50
357,243,974
0
0
null
null
null
null
UTF-8
Python
false
false
111
py
from rich.console import Console console = Console() try: a = 1 / 0 except: console.print_exception()
[ "957498562@qq.com" ]
957498562@qq.com
e10707058cbb09229792c940f0b0188728ca2335
c39f999cae8825afe2cdf1518d93ba31bd4c0e95
/PYME/ParallelTasks/taskQueue.py
c486b62becb2b78e8edbd235be56dd08794665e8
[]
no_license
WilliamRo/CLipPYME
0b69860136a9b2533f2f29fc29408d7471cb934d
6596167034c727ad7dad0a741dd59e0e48f6852a
refs/heads/master
2023-05-11T09:50:58.605989
2023-05-09T02:17:47
2023-05-09T02:17:47
60,789,741
3
1
null
2016-06-17T08:52:44
2016-06-09T16:30:14
Python
UTF-8
Python
false
false
5,659
py
#!/usr/bin/python ################## # taskQueue.py # # Copyright David Baddeley, 2009 # d.baddeley@auckland.ac.nz # # 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/>. # ################## import time import threading CHUNKSIZE = 50 def doNix(taskQueue): #do nothing pass def popZero(workerN, NWorkers, NTasks): #give worker oldest task irrespective of which worker called return 0 class TaskQueue: def __init__(self, name, initialTasks=[], onEmpty = doNix, fTaskToPop = popZero): #Pyro.core.ObjBase.__init__(self) #self.name = name self.queueID = name self.openTasks = list(initialTasks) self.closedTasks = [] self.tasksInProgress = [] self.onEmpty = onEmpty #function to call when queue is empty self.fTaskToPop = fTaskToPop #function to call to decide which task to give a worker (useful if the workers need to have share information with, e.g., previous tasks as this can improve eficiency of per worker buffering of said info). self.inProgressLock = threading.Lock() def postTask(self,task): self.openTasks.append(task) #print '[%s] - Recieved new task' % self.queueID def postTasks(self,tasks): self.openTasks += tasks #print '[%s] - Recieved %d new tasks' % (self.queueID, len(tasks)) def getTask(self, workerN = 0, NWorkers = 1): """get task from front of list, blocks""" #print 'Task requested' while len(self.openTasks) < 1: time.sleep(0.01) task = self.openTasks.pop(self.fTaskToPop(workerN, NWorkers, len(self.openTasks))) task.queueID = self.queueID task.initializeWorkerTimeout(time.clock()) with self.inProgressLock: self.tasksInProgress.append(task) #print '[%s] - Task given to worker' % self.queueID return task def getTasks(self, workerN = 0, NWorkers = 1): return [self.getTask(workerN, NWorkers) for i in range(min(CHUNKSIZE,len(self.openTasks)))] def returnCompletedTask(self, taskResult): with self.inProgressLock: for it in self.tasksInProgress[:]: if (it.taskID == taskResult.taskID): self.tasksInProgress.remove(it) self.fileResult(taskResult) if (len(self.openTasks) + len(self.tasksInProgress)) == 0: #no more tasks self.onEmpty(self) def returnCompletedTasks(self, taskResults): with self.inProgressLock: for taskResult in taskResults: for it in self.tasksInProgress[:]: if (it.taskID == taskResult.taskID): self.tasksInProgress.remove(it) #for taskResult in taskResults: #allow this to be over-ridden self.fileResults(taskResults) if (len(self.openTasks) + len(self.tasksInProgress)) == 0: #no more tasks self.onEmpty(self) def fileResults(self, taskResults): #allow this to be over-ridden in derived classes to file multiple results at once for taskResult in taskResults: self.fileResult(taskResult) def fileResult(self,taskResult): self.closedTasks.append(taskResult) def getCompletedTask(self): if len(self.closedTasks) < 1: return None else: return self.closedTasks.pop(0) def checkTimeouts(self): with self.inProgressLock: curTime = time.clock() for it in self.tasksInProgress: if 'workerTimeout' in dir(it): if curTime > it.workerTimeout: self.openTasks.insert(0, it) self.tasksInProgress.remove(it) def getNumberOpenTasks(self, exact=True): return len(self.openTasks) def getNumberTasksInProgress(self): return len(self.tasksInProgress) def getNumberTasksCompleted(self): return len(self.closedTasks) def cleanup(self): pass def purge(self): self.openTasks = [] self.closedTasks = [] self.tasksInProgress = [] def setPopFcn(self, fcn): ''' sets the function which determines which task to give a worker''' self.fTaskToPop = fcn class TaskQueueWithData(TaskQueue): def __init__(self, name, initialTasks=[], onEmpty = doNix, fTaskToPop = popZero): TaskQueue.__init__(self, name, initialTasks, onEmpty, fTaskToPop) self.data = {} def getTasks(self, workerN = 0, NWorkers = 1): return [self.getTask(workerN, NWorkers)] def getQueueData(self, fieldName, *args): '''Get data, defined by fieldName and potntially additional arguments, ascociated with queue''' return self.data[fieldName] def setQueueData(self, fieldName, value): '''Get data, defined by fieldName and potntially additional arguments, ascociated with queue''' self.data[fieldName] = value
[ "willi4m@zju.edu.cn" ]
willi4m@zju.edu.cn
3804ffbc4338cf88a60d5ae74c2722e1a81e2149
09dd58f46b1e914278067a69142230c7af0165c2
/blackmamba/lib/rope/base/fscommands.py
3564ed919c9cfb40b50806b43940c8f8240d4135
[ "MIT" ]
permissive
zrzka/blackmamba
4e70262fbe3702553bf5d285a81b33eb6b3025ea
b298bc5d59e5aea9d494282910faf522c08ebba9
refs/heads/master
2021-01-01T18:43:19.490953
2020-01-20T08:26:33
2020-01-20T08:26:33
98,410,391
72
12
MIT
2020-01-20T08:26:35
2017-07-26T10:21:15
Python
UTF-8
Python
false
false
7,983
py
"""Project file system commands. This modules implements file system operations used by rope. Different version control systems can be supported by implementing the interface provided by `FileSystemCommands` class. See `SubversionCommands` and `MercurialCommands` for example. """ import os import shutil import subprocess import rope.base.utils.pycompat as pycompat try: unicode except NameError: unicode = str def create_fscommands(root): dirlist = os.listdir(root) commands = {'.hg': MercurialCommands, '.svn': SubversionCommands, '.git': GITCommands, '_svn': SubversionCommands, '_darcs': DarcsCommands} for key in commands: if key in dirlist: try: return commands[key](root) except (ImportError, OSError): pass return FileSystemCommands() class FileSystemCommands(object): def create_file(self, path): open(path, 'w').close() def create_folder(self, path): os.mkdir(path) def move(self, path, new_location): shutil.move(path, new_location) def remove(self, path): if os.path.isfile(path): os.remove(path) else: shutil.rmtree(path) def write(self, path, data): file_ = open(path, 'wb') try: file_.write(data) finally: file_.close() class SubversionCommands(object): def __init__(self, *args): self.normal_actions = FileSystemCommands() import pysvn self.client = pysvn.Client() def create_file(self, path): self.normal_actions.create_file(path) self.client.add(path, force=True) def create_folder(self, path): self.normal_actions.create_folder(path) self.client.add(path, force=True) def move(self, path, new_location): self.client.move(path, new_location, force=True) def remove(self, path): self.client.remove(path, force=True) def write(self, path, data): self.normal_actions.write(path, data) class MercurialCommands(object): def __init__(self, root): self.hg = self._import_mercurial() self.normal_actions = FileSystemCommands() try: self.ui = self.hg.ui.ui( verbose=False, debug=False, quiet=True, interactive=False, traceback=False, report_untrusted=False) except: self.ui = self.hg.ui.ui() self.ui.setconfig('ui', 'interactive', 'no') self.ui.setconfig('ui', 'debug', 'no') self.ui.setconfig('ui', 'traceback', 'no') self.ui.setconfig('ui', 'verbose', 'no') self.ui.setconfig('ui', 'report_untrusted', 'no') self.ui.setconfig('ui', 'quiet', 'yes') self.repo = self.hg.hg.repository(self.ui, root) def _import_mercurial(self): import mercurial.commands import mercurial.hg import mercurial.ui return mercurial def create_file(self, path): self.normal_actions.create_file(path) self.hg.commands.add(self.ui, self.repo, path) def create_folder(self, path): self.normal_actions.create_folder(path) def move(self, path, new_location): self.hg.commands.rename(self.ui, self.repo, path, new_location, after=False) def remove(self, path): self.hg.commands.remove(self.ui, self.repo, path) def write(self, path, data): self.normal_actions.write(path, data) class GITCommands(object): def __init__(self, root): self.root = root self._do(['version']) self.normal_actions = FileSystemCommands() def create_file(self, path): self.normal_actions.create_file(path) self._do(['add', self._in_dir(path)]) def create_folder(self, path): self.normal_actions.create_folder(path) def move(self, path, new_location): self._do(['mv', self._in_dir(path), self._in_dir(new_location)]) def remove(self, path): self._do(['rm', self._in_dir(path)]) def write(self, path, data): # XXX: should we use ``git add``? self.normal_actions.write(path, data) def _do(self, args): _execute(['git'] + args, cwd=self.root) def _in_dir(self, path): if path.startswith(self.root): return path[len(self.root) + 1:] return self.root class DarcsCommands(object): def __init__(self, root): self.root = root self.normal_actions = FileSystemCommands() def create_file(self, path): self.normal_actions.create_file(path) self._do(['add', path]) def create_folder(self, path): self.normal_actions.create_folder(path) self._do(['add', path]) def move(self, path, new_location): self._do(['mv', path, new_location]) def remove(self, path): self.normal_actions.remove(path) def write(self, path, data): self.normal_actions.write(path, data) def _do(self, args): _execute(['darcs'] + args, cwd=self.root) def _execute(args, cwd=None): process = subprocess.Popen(args, cwd=cwd, stdout=subprocess.PIPE) process.wait() return process.returncode def unicode_to_file_data(contents, encoding=None): if not isinstance(contents, unicode): return contents if encoding is None: encoding = read_str_coding(contents) if encoding is not None: return contents.encode(encoding) try: return contents.encode() except UnicodeEncodeError: return contents.encode('utf-8') def file_data_to_unicode(data, encoding=None): result = _decode_data(data, encoding) if '\r' in result: result = result.replace('\r\n', '\n').replace('\r', '\n') return result def _decode_data(data, encoding): if isinstance(data, unicode): return data if encoding is None: encoding = read_str_coding(data) if encoding is None: # there is no encoding tip, we need to guess. # PEP263 says that "encoding not explicitly defined" means it is ascii, # but we will use utf8 instead since utf8 fully covers ascii and btw is # the only non-latin sane encoding. encoding = 'utf-8' try: return data.decode(encoding) except (UnicodeError, LookupError): # fallback to latin1: it should never fail return data.decode('latin1') def read_file_coding(path): file = open(path, 'b') count = 0 result = [] while True: current = file.read(10) if not current: break count += current.count('\n') result.append(current) file.close() return _find_coding(''.join(result)) def read_str_coding(source): if type(source) == bytes: newline = b'\n' else: newline = '\n' #try: # source = source.decode("utf-8") #except AttributeError: # pass try: first = source.index(newline) + 1 second = source.index(newline, first) + 1 except ValueError: second = len(source) return _find_coding(source[:second]) def _find_coding(text): if isinstance(text, pycompat.str): text = text.encode('utf-8') coding = b'coding' to_chr = chr if pycompat.PY3 else lambda x: x try: start = text.index(coding) + len(coding) if text[start] not in b'=:': return start += 1 while start < len(text) and to_chr(text[start]).isspace(): start += 1 end = start while end < len(text): c = text[end] if not to_chr(c).isalnum() and c not in b'-_': break end += 1 result = text[start:end] if isinstance(result, bytes): result = result.decode('utf-8') return result except ValueError: pass
[ "rvojta@me.com" ]
rvojta@me.com
7b2ae68ab7f1b7179ab667418b5826b4e8620bf4
1577e1cf4e89584a125cffb855ca50a9654c6d55
/pyobjc/pyobjc/pyobjc-framework-Quartz-2.5.1/Lib/Quartz/ImageKit/_metadata.py
aa46f15bceb55acf5c17fc448bf22a1d7c140bdd
[ "MIT" ]
permissive
apple-open-source/macos
a4188b5c2ef113d90281d03cd1b14e5ee52ebffb
2d2b15f13487673de33297e49f00ef94af743a9a
refs/heads/master
2023-08-01T11:03:26.870408
2023-03-27T00:00:00
2023-03-27T00:00:00
180,595,052
124
24
null
2022-12-27T14:54:09
2019-04-10T14:06:23
null
UTF-8
Python
false
false
21,281
py
# This file is generated by objective.metadata # # Last update: Fri Jun 8 16:58:05 2012 import objc, sys if sys.maxsize > 2 ** 32: def sel32or64(a, b): return b else: def sel32or64(a, b): return a if sys.byteorder == 'little': def littleOrBig(a, b): return a else: def littleOrBig(a, b): return b misc = { } constants = '''$IKFilterBrowserDefaultInputImage$IKFilterBrowserExcludeCategories$IKFilterBrowserExcludeFilters$IKFilterBrowserFilterDoubleClickNotification$IKFilterBrowserFilterSelectedNotification$IKFilterBrowserShowCategories$IKFilterBrowserShowPreview$IKFilterBrowserWillPreviewFilterNotification$IKImageBrowserBackgroundColorKey$IKImageBrowserCGImageRepresentationType$IKImageBrowserCGImageSourceRepresentationType$IKImageBrowserCellBackgroundLayer$IKImageBrowserCellForegroundLayer$IKImageBrowserCellLayerTypeBackground$IKImageBrowserCellLayerTypeForeground$IKImageBrowserCellLayerTypePlaceHolder$IKImageBrowserCellLayerTypeSelection$IKImageBrowserCellPlaceHolderLayer$IKImageBrowserCellSelectionLayer$IKImageBrowserCellsHighlightedTitleAttributesKey$IKImageBrowserCellsOutlineColorKey$IKImageBrowserCellsSubtitleAttributesKey$IKImageBrowserCellsTitleAttributesKey$IKImageBrowserGroupBackgroundColorKey$IKImageBrowserGroupFooterLayer$IKImageBrowserGroupHeaderLayer$IKImageBrowserGroupRangeKey$IKImageBrowserGroupStyleKey$IKImageBrowserGroupTitleKey$IKImageBrowserIconRefPathRepresentationType$IKImageBrowserIconRefRepresentationType$IKImageBrowserNSBitmapImageRepresentationType$IKImageBrowserNSDataRepresentationType$IKImageBrowserNSImageRepresentationType$IKImageBrowserNSURLRepresentationType$IKImageBrowserPDFPageRepresentationType$IKImageBrowserPathRepresentationType$IKImageBrowserQCCompositionPathRepresentationType$IKImageBrowserQCCompositionRepresentationType$IKImageBrowserQTMoviePathRepresentationType$IKImageBrowserQTMovieRepresentationType$IKImageBrowserQuickLookPathRepresentationType$IKImageBrowserSelectionColorKey$IKOverlayTypeBackground$IKOverlayTypeImage$IKPictureTakerAllowsEditingKey$IKPictureTakerAllowsFileChoosingKey$IKPictureTakerAllowsVideoCaptureKey$IKPictureTakerCropAreaSizeKey$IKPictureTakerImageTransformsKey$IKPictureTakerInformationalTextKey$IKPictureTakerOutputImageMaxSizeKey$IKPictureTakerRemainOpenAfterValidateKey$IKPictureTakerShowAddressBookPicture$IKPictureTakerShowAddressBookPictureKey$IKPictureTakerShowEffectsKey$IKPictureTakerShowEmptyPicture$IKPictureTakerShowEmptyPictureKey$IKPictureTakerShowRecentPictureKey$IKPictureTakerUpdateRecentPictureKey$IKSlideshowAudioFile$IKSlideshowModeImages$IKSlideshowModeOther$IKSlideshowModePDF$IKSlideshowPDFDisplayBox$IKSlideshowPDFDisplayMode$IKSlideshowPDFDisplaysAsBook$IKSlideshowScreen$IKSlideshowStartIndex$IKSlideshowStartPaused$IKSlideshowWrapAround$IKToolModeAnnotate$IKToolModeCrop$IKToolModeMove$IKToolModeNone$IKToolModeRotate$IKToolModeSelect$IKToolModeSelectEllipse$IKToolModeSelectLasso$IKToolModeSelectRect$IKUIFlavorAllowFallback$IKUISizeFlavor$IKUISizeMini$IKUISizeRegular$IKUISizeSmall$IKUImaxSize$IK_ApertureBundleIdentifier$IK_MailBundleIdentifier$IK_iPhotoBundleIdentifier$''' enums = '''$IKCameraDeviceViewDisplayModeIcon@1$IKCameraDeviceViewDisplayModeTable@0$IKCameraDeviceViewTransferModeFileBased@0$IKCameraDeviceViewTransferModeMemoryBased@1$IKCellsStyleNone@0$IKCellsStyleOutlined@2$IKCellsStyleShadowed@1$IKCellsStyleSubtitled@8$IKCellsStyleTitled@4$IKDeviceBrowserViewDisplayModeIcon@2$IKDeviceBrowserViewDisplayModeOutline@1$IKDeviceBrowserViewDisplayModeTable@0$IKGroupBezelStyle@0$IKGroupDisclosureStyle@1$IKImageBrowserDropBefore@1$IKImageBrowserDropOn@0$IKImageStateInvalid@1$IKImageStateNoImage@0$IKImageStateReady@2$IKScannerDeviceViewDisplayModeAdvanced@1$IKScannerDeviceViewDisplayModeSimple@0$IKScannerDeviceViewTransferModeFileBased@0$IKScannerDeviceViewTransferModeMemoryBased@1$''' misc.update({}) aliases = {'IKImagePickerShowEffectsKey': 'IKPictureTakerShowEffectsKey', 'IKImagePickerOutputImageMaxSizeKey': 'IKPictureTakerOutputImageMaxSizeKey', 'IKImagePickerImageTransformsKey': 'IKPictureTakerImageTransformsKey', 'IKImagePickerAllowsFileChoosingKey': 'IKPictureTakerAllowsFileChoosingKey', 'IKImagePickerAllowsEditingKey': 'IKPictureTakerAllowsEditingKey', 'IKImagePickerInformationalTextKey': 'IKPictureTakerInformationalTextKey', 'IKImagePickerCropAreaSizeKey': 'IKPictureTakerCropAreaSizeKey', 'IKImagePickerAllowsVideoCaptureKey': 'IKPictureTakerAllowsVideoCaptureKey', 'IKImagePickerUpdateRecentPictureKey': 'IKPictureTakerUpdateRecentPictureKey', 'IKImagePickerShowRecentPictureKey': 'IKPictureTakerShowRecentPictureKey'} r = objc.registerMetaDataForSelector objc._updatingMetadata(True) try: r(b'IKCameraDeviceView', b'canDeleteSelectedItems', {'retval': {'type': b'Z'}}) r(b'IKCameraDeviceView', b'canDownloadSelectedItems', {'retval': {'type': b'Z'}}) r(b'IKCameraDeviceView', b'canRotateSelectedItemsLeft', {'retval': {'type': b'Z'}}) r(b'IKCameraDeviceView', b'canRotateSelectedItemsRight', {'retval': {'type': b'Z'}}) r(b'IKCameraDeviceView', b'displaysDownloadsDirectoryControl', {'retval': {'type': b'Z'}}) r(b'IKCameraDeviceView', b'displaysPostProcessApplicationControl', {'retval': {'type': b'Z'}}) r(b'IKCameraDeviceView', b'hasDisplayModeIcon', {'retval': {'type': b'Z'}}) r(b'IKCameraDeviceView', b'hasDisplayModeTable', {'retval': {'type': b'Z'}}) r(b'IKCameraDeviceView', b'selectIndexes:byExtendingSelection:', {'arguments': {3: {'type': b'Z'}}}) r(b'IKCameraDeviceView', b'setDisplaysDownloadsDirectoryControl:', {'arguments': {2: {'type': b'Z'}}}) r(b'IKCameraDeviceView', b'setDisplaysPostProcessApplicationControl:', {'arguments': {2: {'type': b'Z'}}}) r(b'IKCameraDeviceView', b'setHasDisplayModeIcon:', {'arguments': {2: {'type': b'Z'}}}) r(b'IKCameraDeviceView', b'setHasDisplayModeTable:', {'arguments': {2: {'type': b'Z'}}}) r(b'IKDeviceBrowserView', b'displaysLocalCameras', {'retval': {'type': b'Z'}}) r(b'IKDeviceBrowserView', b'displaysLocalScanners', {'retval': {'type': b'Z'}}) r(b'IKDeviceBrowserView', b'displaysNetworkCameras', {'retval': {'type': b'Z'}}) r(b'IKDeviceBrowserView', b'displaysNetworkScanners', {'retval': {'type': b'Z'}}) r(b'IKDeviceBrowserView', b'setDisplaysLocalCameras:', {'arguments': {2: {'type': b'Z'}}}) r(b'IKDeviceBrowserView', b'setDisplaysLocalScanners:', {'arguments': {2: {'type': b'Z'}}}) r(b'IKDeviceBrowserView', b'setDisplaysNetworkCameras:', {'arguments': {2: {'type': b'Z'}}}) r(b'IKDeviceBrowserView', b'setDisplaysNetworkScanners:', {'arguments': {2: {'type': b'Z'}}}) r(b'IKFilterBrowserPanel', b'beginSheetWithOptions:modalForWindow:modalDelegate:didEndSelector:contextInfo:', {'arguments': {5: {'sel_of_type': sel32or64(b'v@:@i^v', b'v@:@q^v')}}}) r(b'IKFilterBrowserPanel', b'beginWithOptions:modelessDelegate:didEndSelector:contextInfo:', {'arguments': {4: {'sel_of_type': sel32or64(b'v@:@i^v', b'v@:@q^v')}}}) r(b'IKFilterBrowserView', b'setPreviewState:', {'arguments': {2: {'type': b'Z'}}}) r(b'IKImageBrowserCell', b'isSelected', {'retval': {'type': b'Z'}}) r(b'IKImageBrowserView', b'allowsDroppingOnItems', {'retval': {'type': b'Z'}}) r(b'IKImageBrowserView', b'allowsEmptySelection', {'retval': {'type': b'Z'}}) r(b'IKImageBrowserView', b'allowsMultipleSelection', {'retval': {'type': b'Z'}}) r(b'IKImageBrowserView', b'allowsReordering', {'retval': {'type': b'Z'}}) r(b'IKImageBrowserView', b'animates', {'retval': {'type': b'Z'}}) r(b'IKImageBrowserView', b'canControlQuickLookPanel', {'retval': {'type': b'Z'}}) r(b'IKImageBrowserView', b'constrainsToOriginalSize', {'retval': {'type': b'Z'}}) r(b'IKImageBrowserView', b'isGroupExpandedAtIndex:', {'retval': {'type': b'Z'}}) r(b'IKImageBrowserView', b'setAllowsDroppingOnItems:', {'arguments': {2: {'type': b'Z'}}}) r(b'IKImageBrowserView', b'setAllowsEmptySelection:', {'arguments': {2: {'type': b'Z'}}}) r(b'IKImageBrowserView', b'setAllowsMultipleSelection:', {'arguments': {2: {'type': b'Z'}}}) r(b'IKImageBrowserView', b'setAllowsReordering:', {'arguments': {2: {'type': b'Z'}}}) r(b'IKImageBrowserView', b'setAnimates:', {'arguments': {2: {'type': b'Z'}}}) r(b'IKImageBrowserView', b'setCanControlQuickLookPanel:', {'arguments': {2: {'type': b'Z'}}}) r(b'IKImageBrowserView', b'setConstrainsToOriginalSize:', {'arguments': {2: {'type': b'Z'}}}) r(b'IKImageBrowserView', b'setSelectionIndexes:byExtendingSelection:', {'arguments': {3: {'type': b'Z'}}}) r(b'IKImagePicker', b'beginImagePickerSheetForWindow:withDelegate:didEndSelector:contextInfo:', {'arguments': {4: {'sel_of_type': sel32or64(b'v@:@I^v', b'v@:@Q^v')}}}) r(b'IKImagePicker', b'beginImagePickerWithDelegate:didEndSelector:contextInfo:', {'arguments': {3: {'sel_of_type': sel32or64(b'v@:@I^v', b'v@:@Q^v')}}}) r(b'IKImageView', b'autohidesScrollers', {'retval': {'type': b'Z'}}) r(b'IKImageView', b'autoresizes', {'retval': {'type': b'Z'}}) r(b'IKImageView', b'doubleClickOpensImageEditPanel', {'retval': {'type': b'Z'}}) r(b'IKImageView', b'editable', {'retval': {'type': b'Z'}}) r(b'IKImageView', b'hasHorizontalScroller', {'retval': {'type': b'Z'}}) r(b'IKImageView', b'hasVerticalScroller', {'retval': {'type': b'Z'}}) r(b'IKImageView', b'setAutohidesScrollers:', {'arguments': {2: {'type': b'Z'}}}) r(b'IKImageView', b'setAutoresizes:', {'arguments': {2: {'type': b'Z'}}}) r(b'IKImageView', b'setDoubleClickOpensImageEditPanel:', {'arguments': {2: {'type': b'Z'}}}) r(b'IKImageView', b'setEditable:', {'arguments': {2: {'type': b'Z'}}}) r(b'IKImageView', b'setHasHorizontalScroller:', {'arguments': {2: {'type': b'Z'}}}) r(b'IKImageView', b'setHasVerticalScroller:', {'arguments': {2: {'type': b'Z'}}}) r(b'IKImageView', b'setSupportsDragAndDrop:', {'arguments': {2: {'type': b'Z'}}}) r(b'IKImageView', b'supportsDragAndDrop', {'retval': {'type': b'Z'}}) r(b'IKPictureTaker', b'beginPictureTakerSheetForWindow:withDelegate:didEndSelector:contextInfo:', {'arguments': {4: {'sel_of_type': sel32or64(b'v@:@i^v', b'v@:@q^v')}}}) r(b'IKPictureTaker', b'beginPictureTakerWithDelegate:didEndSelector:contextInfo:', {'arguments': {3: {'sel_of_type': sel32or64(b'v@:@i^v', b'v@:@q^v')}}}) r(b'IKPictureTaker', b'mirroring', {'retval': {'type': b'Z'}}) r(b'IKPictureTaker', b'popUpRecentsMenuForView:withDelegate:didEndSelector:contextInfo:', {'arguments': {4: {'sel_of_type': sel32or64(b'v@:@i^v', b'v@:@q^v')}}}) r(b'IKPictureTaker', b'setMirroring:', {'arguments': {2: {'type': b'Z'}}}) r(b'IKScannerDeviceView', b'displaysDownloadsDirectoryControl', {'retval': {'type': b'Z'}}) r(b'IKScannerDeviceView', b'displaysPostProcessApplicationControl', {'retval': {'type': b'Z'}}) r(b'IKScannerDeviceView', b'hasDisplayModeAdvanced', {'retval': {'type': b'Z'}}) r(b'IKScannerDeviceView', b'hasDisplayModeSimple', {'retval': {'type': b'Z'}}) r(b'IKScannerDeviceView', b'setDisplaysDownloadsDirectoryControl:', {'arguments': {2: {'type': b'Z'}}}) r(b'IKScannerDeviceView', b'setDisplaysPostProcessApplicationControl:', {'arguments': {2: {'type': b'Z'}}}) r(b'IKScannerDeviceView', b'setHasDisplayModeAdvanced:', {'arguments': {2: {'type': b'Z'}}}) r(b'IKScannerDeviceView', b'setHasDisplayModeSimple:', {'arguments': {2: {'type': b'Z'}}}) r(b'IKSlideshow', b'canExportToApplication:', {'retval': {'type': b'Z'}}) r(b'NSObject', b'imageBrowser:moveCellsAtIndexes:toIndex:', {'retval': {'type': b'Z'}}) r(b'NSObject', b'imageBrowser:moveItemsAtIndexes:toIndex:', {'retval': {'type': b'Z'}}) r(b'NSObject', b'isSelectable', {'retval': {'type': b'Z'}}) r(b'NSObject', b'saveOptions:shouldShowUTType:', {'retval': {'type': b'Z'}}) finally: objc._updatingMetadata(False) r = objc.registerMetaDataForSelector objc._updatingMetadata(True) try: r(b'NSObject', b'cameraDeviceView:didDownloadFile:location:fileData:error:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': b'@'}, 5: {'type': b'@'}, 6: {'type': b'@'}}}) r(b'NSObject', b'cameraDeviceView:didEncounterError:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}}) r(b'NSObject', b'cameraDeviceViewSelectionDidChange:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}}) r(b'NSObject', b'canExportSlideshowItemAtIndex:toApplication:', {'required': False, 'retval': {'type': b'Z'}, 'arguments': {2: {'type': sel32or64(b'I', b'L')}, 3: {'type': b'@'}}}) r(b'NSObject', b'deviceBrowserView:didEncounterError:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}}) r(b'NSObject', b'deviceBrowserView:selectionDidChange:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}}) r(b'NSObject', b'hasAdjustMode', {'required': False, 'retval': {'type': b'Z'}}) r(b'NSObject', b'hasDetailsMode', {'required': False, 'retval': {'type': b'Z'}}) r(b'NSObject', b'hasEffectsMode', {'required': False, 'retval': {'type': b'Z'}}) r(b'NSObject', b'image', {'required': True, 'retval': {'type': b'^{CGImage=}'}}) r(b'NSObject', b'imageProperties', {'required': False, 'retval': {'type': b'@'}}) r(b'NSObject', b'nameOfSlideshowItemAtIndex:', {'required': False, 'retval': {'type': b'@'}, 'arguments': {2: {'type': sel32or64(b'I', b'L')}}}) r(b'NSObject', b'numberOfSlideshowItems', {'required': True, 'retval': {'type': sel32or64(b'I', b'L')}}) r(b'NSObject', b'provideViewForUIConfiguration:excludedKeys:', {'required': True, 'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}}) r(b'NSObject', b'scannerDeviceView:didEncounterError:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}}) r(b'NSObject', b'scannerDeviceView:didScanToBandData:scanInfo:error:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': b'@'}, 5: {'type': b'@'}}}) r(b'NSObject', b'scannerDeviceView:didScanToURL:error:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': b'@'}}}) r(b'NSObject', b'scannerDeviceView:didScanToURL:fileData:error:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': b'@'}, 5: {'type': b'@'}}}) r(b'NSObject', b'setImage:imageProperties:', {'required': True, 'retval': {'type': b'v'}, 'arguments': {2: {'type': b'^{CGImage=}'}, 3: {'type': b'@'}}}) r(b'NSObject', b'slideshowDidChangeCurrentIndex:', {'required': False, 'retval': {'type': b'v'}, 'arguments': {2: {'type': sel32or64(b'I', b'L')}}}) r(b'NSObject', b'slideshowDidStop', {'required': False, 'retval': {'type': b'v'}}) r(b'NSObject', b'slideshowItemAtIndex:', {'required': True, 'retval': {'type': b'@'}, 'arguments': {2: {'type': sel32or64(b'I', b'L')}}}) r(b'NSObject', b'slideshowWillStart', {'required': False, 'retval': {'type': b'v'}}) r(b'NSObject', b'thumbnailWithMaximumSize:', {'required': False, 'retval': {'type': b'^{CGImage=}'}, 'arguments': {2: {'type': sel32or64(b'{_NSSize=ff}', b'{CGSize=dd}')}}}) finally: objc._updatingMetadata(False) r = objc.registerMetaDataForSelector objc._updatingMetadata(True) try: r(b'NSObject', b'imageBrowser:backgroundWasRightClickedWithEvent:', {'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}}) r(b'NSObject', b'imageBrowser:cellAtIndex:', {'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'I', b'L')}}}) r(b'NSObject', b'imageBrowser:cellWasDoubleClickedAtIndex:', {'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'I', b'L')}}}) r(b'NSObject', b'imageBrowser:cellWasRightClickedAtIndex:withEvent:', {'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'I', b'L')}, 4: {'type': b'@'}}}) r(b'NSObject', b'imageBrowser:groupAtIndex:', {'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'I', b'L')}}}) r(b'NSObject', b'imageBrowser:itemAtIndex:', {'retval': {'type': b'@'}, 'arguments': {2: {'type': b'@'}, 3: {'type': sel32or64(b'I', b'L')}}}) r(b'NSObject', b'imageBrowser:moveCellsAtIndexes:toIndex:', {'retval': {'type': b'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': sel32or64(b'I', b'L')}}}) r(b'NSObject', b'imageBrowser:moveItemsAtIndexes:toIndex:', {'retval': {'type': b'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': sel32or64(b'I', b'L')}}}) r(b'NSObject', b'imageBrowser:removeCellsAtIndexes:', {'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}}) r(b'NSObject', b'imageBrowser:removeItemsAtIndexes:', {'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}}) r(b'NSObject', b'imageBrowser:writeCellsAtIndexes:toPasteboard:', {'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': b'@'}}}) r(b'NSObject', b'imageBrowser:writeItemsAtIndexes:toPasteboard:', {'retval': {'type': sel32or64(b'I', b'L')}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}, 4: {'type': b'@'}}}) r(b'NSObject', b'imageBrowserSelectionDidChange:', {'retval': {'type': b'v'}, 'arguments': {2: {'type': b'@'}}}) r(b'NSObject', b'imageRepresentation', {'retval': {'type': b'@'}}) r(b'NSObject', b'imageRepresentationType', {'retval': {'type': b'@'}}) r(b'NSObject', b'imageSubtitle', {'retval': {'type': b'@'}}) r(b'NSObject', b'imageTitle', {'retval': {'type': b'@'}}) r(b'NSObject', b'imageUID', {'retval': {'type': b'@'}}) r(b'NSObject', b'imageVersion', {'retval': {'type': sel32or64(b'I', b'L')}}) r(b'NSObject', b'isSelectable', {'retval': {'type': b'Z'}}) r(b'NSObject', b'numberOfCellsInImageBrowser:', {'retval': {'type': sel32or64(b'I', b'L')}, 'arguments': {2: {'type': b'@'}}}) r(b'NSObject', b'numberOfGroupsInImageBrowser:', {'retval': {'type': sel32or64(b'I', b'L')}, 'arguments': {2: {'type': b'@'}}}) r(b'NSObject', b'numberOfItemsInImageBrowser:', {'retval': {'type': sel32or64(b'I', b'L')}, 'arguments': {2: {'type': b'@'}}}) r(b'NSObject', b'saveOptions:shouldShowUTType:', {'retval': {'type': b'Z'}, 'arguments': {2: {'type': b'@'}, 3: {'type': b'@'}}}) finally: objc._updatingMetadata(False) protocols={'IKImageBrowserItem': objc.informal_protocol('IKImageBrowserItem', [objc.selector(None, b'imageTitle', b'@@:', isRequired=False), objc.selector(None, b'imageSubtitle', b'@@:', isRequired=False), objc.selector(None, b'imageRepresentationType', b'@@:', isRequired=False), objc.selector(None, b'imageUID', b'@@:', isRequired=False), objc.selector(None, b'isSelectable', b'Z@:', isRequired=False), objc.selector(None, b'imageVersion', sel32or64(b'I@:', b'L@:'), isRequired=False), objc.selector(None, b'imageRepresentation', b'@@:', isRequired=False)]), 'IKImageBrowserDataSourceDeprecated': objc.informal_protocol('IKImageBrowserDataSourceDeprecated', [objc.selector(None, b'imageBrowser:moveCellsAtIndexes:toIndex:', sel32or64(b'Z@:@@I', b'Z@:@@L'), isRequired=False), objc.selector(None, b'imageBrowser:cellAtIndex:', sel32or64(b'@@:@I', b'@@:@L'), isRequired=False), objc.selector(None, b'numberOfCellsInImageBrowser:', sel32or64(b'I@:@', b'L@:@'), isRequired=False), objc.selector(None, b'imageBrowser:writeCellsAtIndexes:toPasteboard:', b'v@:@@@', isRequired=False), objc.selector(None, b'imageBrowser:removeCellsAtIndexes:', b'v@:@@', isRequired=False)]), 'IKSaveOptionsDelegate': objc.informal_protocol('IKSaveOptionsDelegate', [objc.selector(None, b'saveOptions:shouldShowUTType:', b'Z@:@@', isRequired=False)]), 'IKImageBrowserDelegate': objc.informal_protocol('IKImageBrowserDelegate', [objc.selector(None, b'imageBrowser:cellWasRightClickedAtIndex:withEvent:', sel32or64(b'v@:@I@', b'v@:@L@'), isRequired=False), objc.selector(None, b'imageBrowserSelectionDidChange:', b'v@:@', isRequired=False), objc.selector(None, b'imageBrowser:cellWasDoubleClickedAtIndex:', sel32or64(b'v@:@I', b'v@:@L'), isRequired=False), objc.selector(None, b'imageBrowser:backgroundWasRightClickedWithEvent:', b'v@:@@', isRequired=False)]), 'IKImageBrowserDataSource': objc.informal_protocol('IKImageBrowserDataSource', [objc.selector(None, b'imageBrowser:groupAtIndex:', sel32or64(b'@@:@I', b'@@:@L'), isRequired=False), objc.selector(None, b'numberOfItemsInImageBrowser:', sel32or64(b'I@:@', b'L@:@'), isRequired=False), objc.selector(None, b'imageBrowser:moveItemsAtIndexes:toIndex:', sel32or64(b'Z@:@@I', b'Z@:@@L'), isRequired=False), objc.selector(None, b'numberOfGroupsInImageBrowser:', sel32or64(b'I@:@', b'L@:@'), isRequired=False), objc.selector(None, b'imageBrowser:itemAtIndex:', sel32or64(b'@@:@I', b'@@:@L'), isRequired=False), objc.selector(None, b'imageBrowser:removeItemsAtIndexes:', b'v@:@@', isRequired=False), objc.selector(None, b'imageBrowser:writeItemsAtIndexes:toPasteboard:', sel32or64(b'I@:@@@', b'L@:@@@'), isRequired=False)])} expressions = {} # END OF FILE
[ "opensource@apple.com" ]
opensource@apple.com
761973b5dd1207bb3727936299c38638b92eb8e8
6a0abe2f4172f680415d83f1946baaf85e5711b7
/aliyun-python-sdk-bssopenapi/aliyunsdkbssopenapi/request/v20171214/QueryAccountBalanceRequest.py
5815155394b4b7f9816484efc1ee6806044bb9e0
[ "Apache-2.0" ]
permissive
brw123/aliyun-openapi-python-sdk
905556b268cbe4398f0f57b48422b713d9e89a51
8c77db6fd6503343cffa3c86fcb9d11770a64ca2
refs/heads/master
2020-05-01T16:26:49.291948
2019-03-21T09:11:55
2019-03-21T09:11:55
177,572,187
1
0
null
2019-03-25T11:21:59
2019-03-25T11:21:59
null
UTF-8
Python
false
false
983
py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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 aliyunsdkcore.request import RpcRequest class QueryAccountBalanceRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'BssOpenApi', '2017-12-14', 'QueryAccountBalance')
[ "yixiong.jxy@alibaba-inc.com" ]
yixiong.jxy@alibaba-inc.com
8443bf3ecaa41447fe625e2fe2294e82ecab398d
ccbfc7818c0b75929a1dfae41dc061d5e0b78519
/aliyun-openapi-python-sdk-master/aliyun-python-sdk-cloudesl/aliyunsdkcloudesl/request/v20180801/DescribeStoresRequest.py
5a7a3d07d56264658c0fd2ae92922535fd509779
[ "Apache-2.0" ]
permissive
P79N6A/dysms_python
44b634ffb2856b81d5f79f65889bfd5232a9b546
f44877b35817e103eed469a637813efffa1be3e4
refs/heads/master
2020-04-28T15:25:00.368913
2019-03-13T07:52:34
2019-03-13T07:52:34
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,173
py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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 aliyunsdkcore.request import RpcRequest class DescribeStoresRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'cloudesl', '2018-08-01', 'DescribeStores') def get_ToDate(self): return self.get_query_params().get('ToDate') def set_ToDate(self,ToDate): self.add_query_param('ToDate',ToDate) def get_PageSize(self): return self.get_query_params().get('PageSize') def set_PageSize(self,PageSize): self.add_query_param('PageSize',PageSize) def get_StoreName(self): return self.get_query_params().get('StoreName') def set_StoreName(self,StoreName): self.add_query_param('StoreName',StoreName) def get_Groups(self): return self.get_query_params().get('Groups') def set_Groups(self,Groups): self.add_query_param('Groups',Groups) def get_StoreId(self): return self.get_query_params().get('StoreId') def set_StoreId(self,StoreId): self.add_query_param('StoreId',StoreId) def get_Brand(self): return self.get_query_params().get('Brand') def set_Brand(self,Brand): self.add_query_param('Brand',Brand) def get_PageNumber(self): return self.get_query_params().get('PageNumber') def set_PageNumber(self,PageNumber): self.add_query_param('PageNumber',PageNumber) def get_FromDate(self): return self.get_query_params().get('FromDate') def set_FromDate(self,FromDate): self.add_query_param('FromDate',FromDate)
[ "1478458905@qq.com" ]
1478458905@qq.com
b7cc73147ba4ef14c6838961e1aef059cb0b31c4
66bb3f65f0157a2b5475903c90a54d5173bc4f0a
/djthia/bin/thank_you.py
ee920d6ca181a5ffa1743eab7dad3af84a511194
[ "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,155
py
#! /usr/bin/env python3 # -*- coding: utf-8 -*- import django import os import sys # load apps django.setup() from django.conf import settings from djthia.gearup.models import Annotation from djtools.utils.mail import send_mail # env os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djthia.settings.shell') DEBUG = settings.DEBUG def main(): """Send emails to recipients of thank you notes.""" notes = Annotation.objects.all() for note in notes: if note.status: to = [note.recipients.all()[0].email] frum = note.questionnaire.email if not frum: frum = note.created_by.email if DEBUG: note.to = to note.frum = frum to = [settings.MANAGERS[0][1]] subject = "A Thank You Note from {0} {1}".format( note.created_by.first_name, note.created_by.last_name, ) print(to, frum, subject) send_mail(None, to, subject, frum, 'gearup/notes_email.html', note) note.status = False note.save() if __name__ == '__main__': sys.exit(main())
[ "plungerman@gmail.com" ]
plungerman@gmail.com
7b98ad676a95b27ba930eb3ee2cf809754df15c6
9cc1b58d0319308da98187d071295b2fabf1f080
/0730_numpy/a0730_終於教到Numpy_02.py
3e6fefbfabd6cd5f2e6ebc2b2d00832df63433cd
[ "MIT" ]
permissive
Arwen0905/Python_Test
60d1dee383c9cf27df6b93cfde7884c91092229c
c75357e4354a684a9fae41f751dae60d4cf0716c
refs/heads/master
2023-01-13T13:14:55.355898
2020-10-31T18:52:07
2020-10-31T18:52:07
265,150,874
0
1
null
null
null
null
UTF-8
Python
false
false
1,089
py
import numpy as np a = np.array([1,2,3]) a = a * 3 a = a + 2 print(f"原本的a: {a}") b = np.array([2,2,0]) print(f"原本的b: {b}") print("a+b: ",a+b) # print("a/b: ",a/b) #除有問題 print("a*b: ",a*b) #建立陣列: np.array #建立陣列: np.arange c = np.arange(10) print(c) d = np.linspace(0,10,5) #平均撒點 print(d) e = np.array([[1,2,3],[4,5,6]]) print(e) f = np.arange(10).reshape(2,5) print(f) d = np.array([[[ [[1,2,3],[4,5,6],[7,8,9],[10,11,12]], [[1,2,3],[4,5,6],[7,8,9],[10,11,12]], [[1,2,3],[4,5,6],[7,8,9],[10,11,12]] ]]]) print(d) # 由圖解判斷幾維,從 欄、列 開始往外圈判斷,遇到框即代表一維 print(d.ndim) # 僅檢視該陣列為幾維 print(d.shape) # 由數量判斷有幾組維度,包含欄、列數量 print(d.sum(axis=2)) #指定維度 → 做運算(sum) print(d.reshape(12,3)) #重整結構,總數必須符合實際元素數量 arr = np.array([[1, 2, 3],[4,5,6]], ndmin=5) # ndmin可設定幾維 print(arr) print(arr.ndim) print('shape of array :', arr.shape)
[ "qq23378452@gmail.com" ]
qq23378452@gmail.com
d72d8940b00243adfe8eab7a936b3ee7a94c04c1
7c06b1221eba1da4141cdadaefbe318ad8cc13ec
/email_daemon.py
3e9cbc9b9537327634c8a4b1b02a621f3a790356
[]
no_license
danielmoniz/netrunner_db
c539323ff995157d881dd04d3e294889987c1727
3eb2c3f6388d3a2aebfaa1d7655319a92f385c00
refs/heads/master
2021-01-01T06:00:27.577047
2016-11-09T17:06:06
2016-11-09T17:06:06
19,191,392
0
0
null
null
null
null
UTF-8
Python
false
false
59
py
from netrunner import mail_reader mail_reader.read_mail()
[ "daniel.moniz@gmail.com" ]
daniel.moniz@gmail.com
3ff08b6463ee0d3726a8807965d91aba577eb6f3
dd87194dee537c2291cf0c0de809e2b1bf81b5b2
/test/test_v1beta1_deployment_spec.py
661c7f5b82ef365e85cabe855eb49e525f5a2da1
[ "Apache-2.0" ]
permissive
Arvinhub/client-python
3ea52640ab02e4bf5677d0fd54fdb4503ecb7768
d67df30f635231d68dc4c20b9b7e234c616c1e6a
refs/heads/master
2023-08-31T03:25:57.823810
2016-11-02T22:44:36
2016-11-02T22:44:36
73,865,578
1
0
Apache-2.0
2018-10-10T12:16:45
2016-11-15T23:47:17
Python
UTF-8
Python
false
false
1,440
py
# coding: utf-8 """ Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: unversioned Generated by: https://github.com/swagger-api/swagger-codegen.git Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from __future__ import absolute_import import os import sys import unittest import k8sclient from k8sclient.rest import ApiException from k8sclient.models.v1beta1_deployment_spec import V1beta1DeploymentSpec class TestV1beta1DeploymentSpec(unittest.TestCase): """ V1beta1DeploymentSpec unit test stubs """ def setUp(self): pass def tearDown(self): pass def testV1beta1DeploymentSpec(self): """ Test V1beta1DeploymentSpec """ model = k8sclient.models.v1beta1_deployment_spec.V1beta1DeploymentSpec() if __name__ == '__main__': unittest.main()
[ "mehdy@google.com" ]
mehdy@google.com
f28198c3ce34e8dc612664c6550ed1185d9c3b32
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_5690574640250880_1/Python/kevinleeone/main.py
7a28010c1cded6c2928d58496a1d84262b6a4e88
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
Python
false
false
2,338
py
import sys def fillRow(data, row): for i in range(len(data[row])): data[row][i] = '*' def fillCol(data, col): for i in data: i[col] = '*' def fill(data, row, col): data[row][col] = '*' def printSolution(data): return '\n'.join([''.join(i) for i in data]) def solve(): row, col, mines = map(int, sys.stdin.readline().split()) data = [['.'] * col for i in range(row)] data[0][0] = 'c' row -= 1 col -= 1 if row == 0: while mines: fill(data, row, col) col -= 1 mines -= 1 return printSolution(data) elif col == 0: while mines: fill(data, row, col) row -= 1 mines -= 1 return printSolution(data) else: while row < mines or col < mines: if col < row: fillRow(data, row) row -= 1 mines -= col + 1 else: fillCol(data, col) col -= 1 mines -= row + 1 if not mines: if 1 <= row and 1 <= col or row == 0 and col == 0: return printSolution(data) else: return 'Impossible' else: if col < row: i = row while 1 < i and mines: fill(data, i, col) mines -= 1 i -= 1 assert(mines == 0) row -= 1 col -= 1 if 1 <= row and 1 <= col: return printSolution(data) else: return 'Impossible' else: i = col while 1 < i and mines: fill(data, row, i) mines -= 1 i -= 1 if mines: assert(mines == 1) row -= 1 fill(data, row, col) row -= 1 col -= 1 if 1 <= row and 1 <= col: return printSolution(data) else: return 'Impossible' if __name__ == '__main__': cases = int(sys.stdin.readline().split()[0]) for i in range(cases): print('Case #%d:' % (i + 1)) print(solve())
[ "eewestman@gmail.com" ]
eewestman@gmail.com
050fdadc5b742ad96f26c3e3b74fc638ca7f9300
2cb2bc953975540de8dfe3aee256fb3daa852bfb
/kawagashira_nobuyuki/tyama_codeiq186.py
c27fa12584c938e2faec4bcece92b9bd39865131
[]
no_license
cielavenir/codeiq_solutions
db0c2001f9a837716aee1effbd92071e4033d7e0
750a22c937db0a5d94bfa5b6ee5ae7f1a2c06d57
refs/heads/master
2023-04-27T14:20:09.251817
2023-04-17T03:22:57
2023-04-17T03:22:57
19,687,315
2
4
null
null
null
null
UTF-8
Python
false
false
870
py
#!/usr/bin/python #coding:utf-8 import nltk #import re #nltk.download() #Download Corpora -> gutenberg from nltk.corpus import gutenberg #words1 = [w.lower() for w in gutenberg.words('austen-sense.txt')] #words2 = [w for w in words1 if re.sub(r'[^a-z]','',w)==w] words2 = [w.lower() for w in gutenberg.words('austen-sense.txt') if w.isalpha()] ### freq=nltk.FreqDist(words2) s = len(words2) for e in freq.keys(): print("%s,%d,%f" % (e,freq[e],float(freq[e])/s*100)) ''' keys = freq.keys() ### values = freq.values() ### #s=sum(freq.values()) s=sum(values) ### len(words2) for i in range(len(freq)): #print "%s,%d,%f" % (freq.keys()[i],freq.values()[i],float(freq.values()[i])/s*100) print "%s,%d,%f" % (keys[i],values[i],float(values[i])/s*100) ### ''' #冠詞、前置詞、代名詞、接続詞が多い #主人公であるelinorとmarianneも多く出現する
[ "cielartisan@gmail.com" ]
cielartisan@gmail.com
3ce44d8bde5dbf48a665dbc4c07d1ad54d105060
4db539a1fec5369d1970a10554a71f85b31a1855
/manage_command/migrations/0003_auto_20200707_2112.py
43943b20f0285a850ceef3038c56e8a6990cda4a
[]
no_license
1SouravGhosh/API_MONGO
8f04f37892703fbac9d851028505252cf58886b8
b7071ec5797adf3bcccdf6749c560f50e1469839
refs/heads/master
2022-11-19T23:35:03.933449
2020-07-10T07:24:22
2020-07-10T07:24:22
278,567,555
0
0
null
null
null
null
UTF-8
Python
false
false
374
py
# Generated by Django 3.0.5 on 2020-07-07 15:42 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('manage_command', '0002_auto_20200707_2111'), ] operations = [ migrations.RenameField( model_name='command', old_name='command', new_name='command1', ), ]
[ "1SouravGhosh@noreply.github.com" ]
1SouravGhosh@noreply.github.com
f86b14c00d63c82b17124a789bec6e8f3d9f89e5
37683c6f6c36f47ff4c7344576b268817e992ec3
/源代码/p17/p17_50.py
5b95523d6d60cf37313b3d1f9b97a73f93d0f7ac
[]
no_license
WhiteSheep-y/Python
33e026a798e2a02d75908cefa2b02fa2c654e199
a166bdb8ec8bcea2f955b43d16e9c9b92c44f558
refs/heads/main
2023-06-01T02:09:32.641415
2021-06-16T15:00:09
2021-06-16T15:00:09
359,199,929
0
0
null
null
null
null
UTF-8
Python
false
false
251
py
# p17_50.py from tkinter import * root = Tk() def create(): top = Toplevel() top.title("FishC Demo") msg = Message(top, text="I love FishC.com") msg.pack() Button(root, text="创建顶级窗口", command=create).pack() mainloop()
[ "xiaomie_y@163.com" ]
xiaomie_y@163.com
53096071f7b1fc09e5f96abc1c67458157a34650
1b78ca7f3250ebed418717c6ea28b5a77367f1b8
/051.n-queens/n-queens.py
0d216ecb8ef8f38a36a8a90aa7459786820bdf17
[]
no_license
JaniceLC/lc-all-solutions
ced854f31b94f44c0b03a0677988805e3b9ee718
3f2a4ee8c09a8890423c6a22c73f470eccf979a2
refs/heads/master
2020-04-05T19:53:31.307528
2018-11-12T04:18:45
2018-11-12T04:18:45
157,155,285
0
2
null
2018-11-12T04:13:22
2018-11-12T04:13:22
null
UTF-8
Python
false
false
1,091
py
class Solution(object): def solveNQueens(self, n): """ :type n: int :rtype: List[List[str]] """ ans = [] def dfs(path, n, ans): if len(path) == n: ans.append(drawChess(path)) return for i in range(n): if i not in path and isValidQueen(path, i): path.append(i) dfs(path, n, ans) path.pop() def isValidQueen(path, k): for i in range(len(path)): if abs(k - path[i]) == abs(len(path) - i): return False return True def drawChess(path): ret = [] chess = [["."] * len(path) for _ in range(len(path))] for i in range(0, len(path)): chess[i][path[i]] = "Q" for chs in chess: ret.append("".join(chs)) return ret dfs([], n, ans) return ans
[ "jedihy@yis-macbook-pro.local" ]
jedihy@yis-macbook-pro.local
b7334aef4dd1fac6f082369bba23650ac0764e78
6f866eb49d0b67f0bbbf35c34cebe2babe2f8719
/tests/app/forms/field_handlers/test_field_handler.py
81289acd03f8c36048634f0175cd0fdb9e99385b
[ "MIT", "LicenseRef-scancode-proprietary-license" ]
permissive
ONSdigital/eq-questionnaire-runner
681b0d081f9cff0ee4ae3017ecc61f7390d553bf
87e7364c4d54fee99e6a5e96649123f11c4b53f1
refs/heads/main
2023-09-01T21:59:56.733363
2023-08-31T15:07:55
2023-08-31T15:07:55
219,752,509
12
18
MIT
2023-09-14T11:37:31
2019-11-05T13:32:18
Python
UTF-8
Python
false
false
2,438
py
from wtforms import validators from app.forms import error_messages from app.forms.field_handlers.string_handler import StringHandler from app.forms.validators import ResponseRequired def test_get_mandatory_validator_optional(value_source_resolver, rule_evaluator): answer = {"mandatory": False} text_area_handler = StringHandler( answer, value_source_resolver, rule_evaluator, error_messages ) validate_with = text_area_handler.get_mandatory_validator() assert isinstance(validate_with, validators.Optional) def test_get_mandatory_validator_mandatory(value_source_resolver, rule_evaluator): answer = {"mandatory": True} text_area_handler = StringHandler( answer, value_source_resolver, rule_evaluator, {"MANDATORY_TEXTFIELD": "This is the default mandatory message"}, ) validate_with = text_area_handler.get_mandatory_validator() assert isinstance(validate_with, ResponseRequired) assert validate_with.message == "This is the default mandatory message" def test_get_mandatory_validator_mandatory_with_error( value_source_resolver, rule_evaluator ): answer = { "mandatory": True, "validation": { "messages": { "MANDATORY_TEXTFIELD": "This is the mandatory message for an answer" } }, } text_area_handler = StringHandler( answer, value_source_resolver, rule_evaluator, error_messages ) validate_with = text_area_handler.get_mandatory_validator() assert isinstance(validate_with, ResponseRequired) assert validate_with.message == "This is the mandatory message for an answer" def test_get_mandatory_validator_mandatory_with_question_in_error( value_source_resolver, rule_evaluator ): answer = { "mandatory": True, "validation": { "messages": { "MANDATORY_TEXTFIELD": "Select an answer to ‘%(question_title)s’" } }, } text_area_handler = StringHandler( answer, value_source_resolver, rule_evaluator, {"MANDATORY_TEXTFIELD": "This is the default mandatory message"}, question_title="To be or not to be?", ) validate_with = text_area_handler.get_mandatory_validator() assert isinstance(validate_with, ResponseRequired) assert validate_with.message == "Select an answer to ‘To be or not to be?’"
[ "noreply@github.com" ]
ONSdigital.noreply@github.com
690ea698c2f6650c9785ed6877b332086552e8c7
6b4f38370ce1126a7f74e13c2012ab238a01df93
/azure-mgmt-compute/azure/mgmt/compute/compute/v2017_03_30/models/os_disk_image.py
52165b11bc0cd25a81a4315d22b3130f970e4f7d
[ "MIT" ]
permissive
action/azure-sdk-for-python
52d8a278bfb2fbc9c7e11297e3bd21c604f906b1
f06553e45451f065c87ee9ed503ac4be81e64a71
refs/heads/master
2020-12-03T02:13:52.566291
2017-06-30T18:42:49
2017-06-30T18:42:49
95,917,797
1
0
null
2017-06-30T19:25:58
2017-06-30T19:25:58
null
UTF-8
Python
false
false
1,140
py
# 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 msrest.serialization import Model class OSDiskImage(Model): """Contains the os disk image information. :param operating_system: The operating system of the osDiskImage. Possible values include: 'Windows', 'Linux' :type operating_system: str or :class:`OperatingSystemTypes <azure.mgmt.compute.compute.v2017_03_30.models.OperatingSystemTypes>` """ _validation = { 'operating_system': {'required': True}, } _attribute_map = { 'operating_system': {'key': 'operatingSystem', 'type': 'OperatingSystemTypes'}, } def __init__(self, operating_system): self.operating_system = operating_system
[ "lmazuel@microsoft.com" ]
lmazuel@microsoft.com
3c288fa74b379bbb4e9419282be8f2108292fa16
139715a923c8c82b172803d5bdc1b1bca46fbdf3
/leetcode/swap_node.py
5bfdd00934e97a6e295d9ed9688c73a3b12c36b5
[]
no_license
haoccheng/pegasus
ab32dcc4265ed901e73790d8952aa3d72bdf72e7
76cbac7ffbea738c917e96655e206f8ecb705167
refs/heads/master
2021-01-10T11:33:23.038288
2016-03-18T04:17:28
2016-03-18T04:17:28
46,103,391
0
0
null
null
null
null
UTF-8
Python
false
false
955
py
# Given a linked list, swap every two adjacent nodes and return the head. # 1->2->3->4 return: 2->1->4->3. # Use constant space. May not modify the values in the list; only nodes itself can be changed. class ListNode: def __init__(self, x): self.val = x self.next = None def pt(self): ret = [] ret.append(self.val) if self.next is not None: ret += self.next.pt() return ret def create(input): head = ListNode(input[0]) if len(input) > 1: tail = ListNode.create(input[1:]) head.next = tail return head create = staticmethod(create) def swap_nodes(head): curr = head if curr is None: return None else: next = curr.next if next is None: return curr curr.next = next.next next.next = curr curr = next next = swap_nodes(curr.next.next) curr.next.next = next return curr h = ListNode.create([1,2,3,4,5]) print h.pt() x = swap_nodes(h) print x.pt()
[ "haoc.cheng@gmail.com" ]
haoc.cheng@gmail.com
b285f83ba9cb715e85abeb79cde46b6044797581
9507ff9e9bca2ca8104369c9e25acd74d308e9b3
/data_collect/novatel_pi.py
485fa7917c9ecbd01b49b1f1ad849886d092ea02
[]
no_license
yangkang411/python_tool
03e483c7ec7e1e76284f93cf5b9086fdf98af826
713071a9fbabfabcbc3c16ce58d1382c410a7ea3
refs/heads/master
2023-03-17T16:14:03.332332
2020-09-10T02:37:05
2020-09-10T02:37:05
null
0
0
null
null
null
null
UTF-8
Python
false
false
5,837
py
#!/usr/bin/python import serial import math import time import datetime import os def get_utc_day(): year = int(time.strftime("%Y")) month = int(time.strftime("%m")) day = int(time.strftime("%d")) hour = int(time.strftime("%H")) minute = int(time.strftime("%M")) second = int(time.strftime("%S")) local_time = datetime.datetime(year, month, day, hour, minute, second) time_struct = time.mktime(local_time.timetuple()) utc_st = datetime.datetime.utcfromtimestamp(time_struct) d1 = datetime.datetime(year, 1, 1) utc_sub = utc_st - d1 utc_str = utc_sub.__str__() utc_day_int = int(utc_str.split( )[0]) utc_day_str = str(utc_day_int + 1) return utc_day_str def mkdir(path): path=path.strip() path=path.rstrip("\\") isExists=os.path.exists(path) if not isExists: os.makedirs(path) print path+' mkdir suc' return True else: print 'mkdir exist' return False def getweeknum(weekseconds): return math.floor(weekseconds/(7*24*3600)) def getweeksec(weekseconds): return weekseconds - getweeknum(weekseconds)*(7*24*3600) def yearfour(year): if year<=80: year += 2000 elif year<1990 and year>80: year += 1900 return year def isleapyear(year): return (yearfour(year)%4==0 and yearfour(year)%100!=0) or yearfour(year)%400==0 def timefromGPS(weeknum,weeksec): year = 0 month = 0 day = 0 hour = 0 minute = 0 second = 0 doy = 0 daypermon = [31,28,31,30,31,30,31,31,30,31,30,31] weeknum += getweeknum(weeksec) weeksec = getweeksec(weeksec) weekmin = math.floor(weeksec/60.0) second = weeksec - weekmin*60.0 weekhour = math.floor(weekmin/60) minute = weekmin - weekhour*60 weekday = math.floor(weekhour/24) hour = weekhour - weekday*24 totalday = weekday+weeknum*7 if totalday<360: year = 1980 else: year = 1981 totalday -= 360 while True: if totalday<365: break if isleapyear(year): totalday -= 1 totalday -= 365 year += 1 doy = totalday if totalday <= daypermon[0]: month = 1 else: totalday -= daypermon[0]; if isleapyear(year): totalday -= 1 month = 2 while True: if totalday<=daypermon[month-1]: break else: totalday -= daypermon[month-1] month += 1 if month==2 and isleapyear(year): totalday += 1 day = totalday return [year,month,day,hour,minute,second,doy] def configNovatel(ser): # need to change the following lever arm values when mounting in the car #'setimutoantoffset -0.2077 1.8782 1.0 0.10 0.10 0.10\r',\ # 'setinstranslation ant2 x, y, z, std_x, std_y, std_z\r',\ setupcommands7 = ['unlogall\r',\ 'serialconfig com1 230400 N 8 1 N OFF\r',\ 'ETHCONFIG ETHA AUTO AUTO AUTO AUTO\r',\ 'NTRIPCONFIG ncom1 client v1 106.12.40.121:2201 RTK rtkeasy 555555\r',\ 'interfacemode ncom1 rtcmv3 novatel off\r',\ 'interfacemode com1 novatel novatel on\r',\ 'alignmentmode automatic\r',\ 'setinstranslation ant1 0.0 0.0 0.0 0.10 0.10 0.10\r',\ 'setinstranslation ant2 0.0 0.0 0.0 0.10 0.10 0.10\r',\ 'setinsrotation rbv -180 0 90\r',\ #'setinsrotation rbv 90 0 180\r',\ 'log RANGECMPB ONTIME 0.1\r',\ 'log RAWEPHEMB ONCHANGED\r',\ 'log GLOEPHEMERISB ONCHANGED\r',\ 'log GALFNAVEPHEMERISB ONCHANGED\r',\ 'log GALINAVEPHEMERISB ONCHANGED\r',\ 'log BDSEPHEMERISB ONCHANGED\r',\ 'log QZSSEPHEMERISB ONCHANGED\r',\ 'log INSCONFIGB ONCHANGED\r',\ #'log RAWIMUSXB ONNEW\r',\ 'log versionb once\r',\ 'log rxconfigb once\r',\ 'log rxstatusb once\r',\ 'log thisantennatypeb once\r',\ 'log inspvasb ontime 0.1\r',\ #'log bestposb ontime 0.1\r',\ 'log bestgnssposb ontime 0.1\r',\ 'log bestgnssvelb ontime 0.1\r',\ #'log heading2b onnew\r',\ 'log ncom1 gpgga ontime 1\r',\ 'saveconfig\r'] for cmd in setupcommands7: ser.write(cmd.encode()) ser = serial.Serial('/dev/ttyUSB0',230400,parity='N',bytesize=8,stopbits=1,timeout=None) #novatel fname = '' ser.flushInput() fmode = 'wb' while True: if ser.isOpen(): break print ('\Port is open now\n') configNovatel(ser) ser.flushInput() # get the time information from #INSPVAXA ##while True: ## line = ser.readline().decode('utf-8') ## if line.find('#INSPVAXA', 0, len(line)) >= 0: ## info = line.split(',') ## #print(info) ## gpsweek = int(info[5]); ## sow = float(info[6]); ## #print(gpsweek) ## #print(sow) ## startime = timefromGPS(gpsweek,sow) ## fname += '_%4d%02d%02d_%02d%02d%02d.txt' % (startime[0],startime[1],startime[2],startime[3],startime[4],startime[5]) ## print(fname) ## break #mk_time = time.strftime("%Y_%m_%d",time.localtime()) #mkpath='./' + mk_time day = get_utc_day() mkpath='./' + day mkdir(mkpath) fname += mkpath + '/' + 'novatel_' + time.strftime("%Y_%m_%d_%H_%M_%S", time.localtime()) + '.bin' with open(fname,fmode) as outf: while True: try: line = ser.readline() #print (line, end='\r\n') #outf.write(line.decode('utf-8')) outf.write(bytes(line)) #line.decode('utf-8') except: #break pass outf.close()
[ "41727862+geqian@users.noreply.github.com" ]
41727862+geqian@users.noreply.github.com
6dc99ea802bf1e2b5e2bec7686b08547ccf9f1ae
b71e4e576d242598d8cec5c552e1d66630b81328
/tools/generate_changelog.py
810bde02639a0ed417bc48dd5d0bd88b0c2d2b77
[ "Apache-2.0" ]
permissive
Global19-atlassian-net/qiskit-bot
d77b7b326e3a9b3e4db3b7453fa62326ecc65be7
2cd2e27d0ff51bb517eee0ceab24cb57b2034f12
refs/heads/master
2023-03-31T08:05:38.992587
2021-04-09T20:23:50
2021-04-09T20:23:50
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,863
py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2019 # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. import argparse import tempfile from github import Github from qiskit_bot import config from qiskit_bot import repos from qiskit_bot import release_process def main(): parser = argparse.ArgumentParser() parser.add_argument('repo_name') parser.add_argument('tag') parser.add_argument('--token', '-t', help="optional token for auth", default=None) parser.add_argument( '--username', '-u', help="optional username for auth, password required if specified", default=None) parser.add_argument( '--password', '-p', help="optional password for auth, username required if specified.", default=None) args = parser.parse_args() with tempfile.TemporaryDirectory() as tmpdir: token = args.token repo = repos.Repo(tmpdir, args.repo_name, token) if not token and args.username and args.password: session = Github(args.username, args.password) gh_repo = session.get_repo(args.repo_name) repo.gh_repo = gh_repo categories = repo.get_local_config().get( 'categories', config.default_changelog_categories) print(release_process._generate_changelog( repo, '%s..' % args.tag, categories, show_missing=True)) if __name__ == '__main__': main()
[ "mtreinish@kortar.org" ]
mtreinish@kortar.org
7c7f43bb605f5e933d8b743773578ddafeecd426
35e79b51f691b7737db254ba1d907b2fd2d731ef
/AtCoder/ARC/108/B.py
70f7cfc3ece60774a07f7d71f03ed6736989158b
[]
no_license
rodea0952/competitive-programming
00260062d00f56a011f146cbdb9ef8356e6b69e4
9d7089307c8f61ea1274a9f51d6ea00d67b80482
refs/heads/master
2022-07-01T02:25:46.897613
2022-06-04T08:44:42
2022-06-04T08:44:42
202,485,546
0
0
null
null
null
null
UTF-8
Python
false
false
220
py
n = int(input()) s = input() seq = [] for i in range(n): seq.append(s[i]) if len(seq) <= 2: continue if seq[-3] + seq[-2] + seq[-1] == "fox": for j in range(3): seq.pop() print(len(seq))
[ "dragondoor0912@yahoo.co.jp" ]
dragondoor0912@yahoo.co.jp
dacc6ba9a649d25e5bab950814610ce498f64c67
e77b92df446f0afed18a923846944b5fd3596bf9
/Programers_algo/DFS_BFS/pro_4_re_re_re.py
6c6c3154a70e176d89d9f76bbb775c1d43586c4c
[]
no_license
sds1vrk/Algo_Study
e40ca8eb348d1fc6f88d883b26195b9ee6f35b2e
fbbc21bb06bb5dc08927b899ddc20e6cde9f0319
refs/heads/main
2023-06-27T05:49:15.351644
2021-08-01T12:43:06
2021-08-01T12:43:06
356,512,348
0
0
null
null
null
null
UTF-8
Python
false
false
1,037
py
from collections import defaultdict def solution(tickets): # 특정 티켓의 인접 리스트를 구하는 함수 def init_graph(): routes = defaultdict(list) for key, value in tickets: routes[key].append(value) return routes # 재귀 호출을 사용한 DFS def dfs(key, footprint): if len(footprint) == N + 1: return footprint for idx, country in enumerate(routes[key]): routes[key].pop(idx) fp = footprint[:] # deepcopy # print("fp",fp,"footprirnt",footprint) fp.append(country) ret = dfs(country, fp) if ret: return ret # 모든 티켓을 사용해 통과한 경우 routes[key].insert(idx, country) # 통과 못했으면 티켓 반환 routes = init_graph() for r in routes: routes[r].sort() N = len(tickets) answer = dfs("ICN", ["ICN"]) return answer print(solution([["ICN", "A"], ["A", "B"], ["A", "C"], ["C", "A"], ["B", "D"]]))
[ "51287886+sds1vrk@users.noreply.github.com" ]
51287886+sds1vrk@users.noreply.github.com
77f5260da75e460a62606596b673ba4a447d4e95
795dc0de20ee4c7f4067231560238d67adb81d7e
/tests/tagifai/test_data.py
1c2750da6855674f85cb8a23e6af3aabb053a192
[ "MIT" ]
permissive
raulqf/MLOps
9fe3597b9313c4079b9ec6ec0e64e53c7629a180
9cd4efb5ae4b201f10c92cc1f79b64c04e99b1f7
refs/heads/main
2023-08-08T01:21:41.934588
2021-09-15T23:29:18
2021-09-15T23:29:18
null
0
0
null
null
null
null
UTF-8
Python
false
false
11,631
py
# tests/tagifai/test_data.py # Test tagifai/data.py components. import itertools import tempfile from argparse import Namespace from collections import Counter from pathlib import Path import numpy as np import pytest from app import config from tagifai import data, main, utils @pytest.fixture(scope="module") def tags(): # Load tags tags_url = "https://raw.githubusercontent.com/GokuMohandas/MadeWithML/main/datasets/tags.json" tags_dict = utils.load_json_from_url(url=tags_url) tags = [tag["tag"] for tag in tags_dict] return tags @pytest.fixture(scope="module") def df(): # Load features params_fp = Path(config.CONFIG_DIR, "params.json") params = Namespace(**utils.load_dict(filepath=params_fp)) df, _ = main.compute_features(params=params) return df @pytest.mark.parametrize( "items, include, filtered", [ # one item (["apple"], ["apple"], ["apple"]), # multiple items ( ["apple", "banana", "grape", "orange"], ["apple"], ["apple"], ), # multiple include ( ["apple", "banana", "grape", "orange"], ["apple", "grape"], ["apple", "grape"], ), # no include ( ["apple", "banana", "grape", "orange"], [], [], ), ], ) def test_filter_items(items, include, filtered): assert data.filter_items(items=items, include=include) == filtered def test_clean(tags, df): min_tag_freq = 30 df, tags_above_freq, tags_below_freq = data.prepare( df=df, include=tags, exclude=config.EXCLUDED_TAGS, min_tag_freq=min_tag_freq, ) all_tags = list(itertools.chain.from_iterable(df.tags)) assert Counter(all_tags).most_common()[-1][1] >= min_tag_freq @pytest.mark.parametrize( "text, lower, stem, filters, stopwords, preprocessed_text", [ ("Hello worlds", False, False, "", [], "Hello worlds"), ("Hello worlds", True, False, "", [], "hello worlds"), ("Hello worlds", False, True, "", [], "Hello world"), ("Hello worlds", True, True, "", [], "hello world"), ("Hello worlds", True, True, "l", [], "heo word"), ("Hello worlds", True, True, "", ["world"], "hello world"), ("Hello worlds", True, True, "", ["worlds"], "hello"), ], ) def test_preprocess(text, lower, stem, filters, stopwords, preprocessed_text): assert ( data.preprocess( text=text, lower=lower, stem=stem, filters=filters, stopwords=stopwords, ) == preprocessed_text ) class TestLabelEncoder: @classmethod def setup_class(cls): """Called before every class initialization.""" pass @classmethod def teardown_class(cls): """Called after every class initialization.""" pass def setup_method(self): """Called before every method.""" self.label_encoder = data.LabelEncoder() def teardown_method(self): """Called after every method.""" del self.label_encoder def test_empty_init(self): label_encoder = data.LabelEncoder() assert label_encoder.index_to_class == {} assert len(label_encoder.classes) == 0 def test_dict_init(self): class_to_index = {"apple": 0, "banana": 1} label_encoder = data.LabelEncoder(class_to_index=class_to_index) assert label_encoder.index_to_class == {0: "apple", 1: "banana"} assert len(label_encoder.classes) == 2 def test_len(self): assert len(self.label_encoder) == 0 def test_save_and_load(self): with tempfile.TemporaryDirectory() as dp: fp = Path(dp, "label_encoder.json") self.label_encoder.save(fp=fp) label_encoder = data.LabelEncoder.load(fp=fp) assert len(label_encoder.classes) == 0 @pytest.mark.parametrize( "label_encoder, output", [ (data.MultiClassLabelEncoder(), "<MultiClassLabelEncoder(num_classes=0)>"), (data.MultiLabelLabelEncoder(), "<MultiLabelLabelEncoder(num_classes=0)>"), ], ) def test_str(self, label_encoder, output): assert str(label_encoder) == output @pytest.mark.parametrize( "label_encoder, y", [ (data.MultiClassLabelEncoder(), ["apple", "apple", "banana"]), (data.MultiLabelLabelEncoder(), [["apple"], ["apple", "banana"]]), ], ) def test_fit(self, label_encoder, y): label_encoder.fit(y) assert "apple" in label_encoder.class_to_index assert "banana" in label_encoder.class_to_index assert len(label_encoder.classes) == 2 @pytest.mark.parametrize( "label_encoder, y, y_encoded", [ ( data.MultiClassLabelEncoder(class_to_index={"apple": 0, "banana": 1}), ["apple", "apple", "banana"], [0, 0, 1], ), ( data.MultiLabelLabelEncoder(class_to_index={"apple": 0, "banana": 1}), [["apple"], ["apple", "banana"]], [[1, 0], [1, 1]], ), ], ) def test_encode_decode(self, label_encoder, y, y_encoded): label_encoder.fit(y) assert np.array_equal(label_encoder.encode(y), np.array(y_encoded)) assert label_encoder.decode(y_encoded) == y def test_iterative_train_test_split(tags, df): # Process df, tags_above_freq, tags_below_freq = data.prepare(df=df, include=tags, min_tag_freq=1) df.text = df.text.apply(data.preprocess) # Encode labels labels = df.tags label_encoder = data.MultiLabelLabelEncoder() label_encoder.fit(labels) y = label_encoder.encode(labels) # Split data X = df.text.to_numpy() X_train, X_, y_train, y_ = data.iterative_train_test_split(X=X, y=y, train_size=0.7) X_val, X_test, y_val, y_test = data.iterative_train_test_split(X=X_, y=y_, train_size=0.5) assert len(X_train) == len(y_train) assert len(X_val) == len(y_val) assert len(X_test) == len(y_test) assert len(X_train) / float(len(X)) == pytest.approx(0.7, abs=0.05) # 0.7 ± 0.05 assert len(X_val) / float(len(X)) == pytest.approx(0.15, abs=0.05) # 0.15 ± 0.05 assert len(X_test) / float(len(X)) == pytest.approx(0.15, abs=0.05) # 0.15 ± 0.05 class TestTokenizer: def setup_method(self): """Called before every method.""" self.tokenizer = data.Tokenizer(char_level=True, num_tokens=None) def teardown_method(self): """Called after every method.""" del self.tokenizer @pytest.mark.parametrize( "char_level, num_tokens, separator, token_to_index, expected_token_to_index", [ (True, None, "", None, {"<PAD>": 0, "<UNK>": 1}), (False, None, " ", None, {"<PAD>": 0, "<UNK>": 1}), ( False, None, " ", {"<PAD>": 0, "<UNK>": 1, "hello": 2}, {"<PAD>": 0, "<UNK>": 1, "hello": 2}, ), ], ) def test_init(self, char_level, num_tokens, separator, token_to_index, expected_token_to_index): tokenizer = data.Tokenizer( char_level=char_level, num_tokens=num_tokens, token_to_index=token_to_index ) assert tokenizer.separator == separator assert tokenizer.token_to_index == expected_token_to_index def test_len(self): assert len(self.tokenizer) == 2 def test_str(self): assert str(self.tokenizer) == f"<Tokenizer(num_tokens={len(self.tokenizer)})>" @pytest.mark.parametrize( "char_level, num_tokens, texts, vocab_size", [(False, None, ["hello world", "goodbye"], 5), (False, 4, ["hello world", "goodbye"], 4)], ) def test_fit_on_texts(self, char_level, num_tokens, texts, vocab_size): tokenizer = data.Tokenizer(char_level=char_level, num_tokens=num_tokens) tokenizer.fit_on_texts(texts=texts) assert len(tokenizer) == vocab_size @pytest.mark.parametrize( "tokenizer, texts, sequences, decoded", [ ( data.Tokenizer( char_level=False, token_to_index={"<PAD>": 0, "<UNK>": 1, "hello": 2, "world": 3}, ), ["hello world", "hi world", "apple"], [[2, 3], [1, 3], [1]], ["hello world", "<UNK> world", "<UNK>"], ), ( data.Tokenizer( char_level=True, token_to_index={"<PAD>": 0, "<UNK>": 1, " ": 2, "a": 3, "b": 4} ), ["ab", "b", "a x ab"], [[3, 4], [4], [3, 2, 1, 2, 3, 4]], ["ab", "b", "a <UNK> ab"], ), ], ) def test_encode_decode(self, tokenizer, texts, sequences, decoded): assert tokenizer.texts_to_sequences(texts=texts) == sequences assert tokenizer.sequences_to_texts(sequences=sequences) == decoded def test_save_and_load(self): with tempfile.TemporaryDirectory() as dp: tokenizer = data.Tokenizer( char_level=False, token_to_index={"<PAD>": 0, "<UNK>": 1, "hello": 2, "world": 3} ) fp = Path(dp, "label_encoder.json") tokenizer.save(fp=fp) tokenizer = data.Tokenizer.load(fp=fp) assert len(tokenizer) == 4 def test_pad_sequences(): # Explicit max len seq = np.array([[1, 2, 3], [1, 2]], dtype=object) padded_seq = data.pad_sequences(sequences=seq, max_seq_len=5) assert np.array_equal(padded_seq, np.array([[1, 2, 3, 0, 0], [1, 2, 0, 0, 0]])) # Implicit max len seq = np.array([[1, 2, 3], [1, 2]], dtype=object) padded_seq = data.pad_sequences(sequences=seq) assert np.array_equal(padded_seq, np.array([[1, 2, 3], [1, 2, 0]])) class TestCNNTextDataset: def setup_method(self): """Called before every method.""" self.X = [[4, 2, 3, 0], [2, 4, 3, 3], [2, 3, 0, 0]] self.y = [[0, 1], [1, 1], [1, 0]] self.max_filter_size = 2 self.batch_size = 1 self.dataset = data.CNNTextDataset(X=self.X, y=self.y, max_filter_size=self.max_filter_size) def teardown_method(self): """Called after every method.""" del self.dataset def test_init(self): assert self.max_filter_size == self.dataset.max_filter_size def test_len(self): assert len(self.X) == len(self.dataset) def test_str(self): assert str(self.dataset) == f"<Dataset(N={len(self.dataset)})>" def test_get_item(self): assert self.dataset[0] == [self.X[0], self.y[0]] assert self.dataset[-1] == [self.X[-1], self.y[-1]] @pytest.mark.parametrize( "batch_size, drop_last, num_batches", [(1, False, 3), (2, False, 2), (2, True, 1), (3, False, 1)], ) def test_create_dataloader(self, batch_size, drop_last, num_batches): dataloader = self.dataset.create_dataloader(batch_size=batch_size, drop_last=drop_last) assert len(dataloader) == num_batches def test_dataloader(self): batch_size = 2 dataloader = self.dataset.create_dataloader(batch_size=batch_size, drop_last=False) max_seq_len = max(self.max_filter_size, max(len(sequence) for sequence in self.X)) for batch in dataloader: assert len(batch) <= batch_size assert np.shape(batch[0])[-1] == max_seq_len
[ "gokumd@gmail.com" ]
gokumd@gmail.com
ec3d37871d0b7c038a83fbd98c57ece4b479fd40
ba4e73e43a419b2491c68ef1b64f6ff21c296fb8
/src/profiles_project/profiles_api/serializers.py
41de36ffefe6a3fc177d0ac206d764e10d37fdc8
[]
no_license
adithyanps/profile-rest-api
7ca6c14f43bc072b4cd3815463950753867b5786
65421b9f3fd45f80ef86a8ca6591929a0e5453d8
refs/heads/master
2020-04-09T22:35:40.979205
2018-12-06T07:15:54
2018-12-06T07:15:54
160,632,750
0
0
null
null
null
null
UTF-8
Python
false
false
1,114
py
from rest_framework import serializers from . import models class HelloSerializer(serializers.Serializer): """serialise a name field for testing our API view""" name = serializers.CharField(max_length=10) class UserProfileSerializer(serializers.ModelSerializer): """A serializer for our user profile objects""" class Meta: model = models.UserProfile fields = ('id','email','name','password') extra_kwargs = {'password':{'write_only':True}} #this is to hide password from users def create(self, validated_data): """create and return a new user""" user = models.UserProfile( email=validated_data['email'], name=validated_data['name'], ) user.set_password(validated_data['password']) user.save() return user class ProfilefeedItemSerializer(serializers.ModelSerializer): """A serializer for profile feed items""" class Meta: model = models.ProfileFeedItem fields = ('id','user_profile','status_text','created_on') extra_kwargs = {'user_profile':{'read_only':True}}
[ "adithynps3@gmial.com" ]
adithynps3@gmial.com
3cf0e33afa27ddc56d6846b1d08d09011df235f6
5c11c2731c736be4055639b9ddae74d2536a62b9
/cloudmesh_base/locations.py
f7d263a459b779d2e44c894868778aa42b558464
[ "Apache-2.0" ]
permissive
zaber-paul/base
6694e1e12c0ca7e500e7e645df0336475bf0b11a
9c4d4e40db7a5059dcaa32d44be0146b6bb829c4
refs/heads/master
2020-08-11T09:37:08.805336
2020-01-08T01:24:44
2020-01-08T01:24:44
214,541,353
0
0
Apache-2.0
2019-10-11T22:56:48
2019-10-11T22:56:48
null
UTF-8
Python
false
false
890
py
from cloudmesh_base.util import path_expand from cloudmesh_base.Shell import Shell import os __config_dir_prefix__ = os.path.join("~", ".cloudmesh") __config_dir__ = path_expand(__config_dir_prefix__) def config_file(filename): """ The location of the config file: ~/.cloudmesh/filename. ~ will be expanded :param filename: the filename """ return os.path.join(__config_dir__, filename) def config_file_raw(filename): """ The location of the config file: ~/.cloudmesh/filename. ~ will NOT be expanded :param filename: the filename """ return os.path.join(__config_dir_prefix__, filename) def config_file_prefix(): """ The prefix of the configuration file location """ return __config_dir_prefix__ def config_dir_setup(filename): path = os.path.dirname(filename) if not os.path.isdir(path): Shell.mkdir(path)
[ "laszewski@gmail.com" ]
laszewski@gmail.com
a78b3e5b9320fcde83a6189f7374d3fd0882b1bf
98dfa21cd26462658165c802a16b697cf1ba582f
/blog/models.py
e9c5ed76a0502a3bcd4b7f74d90fcf624cd8409b
[]
no_license
samirpatil2000/startwith_rest-framework
9408c295bf08ed21551ae5e5fe45a54c45bde8d2
0b1e3978886ab3fea40d046814c3ca3bc258c8f7
refs/heads/master
2022-12-31T14:04:36.376080
2020-10-18T06:17:36
2020-10-18T06:17:36
304,104,735
0
0
null
null
null
null
UTF-8
Python
false
false
1,795
py
import random from django.db import models from django.db.models.signals import pre_save from django.urls import reverse from django.utils.text import slugify from django.conf import settings from django.db.models.signals import post_delete from django.dispatch import receiver # Create your models here. def upload_location(instance, filename): file_path = f'blog/{str(instance.author.id)}/{str(instance.title)}-{filename}' return file_path def default_title(): n=random.randrange(10,99) return f'blog{n}' class BlogPost(models.Model): title = models.CharField(max_length=50, default=default_title,null=False, blank=False) body = models.TextField(max_length=5000, default='This is the body',null=True, blank=True) image = models.ImageField(upload_to=upload_location, null=True, blank=True) date_published = models.DateTimeField(auto_now_add=True, verbose_name="date published") date_updated = models.DateTimeField(auto_now=True, verbose_name="date updated") author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) slug = models.SlugField(blank=True, unique=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('blog_detail',kwargs={'slug':self.slug}) """ if blog post is deleted then it will delete image also from database""" @receiver(post_delete, sender=BlogPost) def submission_delete(sender, instance, **kwargs): instance.image.delete(False) """ Here we are creating slug if their is on slug """ # TODO slugify is user fro creating slug def pre_save_blog_post_receiver(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = slugify(f'{instance.author.username} - {instance.title}') pre_save.connect(pre_save_blog_post_receiver, sender=BlogPost)
[ "samirspatil742099@gmail.com" ]
samirspatil742099@gmail.com
bf25d724880936aef9b3440e4517fa7ff12fc670
a024fe3b05dd320a7860165dd72ebd832ce6e484
/sale_order_portal/models/models.py
09856cd628a8bd90a34b8d5a2e76f83c0d408bf3
[]
no_license
acostaw/erp_odoo
97d02a675908e441cf8e1ba4e3dcbc62691f8dec
2437997b650c9fdbf6a6f007c0a1fea2aab018e2
refs/heads/main
2023-04-19T14:52:48.877851
2021-04-22T18:40:07
2021-04-22T18:40:07
360,644,871
0
0
null
null
null
null
UTF-8
Python
false
false
414
py
# -*- coding: utf-8 -*- from odoo import models, fields, api # class sale_order_portal(models.Model): # _name = 'sale_order_portal.sale_order_portal' # name = fields.Char() # value = fields.Integer() # value2 = fields.Float(compute="_value_pc", store=True) # description = fields.Text() # # @api.depends('value') # def _value_pc(self): # self.value2 = float(self.value) / 100
[ "wacosta@INTN.GOV.PY" ]
wacosta@INTN.GOV.PY
978ffec64bc93981e16854128c9f7aade48bfc3f
a4e6b080d17611853374577aaecb0367366b39b5
/glycresoft_sqlalchemy/web_app/services/json_api.py
222df0e6d93e068677cb4d7a0fa37616774c997e
[]
no_license
mobiusklein/glycresoft_sqlalchemy
6235b1ea2c8da9ef6b2e725a60f0b6a925f1689d
e0edf12a8d6243cc2438a6236aa0564a28f92a8a
refs/heads/master
2020-04-06T05:38:35.849225
2016-11-21T03:25:26
2016-11-21T03:25:26
37,537,754
0
2
null
2016-11-21T03:25:27
2015-06-16T15:10:45
Python
UTF-8
Python
false
false
1,370
py
from flask import Response, Blueprint, g, jsonify from glycresoft_sqlalchemy.data_model import GlycopeptideMatch, Hypothesis, HypothesisSampleMatch, json_type from glycresoft_sqlalchemy.report import colors JSONEncoderType = json_type.new_alchemy_encoder() # ---------------------------------------- # JSON Data API Calls # ---------------------------------------- api = Blueprint("api", __name__) @api.route("/api/glycopeptide_matches/<int:id>") def get_glycopeptide_match_api(id): gpm = g.db.query(GlycopeptideMatch).get(id) return Response(JSONEncoderType().encode(gpm), mimetype="text/json") @api.route("/api/tasks") def api_tasks(): return jsonify(**{t.id: t.to_json() for t in g.manager.tasks.values()}) @api.route("/api/hypothesis_sample_matches") def api_hypothesis_sample_matches(): hsms = g.db.query(HypothesisSampleMatch).all() d = {str(h.id): h.to_json() for h in hsms} return jsonify(**d) @api.route("/api/hypotheses") def api_hypothesis(): hypotheses = g.db.query(Hypothesis).all() d = {str(h.id): h.to_json() for h in hypotheses} return jsonify(**d) @api.route("/api/samples") def api_samples(): samples = g.manager.samples() d = {str(h.name): h.to_json() for h in samples} return jsonify(**d) @api.route("/api/colors") def api_colors(): return jsonify(**colors.color_dict())
[ "mobiusklein@gmail.com" ]
mobiusklein@gmail.com
aee11c008b0ca2f0155cc78007ea2d40ddb62c6b
09a6d8dbad5b92f93791948b5bf9b75f5cb2e5ce
/tests/pulse/test_rydberg.py
09b9dec3a11de3365dc2030989535323b841e771
[ "Apache-2.0" ]
permissive
PennyLaneAI/pennylane
458efd5d9457e90ada31ca2ef0fb6bb96a24e9a7
0843183ff15a013c2622af5e61fea431d18076d3
refs/heads/master
2023-09-03T17:00:43.105784
2023-09-01T16:15:07
2023-09-01T16:15:07
129,936,360
1,431
410
Apache-2.0
2023-09-14T21:30:56
2018-04-17T16:45:42
Python
UTF-8
Python
false
false
16,570
py
# Copyright 2018-2023 Xanadu Quantum Technologies 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. """ Tests for everything related to rydberg system specific functionality. """ # pylint: disable=too-few-public-methods, import-outside-toplevel, redefined-outer-name # pylint: disable=reimported, wrong-import-position import numpy as np import pytest import pennylane as qml from pennylane.pulse import rydberg_interaction, rydberg_drive from pennylane.pulse.hardware_hamiltonian import ( HardwareHamiltonian, HardwarePulse, AmplitudeAndPhase, ) from pennylane.wires import Wires from pennylane.pulse.rydberg import RydbergSettings atom_coordinates = [[0, 0], [0, 5], [5, 0], [10, 5], [5, 10], [10, 10]] wires = [1, 6, 0, 2, 4, 3] class TestRydbergInteraction: """Unit tests for the ``rydberg_interaction`` function.""" def test_attributes_and_number_of_terms(self): """Test that the attributes and the number of terms of the ``ParametrizedHamiltonian`` returned by ``rydberg_interaction`` are correct.""" Hd = rydberg_interaction(register=atom_coordinates, wires=wires, interaction_coeff=1) settings = RydbergSettings(atom_coordinates, 1) assert isinstance(Hd, HardwareHamiltonian) assert Hd.wires == Wires(wires) N = len(wires) num_combinations = N * (N - 1) / 2 # number of terms on the rydberg_interaction hamiltonian assert len(Hd.ops) == num_combinations assert Hd.pulses == [] assert Hd.settings == settings def test_wires_is_none(self): """Test that when wires is None the wires correspond to an increasing list of values with the same length as the atom coordinates.""" Hd = rydberg_interaction(register=atom_coordinates) assert Hd.wires == Wires(list(range(len(atom_coordinates)))) def test_coeffs(self): """Test that the generated coefficients are correct.""" coords = [[0, 0], [0, 1], [1, 0]] # factor (2 * np.pi) to convert between angular and standard frequency Hd = rydberg_interaction(coords, interaction_coeff=1 / (2 * np.pi)) assert Hd.coeffs == [1, 1, 1 / np.sqrt(2) ** 6] def test_different_lengths_raises_error(self): """Test that using different lengths for the wires and the register raises an error.""" with pytest.raises(ValueError, match="The length of the wires and the register must match"): _ = rydberg_interaction(register=atom_coordinates, wires=[0]) def test_max_distance(self): """Test that specifying a maximum distance affects the number of elements in the interaction term as expected.""" # This threshold will remove interactions between atoms more than 5 micrometers away from each other max_distance = 5 coords = [[0, 0], [2.5, 0], [5, 0], [6, 6]] h_wires = [1, 0, 2, 3] # Set interaction_coeff to one for easier comparison # factor (2 * np.pi) to convert between angular and standard frequency H_res = rydberg_interaction( register=coords, wires=h_wires, interaction_coeff=1 / (2 * np.pi), max_distance=max_distance, ) H_exp = rydberg_interaction( register=coords[:3], wires=h_wires[:3], interaction_coeff=1 / (2 * np.pi) ) # Only 3 of the interactions will be non-negligible assert H_res.coeffs == [2.5**-6, 5**-6, 2.5**-6] assert qml.equal(H_res([], t=5), H_exp([], t=5)) class TestRydbergDrive: """Unit tests for the ``rydberg_drive`` function""" def test_attributes_and_number_of_terms(self): """Test that the attributes and the number of terms of the ``ParametrizedHamiltonian`` returned by ``rydberg_drive`` are correct.""" Hd = rydberg_drive(amplitude=1, phase=2, detuning=3, wires=[1, 2]) assert isinstance(Hd, HardwareHamiltonian) assert Hd.settings is None assert Hd.wires == Wires([1, 2]) assert len(Hd.ops) == 3 # 2 amplitude/phase terms and one detuning term assert Hd.pulses == [HardwarePulse(1, 2, 3, [1, 2])] def test_multiple_local_drives(self): """Test that adding multiple drive terms behaves as expected""" # factors (2 * np.pi) to convert between angular and standard frequency def fa(p, t): return np.sin(p * t) / (2 * np.pi) def fb(p, t): return np.cos(p * t) H1 = rydberg_drive(amplitude=fa, phase=1, detuning=3, wires=[0, 3]) H2 = rydberg_drive(amplitude=1 / (2 * np.pi), phase=3, detuning=fb, wires=[1, 2]) Hd = H1 + H2 ops_expected = [ qml.Hamiltonian( [-0.5 * (2 * np.pi), -0.5 * (2 * np.pi), 0.5 * (2 * np.pi), 0.5 * (2 * np.pi)], [qml.Identity(0), qml.Identity(3), qml.PauliZ(0), qml.PauliZ(3)], ), qml.Hamiltonian([0.5, 0.5], [qml.PauliX(1), qml.PauliX(2)]), qml.Hamiltonian([-0.5, -0.5], [qml.PauliY(1), qml.PauliY(2)]), qml.Hamiltonian([0.5, 0.5], [qml.PauliX(0), qml.PauliX(3)]), qml.Hamiltonian([-0.5, -0.5], [qml.PauliY(0), qml.PauliY(3)]), qml.Hamiltonian( [-0.5 * (2 * np.pi), -0.5 * (2 * np.pi), 0.5 * (2 * np.pi), 0.5 * (2 * np.pi)], [qml.Identity(1), qml.Identity(2), qml.PauliZ(1), qml.PauliZ(2)], ), ] coeffs_expected = [ 3, np.cos(3), np.sin(3), AmplitudeAndPhase(np.cos, fa, 1), AmplitudeAndPhase(np.sin, fa, 1), fb, ] H_expected = HardwareHamiltonian(coeffs_expected, ops_expected) # structure of Hamiltonian is as expected assert isinstance(Hd, HardwareHamiltonian) assert Hd.wires == Wires([0, 3, 1, 2]) assert Hd.settings is None assert len(Hd.ops) == 6 # 2 terms for amplitude/phase and one detuning for each drive # coefficients are correct # Callable coefficients are shifted to the end of the list. assert Hd.coeffs[0:3] == [3, np.cos(3), np.sin(3)] assert isinstance(Hd.coeffs[3], AmplitudeAndPhase) assert isinstance(Hd.coeffs[4], AmplitudeAndPhase) assert Hd.coeffs[5] is fb # pulses were added correctly assert len(Hd.pulses) == 2 assert Hd.pulses == H1.pulses + H2.pulses # Hamiltonian is as expected assert qml.equal(Hd([0.5, -0.5], t=5), H_expected([0.5, -0.5], t=5)) def test_no_amplitude(self): """Test that when amplitude is not specified, the drive term is correctly defined.""" # factors (2 * np.pi) to convert between angular and standard frequency def f(p, t): return np.cos(p * t) / (2 * np.pi) Hd = rydberg_drive(amplitude=0, phase=1, detuning=f, wires=[0, 3]) ops_expected = [ qml.Hamiltonian( [-0.5 * (2 * np.pi), -0.5 * (2 * np.pi), 0.5 * (2 * np.pi), 0.5 * (2 * np.pi)], [qml.Identity(0), qml.Identity(3), qml.PauliZ(0), qml.PauliZ(3)], ) ] coeffs_expected = [f] H_expected = HardwareHamiltonian(coeffs_expected, ops_expected) assert qml.equal(Hd([0.1], 10), H_expected([0.1], 10)) assert isinstance(Hd, HardwareHamiltonian) assert Hd.wires == Wires([0, 3]) assert Hd.settings is None assert len(Hd.coeffs) == 1 assert Hd.coeffs[0] is f assert len(Hd.ops) == 1 assert qml.equal(Hd.ops[0], ops_expected[0]) def test_no_detuning(self): """Test that when detuning not specified, the drive term is correctly defined.""" def f(p, t): return np.cos(p * t) Hd = rydberg_drive(amplitude=f, phase=1, detuning=0, wires=[0, 3]) ops_expected = [ qml.Hamiltonian([0.5, 0.5], [qml.PauliX(0), qml.PauliX(3)]), qml.Hamiltonian([-0.5, -0.5], [qml.PauliY(0), qml.PauliY(3)]), ] coeffs_expected = [ AmplitudeAndPhase(np.cos, f, 1), AmplitudeAndPhase(np.sin, f, 1), ] H_expected = HardwareHamiltonian(coeffs_expected, ops_expected) assert qml.equal(Hd([0.1], 10), H_expected([0.1], 10)) assert isinstance(Hd, HardwareHamiltonian) assert Hd.wires == Wires([0, 3]) assert Hd.settings is None assert all(isinstance(coeff, AmplitudeAndPhase) for coeff in Hd.coeffs) assert len(Hd.coeffs) == 2 assert all(qml.equal(op, op_expected) for op, op_expected in zip(Hd.ops, ops_expected)) def test_no_amplitude_no_detuning(self): """Test that the correct error is raised if both amplitude and detuning are trivial.""" with pytest.raises(ValueError, match="Expected non-zero value for at least one of either"): _ = rydberg_drive(0, np.pi, 0, wires=[0]) # For rydberg settings test register0 = [[0.0, 1.0], [0.0, 2.0]] register1 = [[2.0, 0.3], [1.0, 4.0], [0.5, 0.4]] class TestRydbergSettings: """Unit tests for TransmonSettings dataclass""" def test_init(self): """Test the initialization of the ``RydbergSettings`` class.""" settings = RydbergSettings(register0) assert settings.register == register0 assert settings.interaction_coeff == 0.0 def test_equal(self): """Test the ``__eq__`` method of the ``RydbergSettings`` class.""" settings0 = RydbergSettings(register0) settings1 = RydbergSettings(register1, interaction_coeff=2.0) settings2 = RydbergSettings(register0, interaction_coeff=0.0) assert settings0 != settings1 assert settings1 != settings2 assert settings0 == settings2 def test_add_two_settings( self, ): """Test that two RydbergSettings are correctly added""" settings0 = RydbergSettings(register0, interaction_coeff=2.0) settings1 = None settings01 = settings0 + settings1 settings10 = settings1 + settings0 assert settings01.register == register0 assert settings01.interaction_coeff == 2.0 assert settings10.register == register0 assert settings10.interaction_coeff == 2.0 # pylint: disable=unused-variable def test_raises_error_two_interaction_terms( self, ): """Raises error when attempting to add two non-trivial RydbergSettings""" settings0 = RydbergSettings(register0) settings1 = RydbergSettings(register1) with pytest.raises(ValueError, match="Cannot add two"): res = settings0 + settings1 class TestIntegration: """Integration tests for Rydberg system Hamiltonians.""" @pytest.mark.jax def test_jitted_qnode(self): """Test that a Rydberg ensemble can be simulated within a jitted qnode.""" import jax import jax.numpy as jnp Hd = rydberg_interaction(register=atom_coordinates, wires=wires) def fa(p, t): return jnp.polyval(p, t) def fb(p, t): return p[0] * jnp.sin(p[1] * t) Ht = rydberg_drive(amplitude=fa, phase=0, detuning=fb, wires=1) dev = qml.device("default.qubit", wires=wires) ts = jnp.array([0.0, 3.0]) H_obj = sum(qml.PauliZ(i) for i in range(2)) @qml.qnode(dev, interface="jax") def qnode(params): qml.evolve(Hd + Ht)(params, ts) return qml.expval(H_obj) @jax.jit @qml.qnode(dev, interface="jax") def qnode_jit(params): qml.evolve(Hd + Ht)(params, ts) return qml.expval(H_obj) params = (jnp.ones(5), jnp.array([1.0, jnp.pi])) res = qnode(params) res_jit = qnode_jit(params) assert isinstance(res, jax.Array) assert np.allclose(res, res_jit) @pytest.mark.jax def test_jitted_qnode_multidrive(self): """Test that a Rydberg ensemble with multiple drive terms can be executed within a jitted qnode.""" import jax import jax.numpy as jnp Hd = rydberg_interaction(register=atom_coordinates, wires=wires) def fa(p, t): return jnp.polyval(p, t) def fb(p, t): return p[0] * jnp.sin(p[1] * t) def fc(p, t): return p[0] * jnp.sin(t) + jnp.cos(p[1] * t) def fd(p, t): return p * jnp.cos(t) H1 = rydberg_drive(amplitude=fa, phase=0, detuning=fb, wires=wires) H2 = rydberg_drive(amplitude=fc, phase=3 * jnp.pi, detuning=0, wires=4) H3 = rydberg_drive(amplitude=0, phase=0, detuning=fd, wires=[3, 0]) dev = qml.device("default.qubit", wires=wires) ts = jnp.array([0.0, 3.0]) H_obj = sum(qml.PauliZ(i) for i in range(2)) @qml.qnode(dev, interface="jax") def qnode(params): qml.evolve(Hd + H1 + H2 + H3)(params, ts) return qml.expval(H_obj) @jax.jit @qml.qnode(dev, interface="jax") def qnode_jit(params): qml.evolve(Hd + H1 + H2 + H3)(params, ts) return qml.expval(H_obj) params = ( jnp.ones(5), jnp.array([1.0, jnp.pi]), jnp.array([jnp.pi / 2, 0.5]), jnp.array(-0.5), ) res = qnode(params) res_jit = qnode_jit(params) assert isinstance(res, jax.Array) assert np.allclose(res, res_jit) @pytest.mark.jax def test_jitted_qnode_all_coeffs_callable(self): """Test that a Rydberg ensemble can be simulated within a jitted qnode when all coeffs are callable.""" import jax import jax.numpy as jnp H_drift = rydberg_interaction(register=atom_coordinates, wires=wires) def fa(p, t): return jnp.polyval(p, t) def fb(p, t): return p[0] * jnp.sin(p[1] * t) def fc(p, t): return p[0] * jnp.sin(t) + jnp.cos(p[1] * t) H_drive = rydberg_drive(amplitude=fa, phase=fb, detuning=fc, wires=1) dev = qml.device("default.qubit", wires=wires) ts = jnp.array([0.0, 3.0]) H_obj = sum(qml.PauliZ(i) for i in range(2)) @qml.qnode(dev, interface="jax") def qnode(params): qml.evolve(H_drift + H_drive)(params, ts) return qml.expval(H_obj) @jax.jit @qml.qnode(dev, interface="jax") def qnode_jit(params): qml.evolve(H_drift + H_drive)(params, ts) return qml.expval(H_obj) params = (jnp.ones(5), jnp.array([1.0, jnp.pi]), jnp.array([jnp.pi / 2, 0.5])) res = qnode(params) res_jit = qnode_jit(params) assert isinstance(res, jax.Array) assert np.allclose(res, res_jit) @pytest.mark.jax def test_pennylane_and_exact_solution_correspond(self): """Test that the results of PennyLane simulation match (within reason) the exact solution""" import jax import jax.numpy as jnp def exact(H, H_obj, t): psi0 = jnp.eye(2 ** len(H.wires))[0] U_exact = jax.scipy.linalg.expm(-1j * t * qml.matrix(H([], 1))) return ( psi0 @ U_exact.conj().T @ qml.matrix(H_obj, wire_order=[0, 1, 2]) @ U_exact @ psi0 ) default_qubit = qml.device("default.qubit", wires=3) coordinates = [[0, 0], [0, 5], [5, 0]] H_i = qml.pulse.rydberg_interaction(coordinates) H = H_i + qml.pulse.rydberg_drive(3, 2, 4, [0, 1, 2]) H_obj = qml.PauliZ(0) @jax.jit @qml.qnode(default_qubit, interface="jax") def circuit(t): qml.evolve(H)([], t) return qml.expval(H_obj) t = jnp.linspace(0.05, 1.55, 151) circuit_results = np.array([circuit(_t) for _t in t]) exact_results = np.array([exact(H, H_obj, _t) for _t in t]) # all results are approximately the same np.allclose(circuit_results, exact_results, atol=0.07)
[ "noreply@github.com" ]
PennyLaneAI.noreply@github.com
f1627ae27f127f6561a052c0246ee3cff0d0491e
b84955813634b3e64a82bc9c9bef13d2b596e4db
/us_addresses.py
fabfdb2b11e79431c34aab25c462521541da4a27
[]
no_license
henocdz/postalcodes
6cf5157c5f6946a42abad875b0d6bddfd77ec7c2
3f95618b2423b6f0fd9970b7b92f8f53322d28d7
refs/heads/master
2021-01-03T04:48:22.295053
2020-02-14T16:25:13
2020-02-14T16:25:13
239,929,346
0
1
null
null
null
null
UTF-8
Python
false
false
4,442
py
import json from geopy.geocoders import GoogleV3 import concurrent.futures MAPS_API_KEY = "" STATES = { "AA": "Armed Forces Americas", "AE": "Armed Forces Middle East", "AK": "Alaska", "AL": "Alabama", "AP": "Armed Forces Pacific", "AR": "Arkansas", "AS": "American Samoa", "AZ": "Arizona", "CA": "California", "CO": "Colorado", "CT": "Connecticut", "DC": "District of Columbia", "DE": "Delaware", "FL": "Florida", "FM": "Federated Stated of Micronesia", "GA": "Georgia", "GU": "Guam", "HI": "Hawaii", "IA": "Iowa", "ID": "Idaho", "IL": "Illinois", "IN": "Indiana", "KS": "Kansas", "KY": "Kentucky", "LA": "Louisiana", "MA": "Massachusetts", "MD": "Maryland", "ME": "Maine", "MH": "Marshall Islands", "MI": "Michigan", "MN": "Minnesota", "MO": "Missouri", "MP": "Northern Mariana Islands", "MS": "Mississippi", "MT": "Montana", "NC": "North Carolina", "ND": "North Dakota", "NE": "Nebraska", "NH": "New Hampshire", "NJ": "New Jersey", "NM": "New Mexico", "NV": "Nevada", "NY": "New York", "OH": "Ohio", "OK": "Oklahoma", "OR": "Oregon", "PA": "Pennsylvania", "PR": "Puerto Rico", "PW": "Palau", "RI": "Rhode Island", "SC": "South Carolina", "SD": "South Dakota", "TN": "Tennessee", "TX": "Texas", "UT": "Utah", "VA": "Virginia", "VI": "Virgin Islands", "VT": "Vermont", "WA": "Washington", "WI": "Wisconsin", "WV": "West Virginia", "WY": "Wyoming", } raw_us_postal_codes_file = "us_zipcodes.json" us_addresses_output = "addresses_us.json" us_city_timezones_file = "us_timezones.json" with open(us_city_timezones_file, "r") as pc: TIME_ZONES = json.loads(pc.read()) with open(raw_us_postal_codes_file, "r") as usf: postal_codes = json.loads(usf.read()) city_timezones = dict() state_timezones = dict() state_tzs = dict(PR="America/Puerto_Rico", VI="America/St_Thomas") last_pc = 0 states = dict() cities = set() for i, (postal_code, info) in enumerate(postal_codes.items()): state_code = info["state"] state_name = STATES[state_code] raw_city_name = info["city"] city_name = " ".join([cc.capitalize() for cc in raw_city_name.split(" ")]) state_data = states.setdefault( state_code, dict(code=state_code, name=state_name, cities={}) ) city_data = state_data["cities"].setdefault( city_name, dict(name=city_name, towns=[], time_zone=None, postal_codes=[]), ) city_key = f"{city_name} {state_code}" cities.add(city_key) timezone = city_data.get("time_zone", None) if timezone is None: try: timezone = TIME_ZONES[city_key] except KeyError: timezone = "America/Denver" city_data["time_zone"] = timezone city_data["postal_codes"].append(postal_code) pc = round((i + 1) * 100 / 41697, 1) per = f"{pc}%" if pc > last_pc: last_pc = pc print(per) # def get_timezone(city_key): # try: # geolocator = GoogleV3(api_key=MAPS_API_KEY, timeout=5) # location = geolocator.geocode(city_key) # tz = geolocator.reverse_timezone(location.point) # timezone = tz.raw["timeZoneId"] # except Exception: # timezone = "" # return timezone # with concurrent.futures.ThreadPoolExecutor(max_workers=30) as executor: # fs = dict() # for city_key in cities: # if city_key not in TIME_ZONES: # fs[executor.submit(get_timezone, city_key=city_key)] = city_key # last_pc = 0 # i = 0 # for future in concurrent.futures.as_completed(fs): # city = fs[future] # tz = future.result() # if tz: # TIME_ZONES[city] = tz # pc = round((i + 1) * 100 / len(cities), 1) # per = f"{pc}%" # if pc > last_pc: # last_pc = pc # i += 1 # with open(us_city_timezones_file, "w") as tzoutput: # tzoutput.write(json.dumps(TIME_ZONES)) with open(us_addresses_output, "w") as output: for _, state in states.items(): cities = list(state["cities"].values()) state["cities"] = cities output.write(json.dumps(list(states.values()), ensure_ascii=True))
[ "henocdz@gmail.com" ]
henocdz@gmail.com
8bc19bc8b5f4e92d2e69058ec02dacb602eba280
36273a4ce1e01bdd3d80c71e22fb5fae751a264c
/elementary/first_word.py
dc268bd1542686110339791a8ac293dd90665da6
[]
no_license
pavoli/checkIO
63e0e347a0a4800626e5d2d1be07f53e86de070f
27578ce460c45a82bd549206a4260fc3f9ec711b
refs/heads/master
2022-02-07T08:26:40.509503
2019-07-11T06:54:54
2019-07-11T06:54:54
114,545,792
0
0
null
null
null
null
UTF-8
Python
false
false
411
py
# -*- coding: utf-8 -*- import re #s = 'Hello world' #s = 'greetings, friends' #s = ' a word ' #s = "don't touch it" #s = "... and so on ..." s = "Hello.World" def first_word(str): new_str = str.replace(',', ' ') new_str = new_str.replace('.', ' ') for i in new_str.split(' '): if re.search('^([a-z]|[A-Z])+',i): return i if __name__ == '__main__': print(first_word(s))
[ "pavel.olifer@gmail.com" ]
pavel.olifer@gmail.com
3720c7d48077bc2eb852dfeb905da7a06b79d172
463c8ba5baad086d37819804af4ee10f43ab6dd5
/Algorithm/190826/서울3반_홍수경_4880_토너먼트 카드게임.py
5e28e22ac950f854a850cfbf5df5597d724a4a28
[]
no_license
sooya14/TIL
dbbb0608d45ce273ddef6f7cea1b1195285f269d
232b0d38d8f6ee2e6e5517bfd6a2a15cf1000dad
refs/heads/master
2023-01-11T17:12:39.370178
2020-05-11T12:06:41
2020-05-11T12:06:41
195,916,241
0
0
null
2023-01-05T18:22:56
2019-07-09T02:17:42
Jupyter Notebook
UTF-8
Python
false
false
231
py
import sys sys.stdin = open('4880_토너먼트 카드게임.txt', 'r') def gbb(people): T = int(input()) for tc in range(T): num = int(input()) people = list(map(int, input().split())) print(tc+1, num, people)
[ "soosmile9653@gmail.com" ]
soosmile9653@gmail.com
9493189223318dadd253d8cd0089fddd799df474
60e38d3122cfb18cf8901e0d7fba02ef2a32affa
/notebooks/__code/ui_registration_profile_settings.py
557057a50a472250f2e9186f5148506fa616bf90
[ "BSD-3-Clause" ]
permissive
earnestdl/python_notebooks
ac11b40d9d5e721b947b083b2f4c301079f206a8
4ef31711b70b90cf621e9e9d094fa2a43eeeae16
refs/heads/master
2023-03-12T19:41:44.229158
2021-02-22T15:41:57
2021-02-22T15:41:57
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,331
py
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file '/Users/j35/git/python_notebooks/notebooks/ui/ui_registration_profile_settings.ui' # # Created by: PyQt5 UI code generator 5.9.2 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(776, 184) self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.verticalLayout = QtWidgets.QVBoxLayout(self.centralwidget) self.verticalLayout.setObjectName("verticalLayout") self.horizontalLayout = QtWidgets.QHBoxLayout() self.horizontalLayout.setObjectName("horizontalLayout") self.label = QtWidgets.QLabel(self.centralwidget) self.label.setObjectName("label") self.horizontalLayout.addWidget(self.label) self.spinBox = QtWidgets.QSpinBox(self.centralwidget) self.spinBox.setMinimum(3) self.spinBox.setProperty("value", 20) self.spinBox.setObjectName("spinBox") self.horizontalLayout.addWidget(self.spinBox) self.plainTextEdit = QtWidgets.QPlainTextEdit(self.centralwidget) self.plainTextEdit.setMinimumSize(QtCore.QSize(300, 60)) self.plainTextEdit.setMaximumSize(QtCore.QSize(16777215, 50)) self.plainTextEdit.setReadOnly(True) self.plainTextEdit.setObjectName("plainTextEdit") self.horizontalLayout.addWidget(self.plainTextEdit) self.verticalLayout.addLayout(self.horizontalLayout) self.horizontalLayout_2 = QtWidgets.QHBoxLayout() self.horizontalLayout_2.setObjectName("horizontalLayout_2") spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.horizontalLayout_2.addItem(spacerItem) self.ok_button = QtWidgets.QPushButton(self.centralwidget) self.ok_button.setObjectName("ok_button") self.horizontalLayout_2.addWidget(self.ok_button) self.verticalLayout.addLayout(self.horizontalLayout_2) MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 776, 22)) self.menubar.setObjectName("menubar") MainWindow.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(MainWindow) self.statusbar.setObjectName("statusbar") MainWindow.setStatusBar(self.statusbar) self.retranslateUi(MainWindow) self.ok_button.clicked.connect(MainWindow.ok_button_clicked) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow")) self.label.setText(_translate("MainWindow", "Maximum Delta Pixel Offset")) self.plainTextEdit.setPlainText(_translate("MainWindow", "Maximum Pixel offset values allowed between two images. If the algorithm returns an offset value greater than this value, the program will use the previous offset value.\n" "")) self.ok_button.setText(_translate("MainWindow", "OK"))
[ "bilheuxjm@ornl.gov" ]
bilheuxjm@ornl.gov
0838708c369b20173d3a097231fd65eda479e366
368c66467b78adf62da04cb0b8cedd2ef37bb127
/SW expert/python/회문2.py
c76690313edabce32dc132e0b0a60e8d53b94f55
[]
no_license
DJHyun/Algorithm
c8786ddcd8b5693fc9b3b4721fdf1eeda21611c5
fd6ae800886dac4ec5ff6cf2618bc2c839a76e7a
refs/heads/master
2020-07-30T16:32:49.344329
2020-02-25T07:59:34
2020-02-25T07:59:34
210,289,983
0
0
null
null
null
null
UTF-8
Python
false
false
1,193
py
import sys sys.stdin = open("회문2.txt", "r") def my_palindrome(a): for i in range(len(a) // 2): if a[i] != a[len(a) - 1 - i]: return False return True for test_case in range(1,11): input() sh = [] sv = [] result = 0 for i in range(100): sh.append(list(input())) for i in range(100): sv.append([]) for j in range(100): sv[i].append(sh[j][i]) for i in sh: for j in range(len(i)): for d in range(len(i)-1,j,-1): if len(i[j:d+1]) > result: if my_palindrome(i[j:d+1]): result = len(i[j:d+1]) break else: break for i in sv: for j in range(len(i)): for d in range(len(i)-1,j,-1): if len(i[j:d+1]) > result: if my_palindrome(i[j:d+1]): result = len(i[j:d+1]) break else: break print(f'#{test_case} {result}')
[ "djestiny4444@naver.com" ]
djestiny4444@naver.com
baea61977f014066c06cd7432a185fe8ee8c8fe4
4fd35f92c0c5fbdab85da5d3583ade2a838e7332
/services/files.py
7e06380031b09b0ec77f58670aa618ab67ec40df
[]
no_license
Finding-Articles-Using-Snippets/AFUS-Backend
0551ff53a5f9f9f2ded30e4a81a0970ef73c7e8a
80f676976e07982e5ed98456c49864ea4ebc1339
refs/heads/main
2023-02-04T20:48:38.217037
2020-12-18T20:37:23
2020-12-18T20:37:23
314,789,145
0
0
null
null
null
null
UTF-8
Python
false
false
119
py
def getPdf(user_id, file_id): text = '' return text def getDictionary(user_id): dict = {} return dict
[ "ajinkyataranekar@gmail.com" ]
ajinkyataranekar@gmail.com
d5d6a4febd04864dbf24cbed11cb887994e90f9d
d8422247ecbe450c75df45dcf2c92fb4438b65af
/horizon/openstack_dashboard/dashboards/network/vpn/forms.py
77329021e3407151bd02ae7f4286d402294cf101
[ "Apache-2.0" ]
permissive
yianjiajia/openstack_horizon
deb9beca534b494b587ae401904c84ddbed64c4a
9e36a4c3648ef29d0df6912d990465f51d6124a6
refs/heads/master
2016-09-12T21:34:25.718377
2016-04-28T05:29:56
2016-04-28T05:29:56
57,273,157
0
0
null
null
null
null
UTF-8
Python
false
false
18,783
py
# Copyright 2013, Mirantis Inc # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import logging from django.core.urlresolvers import reverse from django.utils.translation import ugettext_lazy as _ from horizon import exceptions from horizon import forms from horizon import messages from openstack_dashboard import api LOG = logging.getLogger(__name__) class UpdateVPNCredential(forms.SelfHandlingForm): vpncredential_id = forms.CharField( label=_("ID"),widget=forms.TextInput(attrs={'readonly': 'readonly'})) name = forms.CharField(max_length=80, label=_("Name"), required=False) description = forms.CharField( required=False, max_length=80, label=_("Description")) failure_url = 'horizon:network:vpn:index' def handle(self, request, context): try: data = {'vpn_credential': {'name': context['name'], 'description': context['description'], }} vpncredential = api.vpn.vpncredential_update( request, context['vpncredential_id'], **data) msg = (_('SSL VPN Credential %s was successfully updated.') % context['name']) LOG.debug(msg) messages.success(request, msg) # operation log config = _('Credential Name: %s') %context['name'] api.logger.Logger(request).create(resource_type='vpn', action_name='Update VPN Credential', resource_name='vpn', config=config, status='Success') return vpncredential except Exception as e: msg = _('Failed to update VPN Credential %s') % context['name'] LOG.info('%s: %s' % (msg, e)) redirect = reverse(self.failure_url) exceptions.handle(request, msg, redirect=redirect) # operation log api.logger.Logger(request).create(resource_type='vpn', action_name='Update VPN Credential', resource_name='vpn', config=_('Failed to update VPN Credential %s') % context['name'], status='Error') class UpdateSSLVPNConnection(forms.SelfHandlingForm): sslvpnconnection_id = forms.CharField(label=_("ID"), widget=forms.TextInput(attrs={'readonly': 'readonly'})) name = forms.CharField(max_length=80, label=_("Name"), required=False) description = forms.CharField( required=False, max_length=80, label=_("Description")) admin_state_up = forms.BooleanField(label=_("Admin State"), required=False) failure_url = 'horizon:network:vpn:index' def handle(self, request, context): try: data = {'ssl_vpn_connection': {'name': context['name'], 'description': context['description'], 'admin_state_up': context['admin_state_up'], }} sslvpnconnection = api.vpn.sslvpnconnection_update( request, context['sslvpnconnection_id'], **data) msg = (_('SSL VPN Connection %s was successfully updated.') % context['name']) LOG.debug(msg) messages.success(request, msg) # operation log config = _('VPN Connection Name: %s') %context['name'] api.logger.Logger(request).create(resource_type='vpn', action_name='Update VPN Connection', resource_name='vpn', config=config, status='Success') return sslvpnconnection except Exception as e: msg = (_('Failed to update SSL VPN Connection %s') % context['name']) LOG.info('%s: %s' % (msg, e)) redirect = reverse(self.failure_url) exceptions.handle(request, msg, redirect=redirect)\ # operation log api.logger.Logger(request).create(resource_type='vpn', action_name='Update VPN Connection', resource_name='vpn', config=_('Failed to update SSL ' 'VPN Connection %s') % context['name'], status='Error') class UpdateVPNService(forms.SelfHandlingForm): name = forms.CharField(max_length=80, label=_("Name"), required=False) vpnservice_id = forms.CharField( label=_("ID"), widget=forms.TextInput(attrs={'readonly': 'readonly'})) description = forms.CharField( required=False, max_length=80, label=_("Description")) admin_state_up = forms.ChoiceField(choices=[(True, _('UP')), (False, _('DOWN'))], label=_("Admin State")) failure_url = 'horizon:network:vpn:index' def handle(self, request, context): context['admin_state_up'] = (context['admin_state_up'] == 'True') try: data = {'vpnservice': {'name': context['name'], 'description': context['description'], 'admin_state_up': context['admin_state_up'], }} vpnservice = api.vpn.vpnservice_update( request, context['vpnservice_id'], **data) msg = (_('VPN Service %s was successfully updated.') % context['name']) LOG.debug(msg) messages.success(request, msg) # operation log config = _('VPN Service Name: %s') %context['name'] api.logger.Logger(request).create(resource_type='vpn', action_name='Update VPN Service', resource_name='vpn', config=config, status='Success') return vpnservice except Exception as e: msg = _('Failed to update VPN Service %s') % context['name'] LOG.info('%s: %s' % (msg, e)) redirect = reverse(self.failure_url) exceptions.handle(request, msg, redirect=redirect) # operation log api.logger.Logger(request).create(resource_type='vpn', action_name='Update VPN Service', resource_name='vpn', config=_('Failed to update VPN Service %s') % context['name'], status='Error') class UpdateIKEPolicy(forms.SelfHandlingForm): name = forms.CharField(max_length=80, label=_("Name"), required=False) ikepolicy_id = forms.CharField( label=_("ID"), widget=forms.TextInput(attrs={'readonly': 'readonly'})) description = forms.CharField( required=False, max_length=80, label=_("Description")) # Currently this field has only one choice, so mark it as readonly. auth_algorithm = forms.ChoiceField( label=_("Authorization algorithm"), choices=[('sha1', _('sha1'))], widget=forms.Select(attrs={'readonly': 'readonly'})) encryption_algorithm = forms.ChoiceField( label=_("Encryption algorithm"), choices=[('3des', _('3des')), ('aes-128', _('aes-128')), ('aes-192', _('aes-192')), ('aes-256', _('aes-256'))]) ike_version = forms.ChoiceField( label=_("IKE version"), choices=[('v1', _('v1')), ('v2', _('v2'))]) # Currently this field has only one choice, so mark it as readonly. lifetime_units = forms.ChoiceField( label=_("Lifetime units for IKE keys"), choices=[('seconds', _('seconds'))], widget=forms.Select(attrs={'readonly': 'readonly'})) lifetime_value = forms.IntegerField( min_value=60, label=_("Lifetime value for IKE keys"), help_text=_("Equal to or greater than 60")) pfs = forms.ChoiceField( label=_("Perfect Forward Secrecy"), choices=[('group2', _('group2')), ('group5', _('group5')), ('group14', _('group14'))]) # Currently this field has only one choice, so mark it as readonly. phase1_negotiation_mode = forms.ChoiceField( label=_("IKE Phase1 negotiation mode"), choices=[('main', 'main')], widget=forms.Select(attrs={'readonly': 'readonly'})) failure_url = 'horizon:network:vpn:index' def handle(self, request, context): try: data = {'ikepolicy': {'name': context['name'], 'description': context['description'], 'auth_algorithm': context['auth_algorithm'], 'encryption_algorithm': context['encryption_algorithm'], 'ike_version': context['ike_version'], 'lifetime': {'units': context['lifetime_units'], 'value': context['lifetime_value']}, 'pfs': context['pfs'], 'phase1_negotiation_mode': context['phase1_negotiation_mode'], }} ikepolicy = api.vpn.ikepolicy_update( request, context['ikepolicy_id'], **data) msg = (_('IKE Policy %s was successfully updated.') % context['name']) LOG.debug(msg) messages.success(request, msg) return ikepolicy except Exception as e: msg = _('Failed to update IKE Policy %s') % context['name'] LOG.info('%s: %s' % (msg, e)) redirect = reverse(self.failure_url) exceptions.handle(request, msg, redirect=redirect) class UpdateIPSecPolicy(forms.SelfHandlingForm): name = forms.CharField(max_length=80, label=_("Name"), required=False) ipsecpolicy_id = forms.CharField( label=_("ID"), widget=forms.TextInput(attrs={'readonly': 'readonly'})) description = forms.CharField( required=False, max_length=80, label=_("Description")) # Currently this field has only one choice, so mark it as readonly. auth_algorithm = forms.ChoiceField( label=_("Authorization algorithm"), choices=[('sha1', _('sha1'))], widget=forms.TextInput(attrs={'readonly': 'readonly'})) encapsulation_mode = forms.ChoiceField( label=_("Encapsulation mode"), choices=[('tunnel', _('tunnel')), ('transport', _('transport'))]) encryption_algorithm = forms.ChoiceField( label=_("Encryption algorithm"), choices=[('3des', _('3des')), ('aes-128', _('aes-128')), ('aes-192', _('aes-192')), ('aes-256', _('aes-256'))]) # Currently this field has only one choice, so mark it as readonly. lifetime_units = forms.ChoiceField( label=_("Lifetime units"), choices=[('seconds', _('seconds'))], widget=forms.Select(attrs={'readonly': 'readonly'})) lifetime_value = forms.IntegerField( min_value=60, label=_("Lifetime value"), help_text=_("Equal to or greater than 60")) pfs = forms.ChoiceField( label=_("Perfect Forward Secrecy"), choices=[('group2', _('group2')), ('group5', _('group5')), ('group14', _('group14'))]) transform_protocol = forms.ChoiceField( label=_("Transform Protocol"), choices=[('esp', _('esp')), ('ah', _('ah')), ('ah-esp', _('ah-esp'))]) failure_url = 'horizon:network:vpn:index' def handle(self, request, context): try: data = {'ipsecpolicy': {'name': context['name'], 'description': context['description'], 'auth_algorithm': context['auth_algorithm'], 'encapsulation_mode': context['encapsulation_mode'], 'encryption_algorithm': context['encryption_algorithm'], 'lifetime': {'units': context['lifetime_units'], 'value': context['lifetime_value']}, 'pfs': context['pfs'], 'transform_protocol': context['transform_protocol'], }} ipsecpolicy = api.vpn.ipsecpolicy_update( request, context['ipsecpolicy_id'], **data) msg = (_('IPSec Policy %s was successfully updated.') % context['name']) LOG.debug(msg) messages.success(request, msg) return ipsecpolicy except Exception as e: msg = _('Failed to update IPSec Policy %s') % context['name'] LOG.info('%s: %s' % (msg, e)) redirect = reverse(self.failure_url) exceptions.handle(request, msg, redirect=redirect) class UpdateIPSecSiteConnection(forms.SelfHandlingForm): name = forms.CharField(max_length=80, label=_("Name"), required=False) ipsecsiteconnection_id = forms.CharField( label=_("ID"), widget=forms.TextInput(attrs={'readonly': 'readonly'})) description = forms.CharField( required=False, max_length=80, label=_("Description")) peer_address = forms.IPField( label=_("Peer gateway public IPv4/IPv6 Address or FQDN"), help_text=_("Peer gateway public IPv4/IPv6 address or FQDN for " "the VPN Connection"), version=forms.IPv4 | forms.IPv6, mask=False) peer_id = forms.IPField( label=_("Peer router identity for authentication (Peer ID)"), help_text=_("Peer router identity for authentication. " "Can be IPv4/IPv6 address, e-mail, key ID, or FQDN"), version=forms.IPv4 | forms.IPv6, mask=False) peer_cidrs = forms.MultiIPField( label=_("Remote peer subnet(s)"), help_text=_("Remote peer subnet(s) address(es) " "with mask(s) in CIDR format " "separated with commas if needed " "(e.g. 20.1.0.0/24, 21.1.0.0/24)"), version=forms.IPv4 | forms.IPv6, mask=True) psk = forms.CharField( max_length=80, label=_("Pre-Shared Key (PSK) string")) mtu = forms.IntegerField( min_value=68, label=_("Maximum Transmission Unit size for the connection"), help_text=_("Equal to or greater than 68 if the local subnet is IPv4. " "Equal to or greater than 1280 if the local subnet " "is IPv6.")) dpd_action = forms.ChoiceField( label=_("Dead peer detection actions"), choices=[('hold', _('hold')), ('clear', _('clear')), ('disabled', _('disabled')), ('restart', _('restart')), ('restart-by-peer', _('restart-by-peer'))]) dpd_interval = forms.IntegerField( min_value=1, label=_("Dead peer detection interval"), help_text=_("Valid integer")) dpd_timeout = forms.IntegerField( min_value=1, label=_("Dead peer detection timeout"), help_text=_("Valid integer greater than the DPD interval")) initiator = forms.ChoiceField( label=_("Initiator state"), choices=[('bi-directional', _('bi-directional')), ('response-only', _('response-only'))]) admin_state_up = forms.ChoiceField(choices=[(True, _('UP')), (False, _('DOWN'))], label=_("Admin State")) failure_url = 'horizon:network:vpn:index' def handle(self, request, context): context['admin_state_up'] = (context['admin_state_up'] == 'True') try: data = {'ipsec_site_connection': {'name': context['name'], 'description': context['description'], 'peer_address': context['peer_address'], 'peer_id': context['peer_id'], 'peer_cidrs': context[ 'peer_cidrs'].replace(" ", "").split(","), 'psk': context['psk'], 'mtu': context['mtu'], 'dpd': {'action': context['dpd_action'], 'interval': context['dpd_interval'], 'timeout': context['dpd_timeout']}, 'initiator': context['initiator'], 'admin_state_up': context['admin_state_up'], }} ipsecsiteconnection = api.vpn.ipsecsiteconnection_update( request, context['ipsecsiteconnection_id'], **data) msg = (_('IPSec Site Connection %s was successfully updated.') % context['name']) LOG.debug(msg) messages.success(request, msg) # operation log config = _('IPSec Site Connection Name: %s') %context['name'] api.logger.Logger(request).create(resource_type='vpn', action_name=' Update IPSec Site Connection', resource_name='vpn', config=config, status='Success') return ipsecsiteconnection except Exception as e: msg = (_('Failed to update IPSec Site Connection %s') % context['name']) LOG.info('%s: %s' % (msg, e)) redirect = reverse(self.failure_url) exceptions.handle(request, msg, redirect=redirect) # operation log api.logger.Logger(request).create(resource_type='vpn', action_name=' Update IPSec Site Connection', resource_name='vpn', config=_('Failed to update IPSec ' 'Site Connection %s')% context['name'], status='Error')
[ "yanjj@syscloud.cn" ]
yanjj@syscloud.cn
4ebaf23e1ab2fff8d10ecedfe6fb866c36b15ff4
83de24182a7af33c43ee340b57755e73275149ae
/aliyun-python-sdk-elasticsearch/aliyunsdkelasticsearch/request/v20170613/UpdateInstanceChargeTypeRequest.py
cab978c843cbe65c84557ce41d927fee367195fd
[ "Apache-2.0" ]
permissive
aliyun/aliyun-openapi-python-sdk
4436ca6c57190ceadbc80f0b1c35b1ab13c00c7f
83fd547946fd6772cf26f338d9653f4316c81d3c
refs/heads/master
2023-08-04T12:32:57.028821
2023-08-04T06:00:29
2023-08-04T06:00:29
39,558,861
1,080
721
NOASSERTION
2023-09-14T08:51:06
2015-07-23T09:39:45
Python
UTF-8
Python
false
false
1,944
py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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 aliyunsdkcore.request import RoaRequest from aliyunsdkelasticsearch.endpoint import endpoint_data class UpdateInstanceChargeTypeRequest(RoaRequest): def __init__(self): RoaRequest.__init__(self, 'elasticsearch', '2017-06-13', 'UpdateInstanceChargeType','elasticsearch') self.set_uri_pattern('/openapi/instances/[InstanceId]/actions/convert-pay-type') self.set_method('POST') if hasattr(self, "endpoint_map"): setattr(self, "endpoint_map", endpoint_data.getEndpointMap()) if hasattr(self, "endpoint_regional"): setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional()) def get_InstanceId(self): # string return self.get_path_params().get('InstanceId') def set_InstanceId(self, InstanceId): # string self.add_path_param('InstanceId', InstanceId) def get_clientToken(self): # string return self.get_query_params().get('clientToken') def set_clientToken(self, clientToken): # string self.add_query_param('clientToken', clientToken) def get_body(self): # string return self.get_body_params().get('body') def set_body(self, body): # string self.add_body_params('body', body)
[ "sdk-team@alibabacloud.com" ]
sdk-team@alibabacloud.com
f4a798c794dcd2f46d7d18e1f36c63693a7d3aec
232c2738dff4b89ca63d7d4ec3c812570e3860c3
/ch06/better_rnnlm.py
0f8b26a6b999cb089ed405c9a6e08498643d5b53
[]
no_license
Soh1121/DeepLearningFromScratch2
0c115fcdf15c7b0cfd5d1ce7c6c32873354839d7
f2294156c6394fd105a6534801ff42a078b0a0af
refs/heads/main
2023-02-19T15:58:58.779465
2021-01-20T02:06:07
2021-01-20T02:06:07
319,550,802
0
0
null
2021-01-19T06:30:58
2020-12-08T06:45:41
Python
UTF-8
Python
false
false
2,722
py
import sys sys.path.append('..') from common.np import * # import numpy as np from common.time_layers import * from common.base_model import BaseModel class BetterRnnlm(BaseModel): ''' LSTMレイヤを2層利用し、各層にDropoutを使うモデル [1]で提案されたモデルをベースとし、weight tying[2][3]を利用 [1] Recurrent Neural Network Regularization (https://arxiv.org/abs/1409.2329) [2] Using the Output Embedding to Improve Language Models (https://arxiv.org/abs/1608.05859) [3] Tying Word Vectors and Word Classifiers (https://arxiv.org/pdf/1611.01462.pdf) ''' def __init__(self, vocab_size=10000, wordvec_size=650, hidden_size=650, dropout_ratio=0.5 ): V, D, H = vocab_size, wordvec_size, hidden_size rn = np.random.randn embed_W = (rn(V, D) / 100).astype('f') lstm_Wx1 = (rn(D, 4 * H) / np.sqrt(D)).astype('f') lstm_Wh1 = (rn(H, 4 * H) / np.sqrt(H)).astype('f') lstm_b1 = np.zeros(4 * H).astype('f') lstm_Wx2 = (rn(H, 4 * H) / np.sqrt(H)).astype('f') lstm_Wh2 = (rn(H, 4 * H) / np.sqrt(H)).astype('f') lstm_b2 = np.zeros(4 * H).astype('f') affine_b = np.zeros(V).astype('f') self.layers = [ TimeEmbedding(embed_W), TimeDropout(dropout_ratio), TimeLSTM(lstm_Wx1, lstm_Wh1, lstm_b1, stateful=True), TimeDropout(dropout_ratio), TimeLSTM(lstm_Wx2, lstm_Wh2, lstm_b2, stateful=True), TimeDropout(dropout_ratio), TimeAffine(embed_W.T, affine_b) # weight tying!! ] self.loss_layer = TimeSoftmaxWithLoss() self.lstm_layers = [ self.layers[2], self.layers[4] ] self.drop_layers = [ self.layers[1], self.layers[3], self.layers[5] ] self.params, self.grads = [], [] for layer in self.layers: self.params += layer.params self.grads += layer.grads def predict(self, xs, train_flg=False): for layer in self.drop_layers: layer.train_flg = train_flg for layer in self.layers: xs = layer.forward(xs) return xs def forward(self, xs, ts, train_flg=True): score = self.predict(xs, train_flg) loss = self.loss_layer.forward(score, ts) return loss def backward(self, dout=1): dout = self.loss_layer.backward(dout) for layer in reversed(self.layers): dout = layer.backward(dout) return dout def reset_state(self): for layer in self.lstm_layers: layer.reset_state()
[ "satou.shg@gmail.com" ]
satou.shg@gmail.com
faaa83c242009275d9ca670497e67c056417638e
ac5e52a3fc52dde58d208746cddabef2e378119e
/exps-gsn-edf/gsn-edf_ut=2.0_rd=1_rw=0.06_rn=4_u=0.075-0.35_p=harmonic-2/sched=RUN_trial=2/params.py
a831fdb8216bcc697815a8f8e189c1e1b40951a2
[]
no_license
ricardobtxr/experiment-scripts
1e2abfcd94fb0ef5a56c5d7dffddfe814752eef1
7bcebff7ac2f2822423f211f1162cd017a18babb
refs/heads/master
2023-04-09T02:37:41.466794
2021-04-25T03:27:16
2021-04-25T03:27:16
358,926,457
0
0
null
null
null
null
UTF-8
Python
false
false
251
py
{'cpus': 4, 'duration': 30, 'final_util': '2.040810', 'max_util': '2.0', 'periods': 'harmonic-2', 'release_master': False, 'res_distr': '1', 'res_nmb': '4', 'res_weight': '0.06', 'scheduler': 'GSN-EDF', 'trial': 2, 'utils': 'uni-medium-3'}
[ "ricardo.btxr@gmail.com" ]
ricardo.btxr@gmail.com
7c34b796aabf2898ce5b3391cd849ba3d47df125
5380c194fd3d97ce5779790abe8ffa1694daa519
/BackEnd/Account/views/Account.py
f6880e538f29d92e69825a4999c829b54ee73d67
[]
no_license
frshman/LuffyCity
4efc5360256cb328cdc34091762078bde11610be
8f3143e832a457a1bfbf5aa46c0abb298198164a
refs/heads/master
2023-08-13T22:10:50.544455
2020-06-05T04:47:37
2020-06-05T04:47:37
null
0
0
null
null
null
null
UTF-8
Python
false
false
649
py
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/5/18 23:12 # @File : Account.py # ---------------------------------------------- # ☆ ☆ ☆ ☆ ☆ ☆ ☆ # >>> Author : Alex 007 # >>> QQ : 2426671397 # >>> Mail : alex18812649207@gmail.com # >>> Github : https://github.com/koking0 # >>> Blog : https://alex007.blog.csdn.net/ # ☆ ☆ ☆ ☆ ☆ ☆ ☆ from Stark.main import StarkHandler, getChoice class AccountHandler(StarkHandler): def __init__(self, site, modelClass, prefix): super().__init__(site, modelClass, prefix) self.displayList = ["username", getChoice('身份', 'identity')]
[ "alex18812649207@gmail.com" ]
alex18812649207@gmail.com
affef3944b882801c0913fe7ca31980c9b4f1b7f
de5be7e4d9e20bbfda3ce8697afc3433a3ccf55d
/python_tutorial/excercise_3/reverse_string_list_func.py
6b8f844aa74c95bd28dd0956de310a0c381b3d6d
[]
no_license
poojataksande9211/python_data
42a88e0a0395f383d4375000a3d01b894bd38e62
64c952d622abfa77f2fdfd737c210014fce153c5
refs/heads/main
2023-04-16T10:24:27.213764
2021-04-27T16:34:32
2021-04-27T16:34:32
360,673,774
0
0
null
null
null
null
UTF-8
Python
false
false
837
py
def rev_string(l): element=[] for subelement in l: element.append(subelement[::-1]) return element words=["abc","def","ghi"] print(rev_string(words)) #---------------------------- # def rev_string(l): # element=[] # for subelement in range(len(l)): # element.append(subelement[::-1]) #why error for i in l ///for i in range(len(l)) # return element # words=["abc","def","ghi"] # print(rev_string(words)) #---------------------------- # words=["abc","def","ghi"] # for i in words: # print(i) #---------------------------- # def rev_string(l): # rev=[] # for i in range(len(l)): # pop_item=l.pop() # rev.append(pop_item) # return rev # words=["abc","def","ghi"] # print(rev_string(words))
[ "amitganvir6@gmail.com" ]
amitganvir6@gmail.com
0fbc601cc05227e44edc2e2eea6511f140d8c776
d4f1d1a1657f94376c989b12a8e16c8ff1d86e01
/Stanford_ml/ex2/pylogistic/logistic.py
c0888790944abd48764a573c639db092c0d66ae3
[]
no_license
sbmaruf/DataMing-MachineLearning
6e2335c4f16039bf7e5b4aad852e7426e10d2e6f
baf9d9b668588329504975c6586dbd31b2932900
refs/heads/master
2021-06-07T02:22:31.129127
2016-09-30T09:56:07
2016-09-30T09:56:07
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,921
py
#!/usr/bin/env python # coding=utf-8 import numpy as np import pandas as pd def sigmoid(z): """""" g = 1 / (1 + np.exp(-z)) return g def cost_function(theta, X, y): """""" m = y.size J = (-y.T * np.log(sigmoid(X * theta)) - \ (1 - y).T * np.log(1 - sigmoid(X * theta))) / m grad = ((sigmoid(X * theta) - y).T * X) / m return J, grad def gradient_descent(X, y, theta, alpha): """""" m = y.size row, col = X.shape temp_theta = [] for i in range(col): _temp = theta[i] - alpha * ((sigmoid(X * theta) - y).T * X[:, i]) temp_theta.append(_temp.tolist()[0][0]) theta = np.array(temp_theta) return theta def train(X, y, theta, alpha, num_iters): """""" cost_history = range(num_iters) for i in range(num_iters): _theta = gradient_descent(X, y, theta, alpha) theta = np.mat(_theta, dtype=float).T cost_history[i] = cost_function(theta, X, y) return theta def performance(testData, testY, theta): """""" z = testData * theta g = sigmoid(z) count = 0 for v in g - testY: if v != 0: count += 1 return count / float(testY.size) def predict(): """""" pass if __name__ == '__main__': data = np.mat(pd.read_csv('train.csv', header=None), dtype=float) _x = data[:, range(data.shape[1])[0:-1]] X = np.insert(_x, 0, values=1, axis=1) y = data[:, -1] theta = np.mat(np.zeros(X.shape[1], dtype=float), dtype=float).T alpha, num_iters = 0.01, 1000 theta = train(X, y, theta, alpha, num_iters) print(theta) # get the performance of Model _test_data = np.mat(pd.read_csv('test.csv', header=None), dtype=float) test_data = _test_data[:, range(_test_data.shape[1])[0:-1]] testData = np.insert(test_data, 0, values=1, axis=1) testY = _test_data[:, -1] print(performance(testData, testY, theta))
[ "scutqiuwei@163.com" ]
scutqiuwei@163.com
2ca6d767460661f1a4351a9b75835ee0d90e53b8
0ef933a7b019e9a754222464046aeaaf8a42b553
/django_facebook/tests/test.py
4343a14b74f0bd22fe50c3f8c76231417a08b410
[ "BSD-3-Clause" ]
permissive
kennu/Django-facebook
1d858a53856a3f3997557ad5564c768b9c83c21d
88ba7025d24023756a417d1bae4f84e6ed6b67fd
refs/heads/master
2020-12-25T08:19:29.244207
2011-10-12T17:22:10
2011-10-12T17:22:10
2,562,533
0
0
null
null
null
null
UTF-8
Python
false
false
4,749
py
from __future__ import with_statement from django.contrib.auth.models import AnonymousUser from django_facebook import exceptions as facebook_exceptions from django_facebook.auth_backends import FacebookBackend from django_facebook.connect import connect_user, CONNECT_ACTIONS from django_facebook.tests.base import FacebookTest from open_facebook.exceptions import * from django_facebook.api import get_facebook_graph, FacebookUserConverter, get_persistent_graph import logging import unittest logger = logging.getLogger(__name__) __doctests__ = ['django_facebook.api'] ''' TODO The views are currently untested, only the underlying functionality is. (need to fake facebook cookie stuff to correctly test the views) ''' class UserConnectTest(FacebookTest): ''' Tests the connect user functionality ''' fixtures = ['users.json'] def test_persistent_graph(self): from django.test import RequestFactory from django.contrib.auth.models import AnonymousUser request = RequestFactory() request.session = {} request.user = AnonymousUser() graph = get_persistent_graph(request, access_token='short_username') def test_full_connect(self): #going for a register, connect and login graph = get_facebook_graph(access_token='short_username') facebook = FacebookUserConverter(graph) action, user = connect_user(self.request, facebook_graph=graph) assert action == CONNECT_ACTIONS.REGISTER action, user = connect_user(self.request, facebook_graph=graph) assert action == CONNECT_ACTIONS.CONNECT self.request.user = AnonymousUser() action, user = connect_user(self.request, facebook_graph=graph) assert action == CONNECT_ACTIONS.LOGIN def test_utf8(self): graph = get_facebook_graph(access_token='unicode_string') facebook = FacebookUserConverter(graph) profile_data = facebook.facebook_profile_data() action, user = connect_user(self.request, facebook_graph=graph) def test_invalid_token(self): self.assertRaises(AssertionError, connect_user, self.request, access_token='invalid') def test_no_email_registration(self): self.assertRaises(facebook_exceptions.IncompleteProfileError, connect_user, self.request, access_token='no_email') def test_current_user(self): facebook = get_facebook_graph(access_token='tschellenbach') action, user = connect_user(self.request, facebook_graph=facebook) assert action == CONNECT_ACTIONS.LOGIN def test_new_user(self): facebook = get_facebook_graph(access_token='new_user') action, user = connect_user(self.request, facebook_graph=facebook) def test_short_username(self): facebook = get_facebook_graph(access_token='short_username') action, user = connect_user(self.request, facebook_graph=facebook) assert len(user.username) > 4 assert action == CONNECT_ACTIONS.REGISTER def test_gender(self): graph = get_facebook_graph(access_token='new_user') facebook = FacebookUserConverter(graph) data = facebook.facebook_registration_data() assert data['gender'] == 'm' def test_double_username(self): ''' This used to give an error with duplicate usernames with different capitalization ''' facebook = get_facebook_graph(access_token='short_username') action, user = connect_user(self.request, facebook_graph=facebook) user.username = 'Thierry_schellenbach' user.save() self.request.user = AnonymousUser() facebook = get_facebook_graph(access_token='same_username') action, new_user = connect_user(self.request, facebook_graph=facebook) assert user.username != new_user.username and user.id != new_user.id class AuthBackend(FacebookTest): def test_auth_backend(self): backend = FacebookBackend() facebook = get_facebook_graph(access_token='new_user') action, user = connect_user(self.request, facebook_graph=facebook) facebook_email = user.email facebook_id = user.get_profile().facebook_id auth_user = backend.authenticate(facebook_email=facebook_email) assert auth_user == user auth_user = backend.authenticate(facebook_id=facebook_id) assert auth_user == user auth_user = backend.authenticate(facebook_id=facebook_id, facebook_email=facebook_email) assert auth_user == user auth_user = backend.authenticate() assert not auth_user if __name__ == '__main__': unittest.main()
[ "thierryschellenbach@gmail.com" ]
thierryschellenbach@gmail.com
110c2eaecef9a00e4485c50558865f58db4514b5
de24f83a5e3768a2638ebcf13cbe717e75740168
/moodledata/vpl_data/101/usersdata/173/49768/submittedfiles/av1_m3.py
d342df107865d5b70a00235643849cdcbd0af61c
[]
no_license
rafaelperazzo/programacao-web
95643423a35c44613b0f64bed05bd34780fe2436
170dd5440afb9ee68a973f3de13a99aa4c735d79
refs/heads/master
2021-01-12T14:06:25.773146
2017-12-22T16:05:45
2017-12-22T16:05:45
69,566,344
0
0
null
null
null
null
UTF-8
Python
false
false
220
py
# -*- coding: utf-8 -*- import math m=int(input('Digite o número de termos: ')) i=2 for i in range(0,m,2): if(m>0): pi=4/(i*(i+1)*(i+2))+soma i=i+2 soma=pi-(4/(i*(i+1)*(i+2))) i=i+2 print(soma+3)
[ "rafael.mota@ufca.edu.br" ]
rafael.mota@ufca.edu.br
5c2083159abd93b9c6afcc86c8d18669cb55d2c2
c00a2490947ad10582b5d675f070ccb62b70901d
/chromium/chrome/chrome_common.gypi
98a13da650c3839702b48a08801e8f2bc9195b4a
[ "BSD-3-Clause" ]
permissive
teotikalki/vivaldi-source
543d0ab336fb5784eaae1904457598f95f426186
22a46f2c969f6a0b7ca239a05575d1ea2738768c
refs/heads/master
2021-01-23T01:17:34.305328
2016-04-29T20:28:18
2016-04-29T20:28:18
null
0
0
null
null
null
null
UTF-8
Python
false
false
28,773
gypi
# Copyright (c) 2013 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. { 'variables': { # File lists shared with GN build. 'chrome_common_sources': [ 'common/all_messages.h', 'common/attrition_experiments.h', 'common/auto_start_linux.cc', 'common/auto_start_linux.h', 'common/channel_info.cc', 'common/channel_info.h', 'common/channel_info_android.cc', 'common/channel_info_chromeos.cc', 'common/channel_info_mac.mm', 'common/channel_info_posix.cc', 'common/channel_info_win.cc', 'common/child_process_logging.h', 'common/child_process_logging_win.cc', 'common/chrome_content_client.cc', 'common/chrome_content_client.h', 'common/chrome_content_client_constants.cc', 'common/chrome_content_client_ios.mm', 'common/chrome_result_codes.h', 'common/chrome_utility_messages.h', 'common/common_message_generator.cc', 'common/common_message_generator.h', 'common/common_param_traits.cc', 'common/common_param_traits.h', 'common/common_param_traits_macros.h', 'common/component_flash_hint_file_linux.cc', 'common/component_flash_hint_file_linux.h', 'common/content_restriction.h', 'common/content_settings_pattern_serializer.cc', 'common/content_settings_pattern_serializer.h', 'common/crash_keys.cc', 'common/crash_keys.h', 'common/custom_handlers/protocol_handler.cc', 'common/custom_handlers/protocol_handler.h', 'common/descriptors_android.h', 'common/ini_parser.cc', 'common/ini_parser.h', 'common/instant_types.cc', 'common/instant_types.h', 'common/localized_error.cc', 'common/localized_error.h', 'common/logging_chrome.cc', 'common/logging_chrome.h', 'common/mac/app_shim_launch.h', 'common/mac/app_shim_messages.h', 'common/mac/cfbundle_blocker.h', 'common/mac/cfbundle_blocker.mm', 'common/mac/launchd.h', 'common/mac/launchd.mm', 'common/media/media_resource_provider.cc', 'common/media/media_resource_provider.h', 'common/media/webrtc_logging_message_data.cc', 'common/media/webrtc_logging_message_data.h', 'common/media/webrtc_logging_messages.h', 'common/media_galleries/metadata_types.h', 'common/multi_process_lock.h', 'common/multi_process_lock_linux.cc', 'common/multi_process_lock_mac.cc', 'common/multi_process_lock_win.cc', 'common/partial_circular_buffer.cc', 'common/partial_circular_buffer.h', 'common/pref_names_util.cc', 'common/pref_names_util.h', 'common/prerender_types.h', 'common/profiling.cc', 'common/profiling.h', 'common/ref_counted_util.h', 'common/render_messages.cc', 'common/render_messages.h', 'common/resource_usage_reporter_type_converters.cc', 'common/resource_usage_reporter_type_converters.h', 'common/safe_browsing/safebrowsing_messages.h', 'common/search_provider.h', 'common/search_types.h', 'common/search_urls.cc', 'common/search_urls.h', 'common/secure_origin_whitelist.cc', 'common/secure_origin_whitelist.h', 'common/spellcheck_bdict_language.h', 'common/spellcheck_common.cc', 'common/spellcheck_common.h', 'common/spellcheck_marker.h', 'common/spellcheck_messages.h', 'common/spellcheck_result.h', 'common/switch_utils.cc', 'common/switch_utils.h', 'common/trace_event_args_whitelist.cc', 'common/trace_event_args_whitelist.h', 'common/tts_messages.h', 'common/tts_utterance_request.cc', 'common/tts_utterance_request.h', 'common/url_constants.cc', 'common/url_constants.h', 'common/v8_breakpad_support_win.cc', 'common/v8_breakpad_support_win.h', 'common/variations/variations_util.cc', 'common/variations/variations_util.h', 'common/web_application_info.cc', 'common/web_application_info.h', 'common/widevine_cdm_constants.cc', 'common/widevine_cdm_constants.h', 'common/worker_thread_ticker.cc', 'common/worker_thread_ticker.h', ], 'chrome_common_extensions_sources': [ 'common/cast_messages.cc', 'common/cast_messages.h', 'common/extensions/api/commands/commands_handler.cc', 'common/extensions/api/commands/commands_handler.h', 'common/extensions/api/extension_action/action_info.cc', 'common/extensions/api/extension_action/action_info.h', 'common/extensions/api/notifications/notification_style.cc', 'common/extensions/api/notifications/notification_style.h', 'common/extensions/api/omnibox/omnibox_handler.cc', 'common/extensions/api/omnibox/omnibox_handler.h', 'common/extensions/api/plugins/plugins_handler.cc', 'common/extensions/api/plugins/plugins_handler.h', 'common/extensions/api/speech/tts_engine_manifest_handler.cc', 'common/extensions/api/speech/tts_engine_manifest_handler.h', 'common/extensions/api/spellcheck/spellcheck_handler.cc', 'common/extensions/api/spellcheck/spellcheck_handler.h', 'common/extensions/api/storage/storage_schema_manifest_handler.cc', 'common/extensions/api/storage/storage_schema_manifest_handler.h', 'common/extensions/api/system_indicator/system_indicator_handler.cc', 'common/extensions/api/system_indicator/system_indicator_handler.h', 'common/extensions/api/url_handlers/url_handlers_parser.cc', 'common/extensions/api/url_handlers/url_handlers_parser.h', 'common/extensions/api/webstore/webstore_api_constants.cc', 'common/extensions/api/webstore/webstore_api_constants.h', 'common/extensions/chrome_extension_messages.h', 'common/extensions/chrome_extensions_client.cc', 'common/extensions/chrome_extensions_client.h', 'common/extensions/chrome_manifest_handlers.cc', 'common/extensions/chrome_manifest_handlers.h', 'common/extensions/chrome_manifest_url_handlers.cc', 'common/extensions/chrome_manifest_url_handlers.h', 'common/extensions/chrome_utility_extensions_messages.h', 'common/extensions/command.cc', 'common/extensions/command.h', 'common/extensions/extension_constants.cc', 'common/extensions/extension_constants.h', 'common/extensions/extension_metrics.cc', 'common/extensions/extension_metrics.h', 'common/extensions/extension_process_policy.cc', 'common/extensions/extension_process_policy.h', 'common/extensions/features/chrome_channel_feature_filter.cc', 'common/extensions/features/chrome_channel_feature_filter.h', 'common/extensions/features/feature_channel.cc', 'common/extensions/features/feature_channel.h', 'common/extensions/features/feature_util.cc', 'common/extensions/features/feature_util.h', 'common/extensions/image_writer/image_writer_util_mac.cc', 'common/extensions/image_writer/image_writer_util_mac.h', 'common/extensions/manifest_handlers/app_icon_color_info.cc', 'common/extensions/manifest_handlers/app_icon_color_info.h', 'common/extensions/manifest_handlers/app_launch_info.cc', 'common/extensions/manifest_handlers/app_launch_info.h', 'common/extensions/manifest_handlers/automation.cc', 'common/extensions/manifest_handlers/automation.h', 'common/extensions/manifest_handlers/content_scripts_handler.cc', 'common/extensions/manifest_handlers/content_scripts_handler.h', 'common/extensions/manifest_handlers/copresence_manifest.cc', 'common/extensions/manifest_handlers/copresence_manifest.h', 'common/extensions/manifest_handlers/extension_action_handler.cc', 'common/extensions/manifest_handlers/extension_action_handler.h', 'common/extensions/manifest_handlers/linked_app_icons.cc', 'common/extensions/manifest_handlers/linked_app_icons.h', 'common/extensions/manifest_handlers/minimum_chrome_version_checker.cc', 'common/extensions/manifest_handlers/minimum_chrome_version_checker.h', 'common/extensions/manifest_handlers/settings_overrides_handler.cc', 'common/extensions/manifest_handlers/settings_overrides_handler.h', 'common/extensions/manifest_handlers/theme_handler.cc', 'common/extensions/manifest_handlers/theme_handler.h', 'common/extensions/manifest_handlers/ui_overrides_handler.cc', 'common/extensions/manifest_handlers/ui_overrides_handler.h', 'common/extensions/permissions/chrome_api_permissions.cc', 'common/extensions/permissions/chrome_api_permissions.h', 'common/extensions/permissions/chrome_permission_message_provider.cc', 'common/extensions/permissions/chrome_permission_message_provider.h', 'common/extensions/permissions/chrome_permission_message_rules.cc', 'common/extensions/permissions/chrome_permission_message_rules.h', 'common/extensions/sync_helper.cc', 'common/extensions/sync_helper.h', ], 'chrome_common_printing_sources': [ 'common/chrome_utility_printing_messages.h', 'common/cloud_print/cloud_print_cdd_conversion.cc', 'common/cloud_print/cloud_print_cdd_conversion.h', 'common/cloud_print/cloud_print_class_mac.h', 'common/cloud_print/cloud_print_class_mac.mm', 'common/cloud_print/cloud_print_constants.cc', 'common/cloud_print/cloud_print_constants.h', 'common/cloud_print/cloud_print_helpers.cc', 'common/cloud_print/cloud_print_helpers.h', 'common/cloud_print/cloud_print_proxy_info.cc', 'common/cloud_print/cloud_print_proxy_info.h', ], 'chrome_common_extensions_chromeos_sources': [ 'common/extensions/api/file_browser_handlers/file_browser_handler.cc', 'common/extensions/api/file_browser_handlers/file_browser_handler.h', 'common/extensions/api/file_system_provider_capabilities/file_system_provider_capabilities_handler.cc', 'common/extensions/api/file_system_provider_capabilities/file_system_provider_capabilities_handler.h', 'common/extensions/api/input_ime/input_components_handler.cc', 'common/extensions/api/input_ime/input_components_handler.h', ], 'chrome_common_full_safe_browsing_sources': [ 'common/safe_browsing/binary_feature_extractor.cc', 'common/safe_browsing/binary_feature_extractor.h', 'common/safe_browsing/binary_feature_extractor_mac.cc', 'common/safe_browsing/binary_feature_extractor_posix.cc', 'common/safe_browsing/binary_feature_extractor_win.cc', 'common/safe_browsing/download_protection_util.cc', 'common/safe_browsing/download_protection_util.h', 'common/safe_browsing/ipc_protobuf_message_macros.h', 'common/safe_browsing/ipc_protobuf_message_null_macros.h', 'common/safe_browsing/mach_o_image_reader_mac.cc', 'common/safe_browsing/mach_o_image_reader_mac.h', 'common/safe_browsing/pe_image_reader_win.cc', 'common/safe_browsing/pe_image_reader_win.h', 'common/safe_browsing/protobuf_message_log_macros.h', 'common/safe_browsing/protobuf_message_param_traits.h', 'common/safe_browsing/protobuf_message_read_macros.h', 'common/safe_browsing/protobuf_message_write_macros.h', 'common/safe_browsing/zip_analyzer.cc', 'common/safe_browsing/zip_analyzer.h', 'common/safe_browsing/zip_analyzer_results.cc', 'common/safe_browsing/zip_analyzer_results.h', ], 'chrome_common_importer_sources': [ 'common/importer/edge_importer_utils_win.cc', 'common/importer/edge_importer_utils_win.h', 'common/importer/firefox_importer_utils.cc', 'common/importer/firefox_importer_utils.h', 'common/importer/firefox_importer_utils_linux.cc', 'common/importer/firefox_importer_utils_mac.mm', 'common/importer/firefox_importer_utils_win.cc', 'common/importer/ie_importer_utils_win.cc', 'common/importer/ie_importer_utils_win.h', 'common/importer/imported_bookmark_entry.cc', 'common/importer/imported_bookmark_entry.h', 'common/importer/importer_autofill_form_data_entry.cc', 'common/importer/importer_autofill_form_data_entry.h', 'common/importer/importer_bridge.cc', 'common/importer/importer_bridge.h', 'common/importer/importer_data_types.cc', 'common/importer/importer_data_types.h', 'common/importer/importer_test_registry_overrider_win.cc', 'common/importer/importer_test_registry_overrider_win.h', 'common/importer/importer_type.h', 'common/importer/importer_url_row.cc', 'common/importer/importer_url_row.h', 'common/importer/profile_import_process_messages.cc', 'common/importer/profile_import_process_messages.h', 'common/importer/profile_import_process_param_traits_macros.h', 'common/importer/safari_importer_utils.h', 'common/importer/safari_importer_utils.mm', ], 'chrome_common_ipc_fuzzer_sources': [ 'common/external_ipc_dumper.cc', 'common/external_ipc_dumper.h', ], 'chrome_common_service_process_sources': [ 'common/service_messages.h', 'common/service_process_util.cc', 'common/service_process_util.h', 'common/service_process_util_linux.cc', 'common/service_process_util_mac.mm', 'common/service_process_util_posix.cc', 'common/service_process_util_posix.h', 'common/service_process_util_win.cc', ], 'chrome_common_win_mac_sources': [ 'common/media_galleries/itunes_library.cc', 'common/media_galleries/itunes_library.h', 'common/media_galleries/picasa_types.cc', 'common/media_galleries/picasa_types.h', 'common/media_galleries/pmp_constants.h', ], 'chrome_common_networking_private_sources' : [ 'common/extensions/api/networking_private/networking_private_crypto.cc', 'common/extensions/api/networking_private/networking_private_crypto.h', ], 'chrome_common_mac_sources': [ 'common/media_galleries/iphoto_library.cc', 'common/media_galleries/iphoto_library.h', ] }, 'targets': [ { # GN: //chrome/common:common 'target_name': 'common', 'type': 'static_library', 'hard_dependency': 1, # Because of transitive dep on version_header. 'variables': { 'chrome_common_target': 1, 'enable_wexit_time_destructors': 1, }, 'include_dirs': [ '..', '<(SHARED_INTERMEDIATE_DIR)', # Needed by chrome_content_client.cc. ], 'direct_dependent_settings': { 'include_dirs': [ '..', ], }, 'dependencies': [ # TODO(gregoryd): chrome_resources and chrome_strings could be # shared with the 64-bit target, but it does not work due to a gyp # issue. 'installer_util', 'safe_browsing_proto', '<(DEPTH)/base/base.gyp:base', '<(DEPTH)/base/base.gyp:base_i18n', '<(DEPTH)/base/base.gyp:base_prefs', '<(DEPTH)/base/base.gyp:base_static', '<(DEPTH)/chrome/chrome_features.gyp:chrome_common_features', '<(DEPTH)/chrome/chrome_resources.gyp:chrome_resources', '<(DEPTH)/chrome/chrome_resources.gyp:chrome_strings', '<(DEPTH)/chrome/chrome_resources.gyp:theme_resources', '<(DEPTH)/chrome/common_constants.gyp:common_constants', '<(DEPTH)/chrome/common/variations/fieldtrial_testing_config.gyp:fieldtrial_testing_config', '<(DEPTH)/components/components.gyp:cloud_devices_common', '<(DEPTH)/components/components.gyp:component_updater', '<(DEPTH)/components/components.gyp:content_settings_core_common', '<(DEPTH)/components/components.gyp:crash_core_common', '<(DEPTH)/components/components.gyp:error_page_common', '<(DEPTH)/components/components.gyp:favicon_base', '<(DEPTH)/components/components.gyp:flags_ui_switches', '<(DEPTH)/components/components.gyp:gcm_driver_common', '<(DEPTH)/components/components.gyp:generate_version_info', '<(DEPTH)/components/components.gyp:json_schema', '<(DEPTH)/components/components.gyp:metrics', '<(DEPTH)/components/components.gyp:metrics_net', '<(DEPTH)/components/components.gyp:omnibox_common', '<(DEPTH)/components/components.gyp:policy_component_common', # TODO(fdoray): Remove this once the PreRead field trial has expired. # crbug.com/577698 '<(DEPTH)/components/components.gyp:startup_metric_utils_common', '<(DEPTH)/components/components.gyp:translate_core_common', '<(DEPTH)/components/components.gyp:variations', '<(DEPTH)/components/components.gyp:version_info', '<(DEPTH)/components/components_strings.gyp:components_strings', '<(DEPTH)/components/url_formatter/url_formatter.gyp:url_formatter', '<(DEPTH)/content/content.gyp:content_common', '<(DEPTH)/crypto/crypto.gyp:crypto', '<(DEPTH)/net/net.gyp:net', '<(DEPTH)/skia/skia.gyp:skia', '<(DEPTH)/skia/skia.gyp:skia_library', '<(DEPTH)/third_party/icu/icu.gyp:icui18n', '<(DEPTH)/third_party/icu/icu.gyp:icuuc', '<(DEPTH)/third_party/kasko/kasko.gyp:kasko_features', '<(DEPTH)/third_party/zlib/google/zip.gyp:zip', '<(DEPTH)/ui/gfx/ipc/gfx_ipc.gyp:gfx_ipc', '<(DEPTH)/ui/resources/ui_resources.gyp:ui_resources', '<(DEPTH)/url/url.gyp:url_lib', ], 'sources': [ '<@(chrome_common_sources)' ], 'conditions': [ ['enable_extensions==1', { 'sources': [ '<@(chrome_common_extensions_sources)' ], 'dependencies': [ '<(DEPTH)/device/usb/usb.gyp:device_usb', '<(DEPTH)/chrome/common/extensions/api/api.gyp:chrome_api', '<(DEPTH)/extensions/common/api/api.gyp:extensions_api', '<(DEPTH)/extensions/extensions.gyp:extensions_common', '<(DEPTH)/extensions/extensions_resources.gyp:extensions_resources', '<(DEPTH)/extensions/extensions_strings.gyp:extensions_strings', '<(DEPTH)/media/cast/cast.gyp:cast_net', ], 'export_dependent_settings': [ '<(DEPTH)/chrome/common/extensions/api/api.gyp:chrome_api', ], 'conditions': [ ['chromeos==1', { 'sources': [ '<@(chrome_common_extensions_chromeos_sources)' ], }], ['OS=="win" or OS=="linux"', { 'sources': [ 'common/extensions/api/input_ime/input_components_handler.cc', 'common/extensions/api/input_ime/input_components_handler.h', ] }] ], }], ['enable_extensions==1 and chromeos==1', { 'sources': [ '<@(chrome_common_extensions_chromeos_sources)' ], }], ['OS=="win" or OS=="mac"', { 'sources': [ '<@(chrome_common_win_mac_sources)' ], }], ['OS=="win" or OS=="mac" or chromeos==1', { 'sources': [ '<@(chrome_common_networking_private_sources)' ], 'dependencies': [ '../third_party/boringssl/boringssl.gyp:boringssl', ], }], ['OS=="mac"', { 'sources': [ '<@(chrome_common_mac_sources)' ], 'dependencies': [ 'app_mode_app_support' ], }], ['OS != "ios"', { 'dependencies': [ 'common_mojo_bindings', '<(DEPTH)/components/components.gyp:autofill_core_common', '<(DEPTH)/components/components.gyp:autofill_content_common', '<(DEPTH)/components/components.gyp:password_manager_core_common', '<(DEPTH)/components/components.gyp:password_manager_content_common', '<(DEPTH)/components/components.gyp:signin_core_common', '<(DEPTH)/components/components.gyp:translate_content_common', '<(DEPTH)/components/components.gyp:visitedlink_common', '<(DEPTH)/extensions/extensions.gyp:extensions_common_constants', '<(DEPTH)/ipc/ipc.gyp:ipc', '<(DEPTH)/media/media.gyp:media', '<(DEPTH)/third_party/re2/re2.gyp:re2', '<(DEPTH)/third_party/widevine/cdm/widevine_cdm.gyp:widevine_cdm_version_h', ], }, { # OS == ios 'sources/': [ ['exclude', '^common/child_process_'], ['exclude', '^common/chrome_content_client\\.cc$'], ['exclude', '^common/chrome_version_info_posix\\.cc$'], ['exclude', '^common/common_message_generator\\.cc$'], ['exclude', '^common/common_param_traits'], ['exclude', '^common/custom_handlers/'], ['exclude', '^common/extensions/'], ['exclude', '^common/logging_chrome\\.'], ['exclude', '^common/media/media_resource_provider'], ['exclude', '^common/media_galleries/'], ['exclude', '^common/multi_process_'], ['exclude', '^common/profiling\\.'], ['exclude', '^common/resource_usage_reporter_type_converters'], ['exclude', '^common/spellcheck_'], ['exclude', '^common/validation_message_'], ['exclude', '^common/web_apps\\.'], # TODO(ios): Include files here as they are made to work; once # everything is online, remove everything below here and just # use the exclusions above. ['exclude', '\\.(cc|mm)$'], ['include', '_ios\\.(cc|mm)$'], ['include', '(^|/)ios/'], ['include', '^common/chrome_version_info\\.cc$'], ['include', '^common/translate'], ['include', '^common/zip'], ], }], ['disable_nacl==0', { 'dependencies': [ '<(DEPTH)/components/nacl.gyp:nacl_common', ], }], ['enable_ipc_fuzzer==1', { 'sources': [ '<@(chrome_common_ipc_fuzzer_sources)' ], }], ['enable_plugins==1', { 'dependencies': [ '<(DEPTH)/third_party/adobe/flash/flash_player.gyp:flapper_version_h', ], 'sources': [ 'common/pepper_flash.cc', 'common/pepper_flash.h', 'common/ppapi_utils.cc', 'common/ppapi_utils.h', ], }], ['enable_plugins==1 and enable_extensions==1', { 'sources': [ 'common/pepper_permission_util.cc', 'common/pepper_permission_util.h', ], }], ['enable_basic_printing==1 or enable_print_preview==1', { 'sources': [ '<@(chrome_common_printing_sources)' ], 'dependencies': [ '<(DEPTH)/components/components.gyp:printing_common', '<(DEPTH)/printing/printing.gyp:printing', ], }], ['enable_print_preview==1', { 'sources': [ '<@(chrome_common_service_process_sources)' ], }], ['OS=="android"', { 'sources!': [ 'common/channel_info_posix.cc', 'common/extensions/api/spellcheck/spellcheck_handler.cc', 'common/extensions/manifest_handlers/extension_action_handler.cc', 'common/extensions/manifest_handlers/minimum_chrome_version_checker.cc', 'common/media_galleries/metadata_types.h', ], }, { # Non-Android. 'sources': [ '<@(chrome_common_importer_sources)' ] }], ['OS=="win"', { 'include_dirs': [ '<(DEPTH)/third_party/wtl/include', ], 'dependencies': [ '<(DEPTH)/components/components.gyp:dom_distiller_core', # Needed by chrome_content_client.cc. ], }], ['OS=="mac"', { 'dependencies': [ '../third_party/google_toolbox_for_mac/google_toolbox_for_mac.gyp:google_toolbox_for_mac', '../third_party/mach_override/mach_override.gyp:mach_override', ], 'sources!': [ 'common/channel_info_posix.cc', ], }], ['enable_webrtc==0', { 'sources!': [ 'common/media/webrtc_logging_messages.h', ] }], ['configuration_policy==1', { 'dependencies': [ '<(DEPTH)/components/components.gyp:policy', ], }], ['safe_browsing==1', { 'sources': [ '<@(chrome_common_full_safe_browsing_sources)', ], }], ], 'target_conditions': [ ['OS == "ios"', { 'sources/': [ # Pull in specific Mac files for iOS (which have been filtered out # by file name rules). ['include', '^common/chrome_version_info_mac\\.mm$'], ], }], ], 'export_dependent_settings': [ '../base/base.gyp:base', ], }, { # GN version: //chrome/common/net 'target_name': 'common_net', 'type': 'static_library', 'sources': [ 'common/net/net_resource_provider.cc', 'common/net/net_resource_provider.h', 'common/net/x509_certificate_model.cc', 'common/net/x509_certificate_model.h', 'common/net/x509_certificate_model_nss.cc', 'common/net/x509_certificate_model_openssl.cc', ], 'dependencies': [ '<(DEPTH)/base/base.gyp:base', '<(DEPTH)/chrome/chrome_features.gyp:chrome_common_features', '<(DEPTH)/chrome/chrome_resources.gyp:chrome_resources', '<(DEPTH)/chrome/chrome_resources.gyp:chrome_strings', '<(DEPTH)/components/url_formatter/url_formatter.gyp:url_formatter', '<(DEPTH)/crypto/crypto.gyp:crypto', '<(DEPTH)/net/net.gyp:net', '<(DEPTH)/net/net.gyp:net_resources', '<(DEPTH)/third_party/icu/icu.gyp:icui18n', '<(DEPTH)/third_party/icu/icu.gyp:icuuc', '<(DEPTH)/ui/base/ui_base.gyp:ui_base', ], 'conditions': [ ['OS == "ios"', { 'sources!': [ 'common/net/net_resource_provider.cc', ], }], ['OS == "android" or OS == "ios"', { 'sources!': [ 'common/net/x509_certificate_model.cc', ], }], ['use_openssl_certs == 1 and OS != "android"', { 'dependencies': [ '<(DEPTH)/third_party/boringssl/boringssl.gyp:boringssl', ], }, { 'sources!': [ 'common/net/x509_certificate_model_openssl.cc', ], }], ['use_nss_certs == 1', { 'sources': [ # GN version: //chrome/third_party/mozilla_security_manager 'third_party/mozilla_security_manager/nsNSSCertHelper.cpp', 'third_party/mozilla_security_manager/nsNSSCertHelper.h', 'third_party/mozilla_security_manager/nsNSSCertificate.cpp', 'third_party/mozilla_security_manager/nsNSSCertificate.h', 'third_party/mozilla_security_manager/nsUsageArrayHelper.cpp', 'third_party/mozilla_security_manager/nsUsageArrayHelper.h', ], 'dependencies': [ '../build/linux/system.gyp:ssl', ], }, { 'sources!': [ 'common/net/x509_certificate_model_nss.cc', ], }], ['OS=="win"', { # TODO(jschuh): crbug.com/167187 fix size_t to int truncations. 'msvs_disabled_warnings': [4267, ], }], ], }, { # Protobuf compiler / generator for the safebrowsing client # model proto and the client-side detection (csd) request # protocol buffer. # GN version: //chrome/common/safe_browsing:proto 'target_name': 'safe_browsing_proto', 'type': 'static_library', 'sources': [ 'common/safe_browsing/client_model.proto', 'common/safe_browsing/crx_info.proto', 'common/safe_browsing/csd.proto' ], 'variables': { 'proto_in_dir': 'common/safe_browsing', 'proto_out_dir': 'chrome/common/safe_browsing', }, 'includes': [ '../build/protoc.gypi' ], }, { # GN version: //chrome/common:mojo_bindings 'target_name': 'common_mojo_bindings', 'type': 'static_library', 'includes': [ '../third_party/mojo/mojom_bindings_generator.gypi' ], 'sources': [ 'common/resource_usage_reporter.mojom', ], 'dependencies': [ '../mojo/mojo_base.gyp:mojo_environment_chromium', '../third_party/mojo/mojo_public.gyp:mojo_cpp_bindings', ], }, ], }
[ "jason@theograys.com" ]
jason@theograys.com
213a49e3cf6265a409a23e3a85dc6a390d5167de
93091329589b31111001eb817315e4d734fa8ab4
/detectron2/data/build.py
ce4b183fba1ca01cb9e5d1b673810784a97356d5
[ "Apache-2.0" ]
permissive
natureyoo/detectron2
b5e32f5b4386ad7100ff092a3016179501a9bc14
7f2be92895636e127f3efa8f32fcfed3fb052152
refs/heads/main
2023-08-22T20:37:13.104766
2023-07-14T05:56:04
2023-07-14T05:56:04
274,582,273
0
0
null
2020-06-24T05:23:36
2020-06-24T05:23:35
null
UTF-8
Python
false
false
21,313
py
# Copyright (c) Facebook, Inc. and its affiliates. import itertools import logging import numpy as np import operator import pickle from typing import Any, Callable, Dict, List, Optional, Union import torch import torch.utils.data as torchdata from tabulate import tabulate from termcolor import colored from detectron2.config import configurable from detectron2.structures import BoxMode from detectron2.utils.comm import get_world_size from detectron2.utils.env import seed_all_rng from detectron2.utils.file_io import PathManager from detectron2.utils.logger import _log_api_usage, log_first_n from .catalog import DatasetCatalog, MetadataCatalog from .common import AspectRatioGroupedDataset, DatasetFromList, MapDataset, ToIterableDataset from .dataset_mapper import DatasetMapper from .detection_utils import check_metadata_consistency from .samplers import ( InferenceSampler, RandomSubsetTrainingSampler, RepeatFactorTrainingSampler, TrainingSampler, ) """ This file contains the default logic to build a dataloader for training or testing. """ __all__ = [ "build_batch_data_loader", "build_detection_train_loader", "build_detection_test_loader", "get_detection_dataset_dicts", "load_proposals_into_dataset", "print_instances_class_histogram", ] def filter_images_with_only_crowd_annotations(dataset_dicts): """ Filter out images with none annotations or only crowd annotations (i.e., images without non-crowd annotations). A common training-time preprocessing on COCO dataset. Args: dataset_dicts (list[dict]): annotations in Detectron2 Dataset format. Returns: list[dict]: the same format, but filtered. """ num_before = len(dataset_dicts) def valid(anns): for ann in anns: if ann.get("iscrowd", 0) == 0: return True return False dataset_dicts = [x for x in dataset_dicts if valid(x["annotations"])] num_after = len(dataset_dicts) logger = logging.getLogger(__name__) logger.info( "Removed {} images with no usable annotations. {} images left.".format( num_before - num_after, num_after ) ) return dataset_dicts def filter_images_with_few_keypoints(dataset_dicts, min_keypoints_per_image): """ Filter out images with too few number of keypoints. Args: dataset_dicts (list[dict]): annotations in Detectron2 Dataset format. Returns: list[dict]: the same format as dataset_dicts, but filtered. """ num_before = len(dataset_dicts) def visible_keypoints_in_image(dic): # Each keypoints field has the format [x1, y1, v1, ...], where v is visibility annotations = dic["annotations"] return sum( (np.array(ann["keypoints"][2::3]) > 0).sum() for ann in annotations if "keypoints" in ann ) dataset_dicts = [ x for x in dataset_dicts if visible_keypoints_in_image(x) >= min_keypoints_per_image ] num_after = len(dataset_dicts) logger = logging.getLogger(__name__) logger.info( "Removed {} images with fewer than {} keypoints.".format( num_before - num_after, min_keypoints_per_image ) ) return dataset_dicts def load_proposals_into_dataset(dataset_dicts, proposal_file): """ Load precomputed object proposals into the dataset. The proposal file should be a pickled dict with the following keys: - "ids": list[int] or list[str], the image ids - "boxes": list[np.ndarray], each is an Nx4 array of boxes corresponding to the image id - "objectness_logits": list[np.ndarray], each is an N sized array of objectness scores corresponding to the boxes. - "bbox_mode": the BoxMode of the boxes array. Defaults to ``BoxMode.XYXY_ABS``. Args: dataset_dicts (list[dict]): annotations in Detectron2 Dataset format. proposal_file (str): file path of pre-computed proposals, in pkl format. Returns: list[dict]: the same format as dataset_dicts, but added proposal field. """ logger = logging.getLogger(__name__) logger.info("Loading proposals from: {}".format(proposal_file)) with PathManager.open(proposal_file, "rb") as f: proposals = pickle.load(f, encoding="latin1") # Rename the key names in D1 proposal files rename_keys = {"indexes": "ids", "scores": "objectness_logits"} for key in rename_keys: if key in proposals: proposals[rename_keys[key]] = proposals.pop(key) # Fetch the indexes of all proposals that are in the dataset # Convert image_id to str since they could be int. img_ids = set({str(record["image_id"]) for record in dataset_dicts}) id_to_index = {str(id): i for i, id in enumerate(proposals["ids"]) if str(id) in img_ids} # Assuming default bbox_mode of precomputed proposals are 'XYXY_ABS' bbox_mode = BoxMode(proposals["bbox_mode"]) if "bbox_mode" in proposals else BoxMode.XYXY_ABS for record in dataset_dicts: # Get the index of the proposal i = id_to_index[str(record["image_id"])] boxes = proposals["boxes"][i] objectness_logits = proposals["objectness_logits"][i] # Sort the proposals in descending order of the scores inds = objectness_logits.argsort()[::-1] record["proposal_boxes"] = boxes[inds] record["proposal_objectness_logits"] = objectness_logits[inds] record["proposal_bbox_mode"] = bbox_mode return dataset_dicts def print_instances_class_histogram(dataset_dicts, class_names): """ Args: dataset_dicts (list[dict]): list of dataset dicts. class_names (list[str]): list of class names (zero-indexed). """ num_classes = len(class_names) hist_bins = np.arange(num_classes + 1) histogram = np.zeros((num_classes,), dtype=np.int) for entry in dataset_dicts: annos = entry["annotations"] classes = np.asarray( [x["category_id"] for x in annos if not x.get("iscrowd", 0)], dtype=np.int ) if len(classes): assert classes.min() >= 0, f"Got an invalid category_id={classes.min()}" assert ( classes.max() < num_classes ), f"Got an invalid category_id={classes.max()} for a dataset of {num_classes} classes" histogram += np.histogram(classes, bins=hist_bins)[0] N_COLS = min(6, len(class_names) * 2) def short_name(x): # make long class names shorter. useful for lvis if len(x) > 13: return x[:11] + ".." return x data = list( itertools.chain(*[[short_name(class_names[i]), int(v)] for i, v in enumerate(histogram)]) ) total_num_instances = sum(data[1::2]) data.extend([None] * (N_COLS - (len(data) % N_COLS))) if num_classes > 1: data.extend(["total", total_num_instances]) data = itertools.zip_longest(*[data[i::N_COLS] for i in range(N_COLS)]) table = tabulate( data, headers=["category", "#instances"] * (N_COLS // 2), tablefmt="pipe", numalign="left", stralign="center", ) log_first_n( logging.INFO, "Distribution of instances among all {} categories:\n".format(num_classes) + colored(table, "cyan"), key="message", ) def get_detection_dataset_dicts( names, filter_empty=True, min_keypoints=0, proposal_files=None, check_consistency=True, ): """ Load and prepare dataset dicts for instance detection/segmentation and semantic segmentation. Args: names (str or list[str]): a dataset name or a list of dataset names filter_empty (bool): whether to filter out images without instance annotations min_keypoints (int): filter out images with fewer keypoints than `min_keypoints`. Set to 0 to do nothing. proposal_files (list[str]): if given, a list of object proposal files that match each dataset in `names`. check_consistency (bool): whether to check if datasets have consistent metadata. Returns: list[dict]: a list of dicts following the standard dataset dict format. """ if isinstance(names, str): names = [names] assert len(names), names dataset_dicts = [DatasetCatalog.get(dataset_name) for dataset_name in names] if isinstance(dataset_dicts[0], torchdata.Dataset): if len(dataset_dicts) > 1: # ConcatDataset does not work for iterable style dataset. # We could support concat for iterable as well, but it's often # not a good idea to concat iterables anyway. return torchdata.ConcatDataset(dataset_dicts) return dataset_dicts[0] for dataset_name, dicts in zip(names, dataset_dicts): assert len(dicts), "Dataset '{}' is empty!".format(dataset_name) if proposal_files is not None: assert len(names) == len(proposal_files) # load precomputed proposals from proposal files dataset_dicts = [ load_proposals_into_dataset(dataset_i_dicts, proposal_file) for dataset_i_dicts, proposal_file in zip(dataset_dicts, proposal_files) ] dataset_dicts = list(itertools.chain.from_iterable(dataset_dicts)) has_instances = "annotations" in dataset_dicts[0] if filter_empty and has_instances: dataset_dicts = filter_images_with_only_crowd_annotations(dataset_dicts) if min_keypoints > 0 and has_instances: dataset_dicts = filter_images_with_few_keypoints(dataset_dicts, min_keypoints) if check_consistency and has_instances: try: class_names = MetadataCatalog.get(names[0]).thing_classes check_metadata_consistency("thing_classes", names) print_instances_class_histogram(dataset_dicts, class_names) except AttributeError: # class names are not available for this dataset pass assert len(dataset_dicts), "No valid data found in {}.".format(",".join(names)) return dataset_dicts def build_batch_data_loader( dataset, sampler, total_batch_size, *, aspect_ratio_grouping=False, num_workers=0, collate_fn=None, ): """ Build a batched dataloader. The main differences from `torch.utils.data.DataLoader` are: 1. support aspect ratio grouping options 2. use no "batch collation", because this is common for detection training Args: dataset (torch.utils.data.Dataset): a pytorch map-style or iterable dataset. sampler (torch.utils.data.sampler.Sampler or None): a sampler that produces indices. Must be provided iff. ``dataset`` is a map-style dataset. total_batch_size, aspect_ratio_grouping, num_workers, collate_fn: see :func:`build_detection_train_loader`. Returns: iterable[list]. Length of each list is the batch size of the current GPU. Each element in the list comes from the dataset. """ world_size = get_world_size() assert ( total_batch_size > 0 and total_batch_size % world_size == 0 ), "Total batch size ({}) must be divisible by the number of gpus ({}).".format( total_batch_size, world_size ) batch_size = total_batch_size // world_size if isinstance(dataset, torchdata.IterableDataset): assert sampler is None, "sampler must be None if dataset is IterableDataset" else: dataset = ToIterableDataset(dataset, sampler) if aspect_ratio_grouping: data_loader = torchdata.DataLoader( dataset, num_workers=num_workers, collate_fn=operator.itemgetter(0), # don't batch, but yield individual elements worker_init_fn=worker_init_reset_seed, ) # yield individual mapped dict data_loader = AspectRatioGroupedDataset(data_loader, batch_size) if collate_fn is None: return data_loader return MapDataset(data_loader, collate_fn) else: return torchdata.DataLoader( dataset, batch_size=batch_size, drop_last=True, num_workers=num_workers, collate_fn=trivial_batch_collator if collate_fn is None else collate_fn, worker_init_fn=worker_init_reset_seed, ) def _train_loader_from_config(cfg, mapper=None, *, dataset=None, sampler=None): if dataset is None: dataset = get_detection_dataset_dicts( cfg.DATASETS.TRAIN, filter_empty=cfg.DATALOADER.FILTER_EMPTY_ANNOTATIONS, min_keypoints=cfg.MODEL.ROI_KEYPOINT_HEAD.MIN_KEYPOINTS_PER_IMAGE if cfg.MODEL.KEYPOINT_ON else 0, proposal_files=cfg.DATASETS.PROPOSAL_FILES_TRAIN if cfg.MODEL.LOAD_PROPOSALS else None, ) _log_api_usage("dataset." + cfg.DATASETS.TRAIN[0]) if mapper is None: mapper = DatasetMapper(cfg, True) if sampler is None: sampler_name = cfg.DATALOADER.SAMPLER_TRAIN logger = logging.getLogger(__name__) if isinstance(dataset, torchdata.IterableDataset): logger.info("Not using any sampler since the dataset is IterableDataset.") sampler = None else: logger.info("Using training sampler {}".format(sampler_name)) if sampler_name == "TrainingSampler": sampler = TrainingSampler(len(dataset)) elif sampler_name == "RepeatFactorTrainingSampler": repeat_factors = RepeatFactorTrainingSampler.repeat_factors_from_category_frequency( dataset, cfg.DATALOADER.REPEAT_THRESHOLD ) sampler = RepeatFactorTrainingSampler(repeat_factors) elif sampler_name == "RandomSubsetTrainingSampler": sampler = RandomSubsetTrainingSampler( len(dataset), cfg.DATALOADER.RANDOM_SUBSET_RATIO ) else: raise ValueError("Unknown training sampler: {}".format(sampler_name)) return { "dataset": dataset, "sampler": sampler, "mapper": mapper, "total_batch_size": cfg.SOLVER.IMS_PER_BATCH, "aspect_ratio_grouping": cfg.DATALOADER.ASPECT_RATIO_GROUPING, "num_workers": cfg.DATALOADER.NUM_WORKERS, } @configurable(from_config=_train_loader_from_config) def build_detection_train_loader( dataset, *, mapper, sampler=None, total_batch_size, aspect_ratio_grouping=True, num_workers=0, collate_fn=None, ): """ Build a dataloader for object detection with some default features. Args: dataset (list or torch.utils.data.Dataset): a list of dataset dicts, or a pytorch dataset (either map-style or iterable). It can be obtained by using :func:`DatasetCatalog.get` or :func:`get_detection_dataset_dicts`. mapper (callable): a callable which takes a sample (dict) from dataset and returns the format to be consumed by the model. When using cfg, the default choice is ``DatasetMapper(cfg, is_train=True)``. sampler (torch.utils.data.sampler.Sampler or None): a sampler that produces indices to be applied on ``dataset``. If ``dataset`` is map-style, the default sampler is a :class:`TrainingSampler`, which coordinates an infinite random shuffle sequence across all workers. Sampler must be None if ``dataset`` is iterable. total_batch_size (int): total batch size across all workers. aspect_ratio_grouping (bool): whether to group images with similar aspect ratio for efficiency. When enabled, it requires each element in dataset be a dict with keys "width" and "height". num_workers (int): number of parallel data loading workers collate_fn: a function that determines how to do batching, same as the argument of `torch.utils.data.DataLoader`. Defaults to do no collation and return a list of data. No collation is OK for small batch size and simple data structures. If your batch size is large and each sample contains too many small tensors, it's more efficient to collate them in data loader. Returns: torch.utils.data.DataLoader: a dataloader. Each output from it is a ``list[mapped_element]`` of length ``total_batch_size / num_workers``, where ``mapped_element`` is produced by the ``mapper``. """ if isinstance(dataset, list): dataset = DatasetFromList(dataset, copy=False) if mapper is not None: dataset = MapDataset(dataset, mapper) if isinstance(dataset, torchdata.IterableDataset): assert sampler is None, "sampler must be None if dataset is IterableDataset" else: if sampler is None: sampler = TrainingSampler(len(dataset)) assert isinstance(sampler, torchdata.Sampler), f"Expect a Sampler but got {type(sampler)}" return build_batch_data_loader( dataset, sampler, total_batch_size, aspect_ratio_grouping=aspect_ratio_grouping, num_workers=num_workers, collate_fn=collate_fn, ) def _test_loader_from_config(cfg, dataset_name, mapper=None, strong_aug=False): """ Uses the given `dataset_name` argument (instead of the names in cfg), because the standard practice is to evaluate each test set individually (not combining them). """ if isinstance(dataset_name, str): dataset_name = [dataset_name] dataset = get_detection_dataset_dicts( dataset_name, filter_empty=False, proposal_files=[ cfg.DATASETS.PROPOSAL_FILES_TEST[list(cfg.DATASETS.TEST).index(x)] for x in dataset_name ] if cfg.MODEL.LOAD_PROPOSALS else None, ) if mapper is None: mapper = DatasetMapper(cfg, False, strong_aug) return { "dataset": dataset, "mapper": mapper, "num_workers": cfg.DATALOADER.NUM_WORKERS, "sampler": InferenceSampler(len(dataset)) if not isinstance(dataset, torchdata.IterableDataset) else None, "batch_size": cfg.SOLVER.IMS_PER_BATCH_TEST } @configurable(from_config=_test_loader_from_config) def build_detection_test_loader( dataset: Union[List[Any], torchdata.Dataset], *, mapper: Callable[[Dict[str, Any]], Any], sampler: Optional[torchdata.Sampler] = None, batch_size: int = 1, num_workers: int = 0, collate_fn: Optional[Callable[[List[Any]], Any]] = None, ) -> torchdata.DataLoader: """ Similar to `build_detection_train_loader`, with default batch size = 1, and sampler = :class:`InferenceSampler`. This sampler coordinates all workers to produce the exact set of all samples. Args: dataset: a list of dataset dicts, or a pytorch dataset (either map-style or iterable). They can be obtained by using :func:`DatasetCatalog.get` or :func:`get_detection_dataset_dicts`. mapper: a callable which takes a sample (dict) from dataset and returns the format to be consumed by the model. When using cfg, the default choice is ``DatasetMapper(cfg, is_train=False)``. sampler: a sampler that produces indices to be applied on ``dataset``. Default to :class:`InferenceSampler`, which splits the dataset across all workers. Sampler must be None if `dataset` is iterable. batch_size: the batch size of the data loader to be created. Default to 1 image per worker since this is the standard when reporting inference time in papers. num_workers: number of parallel data loading workers collate_fn: same as the argument of `torch.utils.data.DataLoader`. Defaults to do no collation and return a list of data. Returns: DataLoader: a torch DataLoader, that loads the given detection dataset, with test-time transformation and batching. Examples: :: data_loader = build_detection_test_loader( DatasetRegistry.get("my_test"), mapper=DatasetMapper(...)) # or, instantiate with a CfgNode: data_loader = build_detection_test_loader(cfg, "my_test") """ if isinstance(dataset, list): dataset = DatasetFromList(dataset, copy=False) if mapper is not None: dataset = MapDataset(dataset, mapper) if isinstance(dataset, torchdata.IterableDataset): assert sampler is None, "sampler must be None if dataset is IterableDataset" else: if sampler is None: sampler = InferenceSampler(len(dataset)) return torchdata.DataLoader( dataset, batch_size=batch_size, sampler=sampler, drop_last=False, num_workers=num_workers, collate_fn=trivial_batch_collator if collate_fn is None else collate_fn, ) def trivial_batch_collator(batch): """ A batch collator that does nothing. """ return batch def worker_init_reset_seed(worker_id): initial_seed = torch.initial_seed() % 2**31 seed_all_rng(initial_seed + worker_id)
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
1fac6bde65fdf5f1f5abad21276844002a40ff1c
f4b60f5e49baf60976987946c20a8ebca4880602
/lib64/python2.7/site-packages/acimodel-1.3_2j-py2.7.egg/cobra/modelimpl/isis/treecalcnodestats1d.py
019aef14e5fac61d0bde8f8f6a69940f6fd965a4
[]
no_license
cqbomb/qytang_aci
12e508d54d9f774b537c33563762e694783d6ba8
a7fab9d6cda7fadcc995672e55c0ef7e7187696e
refs/heads/master
2022-12-21T13:30:05.240231
2018-12-04T01:46:53
2018-12-04T01:46:53
159,911,666
0
0
null
2022-12-07T23:53:02
2018-12-01T05:17:50
Python
UTF-8
Python
false
false
20,460
py
# coding=UTF-8 # ********************************************************************** # Copyright (c) 2013-2016 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 TreeCalcNodeStats1d(Mo): """ A class that represents the most current statistics for FTAG global node in a 1 day sampling interval. This class updates every hour. """ meta = StatsClassMeta("cobra.model.isis.TreeCalcNodeStats1d", "FTAG global node") counter = CounterMeta("spineCount", CounterCategory.COUNTER, "count", "spine count") counter._propRefs[PropCategory.IMPLICIT_LASTREADING] = "spineCountLast" counter._propRefs[PropCategory.IMPLICIT_CUMULATIVE] = "spineCountCum" counter._propRefs[PropCategory.IMPLICIT_PERIODIC] = "spineCountPer" counter._propRefs[PropCategory.IMPLICIT_MIN] = "spineCountMin" counter._propRefs[PropCategory.IMPLICIT_MAX] = "spineCountMax" counter._propRefs[PropCategory.IMPLICIT_AVG] = "spineCountAvg" counter._propRefs[PropCategory.IMPLICIT_SUSPECT] = "spineCountSpct" counter._propRefs[PropCategory.IMPLICIT_BASELINE] = "spineCountBase" counter._propRefs[PropCategory.IMPLICIT_THRESHOLDED] = "spineCountThr" counter._propRefs[PropCategory.IMPLICIT_TREND_BASE] = "spineCountTrBase" counter._propRefs[PropCategory.IMPLICIT_TREND] = "spineCountTr" counter._propRefs[PropCategory.IMPLICIT_RATE] = "spineCountRate" meta._counters.append(counter) counter = CounterMeta("leafCount", CounterCategory.COUNTER, "count", "leaf count") counter._propRefs[PropCategory.IMPLICIT_LASTREADING] = "leafCountLast" counter._propRefs[PropCategory.IMPLICIT_CUMULATIVE] = "leafCountCum" counter._propRefs[PropCategory.IMPLICIT_PERIODIC] = "leafCountPer" counter._propRefs[PropCategory.IMPLICIT_MIN] = "leafCountMin" counter._propRefs[PropCategory.IMPLICIT_MAX] = "leafCountMax" counter._propRefs[PropCategory.IMPLICIT_AVG] = "leafCountAvg" counter._propRefs[PropCategory.IMPLICIT_SUSPECT] = "leafCountSpct" counter._propRefs[PropCategory.IMPLICIT_BASELINE] = "leafCountBase" counter._propRefs[PropCategory.IMPLICIT_THRESHOLDED] = "leafCountThr" counter._propRefs[PropCategory.IMPLICIT_TREND_BASE] = "leafCountTrBase" counter._propRefs[PropCategory.IMPLICIT_TREND] = "leafCountTr" counter._propRefs[PropCategory.IMPLICIT_RATE] = "leafCountRate" meta._counters.append(counter) meta.moClassName = "isisTreeCalcNodeStats1d" meta.rnFormat = "CDisisTreeCalcNodeStats1d" meta.category = MoCategory.STATS_CURRENT meta.label = "current FTAG global node stats in 1 day" meta.writeAccessMask = 0x8008020040001 meta.readAccessMask = 0x8008020040001 meta.isDomainable = False meta.isReadOnly = True meta.isConfigurable = False meta.isDeletable = False meta.isContextRoot = True meta.parentClasses.add("cobra.model.isis.Dom") meta.superClasses.add("cobra.model.stats.Item") meta.superClasses.add("cobra.model.stats.Curr") meta.superClasses.add("cobra.model.isis.TreeCalcNodeStats") meta.rnPrefixes = [ ('CDisisTreeCalcNodeStats1d', False), ] 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", "cnt", "cnt", 16212, PropCategory.REGULAR) prop.label = "Number of Collections During this Interval" prop.isImplicit = True prop.isAdmin = True meta.props.add("cnt", 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", "lastCollOffset", "lastCollOffset", 111, PropCategory.REGULAR) prop.label = "Collection Length" prop.isImplicit = True prop.isAdmin = True meta.props.add("lastCollOffset", prop) prop = PropMeta("str", "leafCountAvg", "leafCountAvg", 9536, PropCategory.IMPLICIT_AVG) prop.label = "leaf count average value" prop.isOper = True prop.isStats = True meta.props.add("leafCountAvg", prop) prop = PropMeta("str", "leafCountBase", "leafCountBase", 9531, PropCategory.IMPLICIT_BASELINE) prop.label = "leaf count baseline" prop.isOper = True prop.isStats = True meta.props.add("leafCountBase", prop) prop = PropMeta("str", "leafCountCum", "leafCountCum", 9532, PropCategory.IMPLICIT_CUMULATIVE) prop.label = "leaf count cumulative" prop.isOper = True prop.isStats = True meta.props.add("leafCountCum", prop) prop = PropMeta("str", "leafCountLast", "leafCountLast", 9530, PropCategory.IMPLICIT_LASTREADING) prop.label = "leaf count current value" prop.isOper = True prop.isStats = True meta.props.add("leafCountLast", prop) prop = PropMeta("str", "leafCountMax", "leafCountMax", 9535, PropCategory.IMPLICIT_MAX) prop.label = "leaf count maximum value" prop.isOper = True prop.isStats = True meta.props.add("leafCountMax", prop) prop = PropMeta("str", "leafCountMin", "leafCountMin", 9534, PropCategory.IMPLICIT_MIN) prop.label = "leaf count minimum value" prop.isOper = True prop.isStats = True meta.props.add("leafCountMin", prop) prop = PropMeta("str", "leafCountPer", "leafCountPer", 9533, PropCategory.IMPLICIT_PERIODIC) prop.label = "leaf count periodic" prop.isOper = True prop.isStats = True meta.props.add("leafCountPer", prop) prop = PropMeta("str", "leafCountRate", "leafCountRate", 9541, PropCategory.IMPLICIT_RATE) prop.label = "leaf count rate" prop.isOper = True prop.isStats = True meta.props.add("leafCountRate", prop) prop = PropMeta("str", "leafCountSpct", "leafCountSpct", 9537, PropCategory.IMPLICIT_SUSPECT) prop.label = "leaf count suspect count" prop.isOper = True prop.isStats = True meta.props.add("leafCountSpct", prop) prop = PropMeta("str", "leafCountThr", "leafCountThr", 9538, PropCategory.IMPLICIT_THRESHOLDED) prop.label = "leaf count thresholded flags" prop.isOper = True prop.isStats = True prop.defaultValue = 0 prop.defaultValueStr = "unspecified" prop._addConstant("avgCrit", "avg-severity-critical", 2199023255552) prop._addConstant("avgHigh", "avg-crossed-high-threshold", 68719476736) prop._addConstant("avgLow", "avg-crossed-low-threshold", 137438953472) prop._addConstant("avgMajor", "avg-severity-major", 1099511627776) prop._addConstant("avgMinor", "avg-severity-minor", 549755813888) prop._addConstant("avgRecovering", "avg-recovering", 34359738368) prop._addConstant("avgWarn", "avg-severity-warning", 274877906944) prop._addConstant("cumulativeCrit", "cumulative-severity-critical", 8192) prop._addConstant("cumulativeHigh", "cumulative-crossed-high-threshold", 256) prop._addConstant("cumulativeLow", "cumulative-crossed-low-threshold", 512) prop._addConstant("cumulativeMajor", "cumulative-severity-major", 4096) prop._addConstant("cumulativeMinor", "cumulative-severity-minor", 2048) prop._addConstant("cumulativeRecovering", "cumulative-recovering", 128) prop._addConstant("cumulativeWarn", "cumulative-severity-warning", 1024) prop._addConstant("lastReadingCrit", "lastreading-severity-critical", 64) prop._addConstant("lastReadingHigh", "lastreading-crossed-high-threshold", 2) prop._addConstant("lastReadingLow", "lastreading-crossed-low-threshold", 4) prop._addConstant("lastReadingMajor", "lastreading-severity-major", 32) prop._addConstant("lastReadingMinor", "lastreading-severity-minor", 16) prop._addConstant("lastReadingRecovering", "lastreading-recovering", 1) prop._addConstant("lastReadingWarn", "lastreading-severity-warning", 8) prop._addConstant("maxCrit", "max-severity-critical", 17179869184) prop._addConstant("maxHigh", "max-crossed-high-threshold", 536870912) prop._addConstant("maxLow", "max-crossed-low-threshold", 1073741824) prop._addConstant("maxMajor", "max-severity-major", 8589934592) prop._addConstant("maxMinor", "max-severity-minor", 4294967296) prop._addConstant("maxRecovering", "max-recovering", 268435456) prop._addConstant("maxWarn", "max-severity-warning", 2147483648) prop._addConstant("minCrit", "min-severity-critical", 134217728) prop._addConstant("minHigh", "min-crossed-high-threshold", 4194304) prop._addConstant("minLow", "min-crossed-low-threshold", 8388608) prop._addConstant("minMajor", "min-severity-major", 67108864) prop._addConstant("minMinor", "min-severity-minor", 33554432) prop._addConstant("minRecovering", "min-recovering", 2097152) prop._addConstant("minWarn", "min-severity-warning", 16777216) prop._addConstant("periodicCrit", "periodic-severity-critical", 1048576) prop._addConstant("periodicHigh", "periodic-crossed-high-threshold", 32768) prop._addConstant("periodicLow", "periodic-crossed-low-threshold", 65536) prop._addConstant("periodicMajor", "periodic-severity-major", 524288) prop._addConstant("periodicMinor", "periodic-severity-minor", 262144) prop._addConstant("periodicRecovering", "periodic-recovering", 16384) prop._addConstant("periodicWarn", "periodic-severity-warning", 131072) prop._addConstant("rateCrit", "rate-severity-critical", 36028797018963968) prop._addConstant("rateHigh", "rate-crossed-high-threshold", 1125899906842624) prop._addConstant("rateLow", "rate-crossed-low-threshold", 2251799813685248) prop._addConstant("rateMajor", "rate-severity-major", 18014398509481984) prop._addConstant("rateMinor", "rate-severity-minor", 9007199254740992) prop._addConstant("rateRecovering", "rate-recovering", 562949953421312) prop._addConstant("rateWarn", "rate-severity-warning", 4503599627370496) prop._addConstant("trendCrit", "trend-severity-critical", 281474976710656) prop._addConstant("trendHigh", "trend-crossed-high-threshold", 8796093022208) prop._addConstant("trendLow", "trend-crossed-low-threshold", 17592186044416) prop._addConstant("trendMajor", "trend-severity-major", 140737488355328) prop._addConstant("trendMinor", "trend-severity-minor", 70368744177664) prop._addConstant("trendRecovering", "trend-recovering", 4398046511104) prop._addConstant("trendWarn", "trend-severity-warning", 35184372088832) prop._addConstant("unspecified", None, 0) meta.props.add("leafCountThr", prop) prop = PropMeta("str", "leafCountTr", "leafCountTr", 9540, PropCategory.IMPLICIT_TREND) prop.label = "leaf count trend" prop.isOper = True prop.isStats = True meta.props.add("leafCountTr", prop) prop = PropMeta("str", "leafCountTrBase", "leafCountTrBase", 9539, PropCategory.IMPLICIT_TREND_BASE) prop.label = "leaf count trend baseline" prop.isOper = True prop.isStats = True meta.props.add("leafCountTrBase", 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", "repIntvEnd", "repIntvEnd", 110, PropCategory.REGULAR) prop.label = "Reporting End Time" prop.isImplicit = True prop.isAdmin = True meta.props.add("repIntvEnd", prop) prop = PropMeta("str", "repIntvStart", "repIntvStart", 109, PropCategory.REGULAR) prop.label = "Reporting Start Time" prop.isImplicit = True prop.isAdmin = True meta.props.add("repIntvStart", 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", "spineCountAvg", "spineCountAvg", 9563, PropCategory.IMPLICIT_AVG) prop.label = "spine count average value" prop.isOper = True prop.isStats = True meta.props.add("spineCountAvg", prop) prop = PropMeta("str", "spineCountBase", "spineCountBase", 9558, PropCategory.IMPLICIT_BASELINE) prop.label = "spine count baseline" prop.isOper = True prop.isStats = True meta.props.add("spineCountBase", prop) prop = PropMeta("str", "spineCountCum", "spineCountCum", 9559, PropCategory.IMPLICIT_CUMULATIVE) prop.label = "spine count cumulative" prop.isOper = True prop.isStats = True meta.props.add("spineCountCum", prop) prop = PropMeta("str", "spineCountLast", "spineCountLast", 9557, PropCategory.IMPLICIT_LASTREADING) prop.label = "spine count current value" prop.isOper = True prop.isStats = True meta.props.add("spineCountLast", prop) prop = PropMeta("str", "spineCountMax", "spineCountMax", 9562, PropCategory.IMPLICIT_MAX) prop.label = "spine count maximum value" prop.isOper = True prop.isStats = True meta.props.add("spineCountMax", prop) prop = PropMeta("str", "spineCountMin", "spineCountMin", 9561, PropCategory.IMPLICIT_MIN) prop.label = "spine count minimum value" prop.isOper = True prop.isStats = True meta.props.add("spineCountMin", prop) prop = PropMeta("str", "spineCountPer", "spineCountPer", 9560, PropCategory.IMPLICIT_PERIODIC) prop.label = "spine count periodic" prop.isOper = True prop.isStats = True meta.props.add("spineCountPer", prop) prop = PropMeta("str", "spineCountRate", "spineCountRate", 9568, PropCategory.IMPLICIT_RATE) prop.label = "spine count rate" prop.isOper = True prop.isStats = True meta.props.add("spineCountRate", prop) prop = PropMeta("str", "spineCountSpct", "spineCountSpct", 9564, PropCategory.IMPLICIT_SUSPECT) prop.label = "spine count suspect count" prop.isOper = True prop.isStats = True meta.props.add("spineCountSpct", prop) prop = PropMeta("str", "spineCountThr", "spineCountThr", 9565, PropCategory.IMPLICIT_THRESHOLDED) prop.label = "spine count thresholded flags" prop.isOper = True prop.isStats = True prop.defaultValue = 0 prop.defaultValueStr = "unspecified" prop._addConstant("avgCrit", "avg-severity-critical", 2199023255552) prop._addConstant("avgHigh", "avg-crossed-high-threshold", 68719476736) prop._addConstant("avgLow", "avg-crossed-low-threshold", 137438953472) prop._addConstant("avgMajor", "avg-severity-major", 1099511627776) prop._addConstant("avgMinor", "avg-severity-minor", 549755813888) prop._addConstant("avgRecovering", "avg-recovering", 34359738368) prop._addConstant("avgWarn", "avg-severity-warning", 274877906944) prop._addConstant("cumulativeCrit", "cumulative-severity-critical", 8192) prop._addConstant("cumulativeHigh", "cumulative-crossed-high-threshold", 256) prop._addConstant("cumulativeLow", "cumulative-crossed-low-threshold", 512) prop._addConstant("cumulativeMajor", "cumulative-severity-major", 4096) prop._addConstant("cumulativeMinor", "cumulative-severity-minor", 2048) prop._addConstant("cumulativeRecovering", "cumulative-recovering", 128) prop._addConstant("cumulativeWarn", "cumulative-severity-warning", 1024) prop._addConstant("lastReadingCrit", "lastreading-severity-critical", 64) prop._addConstant("lastReadingHigh", "lastreading-crossed-high-threshold", 2) prop._addConstant("lastReadingLow", "lastreading-crossed-low-threshold", 4) prop._addConstant("lastReadingMajor", "lastreading-severity-major", 32) prop._addConstant("lastReadingMinor", "lastreading-severity-minor", 16) prop._addConstant("lastReadingRecovering", "lastreading-recovering", 1) prop._addConstant("lastReadingWarn", "lastreading-severity-warning", 8) prop._addConstant("maxCrit", "max-severity-critical", 17179869184) prop._addConstant("maxHigh", "max-crossed-high-threshold", 536870912) prop._addConstant("maxLow", "max-crossed-low-threshold", 1073741824) prop._addConstant("maxMajor", "max-severity-major", 8589934592) prop._addConstant("maxMinor", "max-severity-minor", 4294967296) prop._addConstant("maxRecovering", "max-recovering", 268435456) prop._addConstant("maxWarn", "max-severity-warning", 2147483648) prop._addConstant("minCrit", "min-severity-critical", 134217728) prop._addConstant("minHigh", "min-crossed-high-threshold", 4194304) prop._addConstant("minLow", "min-crossed-low-threshold", 8388608) prop._addConstant("minMajor", "min-severity-major", 67108864) prop._addConstant("minMinor", "min-severity-minor", 33554432) prop._addConstant("minRecovering", "min-recovering", 2097152) prop._addConstant("minWarn", "min-severity-warning", 16777216) prop._addConstant("periodicCrit", "periodic-severity-critical", 1048576) prop._addConstant("periodicHigh", "periodic-crossed-high-threshold", 32768) prop._addConstant("periodicLow", "periodic-crossed-low-threshold", 65536) prop._addConstant("periodicMajor", "periodic-severity-major", 524288) prop._addConstant("periodicMinor", "periodic-severity-minor", 262144) prop._addConstant("periodicRecovering", "periodic-recovering", 16384) prop._addConstant("periodicWarn", "periodic-severity-warning", 131072) prop._addConstant("rateCrit", "rate-severity-critical", 36028797018963968) prop._addConstant("rateHigh", "rate-crossed-high-threshold", 1125899906842624) prop._addConstant("rateLow", "rate-crossed-low-threshold", 2251799813685248) prop._addConstant("rateMajor", "rate-severity-major", 18014398509481984) prop._addConstant("rateMinor", "rate-severity-minor", 9007199254740992) prop._addConstant("rateRecovering", "rate-recovering", 562949953421312) prop._addConstant("rateWarn", "rate-severity-warning", 4503599627370496) prop._addConstant("trendCrit", "trend-severity-critical", 281474976710656) prop._addConstant("trendHigh", "trend-crossed-high-threshold", 8796093022208) prop._addConstant("trendLow", "trend-crossed-low-threshold", 17592186044416) prop._addConstant("trendMajor", "trend-severity-major", 140737488355328) prop._addConstant("trendMinor", "trend-severity-minor", 70368744177664) prop._addConstant("trendRecovering", "trend-recovering", 4398046511104) prop._addConstant("trendWarn", "trend-severity-warning", 35184372088832) prop._addConstant("unspecified", None, 0) meta.props.add("spineCountThr", prop) prop = PropMeta("str", "spineCountTr", "spineCountTr", 9567, PropCategory.IMPLICIT_TREND) prop.label = "spine count trend" prop.isOper = True prop.isStats = True meta.props.add("spineCountTr", prop) prop = PropMeta("str", "spineCountTrBase", "spineCountTrBase", 9566, PropCategory.IMPLICIT_TREND_BASE) prop.label = "spine count trend baseline" prop.isOper = True prop.isStats = True meta.props.add("spineCountTrBase", 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) def __init__(self, parentMoOrDn, markDirty=True, **creationProps): namingVals = [] Mo.__init__(self, parentMoOrDn, markDirty, *namingVals, **creationProps) # End of package file # ##################################################
[ "collinsctk@qytang.com" ]
collinsctk@qytang.com
ec6006c50785e0e8b157893e35b4789999df4d00
6be8aa517e679b33b47d35f100e6590902a8a1db
/Greedy/MST/Problem06.py
403924f5fc49aba57dc94d7603a32fc491a619fb
[]
no_license
LeeJuhae/Algorithm-Python
7ca4762712e5e84d1e277abecb3bf39c9cbd4e56
729947b4428205adfbac194a5527b0eeafe1c525
refs/heads/master
2023-04-24T01:02:36.430970
2021-05-23T07:17:25
2021-05-23T07:17:25
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,081
py
# https://www.acmicpc.net/problem/17472 import sys from collections import deque, defaultdict directions = ((1, 0), (0, 1), (-1, 0), (0, -1)) read = sys.stdin.readline n, m = map(int, read().strip().split()) islands = [list(map(int, read().strip().split())) for _ in range(n)] v = 0 visit = [[0 for _ in range(m)] for _ in range(n)] locations = defaultdict(list) for a in range(n): for j in range(m): if islands[a][j] and not visit[a][j]: visit[a][j] = v + 1 locations[visit[a][j]].append((a, j)) q = deque([(a, j)]) while q: x, y = q.popleft() for dx, dy in directions: nx, ny = x + dx, y + dy if nx < 0 or ny < 0 or nx >= n or ny >= m or visit[nx][ny] != 0: continue if islands[a][j] != islands[nx][ny]: continue q.append((nx, ny)) visit[nx][ny] = v + 1 locations[visit[nx][ny]].append((nx, ny)) v += 1 islands = visit bridges = [] def getEdge(island, x, y): ret = [] for dx, dy in directions: nx, ny, d = x, y, 0 while True: nx, ny = nx + dx, ny + dy if nx < 0 or ny < 0 or nx >= n or ny >= m: break if islands[nx][ny]: if island == islands[nx][ny] or d == 1: break ret.append((islands[nx][ny], d)) break d += 1 return ret for a in range(1, v + 1): for x, y in locations[a]: for b, c in getEdge(a, x, y): bridges.append((c, a, b)) bridges.sort() ans = 0 tree = [i for i in range(v + 1)] def find(idx): if idx == tree[idx]: return idx tree[idx] = find(tree[idx]) return tree[idx] def merge(a, b): a, b = find(a), find(b) tree[b] = a cnt = 0 for c, a, b in bridges: if find(a) != find(b): merge(a, b) ans += c cnt += 1 print(ans if cnt == v - 1 else -1)
[ "gusdn0657@gmail.com" ]
gusdn0657@gmail.com
5ea58c5b4506ca5eba55364cae0aa1b3d9f5e864
b4afb44b8f483c048716fe12d778186ce68ac846
/pages/ios/ffan/movie_page_configs.py
cdc95760ceb5ada9045205274bfe84e52614c57f
[]
no_license
liu111xiao111/UItest
64309b2c85f6d2334d64bb0875ba9ced459ebb1e
67e2acc9a99da81022e286e8d8ec7ccb12636ff3
refs/heads/master
2021-09-01T18:30:28.044296
2017-12-28T04:36:46
2017-12-28T04:36:46
115,585,226
1
0
null
null
null
null
UTF-8
Python
false
false
921
py
#!/usr/bin/env python # -*- coding:utf-8 -*- class MoviePageConfigs(object): ''' This is a configuration class for MoviePage class. ''' # Assert view time out assert_view_timeout = 10 # Verify view time out verify_view_timeout = 10 # Assert invalid view time out assert_invalid_view_time = 3 # Click button time out click_on_button_timeout = 10 # Get time out get_timeout = 10 # Movie title text_movie_title = u"电影" # Seat picking and buying ticket button resource_id_seat_picking_and_buying_ticket_button = "com.wanda.app.wanhui:id/movie_buy_ticket" xpath_seat_picking_and_buying_ticket_bt = "//UIAApplication[1]/UIAWindow[1]/UIATableView[1]/UIATableCell[1]/UIAButton[1]" xpath_film_name = "//UIAApplication[1]/UIAWindow[1]/UIATableView[1]/UIATableCell[1]/UIAStaticText[1]" def __init__(self): pass
[ "tl@neusoft.com" ]
tl@neusoft.com
a9316fca169c00cd96bfefb8ba8ffbead21d8a48
0cb72fac7926b7415af3bff1bf7dbe03e96fead5
/LC_Non_Decreasing_Array.py
ca41f20ed70e4daf05dfc1ccff9b789768309e9f
[]
no_license
venkatsvpr/Problems_Solved
586b5ef9f5868785cb52552da674ed003e139278
11c81645893fd65f585c3f558ea837c7dd3cb654
refs/heads/master
2022-11-11T21:53:27.469213
2022-10-14T05:59:11
2022-10-14T05:59:11
114,329,154
5
1
null
null
null
null
UTF-8
Python
false
false
1,785
py
""" 665. Non-decreasing Array Given an array with n integers, your task is to check if it could become non-decreasing by modifying at most 1 element. We define an array is non-decreasing if array[i] <= array[i + 1] holds for every i (1 <= i < n). Example 1: Input: [4,2,3] Output: True Explanation: You could modify the first 4 to 1 to get a non-decreasing array. Example 2: Input: [4,2,1] Output: False Explanation: You can't get a non-decreasing array by modify at most one element. Note: The n belongs to [1, 10,000]. """ """ Simple logic Step 1: Traverse from left to right.. there should be only one position where we find a high to low conversion. if we find second it is not possible Step 2: Traverse from right to left... there should be only one position where we find a low to high conversion. If we find second it is not possible. Either of step 1 and step2 should be true. """ class Solution(object): def checkPossibility(self, nums): """ :type nums: List[int] :rtype: bool """ flag = False count = 0 prev = nums[0] for i in range(1,len(nums)): if (nums[i] < prev): if (flag == True): count = 1 break; flag = True continue; prev = nums[i] if (count == 0): return True flag = False prev = nums[len(nums)-1] count = 0 for i in range(len(nums)-2, -1,-1): if (nums[i] > prev): if (flag == True): count = 1 break; flag = True continue; prev = nums[i] if (count == 0): return True return False
[ "venkatakrishnansvpr@gmail.com" ]
venkatakrishnansvpr@gmail.com
32226188a7bed68e781ad02fb2608f42c19404c7
a3cc7286d4a319cb76f3a44a593c4a18e5ddc104
/lib/googlecloudsdk/core/util/keyboard_interrupt.py
8a1c992f84aeaeb3bed44caaeb72156c683c93d1
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
jordanistan/Google-Cloud-SDK
f2c6bb7abc2f33b9dfaec5de792aa1be91154099
42b9d7914c36a30d1e4b84ae2925df7edeca9962
refs/heads/master
2023-09-01T01:24:53.495537
2023-08-22T01:12:23
2023-08-22T01:12:23
127,072,491
0
1
NOASSERTION
2023-08-22T01:12:24
2018-03-28T02:31:19
Python
UTF-8
Python
false
false
1,941
py
# Copyright 2017 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Cloud SDK default keyboard interrupt handler.""" from __future__ import absolute_import from __future__ import division import os import signal import sys from googlecloudsdk.core import log def HandleInterrupt(signal_number=None, frame=None): """Handles keyboard interrupts (aka SIGINT, ^C). Disables the stack trace when a command is killed by keyboard interrupt. Args: signal_number: The interrupt signal number. frame: The signal stack frame context. """ del signal_number, frame # currently unused message = '\n\nCommand killed by keyboard interrupt\n' try: log.err.Print(message) except NameError: sys.stderr.write(message) # Kill ourselves with SIGINT so our parent can detect that we exited because # of a signal. SIG_DFL disables further KeyboardInterrupt exceptions. signal.signal(signal.SIGINT, signal.SIG_DFL) os.kill(os.getpid(), signal.SIGINT) # Just in case the kill failed ... sys.exit(1) def InstallHandler(): """Installs the default Cloud SDK keyboard interrupt handler.""" try: signal.signal(signal.SIGINT, HandleInterrupt) except ValueError: # Signal cannot be sent from non-main threads. Integration testing will # run parallel threads for performance reasons, occasionally hitting this # exception. Should not be reached in production. pass
[ "jordan.robison@gmail.com" ]
jordan.robison@gmail.com
591261811f03add0430c0fb4333e9d46e62d9105
c3ff891e0e23c5f9488508d30349259cc6b64b4d
/python练习/老王开枪/老王开枪2.py
1897dcbc68707445a20bba1d7fbb9ffb4d19a52b
[]
no_license
JacksonMike/python_exercise
2af2b8913ec8aded8a17a98aaa0fc9c6ccd7ba53
7698f8ce260439abb3cbdf478586fa1888791a61
refs/heads/master
2020-07-14T18:16:39.265372
2019-08-30T11:56:29
2019-08-30T11:56:29
205,370,953
0
0
null
null
null
null
UTF-8
Python
false
false
2,754
py
class Person(): def __init__(self,name): super(Person,self).__init__() self.name = name self.gun = None self.hp = 100 def install_bullet(self,clip_temp,bullet_temp): clip_temp.store_bullet(bullet_temp) def install_clip(self,gun_temp,clip_temp): gun_temp.store_clip(clip_temp) def hold_gun(self,gun_temp): self.gun = gun_temp def __str__(self): if self.gun: return "%s的血量为%d,他有枪%s"%(self.name,self.hp,self.gun) else: if self.hp > 0: return "%s的血量为%d,他没有枪"%(self.name,self.hp) else: return "%s已经死去"%self.name def use_gun(self,enemy): self.gun.fire(enemy) def lose_blood(self,power): self.hp -= power class Gun(): def __init__(self,name): super(Gun,self).__init__() self.name = name self.clip = None def store_clip(self,clip_temp): self.clip = clip_temp def __str__(self): if self.clip: return "枪的信息为%s,%s"%(self.name,self.clip) else: return "枪的信息为%s,这把枪没有弹夹"%(self.name) def fire(self,enemy): bullet_temp = self.clip.eject_clip() if bullet_temp: bullet_temp.shoot(enemy) else: return "弹夹没子弹了" class Clip(): def __init__(self,max_num): super(Clip,self).__init__() self.max_num = max_num self.bullet_list = [] def store_bullet(self,bullet_temp): self.bullet_list.append(bullet_temp) def __str__(self): return "弹夹的信息为%d/%d"%(len(self.bullet_list),self.max_num) def eject_clip(self): if self.bullet_list: return self.bullet_list.pop() else: return None class Bullet(): def __init__(self,power): super(Bullet,self).__init__() self.power = power def shoot(self,enemy): enemy.lose_blood(self.power) def main(): laowang = Person("Jim") Barrett = Gun("巴雷特") clip = Clip(20) for i in range(15): bullet = Bullet(20) laowang.install_bullet(clip,bullet) laowang.install_clip(Barrett,clip) print(Barrett) print(clip) laowang.hold_gun(Barrett) laosong = Person("Kent") print(laosong) laowang.use_gun(laosong) print(laowang) print(laosong) laowang.use_gun(laosong) print(laowang) print(laosong) laowang.use_gun(laosong) print(laowang) print(laosong) laowang.use_gun(laosong) print(laowang) print(laosong) laowang.use_gun(laosong) print(laowang) print(laosong) if __name__ == '__main__': main()
[ "2101706902@qq.com" ]
2101706902@qq.com
a24eae2a57094a02b726d84a5b8fa1291192c8f5
53784d3746eccb6d8fca540be9087a12f3713d1c
/res/packages/scripts/scripts/client/tutorial/doc_loader/sub_parsers/quests.py
ab4c7a0dda44086cdaa465d5711086060442461e
[]
no_license
webiumsk/WOT-0.9.17.1-CT
736666d53cbd0da6745b970e90a8bac6ea80813d
d7c3cf340ae40318933e7205bf9a17c7e53bac52
refs/heads/master
2021-01-09T06:00:33.898009
2017-02-03T21:40:17
2017-02-03T21:40:17
80,870,824
0
0
null
null
null
null
WINDOWS-1250
Python
false
false
7,831
py
# 2017.02.03 21:54:21 Střední Evropa (běžný čas) # Embedded file name: scripts/client/tutorial/doc_loader/sub_parsers/quests.py from tutorial.control.quests import triggers from tutorial.doc_loader import sub_parsers from tutorial.doc_loader.sub_parsers import chains, readVarValue from tutorial.doc_loader.sub_parsers import lobby from items import _xml from tutorial.data import chapter from tutorial.data import effects _EFFECT_TYPE = effects.EFFECT_TYPE def _readAllTurorialBonusesTriggerSection(xmlCtx, section, chapter, triggerID): return sub_parsers.readValidateVarTriggerSection(xmlCtx, section, triggerID, triggers.AllTutorialBonusesTrigger) def _readInvalidateFlagsTriggerSection(xmlCtx, section, chapter, triggerID): return triggers.InvalidateFlagsTrigger(triggerID) def _readRandomBattlesCountTriggerSection(xmlCtx, section, chapter, triggerID): return triggers.RandomBattlesCountTrigger(triggerID) def _readResearchModuleTriggerSection(xmlCtx, section, chapter, triggerID): return triggers.ResearchModuleTrigger(triggerID) def _readInstallModuleTriggerSection(xmlCtx, section, chapter, triggerID): return triggers.InstallModuleTrigger(triggerID) def _readResearchVehicleTriggerSection(xmlCtx, section, chapter, triggerID): return sub_parsers.readValidateVarTriggerSection(xmlCtx, section, triggerID, triggers.ResearchVehicleTrigger) def _readBuyVehicleTriggerSection(xmlCtx, section, chapter, triggerID): return sub_parsers.readValidateVarTriggerSection(xmlCtx, section, triggerID, triggers.BuyVehicleTrigger) def _readInventoryVehicleTriggerSection(xmlCtx, section, chapter, triggerID): return sub_parsers.readValidateVarTriggerSection(xmlCtx, section, triggerID, triggers.InventoryVehicleTrigger) def _readPermanentVehicleOwnTriggerSection(xmlCtx, section, chapter, triggerID): return sub_parsers.readValidateVarTriggerSection(xmlCtx, section, triggerID, triggers.PermanentVehicleOwnTrigger) def _readXpExchangeTriggerSection(xmlCtx, section, chapter, triggerID): return triggers.XpExchangeTrigger(triggerID) def _readVehicleBattlesCountTriggerSection(xmlCtx, section, chapter, triggerID): return sub_parsers.readValidateVarTriggerSection(xmlCtx, section, triggerID, triggers.VehicleBattleCountTrigger) def readTutorialIntSettingTriggerSection(xmlCtx, section, _, triggerID): return sub_parsers.readValidateVarTriggerSection(xmlCtx, section, triggerID, triggers.TutorialIntSettingsTrigger) def readTutorialAccountSettingTriggerSection(xmlCtx, section, _, triggerID): return sub_parsers.readValidateVarTriggerSection(xmlCtx, section, triggerID, triggers.TutorialAccountSettingsTrigger) def _readChapterBonusTriggerSection(xmlCtx, section, _, triggerID): return sub_parsers.readValidateVarTriggerSection(xmlCtx, section, triggerID, triggers.ChapterBonusTrigger) def _readItemsInstallTriggerSection(xmlCtx, section, _, triggerID): return sub_parsers.readValidateVarTriggerSection(xmlCtx, section, triggerID, triggers.InstallItemsTrigger) def _readTimerTriggerSection(xmlCtx, section, _, triggerID): return sub_parsers.readValidateVarTriggerSection(xmlCtx, section, triggerID, triggers.TimerTrigger) def readSaveTutorialSettingSection(xmlCtx, section, _, conditions): settingID = sub_parsers.parseID(xmlCtx, section, 'Specify a setting ID') return effects.HasTargetEffect(settingID, _EFFECT_TYPE.SAVE_TUTORIAL_SETTING, conditions=conditions) def readSaveAccountSettingSection(xmlCtx, section, _, conditions): settingID = sub_parsers.parseID(xmlCtx, section, 'Specify a setting ID') return effects.HasTargetEffect(settingID, _EFFECT_TYPE.SAVE_ACCOUNT_SETTING, conditions=conditions) def readTutorialSettingSection(xmlCtx, section, flags): settingID = sub_parsers.parseID(xmlCtx, section, 'Specify a setting ID') settingName = None if 'setting-name' in section.keys(): settingName = _xml.readString(xmlCtx, section, 'setting-name') else: _xml.raiseWrongXml(xmlCtx, section.name, 'Specify a setting name') settingValue = None if 'setting-value' in section.keys(): settingValue = _xml.readBool(xmlCtx, section, 'setting-value') else: _xml.raiseWrongXml(xmlCtx, section.name, 'Specify a setting value') return chapter.TutorialSetting(settingID, settingName, settingValue) def readQuestConditions(section): result = [] valuesSec = section['quest-conditions'] if valuesSec is not None: for name, conditionsSection in valuesSec.items(): valueType, valueSec = conditionsSection.items()[0] result.append(readVarValue(valueType, valueSec)) return result def _readSimpleWindowCloseTriggerSection(xmlCtx, section, _, triggerID): return sub_parsers.readValidateVarTriggerSection(xmlCtx, section, triggerID, triggers.SimpleWindowCloseTrigger, validateUpdateOnly='validate-update-only' in section.keys()) def _readSimpleWindowProcessTriggerSection(xmlCtx, section, _, triggerID): return sub_parsers.readValidateVarTriggerSection(xmlCtx, section, triggerID, triggers.SimpleWindowProcessTrigger, validateUpdateOnly='validate-update-only' in section.keys()) def _readSelectVehicleInHangarSection(xmlCtx, section, flags, conditions): targetID = section.asString return effects.HasTargetEffect(targetID, effects.EFFECT_TYPE.SELECT_VEHICLE_IN_HANGAR, conditions=conditions) def init(): sub_parsers.setEffectsParsers({'save-setting': readSaveTutorialSettingSection, 'save-account-setting': readSaveAccountSettingSection, 'show-unlocked-chapter': chains.readShowUnlockedChapterSection, 'switch-to-random': lobby.readSwitchToRandomSection, 'select-in-hangar': _readSelectVehicleInHangarSection}) sub_parsers.setEntitiesParsers({'hint': chains.readHintSection, 'tutorial-setting': readTutorialSettingSection}) sub_parsers.setTriggersParsers({'bonus': lobby.readBonusTriggerSection, 'premiumDiscount': lobby.readPremiumDiscountsUseTriggerSection, 'tankmanAcademyDiscount': chains.readTankmanPriceDiscountTriggerSection, 'allTutorialBonuses': _readAllTurorialBonusesTriggerSection, 'randomBattlesCount': _readRandomBattlesCountTriggerSection, 'researchModule': _readResearchModuleTriggerSection, 'installModule': _readInstallModuleTriggerSection, 'researchVehicle': _readResearchVehicleTriggerSection, 'buyVehicle': _readBuyVehicleTriggerSection, 'inventoryVehicle': _readInventoryVehicleTriggerSection, 'permanentOwnVehicle': _readPermanentVehicleOwnTriggerSection, 'buySlot': lobby.readFreeVehicleSlotTriggerSection, 'vehicleBattlesCount': _readVehicleBattlesCountTriggerSection, 'xpExchange': _readXpExchangeTriggerSection, 'tutorialIntSetting': readTutorialIntSettingTriggerSection, 'tutorialAccountSetting': readTutorialAccountSettingTriggerSection, 'chapterBonus': _readChapterBonusTriggerSection, 'installItems': _readItemsInstallTriggerSection, 'invalidateFlags': _readInvalidateFlagsTriggerSection, 'timer': _readTimerTriggerSection, 'fightBtn': chains.readFightBtnDisableTriggerSection, 'windowClosed': _readSimpleWindowCloseTriggerSection, 'windowProcessed': _readSimpleWindowProcessTriggerSection, 'isInSandbox': chains.readIsInSandBoxPreQueueTriggerSection, 'queue': chains.readQueueTrigger, 'isInSandboxOrRandom': chains.readIsInSandBoxOrRandomPreQueueTriggerSection}) sub_parsers.setWindowsParsers({'awardWindow': sub_parsers.readQuestAwardWindowSection}) # okay decompyling c:\Users\PC\wotsources\files\originals\res\packages\scripts\scripts\client\tutorial\doc_loader\sub_parsers\quests.pyc # decompiled 1 files: 1 okay, 0 failed, 0 verify failed # 2017.02.03 21:54:21 Střední Evropa (běžný čas)
[ "info@webium.sk" ]
info@webium.sk
78651cd819bee71e2717fa7ef9e14dd50ca938b4
be1ebe1b2b7fa059e49922a4ba66cf74bb4bcbd2
/main/admin.py
ec32b6e207b024e42a4909134afc658c05fbb6a3
[]
no_license
Offdevelopers/realestate
8c6c5fb222cb2372c223a31183080d6f3c366652
f40d131f0c3c05de1ea38839732835dc6f2b16c5
refs/heads/master
2020-03-21T18:31:39.094430
2018-06-15T16:00:43
2018-06-15T16:00:43
null
0
0
null
null
null
null
UTF-8
Python
false
false
234
py
from django.contrib import admin from .models import Developer, Agent, Property, Mortage # Register your models here. admin.site.register(Property) admin.site.register(Developer) admin.site.register(Agent) admin.site.register(Mortage)
[ "abiodun.toluwanii@gmail.com" ]
abiodun.toluwanii@gmail.com
e08fcd2d1e413bc7a3a92ee6303bb7e8cfd5379e
581b960e3782e6968c23a664567cf1e857161048
/20190505_pycon_plugins/code_pyplugs/plotters/line.py
cb0f32bc87907ba66f3c6c9b086fd2c2e61e74ee
[]
no_license
gahjelle/talks
d6f04e0edf8ce15949120f715479c7e82de9d46c
d0423f46568b6495ee913f8a850c619c65c1214c
refs/heads/master
2023-04-30T16:21:18.801997
2023-04-23T18:39:29
2023-04-23T18:39:29
147,107,339
21
2
null
null
null
null
UTF-8
Python
false
false
149
py
"""Plot a line plot""" # Third party imports import pyplugs @pyplugs.register def line(ax, data): """Plot a line plot""" data.plot(ax=ax)
[ "geirarne@gmail.com" ]
geirarne@gmail.com
c391850ca49a84f97e5fd99f0c065229515432ee
ade5dcc2d30fc7cc52b887bb5c326dbf155f11ad
/tests/test_select.py
5ef4e5ecf77a2543c9f2c04b736e2b780abfb8ac
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
shawnbrown/squint
e08fc6cf12b705c4675ac9d25d3f5f9bb9767493
a9d326ff8edb2e2b740c4355fd953edd2c0cf114
refs/heads/master
2020-06-29T19:01:49.230704
2020-02-01T21:39:49
2020-02-01T21:39:49
200,598,178
3
0
null
null
null
null
UTF-8
Python
false
false
18,341
py
# -*- coding: utf-8 -*- from __future__ import absolute_import import os import shutil import sqlite3 import tempfile from squint._compatibility.builtins import * from squint._compatibility.collections import namedtuple from .common import ( StringIO, unittest, ) from squint.select import Select from squint.select import Query from squint.result import Result class HelperTestCase(unittest.TestCase): def setUp(self): data = [['label1', 'label2', 'value'], ['a', 'x', '17'], ['a', 'x', '13'], ['a', 'y', '20'], ['a', 'z', '15'], ['b', 'z', '5' ], ['b', 'y', '40'], ['b', 'x', '25']] self.select = Select(data) class TestSelect(HelperTestCase): def test_empty_select(self): select = Select() def test_fieldnames(self): expected = ['label1', 'label2', 'value'] self.assertEqual(self.select.fieldnames, expected) select = Select() # <- Empty select. self.assertEqual(select.fieldnames, [], msg='should be empty list') def test_load_data(self): select = Select() # <- Empty select. self.assertEqual(select.fieldnames, []) readerlike1 = [['col1', 'col2'], ['a', 1], ['b', 2]] select.load_data(readerlike1) self.assertEqual(select.fieldnames, ['col1', 'col2']) readerlike2 = [['col1', 'col3'], ['c', 'x'], ['d', 'y']] select.load_data(readerlike2) self.assertEqual(select.fieldnames, ['col1', 'col2', 'col3']) def test_repr(self): data = [['A', 'B'], ['x', 100], ['y', 200]] # Empty select. select = Select() self.assertEqual(repr(select), '<Select (no data loaded)>') # Data-only (no args) select = Select(data) expected = "<Select [['A', 'B'], ['x', 100], ['y', 200]]>" self.assertEqual(repr(select), expected) # Data with args (args don't affect repr) iterable = iter(data) select = Select(iterable, 'foo', bar='baz') regex = '<Select <[a-z_]+ object at [^\n>]+>>' self.assertRegex(repr(select), regex) # Extended after instantiation. select = Select() select.load_data([['A', 'B'], ['z', 300]]) select.load_data([['A', 'B'], ['y', 200]]) select.load_data([['A', 'B'], ['x', 100]]) expected = ( "<Select (3 sources):\n" " [['A', 'B'], ['x', 100]]\n" " [['A', 'B'], ['y', 200]]\n" " [['A', 'B'], ['z', 300]]>" ) self.assertEqual(repr(select), expected) # Test long repr truncation. select = Select([ ['xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'], ['yyyyyyyyyyyyyyyyyyyyyyyyyyyyyy'], ]) self.assertEqual(len(repr(select)), 72) expected = "<Select [['xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'], ['yyyyyyyyyyyyy...yyyyy']]>" self.assertEqual(repr(select), expected) def test_create_user_function(self): select = Select([['A', 'B'], ['x', 1], ['y', 2], ['z', 3]]) # Verify that "_user_function_dict" us empty. self.assertEqual(select._user_function_dict, dict(), 'should be empty dict') # Create first function using a specified id. isodd = lambda x: x % 2 == 1 select._create_user_function(isodd, 123) self.assertEqual(len(select._user_function_dict), 1) self.assertIn(123, select._user_function_dict) # Create second function using a specified id. iseven = lambda x: x % 2 == 0 select._create_user_function(iseven, 456) self.assertEqual(len(select._user_function_dict), 2) self.assertIn(456, select._user_function_dict) # Make sure they are getting new SQLite function names. self.assertNotEqual( select._user_function_dict[123], select._user_function_dict[456], ) # Create third function using a specified id. grteql2 = lambda x: x >= 2 select._create_user_function(grteql2) self.assertEqual(len(select._user_function_dict), 3) # Attempt to recreate the third function again. with self.assertRaises(ValueError, msg='can not register same function twice'): select._create_user_function(grteql2) self.assertEqual(len(select._user_function_dict), 3) def test_get_user_function(self): select = Select([['A', 'B'], ['x', 1], ['y', 2], ['z', 3]]) # Verify that "_user_function_dict" us empty. self.assertEqual(len(select._user_function_dict), 0, 'should be empty dict') # Get existing function. isodd = lambda x: x % 2 == 1 select._create_user_function(isodd) func_name = select._get_user_function(isodd) self.assertEqual(len(select._user_function_dict), 1) self.assertRegex(func_name, r'FUNC\d+') # Get new function. iseven = lambda x: x % 2 == 0 func_name = select._get_user_function(iseven) self.assertEqual(len(select._user_function_dict), 2, 'should be auto-created') self.assertRegex(func_name, r'FUNC\d+') def test_build_where_clause(self): select = Select([['A', 'B'], ['x', 1], ['y', 2], ['z', 3]]) result = select._build_where_clause({'A': 'x'}) expected = ('A=?', ['x']) self.assertEqual(result, expected) result = select._build_where_clause({'A': set(['x', 'y'])}) self.assertEqual(len(result), 2) self.assertEqual(result[0], 'A IN (?, ?)') self.assertEqual(set(result[1]), set(['x', 'y'])) # User-defined function. userfunc = lambda x: len(x) == 1 result = select._build_where_clause({'A': userfunc}) self.assertEqual(len(result), 2) self.assertRegex(result[0], r'FUNC\d+\(A\)') self.assertEqual(result[1], []) # Predicate (a type) prev_len = len(select._user_function_dict) predicate = int result = select._build_where_clause({'A': predicate}) self.assertEqual(len(result), 2) self.assertRegex(result[0], r'FUNC\d+\(A\)') self.assertEqual(result[1], []) self.assertEqual(len(select._user_function_dict), prev_len + 1) # Predicate (a boolean) prev_len = len(select._user_function_dict) predicate = True result = select._build_where_clause({'A': predicate}) self.assertEqual(len(result), 2) self.assertRegex(result[0], r'FUNC\d+\(A\)') self.assertEqual(result[1], []) self.assertEqual(len(select._user_function_dict), prev_len + 1) def test_execute_query(self): data = [['A', 'B'], ['x', 101], ['y', 202], ['z', 303]] source = Select(data) # Test where-clause function. def isodd(x): return x % 2 == 1 result = source('A', B=isodd).fetch() self.assertEqual(result, ['x', 'z']) # Test replacing function. def iseven(x): return x % 2 == 0 result = source('A', B=iseven).fetch() self.assertEqual(result, ['y']) # Test callable-but-unhashable. class IsEven(object): __hash__ = None def __call__(self, x): return x % 2 == 0 unhashable_iseven = IsEven() result = source('A', B=unhashable_iseven).fetch() self.assertEqual(result, ['y']) def test_select_list_of_strings(self): result = self.select._select(['label1']) expected = ['a', 'a', 'a', 'a', 'b', 'b', 'b'] self.assertEqual(result.fetch(), expected) def test_select_tuple_of_strings(self): result = self.select._select(('label1',)) expected = ('a', 'a', 'a', 'a', 'b', 'b', 'b') self.assertEqual(result.fetch(), expected) def test_select_set_of_strings(self): result = self.select._select(set(['label1'])) expected = set(['a', 'b']) self.assertEqual(result.fetch(), expected) def test_select_field_not_found(self): with self.assertRaises(LookupError): result = self.select._select(['bad_field_name']) def test_select_list_of_lists(self): result = self.select._select([['label1']]) expected = [['a'], ['a'], ['a'], ['a'], ['b'], ['b'], ['b']] self.assertEqual(result.fetch(), expected) result = self.select._select([['label1', 'label2']]) expected = [['a', 'x'], ['a', 'x'], ['a', 'y'], ['a', 'z'], ['b', 'z'], ['b', 'y'], ['b', 'x']] self.assertEqual(result.fetch(), expected) def test_select_list_of_tuples(self): result = self.select._select([('label1',)]) expected = [('a',), ('a',), ('a',), ('a',), ('b',), ('b',), ('b',)] self.assertEqual(result.fetch(), expected) def test_select_list_of_namedtuples(self): namedtup = namedtuple('namedtup', ['label1', 'label2']) result = self.select._select([namedtup('label1', 'label2')]) expected = [namedtup(label1='a', label2='x'), namedtup(label1='a', label2='x'), namedtup(label1='a', label2='y'), namedtup(label1='a', label2='z'), namedtup(label1='b', label2='z'), namedtup(label1='b', label2='y'), namedtup(label1='b', label2='x')] self.assertEqual(result.fetch(), expected) def test_select_set_of_frozensets(self): result = self.select._select(set([frozenset(['label1'])])) expected = set([frozenset(['a']), frozenset(['a']), frozenset(['a']), frozenset(['a']), frozenset(['b']), frozenset(['b']), frozenset(['b'])]) self.assertEqual(result.fetch(), expected) def test_select_dict(self): result = self.select._select({'label1': ['value']}) expected = { 'a': ['17', '13', '20', '15'], 'b': ['5', '40', '25'], } self.assertEqual(result.fetch(), expected) def test_select_dict2(self): result = self.select._select({('label1', 'label2'): ['value']}) expected = { ('a', 'x'): ['17', '13'], ('a', 'y'): ['20'], ('a', 'z'): ['15'], ('b', 'x'): ['25'], ('b', 'y'): ['40'], ('b', 'z'): ['5'], } self.assertEqual(result.fetch(), expected) def test_select_dict3(self): result = self.select._select({('label1', 'label2'): [['value']]}) expected = { ('a', 'x'): [['17'], ['13']], ('a', 'y'): [['20']], ('a', 'z'): [['15']], ('b', 'x'): [['25']], ('b', 'y'): [['40']], ('b', 'z'): [['5']], } self.assertEqual(result.fetch(), expected) def test_select_dict_with_namedtuple_keys(self): namedtup = namedtuple('namedtup', ['x', 'y']) result = self.select._select({namedtup('label1', 'label2'): ['value']}) expected = { namedtup(x='a', y='x'): ['17', '13'], namedtup(x='a', y='y'): ['20'], namedtup(x='a', y='z'): ['15'], namedtup(x='b', y='x'): ['25'], namedtup(x='b', y='y'): ['40'], namedtup(x='b', y='z'): ['5'], } self.assertEqual(result.fetch(), expected) def test_select_dict_with_values_container2(self): result = self.select._select({'label1': [('label2', 'label2')]}) expected = { 'a': [('x', 'x'), ('x', 'x'), ('y', 'y'), ('z', 'z')], 'b': [('z', 'z'), ('y', 'y'), ('x', 'x')] } self.assertEqual(result.fetch(), expected) result = self.select._select({'label1': [set(['label2', 'label2'])]}) expected = { 'a': [set(['x']), set(['x']), set(['y']), set(['z'])], 'b': [set(['z']), set(['y']), set(['x'])], } self.assertEqual(result.fetch(), expected) def test_select_alternate_mapping_type(self): class CustomDict(dict): pass result = self.select._select(CustomDict({'label1': ['value']})) result = result.fetch() expected = { 'a': ['17', '13', '20', '15'], 'b': ['5', '40', '25'], } self.assertIsInstance(result, CustomDict) self.assertEqual(result, expected) def test_select_distinct(self): result = self.select._select_distinct(['label1']) expected = ['a', 'b'] self.assertEqual(list(result), expected) result = self.select._select_distinct({'label1': ['label2']}) result = result.fetch() expected = {'a': ['x', 'y', 'z'], 'b': ['z', 'y', 'x']} self.assertIsInstance(result, dict) # Sort values for SQLite versions earlier than 3.7.12 if (3, 7, 12) > sqlite3.sqlite_version_info: sortvalues = lambda x: dict((k, sorted(v)) for k, v in x.items()) result = sortvalues(result) expected = sortvalues(expected) self.assertEqual(result, expected) def test_select_distinct_dict_grouping(self): """Dictionary grouping should work even when key elements are not adjacent in the original data source. To do this efficiently, results of the internal query should be sorted. """ source = Select([ ['A', 'B'], ['x', 1], ['y', 2], ['z', 3], ['x', 4], ['y', 5], ['z', 6], ]) result = source._select_distinct({'A': ['B']}) expected = { 'x': [1, 4], 'y': [2, 5], 'z': [3, 6], } self.assertEqual(result.fetch(), expected) def test_select_aggregate(self): # Not grouped, single result. result = self.select._select_aggregate('COUNT', ['label2']) self.assertEqual(result, 7) # Not grouped, single result as set. result = self.select._select_aggregate('COUNT', set(['label2'])) self.assertEqual(result, 3) # Not grouped, multiple results. result = self.select._select_aggregate('SUM', [['value', 'value']]) self.assertEqual(result, [135, 135]) # Simple group by (grouped by keys). result = self.select._select_aggregate('SUM', {'label1': ['value']}) self.assertIsInstance(result, Result) expected = { 'a': 65, 'b': 70, } self.assertEqual(result.fetch(), expected) # Composite value. result = self.select._select_aggregate('SUM', {'label1': [('value', 'value')]}) expected = { 'a': (65, 65), 'b': (70, 70), } self.assertEqual(dict(result), expected) # Composite key and composite value. result = self.select._select_aggregate('SUM', {('label1', 'label1'): [['value', 'value']]}) expected = { ('a', 'a'): [65, 65], ('b', 'b'): [70, 70], } self.assertEqual(dict(result), expected) def test_select_dict_grouping(self): """Dictionary grouping should work even when key elements are not adjacent in the original data source. To do this efficiently, results of the internal query should be sorted. """ source = Select([ ['A', 'B'], ['x', 1], ['y', 2], ['z', 3], ['x', 4], ['y', 5], ['z', 6], ]) result = source._select({'A': ['B']}) expected = { 'x': [1, 4], 'y': [2, 5], 'z': [3, 6], } self.assertEqual(result.fetch(), expected) class TestCall(HelperTestCase): def test_list_of_elements(self): query = self.select(['label1']) expected = ['a', 'a', 'a', 'a', 'b', 'b', 'b'] self.assertIsInstance(query, Query) self.assertEqual(query.fetch(), expected) def test_list_of_tuples(self): query = self.select([('label1', 'label2')]) expected = [('a', 'x'), ('a', 'x'), ('a', 'y'), ('a', 'z'), ('b', 'z'), ('b', 'y'), ('b', 'x')] self.assertIsInstance(query, Query) self.assertEqual(query.fetch(), expected) def test_list_of_sets(self): query = self.select([set(['label1', 'label2'])]) expected = [set(['a', 'x']), set(['a', 'x']), set(['a', 'y']), set(['a', 'z']), set(['b', 'z']), set(['b', 'y']), set(['b', 'x'])] self.assertIsInstance(query, Query) self.assertEqual(query.fetch(), expected) def test_dict_of_lists(self): query = self.select({'label1': ['label2']}) expected = {'a': ['x', 'x', 'y', 'z'], 'b': ['z', 'y', 'x']} self.assertIsInstance(query, Query) self.assertEqual(query.fetch(), expected) def test_empty_call(self): """When *columns* is omitted, should default to fieldnames.""" query = self.select() # <- No columns given. expected = self.select(self.select.fieldnames) self.assertEqual(query.fetch(), expected.fetch()) class TestQueryToCsv(unittest.TestCase): def setUp(self): self.select = Select([['A', 'B'], ['x', 1], ['y', 2]]) def test_fmtparams(self): query = self.select(['A', 'B']) csvfile = StringIO() query.to_csv(csvfile, delimiter='|', lineterminator='\n') csvfile.seek(0) self.assertEqual(csvfile.readlines(), ['A|B\n', 'x|1\n', 'y|2\n']) def test_actual_file(self): query = self.select(['A', 'B']) try: tmpdir = tempfile.mkdtemp() path = os.path.join(tmpdir, 'tempfile.csv') query.to_csv(path, lineterminator='\n') with open(path) as fh: self.assertEqual(fh.read(), 'A,B\nx,1\ny,2\n') finally: shutil.rmtree(tmpdir) class TestIterable(unittest.TestCase): def test_iterate(self): select = Select([('A', 'B'), (1, 2), (1, 2)]) self.assertEqual(list(select), [[1, 2], [1, 2]])
[ "shawnbrown@users.noreply.github.com" ]
shawnbrown@users.noreply.github.com
bdc7c56228322a08b6c0e6e1e2705a7bb79dad5d
db863bdd3507bf53800368d88a887247ef4a7636
/Transaction/migrations/0009_auto_20210408_1019.py
55bea4125b4834ec2947a82808078a205c74bdd9
[]
no_license
vikasjoshis001/yes_backend
ed116f774237517da23dc5b420d791cba33a3efa
97e071a4037f7020cc4bce667eee10e7294903f7
refs/heads/master
2023-08-01T03:27:40.521169
2021-09-15T09:16:29
2021-09-15T09:16:29
353,229,366
0
1
null
null
null
null
UTF-8
Python
false
false
603
py
# Generated by Django 3.0.7 on 2021-04-08 10:19 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('Transaction', '0008_auto_20210408_1015'), ] operations = [ migrations.AlterField( model_name='transactionhistorymodel', name='transactionDate', field=models.DateField(auto_now_add=True), ), migrations.AlterField( model_name='transactionhistorymodel', name='transactionTime', field=models.TimeField(auto_now_add=True), ), ]
[ "vikasjoshis001@gmail.com" ]
vikasjoshis001@gmail.com
42b84294b85ec7fda3c05db22cbb46d5d6bec28e
462682b3b29304b561eaea3833c29e84d1e95c0e
/PythonTypes/ConsoleCode.py
46da9d7f5a7259f3b5872f29883a929d85b87cc7
[]
no_license
ravi4all/PythonDecMorning
4452b8340ce0b4ab067bd769725c5a6f831b7f45
1e20da3c90d407dbef714770ad54e72f16be0eec
refs/heads/master
2021-09-02T11:01:28.686860
2018-01-02T05:05:06
2018-01-02T05:05:06
113,133,365
0
0
null
null
null
null
UTF-8
Python
false
false
4,304
py
Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:57:36) [MSC v.1900 64 bit (AMD64)] on win32 Type "copyright", "credits" or "license()" for more information. >>> a = [] >>> a.append(1) >>> a [1] >>> a.append(2) >>> a [1, 2] >>> a.append("Hello") >>> a [1, 2, 'Hello'] >>> a = [1,2,3,10.5,"Hello",True] >>> a[0] 1 >>> a[1] 2 >>> a[-1] True >>> a[-2] 'Hello' >>> a[1:5] [2, 3, 10.5, 'Hello'] >>> a[3][1:2] Traceback (most recent call last): File "<pyshell#13>", line 1, in <module> a[3][1:2] TypeError: 'float' object is not subscriptable >>> a[4][1:2] 'e' >>> a.append(12) >>> a [1, 2, 3, 10.5, 'Hello', True, 12] >>> a.append(13,14) Traceback (most recent call last): File "<pyshell#17>", line 1, in <module> a.append(13,14) TypeError: append() takes exactly one argument (2 given) >>> a.append([13,14]) >>> a [1, 2, 3, 10.5, 'Hello', True, 12, [13, 14]] >>> a.extend([15,16,17]) >>> a [1, 2, 3, 10.5, 'Hello', True, 12, [13, 14], 15, 16, 17] >>> user = [] >>> user.extend(["Name"]) >>> user ['Name'] >>> user = {"Name" : ["Ram", "Shyam"]} >>> user {'Name': ['Ram', 'Shyam']} >>> a [1, 2, 3, 10.5, 'Hello', True, 12, [13, 14], 15, 16, 17] >>> a.insert(0, "Bye") >>> a ['Bye', 1, 2, 3, 10.5, 'Hello', True, 12, [13, 14], 15, 16, 17] >>> a[0] = "Hi" >>> a ['Hi', 1, 2, 3, 10.5, 'Hello', True, 12, [13, 14], 15, 16, 17] >>> a.pop() 17 >>> a ['Hi', 1, 2, 3, 10.5, 'Hello', True, 12, [13, 14], 15, 16] >>> a.pop() 16 >>> a ['Hi', 1, 2, 3, 10.5, 'Hello', True, 12, [13, 14], 15] >>> a.pop(4) 10.5 >>> a ['Hi', 1, 2, 3, 'Hello', True, 12, [13, 14], 15] >>> a.remove(11) Traceback (most recent call last): File "<pyshell#38>", line 1, in <module> a.remove(11) ValueError: list.remove(x): x not in list >>> a.remove(12) >>> a ['Hi', 1, 2, 3, 'Hello', True, [13, 14], 15] >>> len(a) 8 >>> a =[12,11,45,3,56,4,7,0,2,23] >>> sorted(a) [0, 2, 3, 4, 7, 11, 12, 23, 45, 56] >>> sorted(a, reverse = True) [56, 45, 23, 12, 11, 7, 4, 3, 2, 0] >>> a [12, 11, 45, 3, 56, 4, 7, 0, 2, 23] >>> a.sort() >>> a [0, 2, 3, 4, 7, 11, 12, 23, 45, 56] >>> 11 in a True >>> 'Hello' not in a True >>> 2 and 3 in a True >>> 2 or 3 in a 2 >>> b =(12,11,45,3,56,4,7,0,2,23) >>> a [0, 2, 3, 4, 7, 11, 12, 23, 45, 56] >>> b (12, 11, 45, 3, 56, 4, 7, 0, 2, 23) >>> a[0] = 'Hi' >>> a ['Hi', 2, 3, 4, 7, 11, 12, 23, 45, 56] >>> b[0] = 'Hi' Traceback (most recent call last): File "<pyshell#57>", line 1, in <module> b[0] = 'Hi' TypeError: 'tuple' object does not support item assignment >>> b (12, 11, 45, 3, 56, 4, 7, 0, 2, 23) >>> b[0] 12 >>> b[0:5] (12, 11, 45, 3, 56) >>> user = {"Name" : "Ram", "Age" : 20, "Num" : 89898979} >>> user {'Name': 'Ram', 'Age': 20, 'Num': 89898979} >>> user[0] Traceback (most recent call last): File "<pyshell#63>", line 1, in <module> user[0] KeyError: 0 >>> user['Name'] 'Ram' >>> for data in user: print(data) Name Age Num >>> user.keys() dict_keys(['Name', 'Age', 'Num']) >>> user.values() dict_values(['Ram', 20, 89898979]) >>> for data in user.values: print(data) Traceback (most recent call last): File "<pyshell#71>", line 1, in <module> for data in user.values: TypeError: 'builtin_function_or_method' object is not iterable >>> for data in user.values(): print(data) Ram 20 89898979 >>> user.items() dict_items([('Name', 'Ram'), ('Age', 20), ('Num', 89898979)]) >>> for data in user.items(): print(data) ('Name', 'Ram') ('Age', 20) ('Num', 89898979) >>> user {'Name': 'Ram', 'Age': 20, 'Num': 89898979} >>> user['Name'] = ['Ram'] >>> user {'Name': ['Ram'], 'Age': 20, 'Num': 89898979} >>> user['Name'] ['Ram'] >>> name = user['Name'] >>> name ['Ram'] >>> name.append('Shyam') >>> user {'Name': ['Ram', 'Shyam'], 'Age': 20, 'Num': 89898979} >>> set_1 = {1,2,3,4,5,6} >>> type(set_1) <class 'set'> >>> set_2 = {4,5,6,7,8,9} >>> set_1.intersection(set_2) {4, 5, 6} >>> a ['Hi', 2, 3, 4, 7, 11, 12, 23, 45, 56] >>> set(a) {'Hi', 2, 3, 4, 7, 11, 12, 45, 23, 56} >>> a ['Hi', 2, 3, 4, 7, 11, 12, 23, 45, 56] >>> set(b) {0, 2, 3, 4, 7, 11, 12, 45, 23, 56} >>> set_a = set(a) >>> set_b = set(b) >>> set_a.intersection(set_b) {2, 3, 4, 7, 11, 12, 45, 23, 56} >>>
[ "noreply@github.com" ]
ravi4all.noreply@github.com
ec95f318cee2e9f5dd28e4996ed3789e99994eb5
bc41457e2550489ebb3795f58b243da74a1c27ae
/python/ghtc2012.py
1eacd49e770cdbff348b5fe621063937f34b7f50
[]
no_license
SEL-Columbia/ss_sql_views
28a901d95fe779b278d2a51aec84d6bf51245c02
d146fd96849a4d165f3dc3f197aadda804a2f60a
refs/heads/master
2021-01-01T19:35:18.999147
2012-05-10T18:43:36
2012-05-10T18:43:36
3,020,367
0
0
null
null
null
null
UTF-8
Python
false
false
2,797
py
import offline_gateway as og import datetime as dt import matplotlib.pyplot as plt import pandas as p ''' 25 "ml00" 164 "ml01" 143 "ml02" 213 "ml03" 192 "ml04" 57 "ml05" 70 "ml06" 102 "ml07" 123 "ml08" ''' # todo: fit solar generation over same time period ''' print print 'ml03' og.analyze_load_profile_curve(213, date_start, date_end) og.plot_load_profile_curve_to_file(213, date_start, date_end, 'ml03-ldc.pdf') print print 'ml05' og.analyze_load_profile_curve(57, date_start, date_end) og.plot_load_profile_curve_to_file(57, date_start, date_end, 'ml05-ldc.pdf') print print 'ml06' og.analyze_load_profile_curve(70, date_start, date_end) og.plot_load_profile_curve_to_file(70, date_start, date_end, 'ml06-ldc.pdf') print print 'ml07' og.analyze_load_profile_curve(102, date_start, date_end) og.plot_load_profile_curve_to_file(102, date_start, date_end, 'ml07-ldc.pdf') print print 'ml08' og.analyze_load_profile_curve(123, date_start, date_end) og.plot_load_profile_curve_to_file(123, date_start, date_end, 'ml08-ldc.pdf') ''' def plot_two_ldc(date_start, date_end): f, ax = plt.subplots(1, 1) og.plot_load_profile_curve_to_axis(57, date_start, date_end, ax, label='Lighting') og.plot_load_profile_curve_to_axis(123, date_start, date_end, ax, label='Lighting and Freezer') ax.legend() ax.set_xlabel('Fraction of Availability') ax.grid(True, linestyle='-', color='#cccccc') plt.savefig('two_ldc.pdf') def plot_two_bulb_profile(date_start, date_end): og.plot_hourly_power_profile(230, date_start, date_end, 'two_bulb_profile.pdf', title=False) def plot_freezer_profile(date_start, date_end): og.plot_hourly_power_profile(96, date_start, date_end, 'freezer_profile.pdf', title=False) def tbl_efficiency(date_start, date_end): print '% tbl_efficiency' print '%', date_start print '%', date_end dl = [] for meter, cid in [('ml05', 57), ('ml06', 70), ('ml07', 102), ('ml08', 123)]: d = og.analyze_load_profile_curve(cid, date_start, date_end) og.plot_load_profile_curve_to_file(cid, date_start, date_end, meter+'-ldc.pdf') dl.append(d) df = p.DataFrame(dl) for row in df.index: print '%.2f' % df.ix[row]['capacity_factor'], print '&', print df.ix[row]['circuit_id'], print '\\\\' if __name__ == '__main__': date_start = dt.datetime(2012, 2, 15) date_end = dt.datetime(2012, 4, 15) #plot_two_ldc(date_start, date_end) date_start = dt.datetime(2012, 1, 1) date_end = dt.datetime(2012, 3, 1) #plot_two_bulb_profile(date_start, date_end) #plot_freezer_profile(dt.datetime(2012, 2, 1), dt.datetime(2012, 4, 15)) date_start = dt.datetime(2012, 2, 15) date_end = dt.datetime(2012, 4, 15) tbl_efficiency(date_start, date_end)
[ "danielrsoto@gmail.com" ]
danielrsoto@gmail.com
cbbc41a4f95e61fcc71ca12aa4a08db0df652e6f
1e4b37d3bfa9ecba22517548c0577dee76704d8f
/temp_ws/src/sawyer_velctrlsim-master/src/ref_rand_joint_state_pub.py
4cb127b09acdbc0ce1e8873cbdce164979627504
[]
no_license
mch5048/catkin_ws_4rl
0aa19dc46effd2ae7941cc1e0b6d824f595d8574
2201d3b353da3b380dc7330ae5651e9640cd3408
refs/heads/master
2020-04-19T01:42:56.013573
2019-02-21T01:09:13
2019-02-21T01:09:13
167,879,885
0
0
null
2019-02-21T01:09:14
2019-01-28T01:27:31
Makefile
UTF-8
Python
false
false
1,350
py
#!/usr/bin/env python import rospy import numpy as np from sensor_msgs.msg import JointState class RandomJointState: def __init__(self): rospy.init_node('ref_js_randomizer') self.pub = rospy.Publisher('/ref_sawyer/joint_states',JointState, queue_size=10) self.ref_js = JointState() self.ref_js.name = ['right_j0', 'head_pan', 'right_j1', 'right_j2', \ 'right_j3', 'right_j4', 'right_j5', 'right_j6'] j_ranges = [[-3.05, 3.05],\ [0,0],\ [-3.81,2.27],\ [-3.04,3.04],\ [-3.04,3.04],\ [-2.98,2.98],\ [-2.98,2.98],\ [-4.71,4.71]] joints = np.ndarray.tolist(np.random.rand(8)) for i in range(len(joints)): joints[i] = joints[i]*np.ptp(j_ranges[i])+j_ranges[i][0] self.ref_js.position = joints def pub_random_js(self): self.ref_js.header.stamp = rospy.Time.now() #add timestamp to joint state msg self.pub.publish(self.ref_js) if __name__=='__main__': try: out = RandomJointState() rate = rospy.Rate(10) #10Hz while not rospy.is_shutdown(): out.pub_random_js() rate.sleep() except rospy.ROSInterruptException: raise e
[ "mch5048@korea.ac.kr" ]
mch5048@korea.ac.kr
f8e97138e7562167aa73dade88277515117fc3a5
21e1d00c48c1732cc44af077572299831b93ffc2
/ANISUL'S_VIDEOS/While-Loop.py
7fd62963e6e7c26514ee7be3a6e6ddbfdbcbae7d
[]
no_license
GolamRabbani20/PYTHON-A2Z
7be72041407e4417359b3a610ced0919f3939993
7c89223f253aa559fa15caacb89c68e0b78ff915
refs/heads/master
2023-05-09T00:43:03.012963
2021-05-26T07:56:56
2021-05-26T07:56:56
317,953,879
0
0
null
null
null
null
UTF-8
Python
false
false
112
py
n=int(input("Enter the value of N: ")) i=1 sum=0 while i<=n: #if i%2==1: sum=sum+i i=i+1 print(sum)
[ "mdgolamrabbani96@gmail.com" ]
mdgolamrabbani96@gmail.com
e34ae855ef6e2c976a31db40c2df67bea7aab7ba
af0877371939aba73e8cd68d1130f5f89f27d48e
/tests/test_engine.py
8920055d4356a2000012ec4f106403298ca5f650
[ "Apache-2.0" ]
permissive
Mil4dy/plumbery
9db82dce591b7fefa72415b36035506e42f0a3ce
5ede749a84f36f2302d3b182776b4f1cc8c1aca9
refs/heads/master
2020-12-25T20:20:30.531737
2016-03-10T22:41:31
2016-03-10T22:41:31
null
0
0
null
null
null
null
UTF-8
Python
false
false
12,121
py
#!/usr/bin/env python """ Tests for `plumbery` module. """ import logging import os import socket import unittest from Crypto.PublicKey import RSA import ast from mock_api import DimensionDataMockHttp from libcloud.compute.drivers.dimensiondata import DimensionDataNodeDriver from libcloud.common.types import InvalidCredsError from plumbery.__main__ import parse_args, main from plumbery.engine import PlumberyEngine from plumbery import __version__ DIMENSIONDATA_PARAMS = ('user', 'password') myPlan = """ --- safeMode: False information: - hello - world links: documentation: "http://www.acme.com/" defaults: domain: ipv4: auto cloud-config: disable_root: false ssh_pwauth: true ssh_keys: rsa_private: | {{ pair1.rsa_private }} rsa_public: "{{ pair1.ssh.rsa_public }}" parameters: locationId: information: - "the target data centre for this deployment" type: locations.list default: EU6 domainName: information: - "the name of the network domain to be deployed" type: str default: myDC networkName: information: - "the name of the Ethernet VLAN to be deployed" type: str default: myVLAN --- # Frankfurt in Europe locationId: "{{ locationId.parameter }}" regionId: dd-eu blueprints: - myBlueprint: domain: name: "{{ domainName.parameter }}" ethernet: name: "{{ networkName.parameter }}" subnet: 10.1.10.0 nodes: - myServer: """ myFacility = { 'regionId': 'dd-na', 'locationId': 'NA9', 'blueprints': [{ 'fake': { 'domain': { 'name': 'VDC1', 'service': 'ADVANCED', 'description': 'fake'}, 'ethernet': { 'name': 'vlan1', 'subnet': '10.0.10.0', 'description': 'fake'}, 'nodes': [{ 'stackstorm': { 'description': 'fake', 'appliance': 'RedHat 6 64-bit 4 CPU' } }] } }] } class FakeLocation: id = 'EU7' name = 'data centre in Amsterdam' country = 'Netherlands' class TestPlumberyEngine(unittest.TestCase): def test_init(self): engine = PlumberyEngine() engine.from_text(myPlan) self.assertEqual(engine.safeMode, False) self.assertEqual(len(engine.information), 2) self.assertEqual(len(engine.links), 1) domain = engine.get_default('domain') self.assertEqual(domain['ipv4'], 'auto') cloudConfig = engine.get_default('cloud-config', {}) self.assertEqual(len(cloudConfig.keys()), 3) parameter = engine.get_parameter('locationId') self.assertEqual(parameter, 'EU6') parameter = engine.get_parameter('domainName') self.assertEqual(parameter, 'myDC') parameter = engine.get_parameter('networkName') self.assertEqual(parameter, 'myVLAN') self.assertEqual(len(engine.facilities), 1) facility = engine.facilities[0] self.assertEqual(facility.settings['locationId'], 'EU6') self.assertEqual(facility.settings['regionId'], 'dd-eu') blueprint = facility.blueprints[0]['myBlueprint'] self.assertEqual(blueprint['domain']['name'], 'myDC') self.assertEqual(blueprint['ethernet']['name'], 'myVLAN') def test_set(self): settings = { 'safeMode': False, 'polishers': [ {'ansible': {}}, {'spit': {}}, ] } engine = PlumberyEngine() DimensionDataNodeDriver.connectionCls.conn_classes = ( None, DimensionDataMockHttp) DimensionDataMockHttp.type = None self.region = DimensionDataNodeDriver(*DIMENSIONDATA_PARAMS) engine.set_shared_secret('fake_secret') self.assertEqual(engine.get_shared_secret(), 'fake_secret') random = engine.get_secret('random') self.assertEqual(len(random), 9) self.assertEqual(engine.get_secret('random'), random) engine.set_user_name('fake_name') self.assertEqual(engine.get_user_name(), 'fake_name') engine.set_user_password('fake_password') self.assertEqual(engine.get_user_password(), 'fake_password') engine.set(settings) self.assertEqual(engine.safeMode, False) engine.add_facility(myFacility) self.assertEqual(len(engine.facilities), 1) def test_lifecycle(self): engine = PlumberyEngine() DimensionDataNodeDriver.connectionCls.conn_classes = ( None, DimensionDataMockHttp) DimensionDataMockHttp.type = None self.region = DimensionDataNodeDriver(*DIMENSIONDATA_PARAMS) engine.set_shared_secret('fake_secret') engine.set_user_name('fake_name') engine.set_user_password('fake_password') engine.do('build') engine.build_all_blueprints() engine.build_blueprint('myBlueprint') engine.do('start') engine.start_all_blueprints() engine.start_blueprint('myBlueprint') engine.do('polish') engine.polish_all_blueprints() engine.polish_blueprint('myBlueprint') engine.do('stop') engine.stop_all_blueprints() engine.stop_blueprint('myBlueprint') engine.wipe_all_blueprints() engine.wipe_blueprint('myBlueprint') engine.do('destroy') engine.destroy_all_blueprints() engine.destroy_blueprint('myBlueprint') banner = engine.document_elapsed() self.assertEqual('Worked for you' in banner, True) def test_as_library(self): engine = PlumberyEngine(myFacility) DimensionDataNodeDriver.connectionCls.conn_classes = ( None, DimensionDataMockHttp) DimensionDataMockHttp.type = None self.region = DimensionDataNodeDriver(*DIMENSIONDATA_PARAMS) engine.set_shared_secret('fake_secret') engine.set_user_name('fake_name') engine.set_user_password('fake_password') facilities = engine.list_facility('NA9') self.assertEqual(len(facilities), 1) facility = facilities[0] self.assertEqual(facility.get_setting('regionId'), 'dd-na') self.assertEqual(facility.get_setting('locationId'), 'NA9') blueprint = facility.get_blueprint('fake') self.assertEqual(blueprint.keys(), ['ethernet', 'domain', 'nodes', 'target']) engine.do('deploy') engine.do('refresh') engine.do('dispose') def test_lookup(self): engine = PlumberyEngine() self.assertEqual(engine.lookup('plumbery.version'), __version__) engine.secrets = {} random = engine.lookup('random.secret') self.assertEqual(len(random), 9) self.assertEqual(engine.lookup('random.secret'), random) md5 = engine.lookup('random.md5.secret') self.assertEqual(len(md5), 32) self.assertNotEqual(md5, random) sha = engine.lookup('random.sha1.secret') self.assertEqual(len(sha), 40) self.assertNotEqual(sha, random) sha = engine.lookup('random.sha256.secret') self.assertEqual(len(sha), 64) self.assertNotEqual(sha, random) id1 = engine.lookup('id1.uuid') self.assertEqual(len(id1), 36) self.assertEqual(engine.lookup('id1.uuid'), id1) id2 = engine.lookup('id2.uuid') self.assertEqual(len(id2), 36) self.assertNotEqual(id1, id2) engine.lookup('application.secret') engine.lookup('database.secret') engine.lookup('master.secret') engine.lookup('slave.secret') original = 'hello world' text = engine.lookup('pair1.rsa_public') self.assertEqual(text.startswith('ssh-rsa '), True) key = RSA.importKey(text) encrypted = key.publickey().encrypt(original, 32) privateKey = engine.lookup('pair1.rsa_private') self.assertEqual(privateKey.startswith( '-----BEGIN RSA PRIVATE KEY-----'), True) key = RSA.importKey(engine.lookup('pair1.rsa_private')) decrypted = key.decrypt(ast.literal_eval(str(encrypted))) self.assertEqual(decrypted, original) self.assertEqual(len(engine.secrets), 12) with self.assertRaises(LookupError): localKey = engine.lookup('local.rsa_private') localKey = engine.lookup('local.rsa_public') try: path = '~/.ssh/id_rsa.pub' with open(os.path.expanduser(path)) as stream: text = stream.read() stream.close() self.assertEqual(localKey.strip(), text.strip()) logging.info("Successful lookup of local public key") except IOError: pass def test_secrets(self): engine = PlumberyEngine() engine.secrets = {'hello': 'world'} engine.save_secrets(plan='test_engine.yaml') self.assertEqual(os.path.isfile('.test_engine.secrets'), True) engine.secrets = {} engine.load_secrets(plan='test_engine.yaml') self.assertEqual(engine.secrets['hello'], 'world') engine.forget_secrets(plan='test_engine.yaml') self.assertEqual(os.path.isfile('.test_engine.secrets'), False) def test_parser(self): args = parse_args(['fittings.yaml', 'build', 'web']) self.assertEqual(args.fittings, 'fittings.yaml') self.assertEqual(args.action, 'build') self.assertEqual(args.blueprints, ['web']) self.assertEqual(args.facilities, None) args = parse_args(['fittings.yaml', 'build', 'web', '-s']) self.assertEqual(args.safe, True) args = parse_args(['fittings.yaml', 'build', 'web', '-d']) self.assertEqual(args.debug, True) self.assertEqual( logging.getLogger().getEffectiveLevel(), logging.DEBUG) args = parse_args(['fittings.yaml', 'build', 'web', '-q']) self.assertEqual(args.quiet, True) self.assertEqual( logging.getLogger().getEffectiveLevel(), logging.WARNING) args = parse_args(['fittings.yaml', 'start', '@NA12']) self.assertEqual(args.fittings, 'fittings.yaml') self.assertEqual(args.action, 'start') self.assertEqual(args.blueprints, None) self.assertEqual(args.facilities, ['NA12']) args = parse_args([ 'fittings.yaml', 'rub', 'web', 'sql', '@NA9', '@NA12']) self.assertEqual(args.fittings, 'fittings.yaml') self.assertEqual(args.action, 'rub') self.assertEqual(args.blueprints, ['web', 'sql']) self.assertEqual(args.facilities, ['NA9', 'NA12']) args = parse_args([ 'fittings.yaml', 'rub', 'web', '@NA9', 'sql', '@NA12']) self.assertEqual(args.fittings, 'fittings.yaml') self.assertEqual(args.action, 'rub') self.assertEqual(args.blueprints, ['web', 'sql']) self.assertEqual(args.facilities, ['NA9', 'NA12']) args = parse_args(['fittings.yaml', 'polish']) self.assertEqual(args.fittings, 'fittings.yaml') self.assertEqual(args.action, 'polish') self.assertEqual(args.blueprints, None) self.assertEqual(args.facilities, None) def test_main(self): engine = PlumberyEngine() engine.from_text(myPlan) engine.set_user_name('fake_name') engine.set_user_password('fake_password') with self.assertRaises(SystemExit): main(['bad args'], engine) with self.assertRaises(SystemExit): main(['fittings.yaml'], engine) with self.assertRaises(SystemExit): main(['fittings.yaml', 'xyz123', 'web'], engine) with self.assertRaises(SystemExit): main(['-v'], engine) with self.assertRaises(SystemExit): main(['fittings.yaml', 'build', 'web', '-v'], engine) if __name__ == '__main__': import sys sys.exit(unittest.main())
[ "bernard.paques@gmail.com" ]
bernard.paques@gmail.com
9c9fb00c316199447af33e79a78359efcc6b08d9
1d2bbeda56f8fede69cd9ebde6f5f2b8a50d4a41
/medium/python/c0075_142_linked-list-cycle-ii/00_leetcode_0075.py
439484c8b6b418348aa22f97d0b9fbe24737d76b
[]
no_license
drunkwater/leetcode
38b8e477eade68250d0bc8b2317542aa62431e03
8cc4a07763e71efbaedb523015f0c1eff2927f60
refs/heads/master
2020-04-06T07:09:43.798498
2018-06-20T02:06:40
2018-06-20T02:06:40
127,843,545
0
2
null
null
null
null
UTF-8
Python
false
false
691
py
# DRUNKWATER TEMPLATE(add description and prototypes) # Question Title and Description on leetcode.com # Function Declaration and Function Prototypes on leetcode.com #142. Linked List Cycle II #Given a linked list, return the node where the cycle begins. If there is no cycle, return null. #Note: Do not modify the linked list. #Follow up: #Can you solve it without using extra space? ## Definition for singly-linked list. ## class ListNode(object): ## def __init__(self, x): ## self.val = x ## self.next = None #class Solution(object): # def detectCycle(self, head): # """ # :type head: ListNode # :rtype: ListNode # """ # Time Is Money
[ "Church.Zhong@audiocodes.com" ]
Church.Zhong@audiocodes.com
99a3b499be8c43322aee33f233fae8f504813476
547018e2fb9b178aacfe2ceabcab4313647ffb79
/mapry/go/validation.py
a3d2be3dea02b0fd3eea4b07a29d0ba93e64152c
[ "MIT" ]
permissive
Parquery/mapry
2eb22862494342f71ca4254e7b2b53df84bd666f
93515307f9eba8447fe64b0ac7cc68b2d07205a7
refs/heads/master
2021-06-11T09:57:17.764387
2021-06-02T14:19:52
2021-06-02T14:19:52
165,482,780
11
3
MIT
2021-06-02T14:19:53
2019-01-13T08:31:08
C++
UTF-8
Python
false
false
14,225
py
"""Validate that the Go code can be generated according to the schema.""" from typing import ( # pylint: disable=unused-import Dict, List, Mapping, MutableMapping) import mapry import mapry.naming import mapry.strftime import mapry.validation _KEYWORDS = { 'break', 'default', 'func', 'interface', 'select', 'case', 'defer', 'go', 'map', 'struct', 'chan', 'else', 'goto', 'package', 'switch', 'const', 'fallthrough', 'if', 'range', 'type', 'continue', 'for', 'import', 'return', 'var' } class _Field: """Represent a Go field of a composite.""" def __init__(self, name: str, ref: str) -> None: """ Initialize the Go field of a composite with the given values. :param name: name of the composite field :param ref: reference path in the mapry schema corresponding to this field """ self.name = name self.ref = ref def _properties_to_fields(properties: Mapping[str, mapry.Property] ) -> List[_Field]: """ Convert properties of a mapry composite into a list of Go composite fields. :param properties: of a composite :return: list of fields. """ # yapf: disable return [ _Field(name=mapry.naming.ucamel_case(identifier=prop.name), ref=prop.ref) for prop in properties.values() ] # yapf: enable def _validate_fields(fields: List[_Field] ) -> List[mapry.validation.SchemaError]: """ Validate the fields of a Go struct. Notably, check that there are no duplicates and no reserved keywords. :param fields: Go fields corresponding to the composite :return: list of errors, or an empty list if no errors """ errs = [] # type: List[mapry.validation.SchemaError] name_to_fields = dict() # type: Dict[str, _Field] for field in fields: if field.name in _KEYWORDS: errs.append( mapry.validation.SchemaError( message=( "The Go field identifier {!r} " "is a keyword in Go").format(field.name), ref=field.ref)) if field.name in name_to_fields: errs.append( mapry.validation.SchemaError( message=( "The Go field identifier {!r} " "conflicts another field ({})").format( field.name, name_to_fields[field.name].ref), ref=field.ref)) else: name_to_fields[field.name] = field return errs def _validate_class_fields(a_class: mapry.Class ) -> List[mapry.validation.SchemaError]: """ Validate that the properties of the class can be translated to Go fields. :param a_class: definition of a mapry class :return: list of errors, or an empty list if no errors """ errs = [] # type: List[mapry.validation.SchemaError] fields = _properties_to_fields(properties=a_class.properties) errs.extend(_validate_fields(fields=fields)) for field in fields: if field.name == 'ID': errs.append( mapry.validation.SchemaError( message=( "The Go field identifier 'ID' is reserved " "for class identifiers and used by the " "autogenerated code"), ref=field.ref)) return errs def _validate_embed_fields(embed: mapry.Embed ) -> List[mapry.validation.SchemaError]: """ Validate that the embeddable structure can be translated to Go fields. :param embed: definition of an embeddable structure :return: list of errors, or an empty list if no errors """ errs = [] # type: List[mapry.validation.SchemaError] fields = _properties_to_fields(properties=embed.properties) errs.extend(_validate_fields(fields=fields)) return errs def _validate_graph_fields(graph: mapry.Graph ) -> List[mapry.validation.SchemaError]: """ Validate that the object graph can be translated into a Go structure. :param graph: mapry definition of the object graph :return: list of errors, or an empty list if no errors """ errs = [] # type: List[mapry.validation.SchemaError] fields = _properties_to_fields(properties=graph.properties) errs.extend(_validate_fields(fields=fields)) property_field_map = {field.name: field for field in fields} registry_field_map = dict() # type: MutableMapping[str, mapry.Class] for cls in graph.classes.values(): plural_field = mapry.naming.ucamel_case(identifier=cls.plural) if plural_field in _KEYWORDS: errs.append( mapry.validation.SchemaError( message=( "The Go field identifier {!r} corresponding " "to the registry of the class {!r} in the object " "graph is a reserved keyword in Go").format( plural_field, cls.name), ref=cls.ref)) if plural_field in property_field_map: errs.append( mapry.validation.SchemaError( message=( "The Go field identifier {!r} corresponding " "to the registry of the class {!r} in the object " "graph conflicts with another Go field corresponding " "to a property of the object graph ({})").format( plural_field, cls.name, property_field_map[plural_field].ref), ref=cls.ref)) if plural_field in registry_field_map: errs.append( mapry.validation.SchemaError( message=( "The Go field identifier {!r} corresponding " "to the registry of the class {!r} in the object " "graph conflicts with the Go field corresponding to " "another registry of the class {!r} ({})").format( plural_field, cls.name, registry_field_map[plural_field].name, registry_field_map[plural_field].ref), ref=cls.ref)) else: registry_field_map[plural_field] = cls reserved_type_names = { 'Errors', '{}FromJSONable'.format(mapry.naming.ucamel_case(graph.name)), '{}ToJSONable'.format(mapry.naming.ucamel_case(graph.name)) } for cls in graph.classes.values(): reserved_type_names.add( '{}FromJSONable'.format(mapry.naming.ucamel_case(cls.name))) reserved_type_names.add( '{}ToJSONable'.format(mapry.naming.ucamel_case(cls.name))) for embed in graph.embeds.values(): reserved_type_names.add( '{}FromJSONable'.format(mapry.naming.ucamel_case(embed.name))) reserved_type_names.add( '{}ToJSONable'.format(mapry.naming.ucamel_case(embed.name))) for cls in graph.classes.values(): cls_name = mapry.naming.ucamel_case(cls.name) if cls_name in reserved_type_names: mapry.validation.SchemaError( message=( "The Go struct identifier {!r} " "conflicts with the name reserved for mapry." ).format(cls_name), ref=cls.ref) for embed in graph.embeds.values(): embed_name = mapry.naming.ucamel_case(embed.name) if embed_name in reserved_type_names: mapry.validation.SchemaError( message=( "The Go struct identifier {!r} " "conflicts with the name reserved for mapry." ).format(embed_name), ref=embed.ref) graph_name = mapry.naming.ucamel_case(graph.name) if graph_name in reserved_type_names: mapry.validation.SchemaError( message=( "The Go struct identifier {!r} " "conflicts with the name reserved for mapry." ).format(graph_name), ref=graph.ref) return errs # yapf: disable _GO_TIME_FORMAT_DIRECTIVES = [ 'Sunday', 'Sun', 'January', 'Jan', '02', '_2', '01', '2006', '06', '15', '03', '3', '04', 'pm', 'PM', '05', '-0700', 'MST' ] # yapf: enable def _validate_date_time_formats(graph: mapry.Graph ) -> List[mapry.validation.SchemaError]: """ Validate that all date/time formats can be parsed and serialized in Go. :param graph: mapry definition of an object graph :return: list of errors, if any """ errs = [] # type: List[mapry.validation.SchemaError] # yapf: disable date_time_types = ((a_type, ref) for a_type, ref in mapry.iterate_over_types(graph=graph) if isinstance(a_type, (mapry.Date, mapry.Datetime, mapry.Time))) # yapf: enable for a_type, ref in date_time_types: tkn_lines = mapry.strftime.tokenize(format=a_type.format) # yapf: disable text_tkns = [ tkn for tkn_line in tkn_lines for tkn in tkn_line if tkn.identifier == 'text' ] # yapf: enable for tkn in text_tkns: for directive in _GO_TIME_FORMAT_DIRECTIVES: if directive in tkn.content: if isinstance(a_type, mapry.Date): type_str = 'Date' elif isinstance(a_type, mapry.Datetime): type_str = 'Date/time' elif isinstance(a_type, mapry.Time): type_str = 'Time' else: raise NotImplementedError( "Unhandled mapry type: {}".format(type(a_type))) errs.append( mapry.validation.SchemaError( message=( '{} format contains a conflicting ' 'Go time.Format directive {}: {}').format( type_str, directive, a_type.format), ref=ref)) break return errs def validate_schema(schema: mapry.Schema) -> List[mapry.validation.SchemaError]: """ Validate that we can generate the Go code for the given mapry schema. :param schema: mapry schema :return: list of errors, or an empty list if no errors """ name_to_composite = dict() # type: Dict[str, mapry.Composite] errs = [] # type: List[mapry.validation.SchemaError] graph_name = mapry.naming.ucamel_case(identifier=schema.graph.name) if graph_name in _KEYWORDS: errs.append( mapry.validation.SchemaError( message=( "Go identifier ({!r}) corresponding to the name of " "the object graph ({!r}) is a keyword in Go").format( graph_name, schema.graph.name), ref=schema.graph.ref)) name_to_composite[graph_name] = schema.graph for cls in schema.graph.classes.values(): cls_name = mapry.naming.ucamel_case(identifier=cls.name) # Check that the name is not a keyword if cls_name in _KEYWORDS: errs.append( mapry.validation.SchemaError( message=( "Go identifier ({!r}) corresponding to the name of " "the class ({!r}) is a keyword in Go").format( cls_name, cls.name), ref=cls.ref)) # Check that the name is not a duplicate if cls_name in name_to_composite: conflict_composite = name_to_composite[cls_name] errs.append( mapry.validation.SchemaError( message=( "Class {!r} and the composite {!r} ({}) have " "conflicting Go identifiers: {!r}".format( cls.name, conflict_composite.name, conflict_composite.ref, cls_name)), ref=cls.ref)) else: name_to_composite[cls_name] = cls # Check that the class field names are valid errs.extend(_validate_class_fields(a_class=cls)) for embed in schema.graph.embeds.values(): embed_name = mapry.naming.ucamel_case(identifier=embed.name) if embed_name in _KEYWORDS: errs.append( mapry.validation.SchemaError( message=( "Go identifier ({!r}) corresponding to the name of " "the embeddable structure ({!r}) " "is a keyword in Go").format(embed_name, embed.name), ref=embed.ref)) if embed_name in name_to_composite: conflict_composite = name_to_composite[embed_name] errs.append( mapry.validation.SchemaError( message=( "The embeddable structure {!r} and " "the composite {!r} ({}) have conflicting " "Go identifiers: {!r}".format( embed.name, conflict_composite.name, conflict_composite.ref, embed_name)), ref=embed.ref)) else: name_to_composite[embed_name] = embed # Check that the field names are valid errs.extend(_validate_embed_fields(embed=embed)) # Check that the field names of the object graph are valid # (including the class registries) errs.extend(_validate_graph_fields(graph=schema.graph)) errs.extend(_validate_date_time_formats(graph=schema.graph)) return errs
[ "noreply@github.com" ]
Parquery.noreply@github.com
65a545ee33b66672c39fab64dbefac761dbab3cf
6fbd633d0c7c831ca8217788dcd3e82cd26dd72d
/src/pkgcheck/const.py
87135e5e7de36a83947d0af03c71d28bba8104a3
[ "BSD-3-Clause" ]
permissive
chutz/pkgcheck
b93724cc0c0dd3d17e49c734faf019b2ad67b0c7
714c016381b53246b449dd9c3116811e50db744f
refs/heads/master
2020-09-22T13:46:59.498632
2019-12-01T04:05:35
2019-12-01T04:06:11
225,225,319
0
0
BSD-3-Clause
2019-12-01T20:22:06
2019-12-01T20:22:05
null
UTF-8
Python
false
false
3,343
py
"""Registration for keywords, checks, and reporters.""" import inspect import os import pkgutil import sys from functools import partial from importlib import import_module from snakeoil import mappings from . import __title__, checks, reporters, results _reporoot = os.path.realpath(__file__).rsplit(os.path.sep, 3)[0] _module = sys.modules[__name__] try: # This is a file written during installation; # if it exists, we defer to it. If it doesn't, then we're # running from a git checkout or a tarball. from . import _const as _defaults except ImportError: _defaults = object() def _GET_CONST(attr, default_value, allow_environment_override=False): consts = mappings.ProxiedAttrs(_module) is_tuple = not isinstance(default_value, str) if is_tuple: default_value = tuple(x % consts for x in default_value) else: default_value %= consts result = getattr(_defaults, attr, default_value) if allow_environment_override: result = os.environ.get(f'PKGCHECK_OVERRIDE_{attr}', result) if is_tuple: result = tuple(result) return result def _find_modules(module): if getattr(module, '__path__', False): for _imp, name, _ in pkgutil.walk_packages(module.__path__, module.__name__ + '.'): # skip "private" modules if name.rsplit('.', 1)[1][0] == '_': continue try: yield import_module(name) except ImportError as e: raise Exception(f'failed importing {name!r}: {e}') else: yield module def _find_classes(module, matching_cls): for _name, cls in inspect.getmembers(module): if (inspect.isclass(cls) and issubclass(cls, matching_cls) and cls.__name__[0] != '_'): yield cls def _find_obj_classes(module_name, matching_cls): module = import_module(f'.{module_name}', __title__) # skip top-level, base classes base_classes = {matching_cls.__name__: matching_cls} if os.path.basename(module.__file__) == '__init__.py': for cls in _find_classes(module, matching_cls): base_classes[cls.__name__] = cls classes = {} for m in _find_modules(module): for cls in _find_classes(m, matching_cls): if cls.__name__ in base_classes: continue if cls.__name__ in classes and classes[cls.__name__] != cls: raise Exception(f'object name overlap: {cls} and {classes[cls.__name__]}') classes[cls.__name__] = cls return classes def _GET_VALS(attr, func): try: result = getattr(_defaults, attr) except AttributeError: result = func() return result REPO_PATH = _GET_CONST('REPO_PATH', _reporoot, allow_environment_override=True) DATA_PATH = _GET_CONST('DATA_PATH', '%(REPO_PATH)s/data') try: KEYWORDS = mappings.ImmutableDict(_GET_VALS( 'KEYWORDS', partial(_find_obj_classes, 'checks', results.Result))) CHECKS = mappings.ImmutableDict(_GET_VALS( 'CHECKS', partial(_find_obj_classes, 'checks', checks.Check))) REPORTERS = mappings.ImmutableDict(_GET_VALS( 'REPORTERS', partial(_find_obj_classes, 'reporters', reporters.Reporter))) except SyntaxError as e: raise SyntaxError(f'invalid syntax: {e.filename}, line {e.lineno}')
[ "radhermit@gmail.com" ]
radhermit@gmail.com
c6ef643551dfb8508cda8c878e72f447e75cb54d
bec8f33002130d8395f4ac4f0c74b785aa22cac5
/appium/options/ios/xcuitest/other/command_timeouts_option.py
420b350397bc4e77af147af84a13acbd818a8ad0
[ "Apache-2.0" ]
permissive
appium/python-client
1c974fdf1ac64ce4ac37f3fc8c0a3e30c186d3ca
2e49569ed45751df4c6953466f9769336698c033
refs/heads/master
2023-09-01T22:14:03.166402
2023-09-01T11:52:27
2023-09-01T11:52:27
18,525,395
1,588
606
Apache-2.0
2023-09-10T02:00:09
2014-04-07T17:01:35
Python
UTF-8
Python
false
false
2,627
py
# Licensed to the Software Freedom Conservancy (SFC) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The SFC licenses this file # to you 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 datetime import timedelta from typing import Dict, Optional, Union from appium.options.common.supports_capabilities import SupportsCapabilities COMMAND_TIMEOUTS = 'commandTimeouts' class CommandTimeoutsOption(SupportsCapabilities): @property def command_timeouts(self) -> Optional[Union[Dict[str, timedelta], timedelta]]: """ Custom timeout(s) for WDA backend commands execution. """ value = self.get_capability(COMMAND_TIMEOUTS) if value is None: return None if isinstance(value, dict): return {k: timedelta(milliseconds=v) for k, v in value.items()} return timedelta(milliseconds=int(value)) @command_timeouts.setter def command_timeouts(self, value: Union[Dict[str, timedelta], timedelta, int]) -> None: """ Custom timeout for all WDA backend commands execution. This might be useful if WDA backend freezes unexpectedly or requires too much time to fail and blocks automated test execution. Dictionary keys are command names which you can find in server logs. Look for "Executing command 'command_name'" records. Timeout value is expected to contain max duration to wait for the given WDA command to be executed before terminating the session forcefully. The magic 'default' key allows to provide the timeout for all other commands that were not explicitly mentioned as dictionary keys """ if isinstance(value, dict): self.set_capability(COMMAND_TIMEOUTS, {k: int(v.total_seconds() * 1000) for k, v in value.items()}) elif isinstance(value, timedelta): self.set_capability(COMMAND_TIMEOUTS, f'{int(value.total_seconds() * 1000)}') else: self.set_capability(COMMAND_TIMEOUTS, value)
[ "noreply@github.com" ]
appium.noreply@github.com
9f3e016075ca44f0a6162e23e5b74692c5851c57
6b1febf141315330fcb67495e094ff7aeb6520c8
/ajaxsite/mixins.py
f42c1cf1f8587b620de9f6014651869faba40358
[]
no_license
anidem/ajax-setup
40a6ae856b0b3415ba3a2842f812c96d2b0978ef
bf5c9187eb878c627c5cb20a6e58a4e0e602be65
refs/heads/master
2021-01-10T20:38:22.928879
2014-11-17T18:13:46
2014-11-17T18:13:46
null
0
0
null
null
null
null
UTF-8
Python
false
false
971
py
from django.http import JsonResponse class AjaxableResponseMixin(object): """ Mixin to add AJAX support to a form. Must be used with an object-based FormView (e.g. CreateView) """ def form_invalid(self, form): response = super(AjaxableResponseMixin, self).form_invalid(form) if self.request.is_ajax(): return JsonResponse(form.errors, status=400) else: return response def form_valid(self, form): # We make sure to call the parent's form_valid() method because # it might do some processing (in the case of CreateView, it will # call form.save() for example). response = super(AjaxableResponseMixin, self).form_valid(form) print 'AJAX Mixin: ', self.request.is_ajax() if self.request.is_ajax(): data = { 'pk': self.object.pk, } return JsonResponse(data) else: return response
[ "richmedina@gmail.com" ]
richmedina@gmail.com
3ac03889ebac07e88d1b65696d71d07c0ca04cb5
3bbe69481d294eba60f83639f3a9430fb8cda4d9
/feedback/views.py
69481acb6cf19ded68b141738fab0ae2af40b3df
[]
no_license
ulugbek1999/ncd-cms
5e288f44b01387cd66a54d2dcaf1e0d288205bc4
dcb43bf65f0d6efcbf6481f5c9284c8c1a7c6b9d
refs/heads/master
2022-09-06T13:22:34.637080
2019-12-14T09:10:26
2019-12-14T09:10:26
204,455,916
0
0
null
null
null
null
UTF-8
Python
false
false
615
py
from django.urls import reverse from django.views.generic import TemplateView, ListView, View, DetailView from .models import Feedback from django.contrib.auth.mixins import LoginRequiredMixin class FeedbackListView(LoginRequiredMixin, ListView): template_name = 'feedback/list.html' model = Feedback context_object_name = 'feedbacks' class FeedbackCreateView(LoginRequiredMixin, TemplateView): template_name = 'feedback/create.html' class FeedbackUpdateView(LoginRequiredMixin, DetailView): template_name = 'feedback/update.html' model = Feedback context_object_name = 'feedback'
[ "kayrat.nazov@gmail.com" ]
kayrat.nazov@gmail.com
11bb78f5bf946d78ca3589dc9dcad9baeaa919c9
163bbb4e0920dedd5941e3edfb2d8706ba75627d
/Code/CodeRecords/2462/60708/289131.py
444c31167f10af1ad63b76154f6c924656b18429
[]
no_license
AdamZhouSE/pythonHomework
a25c120b03a158d60aaa9fdc5fb203b1bb377a19
ffc5606817a666aa6241cfab27364326f5c066ff
refs/heads/master
2022-11-24T08:05:22.122011
2020-07-28T16:21:24
2020-07-28T16:21:24
259,576,640
2
1
null
null
null
null
UTF-8
Python
false
false
652
py
def find(list,l,r,index): if(l>r): return index mid=(l+r)//2 if(list[mid]>list[mid-1] and list[mid]>list[mid+1]): index=mid find(list,l,mid-1,index) return index else: index1=find(list,l,mid-1,index) index2=find(list,mid+1,r,index) if index1!=-1: return index1 if index2!=-1: return index2 else: return -1 if __name__ == '__main__': temp = input().split(",") list = [] for item in temp: list.append(int(item)) try: print(find(list, 0, len(list) - 1,-1)) except BaseException: print(1)
[ "1069583789@qq.com" ]
1069583789@qq.com
02cc23d4157b6b0f584b4183e57cb643b4c693e1
57870ba30e4c530482db3a2f182e6c037a010a01
/cauldron/test/test_reload.py
c9f2890cf6018d34bfe35ba78af77afa1113469a
[ "MIT" ]
permissive
khemanta/cauldron
32e17b978a5856a4ac12bc79cdd23583207c0750
79ae3aa2cf919feb5c3365f85ae006075bec47e3
refs/heads/master
2021-01-11T14:25:16.416313
2017-02-08T23:12:24
2017-02-08T23:12:24
null
0
0
null
null
null
null
UTF-8
Python
false
false
398
py
from cauldron.test import support from cauldron.test.support import scaffolds class TestReload(scaffolds.ResultsTest): """ """ def test_reload(self): """ """ r = support.run_command('open @examples:hello_cauldron') r = support.run_command('reload') self.assertFalse(r.failed, 'should not have failed') support.run_command('close')
[ "swernst@gmail.com" ]
swernst@gmail.com
0f06d523fd131eb90436cc8c91f1e500395a99c9
bfdab27f224d9cac02e319fe55b53172fbf8d1a2
/motion_editor_core/data/thor/positions/arm/cebit_open_1.py
8a67313f858c7528161178e516a267cac8682468
[]
no_license
tu-darmstadt-ros-pkg/motion_editor
c18294b4f035f737ff33d1dcbdfa87d4bb4e6f71
178a7564b18420748e1ca4413849a44965823655
refs/heads/master
2020-04-06T12:37:30.763325
2016-09-15T14:11:48
2016-09-15T14:11:48
35,028,245
2
3
null
2015-05-05T13:20:27
2015-05-04T10:18:22
Python
UTF-8
Python
false
false
73
py
{ 'cebit_open_1': [1.2409, -0.0628, 0.1401, -0.13, 0.6785, 0.0628, 0.0]}
[ "martin.sven.oehler@gmail.com" ]
martin.sven.oehler@gmail.com
f023f3dae9e638f1830edf280727cf851dbd9faa
fdb9b553a23647f7ea06f690613707c40b54902f
/src/main/resources/resource/Tracking/Tracking.py
870b67eea8d276da57bc8641d9971ca3702a1d76
[ "CC-BY-2.5", "Apache-2.0" ]
permissive
ShaunHolt/myrobotlab
d8d9f94e90457474cf363d36f4a45d396cfae900
92046d77abd560f0203050b3cccb21aa9df467f2
refs/heads/develop
2021-07-08T04:55:01.462116
2020-04-18T19:58:17
2020-04-18T19:58:17
122,795,957
0
0
Apache-2.0
2020-04-18T19:58:18
2018-02-25T01:37:54
Java
UTF-8
Python
false
false
2,158
py
# a minimal tracking script - this will start all peer # services and attach everything appropriately # change parameters depending on your pan tilt, pins and # Arduino details # all commented code is not necessary but allows custom # options port = "COM19" #change COM port to your own port xServoPin = 13 #change this to the right servo pin if needed, for inmoov this is right yServoPin = 12 #change this to the right servo pin if needed, for inmoov this is right # create a servo controller and a servo arduino = Runtime.start("arduino","Arduino") xServo = Runtime.start("xServo","Servo") yServo = Runtime.start("yServo","Servo") # start optional virtual arduino service, used for test #virtual=1 if ('virtual' in globals() and virtual): virtualArduino = Runtime.start("virtualArduino", "VirtualArduino") virtualArduino.connect(port) arduino.connect(port) xServo.attach(arduino.getName(), xServoPin) yServo.attach(arduino.getName(), yServoPin) tracker = Runtime.start("tracker", "Tracking") opencv=tracker.getOpenCV() # set specifics on each Servo xServo.setMinMax(30, 150) #minimum and maximum settings for the X servo # servoX.setInverted(True) # invert if necessary xServo.setMinMax(30, 150) #minimum and maximum settings for the Y servo # servoY.setInverted(True) # invert if necessary # changing Pid values change the # speed and "jumpyness" of the Servos pid = tracker.getPID() # these are default setting # adjust to make more smooth # or faster pid.setPID("x",5.0, 5.0, 0.1) pid.setPID("y",5.0, 5.0, 0.1) # connect to the Arduino ( 0 = camera index ) tracker.connect(opencv, xServo, yServo) opencv.broadcastState(); sleep(1) # Gray & PyramidDown make face tracking # faster - if you dont like these filters - you # may remove them before you select a tracking type with # the following command # tracker.clearPreFilters() # diffrent types of tracking # lkpoint - click in video stream with # mouse and it should track # simple point detection and tracking # tracker.startLKTracking() # scans for faces - tracks if found # tracker.findFace() # tracker + facedetect : tracker.faceDetect(True) tracker.faceDetect()
[ "grog@myrobotlab.org" ]
grog@myrobotlab.org
11563a609e255317803e2b21817ec9e87f6efe33
7bededcada9271d92f34da6dae7088f3faf61c02
/pypureclient/flasharray/FA_2_19/models/directory.py
0a684f6248f887806fa3011cccd444893b0e0135
[ "BSD-2-Clause" ]
permissive
PureStorage-OpenConnect/py-pure-client
a5348c6a153f8c809d6e3cf734d95d6946c5f659
7e3c3ec1d639fb004627e94d3d63a6fdc141ae1e
refs/heads/master
2023-09-04T10:59:03.009972
2023-08-25T07:40:41
2023-08-25T07:40:41
160,391,444
18
29
BSD-2-Clause
2023-09-08T09:08:30
2018-12-04T17:02:51
Python
UTF-8
Python
false
false
6,952
py
# coding: utf-8 """ FlashArray REST API No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: 2.19 Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re import six import typing from ....properties import Property if typing.TYPE_CHECKING: from pypureclient.flasharray.FA_2_19 import models class Directory(object): """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { 'id': 'str', 'name': 'str', 'created': 'int', 'destroyed': 'bool', 'directory_name': 'str', 'file_system': 'FixedReference', 'path': 'str', 'space': 'Space', 'time_remaining': 'int', 'limited_by': 'LimitedBy' } attribute_map = { 'id': 'id', 'name': 'name', 'created': 'created', 'destroyed': 'destroyed', 'directory_name': 'directory_name', 'file_system': 'file_system', 'path': 'path', 'space': 'space', 'time_remaining': 'time_remaining', 'limited_by': 'limited_by' } required_args = { } def __init__( self, id=None, # type: str name=None, # type: str created=None, # type: int destroyed=None, # type: bool directory_name=None, # type: str file_system=None, # type: models.FixedReference path=None, # type: str space=None, # type: models.Space time_remaining=None, # type: int limited_by=None, # type: models.LimitedBy ): """ Keyword args: id (str): A globally unique, system-generated ID. The ID cannot be modified and cannot refer to another resource. name (str): A user-specified name. The name must be locally unique and can be changed. created (int): The managed directory creation time, measured in milliseconds since the UNIX epoch. destroyed (bool): Returns a value of `true` if the managed directory has been destroyed and is pending eradication. The `time_remaining` value displays the amount of time left until the destroyed managed directory is permanently eradicated. Once the `time_remaining` period has elapsed, the managed directory is permanently eradicated and can no longer be recovered. directory_name (str): The managed directory name without the file system name prefix. A full managed directory name is constructed in the form of `FILE_SYSTEM:DIR` where `FILE_SYSTEM` is the file system name and `DIR` is the value of this field. file_system (FixedReference): The file system that this managed directory is in. path (str): Absolute path of the managed directory in the file system. space (Space): Displays size and space consumption information. time_remaining (int): The amount of time left, measured in milliseconds until the destroyed managed directory is permanently eradicated. limited_by (LimitedBy): The quota policy that is limiting usage on this managed directory. This policy defines the total amount of space provisioned to this managed directory and its descendants. The returned value contains two parts&#58; the name of the policy and the managed directory to which the policy is attached. """ if id is not None: self.id = id if name is not None: self.name = name if created is not None: self.created = created if destroyed is not None: self.destroyed = destroyed if directory_name is not None: self.directory_name = directory_name if file_system is not None: self.file_system = file_system if path is not None: self.path = path if space is not None: self.space = space if time_remaining is not None: self.time_remaining = time_remaining if limited_by is not None: self.limited_by = limited_by def __setattr__(self, key, value): if key not in self.attribute_map: raise KeyError("Invalid key `{}` for `Directory`".format(key)) self.__dict__[key] = value def __getattribute__(self, item): value = object.__getattribute__(self, item) if isinstance(value, Property): raise AttributeError else: return value def __getitem__(self, key): if key not in self.attribute_map: raise KeyError("Invalid key `{}` for `Directory`".format(key)) return object.__getattribute__(self, key) def __setitem__(self, key, value): if key not in self.attribute_map: raise KeyError("Invalid key `{}` for `Directory`".format(key)) object.__setattr__(self, key, value) def __delitem__(self, key): if key not in self.attribute_map: raise KeyError("Invalid key `{}` for `Directory`".format(key)) object.__delattr__(self, key) def keys(self): return self.attribute_map.keys() def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.swagger_types): if hasattr(self, attr): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value if issubclass(Directory, dict): for key, value in self.items(): result[key] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, Directory): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
[ "noreply@github.com" ]
PureStorage-OpenConnect.noreply@github.com
f3b1cf51d5b02fff27e636e3da4cc964efe47835
77be22f90869e8ad91e8ae15009274e97753e832
/andrewl_mortal_kombat/rsa1.py
8cb9ea18f8adfb8bd5883d58c0d3962a58e2e93a
[]
no_license
lwerdna/crackme
a18b0544c51d04b947bf2d6254c71dc4744dd728
9f9e082805a75120c6084cedb4a9306c6ec3818d
refs/heads/master
2023-02-14T04:55:39.275773
2023-01-22T05:50:25
2023-01-22T05:50:25
192,410,237
4
2
null
null
null
null
UTF-8
Python
false
false
807
py
#!/usr/bin/python # rsa challenge, straight forward # # example name/serial pairs: # # knowledge/26582066182495701597915248727138888909 # is/141271412203160330710342183730048971956 # power/135066534443646675683259471815808056369 # Mortal/125332528239055605555179231197739673804 # Kombat/97493559731364222970517291247384579880 import sys # globals d = 65537 n = 152415787532388368909312594615759791673 # args? if len(sys.argv) != 3: print "usage: ", sys.argv[0], " <name> <serial>"; quit() # convert name to number eg: "AAAA" -> 0x41414141 m = 0; for char in sys.argv[1]: m = m*256 + ord(char); if m > n: m = m % n; # convert serial to number eg: "1234" -> 1234 c = int(sys.argv[2], 10); # process, check if pow(c, d, n) == m: print "good" else: print "bad"
[ "andrew@vector35.com" ]
andrew@vector35.com
c754a90037d31c683e8dcffccf46f531f37f3f1b
f2b172f7c1dcf0ac28fe7465b5844b48facade18
/12/120601/style2.py
6e181d0f6005d2fa5769718d7f1e0e251b2f71ef
[]
no_license
0gravity000/IntroducingPython
2fde12485d0597e72a7da801a08d5048a47f2ff5
5d3281dbe37ed1a08d71cb6a36841781f9ac0ccf
refs/heads/master
2023-07-19T02:53:23.081806
2021-09-30T01:51:44
2021-09-30T01:51:44
403,935,207
0
0
null
null
null
null
UTF-8
Python
false
false
145
py
# 12.6.1 pylint、pyflakes、pep8によるチェック # pip install pylint # pip install pyflakes a = 1 b = 2 c = 3 print(a) print(b) print(c)
[ "0gravity000@gmail.com" ]
0gravity000@gmail.com
72cd412bb1d32b99ae9b5fb9e575dec5bfecfaf3
56d58964a7a498e8f99bf804927b5d15f69fbccb
/fluent_pages/pagetypes/fluentpage/admin.py
992accd311303ed0bd915a6ae3924c8c0af9afd4
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ]
permissive
floppya/django-fluent-pages
3c8e56a12261c6901ef63008e3203f7518f5864e
5041d3b2d1d02bfc90cca1fe017618d99555a37b
refs/heads/master
2021-01-18T11:26:13.853182
2013-04-06T22:16:20
2013-04-06T22:16:20
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,839
py
from django.conf.urls.defaults import patterns, url from fluent_pages.admin import HtmlPageAdmin from fluent_pages.models import PageLayout from fluent_pages.utils.ajax import JsonResponse from fluent_contents.admin.placeholdereditor import PlaceholderEditorAdmin from fluent_contents.analyzer import get_template_placeholder_data from .widgets import LayoutSelector class FluentPageAdmin(PlaceholderEditorAdmin, HtmlPageAdmin): """ This admin is a small binding between the pagetypes of *django-fluent-pages* and page contents of *django-fluent-contents*. In fact, most code only concerns with the layout mechanism that is custom for each implementation. To build a variation of this page, see the API documentation of `Creating a CMS system <http://django-fluent-contents.readthedocs.org/en/latest/cms.html>`_ in the *django-fluent-contents* documentation to implement the required API's. """ # By using base_fieldsets, the parent PageAdmin will # add an extra fieldset for all derived fields automatically. FIELDSET_GENERAL = (None, { 'fields': HtmlPageAdmin.FIELDSET_GENERAL[1]['fields'][:-1] + ('layout',) + HtmlPageAdmin.FIELDSET_GENERAL[1]['fields'][-1:], }) base_fieldsets = ( FIELDSET_GENERAL, HtmlPageAdmin.FIELDSET_SEO, HtmlPageAdmin.FIELDSET_MENU, HtmlPageAdmin.FIELDSET_PUBLICATION, ) change_form_template = ["admin/fluent_pages/page/page_editor.html", "admin/fluent_pages/page.html", ] class Media: js = ('fluent_pages/fluentpage/fluent_layouts.js',) # ---- fluent-contents integration ---- def get_placeholder_data(self, request, obj): """ Provides a list of :class:`fluent_contents.models.PlaceholderData` classes, that describe the contents of the template. """ template = self.get_page_template(obj) if not template: return [] else: return get_template_placeholder_data(template) def get_page_template(self, page): """ Return the template that is associated with the page. """ if page is None: # Add page. start with default template. try: return PageLayout.objects.all()[0].get_template() except IndexError: return None else: # Change page, honor template of object. return page.layout.get_template() # ---- Layout selector code ---- def formfield_for_foreignkey(self, db_field, request=None, **kwargs): if db_field.name == 'layout': kwargs['widget'] = LayoutSelector return super(FluentPageAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs) def get_urls(self): """ Introduce more urls """ urls = super(FluentPageAdmin, self).get_urls() my_urls = patterns('', url(r'^get_layout/(?P<id>\d+)/$', self.admin_site.admin_view(self.get_layout_view)) ) return my_urls + urls def get_layout_view(self, request, id): """ Return the metadata about a layout """ try: layout = PageLayout.objects.get(pk=id) except PageLayout.DoesNotExist: json = {'success': False, 'error': 'Layout not found'} status = 404 else: template = layout.get_template() placeholders = get_template_placeholder_data(template) status = 200 json = { 'id': layout.id, 'key': layout.key, 'title': layout.title, 'placeholders': [p.as_dict() for p in placeholders], } return JsonResponse(json, status=status)
[ "vdboor@edoburu.nl" ]
vdboor@edoburu.nl
dbbc4a131d4c1c6286c0c8fad167b1b843753cd3
795efc7484b5e1ccfd18ead6afed9dc3ccb7de99
/apps/books/urls.py
344716a952eff813a2da3a1fe534e881ef2988ca
[]
no_license
wd5/book_base
ccf874357a42679043cb9063be443761a6d91ed4
922820180b24c45fd56afff72e55de79728d32b4
refs/heads/master
2021-01-10T01:37:41.318168
2012-08-01T09:54:34
2012-08-01T09:54:34
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,181
py
# -*- coding: utf-8 -*- from django.conf.urls import patterns, url from .views import BookList, BookDetail from .views import BookBlank, BookBlankFromBookmark from .views import BookmarkList, BookmarkAdd, BookmarkDel, BookmarkDelAll from .views import RenderOrderBookForm, MakeOrderBook, CancelOrderBook urlpatterns = patterns('', url(r'^$', BookList.as_view(), name='book_list'), url(r'^(?P<pk>\d+)/$', BookDetail.as_view(), name='book_detail'), url(r'^(?P<pk>\d+)/blank/$', BookBlank.as_view(), name='book_blank'), url(r'^bookmark/$', BookmarkList.as_view(), name='bookmark_list'), url(r'^bookmark/add/$', BookmarkAdd.as_view(), name='bookmark_add'), url(r'^bookmark/del/$', BookmarkDel.as_view(), name='bookmark_del'), url(r'^bookmark/del/all/$', BookmarkDelAll.as_view(), name='bookmark_del_all'), url(r'^bookmark/print-all/$', BookBlankFromBookmark.as_view(), name='bookmarks_print_all'), # url(r'^order/form/$', RenderOrderBookForm.as_view(), name='order_form'), url(r'^order/make/$', MakeOrderBook.as_view(), name='order_make'), url(r'^order/calcel/$', CancelOrderBook.as_view(), name='order_cancel'), )
[ "DrMartiner@GMail.Com" ]
DrMartiner@GMail.Com
cbbfba50005ee9b1a3b09f614c684c894ae7e6b6
b0ec01db9a15fcb171f9a73f44f67a736804f113
/app/__init__.py
323adc2762af574ee13612b08b7c39bece7521d6
[]
no_license
uwase-diane/BookApp
60b7aded64f6892e51a13f3c6c487c25534f46f0
4549a1705b38a4a2f86c1b0cb34a2468c5964a56
refs/heads/master
2023-01-29T00:28:24.781440
2020-12-10T09:28:49
2020-12-10T09:28:49
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,242
py
from flask import Flask from config import config_options from flask_bootstrap import Bootstrap from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager from flask_uploads import UploadSet,configure_uploads,IMAGES from flask_simplemde import SimpleMDE login_manager = LoginManager() login_manager.session_protection = 'strong' login_manager.login_view = 'auth.login' bootstrap = Bootstrap() db = SQLAlchemy() photos = UploadSet('photos',IMAGES) simple = SimpleMDE() def create_app(configuration): app = Flask(__name__) app.url_map.strict_slashes = False simple.init_app(app) # Creating the app configurations app.config.from_object(config_options[configuration]) # Initializing Flask Extensions bootstrap = Bootstrap(app) db.init_app(app) login_manager.init_app(app) # Registering the blueprint from .main import main as main_blueprint app.register_blueprint(main_blueprint) from .auth import auth as auth_blueprint app.register_blueprint(auth_blueprint,url_prefix = '/authenticate') # configure UploadSet configure_uploads(app,photos) # setting config from .request import configure_request configure_request(app) return app
[ "tharcissieidufashe@gmail.com" ]
tharcissieidufashe@gmail.com
01521707f60526029a7269c3681ee91590141a97
6219e6536774e8eeb4cadc4a84f6f2bea376c1b0
/scraper/storage_spiders/demxinhvn.py
c23106e40abebd9467378da623d03ed7d214615c
[ "MIT" ]
permissive
nguyenminhthai/choinho
109d354b410b92784a9737f020894d073bea1534
d2a216fe7a5064d73cdee3e928a7beef7f511fd1
refs/heads/master
2023-05-07T16:51:46.667755
2019-10-22T07:53:41
2019-10-22T07:53:41
null
0
0
null
null
null
null
UTF-8
Python
false
false
975
py
# Auto generated by generator.py. Delete this line if you make modification. from scrapy.spiders import Rule from scrapy.linkextractors import LinkExtractor XPATH = { 'name' : "//div[@id='product-main']/h1", 'price' : "//span[@class='price-new']/span[@id='formated_special']", 'category' : "", 'description' : "//div[@id='tab-description']", 'images' : "//ul[@id='boss-image-additional']/li/a/@href | //div[@class='image a_bossthemes']/a/@href", 'canonical' : "//link[@rel='canonical']/@href", 'base_url' : "//base/@href", 'brand' : "" } name = 'demxinh.vn' allowed_domains = ['demxinh.vn'] start_urls = ['http://demxinh.vn/'] tracking_url = '' sitemap_urls = [''] sitemap_rules = [('', 'parse_item')] sitemap_follow = [''] rules = [ Rule(LinkExtractor(allow=['\.html$']), 'parse_item'), Rule(LinkExtractor(allow=['/[a-zA-Z0-9-]+($|\?page=\d+$)'], deny=['index\.php']), 'parse'), #Rule(LinkExtractor(), 'parse_item_and_links'), ]
[ "nguyenchungthuy.hust@gmail.com" ]
nguyenchungthuy.hust@gmail.com
74ebf1832b3b13468d1c73b53dcd6062ad53a6bb
50be0ae5bc8a28b25c2ed81ea119140b8fa160bd
/libs/markdowncode.py
44fef0ef313ec8be9bb438da32e337aa86416770
[]
no_license
Deattor/docmaster
e899c98cc3f93fd2cb4383205ae76111a53febe5
d3647c2734415c566554e07363fc85ec652fa626
refs/heads/master
2020-12-26T20:40:38.404797
2014-03-09T04:45:28
2014-03-09T04:45:28
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,091
py
#encoding=utf-8 ##预处理器 from markdown.preprocessors import Preprocessor class CodePreprocessor(Preprocessor): def run(self, lines): new_lines = [] flag_in = False block = [] for line in lines: if line[:3]=='!!!': flag_in = True block.append('<pre class="brush: %s;">' % line[3:].strip()) elif flag_in: if line.strip() and line[0]=='!': block.append(line[1:]) else: flag_in = False block.append('</pre>') block.append(line) new_lines.extend(block) block = [] else: new_lines.append(line) if not new_lines and block: new_lines = block return new_lines ##后置处理器 from markdown.postprocessors import Postprocessor class CodePostprocessor(Postprocessor): def run(self, text): t_list = [] for line in text.split('\n'): if line[:5]=='<p>!<': line = line.lstrip('<p>').replace('</p>', '')[1:] t_list.append(line) return '\n'.join(t_list) ##扩展主体类 from markdown.extensions import Extension from markdown.util import etree class CodeExtension(Extension): def __init__(self, configs={}): self.config = configs def extendMarkdown(self, md, md_globals): ##注册扩展,用于markdown.reset时扩展同时reset md.registerExtension(self) ##设置Preprocessor codepreprocessor = CodePreprocessor() #print md.preprocessors.keys() md.preprocessors.add('codepreprocessor', codepreprocessor, '<normalize_whitespace') ##设置Postprocessor codepostprocessor = CodePostprocessor() #print md.postprocessors.keys() md.postprocessors.add('codepostprocessor', codepostprocessor, '>unescape') ##print md_globals ##markdown全局变量
[ "five3@163.com" ]
five3@163.com
a372d6acf27900226db66972f167ca17971335c0
5f57cfb662e7a490235255273114d2eb712a9ce4
/djd-prog2/noite-aula10/inimigos.py
84a03745c90c009a40dee665aa4cb6f38314c03d
[]
no_license
antoniorcn/fatec-2020-2s
762e14acfbf0cb42a2e478662e6cf0001794f72c
4d90cc35d354382ad38c20ce2e32924216d7d747
refs/heads/master
2023-01-27T22:52:29.529360
2020-12-05T13:51:30
2020-12-05T13:51:30
289,972,977
9
7
null
null
null
null
UTF-8
Python
false
false
253
py
AMARELO = (255, 255, 0) class Alien: def __init__(self, c, x, y): self.cor = c self.pos_x = x self.pos_y = y a1 = Alien("AMARELO", 100, 500) a2 = Alien("AZUL", 150, 350) print("A1 Cor:", a1.cor) print("A2 Cor:", a2.cor)
[ "antoniorcn@hotmail.com" ]
antoniorcn@hotmail.com
17544fa8a3e7e531224872ab76b461074fd8402f
3db0033d5266d73a84ab8cb0385b1b5f718f1d47
/menpobench/predefined/trainable_method/sdm.py
9f087bed219adb651b23bc29f03d6016f17151ca
[ "BSD-3-Clause" ]
permissive
luckynote/menpobench
64ba98480712289e777d75b1d40402a8fe121857
cf0ea24c0bb6143bcfc6b0dc18951bcded69317e
refs/heads/master
2020-03-26T22:58:14.692536
2016-06-16T21:32:40
2016-06-16T21:32:40
null
0
0
null
null
null
null
UTF-8
Python
false
false
756
py
from menpobench.method import MenpoFitWrapper from menpobench.imgprocess import menpo_img_process from menpofit.sdm import SDMTrainer metadata = { 'display_name': 'Menpo Supervised Decent Method', 'display_name_short': 'Menpo SDM' } def train(img_generator): # clean up the images with the standard menpo pre-processing images = [menpo_img_process(img) for img in img_generator] fitter = SDMTrainer(normalization_diagonal=150, downscale=1.1, n_perturbations=15).train(images, group='gt', verbose=True) # return a callable that wraps the menpo fitter in order to integrate with # menpobench return MenpoFitWrapper(fitter)
[ "jabooth@gmail.com" ]
jabooth@gmail.com