content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
import os import logging import matplotlib matplotlib.use('Agg') import pylab as p import numpy as np import dolfin as df from finmag import Simulation as Sim from finmag.energies import Exchange, Demag from finmag.util.meshes import from_geofile, mesh_volume import pytest logger = logging.getLogger(name='finmag') MODULE_DIR = os.path.dirname(os.path.abspath(__file__)) REL_TOLERANCE = 5e-4 Ms = 0.86e6 unit_length = 1e-9 mesh = from_geofile(os.path.join(MODULE_DIR, "bar30_30_100.geo")) def run_finmag(): """Run the finmag simulation and store data in averages.txt.""" sim = Sim(mesh, Ms, unit_length=unit_length) sim.alpha = 0.5 sim.set_m((1, 0, 1)) exchange = Exchange(13.0e-12) sim.add(exchange) demag = Demag(solver="FK") sim.add(demag) fh = open(os.path.join(MODULE_DIR, "averages.txt"), "w") fe = open(os.path.join(MODULE_DIR, "energies.txt"), "w") logger.info("Time integration") times = np.linspace(0, 3.0e-10, 61) for counter, t in enumerate(times): # Integrate sim.run_until(t) # Save averages to file mx, my, mz = sim.m_average fh.write(str(t) + " " + str(mx) + " " + str(my) + " " + str(mz) + "\n") # Energies E_e = exchange.compute_energy() E_d = demag.compute_energy() fe.write(str(E_e) + " " + str(E_d) + "\n") # Energy densities if counter == 10: exch_energy = exchange.energy_density_function() demag_energy = demag.energy_density_function() finmag_exch, finmag_demag = [], [] R = range(100) for i in R: finmag_exch.append(exch_energy([15, 15, i])) finmag_demag.append(demag_energy([15, 15, i])) # Store data np.save(os.path.join(MODULE_DIR, "finmag_exch_density.npy"), np.array(finmag_exch)) np.save(os.path.join(MODULE_DIR, "finmag_demag_density.npy"), np.array(finmag_demag)) fh.close() fe.close() if __name__ == '__main__': run_finmag() test_compare_averages() test_compare_energies() test_compare_energy_density()
[ 11748, 28686, 198, 11748, 18931, 198, 11748, 2603, 29487, 8019, 198, 6759, 29487, 8019, 13, 1904, 10786, 46384, 11537, 198, 11748, 279, 2645, 397, 355, 279, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 288, 4024, 259, 355, 47764, 198, ...
2.12996
1,008
from ..helpers import get_obj_and_params, all_from_objects from ...extensions.samplers import OverSampler SAMPLERS = { 'oversample': (OverSampler, ['default']), } all_obj_keys = all_from_objects(SAMPLERS)
[ 6738, 11485, 16794, 364, 1330, 651, 62, 26801, 62, 392, 62, 37266, 11, 477, 62, 6738, 62, 48205, 198, 6738, 2644, 2302, 5736, 13, 37687, 489, 364, 1330, 3827, 16305, 20053, 198, 198, 49302, 6489, 4877, 796, 1391, 198, 220, 220, 220, ...
2.813333
75
N, K = map(int, input().split()) ans = N for i in range(K): num_list = [int(n) for n in str(ans)] g1 = sorted(num_list, reverse=True) g1 = ''.join((str(g) for g in g1)) g2 = sorted(num_list, reverse=False) g2 = ''.join((str(g) for g in g2)) ans = int(g1) - int(g2) print(ans)
[ 45, 11, 509, 796, 3975, 7, 600, 11, 5128, 22446, 35312, 28955, 198, 504, 796, 399, 198, 1640, 1312, 287, 2837, 7, 42, 2599, 198, 220, 220, 220, 997, 62, 4868, 796, 685, 600, 7, 77, 8, 329, 299, 287, 965, 7, 504, 15437, 198, 22...
2.097902
143
# Python modules import time from datetime import timedelta def consistency(func, args, expected, n=10**4): """Analyze and report on the consistency of a function.""" print('\n[CONSISTENCY TEST] {0}'.format(func.__doc__.format(*args))) start = time.time() interval = start tally = 0 for i in range(n): isCorrect = func(*args) == expected tally += (1 if isCorrect else 0) diff = time.time() - interval if diff > 0.01: interval = time.time() show(tally, (i+1), time.time() - start, (i+1)/n) show(tally, n, time.time() - start, (i+1)/n, '\n') def max_over(n, func, args=None): """Compute the maximum value returned by func(args) in n runs.""" m = 0 for i in range(n): v = func(*args) if args else func() if v > m: m = v return m
[ 2, 11361, 13103, 198, 11748, 640, 198, 6738, 4818, 8079, 1330, 28805, 12514, 628, 198, 4299, 15794, 7, 20786, 11, 26498, 11, 2938, 11, 299, 28, 940, 1174, 19, 2599, 198, 220, 220, 220, 37227, 37702, 2736, 290, 989, 319, 262, 15794, ...
2.325203
369
from itertools import permutations from collections import Counter import time print(time.time()) s=["dgajkhdjkjfkl","ahfjkh","jfskoj","hfakljfio","fjfjir","jiosj","jiojf","jriosj","jiorjf","jhhhhaskgasjdfljjriof"] t=10 while t>0: S=s[10-t] c=dict(Counter(S)) Cperm=list(permutations(c.values())) flag= False for i in Cperm: for j in range(2,len(i)): if i[j]==i[j-1]+i[j-2]: print("Dynamic") flag= True break if flag==True: break else: print("Not") t=t-1 print(time.time())
[ 6738, 340, 861, 10141, 1330, 9943, 32855, 198, 6738, 17268, 1330, 15034, 198, 11748, 640, 198, 4798, 7, 2435, 13, 2435, 28955, 198, 82, 28, 14692, 67, 70, 1228, 14636, 28241, 42421, 69, 41582, 2430, 993, 69, 73, 14636, 2430, 73, 9501,...
2
260
import configparser import os from typing import ByteString import requests from core.speaker import Speaker from core.texttospeech import TextToSpeechGenerator
[ 11748, 4566, 48610, 198, 11748, 28686, 198, 198, 6738, 19720, 1330, 30589, 10100, 198, 198, 11748, 7007, 198, 198, 6738, 4755, 13, 4125, 3110, 1330, 14931, 198, 6738, 4755, 13, 5239, 83, 418, 431, 3055, 1330, 8255, 2514, 5248, 3055, 864...
3.837209
43
import pandas as pd import os import ssl # I'm getting SSL certificates issues when downloading files from MDIC. # The code below is a hack to get around this issue. try: _create_unverified_https_context = ssl._create_unverified_context except AttributeError: pass else: ssl._create_default_https_context = _create_unverified_https_context if __name__ == '__main__': ExportsObject = ExportsByMesoregion(start_year=2020, end_year=2020, transaction_type='imports') ExportsObject.download_data_and_aggregate_by_meso()
[ 11748, 19798, 292, 355, 279, 67, 198, 11748, 28686, 198, 11748, 264, 6649, 220, 198, 198, 2, 314, 1101, 1972, 25952, 20835, 2428, 618, 22023, 3696, 422, 10670, 2149, 13, 198, 2, 383, 2438, 2174, 318, 257, 8156, 284, 651, 1088, 428, ...
2.919786
187
# Generated by Django 3.1.1 on 2020-10-02 01:11 from django.db import migrations, models import phonenumber_field.modelfields
[ 2, 2980, 515, 416, 37770, 513, 13, 16, 13, 16, 319, 12131, 12, 940, 12, 2999, 5534, 25, 1157, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 198, 11748, 32896, 268, 4494, 62, 3245, 13, 19849, 25747, 628 ]
3.047619
42
from socket import socket, AF_INET, SOCK_STREAM, IPPROTO_TCP import struct import pickle if __name__ == "__main__": server = ServerSock(5500) while True: print(server.getMessage())
[ 6738, 17802, 1330, 17802, 11, 12341, 62, 1268, 2767, 11, 311, 11290, 62, 2257, 32235, 11, 6101, 4805, 26631, 62, 4825, 47, 198, 11748, 2878, 198, 11748, 2298, 293, 198, 220, 220, 220, 220, 220, 220, 220, 220, 220, 198, 198, 361, 115...
2.322581
93
#!/usr/bin/env python # -*- coding: utf-8 -*- from collections import namedtuple import numpy as np import pandas as pd from .series import Series
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 17268, 1330, 3706, 83, 29291, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 6738...
3.020408
49
""" instructions: blah blah blah settings: tifa: enabled: True unit test by function (bool): Whether to test each function entirely before moving onto the next one, or to first check that all functions have been defined, and then checking their parameters, etc. Defaults to True. show case details (bool): Whether to show the specific args/inputs that caused a test case to fail. rubric: functions: total: 100 definition: 10 signature: 10 cases: 80 global: variables: name: type: value: inputs: prints: # Sandbox, type checking functions: documentation: "any" or "google" coverage: 100% tests: int name: do_complicated_stuff arity: int signature: int, int -> float signature: int, int, list[int], (int->str), dict[str:list[int]] -> list[int] parameters: name: banana exactly: regex: includes: within: type: int cases: - arguments (list): 5, 4 inputs (list): returns (Any): equals: 27.3 is: is not: _1 name (str): Meaningful name for tracking purposes? Or possibly separate into label/id/code hint (str): Message to display to user prints: exactly: regex: startswith: endswith: plots: # Cait syntax: prevent: ___ + ___ # Override any of our default feedback messages messages: FUNCTION_NOT_DEFINED: "Oops you missed a function" """ from pedal.core.commands import set_success, give_partial from pedal.core.feedback_category import FeedbackCategory from pedal.questions.constants import TOOL_NAME from pedal.sandbox.commands import get_sandbox from pedal.utilities.comparisons import equality_test SETTING_SHOW_CASE_DETAILS = "show case details" DEFAULT_SETTINGS = { SETTING_SHOW_CASE_DETAILS: True } EXAMPLE_DATA = { 'functions': [{ 'name': 'do_complicated_stuff', 'signature': 'int, int, [int] -> list[int]', 'cases': [ {'arguments': "5, 4, 3", 'returns': "12"}, ] }] } def check_function_defined(function, function_definitions, settings=None): """ Args: function: function_definitions: settings: Returns: """ # 1. Is the function defined syntactically? # 1.1. With the right name? function_name = function['name'] if function_name not in function_definitions: raise FeedbackException(FeedbackCategory.SPECIFICATION, 'missing_function', function_name=function_name) definition = function_definitions[function_name] return definition def check_function_signature(function, definition, settings=None): """ Args: function: definition: settings: Returns: """ function_name = function['name'] # 1.2. With the right parameters and return type? # 1.2.1 'arity' style - simply checks number of parameters if 'arity' in function or 'parameters' in function: expected_arity = function['arity'] if 'arity' in function else len(function['parameters']) actual_arity = len(definition.args.args) if actual_arity < expected_arity: raise FeedbackException(FeedbackCategory.SPECIFICATION, 'insufficient_args', function_name=function_name, expected_arity=expected_arity, actual_arity=actual_arity) elif actual_arity > expected_arity: raise FeedbackException(FeedbackCategory.SPECIFICATION, 'excessive_args', function_name=function_name, expected_arity=expected_arity, actual_arity=actual_arity) # 1.2.2 'parameters' style - checks each parameter's name and type if 'parameters' in function: expected_parameters = function['parameters'] actual_parameters = definition.args.args for expected_parameter, actual_parameter in zip(expected_parameters, actual_parameters): actual_parameter_name = get_arg_name(actual_parameter) if 'name' in expected_parameter: if actual_parameter_name != expected_parameter['name']: raise FeedbackException(FeedbackCategory.SPECIFICATION, 'wrong_parameter_name', function_name=function_name, expected_parameter_name=expected_parameter['name'], actual_parameter_name=actual_parameter_name ) if 'type' in expected_parameter: actual_parameter_type = parse_type(actual_parameter) # TODO: Handle non-string expected_parameter types (dict) expected_parameter_type = parse_type_value(expected_parameter['type'], True) if not type_check(expected_parameter_type, actual_parameter_type): raise FeedbackException(FeedbackCategory.SPECIFICATION, 'wrong_parameter_type', function_name=function_name, parameter_name=actual_parameter_name, expected_parameter_type=expected_parameter_type, actual_parameter_type=actual_parameter_type) # 1.2.3. 'returns' style - checks the return type explicitly if 'returns' in function: expected_returns = parse_type_value(function['returns'], True) actual_returns = parse_type(definition.returns) if actual_returns != "None": if not type_check(expected_returns, actual_returns): raise FeedbackException(FeedbackCategory.SPECIFICATION, "wrong_returns", function_name=function_name, expected_returns=expected_returns, actual_returns=actual_returns) elif expected_returns != "None": raise FeedbackException(FeedbackCategory.SPECIFICATION, "missing_returns", function_name=function_name, expected_returns=expected_returns) # 1.2.4. 'signature' style - shortcut for specifying the types if 'signature' in function: expected_signature = function['signature'] actual_returns = parse_type(definition.returns) actual_parameters = ", ".join(parse_type(actual_parameter.annotation) for actual_parameter in definition.args.args) actual_signature = "{} -> {}".format(actual_parameters, actual_returns) if not type_check(expected_signature, actual_signature): raise FeedbackException(FeedbackCategory.SPECIFICATION, "wrong_signature", function_name=function_name, expected_signature=expected_signature, actual_signature=actual_signature) # All good here! return True def check_function_value(function, values, settings): """ 2. Does the function exist in the data? :param function: :param values: :param settings: :return: """ function_name = function['name'] # 2.1. Does the name exist in the values? if function_name not in values: raise FeedbackException(FeedbackCategory.SPECIFICATION, "function_not_available", function_name=function_name) function_value = values[function_name] # 2.2. Is the name bound to a callable? if not callable(function_value): raise FeedbackException(FeedbackCategory.SPECIFICATION, "name_is_not_function", function_name=function_name) # All good here return function_value def check_case(function, case, student_function): """ :param function: :param case: :param student_function: :return: status, arg, input, error, output, return, message """ function_name = function['name'] test_case = TestCase(function_name, case.get('name')) # Get callable sandbox = get_sandbox(MAIN_REPORT) sandbox.clear_output() # Potential bonus message if 'message' in case: test_case.add_message(case['message']) # Queue up the the inputs if 'inputs' in case: test_case.add_inputs(case['inputs']) sandbox.set_input(test_case.inputs) else: sandbox.clear_input() # Pass in the arguments and call the function if 'arguments' in case: test_case.add_arguments(case['arguments']) result = sandbox.call(function_name, *test_case.arguments) # Store actual values test_case.add_prints_returns(sandbox.output, result) # Check for errors if sandbox.exception: test_case.add_error(sandbox.exception) # 4. Check out the output if 'prints' in case: test_case.add_expected_prints(case['prints']) if not output_test(sandbox.output, case['prints'], False, .0001): test_case.fail() # 5. Check the return value if 'returns' in case: test_case.add_expected_returns(case['returns']) if not equality_test(result, case['returns'], True, .0001): test_case.fail() # TODO: Check the plots # Return results return test_case # TODO: blockpy-feedback-unit => pedal-test-cases in BlockPy Client TEST_TABLE_TEMPLATE = """<table class='pedal-test-cases table table-sm table-bordered table-hover'> <tr class='table-active'> <th></th> <th>Arguments</th> <th>Expected</th> <th>Returned</th> </tr> {body} </table>""" TEST_TABLE_FOOTER = "</table>" TEST_TABLE_ROW_HEADER = "<tr class='table-active'>" TEST_TABLE_ROW_NORMAL = "<tr>" TEST_TABLE_ROW_FOOTER = "</tr>" TEST_TABLE_ROW_INFO = "<tr class='table-info'>" GREEN_CHECK = " <td class='green-check-mark'>&#10004;</td>" RED_X = " <td>&#10060;</td>" CODE_CELL = " <td><code>{}</code></td>" COLUMN_TITLES = ["", "Arguments", "Inputs", "Errors", "Expected", "Expected", "Returned", "Printed"] def make_table(cases): """ Args: cases: Returns: """ body = [] for case in cases: body.append(" <tr>") body.append(GREEN_CHECK if case.success else RED_X) body.append(CODE_CELL.format(", ".join(repr(arg) for arg in case.arguments))) if case.has_error: body.append(" <td colspan='2'>Error: <code>{}</code></td>".format(str(case.error))) else: body.append(CODE_CELL.format(repr(case.expected_returns))) body.append(CODE_CELL.format(repr(case.returns))) if not case.success and case.has_message: body.append(" </tr><tr><td colspan='4'>{}</td>".format(case.message)) body.append(" </tr>") body = "\n".join(body) return TEST_TABLE_TEMPLATE.format(body=body) #if ((any(args) and any(inputs)) or # (any(expected_outputs) and any(expected_returns)) or # (any(actual_outputs) and any(actual_returns))): # # Complex cells # pass #else: # Simple table # Make header # row_mask = [True, any(args), any(inputs), False, # any("returns" in reason for reason in reasons), # any("prints" in reason for reason in reasons), # any("returns" in reason for reason in reasons), # any("prints" in reason for reason in reasons)] # header_cells = "".join("<th>{}</th>".format(title) for use, title in zip(row_mask, COLUMN_TITLES) if use) # body = [TEST_TABLE_ROW_HEADER.format(header_cells)] # for case in zip( # statuses, args, inputs, errors, actual_outputs, actual_returns, # expected_outputs, expected_returns): # status, case = case[0], case[1:] # print(row_mask[1:], case) # def make_code(values): # if values == None: # return "<code>None</code>" # elif isinstance(values, int): # return "<code>{!r}</code>".format(values) # else: # return ", ".join("<code>{}</code>".format(repr(value)) for value in values) # body.append( # TEST_TABLE_ROW_NORMAL+ # (GREEN_CHECK if case[0] else RED_X)+ # "\n".join(" <td>{}</td>".format(make_code(values)) # for use, values in zip(row_mask[1:], case) if use)+ # "</tr>\n" # ) # # Make each row # table = "{}\n{}\n{}".format(TEST_TABLE_HEADER, "\n ".join(body), TEST_TABLE_FOOTER) # return table def check_cases(function, student_function, settings): """ Args: function: student_function: settings: """ function_name = function['name'] if 'cases' in function: cases = function['cases'] test_cases = [check_case(function, case, student_function) for case in cases] success_cases = sum(test.success for test in test_cases) if success_cases < len(cases): if settings[SETTING_SHOW_CASE_DETAILS]: table = make_table(test_cases) raise FeedbackException(FeedbackCategory.SPECIFICATION, "failed_test_cases", function_name=function_name, cases_count=len(cases), failure_count=len(cases)-success_cases, table=table) else: raise FeedbackException(FeedbackCategory.SPECIFICATION, "failed_test_cases_count", function_name=function_name, cases_count=len(cases), failure_count=len(cases) - success_cases) def get_arg_name(node): """ Args: node: Returns: """ name = node.id if name is None: return node.arg else: return name def check_question(data): """ Args: data: """ results = list(load_question(data)) if results: message, label = results[0] gently(message, label=label) def check_pool(questions): """ Args: questions: """ pass def load_file(filename): """ Args: filename: """ pass FEEDBACK_MESSAGES = { FeedbackCategory.SPECIFICATION: { "missing_function": "No function named `{function_name}` was found.", "insufficient_args": ("The function named `{function_name}` " "has fewer parameters ({actual_arity}) " "than expected ({expected_arity})."), "excessive_args": ("The function named `{function_name}` " "has more parameters ({actual_arity}) " "than expected ({expected_arity})."), # TODO: missing_parameter that checks if parameter name exists, but is in the wrong place "wrong_parameter_name": ("Error in definition of `{function_name}`. " "Expected a parameter named `{expected_parameter_name}`, " "instead found `{actual_parameter_name}`."), "wrong_parameter_type": ("Error in definition of function `{function_name}` " "parameter `{parameter_name}`. Expected `{expected_parameter_type}`, " "instead found `{actual_parameter_type}`."), "missing_returns": ("Error in definition of function `{function_name}` return type. " "Expected `{expected_returns}`, but there was no return type specified."), "wrong_returns": ("Error in definition of function `{function_name}` return type. " "Expected `{expected_returns}`, instead found `{actual_returns}`."), "wrong_signature": ("Error in definition of function `{function_name}` signature. " "Expected `{expected_signature}`, instead found `{actual_signature}`."), "name_is_not_function": "You defined `{function_name}`, but did not define it as a function.", "function_not_available": ("You defined `{function_name}` somewhere in your code, " "but it was not available in the top-level scope to be called. " "Perhaps you defined it inside another function or scope?"), "failed_test_cases": ("I ran your function <code>{function_name}</code> on my own test cases. " "It failed {failure_count}/{cases_count} of my tests.\n{table}"), "failed_test_cases_count": ("I ran your function <code>{function_name}</code> on my own test cases. " "It failed {failure_count}/{cases_count} of my tests."), } }
[ 37811, 198, 259, 7249, 507, 25, 33367, 33367, 33367, 198, 198, 33692, 25, 198, 220, 220, 220, 256, 19215, 25, 198, 220, 220, 220, 220, 220, 220, 220, 9343, 25, 6407, 198, 220, 220, 220, 4326, 1332, 416, 2163, 357, 30388, 2599, 10127...
2.220201
7,643
import enum from .ELF import ELF32, enums from .util import SegmentRegs, MissingOpcodeError from .CPU import CPU32 import logging logger = logging.getLogger(__name__)
[ 11748, 33829, 198, 198, 6738, 764, 37738, 1330, 17852, 37, 2624, 11, 551, 5700, 198, 6738, 764, 22602, 1330, 1001, 5154, 8081, 82, 11, 25639, 18257, 8189, 12331, 198, 6738, 764, 36037, 1330, 9135, 2624, 198, 198, 11748, 18931, 198, 6404...
2.934426
61
from termcolor import colored from ...utils.feedback import feedback from .constants import DEPLOYMENT_PREFIX, DEPLOYMENT_REGISTRY from .exceptions import EntityDoesNotExist, EntityExists from .operations import delete_parameter, get_parameter, set_parameter from .project import assert_project_exists from .utils import aws_client def deployment_exists(project, deployment, ssm=None): registry = get_parameter(DEPLOYMENT_REGISTRY.format(project), ssm=ssm) return deployment in registry def assert_deployment_exists(project, deployment, ssm=None): if not deployment_exists(project, deployment, ssm=ssm): raise EntityDoesNotExist( f'deployment {deployment} does not exist' )
[ 6738, 3381, 8043, 1330, 16396, 198, 198, 6738, 2644, 26791, 13, 12363, 1891, 1330, 7538, 198, 6738, 764, 9979, 1187, 1330, 5550, 6489, 21414, 10979, 62, 47, 31688, 10426, 11, 5550, 6489, 21414, 10979, 62, 31553, 1797, 40405, 198, 6738, ...
2.971193
243
import numpy as np from ..tools import batchGenerator # LOGISTIC REGRESSION # for (binary) categorical data
[ 11748, 299, 32152, 355, 45941, 198, 6738, 11485, 31391, 1330, 15458, 8645, 1352, 198, 198, 2, 41605, 8808, 2149, 4526, 10761, 47621, 198, 2, 329, 357, 39491, 8, 4253, 12409, 1366, 198 ]
3.40625
32
bits = '110' #print(str(valore)) print(turnBitsIntoInteger(bits))
[ 9895, 796, 705, 11442, 6, 628, 198, 220, 220, 220, 198, 2, 4798, 7, 2536, 7, 2100, 382, 4008, 198, 198, 4798, 7, 15344, 33, 896, 5317, 78, 46541, 7, 9895, 4008, 628, 628, 628, 628, 628, 628, 628, 628, 628, 628, 628, 628, 628, ...
2.009511
736
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- # pylint: disable=line-too-long # pylint: disable=too-many-statements # pylint: disable=too-many-lines # pylint: disable=too-many-locals # pylint: disable=unused-argument import json # module equivalent: azure_rm_openshiftmanagedcluster # URL: /subscriptions/{{ subscription_id }}/resourceGroups/{{ resource_group }}/providers/Microsoft.ContainerService/openShiftManagedClusters/{{ open_shift_managed_cluster_name }} # module equivalent: azure_rm_openshiftmanagedcluster # URL: /subscriptions/{{ subscription_id }}/resourceGroups/{{ resource_group }}/providers/Microsoft.ContainerService/openShiftManagedClusters/{{ open_shift_managed_cluster_name }} # module equivalent: azure_rm_openshiftmanagedcluster # URL: /subscriptions/{{ subscription_id }}/resourceGroups/{{ resource_group }}/providers/Microsoft.ContainerService/openShiftManagedClusters/{{ open_shift_managed_cluster_name }}
[ 2, 16529, 1783, 10541, 201, 198, 2, 15069, 357, 66, 8, 5413, 10501, 13, 1439, 2489, 10395, 13, 201, 198, 2, 49962, 739, 262, 17168, 13789, 13, 4091, 13789, 13, 14116, 287, 262, 1628, 6808, 329, 5964, 1321, 13, 201, 198, 2, 16529, ...
3.673469
343
# coding: utf-8 from random import randint from urllib.parse import parse_qs import socket import sys import json import traceback import os import base64 import yaml import datetime import requests import re route = Route() def notFound(conn, request): if "/api" in request.header["path"]: notFoundJson(conn) status = "404 Not Found" c_type = "text/plain; charset=UTF-8" msgErr = renderMessage(status, str(len(status)), None, None, c_type, status) writeResponse(conn, msgErr) def notImplemented(conn, request): status = "501 Not Implemented" c_type = "text/plain; charset=UTF-8" msgErr = renderMessage(status, str(len(status)), None, None, c_type, status) writeResponse(conn, msgErr) def badRequest(conn, request): if "/api" in request.header["path"]: badRequestJson(conn, "Please use proper http version") status = "400 Bad Request" c_type = "text/plain; charset=UTF-8" msgErr = renderMessage(status, str(len(status)), None, None, c_type, status) writeResponse(conn, msgErr) def getTime(t_raw): t = datetime.datetime.strptime(t_raw, "%Y-%m-%d %H:%M:%S") return t.strftime("%Y-%m-%dT%H:%M:%S.%fZ") def getCounter(): with open('counter.json', 'r') as json_file: data = json.load(json_file) return data["count"] def writeCounter(c): count = {"count": c} with open('counter.json', 'w') as json_file: data = json.dump(count, json_file) def getApiVersion(): with open('./spesifikasi.yaml', 'r') as f: doc = yaml.load(f) return doc["info"]["version"] def notFoundJson(conn): detail = "The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again." status = "404" title = "Not Found" json_http_error(conn, detail, status, title) def methodNotAllowedJson(conn, d): detail = d status = "405" title = "Method Not Allowed" json_http_error(conn, detail, status, title) def badRequestJson(conn, d): detail = d status = "400" title = "Bad Request" json_http_error(conn, detail, status, title) def json_http_ok(conn, **kwargs): res_dict = {'apiversion': getApiVersion()} for key, value in kwargs.items(): res_dict[key] = value data = json.dumps(res_dict) # Build Response status = "200 OK" c_type = "application/json; charset=UTF-8" msgErr = renderMessage(status, str(len(data)), None, None, c_type, data) writeResponse(conn, msgErr) def json_http_error(conn, detail, status, title): res_dict = {'detail': detail, 'status': status, 'title': title} data = json.dumps(res_dict) status = "{} {}".format(status, title) c_type = "application/json; charset=UTF-8" msgErr = renderMessage(status, str(len(data)), None, None, c_type, data) writeResponse(conn, msgErr) def main(): # HOST = socket.gethostbyname(socket.gethostname()) HOST = "0.0.0.0" PORT = int(sys.argv[1]) #Get method route.route("GET", "/", getRoot) route.route("GET", "/hello-world", getHelloWorld) route.route("GET", "/style", getStyle) route.route("GET", "/background", getBackground) route.route("GET", "/info", getInfo) route.route("GET", "/api/hello", helloAPI) route.route("GET", "/api/plusone/<:digit>", plusOneAPI) route.route("GET", "/api/spesifikasi.yaml", getSpesifikasi) #Post Method route.route("POST", "/api/hello", helloAPI) route.route("POST", "/hello-world", postHelloWorld) # PUT route.route("PUT", "/api/hello", helloAPI) #PATCH route.route("PATCH", "/api/hello", helloAPI) #DELETE route.route("DELETE", "/api/hello", helloAPI) #HEAD route.route("HEAD", "/api/hello", helloAPI) # Serve the connection connect(HOST, PORT) def handler(conn, req): try: debugger = "=== Got Request ===\n{}\n===Got Header====\n{}\n".format(req._raw_request, req.header) print(debugger) route.dispatch(cleanURL(req.header["path"]), req.header["method"])(conn, req) except TypeError as e: print(traceback.format_exc()) if route.findPath(cleanURL(req.header["path"])): notImplemented(conn, req) return notFound(conn, req) return def cleanURL(url): return url.split("?")[0] main()
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 198, 6738, 4738, 1330, 43720, 600, 198, 6738, 2956, 297, 571, 13, 29572, 1330, 21136, 62, 48382, 198, 198, 11748, 17802, 198, 11748, 25064, 198, 11748, 33918, 198, 11748, 12854, 1891, 198, 11748, 2...
2.446558
1,787
from PyQt5.QtWidgets import QTabWidget from glia.widgets.editor import Editor
[ 6738, 9485, 48, 83, 20, 13, 48, 83, 54, 312, 11407, 1330, 1195, 33349, 38300, 198, 198, 6738, 1278, 544, 13, 28029, 11407, 13, 35352, 1330, 12058, 628 ]
2.857143
28
""" Test Driven Development. """ import pytest
[ 37811, 6208, 5809, 574, 7712, 13, 37227, 198, 11748, 12972, 9288, 628, 628, 628, 628, 628, 628 ]
3.411765
17
#!/usr/bin/python # -*- coding: UTF-8 -*- # pylint: disable=E1601 """ 17/02/2018 Profesores: lvaro Snchez de Cruz / ??? - Se hace un repaso de lo que se imparti el da anterior. - Subprogramas o funciones: - Viene de la programacin estructurada. - Sintaxis: def nombreFuncion([parametro1,][parametro2,]...) (codigo de la funcion) [return valor] Los valores se pasan siempre por valor a las funciones. Ahora vamos a ver un ejemplo: def saludo() print "Hola Mundo" - Se explican los ejercicios propuestos del da 1. - Ficheros var = open('ruta al fichero','a'|'r'|'w') - JSON Es un formato de datos originario de JavaScript, que hablando en terminologia de python es una lista de diccionarios, de la siguiente forma: [ {},{},... ] En python los JSON se pueden pasar a un diccionario muy facilmente. """ # modo 'r' read, que lee el fichero si existe y si no dara un error # modo 'a' append, que aade al fichero si existe y si no lo crea # modo 'w' write, que escribe en el fichero si existe, sobreescribiendo lo que tuviera, y si no lo crea. leerFichero() sobreescribirFichero() leerEscribirFichero()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 2, 532, 9, 12, 19617, 25, 41002, 12, 23, 532, 9, 12, 198, 2, 279, 2645, 600, 25, 15560, 28, 36, 1433, 486, 198, 37811, 198, 1596, 14, 2999, 14, 7908, 198, 220, 220, 4415, 274, 2850, 2...
2.208696
575
import logging import requests import json import azure.functions as func dapr_url = "http://localhost:3500/v1.0"
[ 11748, 18931, 198, 198, 11748, 7007, 198, 11748, 33918, 198, 11748, 35560, 495, 13, 12543, 2733, 355, 25439, 198, 198, 67, 499, 81, 62, 6371, 796, 366, 4023, 1378, 36750, 25, 2327, 405, 14, 85, 16, 13, 15, 1, 198 ]
2.9
40
import os import json from logging import config name = os.path.splitext(__file__)[0] json_filename = os.path.join(os.path.dirname(__file__), f'{name}.json') with open(json_filename) as fh: config.dictConfig(json.load(fh))
[ 11748, 28686, 198, 11748, 33918, 198, 6738, 18931, 1330, 4566, 628, 198, 3672, 796, 28686, 13, 6978, 13, 22018, 578, 742, 7, 834, 7753, 834, 38381, 15, 60, 198, 17752, 62, 34345, 796, 28686, 13, 6978, 13, 22179, 7, 418, 13, 6978, 13...
2.241379
116
import responses from tamr_unify_client import Client from tamr_unify_client.auth import UsernamePasswordAuth
[ 11748, 9109, 198, 198, 6738, 21885, 81, 62, 403, 1958, 62, 16366, 1330, 20985, 198, 6738, 21885, 81, 62, 403, 1958, 62, 16366, 13, 18439, 1330, 50069, 35215, 30515, 628 ]
3.733333
30
import warnings warnings.simplefilter("ignore", category=FutureWarning) from skbio import TabularMSA from skbio.sequence import GrammaredSequence from io import StringIO, IOBase from shutil import copyfileobj import copy import numpy as np from pmaf.internal.io._seq import SequenceIO from pmaf.sequence._sequence._nucleotide import Nucleotide from pmaf.sequence._metakit import MultiSequenceMetabase, NucleotideMetabase from pmaf.sequence._shared import validate_seq_mode from typing import Union, Optional, Any, Sequence, Generator from pmaf.internal._typing import AnyGenericIdentifier
[ 11748, 14601, 198, 198, 40539, 654, 13, 36439, 24455, 7203, 46430, 1600, 6536, 28, 29783, 20361, 8, 198, 6738, 1341, 65, 952, 1330, 16904, 934, 44, 4090, 198, 6738, 1341, 65, 952, 13, 43167, 1330, 20159, 76, 1144, 44015, 594, 198, 673...
3.69375
160
if __name__ == '__main__': a = ArvoreDerivacao('a') b = ArvoreDerivacao('b') A = ArvoreDerivacao('A', a) B = ArvoreDerivacao('B', b) S = ArvoreDerivacao('S', A, B) S.print_arvore()
[ 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 257, 796, 943, 85, 382, 28532, 452, 330, 5488, 10786, 64, 11537, 198, 220, 220, 220, 275, 796, 943, 85, 382, 28532, 452, 330, 5488, 10786, 65, 11537,...
1.839286
112
import re import sys from operator import add from pyspark.sql import SparkSession if __name__ == "__main__": if len(sys.argv) != 3: print("Usage: pagerank <file> <iterations>", file=sys.stderr) sys.exit(-1) print("WARN: This is a naive implementation of PageRank and is given as an example!\n" + "Please refer to PageRank implementation provided by graphx", file=sys.stderr) # Initialize the spark context. spark = SparkSession\ .builder\ .appName("PythonPageRank")\ .getOrCreate() # Loads in input file. It should be in format of: # URL neighbor URL # URL neighbor URL # URL neighbor URL # ... lines = spark.read.text(sys.argv[1]).rdd.map(lambda r: r[0]) print("ALL LINKS",lines.collect()) links = lines.flatMap(lambda urls: parseNeighbors(urls)).distinct().groupByKey().cache() print("ALL LINKS",links.collect())
[ 11748, 302, 198, 11748, 25064, 198, 6738, 10088, 1330, 751, 198, 198, 6738, 279, 893, 20928, 13, 25410, 1330, 17732, 36044, 628, 628, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 611, 18896, 7, 175...
2.433915
401
from __future__ import absolute_import, unicode_literals from django.conf import settings from django.templatetags.static import static from django.utils.html import format_html from django.utils.module_loading import import_string from wagtail.core import hooks
[ 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 11, 28000, 1098, 62, 17201, 874, 198, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 6738, 42625, 14208, 13, 11498, 489, 265, 316, 3775, 13, 12708, 1330, 9037, 198, 6738, 42625, 1420...
3.573333
75
# Copyright 2009-2010 Yelp # Copyright 2013 David Marin # Copyright 2014 Disco Project # # 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. """ Iterative implementation of the PageRank algorithm: This example has been ported from the mrjob project. http://en.wikipedia.org/wiki/PageRank The format of the input should be of the form: node_id initial_score neighbor_1 weight_1 neighbor_2 weight_2 ... For example, the following input is derieved from wikipedia: $ cat input 0 1 1 1 2 1 2 1 1 1 3 1 0 0.5 1 0.5 4 1 1 0.33 3 0.33 5 0.33 5 1 1 0.5 4 0.5 6 1 1 0.5 4 0.5 7 1 1 0.5 4 0.5 8 1 1 0.5 4 0.5 9 1 4 1 10 1 4 1 $ cat input | ddfs chunk pages - $ python page_rank.py --iterations 10 pages The results are: 0 : 0.303085470793 1 : 3.32372143585 2 : 3.39335760361 3 : 0.360345571947 4 : 0.749335470793 5 : 0.360345571947 6 : 0.15 7 : 0.15 8 : 0.15 9 : 0.15 10 : 0.15 """ from optparse import OptionParser from disco.core import Job, result_iterator from disco.worker.classic.worker import Params from disco.worker.task_io import chain_reader if __name__ == '__main__': parser = OptionParser(usage='%prog [options] inputs') parser.add_option('--iterations', default=10, help='Numbers of iteration') parser.add_option('--damping-factor', default=0.85, help='probability a web surfer will continue clicking on links') (options, input) = parser.parse_args() results = input params = Params(damping_factor=float(options.damping_factor)) for j in range(int(options.iterations)): job = Job().run(input=results, map=send_score, map_reader = chain_reader, reduce=receive_score, params = params) results = job.wait() for _, node in result_iterator(results): fields = node.split() print fields[0], ":", fields[1]
[ 2, 15069, 3717, 12, 10333, 44628, 198, 2, 15069, 2211, 3271, 36384, 198, 2, 15069, 1946, 19718, 4935, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, ...
2.739837
861
""" restapi - base for calling rest resources Stackdriver Public API, Copyright Stackdriver 2014 Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import requests import copy import types import json import logging logger = logging.getLogger(__name__) def transport_func(func): """ Decorates each of the transport functions that can get wrapped by a transport_controller """ func._is_transport_func = True return func
[ 37811, 198, 2118, 15042, 532, 2779, 329, 4585, 1334, 4133, 198, 198, 25896, 26230, 5094, 7824, 11, 15069, 23881, 26230, 1946, 198, 198, 26656, 15385, 284, 262, 24843, 10442, 5693, 357, 1921, 37, 8, 739, 530, 198, 273, 517, 18920, 5964, ...
4.003497
286
# -*- coding: utf-8 -*- """ Created on Wed Dec 11 15:05:41 2019 @author: jrodriguez119 """ import tkinter as tk from tkinter import ttk import crearcapas import perceptron_multicapa from threading import Thread import sys from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk from matplotlib.figure import Figure from tkinter import filedialog as fd from tkinter import messagebox as mb import menu import sklearn #Funcin que genera la ventana de parmetros del Perceptron multicapa def Ventana_perceptron(ventana_seleccion,X_train,Y_train,X_test,Y_test,ventana_inicio): #Crear ventana ventana_perceptron = tk.Toplevel(ventana_seleccion) ventana_perceptron.geometry('725x600+500+200') #Insertar menu menu.menu(ventana_perceptron,ventana_inicio) #Esconder ventana previa ventana_seleccion.withdraw() #Ttulo labeltitulo = ttk.Label(ventana_perceptron,text = "Parmetros necesarios para el Perceptrn", foreground = "#054FAA",font=("Arial Bold", 15)) labeltitulo.pack(pady=10) #Frame donde alojar los widget de entrada lframe = ttk.Frame(ventana_perceptron) lframe.pack() #------------------------ entrada de datos --------------------------------- #Tamao de lote tamlot = tk.IntVar() lbtamlote = ttk.Label(lframe,text = "Tamao lote: ", foreground = "#054FAA",font=("Arial Bold", 12)) lbtamlote.grid(column=0, row=0 ,pady=5,sticky=tk.W) etamlot = ttk.Entry(lframe,width=5, textvariable = tamlot) etamlot.grid(column=1, row=0,pady=5,sticky=tk.E) #Optimizador opt =tk.StringVar() lbopt = ttk.Label(lframe, text="Optimizador: ", foreground = "#054FAA",font=("Arial Bold", 12)) lbopt.grid(column=0, row=1,pady=5,sticky=tk.W) cbopt=ttk.Combobox(lframe,width=9,state="readonly",textvariable = opt) cbopt["values"] = ["SGD", "RMSProp","Adam","Adagrad"] cbopt.grid(column = 1 ,row = 1,pady=5,columnspan=2) cbopt.current(0) #Proporcin de validacin pv = tk.DoubleVar() pv.set(0.2) lbpv = ttk.Label(lframe,text = "Proporcin de Validacin :", foreground = "#054FAA",font=("Arial Bold", 12)) lbpv.grid(column=0, row=2 ,pady=5,sticky=tk.W) epv = ttk.Entry(lframe,width=5, textvariable = pv) epv.grid(column=1, row=2,pady=5,sticky=tk.E) #Nmero de capas ocultas nco = tk.IntVar() lbnco = ttk.Label(lframe,text = "Nmero capas ocultas :", foreground = "#054FAA",font=("Arial Bold", 12)) lbnco.grid(column=0, row=3 ,pady=5,sticky=tk.W) enco = ttk.Entry(lframe,width=5, textvariable = nco) enco.grid(column=1, row=3,pady=5,sticky=tk.E) #Funcin Loss fl =tk.StringVar() lbfl = ttk.Label(lframe, text="Funcin Loss: ", foreground = "#054FAA",font=("Arial Bold", 12)) lbfl.grid(column=0, row=4,pady=5,sticky=tk.W) cbfl=ttk.Combobox(lframe,width=21,state="readonly",textvariable = fl) cbfl["values"] = ["kullback_leibler_divergence","mean_squared_error", "categorical_hinge", "categorical_crossentropy","binary_crossentropy","poisson","cosine_proximity"] cbfl.grid(column = 1 ,row = 4,pady=5,columnspan=2,sticky=tk.E) cbfl.current(3) #Mtodo de parada labeltitulo1 = ttk.Label(ventana_perceptron,text = "Mtodo de parada", foreground = "#054FAA",font=("Arial Bold", 15)) labeltitulo1.pack(pady=10) lframe1 = ttk.Frame(ventana_perceptron) lframe1.pack() #Tipo de parada #Parada por nmero de iteraciones mp=tk.IntVar() bat1= ttk.Radiobutton(lframe1, value=0,variable=mp) bat1.grid(column=0, row=0) nui=tk.IntVar() lbnui = ttk.Label(lframe1, text="Nmero de iteraciones: ", foreground = "#054FAA",font=("Arial Bold", 12)) lbnui.grid(column=1, row=0,pady=5,sticky=tk.W) enui = ttk.Entry(lframe1,width=5, textvariable = nui) enui.grid(column=2, row=0,pady=5,sticky=tk.E) #Parada por control de un parmetro bat2 = ttk.Radiobutton(lframe1, value=1,variable=mp) bat2.grid(column=0, row=1) lbparada = ttk.Label(lframe1, text="Parada temprana: ", foreground = "#054FAA",font=("Arial Bold", 12)) lbparada.grid(column = 1, row = 1,sticky=tk.W ) #Parmetro a controlar lbcon = ttk.Label(lframe1, text=" Parmetro a controlar: ", foreground = "#054FAA",font=("Arial Bold", 12)) lbcon.grid(column = 1, row = 2,pady=5,sticky=tk.W ) con =tk.StringVar() cbcon=ttk.Combobox(lframe1,width=9,state="readonly",textvariable = con) cbcon["values"] = ["loss","val_loss", "acc","val_acc"] cbcon.grid(column = 2 ,row = 2,pady=5,sticky=tk.E) cbcon.current(0) #Delta mnima de evolucin delt =tk.DoubleVar() delt.set(0.001) lbdelt = ttk.Label(lframe1, text=" Delta min: ", foreground = "#054FAA",font=("Arial Bold", 12)) lbdelt.grid(column=1, row=3,pady=5,sticky=tk.W) edelt = ttk.Entry(lframe1,width=5, textvariable = delt) edelt.grid(column=2, row=3,pady=5,sticky=tk.E) #Paciencia para realizar la parada pat =tk.IntVar() pat.set(3) lbpat = ttk.Label(lframe1, text=" Paciencia: ", foreground = "#054FAA",font=("Arial Bold", 12)) lbpat.grid(column=1, row=4,pady=5,sticky=tk.W) epat = ttk.Entry(lframe1,width=5, textvariable = pat) epat.grid(column=2, row=4,pady=5,sticky=tk.E) #Funcin que abre una ventana externa y nos permite crear nuestro modelo editando las capas ocultas btnmodelo = ttk.Button(ventana_perceptron, text = "Crear modelo",style='my.TButton', command=crearmodelo) btnmodelo.pack(pady=50) lframe2 = ttk.Frame(ventana_perceptron) lframe2.pack(side= "bottom") btntrain = ttk.Button(lframe2, text = "Entrenar",style='my.TButton', command=entrenar) btntrain.grid(row = 0, column = 1, padx = 20, pady=15) btnatras = ttk.Button(lframe2, text = "Atras",style='my.TButton', command=atras) btnatras.grid(row=0,column=0, padx = 20, pady=15)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 201, 198, 37811, 201, 198, 41972, 319, 3300, 4280, 1367, 1315, 25, 2713, 25, 3901, 13130, 201, 198, 201, 198, 31, 9800, 25, 474, 14892, 4359, 14870, 16315, 201, 198, 37811, ...
2.005917
3,211
from tests.graph_case import GraphTestCase
[ 6738, 5254, 13, 34960, 62, 7442, 1330, 29681, 14402, 20448, 628, 198 ]
3.75
12
import requests from ..base.test import BaseTestCase, AuthorizedTestCase import uuid import common
[ 11748, 7007, 201, 198, 6738, 11485, 8692, 13, 9288, 1330, 7308, 14402, 20448, 11, 6434, 1143, 14402, 20448, 201, 198, 11748, 334, 27112, 201, 198, 11748, 2219, 201 ]
3.642857
28
""" Define a command that should be run from a crontab. This one should check consistency of Meldungen: at most one Meldung per Aufgabe, per User. """ from django.core.management.base import BaseCommand, CommandError from django.core.management import call_command from django.utils import translation from django.conf import settings from django.core.mail import send_mail import arbeitsplan.models as models import datetime import pprint from collections import defaultdict
[ 37811, 198, 7469, 500, 257, 3141, 326, 815, 307, 1057, 422, 257, 1067, 756, 397, 13, 198, 1212, 530, 815, 2198, 15794, 286, 2185, 335, 2150, 268, 25, 198, 265, 749, 530, 2185, 335, 2150, 583, 317, 3046, 70, 11231, 11, 583, 11787, ...
3.62406
133
# Generated by Django 2.1.15 on 2020-09-07 10:56 import app.models from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 362, 13, 16, 13, 1314, 319, 12131, 12, 2931, 12, 2998, 838, 25, 3980, 198, 198, 11748, 598, 13, 27530, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
2.972973
37
# coding: utf-8 """ API's OpenData do Open Banking Brasil As API's descritas neste documento so referentes as API's da fase OpenData do Open Banking Brasil. # noqa: E501 OpenAPI spec version: 1.0.0-rc5.2 Contact: apiteam@swagger.io Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, MonthlyPrice): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 198, 37811, 198, 220, 220, 220, 7824, 338, 4946, 6601, 466, 4946, 35385, 39452, 346, 628, 220, 220, 220, 1081, 7824, 338, 1715, 799, 292, 16343, 68, 3188, 78, 523, 6773, 429, 274, 355, 7824, 33...
2.535714
364
import sqlalchemy as sa from sqlalchemy.ext.compiler import compiles from sqlalchemy.sql.functions import GenericFunction
[ 11748, 44161, 282, 26599, 355, 473, 198, 6738, 44161, 282, 26599, 13, 2302, 13, 5589, 5329, 1330, 552, 2915, 198, 6738, 44161, 282, 26599, 13, 25410, 13, 12543, 2733, 1330, 42044, 22203, 628, 198 ]
3.647059
34
# 101050010 sm.warp(101050000, 7) sm.dispose()
[ 2, 8949, 2713, 37187, 198, 5796, 13, 86, 5117, 7, 8784, 2713, 2388, 11, 767, 8, 198, 5796, 13, 6381, 3455, 3419, 198 ]
2.043478
23
from suppy.utils.stats_constants import DIVERGENCE, TYPE from typing import Any, Dict from suppy.simulator.atomics.atomic import Atomic
[ 6738, 802, 88, 13, 26791, 13, 34242, 62, 9979, 1187, 1330, 360, 38757, 38, 18310, 11, 41876, 198, 6738, 19720, 1330, 4377, 11, 360, 713, 198, 6738, 802, 88, 13, 14323, 8927, 13, 265, 31994, 13, 47116, 1330, 28976, 198 ]
3.4
40
import logging from .lib.init_helper import init_logging, load_modules # Initialize logging format before loading all other modules logger = init_logging(logging.INFO) import argparse from .lib import pytorch as lib_pytorch from .lib.config import BenchmarkConfig from .lib.pytorch.benchmark import ( make_default_benchmark, ExecutionPass, get_benchmark_options, ) from .workloads import pytorch as workloads_pytorch if __name__ == "__main__": main()
[ 11748, 18931, 198, 198, 6738, 764, 8019, 13, 15003, 62, 2978, 525, 1330, 2315, 62, 6404, 2667, 11, 3440, 62, 18170, 198, 198, 2, 20768, 1096, 18931, 5794, 878, 11046, 477, 584, 13103, 198, 6404, 1362, 796, 2315, 62, 6404, 2667, 7, 6...
3.019108
157
from sqlalchemy import create_engine from sqlalchemy import Column, Integer, Boolean, String, DateTime, ForeignKey from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.dialects.postgresql import JSONB from sqlalchemy.orm import sessionmaker from sqlalchemy.sql import func import datetime import os import json database = { 'pg_user': os.environ['SCOREBOARD_PG_USERNAME'], 'pg_pass': os.environ['SCOREBOARD_PG_PASSWORD'], 'pg_host': os.environ.get('SCOREBOARD_PG_HOST', 'localhost'), 'pg_port': os.environ.get('SCOREBOARD_PG_PORT', 5432), 'pg_database': os.environ.get('SCOREBOARD_PG_DATABASE', 'scoreboard') } # Build database engine = create_engine( "postgresql://{pg_user}:{pg_pass}@{pg_host}:{pg_port}/{pg_database}".format(**database)) Base = declarative_base() Base.metadata.create_all(engine) # Load Data Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) session = DBSession() with open("initialize.json") as fh: initialize_data = json.load(fh) for challenge in initialize_data["challenges"]: datasets = challenge.pop('datasets', []) new_challenge = Challenge(**challenge) session.add(new_challenge) session.flush() session.refresh(new_challenge) challenge_id = new_challenge.id for dataset in datasets: dataset["challenge_id"] = challenge_id new_dataset = Dataset(**dataset) session.add(new_dataset) for admin in initialize_data["admins"]: new_user = User(github_username=admin, is_admin=True) session.add(new_user) email_settings = initialize_data["email_settings"] settings = AdminEmailSettings(email_provider=email_settings["email_provider"], email_address= email_settings["admin_email"], email_pass=email_settings["admin_pass"]) session.add(settings) session.commit()
[ 6738, 44161, 282, 26599, 1330, 2251, 62, 18392, 198, 6738, 44161, 282, 26599, 1330, 29201, 11, 34142, 11, 41146, 11, 10903, 11, 7536, 7575, 11, 8708, 9218, 198, 6738, 44161, 282, 26599, 13, 2302, 13, 32446, 283, 876, 1330, 2377, 283, ...
2.616134
719
# Need at least 20 # characters """ =============== Generate Images =============== This ipython notebook demonstrates how to generate an image dataset with rich ground truth from a virtual environment. """ #################### import time; print(time.strftime("The last update of this file: %Y-%m-%d %H:%M:%S", time.gmtime())) #################### # Load some python libraries # The dependencies for this tutorials are # PIL, Numpy, Matplotlib from __future__ import division, absolute_import, print_function import os, sys, time, re, json import numpy as np import matplotlib.pyplot as plt imread = plt.imread def imread8(im_file): ''' Read image as a 8-bit numpy array ''' im = np.asarray(Image.open(im_file)) return im ############################### # Connect to the game # =================== # Load unrealcv python client, do :code:`pip install unrealcv` first. from unrealcv import client client.connect() if not client.isconnected(): print('UnrealCV server is not running. Run the game downloaded from http://unrealcv.github.io first.') sys.exit(-1) ############################### # Make sure the connection works well res = client.request('vget /unrealcv/status') # The image resolution and port is configured in the config file. print(res) ############################## # Load a camera trajectory # ======================== traj_file = './camera_traj.json' # Relative to this python script import json; camera_trajectory = json.load(open(traj_file)) # We will show how to record a camera trajectory in another tutorial ############################## # Render an image # =============== idx = 1 loc, rot = camera_trajectory[idx] # Set position of the first camera client.request('vset /camera/0/location {x} {y} {z}'.format(**loc)) client.request('vset /camera/0/rotation {pitch} {yaw} {roll}'.format(**rot)) # Get image res = client.request('vget /camera/0/lit lit.png') print('The image is saved to %s' % res) # It is also possible to get the png directly without saving to a file res = client.request('vget /camera/0/lit png') im = read_png(res) print(im.shape) # Visualize the image we just captured plt.imshow(im) ############################## # Ground truth generation # ======================= # Generate ground truth from this virtual scene res = client.request('vget /camera/0/object_mask png') object_mask = read_png(res) res = client.request('vget /camera/0/normal png') normal = read_png(res) # Visualize the captured ground truth plt.imshow(object_mask) plt.figure() plt.imshow(normal) ############################### # Depth is retrieved as a numpy array # For UnrealCV < v0.3.8, the depth is saved as an exr file, but this has two issues. 1. Exr is not well supported in Linux 2. It depends on OpenCV to read exr file, which is hard to install res = client.request('vget /camera/0/depth npy') depth = read_npy(res) plt.imshow(depth) ############################## # Get object information # ====================== # List all the objects of this virtual scene scene_objects = client.request('vget /objects').split(' ') print('Number of objects in this scene:', len(scene_objects)) # TODO: replace this with a better implementation id2color = {} # Map from object id to the labeling color for obj_id in scene_objects: color = Color(client.request('vget /object/%s/color' % obj_id)) id2color[obj_id] = color # print('%s : %s' % (obj_id, str(color))) ############################# # Parse the segmentation mask id2mask = {} for obj_id in scene_objects: color = id2color[obj_id] mask = match_color(object_mask, [color.R, color.G, color.B], tolerance = 3) if mask is not None: id2mask[obj_id] = mask # This may take a while # TODO: Need to find a faster implementation for this ############################## # Print statistics of this virtual scene and this image # ===================================================== # Load information of this scene with open('object_category.json') as f: id2category = json.load(f) categories = set(id2category.values()) # Show statistics of this frame image_objects = id2mask.keys() print('Number of objects in this image:', len(image_objects)) print('%20s : %s' % ('Category name', 'Object name')) for category in categories: objects = [v for v in image_objects if id2category.get(v) == category] if len(objects) > 6: # Trim the list if too long objects[6:] = ['...'] if len(objects) != 0: print('%20s : %s' % (category, objects)) ############################## # Show the annotation color of some objects ids = ['SM_Couch_1seat_5', 'SM_Vase_17', 'SM_Shelving_6', 'SM_Plant_8'] # for obj_id in ids: obj_id = ids[0] color = id2color[obj_id] print('%s : %s' % (obj_id, str(color))) # color_block = np.zeros((100,100, 3)) + np.array([color.R, color.G, color.B]) / 255.0 # plt.figure(); plt.imshow(color_block); plt.title(obj_id) ############################## # Plot only one object mask = id2mask['SM_Plant_8'] plt.figure(); plt.imshow(mask) ############################## # Show all sofas in this image couch_instance = [v for v in image_objects if id2category.get(v) == 'Couch'] mask = sum(id2mask[v] for v in couch_instance) plt.figure(); plt.imshow(mask) ############################## # Change the annotation color, fixed in v0.3.9 # You can use this to make objects you don't care the same color client.request('vset /object/SM_Couch_1seat_5/color 255 0 0') # Change to pure red client.request('vget /object/SM_Couch_1seat_5/color') res = client.request('vget /camera/0/object_mask png') object_mask = read_png(res) plt.imshow(object_mask) ############################## # Clean up resources # ================== client.disconnect()
[ 2, 10664, 379, 1551, 1160, 1303, 3435, 198, 37811, 198, 25609, 18604, 198, 8645, 378, 5382, 198, 25609, 18604, 198, 198, 1212, 20966, 7535, 20922, 15687, 703, 284, 7716, 281, 2939, 27039, 351, 5527, 198, 2833, 3872, 422, 257, 7166, 2858...
3.117968
1,831
# -*- coding: utf-8 -*- # Generated by Django 1.10 on 2016-10-06 08:54 from __future__ import unicode_literals from django.db import migrations, models
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2980, 515, 416, 37770, 352, 13, 940, 319, 1584, 12, 940, 12, 3312, 8487, 25, 4051, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 198, 6738, ...
2.8
55
""" Summary: Example use of the fmp package to update file paths in an .ief file and save the ief file under a new name. Author: Duncan Runnacles Created: 01 Apr 2016 Copyright: Duncan Runnacles 2016 TODO: Updates: """ import os from ship.utils.fileloaders import fileloader as fl # Contains functions for updating file paths and reading/writing files from ship.utils import filetools def iefExample(): """update some key file paths in an ief file. Updates the .dat file, .tcf file, and results file paths referenced by the ief file and save it under a new ief file name. """ # Load the tuflow model with a tcf file ief_file = r'C:\path\to\an\isis\ieffile.ief' loader = fl.FileLoader() ief = loader.loadFile(ief_file) # Get the referenced fmp .dat and .tcf files dat_path = ief.getValue('Datafile') tcf_path = ief.getValue('2DFile') results_path = ief.getValue('Results') # Update the dat, results and tcf file names root, ext = os.path.splitext(dat_path) new_dat = root + '_Updated' + ext root, ext = os.path.splitext(results_path) new_results = root + '_Updated' + ext root, ext = os.path.splitext(tcf_path) new_tcf = root + '_Updated' + ext ief.setValue('Datafile', new_dat) ief.setValue('Results', new_results) ief.setValue('2DFile', new_tcf) # Update the filename and write contents to disk ief.path_holder.filename += '_Updated' ief_path = ief.path_holder.absolutePath() ief.write(ief_path) if __name__ == '__main__': iefExample()
[ 37811, 198, 220, 220, 220, 21293, 25, 198, 220, 220, 220, 220, 220, 220, 220, 17934, 779, 286, 262, 277, 3149, 5301, 284, 4296, 2393, 13532, 287, 281, 764, 2086, 2393, 198, 220, 220, 220, 220, 220, 220, 220, 290, 3613, 262, 220, 2...
2.488756
667
""" HTTPRequest.py Copyright 2010 Andres Riancho This file is part of w3af, http://w3af.org/ . w3af 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 version 2 of the License. w3af 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 w3af; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA """ import copy import socket import urllib2 from w3af.core.data.dc.headers import Headers from w3af.core.data.dc.utils.token import DataToken from w3af.core.data.parsers.doc.url import URL from w3af.core.data.request.request_mixin import RequestMixIn from w3af.core.data.url.constants import MAX_HTTP_RETRIES
[ 37811, 198, 40717, 18453, 13, 9078, 198, 198, 15269, 3050, 843, 411, 371, 666, 6679, 198, 198, 1212, 2393, 318, 636, 286, 266, 18, 1878, 11, 2638, 1378, 86, 18, 1878, 13, 2398, 14, 764, 198, 198, 86, 18, 1878, 318, 1479, 3788, 26,...
3.356436
303
#!/usr/bin/env python from __future__ import print_function import sys, os from nbformat import v4 if __name__ == '__main__': with open(sys.argv[1], 'r') as nbfile: nb = v4.reads(nbfile.read()) print('Contents\n=======\n---') for cell in nb.cells: if cell['cell_type'] == 'markdown': for line in cell['source'].splitlines(): header = parse_line(line) if header is None: continue ilevel, name = header print(' '*(ilevel-1) + ' - [%s](#%s)'%(name, name.replace(' ','-')))
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 11748, 25064, 11, 28686, 198, 6738, 299, 65, 18982, 1330, 410, 19, 628, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834,...
2.103571
280
from rest_framework import serializers
[ 6738, 1334, 62, 30604, 1330, 11389, 11341 ]
5.428571
7
import numpy as np
[ 11748, 299, 32152, 355, 45941, 628, 198 ]
3
7
import pytest from persine import Persona from selenium import webdriver from selenium.webdriver.chrome.options import Options from unittest.mock import Mock
[ 11748, 12972, 9288, 198, 198, 6738, 2774, 500, 1330, 41581, 198, 6738, 384, 11925, 1505, 1330, 3992, 26230, 198, 6738, 384, 11925, 1505, 13, 12384, 26230, 13, 46659, 13, 25811, 1330, 18634, 198, 6738, 555, 715, 395, 13, 76, 735, 1330, ...
3.622222
45
import torch import numpy as np import cv2 import os import h5py from collections import defaultdict from mvn.models.triangulation import RANSACTriangulationNet, AlgebraicTriangulationNet, VolumetricTriangulationNet from mvn.models.loss import KeypointsMSELoss, KeypointsMSESmoothLoss, KeypointsMAELoss, KeypointsL2Loss, VolumetricCELoss from mvn.utils import img, multiview, op, vis, misc, cfg from mvn.utils.img import get_square_bbox, resize_image, crop_image, normalize_image, scale_bbox from mvn.utils.multiview import Camera from mvn.utils.multiview import project_3d_points_to_image_plane_without_distortion as project from mvn.datasets import utils as dataset_utils from mvn.utils.img import image_batch_to_torch retval = { 'subject_names': ['S1', 'S5', 'S6', 'S7', 'S8', 'S9', 'S11'], 'camera_names': ['54138969', '55011271', '58860488', '60457274'], 'action_names': [ 'Directions-1', 'Directions-2', 'Discussion-1', 'Discussion-2', 'Eating-1', 'Eating-2', 'Greeting-1', 'Greeting-2', 'Phoning-1', 'Phoning-2', 'Posing-1', 'Posing-2', 'Purchases-1', 'Purchases-2', 'Sitting-1', 'Sitting-2', 'SittingDown-1', 'SittingDown-2', 'Smoking-1', 'Smoking-2', 'TakingPhoto-1', 'TakingPhoto-2', 'Waiting-1', 'Waiting-2', 'Walking-1', 'Walking-2', 'WalkingDog-1', 'WalkingDog-2', 'WalkingTogether-1', 'WalkingTogether-2'] } h5_file="data/human36m/extra/una-dinosauria-data/h36m/cameras.h5" bbox_file="data/human36m/extra/bboxes-Human36M-GT.npy" #retval['bboxes'] = fill_bbox(bbox_file) #retval['cameras'] = fill_cameras(h5_file) def loadHuman36mLabel(path,train = True, withDamageAction=True, retain_every_n_frames_in_test=1): """ this load the label, including bouding box, camera matrices """ test = not train labels = np.load(path, allow_pickle=True).item() train_subjects = ['S1', 'S5', 'S6', 'S7', 'S8'] test_subjects = ['S9', 'S11'] train_subjects = list(labels['subject_names'].index(x) for x in train_subjects) test_subjects = list(labels['subject_names'].index(x) for x in test_subjects) indices = [] if train: mask = np.isin(labels['table']['subject_idx'], train_subjects, assume_unique=True) indices.append(np.nonzero(mask)[0]) if test: mask = np.isin(labels['table']['subject_idx'], test_subjects, assume_unique=True) if not withDamageAction: mask_S9 = labels['table']['subject_idx'] == labels['subject_names'].index('S9') damaged_actions = 'Greeting-2', 'SittingDown-2', 'Waiting-1' damaged_actions = [labels['action_names'].index(x) for x in damaged_actions] mask_damaged_actions = np.isin(labels['table']['action_idx'], damaged_actions) mask &= ~(mask_S9 & mask_damaged_actions) indices.append(np.nonzero(mask)[0][::retain_every_n_frames_in_test]) labels['table'] = labels['table'][np.concatenate(indices)] return labels if __name__ == "__main__": #infer("alg",max_num=2, crop=True) infer_videos("alg",max_num=1000, save_images_instead=False, crop=True)
[ 11748, 28034, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 269, 85, 17, 198, 11748, 28686, 198, 11748, 289, 20, 9078, 198, 6738, 17268, 1330, 4277, 11600, 220, 198, 6738, 285, 85, 77, 13, 27530, 13, 28461, 648, 1741, 1330, 371, 150...
2.282857
1,400
#!/usr/bin/env python """ TCP Linux sockets with netstat """ import re import sys import socket import lib_util import lib_common from lib_properties import pc from sources_types import addr as survol_addr # Many advantages compared to psutil: # The Python module psutil is not needed # psutil gives only sockets if the process is accessible. # It is much faster. # On the other it is necessary to run netstat in the shell. # $ netstat -aptn # (Not all processes could be identified, non-owned process info # will not be shown, you would have to be root to see it all.) # Active Internet connections (servers and established) # Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name # tcp 0 0 192.168.0.17:8000 0.0.0.0:* LISTEN 25865/python # tcp 0 0 127.0.0.1:427 0.0.0.0:* LISTEN - # tcp 0 0 0.0.0.0:5900 0.0.0.0:* LISTEN 4119/vino-server # tcp 0 0 192.168.122.1:53 0.0.0.0:* LISTEN - # tcp 0 0 192.168.0.17:44634 192.168.0.14:60685 ESTABLISHED 4118/rygel # tcp 0 0 192.168.0.17:22 192.168.0.14:60371 ESTABLISHED - # tcp 0 0 192.168.0.17:44634 192.168.0.14:58478 ESTABLISHED 4118/rygel # tcp 0 0 192.168.0.17:44634 192.168.0.15:38960 TIME_WAIT - # tcp 0 0 192.168.0.17:44634 192.168.0.14:58658 ESTABLISHED 4118/rygel # tcp 0 0 192.168.0.17:44634 192.168.0.14:59694 ESTABLISHED 4118/rygel # tcp 0 0 fedora22:44634 192.168.0.14:58690 ESTABLISHED 4118/rygel # tcp 0 0 fedora22:ssh 192.168.0.14:63599 ESTABLISHED - # tcp 0 0 fedora22:42042 176.103.:universe_suite ESTABLISHED 23512/amule # tcp6 0 0 [::]:wbem-http [::]:* LISTEN - # tcp6 0 0 [::]:wbem-https [::]:* LISTEN - # tcp6 0 0 [::]:mysql [::]:* LISTEN - # tcp6 0 0 [::]:rfb [::]:* LISTEN 4119/vino-server # tcp6 0 0 [::]:50000 [::]:* LISTEN 23512/amule # tcp6 0 0 [::]:43056 [::]:* LISTEN 4125/httpd # tcp6 0 0 [::]:http [::]:* LISTEN - # tcp6 0 0 [::]:ssh [::]:* LISTEN - # tcp6 0 0 localhost:ipp [::]:* LISTEN - # tcp6 0 0 [::]:telnet [::]:* LISTEN - # if __name__ == '__main__': Main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 37811, 198, 4825, 47, 7020, 37037, 351, 2010, 14269, 198, 37811, 198, 198, 11748, 302, 198, 11748, 25064, 198, 11748, 17802, 198, 11748, 9195, 62, 22602, 198, 11748, 9195, 62, 11321...
1.703078
1,657
# models.py # created by Sylvestre-Alvise Rebuffi [srebuffi@robots.ox.ac.uk] # Copyright The University of Oxford, 2017-2020 # This code is made available under the Apache v2.0 licence, see LICENSE.txt for details import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable from torch.nn.parameter import Parameter import config_task import math # No projection: identity shortcut def resnet26(num_classes=10, blocks=BasicBlock): return ResNet(blocks, [4,4,4],num_classes)
[ 2, 4981, 13, 9078, 198, 2, 2727, 416, 49481, 4223, 260, 12, 2348, 85, 786, 15652, 1648, 72, 685, 82, 34806, 1648, 72, 31, 22609, 1747, 13, 1140, 13, 330, 13, 2724, 60, 198, 2, 15069, 220, 383, 2059, 286, 13643, 11, 2177, 12, 423...
3.142012
169
#Condies Aninhadas #if -> elif -> elif -> else # pode usar quantos elif quiser #Aprovando Emprstimo casa = float(input('Qual o valor da casa: R$ ')) salario = float(input('Qual o valor do salrio: R$ ')) tempo = int(input('Quanto anos para pagar? ')) salario30 = salario * 0.30 prestacao = casa / (tempo * 12) if salario30 >= prestacao and tempo >= 15: print('Emprstimo no excede 30 % do seu slario') print('-='*30) print('EMPRSTIMO APROVADO COM RESTRIES') print('-='*30) elif salario30 >= prestacao and tempo < 15: print('Emprstimo no excede 30 % e pagar em ',tempo) print('-='*30) print('EMPRSTIMO APROVADO SEM RESTRIES') print('-='*30) else: print('Emprstimo excede 30% do seu salrio') print('-='*30) print('EMPRSTIMO NEGADO') print('-='*30) print('Para pagar a casa de R$ {:.2f}.\nCom o salrio que recebe de R$ {:.2f}.\nEm {} anos, voc deve pagar mensalmente R$ {:.2f}'.format(casa,salario,tempo,prestacao)) #\n quebra linha #end=' ' puxa a linha de baixo
[ 2, 25559, 444, 1052, 259, 18108, 292, 198, 2, 361, 4613, 1288, 361, 4613, 1288, 361, 4613, 2073, 1303, 279, 1098, 514, 283, 5554, 418, 1288, 361, 627, 5847, 198, 198, 2, 32, 15234, 25440, 2295, 1050, 301, 25147, 198, 66, 15462, 796,...
2.273138
443
import discord import os import requests import asyncio import psycopg2 import logging from apscheduler.schedulers.asyncio import AsyncIOScheduler from discord.ext import commands logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', datefmt=f"%m/%d/%Y %H:%M:%S %Z") logger = logging.getLogger("Snipe Bot") client = commands.Bot(command_prefix=".") scheduler = AsyncIOScheduler() DATABASE_URL = os.environ.get("DATABASE_URL") conn = psycopg2.connect(DATABASE_URL, sslmode="require") cur = conn.cursor() # with conn: # cur.execute("CREATE TABLE coursesToBeFound (index VARCHAR primary key);") # cur.execute("INSERT INTO coursesToBeFound (index) VALUES (%s)", ("00150",)) # cur.execute("DELETE FROM coursesToBeFound where index = %s", ("00150",)) # cur.execute("SELECT * from coursesToBeFound;") # for row in cur: # print(row[0]) sectionsFound = [] if __name__ == "__main__": logger.info("Starting") scheduler.add_job(check_courses, "interval", seconds=10) scheduler.start() client.run(os.environ.get("token"))
[ 11748, 36446, 198, 11748, 28686, 198, 11748, 7007, 198, 11748, 30351, 952, 198, 11748, 17331, 22163, 70, 17, 198, 11748, 18931, 198, 198, 6738, 257, 862, 1740, 18173, 13, 1416, 704, 377, 364, 13, 292, 13361, 952, 1330, 1081, 13361, 40, ...
2.547297
444
from gingerit.gingerit import GingerIt
[ 6738, 25072, 270, 13, 2667, 263, 270, 1330, 38682, 1026 ]
3.8
10
''' Escreva um programa que leia dois nmeros inteiros e compare- os, mostrando na tela uma mensagem: - O primeiro valor maior - O segundo valor maior - no existe valor maior, os dois so iguais ''' # Ler dois nmeros inteiros n1 = int(input('Informe o primeiro nmero: ')) n2 = int(input('Informe o segundo nmero: ')) # Operadores Lgicos n1_maior = n1 > n2 n2_maior = n2 > n1 # Estrutura Condicional if, elif, else. if n1_maior: print('O nmero {} o maior!'.format(n1)) elif n2_maior: print('O nmero {} o maior!'.format(n2)) else: print('Os nmeros so iguais!')
[ 7061, 6, 198, 220, 220, 220, 16319, 260, 6862, 23781, 1430, 64, 8358, 443, 544, 466, 271, 299, 647, 418, 493, 20295, 4951, 304, 8996, 12, 28686, 11, 749, 25192, 78, 12385, 256, 10304, 334, 2611, 285, 641, 363, 368, 25, 628, 220, 2...
2.111888
286
if __name__ == '__main__': main()
[ 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 1388, 3419, 198 ]
2.105263
19
# -*- coding: utf-8 -*- { 'name': 'Open-Xchange Odoo', 'version': '1.0', 'category': 'Social Network', 'sequence': 2, 'summary': 'Discussions, Mailing Lists, News', 'description': """ Open-Xchange Integration ========================= This module is designed to be a standard open-xchange inbox inside Odoo to allow for the use of email inside the Odoo framework as an option alongside Odoo's own mail module. I would like to slowly add features to this to further integrate Open-Xchange inside Odoo to allow for easier migration to Odoo for those that are not interested in using Odoo's default mail module to completely replace their emails. Main Features ------------- * Open-Xchange webmail interface inside Odoo. * Multi-inbox handling by Open-Xchange. * More features to be added later to further integrate Open-Xchange with Odoo. """, 'author': 'Luke Branch', 'website': 'https://github.com/OdooCommunityWidgets/IDEAS-FOR-MODULES/mail_open_xchange', 'depends': ['base', 'base_setup', 'mail'], 'data': [ '', ], 'installable': False, 'application': True, }
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 90, 198, 220, 220, 220, 705, 3672, 10354, 705, 11505, 12, 55, 3803, 10529, 2238, 3256, 198, 220, 220, 220, 705, 9641, 10354, 705, 16, 13, 15, 3256, 198, 220, 220, 22...
3.156863
357
import sys sys.path.append('src') from functions import * import numpy as np from numpy.testing import assert_allclose "-----------------------Full soliton--------------------------------------------" def pulse_propagations(ram, ss, nm, N_sol=1, cython = True, u = None): "SOLITON TEST. IF THIS FAILS GOD HELP YOU!" n2 = 2.5e-20 # n2 for silica [m/W] # 0.0011666666666666668 # loss [dB/m] alphadB = np.array([0 for i in range(nm)]) gama = 1e-3 # w/m "-----------------------------General options------------------------------" maxerr = 1e-13 # maximum tolerable error per step "----------------------------Simulation parameters-------------------------" N = 10 z = np.array([0,70]) # total distance [m] nplot = 10 # number of plots nt = 2**N # number of grid points #dzstep = z/nplot # distance per step dz_less = 1 dz = 1 # starting guess value of the step lam_p1 = 1550 lamda_c = 1550e-9 lamda = lam_p1*1e-9 beta2 = -1e-3 P0_p1 = 1 betas = np.array([0, 0, beta2]) T0 = (N_sol**2 * np.abs(beta2) / (gama * P0_p1))**0.5 TFWHM = (2*np.log(1+2**0.5)) * T0 int_fwm = sim_parameters(n2, nm, alphadB) int_fwm.general_options(maxerr, raman_object, ss, ram) int_fwm.propagation_parameters(N, z, nplot, dz_less, 1) int_fwm.woble_propagate(0) fv, where = fv_creator(lam_p1,lam_p1 + 25,0, 100, int_fwm) #fv, where = fv_creator(lam_p1, , int_fwm, prot_casc=0) sim_wind = sim_window(fv, lamda, lamda_c, int_fwm, fv_idler_int=1) loss = Loss(int_fwm, sim_wind, amax=int_fwm.alphadB) alpha_func = loss.atten_func_full(sim_wind.fv, int_fwm) int_fwm.alphadB = alpha_func int_fwm.alpha = int_fwm.alphadB dnerr = [0] index = 1 master_index = 0 a_vec = [2.2e-6] Q_large,M1,M2 = get_Qs(nm, gama, fv, a_vec, dnerr, index, master_index, lamda, n2) if nm ==1: M1, M2, Q_large= np.array([1]), np.array([1]), Q_large[:,0,0] betas = betas[np.newaxis, :] # sys.exit() Dop = dispersion_operator(betas, int_fwm, sim_wind) print(Dop.shape) integrator = Integrator(int_fwm) integrand = Integrand(int_fwm.nm,ram, ss, cython = False, timing = False) dAdzmm = integrand.dAdzmm RK = integrator.RK45mm dAdzmm = integrand.dAdzmm pulse_pos_dict_or = ('after propagation', "pass WDM2", "pass WDM1 on port2 (remove pump)", 'add more pump', 'out') #M1, M2, Q = Q_matrixes(1, n2, lamda, gama=gama) raman = raman_object(int_fwm.ram, int_fwm.how) raman.raman_load(sim_wind.t, sim_wind.dt, M2, nm) if raman.on == 'on': hf = raman.hf else: hf = None u = np.empty( [ int_fwm.nm, len(sim_wind.t)], dtype='complex128') U = np.empty([int_fwm.nm, len(sim_wind.t)], dtype='complex128') sim_wind.w_tiled = np.tile(sim_wind.w + sim_wind.woffset, (int_fwm.nm, 1)) u[:, :] = ((P0_p1)**0.5 / np.cosh(sim_wind.t/T0)) * \ np.exp(-1j*(sim_wind.woffset)*sim_wind.t) U[:, :] = fftshift(sim_wind.dt*fft(u[:, :])) gam_no_aeff = -1j*int_fwm.n2*2*pi/sim_wind.lamda u, U = pulse_propagation(u, U, int_fwm, M1, M2.astype(np.int64), Q_large[0].astype(np.complex128), sim_wind, hf, Dop[0], dAdzmm, gam_no_aeff,RK) U_start = np.abs(U[ :, :])**2 u[:, :] = u[:, :] * \ np.exp(1j*z[-1]/2)*np.exp(-1j*(sim_wind.woffset)*sim_wind.t) """ fig1 = plt.figure() plt.plot(sim_wind.fv,np.abs(U[1,:])**2) plt.savefig('1.png') fig2 = plt.figure() plt.plot(sim_wind.fv,np.abs(U[1,:])**2) plt.savefig('2.png') fig3 = plt.figure() plt.plot(sim_wind.t,np.abs(u[1,:])**2) plt.xlim(-10*T0, 10*T0) plt.savefig('3.png') fig4 = plt.figure() plt.plot(sim_wind.t,np.abs(u[1,:])**2) plt.xlim(-10*T0, 10*T0) plt.savefig('4.png') fig5 = plt.figure() plt.plot(fftshift(sim_wind.w),(np.abs(U[1,:])**2 - np.abs(U[1,:])**2 )) plt.savefig('error.png') fig6 = plt.figure() plt.plot(sim_wind.t,np.abs(u[1,:])**2 - np.abs(u[1,:])**2) plt.xlim(-10*T0, 10*T0) plt.savefig('error2.png') plt.show() """ return u, U, maxerr def test_bire_pass(): Da = np.random.uniform(0, 2*pi, 100) b = birfeg_variation(Da,2) u = np.random.randn(2, 2**14) + 1j * np.random.randn(2, 2**14) u *= 10 for i in range(100): ut = b.bire_pass(u,i) assert_allclose(np.abs(u)**2, np.abs(ut)**2) u = 1 * ut
[ 11748, 25064, 198, 17597, 13, 6978, 13, 33295, 10786, 10677, 11537, 198, 6738, 5499, 1330, 1635, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 299, 32152, 13, 33407, 1330, 6818, 62, 439, 19836, 198, 198, 1, 19351, 6329, 13295, 1540, 37...
1.862015
2,551
import os import requests if __name__ == '__main__': url = 'https://jjdong5.com/get_file/4/1fa69b06c6276768e95cc0c04d85feec693488a588/13000/13287/13287_360p.m3u8' download(url)
[ 11748, 28686, 198, 11748, 7007, 198, 220, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 19016, 796, 705, 5450, 1378, 41098, 67, 506, 20, 13, 785, 14, 1136, 62, 7753, 14, 19, 14, 16, 13331, 3388, ...
2.054945
91
from collections import defaultdict from time import sleep from absl import app from absl import flags import erdos.graph from erdos.op import Op from erdos.utils import frequency from erdos.message import Message from erdos.data_stream import DataStream from erdos.timestamp import Timestamp from erdos.message import WatermarkMessage INTEGER_FREQUENCY = 10 # The frequency at which to send the integers. class SecondOperator(Op): """ Second operator that listens in on the numbers and reports their sum when the watermark is received. """ def __init__(self, name): """ Initializes the attributes to be used.""" super(SecondOperator, self).__init__(name) self.windows = defaultdict(list) def save_numbers(self, message): """ Save all the numbers corresponding to a window. """ batch_number = message.timestamp.coordinates[0] self.windows[batch_number].append(message.data) def execute_sum(self, message): """ Sum all the numbers in this window and send out the aggregate. """ batch_number = message.timestamp.coordinates[0] window_data = self.windows.pop(batch_number, None) #print("Received a watermark for the timestamp: {}".format(batch_number)) #print("The sum of the window {} is {}".format( # window_data, sum(window_data))) output_msg = Message(sum(window_data), Timestamp(coordinates = [batch_number])) self.get_output_stream("sum_out").send(output_msg) def execute(self): """ Execute the spin() loop to continue processing messages. """ self.spin() class ThirdOperator(Op): """ Third operator that listens in on the sum and verifies correctness.""" def __init__(self, name): """Initializes the attributes to be used.""" super(ThirdOperator, self).__init__(name) def assert_correctness(self, message): """ Assert the correctness of the results.""" batch_number = message.timestamp.coordinates[0] sum_data = sum(range((batch_number - 1) * 10 + 1, batch_number * 10 + 1)) print("Received sum: {} for the batch_number {}, expected {}".format( message.data, batch_number, sum_data)) if __name__ == "__main__": app.run(main)
[ 6738, 17268, 1330, 4277, 11600, 198, 6738, 640, 1330, 3993, 198, 198, 6738, 2352, 75, 1330, 598, 198, 6738, 2352, 75, 1330, 9701, 198, 198, 11748, 1931, 37427, 13, 34960, 198, 6738, 1931, 37427, 13, 404, 1330, 8670, 198, 6738, 1931, 3...
2.78125
832
from django.http import HttpResponse from django_base_shop.models import ShippingTag from .models import ConcreteCart, ConcreteProduct
[ 6738, 42625, 14208, 13, 4023, 1330, 367, 29281, 31077, 198, 6738, 42625, 14208, 62, 8692, 62, 24643, 13, 27530, 1330, 24147, 24835, 198, 198, 6738, 764, 27530, 1330, 1482, 38669, 43476, 11, 1482, 38669, 15667, 628, 628, 628 ]
3.710526
38
# PYQT import sys #from ...TabPanel import TabPanel import sip from q3.ui.engine import qtw,qtc,qtg from ... import consts, prop, direction from ...ui import orientation, colors from ...moduletype import ModuleType from ...nodeiotype import NodeIoType from ...q3vector import Q3Vector from ...EventSignal import EventProps from ..driverBase import Q3DriverBase from enum import Enum from ...valuetype import ValueType from .IoLinkView import IoLinkView from .IoNodeView import IoNodeView from .ModuleViewImpl import ModuleViewImpl from .GraphViewImpl import GraphViewImpl #class IoNode: # pass
[ 198, 2, 350, 56, 48, 51, 198, 198, 11748, 25064, 198, 2, 6738, 2644, 33349, 26639, 1330, 16904, 26639, 198, 198, 11748, 31145, 220, 198, 198, 6738, 10662, 18, 13, 9019, 13, 18392, 1330, 10662, 4246, 11, 80, 23047, 11, 80, 25297, 198...
3.230366
191
# import pandas, matplotlib, and seaborn import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns pd.set_option('display.width', 53) pd.set_option('display.max_columns', 5) pd.set_option('display.max_rows', 200) pd.options.display.float_format = '{:,.0f}'.format covidtotals = pd.read_csv("data/covidtotals.csv") covidtotals.set_index("iso_code", inplace=True) landtemps = pd.read_csv("data/landtemps2019avgs.csv") # do a scatterplot of total_cases by total_deaths ax = sns.regplot(x="total_cases_mill", y="total_deaths_mill", data=covidtotals) ax.set(xlabel="Cases Per Million", ylabel="Deaths Per Million", title="Total Covid Cases and Deaths by Country") plt.show() fig, axes = plt.subplots(1,2, sharey=True) sns.regplot(x=covidtotals.aged_65_older, y=covidtotals.total_cases_mill, ax=axes[0]) sns.regplot(x=covidtotals.gdp_per_capita, y=covidtotals.total_cases_mill, ax=axes[1]) axes[0].set_xlabel("Aged 65 or Older") axes[0].set_ylabel("Cases Per Million") axes[1].set_xlabel("GDP Per Capita") axes[1].set_ylabel("") plt.suptitle("Age 65 Plus and GDP with Cases Per Million") plt.tight_layout() fig.subplots_adjust(top=0.92) plt.show() # show the high elevation points in a different color low, high = landtemps.loc[landtemps.elevation<=1000], landtemps.loc[landtemps.elevation>1000] low.shape[0], low.avgtemp.mean() high.shape[0], high.avgtemp.mean() plt.scatter(x="latabs", y="avgtemp", c="blue", data=low) plt.scatter(x="latabs", y="avgtemp", c="red", data=high) plt.legend(('low elevation', 'high elevation')) plt.xlabel("Latitude (N or S)") plt.ylabel("Average Temperature (Celsius)") plt.title("Latitude and Average Temperature in 2019") plt.show() # show scatter plot with different regression lines by elevation group landtemps['elevation_group'] = np.where(landtemps.elevation<=1000,'low','high') sns.lmplot(x="latabs", y="avgtemp", hue="elevation_group", palette=dict(low="blue", high="red"), legend_out=False, data=landtemps) plt.xlabel("Latitude (N or S)") plt.ylabel("Average Temperature") plt.legend(('low elevation', 'high elevation'), loc='lower left') plt.yticks(np.arange(-60, 40, step=20)) plt.title("Latitude and Average Temperature in 2019") plt.tight_layout() plt.show() # show this as a 3D plot fig = plt.figure() plt.suptitle("Latitude, Temperature, and Elevation in 2019") ax = plt.axes(projection='3d') ax.set_xlabel("Elevation") ax.set_ylabel("Latitude") ax.set_zlabel("Avg Temp") ax.scatter3D(landtemps.elevation, landtemps.latabs, landtemps.avgtemp) plt.show()
[ 2, 1330, 19798, 292, 11, 2603, 29487, 8019, 11, 290, 384, 397, 1211, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 384, 397, 1211, ...
2.540541
999
import unittest import numpy as np from reamber.base import Bpm, Hit, Hold, Map, MapSet from reamber.base.lists import BpmList from reamber.base.lists.notes import HitList, HoldList # noinspection PyTypeChecker,DuplicatedCode if __name__ == '__main__': unittest.main()
[ 11748, 555, 715, 395, 198, 198, 11748, 299, 32152, 355, 45941, 198, 198, 6738, 302, 7789, 13, 8692, 1330, 347, 4426, 11, 7286, 11, 9340, 11, 9347, 11, 9347, 7248, 198, 6738, 302, 7789, 13, 8692, 13, 20713, 1330, 347, 4426, 8053, 198...
2.90625
96
import re from util import * from operation import Operation, OperationResult
[ 11748, 302, 198, 6738, 7736, 1330, 1635, 198, 6738, 4905, 1330, 14680, 11, 14680, 23004, 628 ]
4.9375
16
# -*- coding: utf-8 -*- from index_matrix import Matrix __author__ = 'Patricio Lopez Juri'
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 6738, 6376, 62, 6759, 8609, 1330, 24936, 198, 198, 834, 9800, 834, 796, 705, 12130, 1173, 952, 22593, 449, 9900, 6, 628 ]
2.540541
37
from urllib.parse import parse_qs # query string my_values = parse_qs('red=5&blue=0&green=', keep_blank_values=True) # print(repr(my_values)) # print(my_values) # # >>> # {'red': ['5'], 'blue': ['0'], 'green': ['']} # blank # # get print('Red: ', my_values.get('red')) print('Green: ', my_values.get('green')) print('Opacity: ', my_values.get('opacity')) print('-' * 50) # # # 0 # False red = my_values.get('red', [''])[0] or 0 green = my_values.get('green', [''])[0] or 0 opacity = my_values.get('opacity', [''])[0] or 0 print('Red: %r' % red) print('Green: %r' % green) print('Opacity: %r' % opacity) print('-' * 50) # # red = int(my_values.get('red', [''])[0] or 0) # # 1 Python 2.5 red = my_values.get('red', ['']) red = int(red[0]) if red[0] else 0 # 2 if/else green = my_values.get('green', ['']) if green[0]: green = int(green[0]) else: green = 0 # 3
[ 6738, 2956, 297, 571, 13, 29572, 1330, 21136, 62, 48382, 198, 198, 2, 220, 12405, 4731, 198, 1820, 62, 27160, 796, 21136, 62, 48382, 10786, 445, 28, 20, 5, 17585, 28, 15, 5, 14809, 28, 3256, 198, 220, 220, 220, 220, 220, 220, 220,...
2.123853
436
from enum import Enum import pygame # Load sprites into pygame # Piece class Objects
[ 6738, 33829, 1330, 2039, 388, 198, 11748, 12972, 6057, 628, 628, 198, 2, 8778, 42866, 656, 12972, 6057, 628, 198, 2, 27053, 1398, 35832, 198 ]
3.64
25
from micropython import schedule _subscribers = {}
[ 6738, 12314, 1773, 7535, 1330, 7269, 198, 198, 62, 7266, 40075, 364, 796, 23884, 628, 628 ]
3.4375
16
import boto3 import logging import os from datetime import datetime log = logging.getLogger(__name__) log.setLevel(logging.DEBUG) def get_env_var_value(env_var): '''Get the value of an environment variable :param env_var: the environment variable :returns: the environment variable's value, None if env var is not found ''' value = os.getenv(env_var) if not value: log.warning(f'cannot get environment variable: {env_var}') return value def get_marketplace_synapse_ids(): '''Get Synapse IDs from the Marketplace Dynamo DB, these are the Marketplace customers. Assumes that there is a Dynamo DB with a table containing a mapping of Synapse IDs to SC subscriber data :return a list of synapse IDs, otherwise return empty list if no customers are in DB ''' synapse_ids = [] ddb_marketplace_table_name = get_env_var_value('MARKETPLACE_ID_DYNAMO_TABLE_NAME') ddb_marketplace_synapse_user_id_attribute = "SynapseUserId" if ddb_marketplace_table_name: client = get_dynamo_client() response = client.scan( TableName=ddb_marketplace_table_name, ProjectionExpression=ddb_marketplace_synapse_user_id_attribute, ) if "Items" in response.keys(): for item in response["Items"]: synapse_ids.append(item[ddb_marketplace_synapse_user_id_attribute]["S"]) return synapse_ids def get_marketplace_customer_id(synapse_id): '''Get the Service Catalog customer ID from the Marketplace Dynamo DB. Assumes that there is a Dynamo DB with a table containing a mapping of Synapse IDs to SC subscriber data :param synapse_id: synapse user id :return the Marketplace customer ID, otherwise return None if cannot find an associated customer ID ''' customer_id = None ddb_marketplace_table_name = get_env_var_value('MARKETPLACE_ID_DYNAMO_TABLE_NAME') if ddb_marketplace_table_name: ddb_customer_id_attribute = 'MarketplaceCustomerId' client = get_dynamo_client() response = client.get_item( Key={ 'SynapseUserId': { 'S': synapse_id, } }, TableName=ddb_marketplace_table_name, ConsistentRead=True, AttributesToGet=[ ddb_customer_id_attribute ] ) if "Item" in response.keys(): customer_id = response["Item"][ddb_customer_id_attribute]["S"] else: log.info(f'cannot find registration for synapse user: {synapse_id}') return customer_id def get_marketplace_product_code(synapse_id): '''Get the registered Service Catalog customer product code. Assumes that there is a Dynamo DB with a table containing a mapping of Synapse IDs to SC subscriber data :param synapse_id: synapse user id :return the Marketplace product code, None if cannot find customer ID ''' product_code = None ddb_marketplace_table_name = get_env_var_value('MARKETPLACE_ID_DYNAMO_TABLE_NAME') if ddb_marketplace_table_name: ddb_product_code_attribute = 'ProductCode' client = get_dynamo_client() response = client.get_item( Key={ 'SynapseUserId': { 'S': synapse_id, } }, TableName=ddb_marketplace_table_name, ConsistentRead=True, AttributesToGet=[ ddb_product_code_attribute ] ) if "Item" in response.keys(): product_code = response["Item"][ddb_product_code_attribute]["S"] else: log.info(f'cannot find registration for synapse user: {synapse_id}') return product_code def get_customer_cost(customer_id, time_period, granularity): ''' Get the total cost of all resources tagged with the customer_id for a given time_period. The time_period and time granularity must match. :param customer_id: the Marketplace customer ID :param time_period: the cost time period :param granularity: the granularity of time HOURLY|DAILY|MONTHLY :return: the total cost of all resources and the currency unit ''' client = get_ce_client() response = client.get_cost_and_usage( TimePeriod=time_period, Granularity=granularity, Filter={ "Tags": { "Key": "marketplace:customerId", "Values": [ customer_id ] } }, Metrics=["UnblendedCost"] ) results_by_time = response['ResultsByTime'] cost = results_by_time[0]["Total"]["UnblendedCost"]["Amount"] unit = results_by_time[0]["Total"]["UnblendedCost"]["Unit"] return float(cost), unit def report_cost(cost, customer_id, product_code): ''' Report the incurred cost of the customer's resources to the AWS Marketplace :param cost: the cost (as a float value) :param customer_id: the Marketplace customer ID :param product_code: the Marketplace product code ''' cost_accrued_rate = 0.001 # TODO: use mareketplace get_dimension API to get this info quantity = int(cost / cost_accrued_rate) mrktpl_client = get_meteringmarketplace_client() response = mrktpl_client.batch_meter_usage( UsageRecords=[ { 'Timestamp': datetime.utcnow(), 'CustomerIdentifier': customer_id, 'Dimension': 'costs_accrued', 'Quantity': quantity } ], ProductCode=product_code ) log.debug(f'batch_meter_usage response: {response}') results = response["Results"][0] status = results["Status"] if status == 'Success': log.info(f'usage record: {results}') else: # TODO: need to add a retry mechanism for failed reports unprocessed_records = response["UnprocessedRecords"][0] log.error(f'unprocessed record: {unprocessed_records}')
[ 11748, 275, 2069, 18, 198, 11748, 18931, 198, 11748, 28686, 198, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 198, 6404, 796, 18931, 13, 1136, 11187, 1362, 7, 834, 3672, 834, 8, 198, 6404, 13, 2617, 4971, 7, 6404, 2667, 13, 30531, ...
2.742658
2,009
# Library Imports from itertools import islice import csv # Local Module Imports import config
[ 2, 10074, 1846, 3742, 198, 6738, 340, 861, 10141, 1330, 318, 75, 501, 220, 198, 11748, 269, 21370, 198, 198, 2, 10714, 19937, 1846, 3742, 198, 11748, 4566, 198 ]
3.344828
29
""" Class to control the execution of the optimization session """ import shutil import configparser import glob import os import subprocess import sys from pathlib import Path from antares_xpansion.input_checker import check_candidates_file from antares_xpansion.input_checker import check_settings_file from antares_xpansion.xpansion_utils import read_and_write_mps
[ 37811, 198, 220, 220, 220, 5016, 284, 1630, 262, 9706, 286, 262, 23989, 6246, 198, 37811, 198, 198, 11748, 4423, 346, 198, 11748, 4566, 48610, 198, 11748, 15095, 198, 11748, 28686, 198, 11748, 850, 14681, 198, 11748, 25064, 198, 198, 67...
3.571429
105
from tweepy import StreamListener import json, time, sys
[ 6738, 4184, 538, 88, 1330, 13860, 33252, 198, 11748, 33918, 11, 640, 11, 25064, 628 ]
3.866667
15
''' N = int(input('Digite um NMERO: ')) tot = 0 for c in range(1, n+1): if n%c == 0: print('\033[33m', end=' ') tot+=1 else: print('\033[31m', end=' ') print('{}'.format(c), end=' ') print('\n\033[mO numero {} foi divisivel {} vezes'.format(n, tot)) if tot == 2: print('E POR ISSO PRIMO') else: print('E POR ISSO NO PRIMO') '''
[ 7061, 6, 198, 45, 796, 493, 7, 15414, 10786, 19511, 578, 23781, 28692, 34812, 25, 705, 4008, 198, 83, 313, 796, 657, 198, 1640, 269, 287, 2837, 7, 16, 11, 299, 10, 16, 2599, 198, 220, 220, 220, 611, 299, 4, 66, 6624, 657, 25, ...
1.943005
193
from django.shortcuts import render # Create your views here.
[ 6738, 42625, 14208, 13, 19509, 23779, 1330, 8543, 198, 198, 2, 13610, 534, 5009, 994, 13, 198 ]
3.705882
17
# -*- coding: utf-8 -*- import qclib.tag_times
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 10662, 565, 571, 13, 12985, 62, 22355, 628, 220, 220, 220, 220 ]
1.925926
27
import socket address = ('127.0.0.1', 31500) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # s = socket.socket() s.bind(address) s.listen(5) ss, addr = s.accept() print 'got connected from',addr ss.send('hihi') ra = ss.recv(512) print ra ss.close() s.close()
[ 11748, 17802, 220, 220, 201, 198, 220, 220, 201, 198, 21975, 796, 19203, 16799, 13, 15, 13, 15, 13, 16, 3256, 32647, 405, 8, 220, 220, 201, 198, 82, 796, 17802, 13, 44971, 7, 44971, 13, 8579, 62, 1268, 2767, 11, 17802, 13, 50, 1...
1.968944
161
# what is the first number to have 5000 different ways to sum with prime numbers? import math import timeit start = timeit.default_timer() print "Answer: %s" % euler_77() stop = timeit.default_timer() print "Time: %f" % (stop - start)
[ 2, 644, 318, 262, 717, 1271, 284, 423, 23336, 1180, 2842, 284, 2160, 351, 6994, 3146, 30, 220, 198, 198, 11748, 10688, 198, 11748, 640, 270, 628, 198, 9688, 796, 640, 270, 13, 12286, 62, 45016, 3419, 198, 198, 4798, 366, 33706, 25, ...
3.116883
77
from package.query_db import query from package.lambda_exception import LambdaException
[ 6738, 5301, 13, 22766, 62, 9945, 1330, 12405, 198, 6738, 5301, 13, 50033, 62, 1069, 4516, 1330, 21114, 6814, 16922, 198 ]
4.190476
21
# Title: Swap Nodes in Pairs # Link: https://leetcode.com/problems/swap-nodes-in-pairs def solution(): head = ListNode(1, ListNode(2, ListNode(3, ListNode(4)))) problem = Problem() return problem.swap_pairs(head) if __name__ == '__main__': main()
[ 2, 11851, 25, 48408, 399, 4147, 287, 350, 3468, 198, 2, 7502, 25, 3740, 1378, 293, 316, 8189, 13, 785, 14, 1676, 22143, 14, 2032, 499, 12, 77, 4147, 12, 259, 12, 79, 3468, 628, 198, 4299, 4610, 33529, 198, 220, 220, 220, 1182, 7...
2.495327
107
import numpy as np import cv2 import imageio import tensorflow as tf import json import csv import os import sys sys.path.append("object_detection") sys.path.append("object_detection/deep_sort") sys.path.append("action_detection") import argparse import object_detection.object_detector as obj import action_detection.action_detector as act import time DISPLAY = False SHOW_CAMS = False np.random.seed(10) COLORS = np.random.randint(0, 255, [1000, 3]) if __name__ == '__main__': main()
[ 11748, 299, 32152, 355, 45941, 198, 11748, 269, 85, 17, 198, 11748, 2939, 952, 198, 11748, 11192, 273, 11125, 355, 48700, 198, 11748, 33918, 198, 11748, 269, 21370, 198, 198, 11748, 28686, 198, 11748, 25064, 198, 17597, 13, 6978, 13, 33...
2.812155
181
import os import unittest from pathlib import Path import pytest from paramak import SweepMixedShape if __name__ == "__main__": unittest.main()
[ 11748, 28686, 198, 11748, 555, 715, 395, 198, 6738, 3108, 8019, 1330, 10644, 198, 198, 11748, 12972, 9288, 198, 198, 6738, 5772, 461, 1330, 42818, 44, 2966, 33383, 628, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, ...
2.942308
52
from boto3.s3.transfer import S3Transfer import boto3 import glob import os files = glob.glob("*.bak") for file in files: print(file) uploaded = upload_to_aws(file, 'newki-backup', file) os.remove(file)
[ 6738, 275, 2069, 18, 13, 82, 18, 13, 39437, 1330, 311, 18, 43260, 198, 11748, 275, 2069, 18, 198, 11748, 15095, 198, 11748, 28686, 198, 220, 220, 220, 220, 198, 16624, 796, 15095, 13, 4743, 672, 7203, 24620, 65, 461, 4943, 198, 1640...
2.455556
90
import numpy as np from deepnet.nnet import RNN from deepnet.solver import sgd_rnn def text_to_inputs(path): """ Converts the given text into X and y vectors X : contains the index of all the characters in the text vocab y : y[i] contains the index of next character for X[i] in the text vocab """ with open(path) as f: txt = f.read() X, y = [], [] char_to_idx = {char: i for i, char in enumerate(set(txt))} idx_to_char = {i: char for i, char in enumerate(set(txt))} X = np.array([char_to_idx[i] for i in txt]) y = [char_to_idx[i] for i in txt[1:]] y.append(char_to_idx['.']) y = np.array(y) vocab_size = len(char_to_idx) return X, y, vocab_size, char_to_idx, idx_to_char if __name__ == "__main__": X, y, vocab_size, char_to_idx, idx_to_char = text_to_inputs('data/Rnn.txt') rnn = RNN(vocab_size,vocab_size,char_to_idx,idx_to_char) rnn = sgd_rnn(rnn,X,y,10,10,0.1)
[ 11748, 299, 32152, 355, 45941, 198, 6738, 2769, 3262, 13, 77, 3262, 1330, 371, 6144, 198, 6738, 2769, 3262, 13, 82, 14375, 1330, 264, 21287, 62, 81, 20471, 628, 198, 4299, 2420, 62, 1462, 62, 15414, 82, 7, 6978, 2599, 198, 220, 220,...
2.057851
484
from __future__ import print_function from __future__ import division from . import _C import torch from fuzzytorch.utils import TDictHolder, tensor_to_numpy, minibatch_dict_collate import numpy as np from fuzzytools.progress_bars import ProgressBar, ProgressBarMulti import fuzzytools.files as files import fuzzytools.datascience.metrics as fcm from fuzzytools.matplotlib.utils import save_fig import matplotlib.pyplot as plt import fuzzytorch.models.seq_utils as seq_utils from scipy.optimize import curve_fit from lchandler import _C as _Clchandler from lchandler.plots.lc import plot_lightcurve from .utils import check_attn_scores EPS = _C.EPS ################################################################################################################################################### ###################################################################################################################################################
[ 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 6738, 11593, 37443, 834, 1330, 7297, 198, 6738, 764, 1330, 4808, 34, 198, 198, 11748, 28034, 198, 6738, 34669, 13165, 354, 13, 26791, 1330, 13320, 713, 39, 19892, 11, 11192, 273, 62, ...
4.251121
223
# if __name__ == "__main__": test_dic = {'a': 1, 'b': 2, 'c': {'a': 1, 'b': {'b': 4}}} r1 = getItemByKey(test_dic, 'b') r2 = getItemByKeyInMyMethod(test_dic, 'b') print(r1, r2, sep='\n')
[ 2, 220, 628, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 1332, 62, 67, 291, 796, 1391, 6, 64, 10354, 352, 11, 705, 65, 10354, 362, 11, 705, 66, 10354, 1391, 6, 64, 10354, 352, 11, 705, 65, ...
1.839286
112
#!/usr/bin/env python # -*- coding: utf-8 -*- from tacit import tac_slices for chunk in tac_slices('data/ordered.list', 2): print repr(chunk)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 6738, 40787, 1330, 26142, 62, 82, 677, 274, 198, 198, 1640, 16058, 287, 26142, 62, 82, 677, 274, 10786, 7890, 14...
2.387097
62
import numpy as np import pandas as pd import json from datetime import datetime import psycopg2 import functools import requests ############################################################## ## https://www.exrx.net/Calculators/WalkRunMETs ## https://www.cdc.gov/growthcharts/clinical_charts.htm ## https://help.fitbit.com/articles/en_US/Help_article/1141 ############################################################## URL = 'https://f73lzrw31i.execute-api.us-west-2.amazonaws.com/default/demo_data_server' HEADER = {'x-api-key': 'XXXXXX'} ############################################################################################# ############################################################################################# revibe = adict() revibe.DBNAME = 'revibe' revibe.HOST = 'prd.c5fw7irdcxik.us-west-2.rds.amazonaws.com' #revibe.PORT = '5432' revibe.USER = 'dave' revibe.PASS = 'tnoiSLoHjEBZE6JKsFgY' revibe.SSLMODE = 'require' CONN = None ## revised Harris-Benedict BMR equations... ## basal metabolic rate (kCals per day) ## find index j into y that minimizes abs(x-y[j]) GC = None # data.bday = data.bday.strftime('%Y-%m-%d') ## s : speed in mph... sec by second vector of speeds.... ## w : weight in lbs ## mode : 2=='walk', 3=='run' ## returns : calories summed across all seconds def calsum(s, w, mode=2): su, wu = 26.8, 2.2 s = s*su w = w/wu if mode==3:## run mode vo = 0.2*s else: ## walk mode == 2 fwvo = 21.11 - 0.3593*s + 0.003*s*s - 3.5 wvo = 0.1*s d = 30 a = np.clip((s-(100-d))/(2*d), 0, 1) vo = wvo*(1.-a) + fwvo*a ############################# return np.sum(vo*w) / 12000.0 ################################### if __name__ == "__main__": pid = 135 ## 135,"1974-05-28",1,0,74,196,1 pid = 169 ## 169,"1980-12-01",1,12,72,170,2 pid = 18947 ## 18947,"2010-08-28",0,0,0,0,0 pid = 10885 ## # dd = request_demo_data(pid) # print(dd) # dd = get_demo_data(pid) # print(dd) ############# dd = make_demo_data(bday='2010-08-28', ht='54.035', wt='69.69', sex='3') # dd = make_demo_data(ht='70', wt='120', sex='2') print(dd)
[ 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 33918, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 11748, 17331, 22163, 70, 17, 198, 11748, 1257, 310, 10141, 198, 11748, 7007, 198, 198, 29113, 14468, 7...
2.37234
940
from django.conf import settings CONTENT_AREAS = getattr(settings, 'PAGELET_CONTENT_AREAS', ( ('main', 'Main'), )) CONTENT_AREA_DEFAULT = getattr(settings, 'PAGELET_CONTENT_AREA_DEFAULT', 'main') CONTENT_TYPES = getattr(settings, 'PAGELET_CONTENT_TYPES', ( ('html', 'HTML', (), {},), ('markdown', 'Markdown', (), {},), ('wymeditor', 'WYMeditor', ('wymeditor/jquery.wymeditor.js',), {},), ('textile', 'Textile', (), {},), )) + getattr(settings, 'PAGELET_CONTENT_TYPES_EXTRA', ()) CONTENT_TYPE_CHOICES = tuple((c[0], c[1]) for c in CONTENT_TYPES) CONTENT_TYPE_DEFAULT = getattr(settings, 'PAGELET_CONTENT_TYPE_DEFAULT', 'html') try: ATTACHMENT_PATH = settings.PAGELET_ATTACHMENT_PATH except AttributeError: ATTACHMENT_PATH = getattr(settings, 'PAGE_ATTACHMENT_PATH', 'attachments/pages/') # settings.PAGELET_TEMPLATE_TAGS is a list of template tag names that # will load before each pagelet is rendered, allowing custom template # tags to be included without including {% load <template_tag> %} tags = set(['pagelet_tags']) if hasattr(settings, 'PAGELET_TEMPLATE_TAGS'): for tag in settings.PAGELET_TEMPLATE_TAGS: tags.add(tag) AUTO_LOAD_TEMPLATE_TAGS = '{%% load %s %%}' % ' '.join(tags) BASE_TEMPLATES = getattr(settings, 'PAGELET_BASE_TEMPLATES', []) BASE_TEMPLATE_DEFAULT = getattr(settings, 'PAGELET_BASE_TEMPLATE_DEFAULT', None) INLINE_PAGELET_EXTRA = getattr(settings, 'PAGELET_INLINE_PAGELET_EXTRA', 0) INLINE_SHARED_EXTRA = getattr(settings, 'PAGELET_INLINE_SHARED_EXTRA', 0) INLINE_ATTACHMENT_EXTRA = getattr(settings, 'PAGELET_INLINE_ATTACHMENT_EXTRA', 0)
[ 6738, 42625, 14208, 13, 10414, 1330, 6460, 628, 198, 37815, 3525, 62, 12203, 1921, 796, 651, 35226, 7, 33692, 11, 705, 4537, 8264, 28882, 62, 37815, 3525, 62, 12203, 1921, 3256, 357, 198, 220, 220, 220, 19203, 12417, 3256, 705, 13383, ...
2.403202
687
import logging import numpy as np from scipy import stats from collections import OrderedDict from alphad3m.metalearning.resource_builder import load_metalearningdb from alphad3m.metalearning.dataset_similarity import get_similar_datasets from alphad3m.primitive_loader import load_primitives_by_name, load_primitives_by_id logger = logging.getLogger(__name__) if __name__ == '__main__': test_dataset('185_baseball_MIN_METADATA')
[ 11748, 18931, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 629, 541, 88, 1330, 9756, 198, 6738, 17268, 1330, 14230, 1068, 35, 713, 198, 6738, 435, 746, 324, 18, 76, 13, 28469, 451, 768, 13, 31092, 62, 38272, 1330, 3440, 62, 28469, ...
2.883871
155
from deap import base, creator, tools import random """ individuallist10 """ # ****************************Types******************************** # def create(name, base, **kargs): # Creates a new class named *name* inheriting from *base* # A negative weight element corresponds to the minimization of # the associated objective and positive weight to the maximization. creator.create("FitnessMin", base.Fitness, weights=(-1.0,)) # an Individual class that is derived from a list with a fitness attribute set # to the just created fitness """ create("Foo", list, bar=dict, spam=1) This above line is exactly the same as defining in the :mod:`creator` module something like the following. :: class Foo(list): spam = 1 def __init__(self): self.bar = dict() """ creator.create("Individual", list, fitness=creator.FitnessMin) # ****************************Initialization******************************** IND_SIZE = 10 toolbox = base.Toolbox() # def register(self, alias, function, *args, **kargs): # Register a *function* in the toolbox under the name *alias*. # *argsfunctionfunction """ >>> def func(a, b, c=3): ... print(a, b, c) ... >>> tools = Toolbox() >>> tools.register("myFunc", func, 2, c=4) >>> tools.myFunc(3) 2 3 4 """ toolbox.register("attribute", random.random) # def initRepeat(container, func, n): # Call the function *container* with a generator function corresponding # to the calling *n* times the function *func*. """ >>> initRepeat(list, random.random, 2) # doctest: +ELLIPSIS, ... # doctest: +NORMALIZE_WHITESPACE [0.6394..., 0.0250...] """ # IND_SIZE random.random()IndividualIndividualIndividual listIND_SIZE toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.attribute, n=IND_SIZE) # individualpopulationn toolbox.register("population", tools.initRepeat, list, toolbox.individual) # ****************************Operators******************************** # def cxTwoPoint(ind1, ind2): # Executes a two-point crossover on the input :term:`sequence` individuals. toolbox.register("mate", tools.cxTwoPoint) # gaussian mutation with mu and sigma # The *indpb* argument is the probability of each attribute to be mutated. # toolbox.register("mutate", tools.mutGaussian, mu=0, sigma=1, indpb=0.1) # def selTournament(individuals, k, tournsize, fit_attr="fitness"): # Select the best individual among *tournsize* randomly chosen # individuals, *k* times. The list returned contains # references to the input *individuals*. toolbox.register("select", tools.selTournament, tournsize=3) toolbox.register("evaluate", evaluate) for ind in main(): print(evaluate(ind))
[ 6738, 390, 499, 1330, 2779, 11, 13172, 11, 4899, 198, 11748, 4738, 198, 37811, 198, 521, 1699, 84, 439, 396, 940, 198, 37811, 198, 198, 2, 220, 8412, 46068, 31431, 17174, 198, 2, 825, 2251, 7, 3672, 11, 2779, 11, 12429, 74, 22046, ...
2.91914
977
from collections import deque import random import numpy as np
[ 6738, 17268, 1330, 390, 4188, 198, 11748, 4738, 198, 11748, 299, 32152, 355, 45941 ]
4.428571
14
# Standard library imports from pprint import pprint import unittest # Local application imports from context import entities from entities import creatures from entities import items from entities import currency from entities import slots if __name__ == '__main__': unittest.main() # runner = unittest.TextTestRunner() # runner.run(suite())
[ 2, 8997, 5888, 17944, 220, 198, 6738, 279, 4798, 1330, 279, 4798, 198, 11748, 555, 715, 395, 198, 198, 2, 10714, 3586, 17944, 198, 6738, 4732, 1330, 12066, 198, 6738, 12066, 1330, 8109, 198, 6738, 12066, 1330, 3709, 198, 6738, 12066, ...
3.646465
99
import collections import re from typing import Iterator, TextIO from .constants import TILE_END, TILE_START, TILE_WARNING
[ 11748, 17268, 198, 11748, 302, 198, 198, 6738, 19720, 1330, 40806, 1352, 11, 8255, 9399, 198, 198, 6738, 764, 9979, 1187, 1330, 31598, 2538, 62, 10619, 11, 31598, 2538, 62, 2257, 7227, 11, 31598, 2538, 62, 31502, 628, 628, 198 ]
3.225
40
import binascii from pwn import * port = 1234 server = '127.0.0.1' sleep(1) for i in range(10000): r = remote(server, port) send(r,i) r.close()
[ 11748, 9874, 292, 979, 72, 198, 6738, 279, 675, 1330, 1635, 198, 634, 796, 1105, 2682, 198, 15388, 796, 705, 16799, 13, 15, 13, 15, 13, 16, 6, 198, 42832, 7, 16, 8, 198, 1640, 1312, 287, 2837, 7, 49388, 2599, 198, 220, 220, 220,...
2.180556
72
from djoser.serializers import UserCreateSerializer from .models import CustomUser
[ 6738, 42625, 13416, 13, 46911, 11341, 1330, 11787, 16447, 32634, 7509, 198, 6738, 764, 27530, 1330, 8562, 12982, 628 ]
4.421053
19
name = "flask_slack_template"
[ 3672, 796, 366, 2704, 2093, 62, 6649, 441, 62, 28243, 1, 198 ]
2.5
12
from typing import Dict from time import time_ns from bus import Bus from instructions.generic_instructions import Instruction from rom import ROM from status import Status import instructions.instructions as i_file import instructions.jump_instructions as j_file import instructions.load_instructions as l_file import instructions.store_instructions as s_file import instructions.stack_instructions as t_file import instructions.arithmetic_instructions as a_file import instructions.logical_instructions as log_file import instructions.nop_instructions as n_file import instructions.unofficial_instructions as u_file
[ 6738, 19720, 1330, 360, 713, 198, 6738, 640, 1330, 640, 62, 5907, 198, 6738, 1323, 1330, 5869, 198, 6738, 7729, 13, 41357, 62, 259, 7249, 507, 1330, 46486, 198, 6738, 9267, 1330, 21224, 198, 6738, 3722, 1330, 12678, 198, 198, 11748, 7...
3.899371
159
#!/usr/bin/env python import datetime import os import subprocess import re import urllib2 import math #################################################################### ## TODO: Replace this function by another one, which simply reads all lines from a file #################################################################### ##################################################################### ## Find the right logfile; logfiles are different for different days ##################################################################### ddat = datetime.datetime.now() theLog = '/home/kalvis/.timeouts/access-{yyyy}-{mm}-{dd}.log'.format( \ yyyy = ddat.year, mm=ddat.month, dd=ddat.day) yellowCount = getYellowCount(theLog) status = getStatus() if yellowCount >= 5: status = "red" if yellowCount > 1: os.system("/home/kalvis/.timeouts/msg.py") logline = '{user}:{time}:{status}({yellowCount})\n'.format(user=currentUser(), \ time=ddat,status=getStatus(),yellowCount=yellowCount) if not os.path.isfile(theLog): open(theLog, 'a').close() with open(theLog, "a") as myfile: myfile.write(logline) if yellowCount >= 5: from subprocess import call call(["pkill","-KILL","-u","marta"])
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 11748, 4818, 8079, 198, 11748, 28686, 198, 11748, 850, 14681, 198, 11748, 302, 198, 11748, 2956, 297, 571, 17, 198, 11748, 10688, 628, 198, 29113, 29113, 4242, 198, 2235, 16926, 46,...
3.2
390
import os import sys import hash_utils if __name__ == '__main__': with open('index.php', 'w') as outfile: StartIndexPhp() for f in os.listdir('.'): if f == 'index.php' or f.find( '?' ) != -1 or f.find( 'System Volume Information' ) != -1 or f.find( 'RECYCLER' ) != -1: continue if os.path.isdir(f): md5str = hash_utils.md5sum(f) print(f + ' - ' + md5str) outfile.write( '\t<tr>\n' ) outfile.write( '\t\t<td align=center><a href="' + f + '">' + f + '</a></td>\n' ) outfile.write( '\t\t<td align=center>' + md5str + '</td>\n' ) outfile.write( '\t</tr>\n' ) CloseIndexPhp( outfile )
[ 11748, 28686, 201, 198, 11748, 25064, 201, 198, 11748, 12234, 62, 26791, 201, 198, 201, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 201, 198, 220, 220, 220, 351, 1280, 10786, 9630, 13, 10121, 3256, 705, 86, 11537, 3...
1.786885
427