def reverse(list): """Returns a new list or string with the elements or characters in reverse order""" if isinstance(list, str): return "".join(reversed(list)) return _list(reversed(list))
def main_stock (data): BASE_DIR =os.path.realpath(__file__) + data; reading_data = read_data('/home/reem/stock_site/stock/'+data) #Suez-Cement #Oriental-Weavers #T-M-G-Holding #Medinet-Nasr-Housing dates = reading_data["Date"].tolist() length = floor((len(reading_data) - 120) * (0.8)) dates = dates[length + 120:] close_scaled,open_scaled,high,low,openprice,closeprice,scaler_open,scaler_close= data_cleaning_scaling(reading_data) trainingX, testingX, trainingY, testingY = data_splitting(close_scaled,open_scaled) t = pd.to_datetime(str(dates[-1])) tomorowday = [] for i in range(3): t = t + datetime.timedelta(days=1) tomorowday.append(t.strftime('%Y/%m/%d')) #GRU_model(trainingX, trainingY) pred = GRU_model_load(testingX, testingY,trainingX) pred1 = scaler_open.inverse_transform(pred) testingy1=scaler_open.inverse_transform(testingY) testy=[] prediction=[] changing=[] for i in reversed (testingy1): testy.append(i) for i in reversed (pred1): prediction.append(i) for i in range(20): changing.append(abs(testy[i]-prediction[i])) change=max(changing) openprice_split=openprice[length + 120:] closeprice_split=closeprice[length + 120:] accuracy_up_down,res=classification(high,low,openprice_split,closeprice_split,pred1) pred2 ,test=GRU_predict(close_scaled) l=[] l1=[] for i in range(3): list_of_pred= scaler_open.inverse_transform(pred2[i]) if ((res)) > 2: l.append(list_of_pred + change) else: l.append(list_of_pred - change) l1.append(l[i][0][0]) print(list_of_pred) keras.backend.clear_session() return reading_data ,dates ,prediction,l1,testy,accuracy_up_down
def _equals(a, b, stack_a=[], stack_b=[]): if _identical(a, b): return True if type(a) != type(b): return False if a is None or b is None: return False if isinstance(getattr(a, "equals", None), collections.Callable) or \ isinstance(getattr(b, "equals", None), collections.Callable): return isinstance(getattr(a, "equals", None), collections.Callable) and \ a.equals(b) and \ isinstance(getattr(b, "equals", None), collections.Callable) and \ b.equals(a) if isinstance(a, (int, float, str)): if not (type(a) == type(b) and _identical(a, b)): return False if isinstance(a, collections.Callable) and isinstance(b, collections.Callable): return id(a) == id(b) keys_a = _keys(a) if len(keys_a) != len(_keys(b)): return False for item_a, item_b in builtins.reversed(builtins.list(builtins.zip(stack_a, stack_b))): if id(item_a) == id(a): return id(item_b) == id(b) stack_a.append(a) stack_b.append(b) for key in keys_a: if not (_has(key, b) and _equals(b[key], a[key], stack_a, stack_b)): return False stack_a.pop() stack_b.pop() return True
def rnn_backward(dh, cache): """ Compute the backward pass for a vanilla RNN over an entire sequence of data. Inputs: - dh: Upstream gradients of all hidden states, of shape (N, T, H). NOTE: 'dh' contains the upstream gradients produced by the individual loss functions at each timestep, *not* the gradients being passed between timesteps (which you'll have to compute yourself by calling rnn_step_backward in a loop). Returns a tuple of: - dx: Gradient of inputs, of shape (N, T, D) - dh0: Gradient of initial hidden state, of shape (N, H) - dWx: Gradient of input-to-hidden weights, of shape (D, H) - dWh: Gradient of hidden-to-hidden weights, of shape (H, H) - db: Gradient of biases, of shape (H,) """ dx, dh0, dWx, dWh, db = None, None, None, None, None ############################################################################## # TODO: Implement the backward pass for a vanilla RNN running an entire # # sequence of data. You should use the rnn_step_backward function that you # # defined above. You can use a for loop to help compute the backward pass. # ############################################################################## (N, T, H) = dh.shape dx_by_t = [] dprev_h_t = np.zeros(shape=(N, H)) for t in reversed(range(T)): dprev_h_t += dh[:, t, :] dx_t, dprev_h_t, dWx_t, dWh_t, db_t = rnn_step_backward( dprev_h_t, cache[t]) dx_by_t.append(dx_t) dWx = dWx_t + dWx if dWx is not None else dWx_t dWh = dWh_t + dWh if dWh is not None else dWh_t db = db_t + db if db is not None else db_t dx = np.asarray(list(reversed(dx_by_t))).transpose(1, 0, 2) dh0 = dprev_h_t ############################################################################## # END OF YOUR CODE # ############################################################################## return dx, dh0, dWx, dWh, db
def replace_vars(line: str, variables: dict, reverse: bool = False): if variables: for k in reversed(variables.keys()) if reverse else variables.keys(): v = str(variables[k]) k = str(k) if reverse: line = line.replace(v, k) else: line = line.replace(k, v) return line
def lstm_backward(dh, cache): """ Backward pass for an LSTM over an entire sequence of data.] Inputs: - dh: Upstream gradients of hidden states, of shape (N, T, H) - cache: Values from the forward pass Returns a tuple of: - dx: Gradient of input data of shape (N, T, D) - dh0: Gradient of initial hidden state of shape (N, H) - dWx: Gradient of input-to-hidden weight matrix of shape (D, 4H) - dWh: Gradient of hidden-to-hidden weight matrix of shape (H, 4H) - db: Gradient of biases, of shape (4H,) """ dx, dh0, dWx, dWh, db = None, None, None, None, None ############################################################################# # TODO: Implement the backward pass for an LSTM over an entire timeseries. # # You should use the lstm_step_backward function that you just defined. # ############################################################################# (N, T, H) = dh.shape dx_by_t = [] dprev_h_t = np.zeros(shape=(N, H)) dprev_c_t = np.zeros(shape=(N, H)) for t in reversed(range(T)): # sum gradients from t+1 step and from loss from step t dprev_h_t += dh[:, t, :] dx_t, dprev_h_t, dprev_c_t, dWx_t, dWh_t, db_t = \ lstm_step_backward(dprev_h_t, dprev_c_t, cache[t]) dx_by_t.append(dx_t) dWx = dWx_t + dWx if dWx is not None else dWx_t dWh = dWh_t + dWh if dWh is not None else dWh_t db = db_t + db if db is not None else db_t dx = np.asarray(list(reversed(dx_by_t))).transpose(1, 0, 2) dh0 = dprev_h_t ############################################################################## # END OF YOUR CODE # ############################################################################## return dx, dh0, dWx, dWh, db
def last_before(error: Callable[[str], None], target: str, files: List[str]) -> Tuple[int, str]: try: idx, file = next( (i, f) for i, f in enumerate(reversed(files)) if f <= target) idx = len(files) - idx - 1 return idx, file except StopIteration: error( f'No wrfout file found before\n\t\t{target}\n\tFirst file is:\n\t\t{files and files[0]}' ) sys.exit(1)
def ajax_get_reviews(request): try: pk = int(request.POST.get('id_pk').strip(' "')) page = int(request.POST.get('page').strip(' "')) reviews = list(reversed( Review.objects.filter(mechanic=pk, comment__isnull=False, comment__gt='').values_list('rating', 'comment', 'user'))) p = Paginator(reviews, 5) last = p.num_pages == page result = {"reviews": [ {"rating": int((x[0] / 5) * 100), "comment": x[1], "user": get_name_icon(get_user_model().objects.get(pk=x[2]))} for x in p.page(page)], "last": last} return HttpResponse(simplejson.dumps(result), content_type="application/json") except Exception: print(traceback.format_exc()) return HttpResponse("Internal Error, try again later", status=500)
def F(x, diffM: bool=False, sBoxesUsed: SBoxesUsed=None): sBoxes = sBoxesReal if not diffM else sBoxesDiff lx = numUtils.toArray(x, width=8, reverse=True) # SBoxes: for i in range(8): lx[i] = sBoxes[i][lx[i]] if sBoxesUsed is not None: sBoxesUsed.append(list(map(lambda num: 1 if num != 0 else 0, reversed(lx)))) # Permutation: lx = numUtils.doPermutation(lx, permTable) return numUtils.arrToInt(lx, reverse=True)
def checkDesignMatrix(X): """ Parameters ---------- X: a matrix of shape (T, N), where T denotes the number of samples and N labels the number of features. If T < N, a warning is issued to the user, and the transpose of X is considered instead. Returns: T: type int N: type int transpose_flag: type bool Specify if the design matrix X should be transposed in view of having less rows than columns. """ try: assert isinstance( X, (np.ndarray, pd.DataFrame, pd.Series, MutableSequence, Sequence)) except AssertionError: raise sys.exit(1) X = np.asarray(X, dtype=float) X = np.atleast_2d(X) if X.shape[0] < X.shape[1]: warnings.warn( "The Marcenko-Pastur distribution pertains to " "the empirical covariance matrix of a random matrix X " "of shape (T, N). It is assumed that the number of " "samples T is assumed higher than the number of " "features N. The transpose of the matrix X submitted " "at input will be considered in the cleaning schemes " "for the corresponding correlation matrix.", UserWarning) T, N = reversed(X.shape) transpose_flag = True else: T, N = X.shape transpose_flag = False return T, N, transpose_flag
def targeting(attackers, targets): # target phase # by order of (epower, init), groups choose a target (ignoring target hp) # target order is (do most dmg to, largest epower, init) targets = set(targets) fight = {} for attacker in reversed(sorted(attackers, key=lambda s: s.target_rank)): if len(targets) == 0: break attack = [(attacker.dmg_to(target), *target.target_rank, target) for target in targets] dmg, ep, init, target = max(attack) if dmg > 0: fight[attacker] = target targets.remove(target) return fight
def GRU_predict(dataclose): json_file = open('/home/reem/stock_site/stock/gruclassficationmodel1.json', 'r') loaded_model_json = json_file.read() json_file.close() loaded_model = model_from_json(loaded_model_json) # load weights into new model i=1 test=[] test1=[] loaded_model.load_weights("/home/reem/stock_site/stock/gruclassficationmodel1.h5") while(i<=120): dataclose[-i]=dataclose[-i].tolist() test.append(dataclose[-i]) i=i+1 for a in reversed(test): test1.append(a) test1=np.array(test1) test1 = np.reshape(test1, (1, test1.shape[0], test1.shape[1])) list_of_predit=[] print(test1.shape) for i in range (3): pred = loaded_model.predict(test1) list_of_predit.append(pred) test1=np.delete(test1,0) test1=np.append(test1,pred) test1 = np.reshape(test1, (1, test1.shape[0], 1)) print(test1.shape) print("list_of_predit",list_of_predit) #print("the value",pred) return list_of_predit ,test1
return inner int = rroulette(_.int, lambda v: _.int(v) - 1) float = rroulette(_.float, lambda v: _.float(v) + 0.001) str = rroulette(_.str, lambda v: _.str(v)[::-1]) bool = rroulette(_.bool, lambda v: not (_.bool(v))) len = rroulette(_.len, lambda v: _.len(v) - 1) ord = rroulette(_.ord, lambda v: _.ord(v.lower() if v.isupper() else v.upper())) abs = rroulette(_.abs, lambda v: -_.abs(v)) pow = rroulette(_.pow, lambda v, p: _.pow(v, p + 1)) min = rroulette(_.min, lambda *v: _.max(*v)) max = rroulette(_.max, lambda *v: _.min(*v)) sum = rroulette(_.sum, lambda v: reduce(op.__sub__, v)) hasattr = rroulette(_.hasattr, lambda o, n: not (_.hasattr(o, n))) sorted = rroulette(_.sorted, lambda v: _.reversed(v)) reversed = rroulette(_.reversed, lambda v: _.sorted(v)) enumerate = rroulette(_.enumerate, lambda v: ((i + 1, _v) for i, _v in _.enumerate(v))) globals = rroulette(_.globals, locals) locals = rroulette(_.locals, _.globals) id = rroulette(_.id, lambda v: _.id(_.id)) help = rroulette(_.help, lambda v: 'halp') exit = rroulette(_.exit, print)
return i int = r(_.int, lambda *a: _.int(*a) - 1) float = r(_.float, lambda v: _.float(v) + 0.001) str = r(_.str, lambda *a, **k: _.str(*a, **k)[::-1]) bool = r(_.bool, lambda v: not (_.bool(v))) len = r(_.len, lambda v: _.len(v) - 1) ord = r(_.ord, lambda v: _.ord(v.lower() if v.isupper() else v.upper())) abs = r(_.abs, lambda v: -_.abs(v)) pow = r(_.pow, lambda v, p, *a: _.pow(v, p + 1, *a)) min = r(_.min, lambda *a: _.max(*a)) max = r(_.max, lambda *a: _.min(*a)) sum = r(_.sum, lambda v, *a: reduce(op.__sub__, v)) hasattr = r(_.hasattr, lambda o, n: not (_.hasattr(o, n))) sorted = r(_.sorted, lambda *a, **k: list(_.reversed(*a, **k))) reversed = r(_.reversed, lambda v: _.sorted(v)) enumerate = r(_.enumerate, lambda v, *a: ((i + 1, _v) for i, _v in _.enumerate(v, *a))) globals = r(_.globals, locals) locals = r(_.locals, _.globals) id = r(_.id, lambda v: _.id(_.id)) help = r(_.help, lambda v: 'halp') exit = r(_.exit, print)
def __repr__(self): representation = "<Stack>\n" for ind, item in enumerate(reversed(self._items), 1): representation += f"{ind}: {str(item)}\n" return representation
'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine' ] numbers.reverse() # replaces the elements in reversed order print(numbers) #--------------------------------------------------------------------------------------------------- numbers = [ 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine' ] for number in reversed( numbers ): # the original list remains unchanged, only reverse in the loop print(number, end=' ') print() #--------------------------------------------------------------------------------------------------- numbers.sort() # sorts the original list alphabetically # numbers.sort(key = len) # numbers.sort(reverse = True) print(numbers) #--------------------------------------------------------------------------------------------------- numbers = [ 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight',
def resolve(self, obj) -> Var: try: self.push_stack() if isinstance(obj, ast.Subscript): target = obj value = self.new_var() if not isinstance(target.slice, ast.Index): raise self._err(target.slice) array = self.resolve(target.value) index = self.resolve(target.slice.value) try: offs = array.get_byte_offset() typ = array.typ inst = {Types.INTS: 'lw', Types.BYTES: 'lb'}[typ] if index.num is not None: self.inst(inst, value, self.new_var(num=offs * index.num), array, fmt='{}, {}({})', reads=[index, array], writes=[value], obj=obj) else: offset = self.new_var() self.assign(offset, index, obj) byte_mul = self.new_var(num=offs) self.inst('mul', offset, offset, byte_mul, reads=[byte_mul, offset], writes=[offset]) self.inst('add', offset, offset, array, reads=[offset, array], writes=[offset], obj=obj) self.inst(inst, value, 0, offset, reads=[offset], writes=[value], fmt='{}, {}({})', obj=obj) except TypeError as e: raise self._err( obj, 'No type defined for {} variable (line {} col {}).' ) from e return value if isinstance(obj, ast.Str): if len(obj.s) != 1: raise self._err( obj, 'Strings are not supported. Only char constants are allowed (line {} col {})' ) return self.new_var(num=ord(obj.s)) if isinstance(obj, ast.NameConstant): if not obj in [True, False, None]: raise self._err( obj, 'Unsupported constant {} (line {} col {}).') return self.new_var(num=1 if obj.value else 0) if isinstance(obj, ast.BoolOp): op = type(obj.op) if not all( type(i) in [ast.Compare, ast.NameConstant] for i in obj.values): raise self._err( obj, 'Unsupported {} expression in boolean expression (line {} col {}).' ) exp = obj.values[0] for value in obj.values[1:]: exp = ast.BinOp(exp, { ast.Or: ast.BitOr, ast.And: ast.BitAnd }[op](), value) return self.resolve(exp) if isinstance(obj, ast.Compare): left = self.resolve(obj.left) right = self.resolve(obj.comparators[0]) if left.num is not None and right.num is not None: exp = ast.Expression( ast.BinOp(ast.Num(left.num), obj.op, ast.Num(right.num))) return self.new_var( num=eval(compile(exp, '', mode='eval'))) op = type(obj.ops[0]) invert_output = False if left.num is not None: left, right = right, left op = { ast.Lt: ast.Gt, ast.LtE: ast.GtE, ast.Eq: ast.Eq, ast.NotEq: ast.NotEq }[op] if right.num is not None: if op == ast.GtE: invert_output = True op = ast.Lt if op == ast.Gt: invert_output = True op = ast.LtE if op == ast.LtE: right = self.new_var(num=right.num + 1) op = ast.Lt if op == ast.Gt: inst = 'sgt' elif op == ast.GtE: inst = 'sge' elif op == ast.Lt: inst = 'slt' if right.num is None else 'slti' elif op == ast.LtE: inst = 'sle' elif op == ast.Eq: inst = 'seq' if right.num is not None: new_right = self.new_var() self.assign(new_right, right, obj=obj) elif op == ast.NotEq: inst = 'sne' else: raise self._err(obj) out = self.new_var() self.inst(inst, out, left, right, reads=[left, right], writes=[out], obj=obj) if invert_output: self.inst('xori', out, out, 1, reads=[out], writes=[out], obj=obj) return out if isinstance(obj, ast.Num): return self.new_var(num=obj.n) if isinstance(obj, ast.Call): for context in self.stack: context.mark_func_call(self.cur_line) for i, arg in enumerate(obj.args): self.assign(self.new_var(reg='a' + str(i)), self.resolve(arg), obj=arg) self.inst('jal', obj.func.id, obj=obj) return_var = self.new_var(reg='v0') out_var = self.new_var() self.assign(out_var, return_var, obj=obj) return out_var if isinstance(obj, ast.UnaryOp): op = obj.op target = self.resolve(obj.operand) if target.num is not None: opera = ast.Num(target.num) opera.lineno = 0 opera.col_offset = 0 op = ast.UnaryOp(op, opera) op.lineno = 0 op.col_offset = 0 exp = ast.Expression(op) exp.lineno = 0 code = compile(exp, '', mode='eval') return self.new_var(num=eval(code)) if isinstance(op, ast.USub): var = self.new_var() var.typ = target.typ self.inst('mul', var, target, self.new_var(num=-1), reads=[target], writes=[var]) elif isinstance(op, ast.Invert): var = self.new_var() var.typ = target.typ self.inst('nor', var, target, target, reads=[target], writes=[var]) elif isinstance(op, ast.UAdd): var = target else: raise self._err( op, 'Unsupported unary operationr {} (line {} col {})') return var if isinstance(obj, ast.BinOp): left_val = self.resolve(obj.left) right_val = self.resolve(obj.right) op_to_inst = { ast.Mult: ('mul', 'mul'), ast.Add: ('add', 'addi'), ast.Sub: ('sub', 'sub'), ast.BitAnd: ('and', 'andi'), ast.BitOr: ('or', 'ori'), ast.BitXor: ('xor', 'xori'), ast.RShift: ('srl', 'srl'), ast.LShift: ('sllv', 'sll') } var = self.new_var() inst, im_inst = op_to_inst[type(obj.op)] if left_val.num is not None and right_val.num is not None: exp = ast.Expression( ast.BinOp(ast.Num(left_val.num), obj.op, ast.Num(right_val.num))) return self.new_var( num=eval(compile(exp, '', mode='eval'))) if left_val.num is not None: if inst in ['sub', 'srv', 'sllv']: old_num = left_val left_val = self.new_var() self.assign(left_val, old_num) else: left_val, right_val = right_val, left_val if type(obj.op) not in op_to_inst: raise self._err( obj.op, 'Unsupported operator {} at line {} col {}.') var.typ = var.typ or left_val.typ or right_val.typ self.inst(inst, var, left_val, right_val, reads=[left_val, right_val], writes=[var], obj=obj, imm=(im_inst, right_val)) return var if isinstance(obj, ast.Name): for ctx in reversed(self.stack): if obj.id in ctx: return ctx[obj.id] raise NameError("No such variable named '{}'.".format(obj.id)) raise self._err( obj, 'Unsupported {} expression syntax at line {} col {}.') finally: self.pop_stack()
def reversed(seq): '''Replacement for the built-in :func:`reversed() <python:reversed>` function.''' return builtins.reversed(seq)
def drop_last_while(fn, xs): drop = len([None for _ in itertools.takewhile(fn, builtins.reversed(xs))]) to = len(xs) - drop return xs[:to]
from builtins import reversed #how to find before 3 characters of a substring a = "Testing" b = "ing" x = a.find(b) #return index value which is 4 here print(a[x - 3:x]) #1:4 #Reverse a string (1st method) list1 = (list(reversed(a))) #reversed function return an object print(" ".join(list1)) #Reverse a string (2nd method) for i in reversed(a): #we can use list1 instead of reversed(a) too print(i) #Reverse a string (3rd method) l = len(a) #length is full and indexing starts from 0 so we have to take l-1 for i in range((l - 1), -1, -1): print(a[i]) #Reverse a string (4th method) a = "Testing" b = "" l = len(a) #length is full and indexing starts from 0 so we have to take l-1 for i in range((l - 1), -1, -1): b = b + a[i] print(b) #Palindrome a = "MadaM" #as python is case sensitive
lambda *args, **kwargs: builtins.print(*args, **kwargs), builtins.print) print._ = functools.update_wrapper( lambda *args, **kwargs: wrap(builtins.print)(*args, **kwargs), builtins.print) range = functools.update_wrapper( lambda *args, **kwargs: builtins.range(*args, **kwargs), builtins.range) range._ = functools.update_wrapper( lambda *args, **kwargs: wrap(builtins.range)(*args, **kwargs), builtins.range) repr = functools.update_wrapper( lambda *args, **kwargs: builtins.repr(*args, **kwargs), builtins.repr) repr._ = functools.update_wrapper( lambda *args, **kwargs: wrap(builtins.repr)(*args, **kwargs), builtins.repr) reversed = functools.update_wrapper( lambda *args, **kwargs: builtins.reversed(*args, **kwargs), builtins.reversed) reversed._ = functools.update_wrapper( lambda *args, **kwargs: wrap(builtins.reversed)(*args, **kwargs), builtins.reversed) round = functools.update_wrapper( lambda *args, **kwargs: builtins.round(*args, **kwargs), builtins.round) round._ = functools.update_wrapper( lambda *args, **kwargs: wrap(builtins.round)(*args, **kwargs), builtins.round) set = functools.update_wrapper( lambda *args, **kwargs: builtins.set(*args, **kwargs), builtins.set) set._ = functools.update_wrapper( lambda *args, **kwargs: wrap(builtins.set)(*args, **kwargs), builtins.set) setattr = functools.update_wrapper( lambda *args, **kwargs: builtins.setattr(*args, **kwargs),
def reversed(coll): try: return builtins.reversed(coll) except TypeError: return reversed(list(coll))
import functools, itertools, types, builtins, operator, weakref import logging, re, fnmatch import ptypes, image.bitmap from ptypes import * ptypes.setbyteorder(ptypes.config.byteorder.littleendian) ## combinators fcompose = lambda *f: functools.reduce(lambda f1, f2: lambda *a: f1(f2(*a)), builtins.reversed(f)) ## primitive types class s8(pint.sint_t): length = 1 class u8(pint.uint_t): length = 1 class s16(pint.sint_t): length = 2 class u16(pint.uint_t): length = 2 class s24(pint.sint_t):
def reverseString_ByReversed(inputStr): if inputStr is None or len(inputStr) is 0: return None return ''.join(reversed(inputStr))
def find_write_before(self, line): for i in reversed(self.writes): if i < line: return i return float('-inf')
from builtins import reversed r = reversed([2, 5, 3]) # print(r[2]) # print(reversed(r)) print(5 in r, 2 in r, 5 in r) from betterbuiltins import reversed r = reversed([2, 5, 3]) print(5 in r, 2 in r, 5 in r, 7 in r) print(r[2]) print(*reversed(r)) from builtins import zip i1, i2, i3, i4 = iter('ABCDE'), iter('ghi'), iter('abc'), iter('FGHIJ') z = zip(i1, i2, i3, i4) print(*z) print(next(i2, None), next(i4, None), next(i1, None)) from betterbuiltins import zip z = zip('ABCDE', 'ghi', 'abc', 'FGHIJ') print(z[1], z[-1]) print(*reversed(z)) from builtins import map m = map(pow, [2, 3, 1, 8, 3], [6, 3, 9, 7], [12, 9, 45, 99]) # print(m[:2])
def read_accumulation(cfg: ConfigGetter, to_time: datetime, from_time: datetime, verbose: bool) -> np.ndarray: """ Read accumulation between timestamps in the configured accumulation """ if from_time >= to_time: cfg.error( f'Empty accumulation period {from_time :%Y-%m-%dT%H:%M} … {to_time :%Y-%m-%dT%H:%M}' ) files = set() paths = cfg.wrfouts if isinstance(paths, str): paths = [paths] for path in paths: path = os.path.expandvars(path) path = os.path.expanduser(path) files_for_path: List[str] = glob(path, recursive=True) files.update(files_for_path) files = sorted(files) if len(files) == 0: print('No wrfout files found') sys.exit(1) if verbose: print(f'\nFound {len(files)} wrfout files') print(f'from time: {from_time:%Y-%m-%dT%H:%M}') print(f' to time: {to_time:%Y-%m-%dT%H:%M}') from_step, step_to = cfg.get('file_steps', (None, None)) if from_step: spinup = timedelta(minutes=from_step * cfg.step_length) from_time_file = from_time - spinup to_time_file = to_time - spinup print(f'\nfrom time: {from_time_file:%Y-%m-%dT%H:%M} with spinup') print(f' to time: {to_time_file:%Y-%m-%dT%H:%M} with spinup') else: from_time_file = from_time to_time_file = to_time wrfout_tpl = cfg.wrfout_tpl wrfout_tpl = os.path.expandvars(wrfout_tpl) wrfout_tpl = os.path.expanduser(wrfout_tpl) # We need the last files that start on or before from_time and to_time from_idx, from_file = last_before( cfg.error, wrfout_tpl.format(start_time=from_time_file), files) to_idx, to_file = last_before(cfg.error, wrfout_tpl.format(start_time=to_time_file), files) if cfg.verbose: print('files:') for i, file in enumerate(files): print(f' {file}', '← from' if i == from_idx else '← to' if i == to_idx else '') print() if from_step is None: # All files are from one simulation if from_file == to_file: accumulation = read_accumulation_time_to_time( from_file, from_time, to_time, verbose) print("accumulation:", np.sum(accumulation)) return accumulation else: to_accumulation = read_accumulation_time_to_time( to_file, to_time, None, verbose) from_accumulation = read_accumulation_time_to_time( from_file, from_time, None, verbose) accumulation = to_accumulation - from_accumulation if cfg.verbose: print("from_accumulation:", np.round(np.sum(from_accumulation), 2)) print(" to_accumulation:", np.round(np.sum(to_accumulation), 2)) print(" accumulation:", np.round(np.sum(accumulation), 2)) return accumulation else: # Each file is from a different simulation so we need to accumulate over each and sum ptr_time = to_time accumulation = 0 for file in reversed(files[from_idx:to_idx + 1]): accumulation_from_file, ptr_time = read_accumulation_idx_to_time( file, from_time, from_step, ptr_time, verbose) accumulation += accumulation_from_file return accumulation
def metodat(inputlista, clientSocket, clientAddress): connection = clientSocket address = clientAddress if (inputlista[0] == 'IPADRESA'): connection.send( str.encode(" IP Adresa e klientit është: " + address[0])) elif (inputlista[0] == 'NUMRIIPORTIT'): connection.send( str.encode("Klienti është duke përdorur portin " + str(address[1]))) elif (inputlista[0] == 'BASHKETINGELLORE'): try: fjala = ''.join(inputlista[1:]) bashketingelloret = ("bcdfghjklmnpqrstvwxzBCDFGHJKLMNPQRSTVWXZ ") nr = 0 for x in fjala: if x in bashketingelloret: nr += 1 connection.send( str.encode("Teksti i pranuar përmbanë " + str(nr) + " bashketingellore")) except Exeption: connection.send( str.encode("Pas kërkesës ju lutem shkruani tekstin")) elif (inputlista[0] == 'PRINTIMI'): s = ' '.join(inputlista[1:]) if not s: connection.send( str.encode("Pas kërkesës ju lutem shkruani tekstin")) else: connection.send(str.encode(s)) elif (inputlista[0] == 'EMRIIKOMPJUTERIT'): try: hostname = socket.gethostname() connection.send(str.encode("Emri i klientit është " + hostname)) except Exception: connection.send(str.encode("Emri i klientit nuk dihet.")) elif (inputlista[0] == 'KOHA'): result = str(datetime.datetime.now().strftime("%d.%m.%Y %H:%M:%S %p")) connection.send(str.encode(result)) elif (inputlista[0] == 'LOJA'): data = str(random.sample(range(1, 49), 7)) connection.send(str.encode(data)) elif (inputlista[0] == 'FIBONACCI'): try: n = fib(int(inputlista[1])) connection.send(str.encode(str(n))) except Exception: connection.send( str.encode("Pas kërkesës ju lutem shkruani shifrën")) #Kilowatt to Horsepower 1kW=1.341Hp #Horsepower to Kilowatt 1Hp=1/1.341kW #Degrees to Radians 1°* (π/180)=0.01745rad #Radians to Degrees 1rad* 180/π=57,296° #Gallons to Litters 1gallon= 3.785L #Litters to Gallons 1L=1/3.785gallons #b-lloji i konvertimit #a-vlera qe konvertohet #c-rezultati elif (inputlista[0] == 'KONVERTIMI'): konvertimet = "Mund t'i bëni këto konvertime:\nKilowattToHorsePower \nHorsepowerToKilowatt \nDegreesToRadians \nRadiansToDegrees \nGallonsToLiters \nLitersToGallons" try: b = inputlista[1] a = float(inputlista[2]) c = '' if (b == "KilowattToHorsepower"): c = (a * 1.341) connection.send(str.encode(str(c))) elif (b == "HorsepowerToKilowatt"): c = (a / 1.341) connection.send(str.encode(str(c))) elif (b == "DegreesToRadians"): c = a * (3.14 / 180) connection.send(str.encode(str(c))) elif (b == "RadiansToDegrees"): c = a * (180 / 3.14) connection.send(str.encode(str(c))) elif (b == "GallonsToLiters"): c = (a * 3.785) connection.send(str.encode(str(c))) elif (b == "LitersToGallons"): c = (a / 3.785) connection.send(str.encode(str(c))) except Exception: connection.send( str.encode( "Ju lutem shkruani emrin e kërkesës, konvertimin e zgjedhur dhe shifrën që dëshironi ta konvertoni\n" + konvertimet)) elif (inputlista[0] == 'PALINDROM'): try: p = inputlista[1] n = reversed(p) if list(p) == list(n): connection.send(str.encode("Është palindrom")) else: connection.send(str.encode("Nuk është palindrom")) except Exception: connection.send( str.encode("Pas kërkesës ju lutem shkruani tekstin")) elif (inputlista[0] == 'VITIBRISHT'): try: vb = int(inputlista[1]) if (vb % 4 == 0 and vb % 100 != 0 or vb % 400 == 0): connection.send(str.encode("Eshtë vit i brishtë!")) else: connection.send(str.encode("Nuk është vit i brishtë")) except Exception: connection.send(str.encode("Pas kërkesës ju lutem shkruani vitin")) else: connection.send(str.encode("Ju lutem zgjedhni njërën nga kërkesat!"))
def isPalindrome(inputString): return list(inputString) == list(reversed(inputString))
def parent_func_label(self): for i, (name, obj) in reversed(list(enumerate(self.labels_stack))): if isinstance(obj, ast.FunctionDef): return '_'.join(name for name, obj in self.labels_stack[:i + 1]) return None
def quantize_lines(self) -> list: used_regs = set() # type: Set[str] all_used_regs = set() for line_no, line in enumerate(self.lines): if isinstance(line, Command): for var in line.reads: var.quantize(used_regs, line_no) for var in line.writes: var.quantize(used_regs, line_no) for var in line.reads + line.writes: if var.reg: all_used_regs.add(var.reg) s_regs = [i for i in all_used_regs if i.startswith('s')] saved_regs = ['ra'] * bool(self.ctx['__ra__'].func_calls) + s_regs lines = [] last_line = None for line in self.lines: if isinstance(line, Command): if line.still_useful: lines.append(str(line)) last_line = Command elif isinstance(line, Label): lines.append('') lines.append(str(line)) last_line = Label elif isinstance(line, Spacer): if last_line == Command: lines.append('') last_line = Spacer elif isinstance(line, StackAlloc): if saved_regs: lines.append( str( Command('sub', '$sp', 4 * len(saved_regs), obj='Allocate stack'))) for i, reg in enumerate(sorted(saved_regs)): lines.append( str( Command('sw', '$' + reg, i * 4, fmt='{}, {}($sp)'))) last_line = Command elif isinstance(line, StackDealloc): if saved_regs: for i, reg in reversed(list(enumerate( sorted(saved_regs)))): lines.append( str( Command('lw', '$' + reg, i * 4, fmt='{}, {}($sp)'))) lines.append( str( Command('add', '$sp', 4 * len(saved_regs), obj='Deallocate stack'))) last_line = Command elif isinstance(line, AssemblerLine): lines.append(str(line)) else: raise RuntimeError('Unknown type in lines') return lines