blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
616
content_id
stringlengths
40
40
detected_licenses
sequencelengths
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
sequencelengths
1
1
author_id
stringlengths
1
132
67a016a9d7ba978adccc3d947bf989f1fe06db71
98e944b793b2d907e802f979bc6309b75b678716
/shell/shell_person.py
30fde62c5f4a05fb73b9732127fd0ead9955e568
[]
no_license
rg3915/avesmarias
3fa17416e64908714f164254434f3ec1a6423696
ce29072d17024b91e8afab309e203e68fc0e15d2
refs/heads/master
2021-01-12T11:32:45.196569
2016-11-06T14:54:05
2016-11-06T14:54:05
72,948,389
0
0
null
null
null
null
UTF-8
Python
false
false
842
py
import string import random import csv from avesmarias.core.models import Person, Phone PHONE_TYPE = ('pri', 'com', 'res', 'cel') person_list = [] ''' Read person.csv ''' with open('fix/person.csv', 'r') as f: r = csv.DictReader(f) for dct in r: person_list.append(dct) f.close() ''' Insert Persons ''' obj = [Person(**person) for person in person_list] Person.objects.bulk_create(obj) def gen_phone(): digits_ = str(''.join(random.choice(string.digits) for i in range(11))) return '{} 9{}-{}'.format(digits_[:2], digits_[3:7], digits_[7:]) ''' Insert Phones ''' persons = Person.objects.all() for person in persons: for i in range(1, random.randint(1, 5)): Phone.objects.create( person=person, phone=gen_phone(), phone_type=random.choice(PHONE_TYPE)) # Done
638bb6032545c27060aeaa7fbe01b9a33bcf0ea7
d6a1630bcc03f059438f949ba4f59b86ef5a4bd6
/features/geopy_distance_features.py
882428e8ac4d7f9aaa832bb3288cfd7c98e3853d
[ "MIT" ]
permissive
SunnyMarkLiu/Kaggle_NYC_Taxi_Trip_Duration
063f7327e9075fc7435930513cc36f8dbd35d256
eca7f44bc3bf1af0690305b45858359adac617b4
refs/heads/master
2021-01-02T09:30:25.639858
2017-09-13T03:53:18
2017-09-13T03:53:18
99,228,943
1
0
null
null
null
null
UTF-8
Python
false
false
1,772
py
#!/usr/local/miniconda2/bin/python # _*_ coding: utf-8 _*_ """ @author: MarkLiu @time : 17-9-12 上午11:10 """ import os import sys module_path = os.path.abspath(os.path.join('..')) sys.path.append(module_path) import pandas as pd from geopy.distance import great_circle from utils import data_utils from conf.configure import Configure # remove warnings import warnings warnings.filterwarnings('ignore') def main(): if os.path.exists(Configure.processed_train_path.format('8')): return train, test = data_utils.load_dataset(op_scope='7') print 'train: {}, test: {}'.format(train.shape, test.shape) trip_durations = train['trip_duration'] del train['trip_duration'] conbined_data = pd.concat([train, test]) def driving_distance(raw): startpoint = (raw['pickup_latitude'], raw['pickup_longitude']) endpoint = (raw['dropoff_latitude'], raw['dropoff_longitude']) distance = great_circle(startpoint, endpoint).miles return distance print 'calc geopy distance features...' conbined_data['osmnx_distance'] = conbined_data[['pickup_latitude', 'pickup_longitude', 'dropoff_latitude', 'dropoff_longitude']].apply(driving_distance, axis=1) train = conbined_data.iloc[:train.shape[0], :] test = conbined_data.iloc[train.shape[0]:, :] train['trip_duration'] = trip_durations print 'train: {}, test: {}'.format(train.shape, test.shape) print 'save dataset...' data_utils.save_dataset(train, test, op_scope='8') if __name__ == '__main__': print '========== generate geopy distance features ==========' main()
90d11cd9857b6436e79804bc753b2bbaf34a422d
fc3f784c8d00f419b11cbde660fe68a91fb080ca
/algoritm/20상반기 코딩테스트/소수 경로/bj1963.py
6f4d4774ef60720d7fc72ff334ec8ba7ecaf763d
[]
no_license
choo0618/TIL
09f09c89c8141ba75bf92657ac39978913703637
70437a58015aecee8f3d86e6bfd0aa8dc11b5447
refs/heads/master
2021-06-25T07:01:34.246642
2020-12-21T04:57:13
2020-12-21T04:57:13
163,782,782
0
0
null
null
null
null
UTF-8
Python
false
false
869
py
import sys sys.stdin=open('bj1963.txt','r') def Find(n,s): ns=[] for i in ['0','1','2','3','4','5','6','7','8','9']: if not n and i=='0':continue ss=s[:n]+i+s[n+1:] if not Map[int(ss)] and s!=ss and not M[int(ss)]: M[int(ss)]=1 ns.append(ss) return ns Map=[0]*10001 for i in range(2,10001): if Map[i]:continue tmp=i while True: tmp+=i if tmp>10000:break Map[tmp]=1 T=int(input()) for t in range(T): n1,n2=map(int,input().split()) if n1==n2:print(0);continue Que=[str(n1)] M=[0]*10001 M[n1]=1 R,Check=0,0 while Que and not Check: R+=1 Q=[] for q in Que: if int(q)==n2:Check=1;break for i in range(4): Q+=Find(i,q) Que=Q if Check:print(R-1) else:print('Impossible')
c411ab47bb8a9ce4418120687416c8e7e69ca45e
ac9f9ff30c64c369c45123f1998161c007b4abb3
/cantools/db/formats/sym.py
3f6fcd8ebf1b59755b4d9c6e2199b97063f6f91d
[ "MIT" ]
permissive
kanirik/cantools
2961712b77610f4e9391a89627780c2a31e37c35
f4a0d0e45ba872638088206a16e5aee01f49bc43
refs/heads/master
2020-03-08T13:37:38.390623
2018-02-16T20:00:16
2018-02-16T20:00:16
null
0
0
null
null
null
null
UTF-8
Python
false
false
13,799
py
# Load and dump a CAN database in SYM format. import logging from collections import OrderedDict from pyparsing import Word from pyparsing import Literal from pyparsing import Keyword from pyparsing import Optional from pyparsing import Suppress from pyparsing import Group from pyparsing import QuotedString from pyparsing import StringEnd from pyparsing import printables from pyparsing import nums from pyparsing import alphas from pyparsing import ZeroOrMore from pyparsing import OneOrMore from pyparsing import delimitedList from pyparsing import dblSlashComment from pyparsing import ParseException from pyparsing import ParseSyntaxException from ..signal import Signal from ..message import Message from ..internal_database import InternalDatabase from .utils import num from .utils import ParseError LOGGER = logging.getLogger(__name__) def _create_grammar_6_0(): """Create the SYM 6.0 grammar. """ word = Word(printables.replace(';', '').replace(':', '')) positive_integer = Word(nums) number = Word(nums + '.Ee-+') lp = Suppress(Literal('(')) rp = Suppress(Literal(')')) lb = Suppress(Literal('[')) rb = Suppress(Literal(']')) name = Word(alphas + nums + '_-').setWhitespaceChars(' ') assign = Suppress(Literal('=')) comma = Suppress(Literal(',')) type_ = name version = Group(Keyword('FormatVersion') - assign - Keyword('6.0')) title = Group(Keyword('Title') - assign - QuotedString('"')) enum_value = Group(number + assign + QuotedString('"')) enum = Group(Suppress(Keyword('Enum')) - assign - name - Suppress(lp) + Group(delimitedList(enum_value)) - Suppress(rp)) sig_unit = Group(Literal('/u:') + word) sig_factor = Group(Literal('/f:') + word) sig_offset = Group(Literal('/o:') + word) sig_min = Group(Literal('/min:') + word) sig_max = Group(Literal('/max:') + word) sig_default = Group(Literal('/d:') + word) sig_long_name = Group(Literal('/ln:') + word) sig_enum = Group(Literal('/e:') + word) signal = Group(Suppress(Keyword('Sig')) - Suppress(assign) - name - type_ + Group(Optional(positive_integer)) + Group(Optional(Keyword('-m'))) + Group(Optional(sig_unit) + Optional(sig_factor) + Optional(sig_offset) + Optional(sig_min) + Optional(sig_max) + Optional(sig_default) + Optional(sig_long_name) + Optional(sig_enum))) symbol = Group(Suppress(lb) - name - Suppress(rb) - Group(Optional(Keyword('ID') + assign + word)) - Group(Keyword('Len') + assign + positive_integer) + Group(Optional(Keyword('Mux') + assign + word + positive_integer + comma + positive_integer + positive_integer)) + Group(Optional(Keyword('CycleTime') + assign + positive_integer)) + Group(Optional(Keyword('Timeout') + assign + positive_integer)) + Group(Optional(Keyword('MinInterval') + assign + positive_integer)) + Group(ZeroOrMore(Group(Keyword('Sig') + assign + name + positive_integer)))) enums = Group(Keyword('{ENUMS}') + Group(ZeroOrMore(enum))) signals = Group(Keyword('{SIGNALS}') + Group(ZeroOrMore(signal))) send = Group(Keyword('{SEND}') + Group(ZeroOrMore(symbol))) receive = Group(Keyword('{RECEIVE}') + Group(ZeroOrMore(symbol))) sendreceive = Group(Keyword('{SENDRECEIVE}') + Group(ZeroOrMore(symbol))) section = (enums | signals | send | receive | sendreceive) grammar = (version - title + Group(OneOrMore(section)) + StringEnd()) grammar.ignore(dblSlashComment) return grammar def _get_section_tokens(tokens, name): for section in tokens[2]: if section[0] == name: return section[1] def _load_enums(tokens): section = _get_section_tokens(tokens, '{ENUMS}') enums = {} for name, values in section: enums[name] = OrderedDict( (num(v[0]), v[1]) for v in values) return enums def _load_signal(tokens, enums): # Default values. name = tokens[0] is_signed = False is_float = False byte_order = 'big_endian' offset = 0 factor = 1 unit = None minimum = None maximum = None enum = None length = 0 # Type and length. type_ = tokens[1] if type_ in 'signed': is_signed = True length = int(tokens[2][0]) elif type_ == 'unsigned': length = int(tokens[2][0]) elif type_ == 'float': is_float = True length = 32 elif type_ == 'double': is_float = True length = 64 else: LOGGER.debug("Ignoring unsupported type '%s'.", type_) # Byte order. try: if tokens[3][0] == '-m': byte_order = 'little_endian' except IndexError: pass # The rest. for key, value in tokens[4]: if key == '/u:': unit = value elif key == '/f:': factor = num(value) elif key == '/o:': offset = num(value) elif key == '/min:': minimum = num(value) elif key == '/max:': maximum = num(value) elif key == '/e:': enum = enums[value] else: LOGGER.debug("Ignoring unsupported message attribute '%s'.", key) return Signal(name=name, start=offset, length=length, nodes=[], byte_order=byte_order, is_signed=is_signed, scale=factor, offset=offset, minimum=minimum, maximum=maximum, unit=unit, choices=enum, is_multiplexer=False, is_float=is_float) def _load_signals(tokens, enums): section = _get_section_tokens(tokens, '{SIGNALS}') signals = {} for signal in section: signal = _load_signal(signal, enums) signals[signal.name] = signal return signals def _load_message_signal(tokens, signals, multiplexer_signal, multiplexer_ids): signal = signals[tokens[1]] return Signal(name=signal.name, start=int(tokens[2]), length=signal.length, nodes=signal.nodes, byte_order=signal.byte_order, is_signed=signal.is_signed, scale=signal.scale, offset=signal.offset, minimum=signal.minimum, maximum=signal.maximum, unit=signal.unit, choices=signal.choices, comment=signal.comment, is_multiplexer=signal.is_multiplexer, multiplexer_ids=multiplexer_ids, multiplexer_signal=multiplexer_signal, is_float=signal.is_float) def _load_message_signals_inner(message_tokens, signals, multiplexer_signal=None, multiplexer_ids=None): return [ _load_message_signal(signal, signals, multiplexer_signal, multiplexer_ids) for signal in message_tokens[7] ] def _load_muxed_message_signals(message_tokens, message_section_tokens, signals): mux_tokens = message_tokens[3] multiplexer_signal = mux_tokens[1] result = [ Signal(name=multiplexer_signal, start=int(mux_tokens[2]), length=int(mux_tokens[3]), byte_order='big_endian', is_multiplexer=True) ] multiplexer_ids = [int(mux_tokens[4])] result += _load_message_signals_inner(message_tokens, signals, multiplexer_signal, multiplexer_ids) for tokens in message_section_tokens: if tokens[0] == message_tokens[0] and tokens != message_tokens: multiplexer_ids = [int(tokens[3][4])] result += _load_message_signals_inner(tokens, signals, multiplexer_signal, multiplexer_ids) return result def _is_multiplexed(message_tokens): return len(message_tokens[3]) > 0 def _load_message_signals(message_tokens, message_section_tokens, signals): if _is_multiplexed(message_tokens): return _load_muxed_message_signals(message_tokens, message_section_tokens, signals) else: return _load_message_signals_inner(message_tokens, signals) def _load_message(frame_id, is_extended_frame, message_tokens, message_section_tokens, signals): # Default values. name = message_tokens[0] length = int(message_tokens[2][1]) cycle_time = None # Cycle time. try: cycle_time = num(message_tokens[4][1]) except IndexError: pass return Message(frame_id=frame_id, is_extended_frame=is_extended_frame, name=name, length=length, nodes=[], send_type=None, cycle_time=cycle_time, signals=_load_message_signals(message_tokens, message_section_tokens, signals), comment=None, bus_name=None) def _parse_message_frame_ids(message): def to_int(string): return int(string[:-1], 16) def is_extended_frame(string): return len(string) == 9 if '-' in message[1][1]: minimum, maximum = message[1][1].split('-') else: minimum = maximum = message[1][1] frame_ids = range(to_int(minimum), to_int(maximum) + 1) return frame_ids, is_extended_frame(minimum) def _load_message_section(section_name, tokens, signals): def has_frame_id(message): return len(message[1]) > 0 message_section_tokens = _get_section_tokens(tokens, section_name) messages = [] for message_tokens in message_section_tokens: if not has_frame_id(message_tokens): continue frame_ids, is_extended_frame = _parse_message_frame_ids(message_tokens) for frame_id in frame_ids: message = _load_message(frame_id, is_extended_frame, message_tokens, message_section_tokens, signals) messages.append(message) return messages def _load_messages(tokens, signals): messages = _load_message_section('{SEND}', tokens, signals) messages += _load_message_section('{RECEIVE}', tokens, signals) messages += _load_message_section('{SENDRECEIVE}', tokens, signals) return messages def _load_version(tokens): return tokens[0][1] def load_string(string): """Parse given string. """ if not string.startswith('FormatVersion=6.0'): raise ParseError('Only SYM version 6.0 is supported.') grammar = _create_grammar_6_0() try: tokens = grammar.parseString(string) except (ParseException, ParseSyntaxException) as e: raise ParseError( "Invalid SYM syntax at line {}, column {}: '{}': {}.".format( e.lineno, e.column, e.markInputline(), e.msg)) version = _load_version(tokens) enums = _load_enums(tokens) signals = _load_signals(tokens, enums) messages = _load_messages(tokens, signals) return InternalDatabase(messages, [], [], version, [], [])
ff94c4fe9772efb3f93861e6eced73496ca45bfe
f3eb45a23b421ed8b160a6cf7c8670efb7e9ff4f
/4_digits_of_pi/3_dask_multicore_digits_of_pi.py
a30c429c179e07f93e73ecee53aed9a9898800f3
[ "MIT" ]
permissive
zonca/intro_hpc
4197a49a3a3b2f8cfbe1cfb9d30e9d7f5100c8ac
b0ee213e95d045abdfbbf82849939a2bb4ea125b
refs/heads/master
2021-01-23T01:41:41.809291
2017-07-22T20:41:53
2017-07-22T21:10:29
92,886,908
2
1
null
null
null
null
UTF-8
Python
false
false
742
py
#!/usr/bin/env python3 import sys import numpy as np import dask.array as da def inside_circle(total_count): x = da.random.uniform(size=total_count, chunks=total_count//48) y = da.random.uniform(size=total_count, chunks=total_count//48) radii_square = x**2 + y**2 count = (radii_square<=1.0).sum().compute() return count def estimate_pi(n_samples): return (4.0 * inside_circle(n_samples) / n_samples) if __name__=='__main__': n_samples = 10000 if len(sys.argv) > 1: n_samples = int(sys.argv[1]) my_pi = estimate_pi(n_samples) sizeof = np.dtype(np.float64).itemsize print("pi is {} from {} samples".format(my_pi,n_samples)) print("error is {:.3e}".format(abs(my_pi - np.pi)))
9c90fde14be791e32a374c0dd2d82fad92ea21ef
27eec9c18320fbc20b0fbec628447a3442facc12
/CNN_ConvLSTM/utils/convlstm.py
f03883c2e05d74cdfccb1069d5bc90d47ba8268c
[ "MIT" ]
permissive
peternara/ResNet_ConvLSTM
06428a400f8e93209d4b81f1a6d2b55a58bdb79a
1e2c239af6854d122f138f109d4c1de82930ce43
refs/heads/main
2023-05-09T12:43:49.965613
2021-06-01T02:49:02
2021-06-01T02:49:02
null
0
0
null
null
null
null
UTF-8
Python
false
false
6,026
py
import torch.nn as nn from torch.autograd import Variable import torch class ConvLSTMCell(nn.Module): def __init__(self, input_size, input_dim, hidden_dim, kernel_size, bias): """ Initialize ConvLSTM cell. Parameters ---------- input_size: (int, int) Height and width of input tensor as (height, width). input_dim: int Number of channels of input tensor. hidden_dim: int Number of channels of hidden state. kernel_size: (int, int) Size of the convolutional kernel. bias: bool Whether or not to add the bias. """ super(ConvLSTMCell, self).__init__() self.height, self.width = input_size self.input_dim = input_dim self.hidden_dim = hidden_dim self.kernel_size = kernel_size self.padding = kernel_size[0] // 2, kernel_size[1] // 2 self.bias = bias self.conv = nn.Conv2d(in_channels=self.input_dim + self.hidden_dim, out_channels=4 * self.hidden_dim, #输出为4*hidden_dim,后面拆成四个部分 kernel_size=self.kernel_size, padding=self.padding, bias=self.bias) def forward(self, input_tensor, cur_state): h_cur, c_cur = cur_state combined = torch.cat([input_tensor, h_cur], dim=1) # concatenate along channel axis combined_conv = self.conv(combined) # 输入门,遗忘门,输出门,候选记忆细胞 cc_i, cc_f, cc_o, cc_g = torch.split(combined_conv, self.hidden_dim, dim=1) i = torch.sigmoid(cc_i) f = torch.sigmoid(cc_f) o = torch.sigmoid(cc_o) g = torch.tanh(cc_g) c_next = f * c_cur + i * g h_next = o * torch.tanh(c_next) return h_next, c_next def init_hidden(self, batch_size): return (Variable(torch.zeros(batch_size, self.hidden_dim, self.height, self.width)).cuda(), Variable(torch.zeros(batch_size, self.hidden_dim, self.height, self.width)).cuda()) class ConvLSTM(nn.Module): def __init__(self, input_size, input_dim, hidden_dim, kernel_size, num_layers, batch_first=False, bias=True, return_all_layers=False): super(ConvLSTM, self).__init__() self._check_kernel_size_consistency(kernel_size) # Make sure that both `kernel_size` and `hidden_dim` are lists having len == num_layers kernel_size = self._extend_for_multilayer(kernel_size, num_layers) hidden_dim = self._extend_for_multilayer(hidden_dim, num_layers) if not len(kernel_size) == len(hidden_dim) == num_layers: raise ValueError('Inconsistent list length.') self.height, self.width = input_size self.input_dim = input_dim self.hidden_dim = hidden_dim self.kernel_size = kernel_size self.num_layers = num_layers self.batch_first = batch_first self.bias = bias self.return_all_layers = return_all_layers cell_list = [] for i in range(0, self.num_layers): cur_input_dim = self.input_dim if i == 0 else self.hidden_dim[i-1] cell_list.append(ConvLSTMCell(input_size=(self.height, self.width), input_dim=cur_input_dim, hidden_dim=self.hidden_dim[i], kernel_size=self.kernel_size[i], bias=self.bias)) self.cell_list = nn.ModuleList(cell_list) def forward(self, input_tensor, hidden_state=None): """ Parameters ---------- input_tensor: todo 5-D Tensor either of shape (t, b, c, h, w) or (b, t, c, h, w) hidden_state: todo None. todo implement stateful Returns ------- last_state_list, layer_output """ if not self.batch_first: # (t, b, c, h, w) -> (b, t, c, h, w) input_tensor = input_tensor.permute(1, 0, 2, 3, 4) # Implement stateful ConvLSTM if hidden_state is not None: raise NotImplementedError() else: hidden_state = self._init_hidden(batch_size=input_tensor.size(0)) layer_output_list = [] last_state_list = [] seq_len = input_tensor.size(1) cur_layer_input = input_tensor for layer_idx in range(self.num_layers): # 层数 h, c = hidden_state[layer_idx] output_inner = [] for t in range(seq_len): # 序列长度 h, c = self.cell_list[layer_idx](input_tensor=cur_layer_input[:, t, :, :, :], cur_state=[h, c]) output_inner.append(h) layer_output = torch.stack(output_inner, dim=1) cur_layer_input = layer_output layer_output_list.append(layer_output) last_state_list.append([h, c]) if not self.return_all_layers: layer_output_list = layer_output_list[-1:] last_state_list = last_state_list[-1:] return layer_output_list, last_state_list def _init_hidden(self, batch_size): init_states = [] for i in range(self.num_layers): init_states.append(self.cell_list[i].init_hidden(batch_size)) return init_states @staticmethod def _check_kernel_size_consistency(kernel_size): if not (isinstance(kernel_size, tuple) or (isinstance(kernel_size, list) and all([isinstance(elem, tuple) for elem in kernel_size]))): raise ValueError('`kernel_size` must be tuple or list of tuples') @staticmethod def _extend_for_multilayer(param, num_layers): if not isinstance(param, list): param = [param] * num_layers return param
07bf52a18c5b362964ad40c919eabdec4a165905
c8d506d822d1ddf338b5edf2b4f1220dd9549b64
/Regex/meta2.py
811fd478ababee66bfc7555f949c7524e47893e0
[]
no_license
zozni/PythonStudy
95e2a433e31de1e339b43c3334f9dc2cc4d15f6b
082a6780947466be4993197ce948c6a42976e750
refs/heads/master
2023-02-18T01:12:54.614803
2021-01-22T10:13:28
2021-01-22T10:13:28
324,503,765
2
0
null
null
null
null
UTF-8
Python
false
false
110
py
# 메타문자 ^ import re print(re.search('^Life', 'Life is too short')) print(re.search('^Life', 'My Life'))
82700d40eab51d34a591596e4a59417b39f75684
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p03393/s165485969.py
2108db1765fd8cb7c870158fd75a81cab596eee9
[]
no_license
Aasthaengg/IBMdataset
7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901
f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8
refs/heads/main
2023-04-22T10:22:44.763102
2021-05-13T17:27:22
2021-05-13T17:27:22
367,112,348
0
0
null
null
null
null
UTF-8
Python
false
false
1,027
py
import re import sys import math import itertools import bisect from copy import copy from collections import deque,Counter from decimal import Decimal import functools def v(): return input() def k(): return int(input()) def S(): return input().split() def I(): return map(int,input().split()) def X(): return list(input()) def L(): return list(input().split()) def l(): return list(map(int,input().split())) def lcm(a,b): return a*b//math.gcd(a,b) sys.setrecursionlimit(10 ** 9) mod = 10**9+7 cnt = 0 ans = 0 inf = float("inf") al = "abcdefghijklmnopqrstuvwxyz" import string s = v() if s == 'zyxwvutsrqponmlkjihgfedcba': print(-1) exit() lis =list(string.ascii_lowercase) nlis = [0]*26 for i in s: t = lis.index(i) nlis[t] += 1 if sum(nlis) != 26: for i in range(26): if nlis[i] == 0: print(s+lis[i]) break else: for i in range(25, -1, -1): for j in lis: if s[i] < j and j not in s[:i]: print(s[:i] + j) exit()
23532656417e4f17a6b726c887f112f46a905d58
ce76b3ef70b885d7c354b6ddb8447d111548e0f1
/right_life.py
a00c57735a1259cdb92912789021f1a768eacd33
[]
no_license
JingkaiTang/github-play
9bdca4115eee94a7b5e4ae9d3d6052514729ff21
51b550425a91a97480714fe9bc63cb5112f6f729
refs/heads/master
2021-01-20T20:18:21.249162
2016-08-19T07:20:12
2016-08-19T07:20:12
60,834,519
0
0
null
null
null
null
UTF-8
Python
false
false
216
py
#! /usr/bin/env python def life_or_little_time(str_arg): hand(str_arg) print('work_bad_part') def hand(str_arg): print(str_arg) if __name__ == '__main__': life_or_little_time('week_and_bad_fact')
02a864677772bde23c7d4bf75b729b9a113adbe6
42240f6bbabcfb7a8e2f0957ab2d3c46c2920fd1
/lib/python/statcode/filetype_config.py
58a15f709ddbf0882bf49841242a61fad5dd2d34
[ "Apache-2.0" ]
permissive
simone-campagna/statcode
164a219c699551b70ee12640f42199b72cc76879
a9f39b666d9670b9916623fde343b9174d563724
refs/heads/master
2021-01-01T06:32:25.734613
2013-09-17T08:12:49
2013-09-17T08:12:49
null
0
0
null
null
null
null
UTF-8
Python
false
false
984
py
#!/usr/bin/env python3 # # Copyright 2013 Simone Campagna # # 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. # __author__ = 'Simone Campagna' from .config import Config class FileTypeConfig(Config): DEFAULT_CATEGORY = '{no-category}' __defaults__ = { 'binary': 'False', 'category': DEFAULT_CATEGORY, 'file_extensions': '', 'file_patterns': '', 'interpreter_patterns': '', 'keywords': '', 'regular_expressions': '', }
e71765761571691b4c463f3710a44d6329846b82
2031771d8c226806a0b35c3579af990dd0747e64
/pyobjc-framework-Intents/PyObjCTest/test_inpersonhandlelabel.py
ad84f5b6277cb2d3c6b8928edf94837316b6d5fe
[ "MIT" ]
permissive
GreatFruitOmsk/pyobjc-mirror
a146b5363a5e39181f09761087fd854127c07c86
4f4cf0e4416ea67240633077e5665f5ed9724140
refs/heads/master
2018-12-22T12:38:52.382389
2018-11-12T09:54:18
2018-11-12T09:54:18
109,211,701
2
0
null
null
null
null
UTF-8
Python
false
false
943
py
import sys from PyObjCTools.TestSupport import * if sys.maxsize > 2 ** 32: import Intents class TestINPersonHandleLabel (TestCase): @min_os_level('10.12') def testConstants(self): self.assertIsInstance(Intents.INPersonHandleLabelHome, unicode) self.assertIsInstance(Intents.INPersonHandleLabelWork, unicode) self.assertIsInstance(Intents.INPersonHandleLabeliPhone, unicode) self.assertIsInstance(Intents.INPersonHandleLabelMobile, unicode) self.assertIsInstance(Intents.INPersonHandleLabelMain, unicode) self.assertIsInstance(Intents.INPersonHandleLabelHomeFax, unicode) self.assertIsInstance(Intents.INPersonHandleLabelWorkFax , unicode) self.assertIsInstance(Intents.INPersonHandleLabelPager, unicode) self.assertIsInstance(Intents.INPersonHandleLabelOther, unicode) if __name__ == "__main__": main()
4750432b226683768a660d9a7566173f603adfbd
0f4cacd40260137d3d0b3d1b34be58ac76fc8bd0
/2016/advent24.my.py
df8a2c52a1d331b2427d0dbb0405963b4335febe
[]
no_license
timrprobocom/advent-of-code
45bc765e6ee84e8d015543b1f2fa3003c830e60e
dc4d8955f71a92f7e9c92a36caeb954c208c50e7
refs/heads/master
2023-01-06T07:19:03.509467
2022-12-27T18:28:30
2022-12-27T18:28:30
161,268,871
0
2
null
null
null
null
UTF-8
Python
false
false
3,570
py
# # Holy shit. # grid = """\ ########### #0.1.....2# #.#######.# #4.......3# ###########""".splitlines() xmax = len(grid[0]) ymax = len(grid) # 0 is at row 18 col 3 # So, as long as there are no decisions, move forward. When we reach a decision point, # push the point on a stack, pick left, continue on. # Stop when : # - no possible choices # - we hit all 8 numbers # - path is longer then the current shortest win # - we reach a visited point with the same collection of items # # Sheesh, one of the numbers is in a dead end, so we can't deny retracing. # I suppose we can stop if we reach a point x with the same collection of items. # Should preprocess to identify possible directions out of each point? N,E,S,W = range(4) deltas = ((-1,0),(0,1),(1,0),(0,-1)) def buildGrid( grid ): dgrid = [] pills = {} for y in range(ymax): row = [] for x in range(xmax): c = grid[y][x] if c == '#': row.append([]) else: # Check N E S W works = [] for dy,dx in deltas: if 0 <= x+dx <= xmax and \ 0 <= y+dy <= ymax and \ grid[y+dy][x+dx] != '#': works.append( (dy,dx) ) row.append( works ) if c != '.': pills[(y,x)] = c dgrid.append( row ) return dgrid, pills dgrid, pills = buildGrid( grid ) decisions = [] stack = [] class State(object): def __init__(self, x0, y0 ): self.x0 = x0 self.y0 = y0 self.came = None self.found = [] self.path = [] self.choices = () def familiar(self): return (self.y0,self.x0,self.found) in self.path def update( self, pair ): self.path.append( (self.y0, self.x0, self.found) ) self.y0 += pair[0] self.x0 += pair[1] def len(self): return len(self.path) def push(self): print "Pushing state" print self.path stack.append( self.__dict__.copy() ) def pop(self): print "Popping state" dct = stack.pop() self.__dict__.update( dct ) print self.path def oneStep( s ): y0, x0 = s.y0, s.x0 print "At ", y0, x0 s.choices = dgrid[y0][x0][:] if (y0,x0) in pills: p = pills[(y0,x0)] if p not in s.found: print "Found ", p s.found += p if len(s.found) == len(pills): print "*** found everything *** length ", s.len() s.pop() return if s.came: print "Came from ", s.came print "Choices are ", s.choices s.choices.remove( s.came ) if len(s.choices) == 0: print "No more choices" s.pop() return if s.familiar(): print "We've been here before." s.pop() return if len(s.choices) == 1: print "Must go ", s.choices[0] s.came = tuple(-k for k in s.choices[0]) s.update( s.choices[0] ) return s.push() pick = s.choices.pop(0) print "First choice ", pick s.came = tuple(-k for k in pick) s.update( pick ) state = State( 1, 1 ); state.push() while 1: oneStep(state) # Remember where we came from # At each step: # Take list of choices # Remove from where we came # If there is only one remaining # Go that way # Otherwise # Remember x, y, treasures, # for each possibility # Try it
2a715ba1c3bd9636d92fbac36798cfaf9786dc35
5dd03f9bd8886f02315c254eb2569e4b6d368849
/src/python/twitter/common/python/eggparser.py
9b5b6bdc1282fe4543ffc44cae5daacea7063937
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ]
permissive
adamsxu/commons
9e1bff8be131f5b802d3aadc9916d5f3a760166c
9fd5a4ab142295692994b012a2a2ef3935d35c0b
refs/heads/master
2021-01-17T23:13:51.478337
2012-03-11T17:30:24
2012-03-11T17:30:24
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,547
py
# ================================================================================================== # Copyright 2011 Twitter, Inc. # -------------------------------------------------------------------------------------------------- # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this work except in compliance with the License. # You may obtain a copy of the License in the LICENSE file, or 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. # ================================================================================================== class EggParserOsModule: """ Abstraction of the os-level functions the egg parser needs, so we can break it in tests. """ @staticmethod def uname(): import os return os.uname() @staticmethod def version_info(): import sys return sys.version_info class EggParser(object): """ Parser of .egg filenames, which come in the following format: name ["-" version ["-py" pyver ["-" required_platform]]] "." ext """ def __init__(self, uname = EggParserOsModule.uname(), version_info = EggParserOsModule.version_info()): self._uname = uname self._version_info = version_info @staticmethod def _get_egg_name(components): return (components[0], components[1:]) @staticmethod def _get_egg_version(components): for k in range(len(components)): if components[k].startswith("py"): return ('-'.join(components[0:k]), components[k:]) if components: return ('-'.join(components), []) else: return (None, []) @staticmethod def _get_egg_py_version(components): if components and components[0].startswith("py"): try: major, minor = components[0][2:].split('.') major, minor = int(major), int(minor) return ((major, minor), components[1:]) except: pass return ((), components) @staticmethod def _get_egg_platform(components): return (tuple(components), []) def parse(self, filename): if not filename: return None if not filename.endswith('.egg'): return None components = filename[0:-len('.egg')].split('-') package_name, components = EggParser._get_egg_name(components) package_version, components = EggParser._get_egg_version(components) package_py_version, components = EggParser._get_egg_py_version(components) package_platform, components = EggParser._get_egg_platform(components) return (package_name, package_version, package_py_version, package_platform) def get_architecture(self): py_version = self._version_info[0:2] platform = self._uname[0].lower() arch = self._uname[-1].lower() if platform == 'darwin': platform = 'macosx' return (platform, arch, py_version) def is_compatible(self, filename): try: _, _, egg_py_version, egg_platform = self.parse(filename) except: return False my_platform, my_arch, my_py_version = self.get_architecture() if egg_py_version and egg_py_version != my_py_version: return False if egg_platform and egg_platform[0] != my_platform: return False # ignore specific architectures until we ever actually care. return True
10ba8b7670ca96c7d6a83e9a4cbb5484f4e95a53
446bd1170475e640e4a50476cd80514b0693ee61
/demo/demo1/demo1/picture/jishe/demo2/Demo3/Demo3/spiders/main.py
04dfd6ea4f4f2efd572b417bf2be0aa4f5725558
[]
no_license
HarperHao/python
f040e1e76a243a3dba2b342029a74a45232c1c8d
4bd807605c0acca57b8eea6444b63d36d758cca9
refs/heads/master
2021-07-20T04:40:37.515221
2020-10-02T08:58:37
2020-10-02T08:58:37
219,732,665
0
0
null
null
null
null
UTF-8
Python
false
false
1,665
py
# from scrapy.cmdline import execute # # execute("scrapy crawl zuowumianji".split()) import numpy as np # LU分解 def LU_Decompose(matrix): rows, columns = np.shape(matrix) if rows != columns: print("所输入的矩阵必须是方阵!") return L = np.eye(rows) U = np.triu(matrix) # 先求出U矩阵(化上三角矩阵) # 求L矩阵(主对角线为1的下三角矩阵) L[:, 0] = matrix[:, 0] / U[0][0] # L的第一列 for k in range(1, columns - 1): # 从第2列到columns-1列 for i in range(k + 1, rows): # 从第3行到第rows行 sum = 0 for j in range(0, k - 1): # (0,0)不行 x = L[i][j] * U[j][k] sum = sum + x L[i][k] = (matrix[i][k] - sum) / U[k][k] return L, U # 解LY=b def solve_equation1(L, b): columns = np.shape(b)[0] y = [] y.append(b[0][0]) # y0=b0 for i in range(1, columns): # 求yi sum = 0 for j in range(i): sum = sum + L[i][j] * y[j] y_ = b[i][0] - sum y.append(y_) return y # 解UX=Y def solve_equation2(U, Y): columns = np.shape(Y)[0] X = [i for i in range(columns)] # 先给X初始化 if U[columns - 1] == 0: X[columns - 1] = Y[columns - 1] / U[columns - 1][columns - 1] # Xcolumns-1=Ycolumns-1/U[columns-1][columns-1] else: X[columns - 1] = 0 matrix = np.array([[2, -1, 1], [4, 1, -1], [1, 1, 1]]) rows, columns = np.shape(matrix) L, U = LU_Decompose(matrix) # b = np.eye(rows) b = np.array([1, 5, 0]).reshape(3, 1) # y = solve_equation1(L, b) print(L, U)
0ca0daaa2b979abd328191a6168d13b742b6e4f8
3637fe729395dac153f7abc3024dcc69e17f4e81
/reference/ucmdb/discovery/LockUtils.py
d37de20386d6bcca8280da0db434a05d758387e4
[]
no_license
madmonkyang/cda-record
daced6846c2456f20dddce7f9720602d1583a02a
c431e809e8d0f82e1bca7e3429dd0245560b5680
refs/heads/master
2023-06-15T08:16:46.230569
2021-07-15T16:27:36
2021-07-15T16:27:36
null
0
0
null
null
null
null
UTF-8
Python
false
false
12,251
py
#coding=utf-8 import sys import re from threading import Event import time import logger import errormessages import inventoryerrorcodes import errorobject from java.lang import System from java.util import Random from java.util import HashMap from com.hp.ucmdb.discovery.library.common import CollectorsParameters ScannerNodeLock = 'SCANNER_EXCLUSIVE_LOCK' ScannerNodeSetLock = 'SCANNER_SET_LOCK' ScannerNodeUnSetLock = 'SCANNER_UNSET_LOCK' ScannerNodeLockedByCallHome = -1 INVENTORY_JOB_TYPE = 0 CALLHOME_JOB_TYPE = 1 LOCK_AGE_PERIOD_HOURS = 24 LOCK_AGE_PERIOD_MINUTES = LOCK_AGE_PERIOD_HOURS * 60 LOCK_AGE_PERIOD_SECONDS = LOCK_AGE_PERIOD_MINUTES * 60 LOCK_AGE_PERIOD_MILLISECONDS = LOCK_AGE_PERIOD_SECONDS * 1000 #LOCK_PATTERN = probe___job___timeinmillis OLD_LOCK_PATTERN_DELIMITER = '___' LOCK_PATTERN_DELIMITER = '\\\\\\___\\\\\\' LOCK_PATTERN = '%s' + LOCK_PATTERN_DELIMITER + '%s' + LOCK_PATTERN_DELIMITER + '%s' + LOCK_PATTERN_DELIMITER + '%s' + LOCK_PATTERN_DELIMITER + '%s' LOCK_RELEASE_RETRIES = 10 class Lock: def __init__(self, probe, jobType, jobId, lockTime, lockExpiration): self.probe = str(probe) self.jobType = jobType self.jobId = str(jobId) self.lockTime = lockTime self.lockExpiration = lockExpiration def isSameLock(self, remoteLock): logger.debug('Comparing locks.') logger.debug('This lock:', self.getLockInfo()) logger.debug('Compared lock:', remoteLock.getLockInfo()) return (self.probe == remoteLock.probe) and (self.jobId == remoteLock.jobId) and (self.jobType == remoteLock.jobType) def isLockExpired(self, compareTime = None): if compareTime is None: compareTime = System.currentTimeMillis() logger.debug('Checking lock expiration. Lock expiration time:', str(self.lockExpiration), ', compare time:', str(compareTime)) return self.lockExpiration < compareTime def getLockInfo(self): return LOCK_PATTERN % (str(self.probe), str(self.jobType), str(self.jobId), str(self.lockTime), str(self.lockExpiration)) def printLockInfo(self): return 'probe ' + self.probe + ', jobType ' + str(self.jobType) + ', jobId' + self.jobId + ', lock time ' + str(self.lockTime) + ', lock expiration ' + str(self.lockExpiration) def extractLock(lockInfoStr): logger.debug('Extracting lock from ', str(lockInfoStr)) lockInfo = lockInfoStr.split(LOCK_PATTERN_DELIMITER) if len(lockInfo) < 5: lockInfo = lockInfoStr.split(OLD_LOCK_PATTERN_DELIMITER) if len(lockInfo) < 5: logger.debug('Invalid lock value, setting lock to be expired') return Lock('EXPIRED_LOCK', INVENTORY_JOB_TYPE, 'EXPIRED_LOCK', long(0), long(0)) else: logger.debug('Found old-fasion lock <pre 10.01 version>') lockProbe = lockInfo[0] lockJobType = lockInfo[1] lockJob = lockInfo[2] lockTime = lockInfo[3] lockExpirationTime = lockInfo[4] return Lock(lockProbe, int(lockJobType), lockJob, long(lockTime), long(lockExpirationTime)) def acquireScannerLock(Framework): client = Framework.getConnectedClient() probe = CollectorsParameters.getValue(CollectorsParameters.KEY_PROBE_MGR_IP) if (probe is None) or (len(str(probe)) == 0): logger.debug('Probe manager ip is not specified in the DiscoveryProbe.properties file, using probe ID') probe = CollectorsParameters.getValue(CollectorsParameters.KEY_COLLECTORS_PROBE_NAME) if (probe is None) or (len(str(probe)) == 0): errorMessage = 'Failed to identify probe name. Lock was not set.' logger.debug(errorMessage) Framework.reportError(errorMessage) Framework.setStepExecutionStatus(WorkflowStepStatus.FATAL_FAILURE) return lockTime = System.currentTimeMillis() lockExpiration = System.currentTimeMillis() + LOCK_AGE_PERIOD_MILLISECONDS jobId = Framework.getDiscoveryJobId() jobType = INVENTORY_JOB_TYPE lock = Lock(probe, jobType, jobId, lockTime, lockExpiration) lockValue = lock.getLockInfo() logger.debug('Trying to lock node with value:', lockValue) existingLock = setNewLockIfExistingLockEmpty(client, lockValue) if (existingLock is None) or (len(existingLock) == 0): # lock was acquired return lockValue else: # found existing lock on remote machine remoteLock = extractLock(existingLock) logger.debug('Node was already locked:', remoteLock.printLockInfo()) if not remoteLock.isLockExpired(): # the lock is more or less fresh if lock.isSameLock(remoteLock): # this is our own lock, just renew it logger.debug('Found lock of same probe/job pair, renewing lock on the node') options = HashMap() options.put(ScannerNodeLock, lockValue) client.setOptionsMap(options) return lockValue # check whether we need to forcefully remove lock, happens in call home based inventory discovery forceAcquire = Framework.getParameter("IsForceLockAcquire") if forceAcquire == 'true': options = HashMap() options.put(ScannerNodeLock, lockValue) client.setOptionsMap(options) return lockValue # if the remote lock was owned by a call home inventory job, we should cancel the current job if remoteLock.jobType == CALLHOME_JOB_TYPE: logger.debug('Remote node was locked by call home inventory job, will cancel the current ' + jobId) return ScannerNodeLockedByCallHome logger.debug('Found valid lock is of different job/probe, will try next time') return None logger.debug('The found lock is already aged, to be removed') if not removeLockOption(Framework): return None # as there can be another probe / job trying to connect to this node, after removing existing lock # we don't set our own lock directly (as it can be removed by another probe/job) but go to sleep for some # time r = Random() waitTime = r.nextInt() % 5 + 1 logger.debug('Going to wait for ' + str(waitTime) + ' seconds before retry to lock') event = Event() event.wait(waitTime) existingLock1 = setNewLockIfExistingLockEmpty(client, lockValue) if (existingLock1 is None) or (len(existingLock1) == 0): # lock was acquired at last!!!! return lockValue # there are other lucky guys return None def releaseScannerLock(Framework): #checking that this destination is the owner of the lock lockValue = acquireScannerLock(Framework) if lockValue and (lockValue != ScannerNodeLockedByCallHome): return removeLockOption(Framework) else: logger.debug('Failed to remove lock as lock was already acquired') return 1 def removeLockOption(Framework): client = Framework.getConnectedClient() logger.debug('Removing lock!!!!') #there is a possibility that during unlock agent options file locked (os lock) by scanner as it is writing here (can be each 10 seconds) #in this case we can fail to release lock. for this purpose we want to retry here several time - kind of workaround for improper behavior i = LOCK_RELEASE_RETRIES lockReleased = client.deleteOption(ScannerNodeLock) while i > 0 and not lockReleased: time.sleep(0.1) logger.debug('Failed to release node lock, going to retry ' + str(i) + ' more times') lockReleased = client.deleteOption(ScannerNodeLock) if not lockReleased: logger.debug('Lock was not released after ' + str(LOCK_RELEASE_RETRIES - i) + ' retries') else: logger.debug('Lock was released after ' + str(LOCK_RELEASE_RETRIES - i) + ' retries') i -= 1 if not lockReleased: Framework.reportError(inventoryerrorcodes.INVENTORY_DISCOVERY_FAILED_DELETEOPTION, [ScannerNodeLock]) else: logger.debug('Lock was released after ' + str(LOCK_RELEASE_RETRIES - i) + ' retries') return lockReleased #This method serves two scenarios: #1. On regular workflow each step checks that lock was not removed as expired by other probe/job #2. On run from particular step tries to aquire lock. def ensureLock(Framework): stepName = Framework.getState().getCurrentStepName() setLock = Framework.getProperty(ScannerNodeSetLock) if setLock is not None: logger.debug('Lock was already acquired for workflow, checking that was not removed for step:', stepName) return checkLock(Framework) else: logger.debug('Lock was not acquired before step ', stepName, ', seems like workflow starts from this step, trying to aquire lock') setNewLock = acquireScannerLock(Framework) if setNewLock is not None and not setNewLock == ScannerNodeLockedByCallHome: logger.debug('Lock was acquired with value:', setNewLock) Framework.setProperty(ScannerNodeSetLock, ScannerNodeSetLock) Framework.setProperty(ScannerNodeLock, setNewLock) return setNewLock def checkLock(Framework): probe = CollectorsParameters.getValue(CollectorsParameters.KEY_PROBE_MGR_IP) if (probe is None) or (len(str(probe)) == 0): logger.debug('Probe manager ip is not specified in the DiscoveryProbe.properties file, using probe ID') probe = CollectorsParameters.getValue(CollectorsParameters.KEY_COLLECTORS_PROBE_NAME) jobType = INVENTORY_JOB_TYPE jobId = Framework.getDiscoveryJobId() lockTime = System.currentTimeMillis() lockExpiration = System.currentTimeMillis() + LOCK_AGE_PERIOD_MILLISECONDS lock = Lock(probe, jobType, jobId, lockTime, lockExpiration) logger.debug('Checking remote lock with current lock:', str(lock.getLockInfo())) triggerid = Framework.getTriggerCIData('id') logger.debug('Checking lock for probe ', probe, ' and jobid ', jobId, ' and triggerid ', triggerid) client = Framework.getConnectedClient() options = getClientOptionsMap(client) lockOption = options.get(ScannerNodeLock) if (lockOption is None) or (len(lockOption.strip()) == 0): logger.debug('Lock on scanner node for probe "' + lock.probe + '" and job "' + lock.jobId + '" is not exists') return 0 remoteLock = extractLock(lockOption) logger.debug('Found remote lock:', str(remoteLock.getLockInfo())) if remoteLock.isLockExpired(): logger.debug('Lock on remote node is already expired, renewing lock on the node') options = HashMap() options.put(ScannerNodeLock, lock.getLockInfo()) client.setOptionsMap(options) elif not lock.isSameLock(remoteLock): logger.debug( 'Lock on remote node is owned by another probe/job (' + remoteLock.probe + '/' + remoteLock.jobId + ')') if remoteLock.jobType == CALLHOME_JOB_TYPE: return ScannerNodeLockedByCallHome return 0 return 1 def setNewLockIfExistingLockEmpty(client, newLock): existingLock = _getScannerLockValue(client) if not existingLock: options = HashMap() options.put(ScannerNodeLock, newLock) logger.debug("Set new lock:", newLock) client.setOptionsMap(options) # double confirm the lock is mine lockAfterLocked = _getScannerLockValue(client) if lockAfterLocked != newLock: logger.debug('The current lock was not the lock just created.') return lockAfterLocked # the lock doesn't not belong to me return existingLock def _getScannerLockValue(client): options = getClientOptionsMap(client) if options: return options.get(ScannerNodeLock) def getClientOptionsMap(client): try: options = client.getOptionsMap() except: options = HashMap() return options
be0a4b0ae23f12893b303e8bc4cb504c7f517d0f
d0f11aa36b8c594a09aa06ff15080d508e2f294c
/leecode/1-500/1-100/39-组合总和.py
751f2a332ffc2b86704c60a28303c9b7f6961e04
[]
no_license
saycmily/vtk-and-python
153c1fe9953fce685903f938e174d3719eada0f5
5045d7c44a5af5c16df5a3b72c157e9a2928a563
refs/heads/master
2023-01-28T14:02:59.970115
2021-04-28T09:03:32
2021-04-28T09:03:32
161,468,316
1
1
null
2023-01-12T05:59:39
2018-12-12T10:00:08
Python
UTF-8
Python
false
false
572
py
class Solution: def combinationSum(self, candidates, target: int): candidates.sort() n = len(candidates) res = [] def backtrack(tmp, tmp_sum=0, first=0): if tmp_sum == target: res.append(tmp.copy()) return for j in range(first, n): if tmp_sum + candidates[j] > target: break tmp.append(candidates[j]) backtrack(tmp, tmp_sum + candidates[j], j) tmp.pop() backtrack([]) return res
eb64e5d68a519e53d4e37ab1f2670f115f660766
f02b21d5072cb66af643a7070cf0df4401229d6e
/leetcode/depth_first_search/695-max_area_of_island.py
939a2da8c3ed73d926cf1e1b3a4173e9f7dc2bbb
[]
no_license
dbconfession78/interview_prep
af75699f191d47be1239d7f842456c68c92b95db
7f9572fc6e72bcd3ef1a22b08db099e1d21a1943
refs/heads/master
2018-10-09T22:03:55.283172
2018-06-23T01:18:00
2018-06-23T01:18:00
110,733,251
2
1
null
null
null
null
UTF-8
Python
false
false
3,673
py
import sys class Solution: # def maxAreaOfIsland_PRACTICE(self, grid): def maxAreaOfIsland(self, grid): retval = 0 for i in range(len(grid)): for j in range(len(grid[i])): if grid[i][j] == 1: retval = max(retval, self.helper(grid, i, j, 0)) return retval def helper(self, grid, i, j, area): if i < 0 or j < 0 or i > len(grid) - 1 or j > len(grid[i]) - 1 or grid[i][j] == 0: return area grid[i][j] = 0 area += 1 area = self.helper(grid, i, j + 1, area) area = self.helper(grid, i + 1, j, area) area = self.helper(grid, i, j - 1, area) area = self.helper(grid, i - 1, j, area) return area def maxAreaOfIsland_PASSED(self, grid): # def maxAreaOfIsland(self, grid): """ :type grid: List[List[int]] :rtype: int """ big = 0 i = j = 0 while i < len(grid): j = 0 while j < len(grid[i]): if grid[i][j] == 1: big = max(big, self.explore(grid, i, j)) j += 1 i += 1 return big def explore(self, grid, i, j): if i < 0 or i > len(grid) - 1 or j < 0 or j > len(grid[i]) - 1 or grid[i][j] == 0: return 0 grid[i][j] = 0 count = 1 count += self.explore(grid, i, j + 1) count += self.explore(grid, i, j - 1) count += self.explore(grid, i - 1, j) count += self.explore(grid, i + 1, j) return count def print_map(grid): for row in grid: for cell in row: sys.stdout.write('{} '.format(cell)) print() def main(): # 4 print(Solution().maxAreaOfIsland([ [1,1,0,0,0], [1,1,0,0,0], [0,0,0,1,1], [0,0,0,1,1] ])) # 3 print(Solution().maxAreaOfIsland([ [1, 1, 0, 1, 1], [1, 0, 0, 0, 0], [0, 0, 0, 0, 1], [1, 1, 0, 1, 1] ])) # 1 print(Solution().maxAreaOfIsland(([[1]]))) # 6 print(Solution().maxAreaOfIsland([ [0,0,1,0,0,0,0,1,0,0,0,0,0], [0,0,0,0,0,0,0,1,1,1,0,0,0], [0,1,1,0,1,0,0,0,0,0,0,0,0], [0,1,0,0,1,1,0,0,1,0,1,0,0], [0,1,0,0,1,1,0,0,1,1,1,0,0], [0,0,0,0,0,0,0,0,0,0,1,0,0], [0,0,0,0,0,0,0,1,1,1,0,0,0], [0,0,0,0,0,0,0,1,1,0,0,0,0]])) # LC Input # [[1,1,0,0,0],[1,1,0,0,0],[0,0,0,1,1],[0,0,0,1,1]] # [[1,1,0,1,1],[1,0,0,0,0],[0,0,0,0,1],[1,1,0,1,1]] # [[1]] # [[0,0,1,0,0,0,0,1,0,0,0,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,1,1,0,1,0,0,0,0,0,0,0,0],[0,1,0,0,1,1,0,0,1,0,1,0,0],[0,1,0,0,1,1,0,0,1,1,1,0,0],[0,0,0,0,0,0,0,0,0,0,1,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,0,0,0,0,0,0,1,1,0,0,0,0]] if __name__ == '__main__': main() # Instructions """ Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water. Find the maximum area of an island in the given 2D array. (If there is no island, the maximum area is 0.) Example 1: [[0,0,1,0,0,0,0,1,0,0,0,0,0], [0,0,0,0,0,0,0,1,1,1,0,0,0], [0,1,1,0,1,0,0,0,0,0,0,0,0], [0,1,0,0,1,1,0,0,1,0,1,0,0], [0,1,0,0,1,1,0,0,1,1,1,0,0], [0,0,0,0,0,0,0,0,0,0,1,0,0], [0,0,0,0,0,0,0,1,1,1,0,0,0], [0,0,0,0,0,0,0,1,1,0,0,0,0]] Given the above grid, return 6. Note the answer is not 11, because the island must be connected 4-directionally. Example 2: [[0,0,0,0,0,0,0,0]] Given the above grid, return 0. Note: The length of each dimension in the given grid does not exceed 50. """
[ "Hyrenkosa1" ]
Hyrenkosa1
ae09834689a7ed3701d3ef9439f82ccc31caa63b
3e4d78628a66927e2a640ca4f328adcc31e156b9
/deejay/queuer.py
be6d7a434cdd0da2d3e15b533b77f38a4bf36a50
[]
no_license
nijotz/shitstream
360d41a1411dc480dd220790f9513d202a18ee78
7d11171fb35aaf6d778d5bf23046d220939711be
refs/heads/master
2021-01-01T16:19:22.224760
2014-10-16T22:48:17
2014-10-16T22:48:17
23,303,299
5
1
null
null
null
null
UTF-8
Python
false
false
3,892
py
import os import re import pyechonest.config import pyechonest.song import pyechonest.playlist from downloaders.youtube import search as youtube_search from mpd_util import mpd from server import app import settings pyechonest.config.CODEGEN_BINARY_OVERRIDE = settings.dj_codegen_binary pyechonest.config.ECHO_NEST_API_KEY = settings.dj_echonest_api_key logger = app.logger @mpd def queuer(mpdc): while True: try: if should_queue(mpdc=mpdc): logger.info('Should queue, dewin it') queue_shit(mpdc=mpdc) else: logger.info('Should not queue') logger.info('Queuer waiting') mpdc.idle(['playlist', 'player']) except Exception as e: logger.exception(e) logger.error('Queuer failure, starting over') @mpd def should_queue(mpdc): current_song = mpdc.currentsong() if not current_song: return False current_pos = int(current_song.get('pos')) queue = mpdc.playlistinfo() next_songs = filter(lambda x: int(x.get('pos')) >= current_pos, queue) timeleft = reduce(lambda x, y: x + float(y.get('time')), next_songs, 0) timeleft -= float(mpdc.status().get('elapsed', 0)) if timeleft < (60 * 10): return True return False @mpd def prev_songs(mpdc, num=5): "Get the last songs listened to" current_song = mpdc.currentsong() if not current_song: return [] current_pos = int(current_song.get('pos')) queue = mpdc.playlistinfo() queue = filter(lambda x: not x.get('file', '').startswith(settings.dj_bumps_dir), queue) #FIXME: bumps filter needs dry queue_dict = dict([ (int(song.get('pos')), song) for song in queue ]) sample = [] i = current_pos while len(sample) < num and i >= 0: song = queue_dict.get(i) if song: sample.append(song) i -= 1 return sample @mpd def queue_shit(mpdc): prev = prev_songs(mpdc=mpdc) recs = get_recommendations(prev) for song in recs: mpd_songs = mpdc.search('artist', song.artist_name, 'title', song.title) if mpd_songs: mpdc.add(mpd_songs[0].get('file')) continue mpd_songs = mpdc.search('artist', song.artist_name) if mpd_songs: mpdc.add(mpd_songs[0].get('file')) continue url = youtube_search(u'{} {}'.format(song.artist_name, song.title)) if url: from server import add_url #FIXME def log(x): logger.info(x) add_url(url, log) def find_youtube_vide(song): pass def get_recommendations(prev): songs = [] for song in prev: more_songs = identify_song(song) if more_songs: songs.append(more_songs) song_ids = [song.id for song in songs] if not song_ids: logger.info('No previous songs identified') return [] logger.info('Identified {} previous songs'.format(len(song_ids))) result = pyechonest.playlist.static(type='song-radio', song_id=song_ids, results=10) return result[5:] # Does echonest return the five songs I gave it to seed? Looks like.. @mpd def identify_song(song, mpdc): artist = song.get('artist') title = song.get('title') if not (artist or title): return #TODO: try harder results = pyechonest.song.search(artist=artist, title=title) if results: return results[0] logger.warn(u'No results for: {} - {}'.format(artist,title)) # try stripping weird characters from the names artist = re.sub(r'([^\s\w]|_)+', '', artist) title = re.sub(r'([^\s\w]|_)+', '', title) results = pyechonest.song.search(artist=artist, title=title) if results: return results[0] logger.warn(u'No results for: {} - {}'.format(artist,title)) personality = queuer
1223460f79aa83654eb9c6e0e3b50f90b2366482
a364f53dda3a96c59b2b54799907f7d5cde57214
/easy/35-Search Insertion Position.py
6c7c2e089fbf94d023498b845a9645138b07243e
[ "Apache-2.0" ]
permissive
Davidxswang/leetcode
641cc5c10d2a97d5eb0396be0cfc818f371aff52
d554b7f5228f14c646f726ddb91014a612673e06
refs/heads/master
2022-12-24T11:31:48.930229
2020-10-08T06:02:57
2020-10-08T06:02:57
260,053,912
3
0
null
null
null
null
UTF-8
Python
false
false
1,153
py
""" https://leetcode.com/problems/search-insert-position/ Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You may assume no duplicates in the array. Example 1: Input: [1,3,5,6], 5 Output: 2 Example 2: Input: [1,3,5,6], 2 Output: 1 Example 3: Input: [1,3,5,6], 7 Output: 4 Example 4: Input: [1,3,5,6], 0 Output: 0 """ # it is pretty simple, since the array is monotonically increasing, we should check == first # if not, check <, move toward the end if yes # if found a nums[i] > target, it indicates that the target is >num[i-1] and target is < nums[i], return i # if in the end, nothing found, add this target at the end of the original list # time complexity: O(n), space complexity: O(1) class Solution: def searchInsert(self, nums: List[int], target: int) -> int: i = 0 while i < len(nums): if nums[i] == target: return i if nums[i] < target: i += 1 continue if nums[i] > target: return i return len(nums)
d489d3858f96a45be324467e1fcc25a31913bf04
28ad76f4f4cd22de8d2cd1680dbf4fb9beaa4d24
/anacrowdboticscom_ana_dev_402/urls.py
7837c47d56c39afd4e03fa971a31a704b0d186ce
[]
no_license
crowdbotics-users/anacrowdboticscom-ana-dev-402
956d557b11a09883b6253d4c02758587628ecaec
ceaf01839ad07ce7d086009ac48f52f1a682cf05
refs/heads/master
2020-04-06T16:05:26.123052
2018-11-14T20:11:36
2018-11-14T20:11:36
157,605,004
0
0
null
null
null
null
UTF-8
Python
false
false
939
py
"""anacrowdboticscom_ana_dev_402 URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url('', include('home.urls')), url(r'^accounts/', include('allauth.urls')), url(r'^api/v1/', include('home.api.v1.urls')), url(r'^admin/', admin.site.urls), ]
db1b2374c6afaa2d2fe5ed4e597a9e4b87926cd0
238e46a903cf7fac4f83fa8681094bf3c417d22d
/VTK/vtk_7.1.1_x64_Release/lib/python2.7/site-packages/twisted/names/test/test_names.py
d882eefdb044c15cc6b244c74e388d368578da5e
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
baojunli/FastCAE
da1277f90e584084d461590a3699b941d8c4030b
a3f99f6402da564df87fcef30674ce5f44379962
refs/heads/master
2023-02-25T20:25:31.815729
2021-02-01T03:17:33
2021-02-01T03:17:33
268,390,180
1
0
BSD-3-Clause
2020-06-01T00:39:31
2020-06-01T00:39:31
null
UTF-8
Python
false
false
36,147
py
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Test cases for twisted.names. """ import socket, operator, copy from StringIO import StringIO from functools import partial, reduce from twisted.trial import unittest from twisted.internet import reactor, defer, error from twisted.internet.defer import succeed from twisted.names import client, server, common, authority, dns from twisted.names.dns import Message from twisted.names.error import DomainError from twisted.names.client import Resolver from twisted.names.secondary import ( SecondaryAuthorityService, SecondaryAuthority) from twisted.test.proto_helpers import StringTransport, MemoryReactorClock def justPayload(results): return [r.payload for r in results[0]] class NoFileAuthority(authority.FileAuthority): def __init__(self, soa, records): # Yes, skip FileAuthority common.ResolverBase.__init__(self) self.soa, self.records = soa, records soa_record = dns.Record_SOA( mname = 'test-domain.com', rname = 'root.test-domain.com', serial = 100, refresh = 1234, minimum = 7654, expire = 19283784, retry = 15, ttl=1 ) reverse_soa = dns.Record_SOA( mname = '93.84.28.in-addr.arpa', rname = '93.84.28.in-addr.arpa', serial = 120, refresh = 54321, minimum = 382, expire = 11193983, retry = 30, ttl=3 ) my_soa = dns.Record_SOA( mname = 'my-domain.com', rname = 'postmaster.test-domain.com', serial = 130, refresh = 12345, minimum = 1, expire = 999999, retry = 100, ) test_domain_com = NoFileAuthority( soa = ('test-domain.com', soa_record), records = { 'test-domain.com': [ soa_record, dns.Record_A('127.0.0.1'), dns.Record_NS('39.28.189.39'), dns.Record_SPF('v=spf1 mx/30 mx:example.org/30 -all'), dns.Record_SPF('v=spf1 +mx a:\0colo', '.example.com/28 -all not valid'), dns.Record_MX(10, 'host.test-domain.com'), dns.Record_HINFO(os='Linux', cpu='A Fast One, Dontcha know'), dns.Record_CNAME('canonical.name.com'), dns.Record_MB('mailbox.test-domain.com'), dns.Record_MG('mail.group.someplace'), dns.Record_TXT('A First piece of Text', 'a SecoNd piece'), dns.Record_A6(0, 'ABCD::4321', ''), dns.Record_A6(12, '0:0069::0', 'some.network.tld'), dns.Record_A6(8, '0:5634:1294:AFCB:56AC:48EF:34C3:01FF', 'tra.la.la.net'), dns.Record_TXT('Some more text, haha! Yes. \0 Still here?'), dns.Record_MR('mail.redirect.or.whatever'), dns.Record_MINFO(rmailbx='r mail box', emailbx='e mail box'), dns.Record_AFSDB(subtype=1, hostname='afsdb.test-domain.com'), dns.Record_RP(mbox='whatever.i.dunno', txt='some.more.text'), dns.Record_WKS('12.54.78.12', socket.IPPROTO_TCP, '\x12\x01\x16\xfe\xc1\x00\x01'), dns.Record_NAPTR(100, 10, "u", "sip+E2U", "!^.*$!sip:[email protected]!"), dns.Record_AAAA('AF43:5634:1294:AFCB:56AC:48EF:34C3:01FF')], 'http.tcp.test-domain.com': [ dns.Record_SRV(257, 16383, 43690, 'some.other.place.fool') ], 'host.test-domain.com': [ dns.Record_A('123.242.1.5'), dns.Record_A('0.255.0.255'), ], 'host-two.test-domain.com': [ # # Python bug # dns.Record_A('255.255.255.255'), # dns.Record_A('255.255.255.254'), dns.Record_A('0.0.0.0') ], 'cname.test-domain.com': [ dns.Record_CNAME('test-domain.com') ], 'anothertest-domain.com': [ dns.Record_A('1.2.3.4')], } ) reverse_domain = NoFileAuthority( soa = ('93.84.28.in-addr.arpa', reverse_soa), records = { '123.93.84.28.in-addr.arpa': [ dns.Record_PTR('test.host-reverse.lookup.com'), reverse_soa ] } ) my_domain_com = NoFileAuthority( soa = ('my-domain.com', my_soa), records = { 'my-domain.com': [ my_soa, dns.Record_A('1.2.3.4', ttl='1S'), dns.Record_NS('ns1.domain', ttl='2M'), dns.Record_NS('ns2.domain', ttl='3H'), dns.Record_SRV(257, 16383, 43690, 'some.other.place.fool', ttl='4D') ] } ) class ServerDNSTestCase(unittest.TestCase): """ Test cases for DNS server and client. """ def setUp(self): self.factory = server.DNSServerFactory([ test_domain_com, reverse_domain, my_domain_com ], verbose=2) p = dns.DNSDatagramProtocol(self.factory) while 1: listenerTCP = reactor.listenTCP(0, self.factory, interface="127.0.0.1") # It's simpler to do the stop listening with addCleanup, # even though we might not end up using this TCP port in # the test (if the listenUDP below fails). Cleaning up # this TCP port sooner than "cleanup time" would mean # adding more code to keep track of the Deferred returned # by stopListening. self.addCleanup(listenerTCP.stopListening) port = listenerTCP.getHost().port try: listenerUDP = reactor.listenUDP(port, p, interface="127.0.0.1") except error.CannotListenError: pass else: self.addCleanup(listenerUDP.stopListening) break self.listenerTCP = listenerTCP self.listenerUDP = listenerUDP self.resolver = client.Resolver(servers=[('127.0.0.1', port)]) def tearDown(self): """ Clean up any server connections associated with the L{DNSServerFactory} created in L{setUp} """ # It'd be great if DNSServerFactory had a method that # encapsulated this task. At least the necessary data is # available, though. for conn in self.factory.connections[:]: conn.transport.loseConnection() def namesTest(self, querying, expectedRecords): """ Assert that the DNS response C{querying} will eventually fire with contains exactly a certain collection of records. @param querying: A L{Deferred} returned from one of the DNS client I{lookup} methods. @param expectedRecords: A L{list} of L{IRecord} providers which must be in the response or the test will be failed. @return: A L{Deferred} that fires when the assertion has been made. It fires with a success result if the assertion succeeds and with a L{Failure} if it fails. """ def checkResults(response): receivedRecords = justPayload(response) self.assertEqual(set(expectedRecords), set(receivedRecords)) querying.addCallback(checkResults) return querying def testAddressRecord1(self): """Test simple DNS 'A' record queries""" return self.namesTest( self.resolver.lookupAddress('test-domain.com'), [dns.Record_A('127.0.0.1', ttl=19283784)] ) def testAddressRecord2(self): """Test DNS 'A' record queries with multiple answers""" return self.namesTest( self.resolver.lookupAddress('host.test-domain.com'), [dns.Record_A('123.242.1.5', ttl=19283784), dns.Record_A('0.255.0.255', ttl=19283784)] ) def testAddressRecord3(self): """Test DNS 'A' record queries with edge cases""" return self.namesTest( self.resolver.lookupAddress('host-two.test-domain.com'), [dns.Record_A('255.255.255.254', ttl=19283784), dns.Record_A('0.0.0.0', ttl=19283784)] ) def testAuthority(self): """Test DNS 'SOA' record queries""" return self.namesTest( self.resolver.lookupAuthority('test-domain.com'), [soa_record] ) def test_mailExchangeRecord(self): """ The DNS client can issue an MX query and receive a response including an MX record as well as any A record hints. """ return self.namesTest( self.resolver.lookupMailExchange(b"test-domain.com"), [dns.Record_MX(10, b"host.test-domain.com", ttl=19283784), dns.Record_A(b"123.242.1.5", ttl=19283784), dns.Record_A(b"0.255.0.255", ttl=19283784)]) def testNameserver(self): """Test DNS 'NS' record queries""" return self.namesTest( self.resolver.lookupNameservers('test-domain.com'), [dns.Record_NS('39.28.189.39', ttl=19283784)] ) def testHINFO(self): """Test DNS 'HINFO' record queries""" return self.namesTest( self.resolver.lookupHostInfo('test-domain.com'), [dns.Record_HINFO(os='Linux', cpu='A Fast One, Dontcha know', ttl=19283784)] ) def testPTR(self): """Test DNS 'PTR' record queries""" return self.namesTest( self.resolver.lookupPointer('123.93.84.28.in-addr.arpa'), [dns.Record_PTR('test.host-reverse.lookup.com', ttl=11193983)] ) def testCNAME(self): """Test DNS 'CNAME' record queries""" return self.namesTest( self.resolver.lookupCanonicalName('test-domain.com'), [dns.Record_CNAME('canonical.name.com', ttl=19283784)] ) def testMB(self): """Test DNS 'MB' record queries""" return self.namesTest( self.resolver.lookupMailBox('test-domain.com'), [dns.Record_MB('mailbox.test-domain.com', ttl=19283784)] ) def testMG(self): """Test DNS 'MG' record queries""" return self.namesTest( self.resolver.lookupMailGroup('test-domain.com'), [dns.Record_MG('mail.group.someplace', ttl=19283784)] ) def testMR(self): """Test DNS 'MR' record queries""" return self.namesTest( self.resolver.lookupMailRename('test-domain.com'), [dns.Record_MR('mail.redirect.or.whatever', ttl=19283784)] ) def testMINFO(self): """Test DNS 'MINFO' record queries""" return self.namesTest( self.resolver.lookupMailboxInfo('test-domain.com'), [dns.Record_MINFO(rmailbx='r mail box', emailbx='e mail box', ttl=19283784)] ) def testSRV(self): """Test DNS 'SRV' record queries""" return self.namesTest( self.resolver.lookupService('http.tcp.test-domain.com'), [dns.Record_SRV(257, 16383, 43690, 'some.other.place.fool', ttl=19283784)] ) def testAFSDB(self): """Test DNS 'AFSDB' record queries""" return self.namesTest( self.resolver.lookupAFSDatabase('test-domain.com'), [dns.Record_AFSDB(subtype=1, hostname='afsdb.test-domain.com', ttl=19283784)] ) def testRP(self): """Test DNS 'RP' record queries""" return self.namesTest( self.resolver.lookupResponsibility('test-domain.com'), [dns.Record_RP(mbox='whatever.i.dunno', txt='some.more.text', ttl=19283784)] ) def testTXT(self): """Test DNS 'TXT' record queries""" return self.namesTest( self.resolver.lookupText('test-domain.com'), [dns.Record_TXT('A First piece of Text', 'a SecoNd piece', ttl=19283784), dns.Record_TXT('Some more text, haha! Yes. \0 Still here?', ttl=19283784)] ) def test_spf(self): """ L{DNSServerFactory} can serve I{SPF} resource records. """ return self.namesTest( self.resolver.lookupSenderPolicy('test-domain.com'), [dns.Record_SPF('v=spf1 mx/30 mx:example.org/30 -all', ttl=19283784), dns.Record_SPF('v=spf1 +mx a:\0colo', '.example.com/28 -all not valid', ttl=19283784)] ) def testWKS(self): """Test DNS 'WKS' record queries""" return self.namesTest( self.resolver.lookupWellKnownServices('test-domain.com'), [dns.Record_WKS('12.54.78.12', socket.IPPROTO_TCP, '\x12\x01\x16\xfe\xc1\x00\x01', ttl=19283784)] ) def testSomeRecordsWithTTLs(self): result_soa = copy.copy(my_soa) result_soa.ttl = my_soa.expire return self.namesTest( self.resolver.lookupAllRecords('my-domain.com'), [result_soa, dns.Record_A('1.2.3.4', ttl='1S'), dns.Record_NS('ns1.domain', ttl='2M'), dns.Record_NS('ns2.domain', ttl='3H'), dns.Record_SRV(257, 16383, 43690, 'some.other.place.fool', ttl='4D')] ) def testAAAA(self): """Test DNS 'AAAA' record queries (IPv6)""" return self.namesTest( self.resolver.lookupIPV6Address('test-domain.com'), [dns.Record_AAAA('AF43:5634:1294:AFCB:56AC:48EF:34C3:01FF', ttl=19283784)] ) def testA6(self): """Test DNS 'A6' record queries (IPv6)""" return self.namesTest( self.resolver.lookupAddress6('test-domain.com'), [dns.Record_A6(0, 'ABCD::4321', '', ttl=19283784), dns.Record_A6(12, '0:0069::0', 'some.network.tld', ttl=19283784), dns.Record_A6(8, '0:5634:1294:AFCB:56AC:48EF:34C3:01FF', 'tra.la.la.net', ttl=19283784)] ) def test_zoneTransfer(self): """ Test DNS 'AXFR' queries (Zone transfer) """ default_ttl = soa_record.expire results = [copy.copy(r) for r in reduce(operator.add, test_domain_com.records.values())] for r in results: if r.ttl is None: r.ttl = default_ttl return self.namesTest( self.resolver.lookupZone('test-domain.com').addCallback(lambda r: (r[0][:-1],)), results ) def testSimilarZonesDontInterfere(self): """Tests that unrelated zones don't mess with each other.""" return self.namesTest( self.resolver.lookupAddress("anothertest-domain.com"), [dns.Record_A('1.2.3.4', ttl=19283784)] ) def test_NAPTR(self): """ Test DNS 'NAPTR' record queries. """ return self.namesTest( self.resolver.lookupNamingAuthorityPointer('test-domain.com'), [dns.Record_NAPTR(100, 10, "u", "sip+E2U", "!^.*$!sip:[email protected]!", ttl=19283784)]) class HelperTestCase(unittest.TestCase): def testSerialGenerator(self): f = self.mktemp() a = authority.getSerial(f) for i in range(20): b = authority.getSerial(f) self.assertTrue(a < b) a = b class AXFRTest(unittest.TestCase): def setUp(self): self.results = None self.d = defer.Deferred() self.d.addCallback(self._gotResults) self.controller = client.AXFRController('fooby.com', self.d) self.soa = dns.RRHeader(name='fooby.com', type=dns.SOA, cls=dns.IN, ttl=86400, auth=False, payload=dns.Record_SOA(mname='fooby.com', rname='hooj.fooby.com', serial=100, refresh=200, retry=300, expire=400, minimum=500, ttl=600)) self.records = [ self.soa, dns.RRHeader(name='fooby.com', type=dns.NS, cls=dns.IN, ttl=700, auth=False, payload=dns.Record_NS(name='ns.twistedmatrix.com', ttl=700)), dns.RRHeader(name='fooby.com', type=dns.MX, cls=dns.IN, ttl=700, auth=False, payload=dns.Record_MX(preference=10, exchange='mail.mv3d.com', ttl=700)), dns.RRHeader(name='fooby.com', type=dns.A, cls=dns.IN, ttl=700, auth=False, payload=dns.Record_A(address='64.123.27.105', ttl=700)), self.soa ] def _makeMessage(self): # hooray they all have the same message format return dns.Message(id=999, answer=1, opCode=0, recDes=0, recAv=1, auth=1, rCode=0, trunc=0, maxSize=0) def testBindAndTNamesStyle(self): # Bind style = One big single message m = self._makeMessage() m.queries = [dns.Query('fooby.com', dns.AXFR, dns.IN)] m.answers = self.records self.controller.messageReceived(m, None) self.assertEqual(self.results, self.records) def _gotResults(self, result): self.results = result def testDJBStyle(self): # DJB style = message per record records = self.records[:] while records: m = self._makeMessage() m.queries = [] # DJB *doesn't* specify any queries.. hmm.. m.answers = [records.pop(0)] self.controller.messageReceived(m, None) self.assertEqual(self.results, self.records) class ResolvConfHandling(unittest.TestCase): def testMissing(self): resolvConf = self.mktemp() r = client.Resolver(resolv=resolvConf) self.assertEqual(r.dynServers, [('127.0.0.1', 53)]) r._parseCall.cancel() def testEmpty(self): resolvConf = self.mktemp() fObj = file(resolvConf, 'w') fObj.close() r = client.Resolver(resolv=resolvConf) self.assertEqual(r.dynServers, [('127.0.0.1', 53)]) r._parseCall.cancel() class AuthorityTests(unittest.TestCase): """ Tests for the basic response record selection code in L{FileAuthority} (independent of its fileness). """ def test_domainErrorForNameWithCommonSuffix(self): """ L{FileAuthority} lookup methods errback with L{DomainError} if the requested C{name} shares a common suffix with its zone but is not actually a descendant of its zone, in terms of its sequence of DNS name labels. eg www.the-example.com has nothing to do with the zone example.com. """ testDomain = test_domain_com testDomainName = 'nonexistent.prefix-' + testDomain.soa[0] f = self.failureResultOf(testDomain.lookupAddress(testDomainName)) self.assertIsInstance(f.value, DomainError) def test_recordMissing(self): """ If a L{FileAuthority} has a zone which includes an I{NS} record for a particular name and that authority is asked for another record for the same name which does not exist, the I{NS} record is not included in the authority section of the response. """ authority = NoFileAuthority( soa=(str(soa_record.mname), soa_record), records={ str(soa_record.mname): [ soa_record, dns.Record_NS('1.2.3.4'), ]}) d = authority.lookupAddress(str(soa_record.mname)) result = [] d.addCallback(result.append) answer, authority, additional = result[0] self.assertEqual(answer, []) self.assertEqual( authority, [ dns.RRHeader( str(soa_record.mname), soa_record.TYPE, ttl=soa_record.expire, payload=soa_record, auth=True)]) self.assertEqual(additional, []) def _referralTest(self, method): """ Create an authority and make a request against it. Then verify that the result is a referral, including no records in the answers or additional sections, but with an I{NS} record in the authority section. """ subdomain = 'example.' + str(soa_record.mname) nameserver = dns.Record_NS('1.2.3.4') authority = NoFileAuthority( soa=(str(soa_record.mname), soa_record), records={ subdomain: [ nameserver, ]}) d = getattr(authority, method)(subdomain) answer, authority, additional = self.successResultOf(d) self.assertEqual(answer, []) self.assertEqual( authority, [dns.RRHeader( subdomain, dns.NS, ttl=soa_record.expire, payload=nameserver, auth=False)]) self.assertEqual(additional, []) def test_referral(self): """ When an I{NS} record is found for a child zone, it is included in the authority section of the response. It is marked as non-authoritative if the authority is not also authoritative for the child zone (RFC 2181, section 6.1). """ self._referralTest('lookupAddress') def test_allRecordsReferral(self): """ A referral is also generated for a request of type C{ALL_RECORDS}. """ self._referralTest('lookupAllRecords') class AdditionalProcessingTests(unittest.TestCase): """ Tests for L{FileAuthority}'s additional processing for those record types which require it (MX, CNAME, etc). """ _A = dns.Record_A(b"10.0.0.1") _AAAA = dns.Record_AAAA(b"f080::1") def _lookupSomeRecords(self, method, soa, makeRecord, target, addresses): """ Perform a DNS lookup against a L{FileAuthority} configured with records as defined by C{makeRecord} and C{addresses}. @param method: The name of the lookup method to use; for example, C{"lookupNameservers"}. @type method: L{str} @param soa: A L{Record_SOA} for the zone for which the L{FileAuthority} is authoritative. @param makeRecord: A one-argument callable which accepts a name and returns an L{IRecord} provider. L{FileAuthority} is constructed with this record. The L{FileAuthority} is queried for a record of the resulting type with the given name. @param target: The extra name which the record returned by C{makeRecord} will be pointed at; this is the name which might require extra processing by the server so that all the available, useful information is returned. For example, this is the target of a CNAME record or the mail exchange host pointed to by an MX record. @type target: L{bytes} @param addresses: A L{list} of records giving addresses of C{target}. @return: A L{Deferred} that fires with the result of the resolver method give by C{method}. """ authority = NoFileAuthority( soa=(soa.mname.name, soa), records={ soa.mname.name: [makeRecord(target)], target: addresses, }, ) return getattr(authority, method)(soa_record.mname.name) def assertRecordsMatch(self, expected, computed): """ Assert that the L{RRHeader} instances given by C{expected} and C{computed} carry all the same information but without requiring the records appear in the same order. @param expected: A L{list} of L{RRHeader} instances giving the expected records. @param computed: A L{list} of L{RRHeader} instances giving the records computed by the scenario under test. @raise self.failureException: If the two collections of records disagree. """ # RRHeader instances aren't inherently ordered. Impose an ordering # that's good enough for the purposes of these tests - in which we # never have more than one record of a particular type. key = lambda rr: rr.type self.assertEqual(sorted(expected, key=key), sorted(computed, key=key)) def _additionalTest(self, method, makeRecord, addresses): """ Verify that certain address records are included in the I{additional} section of a response generated by L{FileAuthority}. @param method: See L{_lookupSomeRecords} @param makeRecord: See L{_lookupSomeRecords} @param addresses: A L{list} of L{IRecord} providers which the I{additional} section of the response is required to match (ignoring order). @raise self.failureException: If the I{additional} section of the response consists of different records than those given by C{addresses}. """ target = b"mail." + soa_record.mname.name d = self._lookupSomeRecords( method, soa_record, makeRecord, target, addresses) answer, authority, additional = self.successResultOf(d) self.assertRecordsMatch( [dns.RRHeader( target, address.TYPE, ttl=soa_record.expire, payload=address, auth=True) for address in addresses], additional) def _additionalMXTest(self, addresses): """ Verify that a response to an MX query has certain records in the I{additional} section. @param addresses: See C{_additionalTest} """ self._additionalTest( "lookupMailExchange", partial(dns.Record_MX, 10), addresses) def test_mailExchangeAdditionalA(self): """ If the name of the MX response has A records, they are included in the additional section of the response. """ self._additionalMXTest([self._A]) def test_mailExchangeAdditionalAAAA(self): """ If the name of the MX response has AAAA records, they are included in the additional section of the response. """ self._additionalMXTest([self._AAAA]) def test_mailExchangeAdditionalBoth(self): """ If the name of the MX response has both A and AAAA records, they are all included in the additional section of the response. """ self._additionalMXTest([self._A, self._AAAA]) def _additionalNSTest(self, addresses): """ Verify that a response to an NS query has certain records in the I{additional} section. @param addresses: See C{_additionalTest} """ self._additionalTest( "lookupNameservers", dns.Record_NS, addresses) def test_nameserverAdditionalA(self): """ If the name of the NS response has A records, they are included in the additional section of the response. """ self._additionalNSTest([self._A]) def test_nameserverAdditionalAAAA(self): """ If the name of the NS response has AAAA records, they are included in the additional section of the response. """ self._additionalNSTest([self._AAAA]) def test_nameserverAdditionalBoth(self): """ If the name of the NS response has both A and AAAA records, they are all included in the additional section of the response. """ self._additionalNSTest([self._A, self._AAAA]) def _answerCNAMETest(self, addresses): """ Verify that a response to a CNAME query has certain records in the I{answer} section. @param addresses: See C{_additionalTest} """ target = b"www." + soa_record.mname.name d = self._lookupSomeRecords( "lookupCanonicalName", soa_record, dns.Record_CNAME, target, addresses) answer, authority, additional = self.successResultOf(d) alias = dns.RRHeader( soa_record.mname.name, dns.CNAME, ttl=soa_record.expire, payload=dns.Record_CNAME(target), auth=True) self.assertRecordsMatch( [dns.RRHeader( target, address.TYPE, ttl=soa_record.expire, payload=address, auth=True) for address in addresses] + [alias], answer) def test_canonicalNameAnswerA(self): """ If the name of the CNAME response has A records, they are included in the answer section of the response. """ self._answerCNAMETest([self._A]) def test_canonicalNameAnswerAAAA(self): """ If the name of the CNAME response has AAAA records, they are included in the answer section of the response. """ self._answerCNAMETest([self._AAAA]) def test_canonicalNameAnswerBoth(self): """ If the name of the CNAME response has both A and AAAA records, they are all included in the answer section of the response. """ self._answerCNAMETest([self._A, self._AAAA]) class NoInitialResponseTestCase(unittest.TestCase): def test_no_answer(self): """ If a request returns a L{dns.NS} response, but we can't connect to the given server, the request fails with the error returned at connection. """ def query(self, *args): # Pop from the message list, so that it blows up if more queries # are run than expected. return succeed(messages.pop(0)) def queryProtocol(self, *args, **kwargs): return defer.fail(socket.gaierror("Couldn't connect")) resolver = Resolver(servers=[('0.0.0.0', 0)]) resolver._query = query messages = [] # Let's patch dns.DNSDatagramProtocol.query, as there is no easy way to # customize it. self.patch(dns.DNSDatagramProtocol, "query", queryProtocol) records = [ dns.RRHeader(name='fooba.com', type=dns.NS, cls=dns.IN, ttl=700, auth=False, payload=dns.Record_NS(name='ns.twistedmatrix.com', ttl=700))] m = dns.Message(id=999, answer=1, opCode=0, recDes=0, recAv=1, auth=1, rCode=0, trunc=0, maxSize=0) m.answers = records messages.append(m) return self.assertFailure( resolver.getHostByName("fooby.com"), socket.gaierror) class SecondaryAuthorityServiceTests(unittest.TestCase): """ Tests for L{SecondaryAuthorityService}, a service which keeps one or more authorities up to date by doing zone transfers from a master. """ def test_constructAuthorityFromHost(self): """ L{SecondaryAuthorityService} can be constructed with a C{str} giving a master server address and several domains, causing the creation of a secondary authority for each domain and that master server address and the default DNS port. """ primary = '192.168.1.2' service = SecondaryAuthorityService( primary, ['example.com', 'example.org']) self.assertEqual(service.primary, primary) self.assertEqual(service._port, 53) self.assertEqual(service.domains[0].primary, primary) self.assertEqual(service.domains[0]._port, 53) self.assertEqual(service.domains[0].domain, 'example.com') self.assertEqual(service.domains[1].primary, primary) self.assertEqual(service.domains[1]._port, 53) self.assertEqual(service.domains[1].domain, 'example.org') def test_constructAuthorityFromHostAndPort(self): """ L{SecondaryAuthorityService.fromServerAddressAndDomains} constructs a new L{SecondaryAuthorityService} from a C{str} giving a master server address and DNS port and several domains, causing the creation of a secondary authority for each domain and that master server address and the given DNS port. """ primary = '192.168.1.3' port = 5335 service = SecondaryAuthorityService.fromServerAddressAndDomains( (primary, port), ['example.net', 'example.edu']) self.assertEqual(service.primary, primary) self.assertEqual(service._port, 5335) self.assertEqual(service.domains[0].primary, primary) self.assertEqual(service.domains[0]._port, port) self.assertEqual(service.domains[0].domain, 'example.net') self.assertEqual(service.domains[1].primary, primary) self.assertEqual(service.domains[1]._port, port) self.assertEqual(service.domains[1].domain, 'example.edu') class SecondaryAuthorityTests(unittest.TestCase): """ L{twisted.names.secondary.SecondaryAuthority} correctly constructs objects with a specified IP address and optionally specified DNS port. """ def test_defaultPort(self): """ When constructed using L{SecondaryAuthority.__init__}, the default port of 53 is used. """ secondary = SecondaryAuthority('192.168.1.1', 'inside.com') self.assertEqual(secondary.primary, '192.168.1.1') self.assertEqual(secondary._port, 53) self.assertEqual(secondary.domain, 'inside.com') def test_explicitPort(self): """ When constructed using L{SecondaryAuthority.fromServerAddressAndDomain}, the specified port is used. """ secondary = SecondaryAuthority.fromServerAddressAndDomain( ('192.168.1.1', 5353), 'inside.com') self.assertEqual(secondary.primary, '192.168.1.1') self.assertEqual(secondary._port, 5353) self.assertEqual(secondary.domain, 'inside.com') def test_transfer(self): """ An attempt is made to transfer the zone for the domain the L{SecondaryAuthority} was constructed with from the server address it was constructed with when L{SecondaryAuthority.transfer} is called. """ secondary = SecondaryAuthority.fromServerAddressAndDomain( ('192.168.1.2', 1234), 'example.com') secondary._reactor = reactor = MemoryReactorClock() secondary.transfer() # Verify a connection attempt to the server address above host, port, factory, timeout, bindAddress = reactor.tcpClients.pop(0) self.assertEqual(host, '192.168.1.2') self.assertEqual(port, 1234) # See if a zone transfer query is issued. proto = factory.buildProtocol((host, port)) transport = StringTransport() proto.makeConnection(transport) msg = Message() # DNSProtocol.writeMessage length encodes the message by prepending a # 2 byte message length to the buffered value. msg.decode(StringIO(transport.value()[2:])) self.assertEqual( [dns.Query('example.com', dns.AXFR, dns.IN)], msg.queries)
[ "l”[email protected]“" ]
3cc745f34716dfeb254720f8c0c01a80b7c5d438
67ca269e39935d0c439329c3a63df859e40168bb
/autoPyTorch/pipeline/components/setup/lr_scheduler/constants.py
2e5895632deb9caa92b26070d7495d27d57ba970
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-philippe-de-muyter" ]
permissive
automl/Auto-PyTorch
2e67ffb44f40d9993470ded9b63f10a5164b41df
56a2ac1d69c7c61a847c678879a67f5d3672b3e8
refs/heads/master
2023-07-14T22:55:57.826602
2022-08-23T16:43:15
2022-08-23T16:43:15
159,791,040
2,214
280
Apache-2.0
2023-04-04T14:41:15
2018-11-30T08:18:34
Python
UTF-8
Python
false
false
450
py
from enum import Enum class StepIntervalUnit(Enum): """ By which interval we perform the step for learning rate schedulers. Attributes: batch (str): We update every batch evaluation epoch (str): We update every epoch valid (str): We update every validation """ batch = 'batch' epoch = 'epoch' valid = 'valid' StepIntervalUnitChoices = [step_interval.name for step_interval in StepIntervalUnit]
744ef4550ea1381e96181d3d0cf7df33ca8a133d
762de1c66746267e05d53184d7854934616416ee
/tools/MolSurfGenService/MolSurfaceGen32/chimera/share/VolumeData/tom_em/em_format.py
6c027e9831ce8864e76310e1e1193380a04ead29
[]
no_license
project-renard-survey/semanticscience
6e74f5d475cf0ebcd9bb7be6bb9522cf15ed8677
024890dba56c3e82ea2cf8c773965117f8cda339
refs/heads/master
2021-07-07T21:47:17.767414
2017-10-04T12:13:50
2017-10-04T12:13:50
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,434
py
# ----------------------------------------------------------------------------- # Read TOM Toolbox EM density map file (http://www.biochem.mpg.de/tom/) # electron microscope data. # # Byte swapping will be done if needed. # # ----------------------------------------------------------------------------- # class EM_Data: def __init__(self, path): self.path = path import os.path self.name = os.path.basename(path) file = open(path, 'rb') file.seek(0,2) # go to end of file file_size = file.tell() file.seek(0,0) # go to beginning of file # Determine byte order from machine code # OS-9 0 # VAX 1 # Convex 2 # SGI 3 # Sun 4 (not supported) # Mac 5 # PC 6 self.swap_bytes = False from numpy import int8, little_endian machine_code = self.read_values(file, int8, 1) file_little_endian = machine_code in (1, 6) self.swap_bytes = ((file_little_endian and not little_endian) or (not file_little_endian and little_endian)) file.seek(0,0) v = self.read_header_values(file) self.check_header_values(v, file_size) self.data_offset = file.tell() file.close() self.data_size = (v['xsize'], v['ysize'], v['zsize']) dstep = v['pixelsize'] if dstep == 0: dstep = 1.0 self.data_step = (dstep, dstep, dstep) self.data_origin = (0., 0., 0.) # --------------------------------------------------------------------------- # Format derived from C header file mrc.h. # def read_header_values(self, file): from numpy import int8, int32 i8 = int8 i32 = int32 v = {} v['machine code']= self.read_values(file, i8, 1) v['os 9 version']= self.read_values(file, i8, 1) v['abandoned header']= self.read_values(file, i8, 1) v['data type code']= self.read_values(file, i8, 1) v['xsize'], v['ysize'], v['zsize'] = self.read_values(file, i32, 3) v['comment'] = file.read(80) v['user param'] = self.read_values(file, i32, 40) v['pixelsize'] = v['user param'][6] / 1000.0 # nm v['user data'] = file.read(256) return v # --------------------------------------------------------------------------- # def check_header_values(self, v, file_size): mc = v['machine code'] if mc < 0 or mc > 6: raise SyntaxError, ('Bad EM machine code %d at byte 0, must be 0 - 6.' % mc) dc = v['data type code'] if not dc in (1,2,4,5,8,9): raise SyntaxError, ('Bad EM data type code %d' % dc + ', must be 1, 2, 4, 5, 8, or 9') from numpy import uint8, int16, int32, float32, float64 types = { 1: uint8, 2: int16, 4: int32, 5: float32, 9: float64 } if types.has_key(dc): self.element_type = types[dc] else: raise SyntaxError, 'Complex EM data value type not supported' if float(v['xsize']) * float(v['ysize']) * float(v['zsize']) > file_size: raise SyntaxError, ('File size %d too small for grid size (%d,%d,%d)' % (file_size, v['xsize'],v['ysize'],v['zsize'])) # --------------------------------------------------------------------------- # def read_values(self, file, etype, count): from numpy import array esize = array((), etype).itemsize string = file.read(esize * count) values = self.read_values_from_string(string, etype, count) return values # --------------------------------------------------------------------------- # def read_values_from_string(self, string, etype, count): from numpy import fromstring values = fromstring(string, etype) if self.swap_bytes: values = values.byteswap() if count == 1: return values[0] return values # --------------------------------------------------------------------------- # Returns 3D NumPy matrix with zyx index order. # def read_matrix(self, ijk_origin, ijk_size, ijk_step, progress): from VolumeData.readarray import read_array matrix = read_array(self.path, self.data_offset, ijk_origin, ijk_size, ijk_step, self.data_size, self.element_type, self.swap_bytes, progress) return matrix
[ "alex.gawronski@d60594c4-dda9-11dd-87d8-31aa04531ed5" ]
alex.gawronski@d60594c4-dda9-11dd-87d8-31aa04531ed5
778ae380f0cad62eb41f8e8dbe2862993143ee93
495907c7e2e2d591df2d6906335c3d89c5a4a47b
/helpers/logHelpers.py
42129a0969e389b0136e85078c31651d76b26bbb
[]
no_license
ePandda/idigpaleo-ingest
319194125aded01f018cfb7c1fe7044fe8c66770
8473ab31e7a56878236136d0ace285ab3738f208
refs/heads/master
2020-11-26T19:48:13.959972
2018-04-21T17:19:38
2018-04-21T17:19:38
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,086
py
# # Class for logining status/errors from the ingest # # Uses the main pythn logging module import logging import time def createLog(module, level): logger = logging.getLogger(module) if level: checkLevel = level.lower() else: checkLevel = 'warning' levels = {'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARNING, 'error': logging.ERROR, 'critical': logging.CRITICAL} today = time.strftime("%Y_%m_%d") loggerFile = './logs/'+today+"_ingest.log" fileLog = logging.FileHandler(loggerFile) conLog = logging.StreamHandler() if checkLevel in levels: logger.setLevel(levels[checkLevel]) fileLog.setLevel(levels[checkLevel]) conLog.setLevel(levels[checkLevel]) else: fileLog.setLevel(levels['warning']) conLog.setLevel(levels['warning']) formatter = logging.Formatter('%(asctime)s_%(name)s_%(levelname)s: %(message)s') fileLog.setFormatter(formatter) conLog.setFormatter(formatter) logger.addHandler(fileLog) logger.addHandler(conLog) return logger
5b7de37d3e3ae6122a53cb151f264294e1e07cfd
4ec57b6ca1125feb546487ebf736fb1f7f3531ce
/src/bin/huawei_server/collect.py
7e38908b1087dbed5c09a721f9b18ad0fac206cd
[ "MIT" ]
permissive
Huawei/Server_Management_Plugin_Nagios
df595b350ef1cf63347725e443b518c521afde5a
fbfbb852a90b6e1283288111eadbd49af2e79343
refs/heads/master
2022-09-14T15:59:48.438453
2022-08-22T03:19:20
2022-08-22T03:19:20
120,845,298
4
0
null
null
null
null
UTF-8
Python
false
false
3,370
py
#encoding:utf-8 import sys import os import traceback from config import VERSTION_STR from base.logger import Logger from model.plugin import LoggerConfig from service.collectservice import CollectService from util.common import Common from util.check import Check from constant.constant import * from threading import Timer import time def loggerConfig(node, loggerData): elements = Common.getChild(node); if elements is None: return False; for element in elements: if "param" != element.tag: return False; if "level" == element.attrib.get("name"): loggerData.setLoggerLevel(element.text); elif "size" == element.attrib.get("name"): loggerData.setLoggerSize(element.text); elif "index" == element.attrib.get("name"): loggerData.setLoggerIndex(element.text); loggerData.setLoggerPath(Common.getExePath() + os.path.sep + "log"); return True; def pluginConfig(loggerData): if not os.path.exists(Common.getPluginConfigPath()): return False; root = Common.getRoot(Common.getPluginConfigPath()); if root is None: return False; for node in Common.getChild(root): if "config" != node.tag: return False; if "log" == node.attrib.get('name'): loggerConfig(node, loggerData); return True; def initPlugin(): #parse plugin config loggerData = LoggerConfig(); if not pluginConfig(loggerData): return False; logger = Logger.getInstance().init(loggerData); return True; def main(argv=None): if not initPlugin(): return -1; Logger.getInstance().error('========= %s ======='%VERSTION_STR) if(len(argv) < 2): Logger.getInstance().error("main error: param length should not be zero."); return -1; try: if "-p" == argv[1]: if not Check.checkPluginModeParam(argv[2:]): Logger.getInstance().error("main error: param is invalid, param=%s." % sys.argv[1:]); return -1; service = CollectService(COLLECT_MODE_CMD_PLUGIN, None); elif "-a" == argv[1]: if not Check.checkTotalModeParam(argv[2:]): Logger.getInstance().error("main error: param is invalid, param=%s." % sys.argv[1] ); return -1; service = CollectService(COLLECT_MODE_CMD_TOTAL, argv[2:]); elif "-f" == argv[1]: if not Check.checkFileModeParam(argv[2:]): Logger.getInstance().error("main error: param is invalid, param=%s." % sys.argv[1] ); return -1; service = CollectService(COLLECT_MODE_CMD_FILE, argv[2:]); else: Logger.getInstance().error("main error: option param is invalid optoion : [%s]" % (argv[1])); return -1 return service.start(); except Exception, e: Logger.getInstance().exception("main exception: collect device info exception: [%s]" % e); return -1 if __name__ == "__main__": timeInteval = 300 while True: t = Timer(timeInteval ,sys.exit(main(sys.argv)) ) t.start() time.sleep(300)
9d7664af768702a3da5d5567e409f84faf975d8a
4380a4029bac26f205ed925026914dce9e96fff0
/slyr/parser/exceptions.py
d791f4c9f6a447c4501d075e561829ba69832613
[]
no_license
deepVector/slyr
6b327f835994c8f20f0614eb6c772b90aa2d8536
5d532ac3eec0e00c5883bf873d30c6b18a4edf30
refs/heads/master
2020-12-03T10:24:39.660904
2019-04-08T00:48:03
2019-04-08T00:48:03
null
0
0
null
null
null
null
UTF-8
Python
false
false
974
py
#!/usr/bin/env python """ SLYR Exceptions """ class UnsupportedVersionException(Exception): """ Thrown when an object of an unsupported version is encountered """ pass class UnreadableSymbolException(Exception): """ Thrown when a symbol could not be read, for whatever reason """ pass class NotImplementedException(Exception): """ Thrown when attempting to read/convert an object, which is known but not yet implemented """ pass class UnknownGuidException(Exception): """ Thrown on encountering an unknown GUID """ pass class InvalidColorException(Exception): """ Thrown when an error was encountered while converting a color """ pass class UnknownPictureTypeException(Exception): """ Thrown on encountering an unknown picture type """ pass class UnreadablePictureException(Exception): """ Thrown on encountering an unreadable picture """ pass
bbf9c3db561c3a9339d630028112a6794a730e5e
db734d1c2fa1ff072c3bad3efbc80f5fb045647b
/examples/advanced_symmetry.py
5b838beba33fb51eb88a5bfddea66a81e01fb2ff
[ "MIT" ]
permissive
yenchunlin024/PyQchem
ff4a0f9062124c3ef47dba5e7c48b372e4a99c21
2edf984ba17373ad3fd450b18592c8b7827b72e5
refs/heads/master
2023-08-12T09:43:46.942362
2021-09-30T10:59:35
2021-09-30T10:59:35
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,469
py
import numpy as np from pyqchem.symmetry import get_wf_symmetry from pyqchem.utils import _set_zero_to_coefficients, get_plane, crop_electronic_structure from pyqchem.qchem_core import get_output_from_qchem, create_qchem_input from pyqchem.structure import Structure from pyqchem.file_io import build_fchk # Define custom classification function def get_custom_orbital_classification(parsed_fchk, center=None, orientation=(0, 0, 1) ): molsym = get_wf_symmetry(parsed_fchk['structure'], parsed_fchk['basis'], parsed_fchk['coefficients'], center=center, orientation=orientation) sh_index = molsym.SymLab.index('i') # operation used to separate orbitals orbital_type = [] for i, overlap in enumerate(molsym.mo_SOEVs_a[:, sh_index]): overlap = overlap / molsym.mo_SOEVs_a[i, molsym.SymLab.index('E')] # normalize if overlap < 0: orbital_type.append([' NOO', np.abs(overlap)]) else: orbital_type.append([' YES', np.abs(overlap)]) return orbital_type dimer_ethene = [[0.0, 0.0000, 0.65750], [0.0, 0.0000, -0.65750], [0.0, 0.92281, 1.22792], [0.0, -0.92281, 1.22792], [0.0, -0.92281, -1.22792], [0.0, 0.92281, -1.22792], [3.7, 0.00000, 0.65750], [3.7, 0.00000, -0.65750], [3.7, 0.92281, 1.22792], [3.7, -0.92281, 1.22792], [3.7, -0.92281, -1.22792], [3.7, 0.92281, -1.22792]] symbols = ['C', 'C', 'H', 'H', 'H', 'H', 'C', 'C', 'H', 'H', 'H', 'H'] range_f1 = range(0, 6) range_f2 = range(6, 12) # create molecule molecule = Structure(coordinates=dimer_ethene, symbols=symbols, charge=0, multiplicity=1) # create Q-Chem input qc_input = create_qchem_input(molecule, jobtype='sp', exchange='hf', basis='6-31G') print(qc_input.get_txt()) # get data from Q-Chem calculation output, electronic_structure = get_output_from_qchem(qc_input, processors=4, force_recalculation=False, read_fchk=True, fchk_only=True) # store original fchk info in file open('test.fchk', 'w').write(build_fchk(electronic_structure)) # get symmetry classification electronic_structure_f1 = crop_electronic_structure(electronic_structure, range_f1) # save test fchk file with new coefficients open('test_f1.fchk', 'w').write(build_fchk(electronic_structure_f1)) # get plane from coordinates coordinates_f1 = electronic_structure['structure'].get_coordinates(fragment=range_f1) center_f1, normal_f1 = get_plane(coordinates_f1) # get classified orbitals orbital_type_f1 = get_custom_orbital_classification(electronic_structure_f1, center=center_f1, orientation=normal_f1) # get plane from coordinates coordinates_f2 = electronic_structure['structure'].get_coordinates(fragment=range_f2) center_f2, normal_f2 = get_plane(coordinates_f2) electronic_structure_f2 = crop_electronic_structure(electronic_structure, range_f2) # save test fchk file with new coefficients open('test_f2.fchk', 'w').write(build_fchk(electronic_structure_f2)) # get classified orbitals orbital_type_f2 = get_custom_orbital_classification(electronic_structure_f2, center=center_f2, orientation=normal_f2) # range of orbitals to show frontier_orbitals = [12, 13, 14, 15, 16, 17, 18, 19, 20] # Print results in table print('Inversion center?') print('index fragment 1 fragment 2') for i in frontier_orbitals: print(' {:4} {:4} {:4.3f} {:4} {:4.3f}'.format(i, orbital_type_f1[i-1][0], orbital_type_f1[i-1][1], orbital_type_f2[i-1][0], orbital_type_f2[i-1][1]))
cc7027ec8852029b29739182b583c126f29a16cf
4ab57a7bd592d267d180f0541ee18b4c544eec28
/tests/orm/mixins/test_soft_deletes.py
bba8c0e6fcda1c345551add5b8b6bc09638e0e42
[ "MIT" ]
permissive
mattcl/orator
f6cfb687ef8f1c3f5dd9828b2b950edbb5387cc9
cc3d2154d596f7e6ff4274d7f8d6e8a233e12a9c
refs/heads/0.8
2021-01-20T17:27:16.342669
2016-06-02T21:55:00
2016-06-02T21:55:00
66,998,160
0
1
null
2018-02-22T21:29:24
2016-08-31T03:08:13
Python
UTF-8
Python
false
false
1,362
py
# -*- coding: utf-8 -*- import datetime import arrow from flexmock import flexmock, flexmock_teardown from orator import Model, SoftDeletes from orator.orm import Builder from orator.query import QueryBuilder from ... import OratorTestCase t = arrow.get().naive class SoftDeletesTestCase(OratorTestCase): def tearDown(self): flexmock_teardown() def test_delete_sets_soft_deleted_column(self): model = flexmock(SoftDeleteModelStub()) model.set_exists(True) builder = flexmock(Builder) query_builder = flexmock(QueryBuilder(None, None, None)) query = Builder(query_builder) model.should_receive('new_query').and_return(query) builder.should_receive('where').once().with_args('id', 1).and_return(query) builder.should_receive('update').once().with_args({'deleted_at': t}) model.delete() self.assertIsInstance(model.deleted_at, datetime.datetime) def test_restore(self): model = flexmock(SoftDeleteModelStub()) model.set_exists(True) model.should_receive('save').once() model.restore() self.assertIsNone(model.deleted_at) class SoftDeleteModelStub(SoftDeletes, Model): def get_key(self): return 1 def get_key_name(self): return 'id' def from_datetime(self, value): return t
72d8d8ac47ceb9f682800efef9aa102bd121eab5
caa06eca3eef2549d5088f6487201f734b35822e
/NLP-PGN/utils/config_bak.py
538451b3b9977af8e798069ab9f3e4cf5672d3bb
[]
no_license
kelvincjr/shared
f947353d13e27530ba44ea664e27de51db71a5b6
4bc4a12b0ab44c6847a67cbd7639ce3c025f38f8
refs/heads/master
2023-06-23T19:38:14.801083
2022-05-17T09:45:22
2022-05-17T09:45:22
141,774,490
6
1
null
2023-06-12T21:30:07
2018-07-21T02:22:34
Python
UTF-8
Python
false
false
1,767
py
""" @Time : 2021/2/814:06 @Auth : 周俊贤 @File :config.py @DESCRIPTION: """ from typing import Optional import torch # General hidden_size: int = 512 dec_hidden_size: Optional[int] = 512 embed_size: int = 512 pointer = True # Data max_vocab_size = 20000 embed_file: Optional[str] = None # use pre-trained embeddings source = 'big_samples' # use value: train or big_samples data_path: str = './data/data/train.txt' val_data_path = './data/data/dev.txt' test_data_path = './data/data/test.txt' stop_word_file = './data/data/HIT_stop_words.txt' max_src_len: int = 300 # exclusive of special tokens such as EOS max_tgt_len: int = 100 # exclusive of special tokens such as EOS truncate_src: bool = True truncate_tgt: bool = True min_dec_steps: int = 30 max_dec_steps: int = 100 enc_rnn_dropout: float = 0.5 enc_attn: bool = True dec_attn: bool = True dec_in_dropout = 0 dec_rnn_dropout = 0 dec_out_dropout = 0 # Training trunc_norm_init_std = 1e-4 eps = 1e-31 learning_rate = 0.001 lr_decay = 0.0 initial_accumulator_value = 0.1 epochs = 8 batch_size = 8 #16 coverage = False fine_tune = False scheduled_sampling = False weight_tying = False max_grad_norm = 2.0 is_cuda = True DEVICE = torch.device("cuda" if is_cuda else "cpu") LAMBDA = 1 output_dir = "./output" if pointer: if coverage: if fine_tune: model_name = 'ft_pgn' else: model_name = 'cov_pgn' elif scheduled_sampling: model_name = 'ss_pgn' elif weight_tying: model_name = 'wt_pgn' else: if source == 'big_samples': model_name = 'pgn_big_samples' else: model_name = 'pgn' else: model_name = 'baseline' # Beam search beam_size: int = 3 alpha = 0.2 beta = 0.2 gamma = 0.6
01e664b7f39575e1a63a4ddf8b5dfefab7300952
a2e638cd0c124254e67963bda62c21351881ee75
/Python modules/SettlementRegenerate.py
f5f2ad83e3c14991b4f4775c28b52ee0110c5cdb
[]
no_license
webclinic017/fa-absa-py3
1ffa98f2bd72d541166fdaac421d3c84147a4e01
5e7cc7de3495145501ca53deb9efee2233ab7e1c
refs/heads/main
2023-04-19T10:41:21.273030
2021-05-10T08:50:05
2021-05-10T08:50:05
null
0
0
null
null
null
null
UTF-8
Python
false
false
5,110
py
"""---------------------------------------------------------------------------------------------------------- MODULE : SettlementRegenerate PURPOSE : This module will regenerate a settlement. DEPARTMENT AND DESK : IT REQUASTER : Heinrich Cronje DEVELOPER : Heinrich Cronje CR NUMBER : ------------------------------------------------------------------------------------------------------------- HISTORY ============================================================================================================= Date Change no Developer Description ------------------------------------------------------------------------------------------------------------- 2011-08-22 Heinrich Cronje Front Arena Upgrade 2010.2. 2019-07-24 FAU-312 Cuen Edwards Replaced custom regenerate functionality with call to Front Arena command. Added security on menu item. ------------------------------------------------------------------------------------------------------------- """ import acm from at_logging import getLogger import FUxCore LOGGER = getLogger(__name__) def _confirm_regenerate(shell, settlements): """ Prompt the user to confirm regeneration of the currently selected settlements. """ message = "The command Regenerate will be executed on the " if settlements.Size() == 1: message += "selected settlement." elif settlements.Size() > 1: message += "{number} selected settlements.".format( number=settlements.Size() ) message += "\n\nDo you want to continue?" return acm.UX.Dialogs().MessageBoxYesNo(shell, 'Question', message) == 'Button1' def _regenerate(settlements): """ Regenerate the specified settlements. """ failures = {} for settlement in settlements: try: command = acm.FRegeneratePayment(settlement) command.Execute() command.CommitResult() LOGGER.info('Regenerated settlement {oid}.'.format( oid=settlement.Oid() )) except Exception as exception: failures[settlement] = exception LOGGER.warn('Failed to regenerate settlement {oid}.'.format( oid=settlement.Oid() )) return failures def _display_failures(shell, failures): """ Display a list of settlements that failed to regenerate along with the associated exceptions. """ settlements = list(failures.keys()) settlements.sort(key=lambda s: s.Oid()) message = "The following settlements failed to regenerate:\n" for settlement in settlements: message += "\n- {oid} - {exception}".format( oid=settlement.Oid(), exception=failures[settlement] ) acm.UX.Dialogs().MessageBoxOKCancel(shell, 'Warning', message) class MenuItem(FUxCore.MenuItem): """ Menu item used to trigger the 'Regenerate Payment' command. """ def __init__(self, extension_object): """ Constructor. """ pass @FUxCore.aux_cb def Invoke(self, eii): """ Perform the action on the menu item being invoked. """ if not self._user_has_access(): return shell = eii.Parameter('shell') settlements = eii.ExtensionObject() if _confirm_regenerate(shell, settlements): failures = _regenerate(settlements) if len(failures) > 0: _display_failures(shell, failures) @FUxCore.aux_cb def Applicable(self): """ Determine whether or not the menu item should be visible (shown at all). """ return self._user_has_access() @FUxCore.aux_cb def Enabled(self): """ Determine whether or not the menu item should be enabled (vs greyed-out). """ return self._user_has_access() @FUxCore.aux_cb def Checked(self): """ Determine whether or not the menu item should be checked (have a check mark). """ return False @staticmethod def _user_has_access(): """ Determine whether or not a user should have access to the menu item. """ if not acm.User().IsAllowed('Authorise Settlement', 'Operation'): return False if not acm.User().IsAllowed('Edit Settlements', 'Operation'): return False if not acm.User().IsAllowed('Regenerate Settlement', 'Operation'): return False return True @FUxCore.aux_cb def create_menu_item(extension_object): """ Function used to create and return the menu item. This function is referenced from the 'Regenerate Payment' FMenuExtension. """ return MenuItem(extension_object)
4e5832c5c5b4c8807e7bcdabe9568f504fedc426
67b8ea7f463e76a74d5144202952e6c8c26a9b75
/cluster-env/bin/undill
455df88dec71f58462d5ce48b4a02c95dad99b63
[ "MIT" ]
permissive
democrazyx/elecsim
5418cb99962d7ee2f9f0510eb42d27cd5254d023
e5b8410dce3cb5fa2e869f34998dfab13161bc54
refs/heads/master
2023-06-27T09:31:01.059084
2021-07-24T19:39:36
2021-07-24T19:39:36
null
0
0
null
null
null
null
UTF-8
Python
false
false
617
#!/home/alexkell/elecsim/cluster-env/bin/python3 # # Author: Mike McKerns (mmckerns @caltech and @uqfoundation) # Copyright (c) 2008-2016 California Institute of Technology. # Copyright (c) 2016-2019 The Uncertainty Quantification Foundation. # License: 3-clause BSD. The full license text is available at: # - https://github.com/uqfoundation/dill/blob/master/LICENSE """ unpickle the contents of a pickled object file Examples:: $ undill hello.pkl ['hello', 'world'] """ if __name__ == '__main__': import sys import dill for file in sys.argv[1:]: print (dill.load(open(file,'rb')))
63655078077b3e9d9b986b5bf295f5aae86a05c0
7b26ead5cca82bc8ec8cec01505435db06959284
/spider.py
8ecd93d5e9b67fa07028d64a1ee83625d4721952
[]
no_license
mnahm5/Web-Crawler
dffa8725f56a1c4c9265c120b9ac5500a497bff3
552ca54fd13e4fc30e1315b6a22fb511d2aaf345
refs/heads/master
2021-01-19T00:52:17.912824
2016-06-30T12:45:25
2016-06-30T12:45:25
60,887,947
0
0
null
null
null
null
UTF-8
Python
false
false
2,375
py
from urllib.request import urlopen from link_finder import LinkFinder from general import * class Spider: # Class variables (shared among all instances) project_name = "" base_url = "" domain_name = "" queue_file = "" crawled_file = "" queue = set() crawled = set() def __init__(self, project_name, base_url, domain_name): Spider.project_name = project_name Spider.base_url = base_url Spider.domain_name = domain_name Spider.queue_file = Spider.project_name + "/queue.txt" Spider.crawled_file = Spider.project_name + "/crawled.txt" self.boot() self.crawl_page("First Spider", Spider.base_url) @staticmethod def boot(): create_project_dir(Spider.project_name) create_data_files(Spider.project_name, Spider.base_url) Spider.queue = file_to_set(Spider.queue_file) Spider.crawled = file_to_set(Spider.crawled_file) @staticmethod def crawl_page(thread_name, page_url): if page_url not in Spider.crawled: print(thread_name + ' now crawling ' + page_url) print("Queue " + str(len(Spider.queue)) + " | Crawled " + str(len(Spider.crawled))) Spider.add_links_to_queue(Spider.gather_links(page_url)) Spider.queue.remove(page_url) Spider.crawled.add(page_url) Spider.update_files() @staticmethod def gather_links(page_url): html_string = "" try: response = urlopen(page_url) if response.getheader("Content-Type") == "text/html": html_bytes = response.read() html_string = html_bytes.decode("utf-8") finder = LinkFinder(Spider.base_url, page_url) finder.feed(html_string) except: print("Error: cannot crawl page") return set() return finder.page_links() @staticmethod def add_links_to_queue(links): for url in links: if url in Spider.queue: continue if url in Spider.crawled: continue if Spider.domain_name not in url: continue Spider.queue.add(url) @staticmethod def update_files(): set_to_file(Spider.queue, Spider.queue_file) set_to_file(Spider.crawled, Spider.crawled_file)
1c2e6fc89feaef8003cf91c6e3db19398008dde5
fa5070498f31026b662053d1d5d91282cb1f68b9
/test01/tapp/views.py
36f742b4db34a7c1ddbfc041c48b401998010c04
[ "Apache-2.0" ]
permissive
jinguangzhu/the_first_python
f074c4943028421f96285a2f772e7ccf102248e5
d9d035b44652a4cd6ecd1834dd9930d1c78bf360
refs/heads/master
2020-03-19T14:16:35.860167
2018-06-19T13:58:25
2018-06-19T13:58:25
136,615,947
0
3
Apache-2.0
2018-06-19T13:31:00
2018-06-08T12:27:09
Python
UTF-8
Python
false
false
270
py
from django.shortcuts import render from tapp.models import * # Create your views here. def my_student(req): student = Student.objects.all() return render(req,"student.html",context={"student":student}) def first(req): return render(req,"hellodjango.html")
79d9d6cab1424a8f758f9bc427220aa90cc5ea9a
781e2692049e87a4256320c76e82a19be257a05d
/all_data/exercism_data/python/bob/40dea17339b24a50970c59a9ab7f2661.py
2b91b02b1c565cfce002da2177d0c653c3e0759a
[]
no_license
itsolutionscorp/AutoStyle-Clustering
54bde86fe6dbad35b568b38cfcb14c5ffaab51b0
be0e2f635a7558f56c61bc0b36c6146b01d1e6e6
refs/heads/master
2020-12-11T07:27:19.291038
2016-03-16T03:18:00
2016-03-16T03:18:42
59,454,921
4
0
null
2016-05-23T05:40:56
2016-05-23T05:40:56
null
UTF-8
Python
false
false
365
py
# # Skeleton file for the Python "Bob" exercise. # def hey(phrase): if not phrase.strip() == '': if any(c.isalpha() for c in phrase) and not any( c.islower() for c in phrase): return 'Whoa, chill out!' elif phrase.endswith('?'): return 'Sure.' return 'Whatever.' return 'Fine. Be that way!'
5455dbfa3f6bdb95fbe0d82fe40400246f03ff85
d5beb80c402954d1b66f765b5d5c93d28491324d
/evtstrd_test/filter.py
854a71c52f33622147a05d857a11213a9abf3fb8
[ "MIT" ]
permissive
srittau/eventstreamd
978d822d7dd504f91aebdf11091733a04bb4c5c2
688ee94aea704230e2d0693195062cea8ba3eb73
refs/heads/main
2023-08-18T21:27:23.962517
2023-08-17T09:55:24
2023-08-17T09:55:24
85,480,241
0
0
MIT
2023-09-08T06:45:51
2017-03-19T14:00:49
Python
UTF-8
Python
false
false
3,121
py
from unittest import TestCase from asserts import assert_equal, assert_false, assert_raises, assert_true from evtstrd.filters import parse_filter class FilterTest(TestCase): def test_str(self) -> None: filter_ = parse_filter("foo.bar<='ABC'") assert_equal("foo.bar<='ABC'", str(filter_)) def test_string_filter__path_not_found(self) -> None: filter_ = parse_filter("foo.bar<='ABC'") assert_false(filter_({"foo": {}})) def test_string_filter__wrong_type(self) -> None: filter_ = parse_filter("foo.bar<='50'") assert_false(filter_({"foo": {"bar": 13}})) def test_string_filter__compare(self) -> None: filter_ = parse_filter("foo.bar<='ABC'") assert_true(filter_({"foo": {"bar": "AAA"}})) assert_true(filter_({"foo": {"bar": "ABC"}})) assert_false(filter_({"foo": {"bar": "CAA"}})) def test_string_filter__lt(self) -> None: filter_ = parse_filter("foo.bar<'ABC'") assert_true(filter_({"foo": {"bar": "AAA"}})) assert_false(filter_({"foo": {"bar": "ABC"}})) assert_false(filter_({"foo": {"bar": "CAA"}})) def test_string_filter__gt(self) -> None: filter_ = parse_filter("foo.bar>'ABC'") assert_false(filter_({"foo": {"bar": "AAA"}})) assert_false(filter_({"foo": {"bar": "ABC"}})) assert_true(filter_({"foo": {"bar": "CAA"}})) class ParseFilterTest(TestCase): def test_invalid_filter(self) -> None: with assert_raises(ValueError): parse_filter("INVALID") def test_invalid_values(self) -> None: with assert_raises(ValueError): parse_filter("foo=bar") with assert_raises(ValueError): parse_filter("foo='bar") with assert_raises(ValueError): parse_filter("foo='") with assert_raises(ValueError): parse_filter("foo=2000-12-32") def test_no_such_field(self) -> None: f = parse_filter("foo<=10") assert_false(f({})) def test_wrong_type(self) -> None: f = parse_filter("foo<=10") assert_false(f({"foo": ""})) def test_eq_int(self) -> None: f = parse_filter("foo=10") assert_false(f({"foo": 9})) assert_true(f({"foo": 10})) assert_false(f({"foo": 11})) def test_le_int(self) -> None: f = parse_filter("foo<=10") assert_true(f({"foo": 9})) assert_true(f({"foo": 10})) assert_false(f({"foo": 11})) def test_ge_int(self) -> None: f = parse_filter("foo>=10") assert_false(f({"foo": 9})) assert_true(f({"foo": 10})) assert_true(f({"foo": 11})) def test_eq_str(self) -> None: f = parse_filter("foo='bar'") assert_false(f({"foo": "baz"})) assert_true(f({"foo": "bar"})) def test_eq_date(self) -> None: f = parse_filter("foo=2016-03-24") assert_false(f({"foo": "2000-01-01"})) assert_true(f({"foo": "2016-03-24"})) def test_nested_value(self) -> None: f = parse_filter("foo.bar<=10") assert_true(f({"foo": {"bar": 10}}))
3dedf611bc54472811b3f467db4eb932c8506bf7
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p03971/s127085901.py
34b5ed2240205dc9db4f33c7ab3dd930dddf6d8a
[]
no_license
Aasthaengg/IBMdataset
7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901
f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8
refs/heads/main
2023-04-22T10:22:44.763102
2021-05-13T17:27:22
2021-05-13T17:27:22
367,112,348
0
0
null
null
null
null
UTF-8
Python
false
false
407
py
n,a,b=map(int,input().split()) s=input() passed=0 abroad_passed=0 for i in s: if i=="a": if passed<a+b: print("Yes") passed+=1 else: print("No") elif i=="b": if passed<a+b and abroad_passed<=b-1: print("Yes") passed+=1 abroad_passed+=1 else: print("No") else: print("No")
0f8ebdd234606243284b482e06e4083e1328c38d
3ef0fd7ff4ab98da91de28b4a3ae6bbd55a38361
/wxrobot-host/wxrobot/baidu_shibie.py
7c2115361e6ee26f68503dd32ffd03c7d4f6470f
[]
no_license
nudepig/wxrobot
d0cbcbe0b1fb0a69532bb2c45630bc01ded8c2af
82bd8f68d3163d8dddf1b9a8ccc14532f040fbab
refs/heads/master
2020-12-27T13:35:24.043856
2020-02-03T09:30:04
2020-02-03T09:30:04
237,920,035
0
0
null
null
null
null
UTF-8
Python
false
false
2,770
py
# from aip import AipOcr # 如果已安装pip,执行pip install baidu-aip即可 # import os # """ 你的 APPID AK SK """ # APP_ID = '16802142' # API_KEY = 'FcIxTPz25FZOSjOfgTKfAWIn' # SECRET_KEY = 'GKIvG4tFqqyzisDCY81ASkMihg3LHrwx' # # client = AipOcr(APP_ID, API_KEY, SECRET_KEY) # """ 读取图片 """ # def get_file_content(filePath): # 读取图片 # with open(filePath, 'rb') as fp: # return fp.read() # # def image_identify(picture): # image = get_file_content(picture) # # print(image) # # time_one = time.time() # result = client.basicAccurate(image) # 获取百度识别的结果 # # time_two = time.time() # # print(time_two - time_one) # # if time_two - time_one > 6: # # else: # if os.path.exists('result.txt'): # os.remove('result.txt') # for result_words in list(result['words_result']): # 提取返回结果 # with open('result.txt', 'a+', encoding='utf-8') as file: # file.write(result_words['words'] + '\n') # with open('result.txt', 'r', encoding='utf-8') as file: # result_input = file.read() # return result_input # 返回识别的文字结果,文字分行 # # picture = r'f43a9ae3508254911d9b551d3b0a2d5.png' # image_identify(picture) # encoding:utf-8 # 旧版api import requests import base64 import os ''' 通用文字识别(高精度版) ''' def image_identify(picture): # client_id 为官网获取的AK, client_secret 为官网获取的SK host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=v6ChGHmbOGNu5yyP1bchGYmF&client_secret=RSLGkQm44tYEti0m7dfg2GGgAibFKkZ2' access_token = requests.get(host) request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic" # 二进制方式打开图片文件 f = open(picture, 'rb') img = base64.b64encode(f.read()) access_token = access_token.json() access_token = access_token['access_token'] params = {"image": img} # access_token = '[调用鉴权接口获取的token]' request_url = '{}?access_token={}'.format(request_url, access_token) headers = {'content-type': 'application/x-www-form-urlencoded'} response = requests.post(request_url, data=params, headers=headers) response = response.json() if os.path.exists('result.txt'): os.remove('result.txt') for result_words in list(response['words_result']): # 提取返回结果 with open('result.txt', 'a+', encoding='utf-8') as file: file.write(result_words['words'] + '\n') with open('result.txt', 'r', encoding='utf-8') as file: result_input = file.read() return result_input
526a36db003f6b888927cfb7031603fc97188b7a
2c143ba64032f65c7f7bf1cbd567a1dcf13d5bb1
/整数转罗马数字.py
2a08f7032b28b37c736f253256397e561ff86593
[]
no_license
tx991020/MyLeetcode
5b6121d32260fb30b12cc8146e44e6c6da03ad89
cfe4f087dfeb258caebbc29fc366570ac170a68c
refs/heads/master
2020-04-09T21:43:41.403553
2019-03-27T18:54:35
2019-03-27T18:54:35
160,611,089
0
0
null
null
null
null
UTF-8
Python
false
false
1,205
py
''' 罗马数字包含以下七种字符: I, V, X, L,C,D 和 M。 字符 数值 I 1 V 5 X 10 L 50 C 100 D 500 M 1000 例如, 罗马数字 2 写做 II ,即为两个并列的 1。12 写做 XII ,即为 X + II 。 27 写做 XXVII, 即为 XX + V + II 。 通常情况下,罗马数字中小的数字在大的数字的右边。但也存在特例,例如 4 不写做 IIII,而是 IV。数字 1 在数字 5 的左边,所表示的数等于大数 5 减小数 1 得到的数值 4 。同样地,数字 9 表示为 IX。这个特殊的规则只适用于以下六种情况: I 可以放在 V (5) 和 X (10) 的左边,来表示 4 和 9。 X 可以放在 L (50) 和 C (100) 的左边,来表示 40 和 90。 C 可以放在 D (500) 和 M (1000) 的左边,来表示 400 和 900。 给定一个整数,将其转为罗马数字。输入确保在 1 到 3999 的范围内。 示例 1: 输入: 3 输出: "III" 示例 2: 输入: 4 输出: "IV" 示例 3: 输入: 9 输出: "IX" ''' class Solution: def intToRoman(self, num): """ :type num: int :rtype: str """
5ee73a5d7a4d21e8ff1b542b13b9828616bbdac6
e02dbefe9f362c3e9b2849c1e22c0ab27e010164
/이것이 코딩 테스트다 - 연습문제/19. 1로 만들기.py
18fba447785ec8766aa41a48e8bf4090b6b8e8c1
[]
no_license
hoyeoon/CodingTest
ac77574539a7a96cbdb64eb1768ba20ab6ad3b4f
4d34b422f0dc85f3d506a6c997f3fa883b7162ab
refs/heads/master
2023-06-05T17:43:38.348537
2021-06-28T10:05:22
2021-06-28T10:05:22
378,081,127
0
0
null
null
null
null
UTF-8
Python
false
false
738
py
d = [0] * 30000 d[1], d[2], d[3], d[4], d[5] = 0, 1, 1, 2, 1 x = int(input()) for i in range(6, x + 1): if i % 2 == 0 and i % 3 == 0 and i % 5 == 0: d[i] = min(d[i - 1], d[i // 2], d[i // 3], d[i // 5]) + 1 elif i % 2 == 0 and i % 3 == 0: d[i] = min(d[i - 1], d[i // 2], d[i // 3]) + 1 elif i % 2 == 0 and i % 5 == 0: d[i] = min(d[i - 1], d[i // 2], d[i // 5]) + 1 elif i % 3 == 0 and i % 5 == 0: d[i] = min(d[i - 1], d[i // 3], d[i // 5]) + 1 elif i % 5 == 0: d[i] = min(d[i - 1], d[i // 5]) + 1 elif i % 3 == 0: d[i] = min(d[i - 1], d[i // 3]) + 1 elif i % 2 == 0: d[i] = min(d[i - 1], d[i // 2]) + 1 else: d[i] = d[i - 1] + 1 print(d[x])
54ceb5d460c811307a4e5e8a7f54e6b990c302b3
0fbd56d4a2ee512cb47f557bea310618249a3d2e
/official/vision/image_classification/configs/base_configs.py
efdcdc0b4327871dd04a854f057cbcdf84a9db9e
[ "Apache-2.0" ]
permissive
joppemassant/models
9968f74f5c48096f3b2a65e6864f84c0181465bb
b2a6712cbe6eb9a8639f01906e187fa265f3f48e
refs/heads/master
2022-12-10T01:29:31.653430
2020-09-11T11:26:59
2020-09-11T11:26:59
294,675,920
1
1
Apache-2.0
2020-09-11T11:21:51
2020-09-11T11:21:51
null
UTF-8
Python
false
false
7,936
py
# Lint as: python3 # Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Definitions for high level configuration groups..""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from typing import Any, List, Mapping, Optional import dataclasses from official.modeling import hyperparams from official.modeling.hyperparams import config_definitions CallbacksConfig = config_definitions.CallbacksConfig TensorboardConfig = config_definitions.TensorboardConfig RuntimeConfig = config_definitions.RuntimeConfig @dataclasses.dataclass class ExportConfig(hyperparams.Config): """Configuration for exports. Attributes: checkpoint: the path to the checkpoint to export. destination: the path to where the checkpoint should be exported. """ checkpoint: str = None destination: str = None @dataclasses.dataclass class MetricsConfig(hyperparams.Config): """Configuration for Metrics. Attributes: accuracy: Whether or not to track accuracy as a Callback. Defaults to None. top_5: Whether or not to track top_5_accuracy as a Callback. Defaults to None. """ accuracy: bool = None top_5: bool = None @dataclasses.dataclass class TimeHistoryConfig(hyperparams.Config): """Configuration for the TimeHistory callback. Attributes: log_steps: Interval of steps between logging of batch level stats. """ log_steps: int = None @dataclasses.dataclass class TrainConfig(hyperparams.Config): """Configuration for training. Attributes: resume_checkpoint: Whether or not to enable load checkpoint loading. Defaults to None. epochs: The number of training epochs to run. Defaults to None. steps: The number of steps to run per epoch. If None, then this will be inferred based on the number of images and batch size. Defaults to None. callbacks: An instance of CallbacksConfig. metrics: An instance of MetricsConfig. tensorboard: An instance of TensorboardConfig. set_epoch_loop: Whether or not to set `experimental_steps_per_execution` to equal the number of training steps in `model.compile`. This reduces the number of callbacks run per epoch which significantly improves end-to-end TPU training time. """ resume_checkpoint: bool = None epochs: int = None steps: int = None callbacks: CallbacksConfig = CallbacksConfig() metrics: MetricsConfig = None tensorboard: TensorboardConfig = TensorboardConfig() time_history: TimeHistoryConfig = TimeHistoryConfig() set_epoch_loop: bool = False @dataclasses.dataclass class EvalConfig(hyperparams.Config): """Configuration for evaluation. Attributes: epochs_between_evals: The number of train epochs to run between evaluations. Defaults to None. steps: The number of eval steps to run during evaluation. If None, this will be inferred based on the number of images and batch size. Defaults to None. skip_eval: Whether or not to skip evaluation. """ epochs_between_evals: int = None steps: int = None skip_eval: bool = False @dataclasses.dataclass class LossConfig(hyperparams.Config): """Configuration for Loss. Attributes: name: The name of the loss. Defaults to None. label_smoothing: Whether or not to apply label smoothing to the loss. This only applies to 'categorical_cross_entropy'. """ name: str = None label_smoothing: float = None @dataclasses.dataclass class OptimizerConfig(hyperparams.Config): """Configuration for Optimizers. Attributes: name: The name of the optimizer. Defaults to None. decay: Decay or rho, discounting factor for gradient. Defaults to None. epsilon: Small value used to avoid 0 denominator. Defaults to None. momentum: Plain momentum constant. Defaults to None. nesterov: Whether or not to apply Nesterov momentum. Defaults to None. moving_average_decay: The amount of decay to apply. If 0 or None, then exponential moving average is not used. Defaults to None. lookahead: Whether or not to apply the lookahead optimizer. Defaults to None. beta_1: The exponential decay rate for the 1st moment estimates. Used in the Adam optimizers. Defaults to None. beta_2: The exponential decay rate for the 2nd moment estimates. Used in the Adam optimizers. Defaults to None. epsilon: Small value used to avoid 0 denominator. Defaults to 1e-7. """ name: str = None decay: float = None epsilon: float = None momentum: float = None nesterov: bool = None moving_average_decay: Optional[float] = None lookahead: Optional[bool] = None beta_1: float = None beta_2: float = None epsilon: float = None @dataclasses.dataclass class LearningRateConfig(hyperparams.Config): """Configuration for learning rates. Attributes: name: The name of the learning rate. Defaults to None. initial_lr: The initial learning rate. Defaults to None. decay_epochs: The number of decay epochs. Defaults to None. decay_rate: The rate of decay. Defaults to None. warmup_epochs: The number of warmup epochs. Defaults to None. batch_lr_multiplier: The multiplier to apply to the base learning rate, if necessary. Defaults to None. examples_per_epoch: the number of examples in a single epoch. Defaults to None. boundaries: boundaries used in piecewise constant decay with warmup. multipliers: multipliers used in piecewise constant decay with warmup. scale_by_batch_size: Scale the learning rate by a fraction of the batch size. Set to 0 for no scaling (default). staircase: Apply exponential decay at discrete values instead of continuous. """ name: str = None initial_lr: float = None decay_epochs: float = None decay_rate: float = None warmup_epochs: int = None examples_per_epoch: int = None boundaries: List[int] = None multipliers: List[float] = None scale_by_batch_size: float = 0. staircase: bool = None @dataclasses.dataclass class ModelConfig(hyperparams.Config): """Configuration for Models. Attributes: name: The name of the model. Defaults to None. model_params: The parameters used to create the model. Defaults to None. num_classes: The number of classes in the model. Defaults to None. loss: A `LossConfig` instance. Defaults to None. optimizer: An `OptimizerConfig` instance. Defaults to None. """ name: str = None model_params: hyperparams.Config = None num_classes: int = None loss: LossConfig = None optimizer: OptimizerConfig = None @dataclasses.dataclass class ExperimentConfig(hyperparams.Config): """Base configuration for an image classification experiment. Attributes: model_dir: The directory to use when running an experiment. mode: e.g. 'train_and_eval', 'export' runtime: A `RuntimeConfig` instance. train: A `TrainConfig` instance. evaluation: An `EvalConfig` instance. model: A `ModelConfig` instance. export: An `ExportConfig` instance. """ model_dir: str = None model_name: str = None mode: str = None runtime: RuntimeConfig = None train_dataset: Any = None validation_dataset: Any = None train: TrainConfig = None evaluation: EvalConfig = None model: ModelConfig = None export: ExportConfig = None
55e3fff99a6a53657ed6aa3797ba4ebd66cd1a7a
be84495751737bbf0a8b7d8db2fb737cbd9c297c
/renlight/tests/renderer/test_sampler.py
b751d8606bc7eb66c363b055ea2f3a538bd86591
[]
no_license
mario007/renmas
5e38ff66cffb27b3edc59e95b7cf88906ccc03c9
bfb4e1defc88eb514e58bdff7082d722fc885e64
refs/heads/master
2021-01-10T21:29:35.019792
2014-08-17T19:11:51
2014-08-17T19:11:51
1,688,798
1
0
null
null
null
null
UTF-8
Python
false
false
1,747
py
import unittest from tdasm import Runtime from renlight.sdl.shader import Shader from renlight.sdl import FloatArg, IntArg from renlight.renderer.sampler import Sampler class SamplerTest(unittest.TestCase): def test_sampler(self): sam = Sampler() sam.set_resolution(2, 2) sam.load('regular') sam.compile() runtimes = [Runtime()] sam.prepare(runtimes) code = """ sample = Sample() r1 = generate_sample(sample) p1 = sample.x p2 = sample.y p3 = sample.ix p4 = sample.iy """ p1 = FloatArg('p1', 566.6) p2 = FloatArg('p2', 566.6) p3 = IntArg('p3', 5655) p4 = IntArg('p4', 5655) r1 = IntArg('r1', 5655) args = [p1, p2, p3, p4, r1] shader = Shader(code=code, args=args) shader.compile([sam.shader]) shader.prepare(runtimes) shader.execute() self._check_result(shader, -0.5, -0.5, 0, 0, 1) shader.execute() self._check_result(shader, 0.5, -0.5, 1, 0, 1) shader.execute() self._check_result(shader, -0.5, 0.5, 0, 1, 1) shader.execute() self._check_result(shader, 0.5, 0.5, 1, 1, 1) shader.execute() ret = shader.get_value('r1') self.assertEqual(ret, 0) def _check_result(self, shader, p1, p2, p3, p4, r1): t1 = shader.get_value('p1') self.assertEqual(t1, p1) t2 = shader.get_value('p2') self.assertEqual(t2, p2) t3 = shader.get_value('p3') self.assertAlmostEqual(t3, p3) t4 = shader.get_value('p4') self.assertAlmostEqual(t4, p4) k1 = shader.get_value('r1') self.assertEqual(k1, r1) if __name__ == "__main__": unittest.main()
06a22bd4d2ef980a8bf8ceb2a13a88b006b28f39
5a82795c3860745112b7410d9060c5ef671adba0
/leetcode/Kth Smallest Element in a BST.py
b169e7cff32636d2f2a3af72ff6449ae26da5f4b
[]
no_license
ashishvista/geeks
8e09d0f3a422c1c9a1c1b19d879ebafa31b62f44
1677a304fc7857a3054b574e8702491f5ce01a04
refs/heads/master
2023-03-05T12:01:03.911096
2021-02-15T03:00:56
2021-02-15T03:00:56
336,996,558
0
0
null
null
null
null
UTF-8
Python
false
false
1,268
py
# Definition for a binary tree node. from collections import deque class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def deserialize(arr): n = len(arr) dq = deque() root = TreeNode(int(arr[0])) dq.append(root) i = 1 while dq: top = dq.popleft() if i < n: if arr[i] != "null": top.left = TreeNode(int(arr[i])) dq.append(top.left) if (i + 1) < n: if arr[i + 1] != "null": top.right = TreeNode(int(arr[i + 1])) dq.append(top.right) i += 2 return root class Solution: def kthSmallest(self, root: TreeNode, k: int) -> int: if root is None: return [] st = [] c = 0 while True: while root: st.append(root) root = root.left root = st.pop() c += 1 if c == k: return root.val root = root.right if __name__ == "__main__": arr = input().strip()[1:-1].split(",") k = int(input()) root = deserialize(arr) res = Solution().kthSmallest(root, k) print(res)
a49e3ed005188518b84eb367a76afe8c6aed96d3
2a5f67db7dfe10c21ee5a148731c4e95cf5f613a
/30 Days of Code/Day 24 - More Linked Lists.py
7fe94449c1d6e0bf7eeac377f35f9172729ebeb4
[]
no_license
bayoishola20/HackerRank
b8d49da0ff648463fda4e590b662b8914550402c
466b17c326ccaf208239fa40dee014efeb9b8561
refs/heads/master
2021-09-06T09:19:51.979879
2018-02-04T23:40:02
2018-02-04T23:40:02
64,167,170
1
3
null
null
null
null
UTF-8
Python
false
false
1,270
py
#==================== GIVEN CODE ======================# class Node: def __init__(self,data): self.data = data self.next = None class Solution: def insert(self,head,data): p = Node(data) if head==None: head=p elif head.next==None: head.next=p else: start=head while(start.next!=None): start=start.next start.next=p return head def display(self,head): current = head while current: print current.data, current = current.next #===================== END =========================# def removeDuplicates(self,head): #Write your code here node = head while node and node.next: while node.next and node.data is node.next.data: node.next = node.next.next node = node.next return head # return head #==================== GIVEN CODE ======================# mylist= Solution() T=int(input()) head=None for i in range(T): data=int(input()) head=mylist.insert(head,data) head=mylist.removeDuplicates(head) mylist.display(head); #===================== END =========================#
59be0bf880afb7289bde3428351fe26aef1322ec
bda892fd07e3879df21dcd1775c86269587e7e07
/leetcode/0058_E_最后一个单词的长度.py
140ca073f044a5177a84e26a03f62afdfde003a6
[]
no_license
CrzRabbit/Python
46923109b6e516820dd90f880f6603f1cc71ba11
055ace9f0ca4fb09326da77ae39e33173b3bde15
refs/heads/master
2021-12-23T15:44:46.539503
2021-09-23T09:32:42
2021-09-23T09:32:42
119,370,525
2
0
null
null
null
null
UTF-8
Python
false
false
1,021
py
''' 给你一个字符串 s,由若干单词组成,单词之间用空格隔开。返回字符串中最后一个单词的长度。如果不存在最后一个单词,请返回 0 。 单词 是指仅由字母组成、不包含任何空格字符的最大子字符串。 示例 1: 输入:s = "Hello World" 输出:5 示例 2: 输入:s = " " 输出:0 提示: 1 <= s.length <= 104 s 仅有英文字母和空格 ' ' 组成 ''' class Solution: def _lengthOfLastWord(self, s: str) -> int: left = -1 right = -1 index = len(s) - 1 while index >= 0: if right < 0 and s[index] != ' ': right = index if right > 0 and s[index] == ' ': left = index break index -= 1 print(right, left) return right - left def lengthOfLastWord(self, s: str) -> int: return len(s.split()[-1:][0]) so = Solution() print(so.lengthOfLastWord('b a '))
3f006e7288b20ee04ed3cd9979855e75f941bfc2
2dd560dc468af0af4ca44cb4cd37a0b807357063
/Leetcode/1441. Build an Array With Stack Operations/solution2.py
6a4545eaa5d00ee6fae207f89c0238a4684c2e0d
[ "MIT" ]
permissive
hi0t/Outtalent
460fe4a73788437ba6ce9ef1501291035c8ff1e8
8a10b23335d8e9f080e5c39715b38bcc2916ff00
refs/heads/master
2023-02-26T21:16:56.741589
2021-02-05T13:36:50
2021-02-05T13:36:50
null
0
0
null
null
null
null
UTF-8
Python
false
false
255
py
class Solution: def buildArray(self, target: List[int], n: int) -> List[str]: result = [] for i in range(1, max(target) + 1): result.append("Push") if i not in target: result.append("Pop") return result
db3b6353b6a685819d237c58f1e1af3c774e7fa3
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p03272/s087307449.py
fcf22c1051c98aacd570a62fca520414b8ef122a
[]
no_license
Aasthaengg/IBMdataset
7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901
f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8
refs/heads/main
2023-04-22T10:22:44.763102
2021-05-13T17:27:22
2021-05-13T17:27:22
367,112,348
0
0
null
null
null
null
UTF-8
Python
false
false
62
py
n,i = map(int,input().split()) count = n - i + 1 print(count)
36dad26e1bf89e1f0c9698c64e31fcf54f3fc7c0
37d9bb2869fe491a67c97de6adc3e0e1693ff82a
/StringMethods.py
6d8af7c493506723fa8c73866f566114291010f2
[]
no_license
qinyanjuidavid/Self-Learning
ffbcb62f2204c5dedd0cde3a116b653da77b3702
8c6a5b3a7f250af99538e9f23d01d8a09839b702
refs/heads/master
2023-03-31T10:20:21.225642
2021-04-03T08:04:27
2021-04-03T08:04:27
null
0
0
null
null
null
null
UTF-8
Python
false
false
680
py
#strip(), len(),lower(),upper(),split() name=" Hello " print(name.strip())#It removes all the spaces in a string nums=" 1 2 3 1 4 " print(nums.strip())#The spaces removed are before and after print(len(name)) #Checks the length of the string name="JOHN DOE" print(name.lower()) #changes the strings to be in lower case name="jane Doe" print(name.upper()) #Changes the string to upper case name="JOHN DOE" print(name.split()) #Changes the string to a string print(type(name.split())) #Count() and find() methodss s="Hello" print(s.find('o')) print(s.find('l')) print(s.find('s'))#Python does not find s print(s.count('h')) print(s.count('l')) print(s.count('z'))#Zero 'z'
1179ed1a0a4a8b465f26500da471f61dec3bfdb5
5251a6be594dff7e56bbe6b4f968ea43c3315471
/atoll/config.py
5dd83a5e843ac4f91ecf18cf5ba16b102eadb80f
[ "Apache-2.0" ]
permissive
coralproject/atoll
aec2e529fd7c5164864c4a2e9a501a8477fc3872
2b62b37d3a320480264c4a0242532aad99c338ec
refs/heads/master
2021-07-14T03:39:09.761086
2016-07-26T18:57:16
2016-07-26T18:57:16
43,079,410
12
1
NOASSERTION
2021-03-19T21:53:15
2015-09-24T16:37:32
Python
UTF-8
Python
false
false
437
py
""" Loads the service configuration. """ import os import yaml conf = { 'worker_broker': 'amqp://guest:guest@localhost/', 'worker_backend': 'amqp', 'executor_host': '127.0.0.1:8786' } user_conf_path = os.environ.get('ATOLL_CONF', None) if user_conf_path is not None: with open(user_conf_path, 'r') as f: conf.update(yaml.load(f)) namespace = globals() for k, v in conf.items(): namespace[k.upper()] = v
cd41d985c603ed0a4723965bfa70df8a138d1f06
f95d2646f8428cceed98681f8ed2407d4f044941
/FlaskDemo04/run01.py
97f6b559d276571f0ef32a6508c258ebd248ba6e
[]
no_license
q2806060/python-note
014e1458dcfa896f2749c7ebce68b2bbe31a3bf8
fbe107d668b44b78ae0094dbcc7e8ff8a4f8c983
refs/heads/master
2020-08-18T01:12:31.227654
2019-10-17T07:40:40
2019-10-17T07:40:40
215,731,114
1
0
null
null
null
null
UTF-8
Python
false
false
486
py
from flask import Flask from flask_sqlalchemy import SQLAlchemy #导入pymysql用来替代MySQLdb import pymysql # pymysql.install_as_MySQLdb() app = Flask(__name__) #为app指定连库字符 app.config['SQLALCHEMY_DATABASE_URI']="mysql+pymysql://root:123456@localhost:3306/flask" #取消SQLAlchemy的信号追踪 app.config['SQLALCHEMY_TRACK_MODIFICATIONS']=False #创建SQLAlchemy程序实例 db = SQLAlchemy(app) if __name__ == "__main__": app.run(debug=True)
9f8c4569973317f1d4012e8eb9299a38aae2c3ac
c9ddbdb5678ba6e1c5c7e64adf2802ca16df778c
/cases/synthetic/sieve-big-2820.py
40ba804c3b66a2d92304552027939b5501509d12
[]
no_license
Virtlink/ccbench-chocopy
c3f7f6af6349aff6503196f727ef89f210a1eac8
c7efae43bf32696ee2b2ee781bdfe4f7730dec3f
refs/heads/main
2023-04-07T15:07:12.464038
2022-02-03T15:42:39
2022-02-03T15:42:39
451,969,776
0
0
null
null
null
null
UTF-8
Python
false
false
31,740
py
# A resizable list of integers class Vector(object): items: [int] = None size: int = 0 def __init__(self:"Vector"): self.items = [0] # Returns current capacity def capacity(self:"Vector") -> int: return len(self.items) # Increases capacity of vector by one element def increase_capacity(self:"Vector") -> int: self.items = self.items + [0] return self.capacity() # Appends one item to end of vector def append(self:"Vector", item: int) -> object: if self.size == self.capacity(): self.increase_capacity() self.items[self.size] = item self.size = self.size + 1 # Appends many items to end of vector def append_all(self:"Vector", new_items: [int]) -> object: item:int = 0 for item in new_items: self.append(item) # Removes an item from the middle of vector def remove_at(self:"Vector", idx: int) -> object: if idx < 0: return while idx < self.size - 1: self.items[idx] = self.items[idx + 1] idx = idx + 1 self.size = self.size - 1 # Retrieves an item at a given index def get(self:"Vector", idx: int) -> int: return self.items[idx] # Retrieves the current size of the vector def length(self:"Vector") -> int: return self.size # A resizable list of integers class Vector2(object): items: [int] = None items2: [int] = None size: int = 0 size2: int = 0 def __init__(self:"Vector2"): self.items = [0] # Returns current capacity def capacity(self:"Vector2") -> int: return len(self.items) # Returns current capacity def capacity2(self:"Vector2") -> int: return len(self.items) # Increases capacity of vector by one element def increase_capacity(self:"Vector2") -> int: self.items = self.items + [0] return self.capacity() # Increases capacity of vector by one element def increase_capacity2(self:"Vector2") -> int: self.items = self.items + [0] return self.capacity() # Appends one item to end of vector def append(self:"Vector2", item: int) -> object: if self.size == self.capacity(): self.increase_capacity() self.items[self.size] = item self.size = self.size + 1 # Appends one item to end of vector def append2(self:"Vector2", item: int, item2: int) -> object: if self.size == self.capacity(): self.increase_capacity() self.items[self.size] = item self.size = self.size + 1 # Appends many items to end of vector def append_all(self:"Vector2", new_items: [int]) -> object: item:int = 0 for item in new_items: self.append(item) # Appends many items to end of vector def append_all2(self:"Vector2", new_items: [int], new_items2: [int]) -> object: item:int = 0 item2:int = 0 for item in new_items: self.append(item) # Removes an item from the middle of vector def remove_at(self:"Vector2", idx: int) -> object: if idx < 0: return while idx < self.size - 1: self.items[idx] = self.items[idx + 1] idx = idx + 1 self.size = self.size - 1 # Removes an item from the middle of vector def remove_at2(self:"Vector2", idx: int, idx2: int) -> object: if idx < 0: return while idx < self.size - 1: self.items[idx] = self.items[idx + 1] idx = idx + 1 self.size = self.size - 1 # Retrieves an item at a given index def get(self:"Vector2", idx: int) -> int: return self.items[idx] # Retrieves an item at a given index def get2(self:"Vector2", idx: int, idx2: int) -> int: return self.items[idx] # Retrieves the current size of the vector def length(self:"Vector2") -> int: return self.size # Retrieves the current size of the vector def length2(self:"Vector2") -> int: return self.size # A resizable list of integers class Vector3(object): items: [int] = None items2: [int] = None items3: [int] = None size: int = 0 size2: int = 0 size3: int = 0 def __init__(self:"Vector3"): self.items = [0] # Returns current capacity def capacity(self:"Vector3") -> int: return len(self.items) # Returns current capacity def capacity2(self:"Vector3") -> int: return len(self.items) # Returns current capacity def capacity3(self:"Vector3") -> int: return len(self.items) # Increases capacity of vector by one element def increase_capacity(self:"Vector3") -> int: self.items = self.items + [0] return self.capacity() # Increases capacity of vector by one element def increase_capacity2(self:"Vector3") -> int: self.items = self.items + [0] return self.capacity() # Increases capacity of vector by one element def increase_capacity3(self:"Vector3") -> int: self.items = self.items + [0] return self.capacity() # Appends one item to end of vector def append(self:"Vector3", item: int) -> object: if self.size == self.capacity(): self.increase_capacity() self.items[self.size] = item self.size = self.size + 1 # Appends one item to end of vector def append2(self:"Vector3", item: int, item2: int) -> object: if self.size == self.capacity(): self.increase_capacity() self.items[self.size] = item self.size = self.size + 1 # Appends one item to end of vector def append3(self:"Vector3", item: int, item2: int, item3: int) -> object: if self.size == self.capacity(): self.increase_capacity() self.items[self.size] = item self.size = self.size + 1 # Appends many items to end of vector def append_all(self:"Vector3", new_items: [int]) -> object: item:int = 0 for item in new_items: self.append(item) # Appends many items to end of vector def append_all2(self:"Vector3", new_items: [int], new_items2: [int]) -> object: item:int = 0 item2:int = 0 for item in new_items: self.append(item) # Appends many items to end of vector def append_all3(self:"Vector3", new_items: [int], new_items2: [int], new_items3: [int]) -> object: item:int = 0 item2:int = 0 item3:int = 0 for item in new_items: self.append(item) # Removes an item from the middle of vector def remove_at(self:"Vector3", idx: int) -> object: if idx < 0: return while idx < self.size - 1: self.items[idx] = self.items[idx + 1] idx = idx + 1 self.size = self.size - 1 # Removes an item from the middle of vector def remove_at2(self:"Vector3", idx: int, idx2: int) -> object: if idx < 0: return while idx < self.size - 1: self.items[idx] = self.items[idx + 1] idx = idx + 1 self.size = self.size - 1 # Removes an item from the middle of vector def remove_at3(self:"Vector3", idx: int, idx2: int, idx3: int) -> object: if idx < 0: return while idx < self.size - 1: self.items[idx] = self.items[idx + 1] idx = idx + 1 self.size = self.size - 1 # Retrieves an item at a given index def get(self:"Vector3", idx: int) -> int: return self.items[idx] # Retrieves an item at a given index def get2(self:"Vector3", idx: int, idx2: int) -> int: return self.items[idx] # Retrieves an item at a given index def get3(self:"Vector3", idx: int, idx2: int, idx3: int) -> int: return self.items[idx] # Retrieves the current size of the vector def length(self:"Vector3") -> int: return self.size # Retrieves the current size of the vector def length2(self:"Vector3") -> int: return self.size # Retrieves the current size of the vector def length3(self:"Vector3") -> int: return self.size # A resizable list of integers class Vector4(object): items: [int] = None items2: [int] = None items3: [int] = None items4: [int] = None size: int = 0 size2: int = 0 size3: int = 0 size4: int = 0 def __init__(self:"Vector4"): self.items = [0] # Returns current capacity def capacity(self:"Vector4") -> int: return len(self.items) # Returns current capacity def capacity2(self:"Vector4") -> int: return len(self.items) # Returns current capacity def capacity3(self:"Vector4") -> int: return len(self.items) # Returns current capacity def capacity4(self:"Vector4") -> int: return len(self.items) # Increases capacity of vector by one element def increase_capacity(self:"Vector4") -> int: self.items = self.items + [0] return self.capacity() # Increases capacity of vector by one element def increase_capacity2(self:"Vector4") -> int: self.items = self.items + [0] return self.capacity() # Increases capacity of vector by one element def $ID(self:"Vector4") -> int: self.items = self.items + [0] return self.capacity() # Increases capacity of vector by one element def increase_capacity4(self:"Vector4") -> int: self.items = self.items + [0] return self.capacity() # Appends one item to end of vector def append(self:"Vector4", item: int) -> object: if self.size == self.capacity(): self.increase_capacity() self.items[self.size] = item self.size = self.size + 1 # Appends one item to end of vector def append2(self:"Vector4", item: int, item2: int) -> object: if self.size == self.capacity(): self.increase_capacity() self.items[self.size] = item self.size = self.size + 1 # Appends one item to end of vector def append3(self:"Vector4", item: int, item2: int, item3: int) -> object: if self.size == self.capacity(): self.increase_capacity() self.items[self.size] = item self.size = self.size + 1 # Appends one item to end of vector def append4(self:"Vector4", item: int, item2: int, item3: int, item4: int) -> object: if self.size == self.capacity(): self.increase_capacity() self.items[self.size] = item self.size = self.size + 1 # Appends many items to end of vector def append_all(self:"Vector4", new_items: [int]) -> object: item:int = 0 for item in new_items: self.append(item) # Appends many items to end of vector def append_all2(self:"Vector4", new_items: [int], new_items2: [int]) -> object: item:int = 0 item2:int = 0 for item in new_items: self.append(item) # Appends many items to end of vector def append_all3(self:"Vector4", new_items: [int], new_items2: [int], new_items3: [int]) -> object: item:int = 0 item2:int = 0 item3:int = 0 for item in new_items: self.append(item) # Appends many items to end of vector def append_all4(self:"Vector4", new_items: [int], new_items2: [int], new_items3: [int], new_items4: [int]) -> object: item:int = 0 item2:int = 0 item3:int = 0 item4:int = 0 for item in new_items: self.append(item) # Removes an item from the middle of vector def remove_at(self:"Vector4", idx: int) -> object: if idx < 0: return while idx < self.size - 1: self.items[idx] = self.items[idx + 1] idx = idx + 1 self.size = self.size - 1 # Removes an item from the middle of vector def remove_at2(self:"Vector4", idx: int, idx2: int) -> object: if idx < 0: return while idx < self.size - 1: self.items[idx] = self.items[idx + 1] idx = idx + 1 self.size = self.size - 1 # Removes an item from the middle of vector def remove_at3(self:"Vector4", idx: int, idx2: int, idx3: int) -> object: if idx < 0: return while idx < self.size - 1: self.items[idx] = self.items[idx + 1] idx = idx + 1 self.size = self.size - 1 # Removes an item from the middle of vector def remove_at4(self:"Vector4", idx: int, idx2: int, idx3: int, idx4: int) -> object: if idx < 0: return while idx < self.size - 1: self.items[idx] = self.items[idx + 1] idx = idx + 1 self.size = self.size - 1 # Retrieves an item at a given index def get(self:"Vector4", idx: int) -> int: return self.items[idx] # Retrieves an item at a given index def get2(self:"Vector4", idx: int, idx2: int) -> int: return self.items[idx] # Retrieves an item at a given index def get3(self:"Vector4", idx: int, idx2: int, idx3: int) -> int: return self.items[idx] # Retrieves an item at a given index def get4(self:"Vector4", idx: int, idx2: int, idx3: int, idx4: int) -> int: return self.items[idx] # Retrieves the current size of the vector def length(self:"Vector4") -> int: return self.size # Retrieves the current size of the vector def length2(self:"Vector4") -> int: return self.size # Retrieves the current size of the vector def length3(self:"Vector4") -> int: return self.size # Retrieves the current size of the vector def length4(self:"Vector4") -> int: return self.size # A resizable list of integers class Vector5(object): items: [int] = None items2: [int] = None items3: [int] = None items4: [int] = None items5: [int] = None size: int = 0 size2: int = 0 size3: int = 0 size4: int = 0 size5: int = 0 def __init__(self:"Vector5"): self.items = [0] # Returns current capacity def capacity(self:"Vector5") -> int: return len(self.items) # Returns current capacity def capacity2(self:"Vector5") -> int: return len(self.items) # Returns current capacity def capacity3(self:"Vector5") -> int: return len(self.items) # Returns current capacity def capacity4(self:"Vector5") -> int: return len(self.items) # Returns current capacity def capacity5(self:"Vector5") -> int: return len(self.items) # Increases capacity of vector by one element def increase_capacity(self:"Vector5") -> int: self.items = self.items + [0] return self.capacity() # Increases capacity of vector by one element def increase_capacity2(self:"Vector5") -> int: self.items = self.items + [0] return self.capacity() # Increases capacity of vector by one element def increase_capacity3(self:"Vector5") -> int: self.items = self.items + [0] return self.capacity() # Increases capacity of vector by one element def increase_capacity4(self:"Vector5") -> int: self.items = self.items + [0] return self.capacity() # Increases capacity of vector by one element def increase_capacity5(self:"Vector5") -> int: self.items = self.items + [0] return self.capacity() # Appends one item to end of vector def append(self:"Vector5", item: int) -> object: if self.size == self.capacity(): self.increase_capacity() self.items[self.size] = item self.size = self.size + 1 # Appends one item to end of vector def append2(self:"Vector5", item: int, item2: int) -> object: if self.size == self.capacity(): self.increase_capacity() self.items[self.size] = item self.size = self.size + 1 # Appends one item to end of vector def append3(self:"Vector5", item: int, item2: int, item3: int) -> object: if self.size == self.capacity(): self.increase_capacity() self.items[self.size] = item self.size = self.size + 1 # Appends one item to end of vector def append4(self:"Vector5", item: int, item2: int, item3: int, item4: int) -> object: if self.size == self.capacity(): self.increase_capacity() self.items[self.size] = item self.size = self.size + 1 # Appends one item to end of vector def append5(self:"Vector5", item: int, item2: int, item3: int, item4: int, item5: int) -> object: if self.size == self.capacity(): self.increase_capacity() self.items[self.size] = item self.size = self.size + 1 # Appends many items to end of vector def append_all(self:"Vector5", new_items: [int]) -> object: item:int = 0 for item in new_items: self.append(item) # Appends many items to end of vector def append_all2(self:"Vector5", new_items: [int], new_items2: [int]) -> object: item:int = 0 item2:int = 0 for item in new_items: self.append(item) # Appends many items to end of vector def append_all3(self:"Vector5", new_items: [int], new_items2: [int], new_items3: [int]) -> object: item:int = 0 item2:int = 0 item3:int = 0 for item in new_items: self.append(item) # Appends many items to end of vector def append_all4(self:"Vector5", new_items: [int], new_items2: [int], new_items3: [int], new_items4: [int]) -> object: item:int = 0 item2:int = 0 item3:int = 0 item4:int = 0 for item in new_items: self.append(item) # Appends many items to end of vector def append_all5(self:"Vector5", new_items: [int], new_items2: [int], new_items3: [int], new_items4: [int], new_items5: [int]) -> object: item:int = 0 item2:int = 0 item3:int = 0 item4:int = 0 item5:int = 0 for item in new_items: self.append(item) # Removes an item from the middle of vector def remove_at(self:"Vector5", idx: int) -> object: if idx < 0: return while idx < self.size - 1: self.items[idx] = self.items[idx + 1] idx = idx + 1 self.size = self.size - 1 # Removes an item from the middle of vector def remove_at2(self:"Vector5", idx: int, idx2: int) -> object: if idx < 0: return while idx < self.size - 1: self.items[idx] = self.items[idx + 1] idx = idx + 1 self.size = self.size - 1 # Removes an item from the middle of vector def remove_at3(self:"Vector5", idx: int, idx2: int, idx3: int) -> object: if idx < 0: return while idx < self.size - 1: self.items[idx] = self.items[idx + 1] idx = idx + 1 self.size = self.size - 1 # Removes an item from the middle of vector def remove_at4(self:"Vector5", idx: int, idx2: int, idx3: int, idx4: int) -> object: if idx < 0: return while idx < self.size - 1: self.items[idx] = self.items[idx + 1] idx = idx + 1 self.size = self.size - 1 # Removes an item from the middle of vector def remove_at5(self:"Vector5", idx: int, idx2: int, idx3: int, idx4: int, idx5: int) -> object: if idx < 0: return while idx < self.size - 1: self.items[idx] = self.items[idx + 1] idx = idx + 1 self.size = self.size - 1 # Retrieves an item at a given index def get(self:"Vector5", idx: int) -> int: return self.items[idx] # Retrieves an item at a given index def get2(self:"Vector5", idx: int, idx2: int) -> int: return self.items[idx] # Retrieves an item at a given index def get3(self:"Vector5", idx: int, idx2: int, idx3: int) -> int: return self.items[idx] # Retrieves an item at a given index def get4(self:"Vector5", idx: int, idx2: int, idx3: int, idx4: int) -> int: return self.items[idx] # Retrieves an item at a given index def get5(self:"Vector5", idx: int, idx2: int, idx3: int, idx4: int, idx5: int) -> int: return self.items[idx] # Retrieves the current size of the vector def length(self:"Vector5") -> int: return self.size # Retrieves the current size of the vector def length2(self:"Vector5") -> int: return self.size # Retrieves the current size of the vector def length3(self:"Vector5") -> int: return self.size # Retrieves the current size of the vector def length4(self:"Vector5") -> int: return self.size # Retrieves the current size of the vector def length5(self:"Vector5") -> int: return self.size # A faster (but more memory-consuming) implementation of vector class DoublingVector(Vector): doubling_limit:int = 1000 # Overriding to do fewer resizes def increase_capacity(self:"DoublingVector") -> int: if (self.capacity() <= self.doubling_limit // 2): self.items = self.items + self.items else: # If doubling limit has been reached, fall back to # standard capacity increases self.items = self.items + [0] return self.capacity() # A faster (but more memory-consuming) implementation of vector class DoublingVector2(Vector): doubling_limit:int = 1000 doubling_limit2:int = 1000 # Overriding to do fewer resizes def increase_capacity(self:"DoublingVector2") -> int: if (self.capacity() <= self.doubling_limit // 2): self.items = self.items + self.items else: # If doubling limit has been reached, fall back to # standard capacity increases self.items = self.items + [0] return self.capacity() # Overriding to do fewer resizes def increase_capacity2(self:"DoublingVector2") -> int: if (self.capacity() <= self.doubling_limit // 2): self.items = self.items + self.items else: # If doubling limit has been reached, fall back to # standard capacity increases self.items = self.items + [0] return self.capacity() # A faster (but more memory-consuming) implementation of vector class DoublingVector3(Vector): doubling_limit:int = 1000 doubling_limit2:int = 1000 doubling_limit3:int = 1000 # Overriding to do fewer resizes def increase_capacity(self:"DoublingVector3") -> int: if (self.capacity() <= self.doubling_limit // 2): self.items = self.items + self.items else: # If doubling limit has been reached, fall back to # standard capacity increases self.items = self.items + [0] return self.capacity() # Overriding to do fewer resizes def increase_capacity2(self:"DoublingVector3") -> int: if (self.capacity() <= self.doubling_limit // 2): self.items = self.items + self.items else: # If doubling limit has been reached, fall back to # standard capacity increases self.items = self.items + [0] return self.capacity() # Overriding to do fewer resizes def increase_capacity3(self:"DoublingVector3") -> int: if (self.capacity() <= self.doubling_limit // 2): self.items = self.items + self.items else: # If doubling limit has been reached, fall back to # standard capacity increases self.items = self.items + [0] return self.capacity() # A faster (but more memory-consuming) implementation of vector class DoublingVector4(Vector): doubling_limit:int = 1000 doubling_limit2:int = 1000 doubling_limit3:int = 1000 doubling_limit4:int = 1000 # Overriding to do fewer resizes def increase_capacity(self:"DoublingVector4") -> int: if (self.capacity() <= self.doubling_limit // 2): self.items = self.items + self.items else: # If doubling limit has been reached, fall back to # standard capacity increases self.items = self.items + [0] return self.capacity() # Overriding to do fewer resizes def increase_capacity2(self:"DoublingVector4") -> int: if (self.capacity() <= self.doubling_limit // 2): self.items = self.items + self.items else: # If doubling limit has been reached, fall back to # standard capacity increases self.items = self.items + [0] return self.capacity() # Overriding to do fewer resizes def increase_capacity3(self:"DoublingVector4") -> int: if (self.capacity() <= self.doubling_limit // 2): self.items = self.items + self.items else: # If doubling limit has been reached, fall back to # standard capacity increases self.items = self.items + [0] return self.capacity() # Overriding to do fewer resizes def increase_capacity4(self:"DoublingVector4") -> int: if (self.capacity() <= self.doubling_limit // 2): self.items = self.items + self.items else: # If doubling limit has been reached, fall back to # standard capacity increases self.items = self.items + [0] return self.capacity() # A faster (but more memory-consuming) implementation of vector class DoublingVector5(Vector): doubling_limit:int = 1000 doubling_limit2:int = 1000 doubling_limit3:int = 1000 doubling_limit4:int = 1000 doubling_limit5:int = 1000 # Overriding to do fewer resizes def increase_capacity(self:"DoublingVector5") -> int: if (self.capacity() <= self.doubling_limit // 2): self.items = self.items + self.items else: # If doubling limit has been reached, fall back to # standard capacity increases self.items = self.items + [0] return self.capacity() # Overriding to do fewer resizes def increase_capacity2(self:"DoublingVector5") -> int: if (self.capacity() <= self.doubling_limit // 2): self.items = self.items + self.items else: # If doubling limit has been reached, fall back to # standard capacity increases self.items = self.items + [0] return self.capacity() # Overriding to do fewer resizes def increase_capacity3(self:"DoublingVector5") -> int: if (self.capacity() <= self.doubling_limit // 2): self.items = self.items + self.items else: # If doubling limit has been reached, fall back to # standard capacity increases self.items = self.items + [0] return self.capacity() # Overriding to do fewer resizes def increase_capacity4(self:"DoublingVector5") -> int: if (self.capacity() <= self.doubling_limit // 2): self.items = self.items + self.items else: # If doubling limit has been reached, fall back to # standard capacity increases self.items = self.items + [0] return self.capacity() # Overriding to do fewer resizes def increase_capacity5(self:"DoublingVector5") -> int: if (self.capacity() <= self.doubling_limit // 2): self.items = self.items + self.items else: # If doubling limit has been reached, fall back to # standard capacity increases self.items = self.items + [0] return self.capacity() # Makes a vector in the range [i, j) def vrange(i:int, j:int) -> Vector: v:Vector = None v = DoublingVector() while i < j: v.append(i) i = i + 1 return v def vrange2(i:int, j:int, i2:int, j2:int) -> Vector: v:Vector = None v2:Vector = None v = DoublingVector() while i < j: v.append(i) i = i + 1 return v def vrange3(i:int, j:int, i2:int, j2:int, i3:int, j3:int) -> Vector: v:Vector = None v2:Vector = None v3:Vector = None v = DoublingVector() while i < j: v.append(i) i = i + 1 return v def vrange4(i:int, j:int, i2:int, j2:int, i3:int, j3:int, i4:int, j4:int) -> Vector: v:Vector = None v2:Vector = None v3:Vector = None v4:Vector = None v = DoublingVector() while i < j: v.append(i) i = i + 1 return v def vrange5(i:int, j:int, i2:int, j2:int, i3:int, j3:int, i4:int, j4:int, i5:int, j5:int) -> Vector: v:Vector = None v2:Vector = None v3:Vector = None v4:Vector = None v5:Vector = None v = DoublingVector() while i < j: v.append(i) i = i + 1 return v # Sieve of Eratosthenes (not really) def sieve(v:Vector) -> object: i:int = 0 j:int = 0 k:int = 0 while i < v.length(): k = v.get(i) j = i + 1 while j < v.length(): if v.get(j) % k == 0: v.remove_at(j) else: j = j + 1 i = i + 1 def sieve2(v:Vector, v2:Vector) -> object: i:int = 0 i2:int = 0 j:int = 0 j2:int = 0 k:int = 0 k2:int = 0 while i < v.length(): k = v.get(i) j = i + 1 while j < v.length(): if v.get(j) % k == 0: v.remove_at(j) else: j = j + 1 i = i + 1 def sieve3(v:Vector, v2:Vector, v3:Vector) -> object: i:int = 0 i2:int = 0 i3:int = 0 j:int = 0 j2:int = 0 j3:int = 0 k:int = 0 k2:int = 0 k3:int = 0 while i < v.length(): k = v.get(i) j = i + 1 while j < v.length(): if v.get(j) % k == 0: v.remove_at(j) else: j = j + 1 i = i + 1 def sieve4(v:Vector, v2:Vector, v3:Vector, v4:Vector) -> object: i:int = 0 i2:int = 0 i3:int = 0 i4:int = 0 j:int = 0 j2:int = 0 j3:int = 0 j4:int = 0 k:int = 0 k2:int = 0 k3:int = 0 k4:int = 0 while i < v.length(): k = v.get(i) j = i + 1 while j < v.length(): if v.get(j) % k == 0: v.remove_at(j) else: j = j + 1 i = i + 1 def sieve5(v:Vector, v2:Vector, v3:Vector, v4:Vector, v5:Vector) -> object: i:int = 0 i2:int = 0 i3:int = 0 i4:int = 0 i5:int = 0 j:int = 0 j2:int = 0 j3:int = 0 j4:int = 0 j5:int = 0 k:int = 0 k2:int = 0 k3:int = 0 k4:int = 0 k5:int = 0 while i < v.length(): k = v.get(i) j = i + 1 while j < v.length(): if v.get(j) % k == 0: v.remove_at(j) else: j = j + 1 i = i + 1 # Input parameter n:int = 50 n2:int = 50 n3:int = 50 n4:int = 50 n5:int = 50 # Data v:Vector = None v2:Vector = None v3:Vector = None v4:Vector = None v5:Vector = None i:int = 0 i2:int = 0 i3:int = 0 i4:int = 0 i5:int = 0 # Crunch v = vrange(2, n) v2 = vrange(2, n) v3 = vrange(2, n) v4 = vrange(2, n) v5 = vrange(2, n) sieve(v) # Print while i < v.length(): print(v.get(i)) i = i + 1
c9816561b3e191bbcd544b2288a6e29705b965fe
60dd6073a3284e24092620e430fd05be3157f48e
/tiago_public_ws/build/pal_gripper/pal_gripper/catkin_generated/pkg.develspace.context.pc.py
ffa8184246ae074a71bbd494df35fa3b06cbfed1
[]
no_license
SakshayMahna/Programming-Robots-with-ROS
e94d4ec5973f76d49c81406f0de43795bb673c1e
203d97463d07722fbe73bdc007d930b2ae3905f1
refs/heads/master
2020-07-11T07:28:00.547774
2019-10-19T08:05:26
2019-10-19T08:05:26
204,474,383
0
0
null
null
null
null
UTF-8
Python
false
false
417
py
# generated from catkin/cmake/template/pkg.context.pc.in CATKIN_PACKAGE_PREFIX = "" PROJECT_PKG_CONFIG_INCLUDE_DIRS = "".split(';') if "" != "" else [] PROJECT_CATKIN_DEPENDS = "".replace(';', ' ') PKG_CONFIG_LIBRARIES_WITH_PREFIX = "".split(';') if "" != "" else [] PROJECT_NAME = "pal_gripper" PROJECT_SPACE_DIR = "/media/root/BuntuDrive/Programming-Robots-with-ROS/tiago_public_ws/devel" PROJECT_VERSION = "1.0.2"
f903c442aee0263c16da660e86b0ec16555e3da6
d45de88d276bfa76ad0345b718c50f5d3c0f3d7f
/days_until_event.py
c3d8fafc5001f53f473ee5c63372eb3e0ab29e38
[]
no_license
donniewherman/Pythonista_scene
3c6d5ffa07f4c63fe06ee75d54937c8ea98387e8
11e43bf94c70c10fe74f931a7ab43df9ccf4e3d1
refs/heads/master
2021-01-17T06:00:12.676067
2015-08-07T21:40:41
2015-08-07T21:40:41
42,383,096
1
0
null
2015-09-13T04:02:48
2015-09-13T04:02:47
null
UTF-8
Python
false
false
1,217
py
# See: https://omz-forums.appspot.com/pythonista/post/6142748495183872 import console, datetime, scene fmt = '{} is {} days away.' class days_until_event(scene.Scene): def __init__(self, event_name, event_date): self.event_name = event_name self.event_date = event_date scene.run(self) def setup(self): self.center = self.bounds.center() self.font_size = 64 if self.size.w > 700 else 32 def draw(self): scene.background(0, 0, 0) msg = fmt.format(self.event_name, (self.event_date - datetime.date.today()).days) scene.text(msg, 'Futura', self.font_size, *self.center) prompt = '''Please enter the event name. i.e. First day of school''' event_name = console.input_alert('Event', prompt, '', 'Enter').strip() or 'My event' prompt = '''Please enter the date you would like to countdown to. i.e. 2009 (year),6 (month),29 (day)''' event_date = console.input_alert('Date', prompt, '', 'Enter') try: year, month, day = [int(s.strip()) for s in event_date.split(',')] event_date = datetime.date(year, month, day) except ValueError: exit('Incorrect date format (must be "year, month, day")') days_until_event(event_name, event_date)
a6c70a7e6b270d06977f70f509ce24378ca308aa
bf542e318773faaaa48931f08f64264748514024
/utils/sub8_ros_tools/sub8_misc_tools/__init__.py
d501d40f359d107e294b89b9839daf1c0dab63bb
[ "MIT" ]
permissive
guojiyao/Sub8
3b30f517e65cf127fd1e6ee797e4318c8c4be227
6de4bcf20eb2863ec0d06234539ffb19892009f7
refs/heads/master
2020-05-21T10:12:18.471001
2016-03-29T00:45:35
2016-03-29T00:45:35
54,933,672
0
0
null
2016-03-29T00:37:37
2016-03-29T00:37:36
null
UTF-8
Python
false
false
69
py
from download import download_and_unzip from download import download
8f362b8ed7c76e2766013bb4e6803278ae161094
981d425745639e5338de6847184fac2ab0175ce8
/src/test.py
087de4f1eb7b797d4bdeeecfa6a5b65c9a23e61e
[]
no_license
exploring-realities/Mobi
17f06dd0fcdda30eab9519992d29d2530f4bc307
f6f0e5d779424979d32e8175066bebe83399f289
refs/heads/master
2021-07-06T05:28:15.451058
2017-10-01T22:53:00
2017-10-01T22:53:00
null
0
0
null
null
null
null
UTF-8
Python
false
false
275
py
#!/usr/bin/python import datetime import crawler now = datetime.datetime.now() on = str(now.day) + "." + str(now.month) + "." + str(now.year) at = str(now.hour) + ":" + str(now.minute) response_json = crawler.request_station_info("Hallerstrasse", at, on) print response_json
d432478397bf133a423bca8172f73dfbdf6dd036
a34e3d435f48ef87477d3ae13ca8a43015e5052c
/pyopengl2.py
788e2feeea3f13c7cc5bba01fafc836249f2b5da
[]
no_license
haehn/sandbox
636069372fc7bb7fd72b5fde302f42b815e8e9b0
e49a0a30a1811adb73577ff697d81db16ca82808
refs/heads/master
2021-01-22T03:39:03.415863
2015-02-11T23:16:22
2015-02-11T23:16:22
26,128,048
1
0
null
null
null
null
UTF-8
Python
false
false
6,880
py
import sys from OpenGL.GLUT import * from OpenGL.GL import * from OpenGL.GLU import * from OpenGL.GL import shaders from OpenGL.arrays import vbo # from vrml.arrays import * from numpy import concatenate, identity, transpose, multiply import numpy from datetime import datetime class Sample15: def __init__(self): self.current_time = None self.current_angle = 0.0 vertex_shader = shaders.compileShader(""" attribute vec4 vPosition; attribute vec4 vColor; uniform mat4 modelMatrix; uniform float rotationAngle; varying vec4 varyingColor; // function from http://www.neilmendoza.com/glsl-rotation-about-an-arbitrary-axis/ mat4 rotationMatrix(vec3 axis, float angle) { axis = normalize(axis); float s = sin(angle); float c = cos(angle); float oc = 1.0 - c; return mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0, oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0, oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0, 0.0, 0.0, 0.0, 1.0); } void main() { mat4 rotation = rotationMatrix(vec3(0.1, 0.2, 0.3), rotationAngle); gl_Position = modelMatrix * rotation * vPosition; varyingColor = vColor; }""", GL_VERTEX_SHADER) fragment_shader = shaders.compileShader(""" varying vec4 varyingColor; void main() { gl_FragColor = varyingColor; }""", GL_FRAGMENT_SHADER) self.shader = shaders.compileProgram(vertex_shader, fragment_shader) shaders.glUseProgram(self.shader) self.position_location = glGetAttribLocation( self.shader, 'vPosition' ) self.color_location = glGetAttribLocation( self.shader, 'vColor' ) self.model_matrix_location = glGetUniformLocation( self.shader, 'modelMatrix' ) self.rotation_angle_location = glGetUniformLocation( self.shader, 'rotationAngle' ) vertex_positions = numpy.array([ -1.0, -1.0, -1.0, 1.0, -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, -1.0, 1.0, -1.0, 1.0, 1.0, 1.0, 1.0, -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 1.0, 1.0, 1.0 ], dtype=numpy.float32) vertex_colors = numpy.array([ 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.5, 0.5, 0.5, 1.0 ], dtype=numpy.float32) self.vertex_buffer_object = vbo.VBO(concatenate((vertex_positions, vertex_colors))) self.vertex_buffer_object.bind() self.vertex_indices = vbo.VBO( numpy.array([ 0, 1, 2, 3, 6, 7, 4, 5, 0xFFFF, 2, 6, 0, 4, 1, 5, 3, 7 ], dtype=numpy.uint32), target=GL_ELEMENT_ARRAY_BUFFER) self.vertex_indices.bind() glEnable(GL_PRIMITIVE_RESTART) glPrimitiveRestartIndex(0xFFFF) glVertexAttribPointer( self.position_location, 4, GL_FLOAT, False, 0, self.vertex_buffer_object ) glEnableVertexAttribArray(self.position_location) glVertexAttribPointer( self.color_location, 4, GL_FLOAT, False, 0, self.vertex_buffer_object + vertex_positions.nbytes ) glEnableVertexAttribArray(self.color_location) glEnable(GL_DEPTH_TEST) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glBlendEquation(GL_FUNC_SUBTRACT) render_buffer_color = glGenRenderbuffers(1) render_buffer_depth = glGenRenderbuffers(1) glBindRenderbuffer(GL_RENDERBUFFER, render_buffer_color) glRenderbufferStorage(GL_RENDERBUFFER, GL_RGBA, 256, 256) glBindRenderbuffer(GL_RENDERBUFFER, render_buffer_depth) glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, 256, 256) self.framebuffer = glGenFramebuffers(1) glBindFramebuffer(GL_DRAW_FRAMEBUFFER, self.framebuffer) glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, render_buffer_color) glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, render_buffer_depth) def display(self): if self.current_time is None: self.current_time = datetime.now() self.delta_time = datetime.now() - self.current_time self.current_time = datetime.now() self.current_angle += 0.000002 * self.delta_time.microseconds print self.current_angle try: # Prepare to render into the renderbuffer glBindFramebuffer(GL_DRAW_FRAMEBUFFER, self.framebuffer) glViewport(0, 0, 125, 125) # Render into renderbuffer glClearColor (1.0, 0.0, 0.0, 1.0) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) translation_matrix = identity(4, 'f') # really it scale matrix there translation_matrix[-1][-1] = 2 glUniformMatrix4fv(self.model_matrix_location, 1 , GL_TRUE, translation_matrix.tolist()) glUniform1f(self.rotation_angle_location, self.current_angle) glDrawElements(GL_TRIANGLE_STRIP, 17, GL_UNSIGNED_INT, self.vertex_indices) # Set up to read from the renderbuffer and draw to window-system framebuffer glBindFramebuffer(GL_READ_FRAMEBUFFER, self.framebuffer) glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0) glViewport(0, 0, 250, 250) glClearColor(0.0, 0.0, 1.0, 1.0) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) # Do the copy glBlitFramebuffer(0, 0, 125, 125, 0, 0, 125, 125, GL_COLOR_BUFFER_BIT, GL_NEAREST) glutSwapBuffers() finally: glFlush() glutPostRedisplay() if __name__ == '__main__': glutInit(sys.argv) glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB | GLUT_DEPTH | GLUT_STENCIL) glutInitWindowSize(250, 250) glutInitWindowPosition(100, 100) glutCreateWindow("sample 15") sample = Sample15() glutDisplayFunc(sample.display) glutIdleFunc(sample.display) glutMainLoop()
267300a0c6be411af5da94c956325769ac8c743b
15f321878face2af9317363c5f6de1e5ddd9b749
/solutions_python/Problem_55/726.py
2e1116bc8beaa4f056422822aff316eb7493302d
[]
no_license
dr-dos-ok/Code_Jam_Webscraper
c06fd59870842664cd79c41eb460a09553e1c80a
26a35bf114a3aa30fc4c677ef069d95f41665cc0
refs/heads/master
2020-04-06T08:17:40.938460
2018-10-14T10:12:47
2018-10-14T10:12:47
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,012
py
#!/usr/bin/env python import sys def Take(k, gs, i): 'Memoize this.' queue = gs[i:] + gs[:i] taken = 0 N = len(gs) f = 0 while k and f < N: next_group = queue[f] if next_group > k: break k -= next_group taken += next_group f += 1 return taken, f+i def Euros(R, k, gs): i = 0 euros = 0 N = len(gs) _done = dict() while R: if i not in _done: _done[i] = Take(k, gs, i) (taken, i) = _done[i] if taken == 0: # We can go no further! return euros #print taken, i euros += taken i = i % N R -= 1 return euros def main(): it = iter(sys.stdin) T = int(next(it)) for x in range(1, T+1): R, k, N = map(int, next(it).split()) gs = map(int, next(it).split()) assert len(gs) == N y = Euros(R, k, gs) print "Case #%d: %d" %(x, y) if __name__=='__main__': main()
4bfb6153a6a1331122310bcd35d0ddd45cc654dd
86c85939a566e11c87ef0cd0668ba2dd29e83b7b
/tests/core/val-type/test_val_type.py
d518d13effb9aaecb0cd406d03956f131791d13a
[ "NCSA", "LicenseRef-scancode-unknown-license-reference" ]
permissive
ethereum/py-wasm
eca49823f5a683f125d89ed6a9c45e5f5eee7139
41a6d07a620dfc4f590463dd038dffe4efe0c8c6
refs/heads/master
2023-08-02T00:39:43.402121
2019-03-05T03:29:25
2019-03-05T03:29:25
161,232,280
94
20
NCSA
2023-02-17T18:50:24
2018-12-10T20:25:19
Python
UTF-8
Python
false
false
1,965
py
import itertools import pytest from wasm.datatypes import ( BitSize, ValType, ) @pytest.mark.parametrize( 'get_X_type,bit_size', itertools.product( [ValType.get_integer_type, ValType.get_float_type], (0, 31, 33, 63, 65, BitSize.b8, BitSize.b16), ), ) def test_get_X_type_invalid_bit_size(get_X_type, bit_size): with pytest.raises(ValueError): get_X_type(bit_size) @pytest.mark.parametrize( 'value,expected', ( (BitSize.b32, ValType.f32), (BitSize.b64, ValType.f64), ) ) def test_get_float_type(value, expected): actual = ValType.get_float_type(value) # using `is` comparison here to ensure that we are using the same object, # not just an equal string. assert actual is expected @pytest.mark.parametrize( 'value,expected', ( (BitSize.b32, ValType.i32), (BitSize.b64, ValType.i64), ) ) def test_get_integer_type(value, expected): actual = ValType.get_integer_type(value) # using `is` comparison here to ensure that we are using the same object, # not just an equal string. assert actual is expected @pytest.mark.parametrize( 'value,expected', ( (ValType.f32, True), (ValType.f64, True), (ValType.i32, False), (ValType.i64, False), ) ) def test_is_float_type(value, expected): assert value.is_float_type is expected @pytest.mark.parametrize( 'value,expected', ( (ValType.f32, False), (ValType.f64, False), (ValType.i32, True), (ValType.i64, True), ) ) def test_is_integer_type(value, expected): assert value.is_integer_type is expected @pytest.mark.parametrize( 'value,expected', ( (ValType.f32, BitSize.b32), (ValType.f64, BitSize.b64), (ValType.i32, BitSize.b32), (ValType.i64, BitSize.b64), ), ) def test_get_bit_size(value, expected): assert value.bit_size == expected
89c182daa5b7726cb8251be1c823b804cda7fcad
2f98aa7e5bfc2fc5ef25e4d5cfa1d7802e3a7fae
/python/python_18429.py
359b1b34ef43ef6954446d0b6d9a5e7a29cc9db7
[]
no_license
AK-1121/code_extraction
cc812b6832b112e3ffcc2bb7eb4237fd85c88c01
5297a4a3aab3bb37efa24a89636935da04a1f8b6
refs/heads/master
2020-05-23T08:04:11.789141
2015-10-22T19:19:40
2015-10-22T19:19:40
null
0
0
null
null
null
null
UTF-8
Python
false
false
172
py
# ImportError: No module named PyQt5 - OSX Mavericks export set PYTHONPATH=$PYTHONPATH:/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages
c432933ce0fe73abcaf7f23a86fb750a7156178d
145205b1b9b9042a5809bf10c05b546be2f27f6f
/chapter07/interface_demo.py
a0b503cdd5a26b870bfa47440dd50e7e300bc64d
[]
no_license
tangkaiyang/python_interface_development_and_testing
43ff43ee86788bcb5c07a26d81e8eef0294771ca
1349d309a2b551f17de3aaff266548e53dd10c4b
refs/heads/master
2020-04-25T02:06:43.543323
2019-03-13T06:32:10
2019-03-13T06:32:10
172,427,886
0
0
null
null
null
null
UTF-8
Python
false
false
457
py
from zope.interface import Interface from zope.interface.declarations import implementer # 定义接口 class IHost(Interface): def goodmorning(self, host): """Say good morning to host""" @implementer(IHost) # 继承接口 class Host: def goodmorning(self, guest): """Say good morning to guest""" return "Good morning, %s!" % guest if __name__ == '__main__': p = Host() hi = p.goodmorning('Tom') print(hi)
216517ac51305fb90d8b4e5ea4fb6742af575ab2
5a52ccea88f90dd4f1acc2819997fce0dd5ffb7d
/alipay/aop/api/response/AlipayEbppInvoiceEnterpriseconsumeEnterpriseopenruleQueryResponse.py
5bb6da84803ce7b34c17434f46cfbd99b4b8b08a
[ "Apache-2.0" ]
permissive
alipay/alipay-sdk-python-all
8bd20882852ffeb70a6e929038bf88ff1d1eff1c
1fad300587c9e7e099747305ba9077d4cd7afde9
refs/heads/master
2023-08-27T21:35:01.778771
2023-08-23T07:12:26
2023-08-23T07:12:26
133,338,689
247
70
Apache-2.0
2023-04-25T04:54:02
2018-05-14T09:40:54
Python
UTF-8
Python
false
false
1,200
py
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.response.AlipayResponse import AlipayResponse from alipay.aop.api.domain.EnterpriseOpenRuleInfo import EnterpriseOpenRuleInfo class AlipayEbppInvoiceEnterpriseconsumeEnterpriseopenruleQueryResponse(AlipayResponse): def __init__(self): super(AlipayEbppInvoiceEnterpriseconsumeEnterpriseopenruleQueryResponse, self).__init__() self._enterprise_open_rule_info = None @property def enterprise_open_rule_info(self): return self._enterprise_open_rule_info @enterprise_open_rule_info.setter def enterprise_open_rule_info(self, value): if isinstance(value, EnterpriseOpenRuleInfo): self._enterprise_open_rule_info = value else: self._enterprise_open_rule_info = EnterpriseOpenRuleInfo.from_alipay_dict(value) def parse_response_content(self, response_content): response = super(AlipayEbppInvoiceEnterpriseconsumeEnterpriseopenruleQueryResponse, self).parse_response_content(response_content) if 'enterprise_open_rule_info' in response: self.enterprise_open_rule_info = response['enterprise_open_rule_info']
14e4a43f8a1d2f0490b0464b20eace77b3771c27
f43c8f0f722df416890042555f3ab340af4148c5
/misc-scripts/parseglobalma.py
8bd9407156bf3f6972c636351178014131a2ef92
[ "MIT" ]
permissive
RenaKunisaki/StarFoxAdventures
98e0b11df4f8b28bbe5eabe203b768ecfc01f1e7
f7dc76f11f162d495cd86ca819f911946e5bfecd
refs/heads/master
2023-07-23T18:45:34.192956
2023-07-10T19:19:43
2023-07-10T19:19:43
211,404,362
30
5
MIT
2022-05-05T20:10:19
2019-09-27T21:27:49
C
UTF-8
Python
false
false
16,205
py
#!/usr/bin/env python3 """Read GLOBALMA.bin and generate a map grid image.""" import sys import math import struct from PIL import Image, ImageDraw, ImageFont def printf(fmt, *args, **kwargs): print(fmt % args, end='', **kwargs) def readStruct(file, fmt, offset=None): size = struct.calcsize(fmt) if offset is not None: file.seek(offset) data = file.read(size) r = struct.unpack(fmt, data) if len(r) == 1: return r[0] # grumble return r def _mapIdToColor(id): n = id + 1 id = 0 for i in range(8): id |= ((n >> i) & 1) << i r = ((id >> 1) & 3) / 3 g = ((id >> 3) & 7) / 7 b = ((id >> 6) & 3) / 3 return int(r*255), int(g*255), int(b*255) def _mapIdToHtml(id): r, g, b = _mapIdToColor(id) return '#%02X%02X%02X' % (r, g, b) class MapGrid: def __init__(self, width, height, originX=0, originY=0): self.grid = [] self.width, self.height = width, height self.originX, self.originY = originX, originY self.xMin, self.yMin = 999999, 999999 self.xMax, self.yMax = -self.xMin, -self.yMin for y in range(self.height - self.originY): for x in range(self.width): self.grid.append(None) def _checkCoords(self, x, y): idx = ((y - self.originY) * self.width) + (x - self.originX) if idx < 0 or idx >= len(self.grid): raise KeyError("Coords %d, %d out of range for grid %d,%d - %d,%d" % ( x, y, self.originX, self.originY, self.width - self.originX, self.height - self.originY)) return idx def set(self, x, y, val): idx = self._checkCoords(x, y) self.grid[idx] = val self.xMin = min(x, self.xMin) self.yMin = min(y, self.yMin) self.xMax = max(x, self.xMax) self.yMax = max(y, self.yMax) def get(self, x, y): idx = self._checkCoords(x, y) return self.grid[idx] class MapGridCell: def __init__(self, x, y, layer, map, link1, link2): self.x, self.y = x, y self.layer, self.map = layer, map self.linked = [link1, link2] @classmethod def read(cls, file): x, y, ly, map, l1, l2 = readStruct(file, '>6h') if map < 0: return None return MapGridCell(x, y, ly, map, l1, l2) class MapReader: MIN_LAYER = -2 MAX_LAYER = 2 def __init__(self, discroot:str): self.root = discroot self.layer = {} for i in range(self.MIN_LAYER, self.MAX_LAYER+1): self.layer[i] = MapGrid(1024, 1024, -512, -512) def run(self): cells = self.readGlobalMap() self.maps = self.readMapsBin() # plot maps on grid for cell in cells: if cell.map >= 0 and cell.map < len(self.maps): map = self.maps[cell.map] for y in range(map['h']): for x in range(map['w']): gx = (x + cell.x) - map['x'] gy = (y + cell.y) - map['y'] bi = (y * map['w']) + x block = map['blocks'][bi] self.layer[cell.layer].set(gx, gy, { 'map': map, 'block': block, 'cell': cell, }) else: printf("Map %r is not in MAPS.bin\n", cell.map) self.warps = self.readWarpTab() self.mapInfo = self.readMapInfo() for i, layer in self.layer.items(): self.layerToImage(layer, i) # self.printLayer(layer, i) #with open('globalmap.html', 'wt') as outFile: # outFile.write('<html><head>') # outFile.write('<link rel="stylesheet" href="globalmap.css" />') # outFile.write('</head><body>') # for i, layer in self.layer.items(): # outFile.write('<h1>Layer %d</h1>' % i) # outFile.write(self.layerToHtml(layer, i)) # outFile.write('</body></html>') def readGlobalMap(self, path='/globalma.bin'): cells = [] with open(self.root+path, 'rb') as globalMa: while True: cell = MapGridCell.read(globalMa) if cell is None: break cells.append(cell) return cells def readMapsBin(self, path='/'): entries = [] try: bin = open(self.root+path+'MAPS.bin', 'rb') tab = open(self.root+path+'MAPS.tab', 'rb') idx = 0 while True: try: tabEntries = readStruct(tab, '>7i') except struct.error as ex: # we should be checking for an entry of 0xFFFFFFFF # but that requires reading them one by one break if tabEntries[0] < 0: break printf("MAPS.tab %02X = %08X %08X %08X %08X %08X %08X %08X\n", idx, *tabEntries) entry = { 'tab': tabEntries, 'map': idx, 'blocks': [], } entries.append(entry) try: bin.seek(tabEntries[0]) data = bin.read(8) if data.startswith(b'\xFA\xCE\xFE\xED'): printf("Map %02d blocks = FACEFEED\n", idx) idx += 1 continue w, h, x, y = struct.unpack('>4h', data) except struct.error as ex: printf("Error reading MAPS.bin entry at 0x%X: %s\n", bin.tell(), ex) break entry['x'], entry['y'], entry['w'], entry['h'] = x,y,w,h #printf("Map %02X rect is %d, %d, %dx%d\n", idx, x, y, w, h) bin.seek(tabEntries[1]) for i in range(w*h): try: block = readStruct(bin, '>I') except struct.error as ex: printf("Error reading block entry at 0x%X: %s\n", bin.tell(), ex) break unk1 = block >> 31 mod = (block >> 23) & 0xFF sub = (block >> 17) & 0x3F unk2 = block & 0x1FF entry['blocks'].append({ 'mod': mod, 'sub': sub, 'unk': (unk1, unk2) }) idx += 1 return entries finally: bin.close() tab.close() def readWarpTab(self, path="/WARPTAB.bin"): entries = [] with open(self.root+path, 'rb') as file: i = 0 while True: try: x, y, z, ly, ang = readStruct(file, '>3f2h') except struct.error: break # there's no end-of-file marker here... # for some reason angle is only the high byte of an s16, # even though it's stored as a full s16 itself. # ie it ranges from -128 to 127. entries.append({ 'x':x, 'y':y, 'z':z, 'cx':math.floor(x/640), 'cz':math.floor(z/640), 'idx':i, 'layer':ly, 'angle':(ang / 128) * 180, }) return entries def readMapInfo(self, path="/MAPINFO.bin"): maps = [] with open(self.root+path, 'rb') as file: while True: try: name, typ, unk2, unk3 = readStruct(file, '>28s2bh') except struct.error: break maps.append({ 'name': name.replace(b'\0', b'').decode('utf-8'), 'type': typ, 'unk2': unk2, 'unk3': unk3, }) return maps def printLayer(self, layer, id): printf("Layer %d is %d, %d - %d, %d\n ", id, layer.xMin, layer.yMin, layer.xMax, layer.yMax) for x in range(layer.xMin, layer.xMax+1): printf("%2d", abs(x)) printf("\n") for y in range(layer.yMin, layer.yMax+1): printf("%4d│", y) for x in range(layer.xMin, layer.xMax+1): cell = layer.get(x, y) col = (x & 1) ^ (y & 1) col = 19 if col == 0 else 17 printf("\x1B[48;5;%d;38;5;8m", col) if cell is None: printf(" ") else: map = cell['map'] block = cell['block'] if block['mod'] == 0xFF: printf("%02X", map['map']) else: printf("\x1B[38;5;15m%02X", map['map']) printf("\x1B[0m\n") def layerToImage(self, layer, id): scale = 16 lw = layer.xMax - layer.xMin lh = layer.yMax - layer.yMin w = lw * scale h = lh * scale img = Image.new('RGBA', (w+1, h+1), (32, 32, 32, 255)) draw = ImageDraw.Draw(img) maps = {} fnt = ImageFont.truetype( '/usr/share/fonts/TTF/DejaVuSans.ttf', 13) # plot the grid for y in range(layer.yMin, layer.yMax+1): for x in range(layer.xMin, layer.xMax+1): px = (x-layer.xMin) * scale py = (lh-(y-layer.yMin)) * scale cell = layer.get(x, y) if cell is not None: map = cell['map'] block = cell['block'] r, g, b = _mapIdToColor(map['map']) #r, g, b = 192, 192, 192 draw.rectangle( (px, py, px+scale, py+scale), # x0 y0 x1 y1 fill=(r, g, b, 255), outline=(128, 128, 128, 255)) if block['mod'] == 0xFF: draw.rectangle( (px, py, px+scale, py+scale), # x0 y0 x1 y1 fill=(r//2, g//2, b//2, 255), outline=(128, 128, 128, 255)) draw.line((px, py, px+scale, py+scale), fill=(128, 128, 128, 255), width=1) mapId = map['map'] if mapId not in maps: maps[mapId] = { 'xMin':x, 'yMin':y, 'xMax':x, 'yMax':y} else: m = maps[mapId] m['xMin'] = min(m['xMin'], x) m['yMin'] = min(m['yMin'], y) m['xMax'] = max(m['xMax'], x) m['yMax'] = max(m['yMax'], y) else: draw.rectangle( (px, py, px+scale, py+scale), # x0 y0 x1 y1 fill=None, outline=(64, 64, 64, 255)) # draw warps for i, warp in enumerate(self.warps): if warp['layer'] == id: angle = warp['angle'] - 90 wx, wy = warp['cx'], warp['cz'] wx = (wx - layer.xMin) * scale wy = (lh-(wy-layer.yMin)) * scale draw.pieslice(( wx, wy, wx+scale, wy+scale ), angle-20, angle+20, fill=(255, 0, 0, 128), outline=(255, 255, 255, 255), ) #draw.text((wx+scale, wy), "%02X" % i, # fill=(255, 255, 255, 255), # font=fnt, stroke_width=1, stroke_fill=(0, 0, 0, 128)) # put map names over cells for mapId, map in maps.items(): x0, y0 = map['xMin'], map['yMin']-1 x1, y1 = map['xMax']+1, map['yMax'] px0 = (x0-layer.xMin) * scale py0 = (lh-(y0-layer.yMin)) * scale px1 = (x1-layer.xMin) * scale py1 = (lh-(y1-layer.yMin)) * scale pw = px1 - px0 ph = py1 - py0 #r, g, b = _mapIdToColor(mapId) r, g, b = 192, 192, 192 draw.rectangle((px0, py0, px1, py1), outline=(r, g, b, 255)) # draw name text = "%02X %s" % (mapId, self.mapInfo[mapId]['name']) size = draw.textsize(text, font=fnt, stroke_width=1) tx = px0 + (pw/2) - (size[0]/2) ty = py0 + (ph/2) - (size[1]/2) if tx < 0: tx = 0 # HACK if mapId == 0x37: ty += 16 #if ty < 0: ty = py0 + 2 #draw.text((tx, ty), text, fill=(r, g, b, 255), # font=fnt, stroke_width=1, stroke_fill=(0, 0, 0, 128)) img.save("layer%d.png" % id, "PNG") def layerToHtml(self, layer, id): elems = ['<table><tr><th></th>'] for x in range(layer.xMin, layer.xMax+1): elems.append('<th>%d</th>' % x) elems.append('</tr>') for y in range(layer.yMax, layer.yMin-1, -1): elems.append('<tr><th>%d</th>' % y) for x in range(layer.xMin, layer.xMax+1): # this is slow but who cares warpIdx = -1 for i, warp in enumerate(self.warps): if (warp['layer'] == id and warp['cx'] == x and warp['cz'] == y): warpIdx = i break cell = layer.get(x, y) if cell is None: if warpIdx >= 0: title = "%d, %d: no map\nWarp #%02X" % ( x, y, warpIdx) elems.append('<td class="empty warp" title="%s">W%02X</td>' % ( title, warpIdx)) else: elems.append('<td class="empty"></td>') else: map = cell['map'] block = cell['block'] cls = 'map%02X' % map['map'] style = 'background:'+_mapIdToHtml(map['map']) if block['mod'] == 0xFF: cls += ' oob' title = "%d, %d: out of bounds\n%02X %s" % ( x, y, map['map'], self.mapInfo[map['map']]['name']) else: title = "%d, %d (%d, %d): mod%d.%d\n%02X %s" % ( x, y, x*640, y*640, block['mod'], block['sub'], map['map'], self.mapInfo[map['map']]['name']) if warpIdx >= 0: cls += ' warp' title += "\nWarp #%02X" % warpIdx warpIdx = 'W%02X' % warpIdx else: warpIdx = '' text = '%02X %s\n%3d.%2d' % ( map['map'], warpIdx, block['mod'], block['sub'] ) if cell['cell'].linked[0] != -1: cls += ' link' links = [] link1 = cell['cell'].linked[0] link2 = cell['cell'].linked[1] if link1 >= 0: links.append('%02X %s' % (link1, self.mapInfo[link1]['name'])) if link2 >= 0: links.append('%02X %s' % (link2, self.mapInfo[link2]['name'])) title += '\nLinked: ' + ', '.join(links) elems.append( '<td class="%s" style="%s" title="%s">%s</td>' % ( cls, style, title, text)) elems.append('</tr>') elems.append('</table>') return ''.join(elems) if __name__ == '__main__': if len(sys.argv) > 1: m = MapReader(sys.argv[1]) m.run() else: print("Usage: %s disc-root-path" % sys.argv[0])
5f28a9aefa463f398ffd5a49c5f88a2014da21b2
a8f3204139d7f68c23bd8411b8594899ba792e79
/test/test_mgi.py
9355c91926884348daa41be469666e8d52450f2a
[ "BSD-3-Clause" ]
permissive
switt4/sequana
874189c869ccc07a592c0a6a3c77999adcabe025
7bd4f32607d62bebfd709628abc25bfda504761b
refs/heads/master
2023-02-13T13:06:26.021426
2020-12-01T14:49:02
2020-12-01T14:49:02
null
0
0
null
null
null
null
UTF-8
Python
false
false
170
py
from sequana.mgi import MGI from sequana import sequana_data def test_mgi(): m = MGI(sequana_data("test_mgi.fqStat.txt")) m.plot_acgt() m.boxplot_quality()
587d5499f4095c8e2541f77a2b56546daa77f7a1
ecee6e84ba18100b621c7e06f493ae48e44a34fe
/build/navigation/rotate_recovery/catkin_generated/pkg.develspace.context.pc.py
8169a859e64afd3b5511ba8fc9b971732b77cb60
[]
no_license
theleastinterestingcoder/Thesis
6d59e06b16cbe1588a6454689248c88867de2094
3f6945f03a58f0eff105fe879401a7f1df6f0166
refs/heads/master
2016-09-05T15:30:26.501946
2015-05-11T14:34:15
2015-05-11T14:34:15
31,631,628
0
0
null
null
null
null
UTF-8
Python
false
false
544
py
# generated from catkin/cmake/template/pkg.context.pc.in CATKIN_PACKAGE_PREFIX = "" PROJECT_PKG_CONFIG_INCLUDE_DIRS = "/home/alfred/quan_ws/src/navigation/rotate_recovery/include".split(';') if "/home/alfred/quan_ws/src/navigation/rotate_recovery/include" != "" else [] PROJECT_CATKIN_DEPENDS = "roscpp;pluginlib".replace(';', ' ') PKG_CONFIG_LIBRARIES_WITH_PREFIX = "-lrotate_recovery".split(';') if "-lrotate_recovery" != "" else [] PROJECT_NAME = "rotate_recovery" PROJECT_SPACE_DIR = "/home/alfred/quan_ws/devel" PROJECT_VERSION = "1.13.0"
a501a4ab05f3d9e89675e2356cd1b41b8b15c30b
a995f917e307be0d427cc9cfd3dbdd045abdd097
/算法基础课/1.基础算法/AcWing 787. 归并排序.py
e744c5c260576841526218d12f96711f9577710f
[]
no_license
Andrewlearning/Leetcoding
80d304e201588efa3ac93626021601f893bbf934
819fbc523f3b33742333b6b39b72337a24a26f7a
refs/heads/master
2023-04-02T09:50:30.501811
2023-03-18T09:27:24
2023-03-18T09:27:24
243,919,298
1
4
null
null
null
null
UTF-8
Python
false
false
1,080
py
def merge_sort(arr, l, r, temp): if l >= r: return # 1.选取中点 mid = (l + r) // 2 # 2.递归排序 merge_sort(arr, l, mid, temp) merge_sort(arr, mid + 1, r, temp) # 3.归并操作,原数组的左右两半指针 i = l j = mid + 1 # temp数组的指针 k = 0 while (i <= mid and j <= r): if arr[i] <= arr[j]: temp[k] = arr[i] i += 1 else: temp[k] = arr[j] j += 1 k += 1 while i <= mid: temp[k] = arr[i] i += 1 k += 1 while j <= r: temp[k] = arr[j] j += 1 k += 1 # temp记录排序好的数组 # 然后更新到原数组上 i, j = l, 0 while i <= r: arr[i] = temp[j] i += 1 j += 1 if __name__ == '__main__': n = int(input()) lst = list(map(int, input().split())) temp = [0] * n merge_sort(lst, 0, len(lst) - 1, temp) print(' '.join(map(str, lst))) # 链接:https://www.acwing.com/activity/content/code/content/111492/
972744e8cd7d968799613fd102bb9eb9d912e243
33195bfc9e62bb00ce54f050febb6a3a0929a34b
/ms_face_api/src/ms_face_api/face.py
f4e45a229df977cece372f41acae8dfe64ccfceb
[ "MIT" ]
permissive
LCAS/ros_web_apis
8f48e08b52433d6d97173cac1debd45a41681110
4b42bcc3c970769e8c814525e566ae37b506f415
refs/heads/master
2021-10-24T20:33:27.444877
2019-03-28T15:54:42
2019-03-28T15:54:42
82,785,629
0
4
MIT
2019-03-28T15:54:43
2017-02-22T09:25:33
Python
UTF-8
Python
false
false
6,400
py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ File: face.py Description: Face section of the Cognitive Face API. """ from . import util def detect(image, face_id=True, landmarks=False, attributes=''): """Detect human faces in an image and returns face locations, and optionally with `face_id`s, landmarks, and attributes. Args: image: A URL or a file path or a file-like object represents an image. face_id: Optional parameter. Return `face_id`s of the detected faces or not. The default value is `True`. landmarks: Optional parameter. Return face landmarks of the detected faces or not. The default value is `False`. attributes: Optional parameter. Analyze and return the one or more specified face attributes in the comma-separated string like `age,gender`. Supported face attributes include age, gender, headPose, smile, facialHair, and glasses. Note that each face attribute analysis has additional computational and time cost. Returns: An array of face entries ranked by face rectangle size in descending order. An empty response indicates no faces detected. A face entry may contain the corresponding values depending on input parameters. """ url = 'detect' headers, data, json = util.parse_image(image) params = { 'returnFaceId': face_id and 'true' or 'false', 'returnFaceLandmarks': landmarks and 'true' or 'false', 'returnFaceAttributes': attributes, } return util.request('POST', url, headers=headers, params=params, json=json, data=data) def find_similars(face_id, face_list_id=None, face_ids=None, max_candidates_return=20, mode='matchPerson'): """Given query face's `face_id`, to search the similar-looking faces from a `face_id` array or a `face_list_id`. Parameter `face_list_id` and `face_ids` should not be provided at the same time. Args: face_id: `face_id` of the query face. User needs to call `face.detect` first to get a valid `face_id`. Note that this `face_id` is not persisted and will expire in 24 hours after the detection call. face_list_id: An existing user-specified unique candidate face list, created in `face_list.create`. Face list contains a set of `persisted_face_ids` which are persisted and will never expire. face_ids: An array of candidate `face_id`s. All of them are created by `face.detect` and the `face_id`s will expire in 24 hours after the detection call. The number of `face_id`s is limited to 1000. max_candidates_return: Optional parameter. The number of top similar faces returned. The valid range is [1, 1000]. It defaults to 20. mode: Optional parameter. Similar face searching mode. It can be "matchPerson" or "matchFace". It defaults to "matchPerson". Returns: An array of the most similar faces represented in `face_id` if the input parameter is `face_ids` or `persisted_face_id` if the input parameter is `face_list_id`. """ url = 'findsimilars' json = { 'faceId': face_id, 'faceListId': face_list_id, 'faceIds': face_ids, 'maxNumOfCandidatesReturned': max_candidates_return, 'mode': mode, } return util.request('POST', url, json=json) def group(face_ids): """Divide candidate faces into groups based on face similarity. Args: face_ids: An array of candidate `face_id`s created by `face.detect`. The maximum is 1000 faces. Returns: one or more groups of similar faces (ranked by group size) and a messyGroup. """ url = 'group' json = { 'faceIds': face_ids, } return util.request('POST', url, json=json) def identify(face_ids, person_group_id, max_candidates_return=1, threshold=None): """Identify unknown faces from a person group. Args: face_ids: An array of query `face_id`s, created by the `face.detect`. Each of the faces are identified independently. The valid number of `face_ids` is between [1, 10]. person_group_id: `person_group_id` of the target person group, created by `person_group.create`. max_candidates_return: Optional parameter. The range of `max_candidates_return` is between 1 and 5 (default is 1). threshold: Optional parameter. Confidence threshold of identification, used to judge whether one face belongs to one person. The range of confidence threshold is [0, 1] (default specified by algorithm). Returns: The identified candidate person(s) for each query face(s). """ url = 'identify' json = { 'personGroupId': person_group_id, 'faceIds': face_ids, 'maxNumOfCandidatesReturned': max_candidates_return, 'confidenceThreshold': threshold, } return util.request('POST', url, json=json) def verify(face_id, another_face_id=None, person_group_id=None, person_id=None): """Verify whether two faces belong to a same person or whether one face belongs to a person. For face to face verification, only `face_id` and `another_face_id` is necessary. For face to person verification, only `face_id`, `person_group_id` and `person_id` is needed. Args: face_id: `face_id` of one face, comes from `face.detect`. another_face_id: `face_id` of another face, comes from `face.detect`. person_group_id: Using existing `person_group_id` and `person_id` for fast loading a specified person. `person_group_id` is created in `person_group.create`. person_id: Specify a certain person in a person group. `person_id` is created in `person.create`. Returns: The verification result. """ url = 'verify' json = {} if another_face_id: json.update({ 'faceId1': face_id, 'faceId2': another_face_id, }) else: json.update({ 'faceId': face_id, 'personGroupId': person_group_id, 'personId': person_id, }) return util.request('POST', url, json=json)
d8d1812873a44c27109fa4743dfcfd87d8b54ca3
d2f63dd0bb5bd8fa7e9ae4ca828cbfe710390f33
/horizon/horizon/dashboards/nova/images_and_snapshots/snapshots/forms.py
aad9e6b93451418dbc9496b6625eebdf3778f553
[ "Apache-2.0" ]
permissive
citrix-openstack/horizon
4df36bec738a212cbb320b8ac4caf624a883815e
7987e68f135895728f891c2377b589f701d8106e
HEAD
2016-09-11T11:30:42.348228
2012-01-24T01:46:06
2012-01-24T01:46:06
2,492,995
2
0
null
null
null
null
UTF-8
Python
false
false
2,224
py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Copyright 2011 Nebula, 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 import shortcuts from django.contrib import messages from django.utils.translation import ugettext as _ from openstackx.api import exceptions as api_exceptions from horizon import api from horizon import forms LOG = logging.getLogger(__name__) class CreateSnapshot(forms.SelfHandlingForm): tenant_id = forms.CharField(widget=forms.HiddenInput()) instance_id = forms.CharField(widget=forms.TextInput( attrs={'readonly': 'readonly'})) name = forms.CharField(max_length="20", label=_("Snapshot Name")) def handle(self, request, data): try: LOG.info('Creating snapshot "%s"' % data['name']) snapshot = api.snapshot_create(request, data['instance_id'], data['name']) instance = api.server_get(request, data['instance_id']) messages.info(request, _('Snapshot "%(name)s" created for instance "%(inst)s"') % {"name": data['name'], "inst": instance.name}) return shortcuts.redirect('horizon:nova:images_and_snapshots:' 'index') except api_exceptions.ApiException, e: msg = _('Error Creating Snapshot: %s') % e.message LOG.exception(msg) messages.error(request, msg) return shortcuts.redirect(request.build_absolute_uri())
1190c16c78aea4a60bd6c95b91fa8737499b53b0
95d32a98d0715816fd763c6df356069d91d74f33
/021.py
83ecc3eddb072db50e4b272f4ea5ba096ba4d2c3
[]
no_license
jod35/coding-challenges
1f65d08d92c143004f44eafd4922ec0dcb652a1f
21cfa2853dac70055d2b20155e03dff1c235ee02
refs/heads/master
2022-12-14T22:31:37.344450
2020-09-18T19:47:51
2020-09-18T19:47:51
291,939,964
0
0
null
null
null
null
UTF-8
Python
false
false
153
py
firstname=input("Enter your first name: ") surname=input("Enter your surname: ") print(f"{firstname} {surname} is of length {len(firstname+surname)}")
cc45974788b4c903867236a1b7f7e11984d3e59a
19cec240505e27546cb9b10104ecb16cc2454702
/linux/lang/python/flume/flmos.py
1e2f7237d84356a384547d47f79bf2e46c0c1cdc
[]
no_license
imosts/flume
1a9b746c5f080c826c1f316a8008d8ea1b145a89
a17b987c5adaa13befb0fd74ac400c8edbe62ef5
refs/heads/master
2021-01-10T09:43:03.931167
2016-03-09T12:09:53
2016-03-09T12:09:53
53,101,798
0
0
null
null
null
null
UTF-8
Python
false
false
45,843
py
"""High level wrappers for wrapping auto-swig-generated code.""" # # still import the fli._* stuff with this. # import flume_internal as fli import flume import posix import errno import os import struct ##----------------------------------------------------------------------- def raise_err (s=None): """Raise an error based on what the global Flume Error flag reported was the error.""" if s is None: s = "" if flume.get_errno () == flume.ENOMEM: raise MemoryError, "out of memory in flumeclient code" elif flume.get_errno () == flume.ENULL: raise ValueError, "NULL value encountered" elif flume.get_errno () == flume.EPERM: ss = [] if (s): ss.append (s) s2 = flume.get_errstr () if (s2): ss.append (s2) if len(ss) > 0: s = '; '.join (ss) else: s = "permission denied" raise flume.PermissionError, s elif flume.get_errno () == flume.EINVAL: raise ValueError, "Unexpected valued encountered: '%s'" %s elif flume.get_errno () == flume.ERANGE: raise IndexError, "Value out of range" elif flume.get_errno () == flume.EHANDLE: raise flume.HandleError, "Could not parse handle: '%s'" % s elif flume.get_errno () == flume.ECAPABILITY: raise flume.CapabilityError, "Expected a capability" elif flume.get_errno () == flume.EROFS: raise flume.ReadOnlyError, "Attempted write to read-only FS" elif flume.get_errno () == flume.EEXPIRED: raise flume.ExpirationError, "expiration encountered" elif flume.get_errno () == flume.EATTR: raise flume.ExtattrError, "Extended attributes error encountered" elif flume.get_errno () == flume.EPERSISTENCE: raise flume.PersistenceError, "Persistence error encountered: %s" % s else: ec = flume.sysErrno () if ec is not None: raise OSError (ec, s) else: raise Exception, ("Unhandled flume error (%s) on %s" % \ (str (flume.get_errno ()), s)) ##----------------------------------------------------------------------- class Callable: def __init__(self, anycallable): self.__call__ = anycallable ##----------------------------------------------------------------------- def orderBits (bitset, order): """Given a bitset and a canonical ordering, return the set bits in the given order.""" ret = [] for b in order: if b & bitset != 0: ret += [ b ] return ret ##----------------------------------------------------------------------- class Argv (fli._Argv): """A wrapper around char *argv[] things that you'll see passed to execve and so on.""" def __init__ (self, l): if l is None: fli._Argv.__init__ (self, -1) elif type(l) is list: self.init_from_list (l) else: self.init_from_dict (l) def init_from_dict (self, d): l = [ str(k) + "=" + str (d[k]) for k in d.keys () ] self.init_from_list (l) def init_from_list (self, l): fli._Argv.__init__ (self, len (l)) i = 0 for a in l: self._set (i, a) i += 1 ##----------------------------------------------------------------------- class RawData (fli._RawData): """A wrapper class around raw XDR data.""" def __init__ (self, dat = None, armored = False): fli._RawData.__init__ (self) if type (dat) is str: if armored: self.dearmor (dat) else: if self._init (dat) < 0: raise_err ("error in RawData allocation"); elif isinstance (dat, fli._RawData): if self._copy (dat) < 0: raise_err ("failed to copy RawData in constructor") elif dat is not None: raise TypeError, "wrong type to RawData()" def __eq__ (self, x): return isinstance (x, fli._RawData) and self._eq (x) def dearmor (self, s): if type (s) is not str: raise TypeError, "Can only dearmor a string" if self._dearmor (s) < 0: raise_err ("Cannot dearmor given string") return self ##----------------------------------------------------------------------- class Token (fli._Token): """A wrapper class around the autogenerated Swig Tokens.""" def __init__ (self, s): fli._Token.__init__ (self, s) def dearmor (self, s): if fli._Token.dearmor (self, s) < 0: raise_err ("dearmor Token") ##----------------------------------------------------------------------- class Handle (fli._Handle): """A wrapper class around an autogenerated-Swig handle, to iterface with some Python-specific features.""" # default value can't be None, since that's an error result # from some syscalls def __init__(self, x = 0, nm = None): fli._Handle.__init__ (self, 0, None) if x is None: raise_err ("handle failure") elif isinstance (x, fli._Handle): self._init (x.val (), x.name ()) elif type(x) is long or type(x) is int: self._init (x, nm) elif isinstance (x, fli._RawData): self.fromRaw (x) elif type (x) is str: h = Handle () h.dearmor32(x) self._init (h.val (), nm) else: raise TypeError, "Bad arguments to constructor" def fromRaw (self, x): if self._from_raw (x) < 0: raise_err ("Cannot convert handle from raw repr") def toRaw (self): return RawData (self._to_raw ()) def thaw (self): return Label (fli._thaw_handle (self)) def __str__ (self): """Convert a handle to a human-readable string.""" if self.name () is not None: return self.name () + " (0x%016x)" % self.val () else: return "0x%016x" % self.val () def dearmor32(self, s): """Dearmor a given handle.""" rc = self._dearmor32 (s) if rc < 0: raise_err (flume.get_errstr ()) def toCapability (self, opt): return Handle (self._to_capability (opt)) def toCapabilities (self): # Figure out what type of handle this is, and return a list of # the corresponding capabilities m = ((flume.HANDLE_OPT_GROUP, [flume.CAPABILITY_GROUP_SELECT]), (flume.HANDLE_OPT_DEFAULT_ADD, [flume.CAPABILITY_SUBTRACT]), (flume.HANDLE_OPT_DEFAULT_SUBTRACT, [flume.CAPABILITY_ADD]), (0, [flume.CAPABILITY_ADD, flume.CAPABILITY_SUBTRACT])) all_opts = reduce (lambda x,y: x|y, [z[0] for z in m]) for opt, caps in m: if (self.prefix () & all_opts) == opt: return [self.toCapability (cap) for cap in caps] raise ValueError ("%s does not look like a valid capability" % (self,)) def toTag (self): """Return a Handle with the Capability bits cleared""" # If it's a wrap capability, return self. if ((self.prefix () & (flume.CAPABILITY_GROUP_SELECT | flume.HANDLE_OPT_IDENTIFIER)) == flume.CAPABILITY_GROUP_SELECT | flume.HANDLE_OPT_IDENTIFIER): return self # otherwise, clear the capability bits xhandle = Handle.mk ( ~(flume.CAPABILITY_ADD | flume.CAPABILITY_SUBTRACT | flume.CAPABILITY_GROUP_SELECT) & self.prefix (), self.base ()) return Handle (xhandle) def __hash__ (self): return hash (self.val ()) def __eq__ (self, other): return self.val () == other.val () def __ne__ (self, other): return not self.__eq__ (other) ##----------------------------------------------------------------------- class Int (fli._Int): """A wrapper class around an Int, for the purposes of making an array of ints...""" def __init__ (self, x = 0): if x is None: raise_err ("int failure") if isinstance (x, fli._Int): v = x.val () elif type (x) is long or type (x) is int: v = x elif type (x) is str: v = int (x) else: raise TypeError, "Bad arguments to constructor" fli._Int.__init__ (self, v) def __str__ (self): return "%d" % self.val () def to_int (self): return self.val () ##----------------------------------------------------------------------- class _PyObjSetWrapperIter: """A simple iterator for _PyObjSetWrappers.""" def __init__ (self, osw): self._osw = osw self._i = 0 def next (self): i = self._i if i >= len (self._osw): raise StopError self._i =+ 1 return self._osw.get (i) ##----------------------------------------------------------------------- class _PyObjSetWrapper: """A layer that goes between python objects and C++ Swig objects derived from _ObjSetWrapper<>.""" def __init__ (self, obj, py_class, swig_class, py_obj_class, name): self._py_class = py_class self._swig_class = swig_class self._py_obj_class = py_obj_class self._class_name = name self._swig_class.__init__ (self) if obj is None: raise_err ("%s allocation failure" % name) elif type (obj) is self._swig_class: self.copy (obj) elif isinstance (obj, fli._RawData): self.fromRaw (obj) elif type (obj) is set: self.fromList (list (obj)) elif type (obj) is list or type (obj) is tuple: self.fromList (obj) elif type (obj) is int: if obj >= 0: self.resize (obj) else: raise TypeError, "bad argument to constructor" def __iter__ (self): return _PyObjSetWrapperIter (self) def __len__ (self): return self._size () def size (self): return self._size () def clone (self): return self._py_class (self._clone ()) def get (self, i): return self._py_obj_class (self._get (i)) def copy (self, i): if self._copy (i) < 0: raise_err ("%s::copy" % self._class_name) def resize (self, i): if self._resize (i) < 0: raise_err ("%s::resize" % self._class_name) def set (self, i, l): if self._set (i, l) < 0: raise_err ("%s::set" % self._class_name) def fromList (self, l): self.resize (len (l)) for i, o in enumerate (l): self.set (i, o) def toList (self): return [ self.get (i) for i in range (len(self)) ] def fromRaw (self, d): if self._from_raw (d) < 0: raise_err ("Error converting object from raw data") def toRaw (self): return RawData (self._to_raw ()) def __str__ (self): return str ([ str(x) for x in self.toList() ]) def __getitem__ (self, key): l = self.toList () return l[key] def __setitem__ (self, key, value): l = self.toList () l[key] = value self.fromList (l) def __delitem__ (self, key): l = self.toList () del (l[key]) self.fromList (l) def __iter__ (self): return iter (self.toList ()) def __contains__ (self, item): return self.toList().__contains__(item) def _add_ready_list (self, l): if isinstance(l, self._py_obj_class): l = [l] elif isinstance (l, self._py_class): l = l.toList () elif type (l) is list: for i in l: if not isinstance (i, self._py_obj_class): raise TypeError, "expected a list of type: %s" % \ str (self._py_obj_class) else: raise TypeError, "cannot add type to list: %s + $s" % \ (str (self), str (l)) return l def __add__ (self, l): l = self._add_ready_list (l) return (self._py_class (self.toList () + l)) def __iadd__ (self, l): l = self._add_ready_list (l) self.fromList (self.toList () + l) return self def __sub__ (self, l): s = set (self._add_ready_list (l)) return (self._py_class (set(self.toList ()) - s)) def __isub__ (self, l): s = set (self._add_ready_list (l)) self.fromList (set(self.toList ()) - s) return self ##----------------------------------------------------------------------- class IntArr (_PyObjSetWrapper, fli._IntArr): def __init__ (self, x = 0): _PyObjSetWrapper.__init__ (self, x, IntArr, fli._IntArr, Int, "IntArr") def set (self, i, x): if type (x) is int or type (x) is long: x = Int (x) _PyObjSetWrapper.set (self, i, x) def toListV (self): return [ x.val() for x in self.toList() ] ##----------------------------------------------------------------------- class Label (_PyObjSetWrapper, fli._Label): """A wrapper class around an autogenerated-Swig label, to interface with some Python-specific features.""" # default value can't be None, since that's an error result from # _get_label() def __init__(self, x = 0): _PyObjSetWrapper.__init__ (self, x, Label, fli._Label, Handle, "Label") def uniquify (self, seq): """ Preserves order """ seen = set() return [x for x in seq if x not in seen and not seen.add(x)] # Overload fromList and fromRaw to remove duplicates def fromList (self, l): l2 = self.uniquify (l) _PyObjSetWrapper.fromList (self, l2) def fromRaw (self, d): _PyObjSetWrapper.fromRaw (self, d) l = self.uniquify (self.toList ()) self.fromList (l) def __lt__ (self, b): return self.toSet().__lt__(b.toSet()) def __le__ (self, b): return self.toSet().__le__(b.toSet()) def __eq__ (self, b): return self.toSet().__eq__(b.toSet()) def __ne__(self, b): return self.toSet().__ne__(b.toSet()) def __gt__ (self, b): return self.toSet().__gt__(b.toSet()) def __ge__ (self, b): return self.toSet().__ge__(b.toSet()) def subsetOf (self, rhs, typ): r = fli._subsetOf (self, LabelVec (rhs), typ) if r < 0: raise_err () if r == 0: return False return True def freeze (self): return Handle (fli._Label_freeze (self)) def __str__(self): return "[" + ", ".join ([str(s) for s in self.toList ()]) + "]" def toListV (self): return [ x.val() for x in self.toList() ] def toSet (self): return set (self.toListV()) def __contains__(self, h): if type(h) is int or type(h) is long: v = h else: v = h.val() return v in self.toSet () def pack (self): l = self.toListV () l.sort () format = '!' + 'Q' * len (l) l.insert (0, format) return struct.pack (*l) def unpack (s): if (len (s) % struct.calcsize ('Q')) > 0: raise AssertionError, ('serialized label, incorrect ' 'size %d is not a multiple of %d' % (len (s), struct.calcsize ('Q'))) format = '!' + 'Q' * (len(s)/struct.calcsize ('Q')) v = struct.unpack (format, s) return Label ([Handle (x) for x in v]) unpack = Callable (unpack) def hashkey (self): """ Returns a canonicalized string that can be used as a hash key. We don't implement __hash__ because a labelset is mutable and implementing __hash__ implies that the underlying object is immutable.""" values = self.toList () values.sort (key=lambda h: h.val ()) return "[" + ", ".join ([str(s) for s in values]) + "]" ##----------------------------------------------------------------------- class LabelVec (fli._LabelVec): """A wrapper class used as an input to subsetOf operations.""" def __init__ (self, labels): fli._LabelVec.__init__(self, len(labels)) i = 0 for l in labels: self._set (i, l) i += 1 ##----------------------------------------------------------------------- class Filter (fli._Filter): """A wrapper class around filters.""" def __init__ (self, f): fli._Filter.__init__ (self) if type (f) is fli._Filter: if self.copy (f) < 0: raise_err ("copy Filter") else: raise TypeError, "bad argument to constructor" def find (self): return Label (fli._Filter.find (self)) def replace (self): return Label (fli._Fitler.replace (self)) ##----------------------------------------------------------------------- class Capset (Label): """A type of label specifically designed for storing capabilities.""" def __init__ (self, l, priv): Label.__init__ (self, [ x.toCapability (priv) for x in l.toList() ] ) ##----------------------------------------------------------------------- class Endpoint (fli._Endpoint): """A high-level wrapper to the _Endpoint autogenerated by Swig.""" def __init__ (self, ep = -1, I = None, S = None): fli._Endpoint.__init__(self) if ep is None: raise_err ("Endpoint failure") elif type(ep) is fli._Endpoint: if self.copy (ep) < 0: raise_err ("Endpoint copy failure") elif type(ep) is int and ep == -1: if I is not None: fli._Endpoint._set_I (self, I) if S is not None: fli._Endpoint._set_S (self, S) else: raise TypeError, "bad argument to constructor" def get_S (self): return Label (self._get_S()) def get_I (self): return Label (self._get_I()) def get_desc (self): ret = self._get_desc () if ret is None: ret = "<none>" else: ret = str (ret) return ret def toDict (self): d = { 'readable' : bool (self.getReadable ()), 'writable' : bool (self.getWritable ()), 'mutable' : bool (self.getMutable ()), 'I' : self.get_I(), 'S' : self.get_S(), 'desc' : self.get_desc () } return d def attrStr (self): l = [ ('r', self.getReadable ()), ('w', self.getWritable ()), ('m', self.getMutable ()) ] r = "" for t in l: if t[1]: r += t[0] return r def prettyPrint (self, prfx = ""): pairs = [ ( 'S: ' , self.get_S () ), ( 'I: ' , self.get_I () ), ( 'attrs:' , self.attrStr () ), ( 'desc: ' , self.get_desc () ) ] # XXX allow endpoints to be named, too lines = [ "Endpoint {" ] + \ [ " %s %s" % (t[0], t[1]) for t in pairs ] + \ [ "}" ] return '\n'.join ( [ "%s%s" % (prfx, l) for l in lines ] ) def __str__(self): return str (dict ([ (k,str (v)) for (k,v) in self.toDict().items()])) def getMutable (self): return bool (self._get_mutable ()) def getWritable (self): return bool (self._get_writable ()) def getReadable (self): return bool (self._get_readable ()) def setReadable (self, b): self._set_reable (int (b)) def setWritable (self, b): self._set_writable (self, int (b)) def setMutable (self, b): self._set_mutable (self, int (b)) ##----------------------------------------------------------------------- class EndpointSet (_PyObjSetWrapper, fli._EndpointSet): """A high-level wrapper around Endpoint sets autogenerated by Swig.""" def __init__ (self, eps = 0): _PyObjSetWrapper.__init__ (self, eps, EndpointSet, fli._EndpointSet, Endpoint, "EndpointSet") def prettyPrint (self): lst = [ "EndpointSet {" ] + \ [ x.prettyPrint (" ") for x in self.toList ()] + \ [ "}" , '' ] return '\n'.join (lst) ##----------------------------------------------------------------------- class LabelSet (fli._LabelSet): """A high-level wrapper to the LabelSet autogenerated by Swig.""" # When make label changes from this LabelSet, do it in this # order. Alex suggests this order. change_order = [flume.LABEL_O, flume.LABEL_I, flume.LABEL_S] def __init__(self, ls = -1, I = None, S = None, O = None, armoredraw=False): fli._LabelSet.__init__(self) if ls is None: raise_err ("LabelSet failure") elif type(ls) is dict: for l in [ ("I", fli._LabelSet._set_I), ("S", fli._LabelSet._set_S), ("O", fli._LabelSet._set_O) ] : try: f = l[1] f (self, ls[l[0]]) except KeyError: pass elif isinstance (ls, fli._LabelSet): self.copy (ls) elif isinstance (ls, fli._RawData): self.fromRaw (ls) elif type(ls) is int and ls == -1: if I is not None: fli._LabelSet._set_I (self, I) if S is not None: fli._LabelSet._set_S (self, S) if O is not None: fli._LabelSet._set_O (self, O) elif type (ls) is type ('a'): if armoredraw: rd = RawData (ls, True) self.fromRaw (rd) else: ls = fli._filename_to_labelset (ls) self.copy (ls) else: raise TypeError, "bad argument to constructor" def __le__ (self, b): return self.get_S() <= b.get_S() and b.get_I() <= self.get_I() def __ge__ (self, b): return self.get_S() >= b.get_S() and b.get_I() >= self.get_I() def __eq__ (self, b): return self.get_S() == b.get_S() and b.get_I() == self.get_I() def __ne__ (self, b): return self.get_S() != b.get_S() or b.get_I() != self.get_I() def __gt__ (self, b): return self.get_S() > b.get_S() and b.get_I() > self.get_I() def __lt__ (self, b): return self.get_S() < b.get_S() and b.get_I() < self.get_I() def toDict (self): return { "I" : self.get_I (), "S" : self.get_S (), "O" : self.get_O () } def toDictEnumKeys (self): return { flume.LABEL_I : self.get_I (), flume.LABEL_S : self.get_S (), flume.LABEL_O : self.get_O () } def toLabelChangeList (self, which = flume.LABEL_ALL): ret = [] d = self.toDictEnumKeys () for i in orderBits (which, self.change_order): if d[i] is not None: ret += [ LabelChange (lab = d[i], which = i) ] return ret def apply (self): LabelChangeSet (self.toLabelChangeList ()).make () def apply_ep (self, fd): LabelChangeSet (self.toLabelChangeList (flume.LABEL_NO_O)).make_ep (fd) def set_S (self, l=None): if self._set_S (l) < 0: raise_err ("label = %s" % l) def set_I (self, l=None): if self._set_I (l) < 0: raise_err ("label = %s" % l) def set_O (self, l=None): if self._set_O (l) < 0: raise_err ("label = %s" % l) def set_label (self, typ, l=None): return { flume.LABEL_I : self.set_I, flume.LABEL_S : self.set_S, flume.LABEL_O : self.set_O }[typ] (l) def get_S (self): return Label (self._get_S ()) def get_I (self): return Label (self._get_I ()) def get_O (self): return Label (self._get_O ()) def get_label (self, typ): return self.toDictEnumKeys ()[typ] def __str__(self): return str (dict ([ (k,str(v)) for (k,v) in self.toDict().items() ])) def to_filename (self): if len(self.get_S ()) == 0 and len(self.get_I()) == 0 and \ len(self.get_I ()) == 0: return "0" ret = self._to_filename () if ret is None: raise_err ("labelset_to_filename") return ret def toList (self): return [self._get_S (), self._get_I (), self._get_O () ] def fromRaw (self, obj): if self._from_raw (obj) < 0: raise_err ("Error converting object from raw data") def toRaw (self): return RawData (self._to_raw ()) def armoredraw (self): return self.toRaw ().armor () def hashkey (self): """ Returns a canonicalized string that can be used as a hash key. We don't implement __hash__ because a labelset is mutable and implementing __hash__ implies that the underlying object is immutable.""" ret = [Label(lab).hashkey() for lab in self.toList ()] return str(ret) def clone (self): ls = LabelSet () ls.copy (self) return ls ##----------------------------------------------------------------------- class LabelChange (fli._LabelChange): """A high-level wrapper around _LabelChange generated by swig.""" def __init__ (self, lab = None, which = fli.LABEL_NONE): """lab can be either a LabelChange or a Label object, and this construction should do the right thing. Pass a LabelChange as part a copy constructor, and pass a Label if calling from somewhere external to this function.""" fli._LabelChange.__init__ (self) if lab is not None: if type (lab) is fli._LabelChange: self.copy (lab) else: self.setLabel (lab) if which is not None: self.setWhich (which) def getWhich (self): return fli._LabelChange.get_which (self) def setWhich (self, i): return fli._LabelChange.set_which (self, i) def clone (self): """Make a clone of this label change.""" return LabelChange (fli._LabelChange.clone (self)) def setLabel (self, l): """Set the label on LabelChange object""" if fli._LabelChange._set_label (self, l) < 0: raise_err ("LabelChange::set_label") def getLabel (self): return Label (self._get_label ()) def copy (self, l): if fli._LabelChange._copy (self, l) < 0: raise_err ("LabelChange::copy") def __str__ (self): return str ((str (self.getLabel ()), self.getWhich ())) def make (self): """Actually make this label change.""" set_label (self.getWhich (), self.getLabel ()) def make_ep (self, fd): """Actually make this label change to an endpoint.""" set_fd_label (self.getWhich (), fd, self.getLabel ()) ##----------------------------------------------------------------------- class LabelChangeSet (_PyObjSetWrapper, fli._LabelChangeSet): """A high level wrapper around _LabelChangeSet generated by Swig.""" def __init__ (self, lcs = []): _PyObjSetWrapper.__init__ (self, lcs, LabelChangeSet, fli._LabelChangeSet, LabelChange, "LabelChangeSet") def _add_arg_to_label_change_list (self, l): """Convert the argument to __add__ or __iadd__ to be a list of label changes.""" if type (l) is list: l2 = l elif isinstance (l, LabelChangeSet): l2 = l.toList () elif isinstance (l, LabelSet): l2 = l.toLabelChangeList () else: raise TypeError, \ "arg to +/+= must be list, LabelChangeSet or LabelSet" return l2 def __add__ (self, l): """Add more label changes to this label change set, without destructively changing it.""" l1 = self.toList () l2 = self._add_arg_to_label_change_list (l) return LabelChangeSet (l1 + l2) def make (self): """Make the label changes contained in this label set.""" for l in self.toList (): l.make () def make_ep(self, fd): """Make the label chagnes to the EP.""" for l in self.toList (): l.make_ep(fd) def __iadd__ (self, l): """Add more label changes to this label change set, and alter the underlying LabelChangeSet.""" l2 = self._add_arg_to_label_change_list (l) oldlen = len(self) self.resize (oldlen + len (l2)) for i,obj in enumerate (l2): self.set (oldlen + i, obj) return self ##----------------------------------------------------------------------- class CapabilityOp (fli._CapabilityOp): """A high-level wrapper around a capability operation that we have in the SQL library.""" def __init__ (self, h, op=None): fli._CapabilityOp.__init__ (self) if isinstance(h, fli._CapabilityOp): op = h._get_op () h = Handle (h._get_h ()) self.set_h (h) self.set_op (op) def __str__ (self): return "(%s,%d)" % (str (self.get_h ()), self.get_op ()) def set_h (self, h): self._set_h (h) def set_op (self, op): self._set_op (op) def get_h (self): return Handle (self._get_h ()) def get_op (self): return self._get_op () def toPair (self): return (self.get_h (), self.get_op ()) ##----------------------------------------------------------------------- class CapabilityOpSet (_PyObjSetWrapper, fli._CapabilityOpSet): def __init__ (self, cos = None): _PyObjSetWrapper.__init__ (self, cos, CapabilityOpSet, fli._CapabilityOpSet, CapabilityOp, "CapabilityOpSet") def toDict (self): return dict ([ cop.toPair () for cop in self ] ) ##----------------------------------------------------------------------- ##----------------------------------------------------------------------- ##----------------------------------------------------------------------- def set_label (typ, label=None, frc=True): """Set the processes label to the give label. 'typ' should be one of flume.LABEL_I, flume.LABEL_S, or flume.LABEL_O, and the 'label' argument should be a flmos.Label object. If given None, we will try to clear the label. On success no return code; on error, raise an exception.""" if fli._set_label (typ, label, frc) < 0: raise_err ("set_label failed") ##----------------------------------------------------------------------- def set_label2 (O = -1, I = -1, S = -1, frc=True): """A slightly more convenient way to set this proc's label. Perform in the order: O, I, S, as per standard. Note, the -1 hack is because None are allowed as label types, if we want to clear the label.""" dat = [ ( flume.LABEL_O, O), ( flume.LABEL_I, I), ( flume.LABEL_S, S) ] for p in dat: if p[1] is None or isinstance (p[1], Label): if fli._set_label (p[0], p[1], frc) < 0: raise_err ("set_label failed") elif (type(p[1]) == type(-1)) and p[1] == -1: pass else: raise TypeError, 'Invalid argument type to set_label2' ##----------------------------------------------------------------------- def set_fd_label (typ, fd, label=None): """Set a label on the given 'fd'. Provide an 'fd' in addition to the arguments from set_label.""" if fli._set_fd_label (typ, fd, label) < 0: raise_err ("set_fd_label failed") ##----------------------------------------------------------------------- def get_label (typ): """Where 'typ' is flume.LABEL_I, flume.LABEL_O or flume.LABEL_S, get the given label for this process from the reference monitor.""" return Label (fli._get_label (typ)) ##----------------------------------------------------------------------- def get_endpoint_info (): """Get the endpoint information for the calling process.""" return EndpointSet (fli._get_endpoint_info()) ##----------------------------------------------------------------------- def get_labelset (): """Get the labelset for this process.""" return LabelSet (fli._get_labelset()) ##----------------------------------------------------------------------- def get_fd_label (typ, fd): """Same as 'get_label', but get the label for a specific FD.""" l = fli._get_fd_label (typ, fd) if l is None: # If l was NULL but the RM returned ENULL, that means that no # label was set on this fd, which is not an error condition if flume.get_errno () != flume.ENULL: raise_err ("get_fd_label failure"); else: l = Label (l) return l ##----------------------------------------------------------------------- def stat_group (h): """Determine the label on the object corresponding to the group given by 'h'.""" ls = fli._stat_group (h) if ls is None: raise_err ("error in stat_group (%)" % h) return LabelSet (ls) ##----------------------------------------------------------------------- def stat_file (fn): """Ask the RM for the labelset on the file given by the filename 'fn'.""" ls = fli._stat_file (fn) if ls is None: raise_err ("error in stat_file(%s)" % fn) return LabelSet (ls) ##----------------------------------------------------------------------- def new_handle (opts, name): """ Create a new handle from the reference monitor, with the given 'opts' options and the given name 'name'. 'opts' should be a bitwise OR of: flume.HANDLE_OPT_DEFAULT_ADD flume.HANDLE_OPT_DEFAULT_SUBTRACT flume.HANDLE_OPT_PERSISTENT flume.HANDLE_OPT_IDENTIFIER Return a new flmos.Handle object, or raise an exception if there was a problem. """ return Handle(fli._new_handle (opts, name)) ##----------------------------------------------------------------------- def new_group (name, ls): """ Create a new group of capabilities, given the 'name' of the group and the flmos.LabelSet object 'ls' to specify the labels on the group. Return a new handle that identifies the group (generated by the reference monitor). """ h = Handle(fli._new_group (name, ls)) return h ##----------------------------------------------------------------------- def add_to_group (h, v): """ Given the handle 'h' that names a group, add the capabilities in the list 'v' to the group. """ if type (v) is list: lst = Label (v) else: lst = v if fli._add_to_group (h, lst) < 0: raise_err ("add (%s) to group (%s) failed" % (str (h), str (lst))) ##----------------------------------------------------------------------- def unixsocket (fn, c): fd = fli._unixsocket (fn, c) if fd < 0: raise_err ("unixsocket failed: " + fn) return fd ##----------------------------------------------------------------------- def unixsocket_connect (fn): fd = fli._unixsocket_connect (fn) if fd < 0: raise_err () return fd ##----------------------------------------------------------------------- def listen (fd, queue_len): rc = fli._listen (fd, queue_len) if rc < 0: raise_err () return rc ##----------------------------------------------------------------------- def accept (fd): rc = fli._accept (fd) if rc < 0: raise_err () return rc ##----------------------------------------------------------------------- def make_login (h, duration=0, fixed=False): tok = fli._make_login (h, duration, fixed) if tok is None: raise_err ("make_login failed") return tok ##----------------------------------------------------------------------- def req_privs (h, tok): rc = fli._req_privs (h, tok) if rc < 0: if flume.get_errno () == flume.ENOENT: raise flume.LoginError, \ "No login token found for pair (%s,'%s')" % (str (h), tok) elif flume.get_errno () == flume.EEXPIRED: raise flume.ExpirationError, \ "Login token expired for pair (%s,'%s')" % (str (h), tok) else: raise_err ("req_privs (%s,%s)" % (str (h), tok)) ##----------------------------------------------------------------------- def dearmor_token (x): t = fli._dearmor_token (x) if t is None: raise_err ("dearmor") return t ##----------------------------------------------------------------------- def setuid_handle (): h = fli._setuid_handle () if h is None: raise_err ("setuid_handle") return Handle (h) ##----------------------------------------------------------------------- def make_nickname (h, name): rc = fli._make_nickname (h, name) if rc != 0: raise_err ("make_nickname") ##----------------------------------------------------------------------- def writefile (name, data, mode=0600, labelset=None): flags = posix.O_WRONLY | posix.O_CREAT | posix.O_TRUNC rc = fli._writefile (name, flags, mode, labelset, data) if rc < 0: raise_err ("writefile failed on '%s'" % name) ##----------------------------------------------------------------------- def open (name, flags='r', mode=0, labelset=None, endpoint=None, bufsize=4096): py_fl = "" c_fl = 0 map = { "w" : (posix.O_WRONLY, True), "r" : (posix.O_RDONLY, True), "a" : (posix.O_APPEND, True), "c" : (posix.O_CREAT, False), "e" : (posix.O_EXCL, False), "t" : (posix.O_TRUNC, False)} for c in flags: p = map.get (c) if p is None: raise ValueError, "Unknown flag to open: '%s'" % c c_fl |= p[0] if p[1]: py_fl += c fd = fli._open (name, c_fl, mode, labelset, endpoint) if fd < 0: raise_err ("open failed on file '%s'" % name) return posix.fdopen (fd, py_fl, bufsize) ##----------------------------------------------------------------------- def mkdir (path, mode=0700, labelset=None): rc = fli._mkdir (path, mode, labelset) if rc < 0: raise_err ("mkdir failed on file '%s'" % path) ##----------------------------------------------------------------------- def symlink (contents, newfile, labelset=None): rc = fli._symlink (contents, newfile, labelset) if rc < 0: raise_err ("symlink failed on file '%s'" % newfile) ##----------------------------------------------------------------------- def optimal_label_changes (from_ls, to_ls): changelist = [] # get all caps (Do this before adding any I tags, since that might # prevent us from reading our capability groups). all_o = set(from_ls.get_O ()) | set (to_ls.get_O ()) changelist.append (LabelChange (lab=Label (all_o), which=flume.LABEL_O)) changelist.append (LabelChange (lab=to_ls.get_S (), which=flume.LABEL_S)) changelist.append (LabelChange (lab=to_ls.get_I (), which=flume.LABEL_I)) changelist.append (LabelChange (lab=to_ls.get_O (), which=flume.LABEL_O)) return LabelChangeSet (changelist) def spawn (prog, argv, env=None, confined=True, opt=0, claim=None, I_min=None, endpoint=None, ch_endpoint=None, labelset=None): """The original spawn; accepts a labelset for the child process and returns just a handle -- the pid of the child process -- on success.""" lchanges = None if labelset is not None: lchanges = optimal_label_changes (get_labelset (), labelset) tmp = spawn2 (prog=prog, argv=argv, env=env, confined=confined, opt=opt, claim=claim, lchanges=lchanges, I_min=I_min, endpoint=endpoint, ch_endpoint=ch_endpoint) if tmp is None: raise_err ("Spawn failed on program '%s'" % prog) return tmp[0] ##----------------------------------------------------------------------- def spawn2 (prog, argv, env=None, confined=True, opt=0, claim=None, lchanges=None, I_min=None, endpoint=None, ch_endpoint=None): """The new spawn procedure. Accepts a vector of label changes to make, and returns a pair. The first element in the pair is the pid of the child process (in Handle form). The second element is the status, either SPAWN_OK=0 or SPAWN_DISAPPEARED.""" cl=None if env is None: env = os.environ if claim is not None: cl = Label (claim) if confined: opt |= fli.SPAWN_CONFINED tmp = fli._spawn (prog, Argv (argv), Argv (env), opt, cl, lchanges, I_min, endpoint, ch_endpoint) if tmp is None: raise_err ("Spawn failed on program '%s'" % prog) return (Handle (tmp.gethandle ()), tmp.getfd ()) ##----------------------------------------------------------------------- def socketpair (duplex = fli.DUPLEX_FULL, desc = None): sp = fli._socketpair (fli.DUPLEX_FULL, desc) if sp is None: raise_err ("socketpair") return (sp.getfd (), Handle (sp.gethandle ())) ##----------------------------------------------------------------------- def rpipe (desc = None): return socketpair (fli.DUPLEX_THEM_TO_ME, desc) ##----------------------------------------------------------------------- def wpipe (desc = None): return socketpair (fli.DUPLEX_ME_TO_THEM, desc) ##----------------------------------------------------------------------- def claim (s, desc = None): fd = fli._claim (Handle (s), desc) if fd < 0: raise_err ("claim") return fd ##----------------------------------------------------------------------- def waitpid (h=None, opt = 0): pr = fli._waitpid (h, opt) if pr is None: raise_err ("waitpid") return (Handle (pr._get_pid (), "exitpid"), pr._get_exit_code (), pr._get_visible()) ##----------------------------------------------------------------------- def apply_filter (name, typ): f = fli._apply_filter (name, typ) if f is None: raise_err ("applying filter: %s" % name) return Filter (f) ##----------------------------------------------------------------------- def closed_files (): if fli._closed_files () < 0: raise_err ("closed_files") ##----------------------------------------------------------------------- def unlink (path): rc = fli._unlink (path) if rc < 0: raise_err ("unlink failed on file '%s'" % path) ##----------------------------------------------------------------------- def set_libc_interposing (v): rc = fli._set_libc_interposing (v) if (rc <0): raise_err ('unable to set libc interposing to %d' % v) ##----------------------------------------------------------------------- def get_libc_interposing (): return bool (fli._libc_interposing ()) ##----------------------------------------------------------------------- def myctlsock (): return fli._ctl_sock () ##----------------------------------------------------------------------- def close (fd): if fli._close (fd) < 0: raise_err ('error closing fd %d' % fd) ##----------------------------------------------------------------------- def flume_null (): r = fli._flume_null (); if r < 0: raise_err ('error calling flume_null') return r ##----------------------------------------------------------------------- def flume_debug_msg (s): r = fli._flume_debug_msg (s); if r < 0: raise_err ('error calling flume_debug_msg') return r ##----------------------------------------------------------------------- def verify_capabilities (fd, ops, caps): res = fli._verify_capabilities (fd, ops, caps) if res is None: raise_err ('error in verify_capabilities') return CapabilityOpSet (res) ##----------------------------------------------------------------------- def send_capabilities (fd, caps): r = fli._send_capabilities (fd, caps) if r < 0: raise_err ('error in send_capabilities') ##----------------------------------------------------------------------- def fork (fds, confined): if type (fds) is list: fds = IntArr (fds) rc = fli._flume_fork (fds, confined) if rc < 0: raise_err ('error in flume_fork') return rc ##----------------------------------------------------------------------- def setepopt (fd, strict=None, fix=None): op = val = 0 if fix is not None and fix is True: op = flume.FLUME_EP_OPT_FIX val = True elif strict is not None: op = flume.FLUME_EP_OPT_STRICT val = strict else: raise TypeError, "unknown option given to setepopt" rc = fli._setepopt (fd, op, val) if rc < 0: raise_err ('error in setepopt') ##----------------------------------------------------------------------- ##-----------------------------------------------------------------------
[ "imosts" ]
imosts
3ed7586381e1664293709ab9dac14351df1831e7
6999630ddf8559c9c6bee40a1dfa4a53d2ce4867
/get_proxy_from_XMX.py
5b1e4d26017e8ab210b7b69b68e4d87cb4dd843d
[]
no_license
possager/YFZX_new
a6a21cd7a8d6731af5ce87aae9887408472d295a
057925659a7fcae4179d68cf2e0fca576e1de9f2
refs/heads/master
2021-01-02T22:33:00.488949
2017-11-27T00:49:47
2017-11-27T00:49:47
99,334,747
0
0
null
null
null
null
UTF-8
Python
false
false
2,029
py
#_*_coding:utf-8_*_ #因为reids在idc上挂了,所以写了这么一个新的代理 import requests import json import time from saveresult import BASIC_FILE import random import datetime class Proxy: # def __init__(self,url_proxy='http://172.16.2.11:8899'): def __init__(self,url_proxy='http://172.16.1.4:8899/'): self.url_proxy=url_proxy def save_proxy(self): response=requests.get(self.url_proxy) jsondata=json.loads(response.text) file1=BASIC_FILE+'/proxy.txt' with open(file1,'w') as fl: json.dump(jsondata,fl,encoding='utf-8') # json.dump(jsondata,file1) def get_proxy_couple(self,num): file1 = BASIC_FILE + '/proxy.txt' with open(file1,'r') as fl: datajson=json.load(fl,encoding='utf-8') if datajson: # return (str(datajson[num]['ip']),str(datajson[num]['port'])) return str(datajson[num]['ip'])+':'+str(datajson[num]['port']) # url_proxy='http://192.168.8.52:8899/' url_proxy='http://172.16.1.4:8899/'#yuancheng def save_proxy(): while True: try: response = requests.get(url_proxy) jsondata = json.loads(response.text) file1 = BASIC_FILE + '/proxy.txt' with open(file1, 'w') as fl: json.dump(jsondata, fl, encoding='utf-8') print datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') time.sleep(30) except Exception as e: pass def get_proxy_couple(num): file1 = BASIC_FILE + '/proxy.txt' with open(file1,'r') as fl: datajson=json.load(fl,encoding='utf-8') if datajson: # return (str(datajson[num]['ip']),str(datajson[num]['port'])) num=random.randint(0,len(datajson)-1) return str(datajson[num]['ip'])+':'+str(datajson[num]['port']) if __name__ == '__main__': # thisclass=Proxy() # # thisclass.save_proxy() # print thisclass.get_proxy_couple(2) # print get_proxy_couple(2) save_proxy()
9f653ab13307676c72916817ec6736cef0226239
d41d18d3ea6edd2ec478b500386375a8693f1392
/plotly/validators/carpet/aaxis/_tickvals.py
d662833232a93d94748922377e31518cbba4b730
[ "MIT" ]
permissive
miladrux/plotly.py
38921dd6618650d03be9891d6078e771ffccc99a
dbb79e43e2cc6c5762251537d24bad1dab930fff
refs/heads/master
2020-03-27T01:46:57.497871
2018-08-20T22:37:38
2018-08-20T22:37:38
145,742,203
1
0
MIT
2018-08-22T17:37:07
2018-08-22T17:37:07
null
UTF-8
Python
false
false
422
py
import _plotly_utils.basevalidators class TickvalsValidator(_plotly_utils.basevalidators.DataArrayValidator): def __init__( self, plotly_name='tickvals', parent_name='carpet.aaxis', **kwargs ): super(TickvalsValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type='calc', role='data', **kwargs )
654f906f59ef8bb22afe907524e10160829658d8
1f006f0c7871fcde10986c4f5cec916f545afc9f
/apps/ice/plugins/required/plugin_info.py
efab21549b3cbef46e32e6e38adbc4c8701eb49f
[]
no_license
ptsefton/integrated-content-environment
248b8cd29b29e8989ec1a154dd373814742a38c1
c1d6b5a1bea3df4dde10cb582fb0da361dd747bc
refs/heads/master
2021-01-10T04:46:09.319989
2011-05-05T01:42:52
2011-05-05T01:42:52
36,273,470
0
0
null
null
null
null
UTF-8
Python
false
false
3,006
py
# # Copyright (C) 2007 Distance and e-Learning Centre, # University of Southern Queensland # # 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 2 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, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # import os import pysvn import sys pluginName = "ice.info" pluginDesc = "" pluginFunc = None # either (or both) pluginFunc or pluginClass should pluginClass = None # be set by the pluginInit() method pluginInitialized = False # set to True by pluginInit() method def pluginInit(iceContext, **kwargs): global pluginFunc, pluginClass, pluginInitialized pluginFunc = None pluginClass = VersionInfo pluginInitialized = True return pluginFunc class VersionInfo: def __init__(self, iceContext=None, *args): self.iceContext = iceContext def svn(self): return str(pysvn.svn_version) def pysvn(self): return str(pysvn.version) def python(self): return str(os.sys.version) def iceTrunkRevision(self): svn = pysvn.Client() return str(svn.info('../../../trunk').revision) def __getArgs(self): return self.__args def summary(self): info = VersionInfo() summary = "Built from ICE trunk " + info.iceTrunkRevision() + "\n" summary = summary + "SVN version " + info.svn() + "\n" summary = summary + "pysvn version " + info.pysvn() + "\n" summary = summary + "Python: " + info.python() return summary def getSummary(self): argv = sys.argv info = VersionInfo() try: result = "ICE version: " + argv[1] + "\n" result = result + info.summary() return str(result) except: try: f = open('version_info.txt', 'r') info = f.read() f.close() return info except IOError: summary = "ICE version: unversioned \n" summary = summary + "SVN version " + info.svn() + "\n" summary = summary + "pysvn version " + info.pysvn() + "\n" summary = summary + "Python: " + info.python() return summary def main(argv=None): if argv is None: argv = sys.argv info = VersionInfo() print "%s" % info.getSummary() if __name__ == "__main__": sys.exit(main())
[ "[email protected]@110e3293-9ef9-cb8f-f479-66bdb1942d05" ]
[email protected]@110e3293-9ef9-cb8f-f479-66bdb1942d05
20a5389145ea522daccca65f7fb7d8b787f1b09e
978248bf0f275ae688f194593aa32c267832b2b6
/xlsxwriter/test/comparison/test_set_start_page01.py
11f627dcef39de7dc1ca840d9031d251ff300970
[ "BSD-2-Clause-Views" ]
permissive
satish1337/XlsxWriter
b0c216b91be1b74d6cac017a152023aa1d581de2
0ab9bdded4f750246c41a439f6a6cecaf9179030
refs/heads/master
2021-01-22T02:35:13.158752
2015-03-31T20:32:28
2015-03-31T20:32:28
33,300,989
1
0
null
null
null
null
UTF-8
Python
false
false
1,189
py
############################################################################### # # Tests for XlsxWriter. # # Copyright (c), 2013-2015, John McNamara, [email protected] # from ..excel_comparsion_test import ExcelComparisonTest from ...workbook import Workbook class TestCompareXLSXFiles(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.maxDiff = None filename = 'set_start_page01.xlsx' test_dir = 'xlsxwriter/test/comparison/' self.got_filename = test_dir + '_test_' + filename self.exp_filename = test_dir + 'xlsx_files/' + filename self.ignore_files = [] self.ignore_elements = {'xl/worksheets/sheet1.xml': ['<pageMargins']} def test_create_file(self): """Test the creation of a simple XlsxWriter file with printer settings.""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() worksheet.set_start_page(1) worksheet.set_paper(9) worksheet.vertical_dpi = 200 worksheet.write('A1', 'Foo') workbook.close() self.assertExcelEqual()
ab1b83f541859e0497ec43adf826cb8f44c0793e
ef6229d281edecbea3faad37830cb1d452d03e5b
/ucsmsdk/mometa/sw/SwFcMon.py
2bf6bd3af9a6b1ae66a826281d4f11a20c9017d0
[ "Apache-2.0" ]
permissive
anoop1984/python_sdk
0809be78de32350acc40701d6207631322851010
c4a226bad5e10ad233eda62bc8f6d66a5a82b651
refs/heads/master
2020-12-31T00:18:57.415950
2016-04-26T17:39:38
2016-04-26T17:39:38
57,148,449
0
0
null
null
null
null
UTF-8
Python
false
false
22,479
py
"""This module contains the general information for SwFcMon ManagedObject.""" import sys, os from ...ucsmo import ManagedObject from ...ucscoremeta import UcsVersion, MoPropertyMeta, MoMeta from ...ucsmeta import VersionMeta class SwFcMonConsts(): ADMIN_STATE_DISABLED = "disabled" ADMIN_STATE_ENABLED = "enabled" FSM_PREV_DEPLOY_BEGIN = "DeployBegin" FSM_PREV_DEPLOY_FAIL = "DeployFail" FSM_PREV_DEPLOY_SUCCESS = "DeploySuccess" FSM_PREV_DEPLOY_UPDATE_FC_MON = "DeployUpdateFcMon" FSM_PREV_NOP = "nop" FSM_RMT_INV_ERR_CODE_ERR_2FA_AUTH_RETRY = "ERR-2fa-auth-retry" FSM_RMT_INV_ERR_CODE_ERR_ACTIVATE_FAILED = "ERR-ACTIVATE-failed" FSM_RMT_INV_ERR_CODE_ERR_ACTIVATE_IN_PROGRESS = "ERR-ACTIVATE-in-progress" FSM_RMT_INV_ERR_CODE_ERR_ACTIVATE_RETRY = "ERR-ACTIVATE-retry" FSM_RMT_INV_ERR_CODE_ERR_BIOS_TOKENS_OLD_BIOS = "ERR-BIOS-TOKENS-OLD-BIOS" FSM_RMT_INV_ERR_CODE_ERR_BIOS_TOKENS_OLD_CIMC = "ERR-BIOS-TOKENS-OLD-CIMC" FSM_RMT_INV_ERR_CODE_ERR_BIOS_NETWORK_BOOT_ORDER_NOT_FOUND = "ERR-BIOS-network-boot-order-not-found" FSM_RMT_INV_ERR_CODE_ERR_BOARDCTRLUPDATE_IGNORE = "ERR-BOARDCTRLUPDATE-ignore" FSM_RMT_INV_ERR_CODE_ERR_DIAG_CANCELLED = "ERR-DIAG-cancelled" FSM_RMT_INV_ERR_CODE_ERR_DIAG_FSM_RESTARTED = "ERR-DIAG-fsm-restarted" FSM_RMT_INV_ERR_CODE_ERR_DIAG_TEST_FAILED = "ERR-DIAG-test-failed" FSM_RMT_INV_ERR_CODE_ERR_DNLD_AUTHENTICATION_FAILURE = "ERR-DNLD-authentication-failure" FSM_RMT_INV_ERR_CODE_ERR_DNLD_HOSTKEY_MISMATCH = "ERR-DNLD-hostkey-mismatch" FSM_RMT_INV_ERR_CODE_ERR_DNLD_INVALID_IMAGE = "ERR-DNLD-invalid-image" FSM_RMT_INV_ERR_CODE_ERR_DNLD_NO_FILE = "ERR-DNLD-no-file" FSM_RMT_INV_ERR_CODE_ERR_DNLD_NO_SPACE = "ERR-DNLD-no-space" FSM_RMT_INV_ERR_CODE_ERR_DNLD_USB_UNMOUNTED = "ERR-DNLD-usb-unmounted" FSM_RMT_INV_ERR_CODE_ERR_DNS_DELETE_ERROR = "ERR-DNS-delete-error" FSM_RMT_INV_ERR_CODE_ERR_DNS_GET_ERROR = "ERR-DNS-get-error" FSM_RMT_INV_ERR_CODE_ERR_DNS_SET_ERROR = "ERR-DNS-set-error" FSM_RMT_INV_ERR_CODE_ERR_DIAGNOSTICS_IN_PROGRESS = "ERR-Diagnostics-in-progress" FSM_RMT_INV_ERR_CODE_ERR_DIAGNOSTICS_MEMTEST_IN_PROGRESS = "ERR-Diagnostics-memtest-in-progress" FSM_RMT_INV_ERR_CODE_ERR_DIAGNOSTICS_NETWORK_IN_PROGRESS = "ERR-Diagnostics-network-in-progress" FSM_RMT_INV_ERR_CODE_ERR_FILTER_ILLEGAL_FORMAT = "ERR-FILTER-illegal-format" FSM_RMT_INV_ERR_CODE_ERR_FSM_NO_SUCH_STATE = "ERR-FSM-no-such-state" FSM_RMT_INV_ERR_CODE_ERR_HOST_FRU_IDENTITY_MISMATCH = "ERR-HOST-fru-identity-mismatch" FSM_RMT_INV_ERR_CODE_ERR_HTTP_SET_ERROR = "ERR-HTTP-set-error" FSM_RMT_INV_ERR_CODE_ERR_HTTPS_SET_ERROR = "ERR-HTTPS-set-error" FSM_RMT_INV_ERR_CODE_ERR_IBMC_ANALYZE_RESULTS = "ERR-IBMC-analyze-results" FSM_RMT_INV_ERR_CODE_ERR_IBMC_CONNECT_ERROR = "ERR-IBMC-connect-error" FSM_RMT_INV_ERR_CODE_ERR_IBMC_CONNECTOR_INFO_RETRIEVAL_ERROR = "ERR-IBMC-connector-info-retrieval-error" FSM_RMT_INV_ERR_CODE_ERR_IBMC_FRU_RETRIEVAL_ERROR = "ERR-IBMC-fru-retrieval-error" FSM_RMT_INV_ERR_CODE_ERR_IBMC_INVALID_END_POINT_CONFIG = "ERR-IBMC-invalid-end-point-config" FSM_RMT_INV_ERR_CODE_ERR_IBMC_RESULTS_NOT_READY = "ERR-IBMC-results-not-ready" FSM_RMT_INV_ERR_CODE_ERR_MAX_SUBSCRIPTIONS_ALLOWED_ERROR = "ERR-MAX-subscriptions-allowed-error" FSM_RMT_INV_ERR_CODE_ERR_MO_CONFIG_CHILD_OBJECT_CANT_BE_CONFIGURED = "ERR-MO-CONFIG-child-object-cant-be-configured" FSM_RMT_INV_ERR_CODE_ERR_MO_META_NO_SUCH_OBJECT_CLASS = "ERR-MO-META-no-such-object-class" FSM_RMT_INV_ERR_CODE_ERR_MO_PROPERTY_NO_SUCH_PROPERTY = "ERR-MO-PROPERTY-no-such-property" FSM_RMT_INV_ERR_CODE_ERR_MO_PROPERTY_VALUE_OUT_OF_RANGE = "ERR-MO-PROPERTY-value-out-of-range" FSM_RMT_INV_ERR_CODE_ERR_MO_ACCESS_DENIED = "ERR-MO-access-denied" FSM_RMT_INV_ERR_CODE_ERR_MO_DELETION_RULE_VIOLATION = "ERR-MO-deletion-rule-violation" FSM_RMT_INV_ERR_CODE_ERR_MO_DUPLICATE_OBJECT = "ERR-MO-duplicate-object" FSM_RMT_INV_ERR_CODE_ERR_MO_ILLEGAL_CONTAINMENT = "ERR-MO-illegal-containment" FSM_RMT_INV_ERR_CODE_ERR_MO_ILLEGAL_CREATION = "ERR-MO-illegal-creation" FSM_RMT_INV_ERR_CODE_ERR_MO_ILLEGAL_ITERATOR_STATE = "ERR-MO-illegal-iterator-state" FSM_RMT_INV_ERR_CODE_ERR_MO_ILLEGAL_OBJECT_LIFECYCLE_TRANSITION = "ERR-MO-illegal-object-lifecycle-transition" FSM_RMT_INV_ERR_CODE_ERR_MO_NAMING_RULE_VIOLATION = "ERR-MO-naming-rule-violation" FSM_RMT_INV_ERR_CODE_ERR_MO_OBJECT_NOT_FOUND = "ERR-MO-object-not-found" FSM_RMT_INV_ERR_CODE_ERR_MO_RESOURCE_ALLOCATION = "ERR-MO-resource-allocation" FSM_RMT_INV_ERR_CODE_ERR_NTP_DELETE_ERROR = "ERR-NTP-delete-error" FSM_RMT_INV_ERR_CODE_ERR_NTP_GET_ERROR = "ERR-NTP-get-error" FSM_RMT_INV_ERR_CODE_ERR_NTP_SET_ERROR = "ERR-NTP-set-error" FSM_RMT_INV_ERR_CODE_ERR_POWER_CAP_UNSUPPORTED = "ERR-POWER-CAP-UNSUPPORTED" FSM_RMT_INV_ERR_CODE_ERR_POWER_PROFILE_IN_PROGRESS = "ERR-POWER-PROFILE-IN-PROGRESS" FSM_RMT_INV_ERR_CODE_ERR_SERVER_MIS_CONNECT = "ERR-SERVER-mis-connect" FSM_RMT_INV_ERR_CODE_ERR_SWITCH_INVALID_IF_CONFIG = "ERR-SWITCH-invalid-if-config" FSM_RMT_INV_ERR_CODE_ERR_TOKEN_REQUEST_DENIED = "ERR-TOKEN-request-denied" FSM_RMT_INV_ERR_CODE_ERR_UNABLE_TO_FETCH_BIOS_SETTINGS = "ERR-UNABLE-TO-FETCH-BIOS-SETTINGS" FSM_RMT_INV_ERR_CODE_ERR_UPDATE_FAILED = "ERR-UPDATE-failed" FSM_RMT_INV_ERR_CODE_ERR_UPDATE_IN_PROGRESS = "ERR-UPDATE-in-progress" FSM_RMT_INV_ERR_CODE_ERR_UPDATE_RETRY = "ERR-UPDATE-retry" FSM_RMT_INV_ERR_CODE_ERR_AAA_CONFIG_MODIFY_ERROR = "ERR-aaa-config-modify-error" FSM_RMT_INV_ERR_CODE_ERR_ACCT_REALM_SET_ERROR = "ERR-acct-realm-set-error" FSM_RMT_INV_ERR_CODE_ERR_ADMIN_PASSWD_SET = "ERR-admin-passwd-set" FSM_RMT_INV_ERR_CODE_ERR_AUTH_ISSUE = "ERR-auth-issue" FSM_RMT_INV_ERR_CODE_ERR_AUTH_REALM_GET_ERROR = "ERR-auth-realm-get-error" FSM_RMT_INV_ERR_CODE_ERR_AUTH_REALM_SET_ERROR = "ERR-auth-realm-set-error" FSM_RMT_INV_ERR_CODE_ERR_AUTHENTICATION = "ERR-authentication" FSM_RMT_INV_ERR_CODE_ERR_AUTHORIZATION_REQUIRED = "ERR-authorization-required" FSM_RMT_INV_ERR_CODE_ERR_CLI_SESSION_LIMIT_REACHED = "ERR-cli-session-limit-reached" FSM_RMT_INV_ERR_CODE_ERR_CREATE_KEYRING = "ERR-create-keyring" FSM_RMT_INV_ERR_CODE_ERR_CREATE_LOCALE = "ERR-create-locale" FSM_RMT_INV_ERR_CODE_ERR_CREATE_ROLE = "ERR-create-role" FSM_RMT_INV_ERR_CODE_ERR_CREATE_TP = "ERR-create-tp" FSM_RMT_INV_ERR_CODE_ERR_CREATE_USER = "ERR-create-user" FSM_RMT_INV_ERR_CODE_ERR_DELETE_LOCALE = "ERR-delete-locale" FSM_RMT_INV_ERR_CODE_ERR_DELETE_ROLE = "ERR-delete-role" FSM_RMT_INV_ERR_CODE_ERR_DELETE_SESSION = "ERR-delete-session" FSM_RMT_INV_ERR_CODE_ERR_DELETE_USER = "ERR-delete-user" FSM_RMT_INV_ERR_CODE_ERR_DOWNGRADE_FAIL = "ERR-downgrade-fail" FSM_RMT_INV_ERR_CODE_ERR_EFI_DIAGNOSTICS_IN_PROGRESS = "ERR-efi-Diagnostics--in-progress" FSM_RMT_INV_ERR_CODE_ERR_ENABLE_MGMT_CONN = "ERR-enable-mgmt-conn" FSM_RMT_INV_ERR_CODE_ERR_EP_SET_ERROR = "ERR-ep-set-error" FSM_RMT_INV_ERR_CODE_ERR_GET_MAX_HTTP_USER_SESSIONS = "ERR-get-max-http-user-sessions" FSM_RMT_INV_ERR_CODE_ERR_HTTP_INITIALIZING = "ERR-http-initializing" FSM_RMT_INV_ERR_CODE_ERR_INSUFFICIENTLY_EQUIPPED = "ERR-insufficiently-equipped" FSM_RMT_INV_ERR_CODE_ERR_INTERNAL_ERROR = "ERR-internal-error" FSM_RMT_INV_ERR_CODE_ERR_LDAP_DELETE_ERROR = "ERR-ldap-delete-error" FSM_RMT_INV_ERR_CODE_ERR_LDAP_GET_ERROR = "ERR-ldap-get-error" FSM_RMT_INV_ERR_CODE_ERR_LDAP_GROUP_MODIFY_ERROR = "ERR-ldap-group-modify-error" FSM_RMT_INV_ERR_CODE_ERR_LDAP_GROUP_SET_ERROR = "ERR-ldap-group-set-error" FSM_RMT_INV_ERR_CODE_ERR_LDAP_SET_ERROR = "ERR-ldap-set-error" FSM_RMT_INV_ERR_CODE_ERR_LOCALE_SET_ERROR = "ERR-locale-set-error" FSM_RMT_INV_ERR_CODE_ERR_MAX_USERID_SESSIONS_REACHED = "ERR-max-userid-sessions-reached" FSM_RMT_INV_ERR_CODE_ERR_MISSING_METHOD = "ERR-missing-method" FSM_RMT_INV_ERR_CODE_ERR_MODIFY_LOCALE = "ERR-modify-locale" FSM_RMT_INV_ERR_CODE_ERR_MODIFY_ROLE = "ERR-modify-role" FSM_RMT_INV_ERR_CODE_ERR_MODIFY_USER = "ERR-modify-user" FSM_RMT_INV_ERR_CODE_ERR_MODIFY_USER_LOCALE = "ERR-modify-user-locale" FSM_RMT_INV_ERR_CODE_ERR_MODIFY_USER_ROLE = "ERR-modify-user-role" FSM_RMT_INV_ERR_CODE_ERR_PROVIDER_GROUP_MODIFY_ERROR = "ERR-provider-group-modify-error" FSM_RMT_INV_ERR_CODE_ERR_PROVIDER_GROUP_SET_ERROR = "ERR-provider-group-set-error" FSM_RMT_INV_ERR_CODE_ERR_RADIUS_GET_ERROR = "ERR-radius-get-error" FSM_RMT_INV_ERR_CODE_ERR_RADIUS_GLOBAL_SET_ERROR = "ERR-radius-global-set-error" FSM_RMT_INV_ERR_CODE_ERR_RADIUS_GROUP_SET_ERROR = "ERR-radius-group-set-error" FSM_RMT_INV_ERR_CODE_ERR_RADIUS_SET_ERROR = "ERR-radius-set-error" FSM_RMT_INV_ERR_CODE_ERR_REQUEST_TIMEOUT = "ERR-request-timeout" FSM_RMT_INV_ERR_CODE_ERR_RESET_ADAPTER = "ERR-reset-adapter" FSM_RMT_INV_ERR_CODE_ERR_ROLE_SET_ERROR = "ERR-role-set-error" FSM_RMT_INV_ERR_CODE_ERR_SECONDARY_NODE = "ERR-secondary-node" FSM_RMT_INV_ERR_CODE_ERR_SERVICE_NOT_READY = "ERR-service-not-ready" FSM_RMT_INV_ERR_CODE_ERR_SESSION_CACHE_FULL = "ERR-session-cache-full" FSM_RMT_INV_ERR_CODE_ERR_SESSION_NOT_FOUND = "ERR-session-not-found" FSM_RMT_INV_ERR_CODE_ERR_SET_NETWORK = "ERR-set-network" FSM_RMT_INV_ERR_CODE_ERR_SET_PASSWORD_STRENGTH_CHECK = "ERR-set-password-strength-check" FSM_RMT_INV_ERR_CODE_ERR_SET_PORT_CHANNEL = "ERR-set-port-channel" FSM_RMT_INV_ERR_CODE_ERR_STORE_PRE_LOGIN_BANNER_MSG = "ERR-store-pre-login-banner-msg" FSM_RMT_INV_ERR_CODE_ERR_TACACS_ENABLE_ERROR = "ERR-tacacs-enable-error" FSM_RMT_INV_ERR_CODE_ERR_TACACS_GLOBAL_SET_ERROR = "ERR-tacacs-global-set-error" FSM_RMT_INV_ERR_CODE_ERR_TACACS_GROUP_SET_ERROR = "ERR-tacacs-group-set-error" FSM_RMT_INV_ERR_CODE_ERR_TACACS_PLUS_GET_ERROR = "ERR-tacacs-plus-get-error" FSM_RMT_INV_ERR_CODE_ERR_TACACS_SET_ERROR = "ERR-tacacs-set-error" FSM_RMT_INV_ERR_CODE_ERR_TEST_ERROR_1 = "ERR-test-error-1" FSM_RMT_INV_ERR_CODE_ERR_TEST_ERROR_2 = "ERR-test-error-2" FSM_RMT_INV_ERR_CODE_ERR_TIMEZONE_SET_ERROR = "ERR-timezone-set-error" FSM_RMT_INV_ERR_CODE_ERR_USER_ACCOUNT_EXPIRED = "ERR-user-account-expired" FSM_RMT_INV_ERR_CODE_ERR_USER_SET_ERROR = "ERR-user-set-error" FSM_RMT_INV_ERR_CODE_ERR_XML_PARSE_ERROR = "ERR-xml-parse-error" FSM_RMT_INV_ERR_CODE_NONE = "none" FSM_STAMP_NEVER = "never" FSM_STATUS_DEPLOY_BEGIN = "DeployBegin" FSM_STATUS_DEPLOY_FAIL = "DeployFail" FSM_STATUS_DEPLOY_SUCCESS = "DeploySuccess" FSM_STATUS_DEPLOY_UPDATE_FC_MON = "DeployUpdateFcMon" FSM_STATUS_NOP = "nop" HAS_LAST_DEST_FALSE = "false" HAS_LAST_DEST_NO = "no" HAS_LAST_DEST_TRUE = "true" HAS_LAST_DEST_YES = "yes" LIFE_CYCLE_DELETED = "deleted" LIFE_CYCLE_NEW = "new" LIFE_CYCLE_NORMAL = "normal" SWITCH_ID_A = "A" SWITCH_ID_B = "B" SWITCH_ID_NONE = "NONE" class SwFcMon(ManagedObject): """This is SwFcMon class.""" consts = SwFcMonConsts() naming_props = set([u'name']) mo_meta = MoMeta("SwFcMon", "swFcMon", "mon-[name]", VersionMeta.Version141i, "InputOutput", 0xff, [], ["read-only"], [u'swFcSanMon'], [u'dcxVc', u'eventInst', u'faultInst', u'swEthMonDestEp', u'swFcMonDestEp', u'swFcMonFsm', u'swFcMonFsmTask', u'swFcMonSrcEp', u'swFcSanPc', u'swFcoeSanPc', u'swSubGroup', u'swVsan'], ["Get"]) prop_meta = { "admin_state": MoPropertyMeta("admin_state", "adminState", "string", VersionMeta.Version141i, MoPropertyMeta.READ_WRITE, 0x2, None, None, None, ["disabled", "enabled"], []), "child_action": MoPropertyMeta("child_action", "childAction", "string", VersionMeta.Version141i, MoPropertyMeta.INTERNAL, 0x4, None, None, r"""((deleteAll|ignore|deleteNonPresent),){0,2}(deleteAll|ignore|deleteNonPresent){0,1}""", [], []), "dn": MoPropertyMeta("dn", "dn", "string", VersionMeta.Version141i, MoPropertyMeta.READ_ONLY, 0x8, 0, 256, None, [], []), "fsm_descr": MoPropertyMeta("fsm_descr", "fsmDescr", "string", VersionMeta.Version141i, MoPropertyMeta.INTERNAL, None, None, None, None, [], []), "fsm_prev": MoPropertyMeta("fsm_prev", "fsmPrev", "string", VersionMeta.Version141i, MoPropertyMeta.INTERNAL, None, None, None, None, ["DeployBegin", "DeployFail", "DeploySuccess", "DeployUpdateFcMon", "nop"], []), "fsm_progr": MoPropertyMeta("fsm_progr", "fsmProgr", "byte", VersionMeta.Version141i, MoPropertyMeta.INTERNAL, None, None, None, None, [], ["0-100"]), "fsm_rmt_inv_err_code": MoPropertyMeta("fsm_rmt_inv_err_code", "fsmRmtInvErrCode", "string", VersionMeta.Version141i, MoPropertyMeta.INTERNAL, None, None, None, None, ["ERR-2fa-auth-retry", "ERR-ACTIVATE-failed", "ERR-ACTIVATE-in-progress", "ERR-ACTIVATE-retry", "ERR-BIOS-TOKENS-OLD-BIOS", "ERR-BIOS-TOKENS-OLD-CIMC", "ERR-BIOS-network-boot-order-not-found", "ERR-BOARDCTRLUPDATE-ignore", "ERR-DIAG-cancelled", "ERR-DIAG-fsm-restarted", "ERR-DIAG-test-failed", "ERR-DNLD-authentication-failure", "ERR-DNLD-hostkey-mismatch", "ERR-DNLD-invalid-image", "ERR-DNLD-no-file", "ERR-DNLD-no-space", "ERR-DNLD-usb-unmounted", "ERR-DNS-delete-error", "ERR-DNS-get-error", "ERR-DNS-set-error", "ERR-Diagnostics-in-progress", "ERR-Diagnostics-memtest-in-progress", "ERR-Diagnostics-network-in-progress", "ERR-FILTER-illegal-format", "ERR-FSM-no-such-state", "ERR-HOST-fru-identity-mismatch", "ERR-HTTP-set-error", "ERR-HTTPS-set-error", "ERR-IBMC-analyze-results", "ERR-IBMC-connect-error", "ERR-IBMC-connector-info-retrieval-error", "ERR-IBMC-fru-retrieval-error", "ERR-IBMC-invalid-end-point-config", "ERR-IBMC-results-not-ready", "ERR-MAX-subscriptions-allowed-error", "ERR-MO-CONFIG-child-object-cant-be-configured", "ERR-MO-META-no-such-object-class", "ERR-MO-PROPERTY-no-such-property", "ERR-MO-PROPERTY-value-out-of-range", "ERR-MO-access-denied", "ERR-MO-deletion-rule-violation", "ERR-MO-duplicate-object", "ERR-MO-illegal-containment", "ERR-MO-illegal-creation", "ERR-MO-illegal-iterator-state", "ERR-MO-illegal-object-lifecycle-transition", "ERR-MO-naming-rule-violation", "ERR-MO-object-not-found", "ERR-MO-resource-allocation", "ERR-NTP-delete-error", "ERR-NTP-get-error", "ERR-NTP-set-error", "ERR-POWER-CAP-UNSUPPORTED", "ERR-POWER-PROFILE-IN-PROGRESS", "ERR-SERVER-mis-connect", "ERR-SWITCH-invalid-if-config", "ERR-TOKEN-request-denied", "ERR-UNABLE-TO-FETCH-BIOS-SETTINGS", "ERR-UPDATE-failed", "ERR-UPDATE-in-progress", "ERR-UPDATE-retry", "ERR-aaa-config-modify-error", "ERR-acct-realm-set-error", "ERR-admin-passwd-set", "ERR-auth-issue", "ERR-auth-realm-get-error", "ERR-auth-realm-set-error", "ERR-authentication", "ERR-authorization-required", "ERR-cli-session-limit-reached", "ERR-create-keyring", "ERR-create-locale", "ERR-create-role", "ERR-create-tp", "ERR-create-user", "ERR-delete-locale", "ERR-delete-role", "ERR-delete-session", "ERR-delete-user", "ERR-downgrade-fail", "ERR-efi-Diagnostics--in-progress", "ERR-enable-mgmt-conn", "ERR-ep-set-error", "ERR-get-max-http-user-sessions", "ERR-http-initializing", "ERR-insufficiently-equipped", "ERR-internal-error", "ERR-ldap-delete-error", "ERR-ldap-get-error", "ERR-ldap-group-modify-error", "ERR-ldap-group-set-error", "ERR-ldap-set-error", "ERR-locale-set-error", "ERR-max-userid-sessions-reached", "ERR-missing-method", "ERR-modify-locale", "ERR-modify-role", "ERR-modify-user", "ERR-modify-user-locale", "ERR-modify-user-role", "ERR-provider-group-modify-error", "ERR-provider-group-set-error", "ERR-radius-get-error", "ERR-radius-global-set-error", "ERR-radius-group-set-error", "ERR-radius-set-error", "ERR-request-timeout", "ERR-reset-adapter", "ERR-role-set-error", "ERR-secondary-node", "ERR-service-not-ready", "ERR-session-cache-full", "ERR-session-not-found", "ERR-set-network", "ERR-set-password-strength-check", "ERR-set-port-channel", "ERR-store-pre-login-banner-msg", "ERR-tacacs-enable-error", "ERR-tacacs-global-set-error", "ERR-tacacs-group-set-error", "ERR-tacacs-plus-get-error", "ERR-tacacs-set-error", "ERR-test-error-1", "ERR-test-error-2", "ERR-timezone-set-error", "ERR-user-account-expired", "ERR-user-set-error", "ERR-xml-parse-error", "none"], ["0-4294967295"]), "fsm_rmt_inv_err_descr": MoPropertyMeta("fsm_rmt_inv_err_descr", "fsmRmtInvErrDescr", "string", VersionMeta.Version141i, MoPropertyMeta.INTERNAL, None, 0, 510, None, [], []), "fsm_rmt_inv_rslt": MoPropertyMeta("fsm_rmt_inv_rslt", "fsmRmtInvRslt", "string", VersionMeta.Version141i, MoPropertyMeta.INTERNAL, None, None, None, r"""((defaultValue|not-applicable|resource-unavailable|service-unavailable|intermittent-error|sw-defect|service-not-implemented-ignore|extend-timeout|capability-not-implemented-failure|illegal-fru|end-point-unavailable|failure|resource-capacity-exceeded|service-protocol-error|fw-defect|service-not-implemented-fail|task-reset|unidentified-fail|capability-not-supported|end-point-failed|fru-state-indeterminate|resource-dependency|fru-identity-indeterminate|internal-error|hw-defect|service-not-supported|fru-not-supported|end-point-protocol-error|capability-unavailable|fru-not-ready|capability-not-implemented-ignore|fru-info-malformed|timeout),){0,32}(defaultValue|not-applicable|resource-unavailable|service-unavailable|intermittent-error|sw-defect|service-not-implemented-ignore|extend-timeout|capability-not-implemented-failure|illegal-fru|end-point-unavailable|failure|resource-capacity-exceeded|service-protocol-error|fw-defect|service-not-implemented-fail|task-reset|unidentified-fail|capability-not-supported|end-point-failed|fru-state-indeterminate|resource-dependency|fru-identity-indeterminate|internal-error|hw-defect|service-not-supported|fru-not-supported|end-point-protocol-error|capability-unavailable|fru-not-ready|capability-not-implemented-ignore|fru-info-malformed|timeout){0,1}""", [], []), "fsm_stage_descr": MoPropertyMeta("fsm_stage_descr", "fsmStageDescr", "string", VersionMeta.Version141i, MoPropertyMeta.INTERNAL, None, None, None, None, [], []), "fsm_stamp": MoPropertyMeta("fsm_stamp", "fsmStamp", "string", VersionMeta.Version141i, MoPropertyMeta.INTERNAL, None, None, None, r"""([0-9]){4}-([0-9]){2}-([0-9]){2}T([0-9]){2}:([0-9]){2}:([0-9]){2}((\.([0-9]){3})){0,1}""", ["never"], []), "fsm_status": MoPropertyMeta("fsm_status", "fsmStatus", "string", VersionMeta.Version141i, MoPropertyMeta.INTERNAL, None, None, None, None, ["DeployBegin", "DeployFail", "DeploySuccess", "DeployUpdateFcMon", "nop"], []), "fsm_try": MoPropertyMeta("fsm_try", "fsmTry", "byte", VersionMeta.Version141i, MoPropertyMeta.INTERNAL, None, None, None, None, [], []), "has_last_dest": MoPropertyMeta("has_last_dest", "hasLastDest", "string", VersionMeta.Version141i, MoPropertyMeta.READ_ONLY, None, None, None, None, ["false", "no", "true", "yes"], []), "life_cycle": MoPropertyMeta("life_cycle", "lifeCycle", "string", VersionMeta.Version141i, MoPropertyMeta.READ_ONLY, None, None, None, None, ["deleted", "new", "normal"], []), "name": MoPropertyMeta("name", "name", "string", VersionMeta.Version141i, MoPropertyMeta.NAMING, 0x10, None, None, r"""[\-\.:_a-zA-Z0-9]{1,16}""", [], []), "peer_dn": MoPropertyMeta("peer_dn", "peerDn", "string", VersionMeta.Version141i, MoPropertyMeta.READ_ONLY, None, 0, 256, None, [], []), "rn": MoPropertyMeta("rn", "rn", "string", VersionMeta.Version141i, MoPropertyMeta.READ_ONLY, 0x20, 0, 256, None, [], []), "sacl": MoPropertyMeta("sacl", "sacl", "string", VersionMeta.Version302a, MoPropertyMeta.READ_ONLY, None, None, None, r"""((none|del|mod|addchild|cascade),){0,4}(none|del|mod|addchild|cascade){0,1}""", [], []), "session": MoPropertyMeta("session", "session", "uint", VersionMeta.Version141i, MoPropertyMeta.READ_ONLY, None, None, None, None, [], ["1-255"]), "status": MoPropertyMeta("status", "status", "string", VersionMeta.Version141i, MoPropertyMeta.READ_WRITE, 0x40, None, None, r"""((removed|created|modified|deleted),){0,3}(removed|created|modified|deleted){0,1}""", [], []), "switch_id": MoPropertyMeta("switch_id", "switchId", "string", VersionMeta.Version141i, MoPropertyMeta.READ_WRITE, 0x80, None, None, None, ["A", "B", "NONE"], []), "transport": MoPropertyMeta("transport", "transport", "string", VersionMeta.Version141i, MoPropertyMeta.READ_ONLY, None, None, None, r"""((defaultValue|unknown|ether|dce|fc),){0,4}(defaultValue|unknown|ether|dce|fc){0,1}""", [], []), "type": MoPropertyMeta("type", "type", "string", VersionMeta.Version141i, MoPropertyMeta.READ_ONLY, None, None, None, r"""((defaultValue|unknown|lan|san|ipc),){0,4}(defaultValue|unknown|lan|san|ipc){0,1}""", [], []), } prop_map = { "adminState": "admin_state", "childAction": "child_action", "dn": "dn", "fsmDescr": "fsm_descr", "fsmPrev": "fsm_prev", "fsmProgr": "fsm_progr", "fsmRmtInvErrCode": "fsm_rmt_inv_err_code", "fsmRmtInvErrDescr": "fsm_rmt_inv_err_descr", "fsmRmtInvRslt": "fsm_rmt_inv_rslt", "fsmStageDescr": "fsm_stage_descr", "fsmStamp": "fsm_stamp", "fsmStatus": "fsm_status", "fsmTry": "fsm_try", "hasLastDest": "has_last_dest", "lifeCycle": "life_cycle", "name": "name", "peerDn": "peer_dn", "rn": "rn", "sacl": "sacl", "session": "session", "status": "status", "switchId": "switch_id", "transport": "transport", "type": "type", } def __init__(self, parent_mo_or_dn, name, **kwargs): self._dirty_mask = 0 self.name = name self.admin_state = None self.child_action = None self.fsm_descr = None self.fsm_prev = None self.fsm_progr = None self.fsm_rmt_inv_err_code = None self.fsm_rmt_inv_err_descr = None self.fsm_rmt_inv_rslt = None self.fsm_stage_descr = None self.fsm_stamp = None self.fsm_status = None self.fsm_try = None self.has_last_dest = None self.life_cycle = None self.peer_dn = None self.sacl = None self.session = None self.status = None self.switch_id = None self.transport = None self.type = None ManagedObject.__init__(self, "SwFcMon", parent_mo_or_dn, **kwargs)
034ebb7456f82467d4f6eac71983f9f9b364a2db
306045a1cd0fb362f46d4db88311f442311bbc16
/examples/idioms/programs/002.0011-print-hello-10-times.py
3793da0117c8784ebd602f2ed2ba9a02168556cd
[ "MIT" ]
permissive
laowantong/paroxython
608c9010a2b57c8f7ed5ea309e24035c2b2e44a3
a6d45829dd34f046d20e5bae780fbf7af59429cb
refs/heads/master
2023-09-01T05:18:29.687916
2022-11-07T17:40:31
2022-11-07T17:40:31
220,820,424
36
5
MIT
2023-09-08T04:44:58
2019-11-10T16:54:56
Python
UTF-8
Python
false
false
307
py
"""Print Hello 10 times. Loop to execute some code a constant number of times Source: programming-idioms.org """ # Implementation author: # Created on 2015-11-30T12:37:23.746597Z # Last modified on 2019-09-27T02:17:54.987284Z # Version 2 # Indention is mandatory for i in range(10): print("Hello")
8dfe4354130dd664527f1ddd3ce0a81ac5a51536
3c9103046db53185cfedc1598933a790718e4d57
/pygame_assets/tests/test_loaders.py
e8d9dde92a8a2bda26361859538fcfebf686ce40
[ "MIT" ]
permissive
florimondmanca/pygame-assets
9aabe7e482e72c37a95f9283f6b67e47acadf941
1ad7870800866d2b1b287d8063bd10edd99fd521
refs/heads/master
2021-08-19T12:46:04.149161
2017-11-25T12:14:06
2017-11-25T12:14:06
110,216,972
3
0
null
2017-11-11T12:28:38
2017-11-10T07:31:56
Python
UTF-8
Python
false
false
5,844
py
"""Tests for the loaders API.""" import unittest import pygame from pygame_assets.loaders import image as load_image from pygame_assets.loaders import image_with_rect as load_image_with_rect from pygame_assets.loaders import sound as load_sound from pygame_assets.loaders import music as load_music from pygame_assets.loaders import font as load_font from pygame_assets.loaders import freetype as load_freetype from pygame_assets.configure import get_config from .utils import TestCase, change_config class LoaderTestCase(TestCase): """Test case suited for loader unit testing. Class attributes ---------------- loader : function A loader as defined by pygame_assets. filename : str If defined, the .asset() shortcut will be available to get the corresponding asset. """ filename = None loader = None @classmethod def asset(cls, *args, **kwargs): if cls.filename is None: raise ValueError('Could not get asset: no filename defined.') return cls.loader(cls.filename, *args, **kwargs) class TestImageLoader(LoaderTestCase): """Unit tests for the image loader.""" loader = load_image filename = 'test-image.png' @classmethod def setUpClass(cls): pygame.init() # pygame requires to set_mode before loading images # the same constraint applies to pygame_assets cls.screen = pygame.display.set_mode((800, 600)) def test_load_image_from_path(self): self.assertIsInstance(self.asset(), pygame.Surface) def test_image_with_alpha_keeps_alpha(self): image = load_image('test-image-with-alpha.png') self.assertIsNotNone(image.get_alpha()) def test_image_without_alpha_has_no_alpha(self): image = load_image('test-image-without-alpha.jpg') self.assertIsNone(image.get_alpha()) def test_force_convert_alpha(self): self.asset(convert_alpha=True) self.asset(convert_alpha=False) def test_alpha_is_kwarg_only(self): with self.assertRaises(TypeError): self.asset(True) class TestImageWithRectLoader(LoaderTestCase): """Unit tests for the image_with_rect loader.""" loader = load_image_with_rect filename = 'test-image.png' @classmethod def setUpClass(cls): pygame.init() # pygame requires to set_mode before loading images # the same constraint applies to pygame_assets cls.screen = pygame.display.set_mode((800, 600)) def test_load_image_with_rect(self): image, rect = self.asset() self.assertIsInstance(image, pygame.Surface) self.assertIsInstance(rect, pygame.Rect) class TestSoundLoader(LoaderTestCase): """Unit tests for the sound loader.""" loader = load_sound filename = 'test-sound.wav' @classmethod def setUpClass(cls): pygame.mixer.init() def test_load_sound_from_path(self): self.assertIsInstance(self.asset(), pygame.mixer.Sound) def test_set_volume_when_loading(self): sound = self.asset(volume=0.5) self.assertEqual(sound.get_volume(), 0.5) def test_volume_is_kwarg_only(self): with self.assertRaises(TypeError): self.asset(0.5) class TestMusicLoader(LoaderTestCase): """Unit tests for the music loader.""" loader = load_music filename = 'test-sound.wav' @classmethod def setUpClass(cls): pygame.mixer.init() def test_dir_is_sound(self): self.assertListEqual(get_config().dirs['music'], ['sound']) def test_load_music_from_path(self): self.assertFalse(pygame.mixer.music.get_busy()) returned_value = self.asset() self.assertIsNone(returned_value) # music did not start playing self.assertFalse(pygame.mixer.music.get_busy()) def test_set_volume_when_loading(self): self.asset(volume=0.5) self.assertEqual(pygame.mixer.music.get_volume(), 0.5) def test_volume_is_kwarg_only(self): with self.assertRaises(TypeError): self.asset(0.5) class TestFontLoader(LoaderTestCase): """Unit tests for the font loader.""" filename = 'bebas-neue.otf' loader = load_font @classmethod def setUpClass(cls): pygame.font.init() def test_load_font_from_path(self): self.assertIsInstance(self.asset(), pygame.font.Font) def test_load_with_size(self): self.assertAlmostEqual(self.asset(size=40).get_height(), 40, delta=10) def test_default_size_is_20(self): self.assertEqual(get_config().default_font_size, 20) self.assertAlmostEqual(self.asset().get_height(), 20, delta=10) def test_default_change_default_size(self): with change_config('default_font_size') as config: config.default_font_size = 60 self.assertAlmostEqual(self.asset().get_height(), 60, delta=15) class TestFreetypeFontLoader(LoaderTestCase): """Unit tests for the freetype font loader.""" filename = 'bebas-neue.otf' loader = load_freetype @classmethod def setUpClass(cls): pygame.font.init() def test_dir_is_font(self): self.assertListEqual(get_config().dirs['freetype'], ['font']) def test_load_font_from_path(self): self.assertIsInstance(self.asset(), pygame.freetype.Font) def test_load_with_size(self): self.assertEqual(self.asset(size=40).size, 40) def test_default_size_is_20(self): self.assertEqual(get_config().default_font_size, 20) self.assertEqual(self.asset().size, 20) def test_change_default_size(self): with change_config('default_font_size') as config: config.default_font_size = 60 self.assertEqual(self.asset().size, 60) if __name__ == '__main__': unittest.main()
18c381de7282cb9e143b3c630f47752bc1dca908
894b8a99a3e05dda63ff156d9a2f3ce81f25c3ba
/imix/data/reader/textvqa_reader.py
984acecbce85bfcc240b0181dd9e58d455efa3cc
[ "Apache-2.0" ]
permissive
jjInsper/iMIX
e5e46c580e2925fb94a2571c25777ce504ffab14
99898de97ef8b45462ca1d6bf2542e423a73d769
refs/heads/master
2023-08-08T01:24:47.161948
2021-09-16T09:35:35
2021-09-16T09:35:35
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,379
py
from ..utils.stream import ItemFeature from .base_reader import IMIXDataReader from imix.utils.common_function import update_d1_with_d2 class TextVQAReader(IMIXDataReader): def __init__(self, cfg): super().__init__(cfg) # assert self.default_feature, ('Not support non-default features now.') def __len__(self): return len(self.mix_annotations) def __getitem__(self, idx): annotation = self.mix_annotations[idx] feature = self.feature_obj[idx] global_feature, ocr_feature = {}, {} item_feature = ItemFeature(annotation) item_feature.error = False item_feature.tokens = annotation['question_tokens'] item_feature.img_id = annotation['image_id'] update_d1_with_d2(d1=item_feature, d2=feature) if self.global_feature_obj: global_feature = self.global_feature_obj[idx] global_feature.update({'features_global': global_feature.pop('features')}) update_d1_with_d2(d1=item_feature, d2=global_feature) if self.ocr_feature_obj: ocr_feature = self.ocr_feature_obj[idx] ocr_feature.update({'features_ocr': ocr_feature.pop('features')}) update_d1_with_d2(d1=item_feature, d2=ocr_feature) item_feature.error = None in [feature, global_feature, ocr_feature] return item_feature
08d782838db68810147ca27d62dcd4ca28c26ec9
e81d274d6a1bcabbe7771612edd43b42c0d48197
/Django/day76(中间件)/demo/webapp/user/views.py
45a2bf2c3f84afbb53964e886aeb9bd72f7aabe7
[ "MIT" ]
permissive
ChWeiking/PythonTutorial
1259dc04c843382f2323d69f6678b9431d0b56fd
1aa4b81cf26fba2fa2570dd8e1228fef4fd6ee61
refs/heads/master
2020-05-15T00:50:10.583105
2016-07-30T16:03:45
2016-07-30T16:03:45
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,800
py
from django.shortcuts import render,redirect from user.models import * from hashlib import * from django.http import * from django.template import loader,RequestContext from django.core.urlresolvers import reverse from datetime import timedelta from django.views.decorators.csrf import csrf_exempt from PIL import Image, ImageDraw, ImageFont, ImageFilter from io import StringIO,BytesIO import random # Create your views here. def register(request): return render(request, 'user/register.html') def register_handler(request): user = User() user.uname = request.POST.get('username') user.upwd = sha1(request.POST.get('userpwd').encode('utf-8')).hexdigest() user.save() return render(request, 'user/success.html') def login(request): print('session:%s'%request.session.get('currentUser')) context = {} #获取cookie username = request.COOKIES.get('mycooki') if username: context['username']=username return render(request, 'user/login.html',context) #@csrf_exempt def login_handler(request): # 定义上下文 context = {} #获取验证码 userverification = request.POST.get('userverification') if userverification==None or request.session['codes'].upper() != userverification.upper(): context = {'userverification_error':'验证码输入错误'} return render(request,'user/login.html',context) #用户名密码 username = request.POST.get('username') userpwd = sha1(request.POST.get('userpwd').encode('utf-8')).hexdigest() #匹配 ret = User.objects.filter(uname=username,upwd=userpwd) if len(ret)==0: return HttpResponseRedirect('/user/login') else: #在服务端保持一个session键值对 request.session['currentUser'] = username request.session.set_expiry(36000) #request.session.set_expiry(timedelta(days=2)) #加载模板 t1 = loader.get_template('user/success.html') #上下文 requestcontext = RequestContext(request,context) #创建具有模板和上下文的reponse response = HttpResponse(t1.render(requestcontext)) #记录用户名密码的变量 rememberName = request.POST.get('rememberName') #判断 if rememberName=='1': #写cookie response.set_cookie('mycookie',username,max_age=3600) return response def verification(request): # 240 x 60: width = 60 * 4 height = 60 image = Image.new('RGB', (width, height), (255, 255, 255)) # 创建Font对象: font = ImageFont.truetype('/usr/share/fonts/truetype/liberation/LiberationSerif-BoldItalic.ttf', 36) # 创建Draw对象: draw = ImageDraw.Draw(image) # 填充每个像素: for x in range(width): for y in range(height): draw.point((x, y), fill=rndColor()) #储存验证码字符串 codes = '' # 输出文字: for t in range(4): code = rndChar() codes += code draw.text((60 * t + 10, 10),code , font=font, fill=rndColor2()) # 模糊: image = image.filter(ImageFilter.BLUR) #将验证码字符串存储到session中 request.session['codes'] = codes request.session.set_expiry(0) #内存级的字节读写 f = BytesIO() image.save(f,'jpeg') return HttpResponse(f.getvalue(),'image/jpeg') def test1(request): #模拟异常 num = 1/0 return render(request, 'user/test1.html') # 随机字母: def rndChar(): return chr(random.randint(65, 90)) # 随机颜色1: def rndColor(): return (random.randint(64, 255), random.randint(64, 255), random.randint(64, 255)) # 随机颜色2: def rndColor2(): return (random.randint(32, 127), random.randint(32, 127), random.randint(32, 127))
afb62f95eaaa4ce1aada8b5967d560921f144a77
6d2e4655ce0a9012aea88c83e2f49572e6d06738
/day-04/day-04-passport-processing-01.py
e90db8ced1bc732920d3e2c46bd83a708a9de7e0
[]
no_license
LilySu/Advent_of_Code_2020
d7664b2e4469e5b0434db94d2452cdf62bc05daa
521da7b20b3e47d49a6180e2a2aad78b4d923efa
refs/heads/main
2023-02-05T00:51:56.363196
2020-12-26T03:43:30
2020-12-26T03:43:30
321,393,922
0
0
null
null
null
null
UTF-8
Python
false
false
1,156
py
import re from typing import List from run_for_all_input_and_timer import Manager, timer setup = Manager() input = setup.get_file() @timer def solve(input: List[str]) -> int: counter = 0 passports = [] txt_block = [] req = ['byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid'] reqc = ['byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid', 'cid'] for line in input: if line != '': if ' ' in line: line = line.split(' ') for i in line: txt_block.append(i) else: txt_block.append(line) else: passports.append(txt_block) txt_block = [] for idx, txt_block in enumerate(passports): for idy, field in enumerate(passports[idx]): before_colon = re.compile(r"^[^:]+:") [requirement] = before_colon.findall(field) passports[idx][idy] = requirement[:-1] for txt_block in passports: if (sorted(txt_block) == sorted(req)) or (sorted(txt_block) == sorted(reqc)): counter += 1 return counter if __name__ == "__main__": print(solve(input))
fd4b9bbad032fd93f0ca1ccbfe850ab51f7e941f
487ce91881032c1de16e35ed8bc187d6034205f7
/codes/CodeJamCrawler/16_0_2/babpls/pancake.py
d28c2b437d135f52472fcf97a0e7317ca7ed9438
[]
no_license
DaHuO/Supergraph
9cd26d8c5a081803015d93cf5f2674009e92ef7e
c88059dc66297af577ad2b8afa4e0ac0ad622915
refs/heads/master
2021-06-14T16:07:52.405091
2016-08-21T13:39:13
2016-08-21T13:39:13
49,829,508
2
0
null
2021-03-19T21:55:46
2016-01-17T18:23:00
Python
UTF-8
Python
false
false
324
py
fin = open('pancake.in', 'r') fout = open('pancake.out', 'w') count = 0 for line in fin: if count != 0: out = 0 cur = '+' for x in line[:-1][::-1]: if cur != x: cur = x out += 1 fout.write('Case #%d: %s\n' % (count, str(out))) count += 1
ca694b19b1ddaa3393d91190f4addb316c5fd96e
8240abd177ece3a1cf2d753cc5694c1fec478709
/week1/codeingBat/list-2/04.py
def4b4029205be7d5c428af84f9eba1616343dda
[]
no_license
DastanB/BF-Django
255001185d8a8318bd19b750fe662a7f86b64d92
adcd1d968b94ea5097fd3d03338f031d5497d463
refs/heads/master
2022-10-27T06:44:56.648527
2018-11-24T18:33:35
2018-11-24T18:33:35
147,125,321
1
1
null
2022-10-19T08:22:54
2018-09-02T22:07:22
Python
UTF-8
Python
false
false
242
py
def sum13(nums): sum = 0 for i in range (len(nums)): if nums[i] != 13: sum += nums[i] elif nums[i] == 13 and i < len(nums)-1: nums[i]=0; nums[i+1] =0 return sum
96b80fdd8c80d38fff3348a20ed3e1d9e961fbd0
7356f77784c9ad3ffb3da4b3b60d844b23bb7b29
/dt_automator/maker/model/scene.py
3af1bfa5266ca3679ea24f3ea9652d3b6e46778b
[]
no_license
HsOjo/DTAutomator
5cc513e41a3eba0a595bb410bcee6ff990140805
d51c31ea04a79ed767f661ab0f9599b1c0f0bcef
refs/heads/master
2021-02-13T00:59:06.424434
2020-05-03T04:34:12
2020-05-03T04:34:12
244,647,246
0
0
null
null
null
null
UTF-8
Python
false
false
669
py
from typing import List from dt_automator.base.model import BaseModel from .feature import FeatureModel from .object import ObjectModel class SceneModel(BaseModel): _sub_model = dict( features=(list, FeatureModel), objects=(list, ObjectModel), ) def __init__(self, event: dict): self._event = event self.name = '' self.img = '' self.features = [] # type: List[FeatureModel] self.objects = [] # type: List[ObjectModel] @property def img_path(self): return self._event['get_path'](self.img) def __repr__(self): return '<%s %s>' % (self.__class__.__name__, self.name)
fbb829ca8e1fb3c025af62444ebef149db9b56ce
07996c7f93e7b200146cd314520100cf99d003bd
/raw data/40_tos_with_paragraph/code/crawlParagraph/new-env/bin/conch
4090c800e7522412274480e3f813286e46384855
[]
no_license
tjuyanghw/data_policy_analyzer
31ae683128ca5241fa8f0cb67e2f1132820c2d02
010a44ff024bd6d97b21f409f6c62f969e1fdc55
refs/heads/master
2022-07-02T19:23:14.141170
2020-05-13T16:24:11
2020-05-13T16:24:11
null
0
0
null
null
null
null
UTF-8
Python
false
false
442
#!/Users/huthvincent/Desktop/scrapy/scrapyenv/crawlByOnce/new-env/bin/python # EASY-INSTALL-ENTRY-SCRIPT: 'Twisted==19.10.0','console_scripts','conch' __requires__ = 'Twisted==19.10.0' import re import sys from pkg_resources import load_entry_point if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) sys.exit( load_entry_point('Twisted==19.10.0', 'console_scripts', 'conch')() )
eaf1784c0d34c71a35a44e1272093d4e512ce762
e81188e8ff0af121025b52f458ccf4aa9c0461a1
/watson/framework/views/renderers/jinja2.py
b68a79947b6efa25e8d14438c4b252d3f6d25473
[ "MIT" ]
permissive
SabatierBoris/watson-framework
f1be30d56a23654d5923ef02e4613786d30f8dfc
cfcdf4d8aedb6f3d49d4261122542354131389b8
refs/heads/master
2021-01-17T07:41:58.864120
2014-03-11T15:56:15
2014-03-11T15:56:15
null
0
0
null
null
null
null
UTF-8
Python
false
false
9,362
py
# -*- coding: utf-8 -*- import importlib import types import jinja2 from watson.common import datastructures from watson.framework.views.renderers import abc TEMPLATES = { 'base': '''<!DOCTYPE html> <html> <head> {% block head %} <style type="text/css"> html, body { font-family: Helvetica, Arial, sans-serif } {% block styles %}{% endblock %} </style> {% endblock %} </head> <body> {% block body %}{% endblock %} </body> </html> ''', 'exception_styling': ''' body { -webkit-font-smoothing: antialiased; margin: 0; padding: 0; font-size: 12px; } h1, h2 { background: #232e34; color: #fff; margin: 0; padding: 10px; font-weight: normal; } h1:first-of-type { padding-bottom: 0; } h2 { color: #3e515a; font-size: 1.1em; padding-top: 0; } h3 { color: #333; margin-left: 10px; } p { margin: 0; padding: 10px; } table { margin: 10px; width: 98%; border-collapse: collapse; } table th { text-align: left; font-size: 1.1em; padding: 0 6px 6px; } table td { padding: 6px; vertical-align: top; color: #333; } .watson-stack-frames > tbody > tr:nth-child(3n+1) { background-color: #fff; } .watson-stack-frames > tbody > tr { background-color: #f5f5f5; cursor: pointer; } .watson-stack-frames > tbody > tr.watson-stack-frames-frame-vars { cursor: default; background: #f1ecc2; } .hide { display: none; } table td { font-family: "Lucida Console", Monaco, monospace; } dl { margin: 0; padding: 10px; } dl.watson-info { background: #d9f2fe; color: #1c4d72; border-bottom: 1px solid #9cb3be; } dl.watson-error { box-shadow: -6px 0 6px rgba(0, 0, 0, 0.05); border-top: 1px solid #00d9ee; border-bottom: 1px solid #00b7df; background: #00bfe3; color: #fff; text-shadow: 0 1px #009fcc; padding-top: 12px; } dt { font-weight: bold; font-size: 1.1em; float: left; width: 160px; clear: both; } dd { color: #6087af; margin-bottom: 4px; margin-left: 160px; } dd table { margin: 0; table-layout: fixed; } dd table td { font-family: inherit; padding: 2px 0; color: inherit; } dd table tr > td:first-of-type { width: 200px; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } dl.watson-error dd { color: #f6f6f6; padding-top: 2px; } ''', 'exception_details': ''' {% if debug %} <h2>{{ message|escape }}</h2> <dl class="watson-error"> <dt>Exception Type:</dt> <dd>{{ type }}</dd> {% if cause_message %} <dt>Exception Message:</dt> <dd>{{ cause_message|escape }}</dd> {% endif %} </dl> <dl class="watson-info"> {% if route_match %} <dt>Watson Version:<dt> <dd>{{ version }}</dd> <dt>Route:</dt> <dd>{{ route_match.name|e }}</dd> {% endif %} <dt>Request:</dt> <dd>{{ request().url }}</dd> <dt>Method:</dt> <dd>{{ request().method }}</dd> <dt>Session Id:</dt> <dd>{{ request().session.id }}</dd> <dt>Headers:</dt> <dd> <table> {% for key, value in request().headers|dictsort %} <tr><td>{{ key }}</td><td>{{ value }}</td></tr> {% endfor %} </table> </dd> <dt>Get Vars:</dt> <dd> <table> {% for key, value in request().get|dictsort %} <tr><td>{{ key }}</td><td>{{ value }}</td></tr> {% else %} - {% endfor %} </table> </dd> <dt>Post Vars:</dt> <dd> <table> {% for key, value in request().post|dictsort %} <tr><td>{{ key }}</td><td>{{ value }}</td></tr> {% else %} - {% endfor %} </table> </dd> <dt>Server:</dt> <dd> <table> {% for key, value in request().server|dictsort %} <tr><td>{{ key }}</td><td>{{ value }}</td></tr> {% endfor %} </table> </dd> </dl> <h1>Stack Trace</h1> <table class="watson-stack-frames"> <tr> <th>Line</th><th>File</th><th>Function</th><th>Code</th> </tr> {% for frame in frames %} <tr class="watson-stack-frames-frame"> <td>{{ frame.line }}</td> <td>{{ frame.file }}</td> <td>{{ frame.function }}</td> <td>{{ frame.code }}</td> </tr> {% if frame.vars %} <tr class="watson-stack-frames-frame-vars"> <td colspan="4" class="hide"> <table class="watson-stack-frames-vars"> <tr><th>Name</th><th>Value</th></tr> {% for k, v in frame.vars|dictsort %} <tr> <td>{{ k|e }}</td> <td>{{ v|e }}</td> </tr> {% endfor %} </table> </td> </tr> {% endif %} {% endfor %} </table> <script> Element.prototype.toggleClass = function (className) { this.className = this.className === className ? '' : className; }; var frames = document.getElementsByClassName('watson-stack-frames-frame'); for (var i = 0; i < frames.length; i++) { var frame = frames[i]; frame.onclick = function() { this.nextElementSibling.children[0].toggleClass('hide'); } } </script> {% endif %} ''', 'blank.html': '''{% extends "base" %} {% block body %} {{ content }} {% endblock %} ''', 'errors/404.html': '''{% extends "base" %} {% block styles %} {{ super() }} {% include "exception_styling" %} {% endblock %} {% block body %} <h1>Not Found</h1> {% include "exception_details" %} {% if not debug %} <p>The requested page cannot be found.</p> {% endif %} {% endblock %} ''', 'errors/500.html': '''{% extends "base" %} {% block styles %} {{ super() }} {% include "exception_styling" %} {% endblock %} {% block body %} <h1>Internal Server Error</h1> {% include "exception_details" %} {% if not debug %} <p>A non-recoverable error has occurred and an administrator has been notified.</p> {% endif %} {% endblock %} ''' } class Renderer(abc.Renderer): _env = None _debug_mode = False @property def env(self): return self._env def __init__(self, config=None, application=None): super(Renderer, self).__init__(config) self._debug_mode = application.config['debug']['enabled'] self.register_loaders() _types = ('filters', 'globals') for _type in _types: for module in config[_type]: mod = importlib.import_module(module) dic = datastructures.module_to_dict( mod, ignore_starts_with='__') for name, definition in dic.items(): obj = '{0}.{1}'.format(module, name) env_type = getattr(self.env, _type) if isinstance(definition, types.FunctionType): env_type[name] = definition else: env_type[name] = application.container.get(obj) def register_loaders(self): user_loaders = [jinja2.FileSystemLoader(path) for path in self.config.get('paths')] system_loaders = [jinja2.DictLoader(TEMPLATES)] if self._debug_mode: loaders = system_loaders + user_loaders else: loaders = user_loaders + system_loaders kwargs = self.config.get('environment', {}) kwargs['loader'] = jinja2.ChoiceLoader(loaders) self._env = jinja2.Environment(**kwargs) def __call__(self, view_model, context=None): template = self._env.get_template( '{0}.{1}'.format(view_model.template, self.config['extension'])) return template.render(context=context or {}, **view_model.data)
1f2e7b1fdb24d899b19051ed50eaeaf5aeeb8f4e
b3fd61fdfd6ea82695d805c95321619423b836e6
/Tom_Sawyer.py
02e8482d4f8b2e35842c340ef85ed059753499c5
[]
no_license
sjogleka/General_codes
761967fd1175c97804d49290af9db10828d4900f
2772ea7b723c4ca680864b40b41fd34cc197726d
refs/heads/master
2021-07-16T07:41:05.841942
2020-10-14T01:49:12
2020-10-14T01:49:12
218,369,391
7
8
null
null
null
null
UTF-8
Python
false
false
312
py
def countWays(arr, n): pos = [0 for i in range(n)] p = 0 for i in range(n): if (arr[i] == 1): pos[p] = i + 1 p += 1 if (p == 0): return 0 ways = 1 for i in range(p - 1): ways *= pos[i + 1] - pos[i] return ways print(countWays([0,1],2))
443078e7b5c9ba43b126cdffff5dbe5295c466bb
b54a6c788ca6fd2b734899fe92e9ac7c288fbe01
/src/form/panel/ArmIKtoFKPanel.py
4c977840cce3d97515f2a61ced8c54ad896f8087
[ "MIT" ]
permissive
fehler001/motion_supporter
6bff2ed08b0dbf1b7457e6cbea3559f0a0f9fb6b
4a5db3746b80683bdc0f610211ebdb6e60e6941f
refs/heads/master
2023-08-01T12:32:07.716946
2021-09-24T19:59:35
2021-09-24T19:59:35
null
0
0
null
null
null
null
UTF-8
Python
false
false
13,041
py
# -*- coding: utf-8 -*- # import os import wx import wx.lib.newevent import sys from form.panel.BasePanel import BasePanel from form.parts.BaseFilePickerCtrl import BaseFilePickerCtrl from form.parts.HistoryFilePickerCtrl import HistoryFilePickerCtrl from form.parts.ConsoleCtrl import ConsoleCtrl from form.worker.ArmIKtoFKWorkerThread import ArmIKtoFKWorkerThread from utils import MFormUtils, MFileUtils from utils.MLogger import MLogger # noqa logger = MLogger(__name__) TIMER_ID = wx.NewId() # イベント定義 (ArmIKtoFKThreadEvent, EVT_ARM_IK_THREAD) = wx.lib.newevent.NewEvent() class ArmIKtoFKPanel(BasePanel): def __init__(self, frame: wx.Frame, arm_ik2fk: wx.Notebook, tab_idx: int): super().__init__(frame, arm_ik2fk, tab_idx) self.convert_arm_ik2fk_worker = None self.header_sizer = wx.BoxSizer(wx.VERTICAL) self.description_txt = wx.StaticText(self, wx.ID_ANY, u"腕IKを腕FK(腕・ひじ・手首)に変換します。元モデルには腕IKが入ったモデルを指定してください。" \ + "\n捩りは統合しちゃいますので、必要に応じてサイジングで捩り分散をかけてください。" + "\n不要キー削除を行うと、キーが間引きされます。キー間がオリジナルから多少ずれ、またそれなりに時間がかかります。", wx.DefaultPosition, wx.DefaultSize, 0) self.header_sizer.Add(self.description_txt, 0, wx.ALL, 5) self.static_line01 = wx.StaticLine(self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.LI_HORIZONTAL) self.header_sizer.Add(self.static_line01, 0, wx.EXPAND | wx.ALL, 5) # 対象VMDファイルコントロール self.arm_ik2fk_vmd_file_ctrl = HistoryFilePickerCtrl(self.frame, self, u"対象モーションVMD/VPD", u"対象モーションVMDファイルを開く", ("vmd", "vpd"), wx.FLP_DEFAULT_STYLE, \ u"調整したい対象モーションのVMDパスを指定してください。\nD&Dでの指定、開くボタンからの指定、履歴からの選択ができます。", \ file_model_spacer=46, title_parts_ctrl=None, title_parts2_ctrl=None, file_histories_key="arm_ik2fk_vmd", is_change_output=True, \ is_aster=False, is_save=False, set_no=1) self.header_sizer.Add(self.arm_ik2fk_vmd_file_ctrl.sizer, 1, wx.EXPAND, 0) # 対象PMXファイルコントロール(IK) self.arm_ik2fk_ik_model_file_ctrl = HistoryFilePickerCtrl(self.frame, self, u"腕IKありモデルPMX", u"腕IKありモデルPMXファイルを開く", ("pmx"), wx.FLP_DEFAULT_STYLE, \ u"腕IKモーションを適用したいモデルのPMXパスを指定してください。\nD&Dでの指定、開くボタンからの指定、履歴からの選択ができます。", \ file_model_spacer=60, title_parts_ctrl=None, title_parts2_ctrl=None, file_histories_key="arm_ik2fk_pmx", \ is_change_output=True, is_aster=False, is_save=False, set_no=1) self.header_sizer.Add(self.arm_ik2fk_ik_model_file_ctrl.sizer, 1, wx.EXPAND, 0) # 対象PMXファイルコントロール(FK) self.arm_ik2fk_fk_model_file_ctrl = HistoryFilePickerCtrl(self.frame, self, u"腕IKなしモデルPMX", u"腕IKなしモデルPMXファイルを開く", ("pmx"), wx.FLP_DEFAULT_STYLE, \ u"変換後の腕FKモーションを適用したいモデルのPMXパスを指定してください。\nD&Dでの指定、開くボタンからの指定、履歴からの選択ができます。", \ file_model_spacer=60, title_parts_ctrl=None, title_parts2_ctrl=None, file_histories_key="arm_ik2fk_pmx_fk", \ is_change_output=True, is_aster=False, is_save=False, set_no=1) self.header_sizer.Add(self.arm_ik2fk_fk_model_file_ctrl.sizer, 1, wx.EXPAND, 0) # 出力先VMDファイルコントロール self.output_arm_ik2fk_vmd_file_ctrl = BaseFilePickerCtrl(frame, self, u"出力対象VMD", u"出力対象VMDファイルを開く", ("vmd"), wx.FLP_OVERWRITE_PROMPT | wx.FLP_SAVE | wx.FLP_USE_TEXTCTRL, \ u"調整結果の対象VMD出力パスを指定してください。\n対象VMDファイル名に基づいて自動生成されますが、任意のパスに変更することも可能です。", \ is_aster=False, is_save=True, set_no=1) self.header_sizer.Add(self.output_arm_ik2fk_vmd_file_ctrl.sizer, 1, wx.EXPAND, 0) # 不要キー削除処理 self.remove_unnecessary_flg_ctrl = wx.CheckBox(self, wx.ID_ANY, u"不要キー削除処理を追加実行する", wx.DefaultPosition, wx.DefaultSize, 0) self.remove_unnecessary_flg_ctrl.SetToolTip(u"チェックを入れると、不要キー削除処理を追加で実行します。キーが減る分、キー間が少しズレる事があります。") self.header_sizer.Add(self.remove_unnecessary_flg_ctrl, 0, wx.ALL, 5) self.sizer.Add(self.header_sizer, 0, wx.EXPAND | wx.ALL, 5) btn_sizer = wx.BoxSizer(wx.HORIZONTAL) # 多段分割変換実行ボタン self.arm_ik2fk_btn_ctrl = wx.Button(self, wx.ID_ANY, u"腕IK変換", wx.DefaultPosition, wx.Size(200, 50), 0) self.arm_ik2fk_btn_ctrl.SetToolTip(u"足FKを足IKに変換したモーションを再生成します。") self.arm_ik2fk_btn_ctrl.Bind(wx.EVT_LEFT_DOWN, self.on_convert_arm_ik2fk) self.arm_ik2fk_btn_ctrl.Bind(wx.EVT_LEFT_DCLICK, self.on_doubleclick) btn_sizer.Add(self.arm_ik2fk_btn_ctrl, 0, wx.ALL, 5) self.sizer.Add(btn_sizer, 0, wx.ALIGN_CENTER | wx.SHAPED, 5) # コンソール self.console_ctrl = ConsoleCtrl(self, self.frame.logging_level, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size(-1, 420), \ wx.TE_MULTILINE | wx.TE_READONLY | wx.BORDER_NONE | wx.HSCROLL | wx.VSCROLL | wx.WANTS_CHARS) self.console_ctrl.SetBackgroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DLIGHT)) self.console_ctrl.Bind(wx.EVT_CHAR, lambda event: MFormUtils.on_select_all(event, self.console_ctrl)) self.sizer.Add(self.console_ctrl, 1, wx.ALL | wx.EXPAND, 5) # ゲージ self.gauge_ctrl = wx.Gauge(self, wx.ID_ANY, 100, wx.DefaultPosition, wx.DefaultSize, wx.GA_HORIZONTAL) self.gauge_ctrl.SetValue(0) self.sizer.Add(self.gauge_ctrl, 0, wx.ALL | wx.EXPAND, 5) self.Layout() self.fit() # フレームに変換完了処理バインド self.frame.Bind(EVT_ARM_IK_THREAD, self.on_convert_arm_ik2fk_result) def on_wheel_spin_ctrl(self, event: wx.Event, inc=1): self.frame.on_wheel_spin_ctrl(event, inc) self.set_output_vmd_path(event) # ファイル変更時の処理 def on_change_file(self, event: wx.Event): self.set_output_vmd_path(event, is_force=True) def set_output_vmd_path(self, event, is_force=False): output_arm_ik2fk_vmd_path = MFileUtils.get_output_arm_ik2fk_vmd_path( self.arm_ik2fk_vmd_file_ctrl.file_ctrl.GetPath(), self.arm_ik2fk_fk_model_file_ctrl.file_ctrl.GetPath(), self.output_arm_ik2fk_vmd_file_ctrl.file_ctrl.GetPath(), is_force) self.output_arm_ik2fk_vmd_file_ctrl.file_ctrl.SetPath(output_arm_ik2fk_vmd_path) if len(output_arm_ik2fk_vmd_path) >= 255 and os.name == "nt": logger.error("生成予定のファイルパスがWindowsの制限を超えています。\n生成予定パス: {0}".format(output_arm_ik2fk_vmd_path), decoration=MLogger.DECORATION_BOX) # フォーム無効化 def disable(self): self.arm_ik2fk_vmd_file_ctrl.disable() self.arm_ik2fk_ik_model_file_ctrl.disable() self.arm_ik2fk_fk_model_file_ctrl.disable() self.output_arm_ik2fk_vmd_file_ctrl.disable() self.arm_ik2fk_btn_ctrl.Disable() # フォーム無効化 def enable(self): self.arm_ik2fk_vmd_file_ctrl.enable() self.arm_ik2fk_ik_model_file_ctrl.enable() self.arm_ik2fk_fk_model_file_ctrl.enable() self.output_arm_ik2fk_vmd_file_ctrl.enable() self.arm_ik2fk_btn_ctrl.Enable() def on_doubleclick(self, event: wx.Event): self.timer.Stop() logger.warning("ダブルクリックされました。", decoration=MLogger.DECORATION_BOX) event.Skip(False) return False # 多段分割変換 def on_convert_arm_ik2fk(self, event: wx.Event): self.timer = wx.Timer(self, TIMER_ID) self.timer.Start(200) self.Bind(wx.EVT_TIMER, self.on_convert, id=TIMER_ID) # 多段分割変換 def on_convert(self, event: wx.Event): self.timer.Stop() self.Unbind(wx.EVT_TIMER, id=TIMER_ID) # フォーム無効化 self.disable() # タブ固定 self.fix_tab() # コンソールクリア self.console_ctrl.Clear() # 出力先を多段分割パネルのコンソールに変更 sys.stdout = self.console_ctrl self.arm_ik2fk_vmd_file_ctrl.save() self.arm_ik2fk_ik_model_file_ctrl.save() self.arm_ik2fk_fk_model_file_ctrl.save() # JSON出力 MFileUtils.save_history(self.frame.mydir_path, self.frame.file_hitories) self.elapsed_time = 0 result = True result = self.arm_ik2fk_vmd_file_ctrl.is_valid() and self.arm_ik2fk_ik_model_file_ctrl.is_valid() and self.arm_ik2fk_fk_model_file_ctrl.is_valid() and result if not result: # 終了音 self.frame.sound_finish() # タブ移動可 self.release_tab() # フォーム有効化 self.enable() return result # 腕IK変換変換開始 if self.arm_ik2fk_btn_ctrl.GetLabel() == "腕IK変換停止" and self.convert_arm_ik2fk_worker: # フォーム無効化 self.disable() # 停止状態でボタン押下時、停止 self.convert_arm_ik2fk_worker.stop() # タブ移動可 self.frame.release_tab() # フォーム有効化 self.frame.enable() # ワーカー終了 self.convert_arm_ik2fk_worker = None # プログレス非表示 self.gauge_ctrl.SetValue(0) logger.warning("腕IK変換を中断します。", decoration=MLogger.DECORATION_BOX) self.arm_ik2fk_btn_ctrl.SetLabel("腕IK変換") event.Skip(False) elif not self.convert_arm_ik2fk_worker: # フォーム無効化 self.disable() # タブ固定 self.fix_tab() # コンソールクリア self.console_ctrl.Clear() # ラベル変更 self.arm_ik2fk_btn_ctrl.SetLabel("腕IK変換停止") self.arm_ik2fk_btn_ctrl.Enable() self.convert_arm_ik2fk_worker = ArmIKtoFKWorkerThread(self.frame, ArmIKtoFKThreadEvent, self.frame.is_saving, self.frame.is_out_log) self.convert_arm_ik2fk_worker.start() event.Skip() else: logger.error("まだ処理が実行中です。終了してから再度実行してください。", decoration=MLogger.DECORATION_BOX) event.Skip(False) return result # 多段分割変換完了処理 def on_convert_arm_ik2fk_result(self, event: wx.Event): self.elapsed_time = event.elapsed_time logger.info("\n処理時間: %s", self.show_worked_time()) self.arm_ik2fk_btn_ctrl.SetLabel("腕IK変換") # 終了音 self.frame.sound_finish() # タブ移動可 self.release_tab() # フォーム有効化 self.enable() # ワーカー終了 self.convert_arm_ik2fk_worker = None # プログレス非表示 self.gauge_ctrl.SetValue(0) def show_worked_time(self): # 経過秒数を時分秒に変換 td_m, td_s = divmod(self.elapsed_time, 60) if td_m == 0: worked_time = "{0:02d}秒".format(int(td_s)) else: worked_time = "{0:02d}分{1:02d}秒".format(int(td_m), int(td_s)) return worked_time
9e6e89a22d2678d31373d33e7f817a66b671619b
dcc491dd2fa4ece68728255d236fa6e784eef92d
/modules/2.78/bpy/ops/outliner.py
0825988f0ade8aa85899d877be01bb396b376431
[ "MIT" ]
permissive
cmbasnett/fake-bpy-module
a8e87d5a95d075e51133307dfb55418b94342f4f
acb8b0f102751a9563e5b5e5c7cd69a4e8aa2a55
refs/heads/master
2020-03-14T16:06:29.132956
2018-05-13T01:29:55
2018-05-13T01:29:55
131,691,143
0
0
null
null
null
null
UTF-8
Python
false
false
1,671
py
def action_set(action=''): pass def animdata_operation(type='CLEAR_ANIMDATA'): pass def constraint_operation(type='ENABLE'): pass def data_operation(type='SELECT'): pass def drivers_add_selected(): pass def drivers_delete_selected(): pass def expanded_toggle(): pass def group_link(object="Object"): pass def group_operation(type='UNLINK'): pass def id_delete(): pass def id_operation(type='UNLINK'): pass def id_remap(id_type='OBJECT', old_id='', new_id=''): pass def item_activate(extend=True, recursive=False): pass def item_openclose(all=True): pass def item_rename(): pass def keyingset_add_selected(): pass def keyingset_remove_selected(): pass def lib_operation(type='RENAME'): pass def lib_relocate(): pass def material_drop(object="Object", material="Material"): pass def modifier_operation(type='TOGVIS'): pass def object_operation(type='SELECT'): pass def operation(): pass def orphans_purge(): pass def parent_clear(dragged_obj="Object", type='CLEAR'): pass def parent_drop(child="Object", parent="Object", type='OBJECT'): pass def renderability_toggle(): pass def scene_drop(object="Object", scene="Scene"): pass def scene_operation(type='DELETE'): pass def scroll_page(up=False): pass def select_border(gesture_mode=0, xmin=0, xmax=0, ymin=0, ymax=0): pass def selectability_toggle(): pass def selected_toggle(): pass def show_active(): pass def show_hierarchy(): pass def show_one_level(open=True): pass def visibility_toggle(): pass
6daa0f6ca0ec15a3661dc69769cc530be5110fb4
ecbc312f6c5733a4c8ebcc9c3fccdba8bc35fd2f
/text_normalizer/collection/eng_basic.py
0432800ebf5e9c3e77fbc5fa67ff71ed84217fbd
[ "MIT" ]
permissive
Yoctol/text-normalizer
d200a4e020618e70162cbc52a3099d9a9203aab9
3609c10cd229c08b4623531e82d2292fc370734c
refs/heads/master
2020-03-11T00:56:25.337539
2018-11-06T04:08:37
2018-11-06T04:08:37
129,676,388
17
3
MIT
2018-11-06T04:08:38
2018-04-16T02:57:34
Python
UTF-8
Python
false
false
439
py
from .base_collection import BaseCollection from ..library import ( whitespace_char_text_normalizer, pure_strip_text_normalizer, eng_lowercase_text_normalizer, ) eng_basic_text_normalizer_collection = BaseCollection() eng_basic_text_normalizer_collection.add_text_normalizers( text_normalizers=[ eng_lowercase_text_normalizer, whitespace_char_text_normalizer, pure_strip_text_normalizer, ], )
211dc4152498ce7967b1fc4828f9e7be31a98caf
e23a4f57ce5474d468258e5e63b9e23fb6011188
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/096_Unique_Binary_Search_Trees.py
6b846c2a2a8141cdb599d93d5826000dc142e497
[]
no_license
syurskyi/Python_Topics
52851ecce000cb751a3b986408efe32f0b4c0835
be331826b490b73f0a176e6abed86ef68ff2dd2b
refs/heads/master
2023-06-08T19:29:16.214395
2023-05-29T17:09:11
2023-05-29T17:09:11
220,583,118
3
2
null
2023-02-16T03:08:10
2019-11-09T02:58:47
Python
UTF-8
Python
false
false
419
py
c_ Solution o.. ___ numTrees n """ :type n: int :rtype: int """ # https://leetcode.com/discuss/86650/fantastic-clean-java-dp-solution-with-detail-explaination dp = [0] * (n + 1) dp[0] = 1 dp[1] = 1 ___ level __ r.. 2, n + 1 ___ root __ r.. 1, level + 1 dp[level] += dp[level - root] * dp[root - 1] r_ dp[n]
403157814d970ad27e47a62924b88c665308ac35
a1b375c3e98fe059dafc4d74cbcbcb99a0571e44
/accounts/migrations/0001_initial.py
ffea45cf723bf87cb80e5a6a39898021cf2970d0
[ "MIT" ]
permissive
mohsenamoon1160417237/Social_app
478a73552ceed8001c167be6caaf550cd58626bd
79fa0871f7b83648894941f9010f1d99f1b27ab3
refs/heads/master
2022-12-09T16:03:53.623506
2020-09-21T05:59:22
2020-09-21T06:02:03
297,242,915
0
0
null
null
null
null
UTF-8
Python
false
false
833
py
# Generated by Django 2.2 on 2020-09-10 17:48 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Profile', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('first_name', models.CharField(max_length=50)), ('last_name', models.CharField(max_length=50)), ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='profile', to=settings.AUTH_USER_MODEL)), ], ), ]
e6a83c518c0ad5a0e277d860ea3388efff7b2f63
44a7330dfa4fe321eb432ee57a32328578dec109
/milk/unsupervised/som.py
abe3f6dbe5b47773ecfa3cb5f58852d2d220e17f
[ "MIT" ]
permissive
tzuryby/milk
7cb6760fad600e9e0d0c9216dc749db289b596fb
a7159b748414d4d095741978fb994c4affcf6b9b
refs/heads/master
2020-12-29T02:45:33.044864
2011-03-15T20:23:29
2011-03-15T20:25:11
1,485,748
2
0
null
null
null
null
UTF-8
Python
false
false
3,261
py
# -*- coding: utf-8 -*- # Copyright (C) 2010, Luis Pedro Coelho <[email protected]> # vim: set ts=4 sts=4 sw=4 expandtab smartindent: # License: MIT. See COPYING.MIT file in the milk distribution from __future__ import division import numpy as np from ..utils import get_pyrandom from . import _som def putpoints(grid, points, L=.2, radius=4, iterations=1, shuffle=True, R=None): ''' putpoints(grid, points, L=.2, radius=4, iterations=1, shuffle=True, R=None) Feeds elements of `points` into the SOM `grid` Parameters ---------- grid : ndarray Self organising map points : ndarray data to feed to array L : float, optional How much to influence neighbouring points (default: .2) radius : integer, optional Maximum radius of influence (in L_1 distance, default: 4) iterations : integer, optional Number of iterations shuffle : boolean, optional Whether to shuffle the points before each iterations R : source of randomness ''' if radius is None: radius = 4 if type(L) != float: raise TypeError("milk.unsupervised.som: L should be floating point") if type(radius) != int: raise TypeError("milk.unsupervised.som: radius should be an integer") if grid.dtype != np.float32: raise TypeError('milk.unsupervised.som: only float32 arrays are accepted') if points.dtype != np.float32: raise TypeError('milk.unsupervised.som: only float32 arrays are accepted') if len(grid.shape) == 2: grid = grid.reshape(grid.shape+(1,)) if shuffle: random = get_pyrandom(R) for i in xrange(iterations): if shuffle: random.shuffle(points) _som.putpoints(grid, points, L, radius) def closest(grid, f): ''' y,x = closest(grid, f) Finds the coordinates of the closest point in the `grid` to `f` :: y,x = \\argmin_{y,x} { || grid[y,x] - f ||^2 } Parameters ---------- grid : ndarray of shape Y,X,J self-organised map f : ndarray of shape J point Returns ------- y,x : integers coordinates into `grid` ''' delta = grid - f delta **= 2 delta = delta.sum(2) return np.unravel_index(delta.argmin(), delta.shape) def som(data, shape, iterations=1000, L=.2, radius=4, R=None): ''' grid = som(data, shape, iterations=1000, L=.2, radius=4, R=None): Self-organising maps Parameters ---------- points : ndarray data to feed to array shape : tuple Desired shape of output. Must be 2-dimensional. L : float, optional How much to influence neighbouring points (default: .2) radius : integer, optional Maximum radius of influence (in L_1 distance, default: 4) iterations : integer, optional Number of iterations R : source of randomness Returns ------- grid : ndarray Map ''' R = get_pyrandom(R) d = data.shape[1] if data.dtype != np.float32: data = data.astype(np.float32) grid = np.array(R.sample(data, np.product(shape))).reshape(shape + (d,)) putpoints(grid, data, L=L, radius=radius, iterations=iterations, shuffle=True, R=R) return grid
54f59acba3e28e9e73601f99667ca553cc1f9529
738b6d6ec4572f5848940b6adc58907a03bda6fb
/tests/nutmeg4_pymcell4/0625_prob_changed_notification_disabled/model.py
bb49dac21464576f72e6b5d1f13578c087a464db
[ "Unlicense", "LicenseRef-scancode-public-domain", "MIT" ]
permissive
mcellteam/mcell_tests
09cd1010a356e0e07c88d7e044a73c5606c6e51a
34d2d967b75d56edbae999bf0090641850f4f4fe
refs/heads/master
2021-12-24T02:36:24.987085
2021-09-24T14:19:41
2021-09-24T14:19:41
174,733,926
1
0
null
null
null
null
UTF-8
Python
false
false
1,015
py
#!/usr/bin/env python3 import sys import os MCELL_PATH = os.environ.get('MCELL_PATH', '') if MCELL_PATH: sys.path.append(os.path.join(MCELL_PATH, 'lib')) else: print("Error: variable MCELL_PATH that is used to find the mcell library was not set.") sys.exit(1) import mcell as m params = m.bngl_utils.load_bngl_parameters('test.bngl') ITERATIONS = int(params['ITERATIONS']) DUMP = True EXPORT_DATA_MODEL = True # ---- load bngl file ---- model = m.Model() model.load_bngl('test.bngl') rxn = model.find_reaction_rule('rxn') assert(rxn) var_rate_react_a_plus_b = [ [0, 0], [1e-05, 9.98334e+06], [2e-05, 1.98669e+07], [3e-05, 2.9552e+07], [4e-05, 3.89418e+07], [5e-05, 4.79426e+07], [6e-05, 5.64642e+07] ] rxn.variable_rate = var_rate_react_a_plus_b # ---- configuration ---- model.config.total_iterations = ITERATIONS model.notifications.rxn_probability_changed = False model.initialize() #model.dump_internal_state() model.run_iterations(ITERATIONS) model.end_simulation()
8bde1e7c8d3f15fa84f32773e315e26557bde33f
6c816f19d7f4a3d89abbb00eeaf43dd818ecc34f
/apps/detailQuestion/migrations/0001_initial.py
f55e7aa24232e3c288aacd4cef66e2d65e699b32
[]
no_license
reo-dev/bolt
29ee6aa7cfc96bd50fa7a7dae07fbaafc2125e54
d1a7859dd1ebe2f5b0e6e295047b620f5afdb92e
refs/heads/master
2023-07-13T04:05:57.856278
2021-08-27T09:07:03
2021-08-27T09:07:03
382,195,547
0
0
null
null
null
null
UTF-8
Python
false
false
2,297
py
# Generated by Django 3.0.8 on 2021-01-12 02:20 from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ ('project', '0013_proposaltype_name'), ] operations = [ migrations.CreateModel( name='DetailQuestionTitle', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('question', models.TextField(verbose_name='질문제목')), ('createdAt', models.DateTimeField(default=django.utils.timezone.now, verbose_name='작성일')), ], options={ 'verbose_name': ' 질문제목', 'verbose_name_plural': ' 질문제목', }, ), migrations.CreateModel( name='DetailQuestionSelect', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('select', models.TextField(verbose_name='질문 선택지')), ('createdAt', models.DateTimeField(default=django.utils.timezone.now, verbose_name='작성일')), ('title', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='detailQuestion.DetailQuestionTitle', verbose_name='질문제목')), ], ), migrations.CreateModel( name='DetailQuestionSave', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('createdAt', models.DateTimeField(default=django.utils.timezone.now, verbose_name='작성일')), ('question', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='detailQuestion.DetailQuestionTitle', verbose_name='질문제목')), ('request', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='project.Request', verbose_name='의뢰서')), ('select', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='detailQuestion.DetailQuestionSelect', verbose_name='질문 선택지')), ], ), ]
a88524be820b8141ba2700ef02283fe69fe301c4
39bc55c2a4457bbe7ff4136ea660a29ff88ee66d
/skued/simulation/tests/test_structure_factors.py
7513665650da42ed29e663bb4456ea09438f61dd
[ "MIT" ]
permissive
KOLANICH-physics/scikit-ued
c72b3219e547e33ae067c5d36a93439d2f9045e2
c13472129df33105312b57427ce588e66d20391f
refs/heads/master
2022-01-22T05:47:04.286449
2018-09-24T15:06:00
2018-09-24T15:06:00
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,918
py
# -*- coding: utf-8 -*- import unittest import numpy as np from random import randint from .. import structure_factor, bounded_reflections, affe from ... import Crystal, Atom class TestElectronFormFactor(unittest.TestCase): def test_side_effects(self): nG = np.random.random(size = (16, 32)) nG.setflags(write = False) # if nG is written to, Exception is raised affe(Atom('He', coords = [0,0,0]), nG) def test_out_shape(self): nG = np.random.random(size = (16, 32)) eff = affe(Atom('He', coords = [0,0,0]), nG) self.assertSequenceEqual(eff.shape, nG.shape) def test_int(self): """ Test that affe(int, ...) also works """ atomic_number = randint(1, 103) nG = np.random.random(size = (16, 32)) from_int = affe(atomic_number, nG) from_atom = affe(Atom(atomic_number, [0,0,0]), nG) self.assertTrue(np.allclose(from_int, from_atom)) def test_str(self): """ Test that affe(str, ...) also works """ # Try with Chlorine (Z = 17) atomic_number = 17 nG = np.random.random(size = (16, 32)) from_int = affe(atomic_number, nG) from_str = affe('Cl', nG) self.assertTrue(np.allclose(from_int, from_str)) class TestStructureFactor(unittest.TestCase): def setUp(self): self.crystal = Crystal.from_database(next(iter(Crystal.builtins))) def test_shape_and_dtype(self): """ Test that output of structure_factor is same shape as input, and that the dtype is complex """ h, k, l = np.meshgrid([1, 2, 3], [1, 2, 3], [1, 2, 3]) sf = structure_factor(self.crystal, h, k, l) self.assertSequenceEqual(sf.shape, h.shape) self.assertEqual(sf.dtype, np.complex) class TestBoundedReflections(unittest.TestCase): def setUp(self): self.crystal = Crystal.from_database(next(iter(Crystal.builtins))) def test_bounded_reflections_negative(self): """ Test that negative reflection bounds raise an Exception. Otherwise, an infinite number of reflections will be generated """ with self.assertRaises(ValueError): hkl = list(bounded_reflections(self.crystal, -1)) def test_bounded_reflections_zero(self): """ Check that bounded_reflections returns (000) for a zero bound """ h, k, l = bounded_reflections(self.crystal,0) [self.assertEqual(len(i), 1) for i in (h, k, l)] [self.assertEqual(i[0], 0) for i in (h, k, l)] def test_bounded_reflections_all_within_bounds(self): """ Check that every reflection is within the bound """ bound = 10 Gx, Gy, Gz = self.crystal.scattering_vector(*bounded_reflections(self.crystal,nG = bound)) norm_G = np.sqrt(Gx**2 + Gy**2 + Gz**2) self.assertTrue(np.all(norm_G <= bound)) if __name__ == '__main__': unittest.main()
de4798e70d7c9c101c756128701b3dde305bd873
006ff11fd8cfd5406c6f4318f1bafa1542095f2a
/Validation/CheckOverlap/test/python/runFP420_cfg.py
bb8cd03847118c55541afbb0a89d58fb4eb5fa73
[]
permissive
amkalsi/cmssw
8ac5f481c7d7263741b5015381473811c59ac3b1
ad0f69098dfbe449ca0570fbcf6fcebd6acc1154
refs/heads/CMSSW_7_4_X
2021-01-19T16:18:22.857382
2016-08-09T16:40:50
2016-08-09T16:40:50
262,608,661
0
0
Apache-2.0
2020-05-09T16:10:07
2020-05-09T16:10:07
null
UTF-8
Python
false
false
2,204
py
import FWCore.ParameterSet.Config as cms process = cms.Process("PROD") process.load("SimGeneral.HepPDTESSource.pdt_cfi") process.load("Geometry.CMSCommonData.cmsAllGeometryXML_cfi") process.load("Geometry.TrackerNumberingBuilder.trackerNumberingGeometry_cfi") process.load("Geometry.MuonNumbering.muonNumberingInitialization_cfi") process.load("SimG4Core.Application.g4SimHits_cfi") process.MessageLogger = cms.Service("MessageLogger", destinations = cms.untracked.vstring('cout'), categories = cms.untracked.vstring('G4cout', 'G4cerr'), cout = cms.untracked.PSet( default = cms.untracked.PSet( limit = cms.untracked.int32(0) ), G4cout = cms.untracked.PSet( limit = cms.untracked.int32(-1) ), G4cerr = cms.untracked.PSet( limit = cms.untracked.int32(-1) ) ), ) process.RandomNumberGeneratorService = cms.Service("RandomNumberGeneratorService", moduleSeeds = cms.PSet( generator = cms.untracked.uint32(456789), g4SimHits = cms.untracked.uint32(9876), VtxSmeared = cms.untracked.uint32(12345) ), sourceSeed = cms.untracked.uint32(98765) ) process.source = cms.Source("EmptySource") process.generator = cms.EDProducer("FlatRandomEGunProducer", PGunParameters = cms.PSet( PartID = cms.vint32(14), MinEta = cms.double(-3.5), MaxEta = cms.double(3.5), MinPhi = cms.double(-3.14159265359), MaxPhi = cms.double(3.14159265359), MinE = cms.double(9.99), MaxE = cms.double(10.01) ), AddAntiParticle = cms.bool(False), Verbosity = cms.untracked.int32(0), firstRun = cms.untracked.uint32(1) ) process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(1) ) process.p1 = cms.Path(process.generator*process.g4SimHits) process.g4SimHits.UseMagneticField = False process.g4SimHits.Physics.type = 'SimG4Core/Physics/DummyPhysics' process.g4SimHits.Physics.DummyEMPhysics = True process.g4SimHits.Watchers = cms.VPSet(cms.PSet( type = cms.string('CheckOverlap'), Resolution = cms.untracked.int32(1000), NodeNames = cms.untracked.vstring('FP420E') ))
442bf86ccac1d097b67f928e10a2d28a7d1a246a
390a9771799a8264b3c0c8c61cc7e1bf97ef2d79
/day23.py
ee7b0c961b026c7a9198fb1b34e91d632c061fa0
[]
no_license
Goldenlion5648/AdventOfCode2017
2bbf96d03017eceaac1279413dc3387359d03a6f
482f2c0d5eba49a29c4631ea131753945cfe3baa
refs/heads/master
2022-12-12T06:20:41.812048
2020-09-19T05:08:35
2020-09-19T05:08:35
289,359,883
0
0
null
null
null
null
UTF-8
Python
false
false
1,833
py
from collections import Counter a='''set b 99 set c b jnz a 2 jnz 1 5 mul b 100 sub b -100000 set c b sub c -17000 set f 1 set d 2 set e 2 set g d mul g e sub g b jnz g 2 set f 0 sub e -1 set g e sub g b jnz g -8 sub d -1 set g d sub g b jnz g -13 jnz f 2 sub h -1 set g b sub g c jnz g 2 jnz 1 3 sub b -17 jnz 1 -23''' positions = Counter([chr(i) for i in range(97, 97 + 8)]) for i in positions: positions[i] -= 1 print(positions) instructs = a.split("\n") curInstruct = 0 # for i in instructs: count = 0 while curInstruct < len(instructs): i = instructs[curInstruct] inst, b, c = i.split(" ") jumped = False try: b = int(b) except: pass try: c = int(c) except: pass if inst == "set": if type(b) == type(2): positions[chr(b)+97] = c if type(c) == type(3) else positions[c] else: positions[b] = c if type(c) == type(3) else positions[c] elif inst == "sub": if type(b) == type(2): positions[chr(b)+97] -= c if type(c) == type(3) else positions[c] else: positions[b] -= c if type(c) == type(3) else positions[c] elif inst == "mul": if type(b) == type(2): positions[chr(b)+97] *= c if type(c) == type(3) else positions[c] else: positions[b] *= c if type(c) == type(3) else positions[c] count += 1 elif inst == "jnz": if type(b) == type(2): if b != 0: curInstruct += c if type(c) == type(3) else positions[c] jumped = True else: if positions[b] != 0: curInstruct += c if type(c) == type(3) else positions[c] jumped = True if jumped == False: curInstruct += 1 print(count) #part 1 done in 16:57, worked first try
88917a546cf6b78403ff35ece587c512e0f076ee
622a338ee1f856e542e14757b761546aa4267604
/confu/isa.py
ddfa5a58dfcb9268fd62c9b758090d785344f16b
[ "MIT" ]
permissive
Maratyszcza/confu
ad8f30998d6d6ed4b37b72b6d63b7fd8ba549f1d
4f3d0e73d20dbae54c154817d70f74b6a63940e1
refs/heads/master
2023-06-05T15:49:05.476642
2020-04-12T20:00:19
2020-04-12T20:14:52
79,974,006
14
14
MIT
2020-01-06T22:34:03
2017-01-25T01:55:44
Python
UTF-8
Python
false
false
1,086
py
from copy import copy class InstructionSet: def __init__(self, tags=None, generate_flags_fn=None): if tags is None: self.tags = set() elif isinstance(tags, str): self.tags = set((tags,)) else: self.tags = set(tags) self.generate_flags = generate_flags_fn def get_flags(self, compiler): if self.generate_flags is not None: return self.generate_flags(self.tags, compiler) else: return list() def __str__(self): return self.name def __add__(self, instruction_set): if not isinstance(instruction_set, InstructionSet): raise TypeError("Invalid instruction set type; InstructionSet expected") if self.generate_flags is not None and self.generate_flags is not instruction_set.generate_flags: raise ValueError("Instruction sets %s and %s are mutually incompatible" % (self.tags[-1], instruction_set.tags[0])) return InstructionSet(self.tags.union(instruction_set.tags), self.generate_flags)
5247e05fedc3b4010c1fd05918da47a596108f5a
0b480b28455d4ea133eaeec5625e2ce62660dbb1
/populate_rango.py
c872d3fa71f07dc547fc08034fa6175d00d97eca
[]
no_license
jtr109/tango_with_django_exercise
8ff6c05321be8ca614a550abc6c66aef55886136
ce2aa7c5a12eae0352b435dc726bef4e378ef3c5
refs/heads/master
2020-09-22T09:28:34.217081
2016-08-30T02:49:35
2016-08-30T02:49:35
66,900,401
0
0
null
null
null
null
UTF-8
Python
false
false
2,374
py
import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tango_with_django_project.settings') import django django.setup() from rango.models import Category, Page def populate(): python_cat = add_cat(name='Python', views=128, likes=64) add_page(cat=python_cat, title="Official Python Tutorial", url="http://docs.python.org/2/tutorial/", views=16) add_page(cat=python_cat, title="How to Think like a Computer Scientist", url="http://www.greenteapress.com/thinkpython/", views=32) add_page(cat=python_cat, title="Learn Python in 10 Minutes", url="http://www.korokithakis.net/tutorials/python/", views=64) django_cat = add_cat(name="Django", views=64, likes=32) add_page(cat=django_cat, title="Official Django Tutorial", url="https://docs.djangoproject.com/en/1.5/intro/tutorial01/", views=128) add_page(cat=django_cat, title="Django Rocks", url="http://www.djangorocks.com/", views=256) add_page(cat=django_cat, title="How to Tango with Django", url="http://www.tangowithdjango.com/", views=512) frame_cat = add_cat(name="Other Frameworks", views=32, likes=16) add_page(cat=frame_cat, title="Bottle", url="http://bottlepy.org/docs/dev/", views=400) add_page(cat=frame_cat, title="Flask", url="http://flask.pocoo.org", views=300) # Print out what we have added to the user. for c in Category.objects.all(): for p in Page.objects.filter(category=c): print "- {0} - {1}".format(str(c), str(p)) def add_page(cat, title, url, views=0): p = Page.objects.get_or_create(category=cat, title=title)[0] p.url = url p.views = views p.save() return p def add_cat(name, views, likes): # The get_or_create() method returns a tuple of (object, created). c = Category.objects.get_or_create(name=name)[0] c.views = views c.likes = likes c.save() return c # Start execution here! if __name__ == '__main__': print "Starting Rango population script..." populate()
bfa5b4a6470235a489f54741c7f0f9fe574cef1a
1c0505803cf4ebe42bd1f6f369c949c35d7a4d5b
/ConceptZI/asgi.py
24e3f6d0b87254642df1b96f867bea4629215e26
[]
no_license
tahirs95/django_stripe_sepa
37d6787e0e5cb9e88dea7a94c3edcb07902f6fc1
8ed597be78aee9f84569562d4cd187485f750cb4
refs/heads/main
2023-08-22T19:16:35.786920
2021-10-01T16:22:36
2021-10-01T16:22:36
412,537,848
0
0
null
null
null
null
UTF-8
Python
false
false
395
py
""" ASGI config for ConceptZI project. It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/ """ import os from django.core.asgi import get_asgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ConceptZI.settings") application = get_asgi_application()
ed93de707065f2b8a365587714ca37565801df90
6d395ffb748ac60733e9a5f039e2a307adae44d4
/api/views_dir/xcx/page_group.py
ee7abc895b1e88940fd96cd77f904775668ab555
[]
no_license
itcastpeng/hzWebSiteApi
4f69c0f68dc78eebc4a5dad668d03e3c9d9c1d57
f2bcd7a9ef28bf9c7f867e803f35d7b307d25527
refs/heads/master
2021-03-06T14:26:34.923464
2020-03-10T04:07:27
2020-03-10T04:07:27
246,204,894
2
0
null
null
null
null
UTF-8
Python
false
false
2,787
py
from api import models from publicFunc import Response from publicFunc import account from django.http import JsonResponse from publicFunc.condition_com import conditionCom from api.forms.xcx.page_group import SelectForm import json # @account.is_token(models.UserProfile) def page_group(request): response = Response.ResponseObj() if request.method == "GET": forms_obj = SelectForm(request.GET) if forms_obj.is_valid(): current_page = forms_obj.cleaned_data['current_page'] length = forms_obj.cleaned_data['length'] print('forms_obj.cleaned_data -->', forms_obj.cleaned_data) order = request.GET.get('order', '-create_datetime') field_dict = { 'id': '', 'template_id': '', 'name': '__contains', 'create_datetime': '', } q = conditionCom(request, field_dict) print('q -->', q) objs = models.PageGroup.objects.filter(q).order_by(order) count = objs.count() if length != 0: start_line = (current_page - 1) * length stop_line = start_line + length objs = objs[start_line: stop_line] # 返回的数据 ret_data = [] default_page_id = None for obj in objs: # 获取分组下面的页面数据 page_objs = obj.page_set.all() page_data = [] for page_obj in page_objs: if not default_page_id: default_page_id = page_obj.id page_data.append({ 'id': page_obj.id, 'name': page_obj.name }) # 将查询出来的数据 加入列表 ret_data.append({ 'id': obj.id, 'name': obj.name, 'page_data': page_data, 'create_datetime': obj.create_datetime.strftime('%Y-%m-%d %H:%M:%S'), }) # 查询成功 返回200 状态码 response.code = 200 response.msg = '查询成功' response.data = { 'ret_data': ret_data, 'data_count': count, 'default_page_id': default_page_id, } response.note = { 'id': "页面分组id", 'name': '页面分组名称', 'create_datetime': '创建时间', } else: response.code = 402 response.msg = "请求异常" response.data = json.loads(forms_obj.errors.as_json()) return JsonResponse(response.__dict__)
f921dad333bc6888e2dfb4562a8301606217b4bc
871f682f14509323c796919a238988dd5360d36e
/if_else/last_number_7.py
70649431a102d07b442182db01ff3160c8c78d45
[]
no_license
shreshta2000/If-else_questions_
c59242ff07c626875f981a5c83a6287bdade24e3
f30f2100d6328367a3db92ef7ebf39db7e5f0107
refs/heads/master
2022-12-02T16:01:01.552430
2020-08-20T14:40:34
2020-08-20T14:40:34
289,026,245
0
0
null
null
null
null
UTF-8
Python
false
false
118
py
number=int(input("entre any number")) if number%10==7: print("last number is 7") else: print("last number is not 7")