content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
import os basedir = os.path.abspath(os.path.dirname(__file__))
[ 11748, 28686, 198, 3106, 343, 796, 28686, 13, 6978, 13, 397, 2777, 776, 7, 418, 13, 6978, 13, 15908, 3672, 7, 834, 7753, 834, 4008, 198 ]
2.423077
26
from .default import size7extracondensedfont
[ 6738, 764, 12286, 1330, 2546, 22, 2302, 11510, 623, 15385, 10331, 198 ]
3.75
12
from bom.octopart_parts_match import match_part from bom.models import Part, PartClass, Seller, SellerPart, Subpart, \ Manufacturer, Organization, PartFile
[ 6738, 8626, 13, 38441, 404, 433, 62, 42632, 62, 15699, 1330, 2872, 62, 3911, 198, 6738, 8626, 13, 27530, 1330, 2142, 11, 2142, 9487, 11, 46555, 11, 46555, 7841, 11, 3834, 3911, 11, 3467, 198, 220, 220, 220, 40218, 11, 12275, 11, 214...
3.428571
49
# Source: # https://github.com/tpn/winsdk-10/blob/46c66795f49679eb4783377968ce25f6c778285a/Include/10.0.10240.0/um/WinUser.h # # convert all C-style comments to python multi-line string comment # find: (^/\*[\s\S\r]+?\*/) # replace: """\n$1\n""" # # convert all keycode #defines to be python constants # find: #define\s(.+_.+?)\s+([\w]+)(\s*)(/[/*].+)? # replace: $1 = $2$3# $4\n # # clean up results by removing lines with only a single # caused by previous regex # find: ^# $\n # replace: # # clean up duplicate newlines # find: (\s#.+\n)\n # replace: $1 # # clean up multi-line comments. # find: ^(\s{3,})(\S.+) # replace: $1 # $2 from enum import IntEnum
[ 2, 8090, 25, 198, 2, 3740, 1378, 12567, 13, 785, 14, 83, 21999, 14, 86, 1040, 34388, 12, 940, 14, 2436, 672, 14, 3510, 66, 2791, 41544, 69, 2920, 37601, 1765, 29059, 2091, 3324, 38956, 344, 1495, 69, 21, 66, 39761, 26279, 64, 14, ...
2.363958
283
#! python3 # -*- coding: utf-8 -*- # from flask import Blueprint bp_errors = Blueprint('flicket-errors', __name__)
[ 2, 0, 21015, 18, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 198, 6738, 42903, 1330, 39932, 198, 198, 46583, 62, 48277, 796, 39932, 10786, 2704, 9715, 12, 48277, 3256, 11593, 3672, 834, 8, 198 ]
2.659091
44
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 4981, 11, 15720, 602, 628 ]
2.891892
37
import abc import argparse import logging import pathlib from collections import namedtuple from operator import itemgetter import toml def __str__(self): return str(self.config) def build_model(self): """Build model according to the configurations in current workspace.""" return self.model_cls.build(**self.config) def logger(self, name: str): """Get a logger that logs to a file. Notice that same logger instance is returned for same names. Args: name(str): logger name """ logger = logging.getLogger(name) if logger.handlers: # previously configured, remain unchanged return logger fileFormatter = logging.Formatter('%(levelname)s [%(name)s] ' '%(asctime)s %(message)s', datefmt='%Y-%m-%d %H:%M:%S') fileHandler = logging.FileHandler( str(self.log_path / (name + '.log'))) fileHandler.setFormatter(fileFormatter) logger.addHandler(fileHandler) return logger def _load(self): """Load configuration.""" try: cfg = toml.load((self.path / 'config.toml').open()) self._set_model(cfg['model_name'], cfg[cfg['model_name'].lower()]) except (FileNotFoundError, KeyError): raise NotConfiguredError('config.toml doesn\'t exist or ' 'is incomplete') def _save(self): """Save configuration.""" f = (self.path / 'config.toml').open('w') toml.dump({'model_name': self.model_name, self.model_name.lower(): self.config}, f) f.close() class Command(abc.ABC): """Command interface."""
[ 11748, 450, 66, 198, 11748, 1822, 29572, 198, 11748, 18931, 198, 11748, 3108, 8019, 198, 6738, 17268, 1330, 3706, 83, 29291, 198, 6738, 10088, 1330, 2378, 1136, 353, 198, 198, 11748, 284, 4029, 628, 628, 198, 220, 220, 220, 825, 11593, ...
2.152381
840
from __future__ import unicode_literals, print_function import sys from pathlib import Path import spacy from spacy.lang.ru import Russian from spacy.pipeline import Tagger, DependencyParser from spacy.util import fix_random_seed, set_lang_class from models.dep import MyDEP from models.loadvec import get_ft_vec from models.pos import MyPOS from models.t2v import build_tok2vec from training.corpora.syntagrus import get_syntagrus_example, get_syntagrus from training.trainer import Trainer, Extractor from utils.corpus import tag_morphology CFG = {"device": 0, 'verbose': 1} GPU_1 = "-g1" in sys.argv[1:] if GPU_1: CFG["device"] = 1 TESTS = False spacy.require_gpu(CFG['device']) TEST_MODE = "--test" in sys.argv[1:] if TEST_MODE: SynTagRus = get_syntagrus_example(Path("data/syntagrus/")) else: SynTagRus = get_syntagrus(Path("data/syntagrus/")) ft_vectors = get_ft_vec() tok2vec = build_tok2vec(embed_size=2000, vectors={"word_vectors": ft_vectors}) if __name__ == "__main__": main()
[ 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 11, 3601, 62, 8818, 198, 198, 11748, 25064, 198, 6738, 3108, 8019, 1330, 10644, 198, 198, 11748, 599, 1590, 198, 6738, 599, 1590, 13, 17204, 13, 622, 1330, 3394, 198, 6738, 5...
2.65625
384
# pylint:disable=missing-class-docstring,no-self-use import os import unittest import archinfo import ailment import angr from angr.analyses.decompiler.peephole_optimizations import ConstantDereferences test_location = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..', 'binaries', 'tests') if __name__ == "__main__": unittest.main()
[ 2, 279, 2645, 600, 25, 40223, 28, 45688, 12, 4871, 12, 15390, 8841, 11, 3919, 12, 944, 12, 1904, 198, 11748, 28686, 198, 198, 11748, 555, 715, 395, 198, 11748, 3934, 10951, 198, 11748, 31907, 434, 198, 11748, 281, 2164, 198, 6738, 2...
2.763359
131
#!/usr/bin/python3 # mysql_createtable.py import pymysql # db = pymysql.connect('localhost','root','1234','fdtest') # cursor()cursor cursor = db.cursor() # SQL sql = """INSERT INTO EMPLOYEE( FIRST_NAME,LAST_NAME,AGE,SEX,INCOME) VALUES('Mac2','Mohan2',20,'M',6000)""" """ sql = "INSERT INTO EMPLOYEE(FIRST_NAME, \ LAST_NAME, AGE, SEX, INCOME) \ VALUES ('%s', '%s', '%d', '%c', '%d' )" % \ ('Mac', 'Mohan', 20, 'M', 2000) """ try: # sql cursor.execute(sql) # db.commit() except: # db.rollback() # db.close()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 18, 198, 2, 48761, 62, 20123, 316, 540, 13, 9078, 198, 198, 11748, 279, 4948, 893, 13976, 198, 198, 2, 220, 198, 9945, 796, 279, 4948, 893, 13976, 13, 8443, 10786, 36750, 41707, 15763, 41707, 10...
2.010989
273
import os import subprocess import threading mutex = threading.Lock()
[ 11748, 28686, 198, 11748, 850, 14681, 198, 11748, 4704, 278, 198, 198, 21973, 1069, 796, 4704, 278, 13, 25392, 3419, 628 ]
3.428571
21
from ubuntui.utils import Padding from ubuntui.widgets.hr import HR from conjureup.app_config import app from conjureup.ui.views.base import BaseView, SchemaFormView from conjureup.ui.widgets.selectors import MenuSelectButtonList
[ 6738, 20967, 2797, 9019, 13, 26791, 1330, 350, 26872, 198, 6738, 20967, 2797, 9019, 13, 28029, 11407, 13, 11840, 1330, 15172, 198, 198, 6738, 11644, 495, 929, 13, 1324, 62, 11250, 1330, 598, 198, 6738, 11644, 495, 929, 13, 9019, 13, 3...
3.236111
72
""" SleekXMPP: The Sleek XMPP Library Copyright (C) 2010 Nathanael C. Fritz This file is part of SleekXMPP. See the file LICENSE for copying permission. """ __all__ = ['xep_0004', 'xep_0012', 'xep_0030', 'xep_0033', 'xep_0045', 'xep_0050', 'xep_0085', 'xep_0092', 'xep_0199', 'gmail_notify', 'xep_0060', 'xep_0202']
[ 37811, 198, 220, 220, 220, 19498, 988, 55, 7378, 47, 25, 383, 19498, 988, 1395, 7378, 47, 10074, 198, 220, 220, 220, 15069, 357, 34, 8, 3050, 32607, 2271, 417, 327, 13, 45954, 198, 220, 220, 220, 770, 2393, 318, 636, 286, 19498, 9...
2.04023
174
#!/usr/bin/env python3 import transactions import taxmap import db import settings import datetime import argparse import uuid import pickle import jsonpickle import logging import logging.handlers import traceback if __name__ == "__main__": main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 11748, 8945, 198, 11748, 1687, 8899, 198, 11748, 20613, 198, 11748, 6460, 198, 11748, 4818, 8079, 198, 11748, 1822, 29572, 198, 11748, 334, 27112, 198, 11748, 2298, 293, 198, 11748, ...
3.452055
73
from .problem import ContingentProblem as Problem from .. action import Action from .sensor import Sensor from . import errors
[ 6738, 764, 45573, 1330, 2345, 278, 298, 40781, 355, 20647, 198, 6738, 11485, 2223, 1330, 7561, 198, 6738, 764, 82, 22854, 1330, 35367, 198, 6738, 764, 1330, 8563, 198 ]
4.37931
29
sum = 0 for i in xrange(1,1001): sum = sum + i**i print sum % 10000000000
[ 16345, 796, 657, 198, 198, 1640, 1312, 287, 2124, 9521, 7, 16, 11, 47705, 2599, 198, 220, 220, 220, 2160, 796, 2160, 1343, 1312, 1174, 72, 198, 198, 4798, 2160, 4064, 1802, 8269, 198 ]
2.352941
34
#!/usr/bin/python help_msg = 'get uniprot length of entire proteome' import os, sys CWD = os.getcwd() UTLTS_DIR = CWD[:CWD.index('proteomevis_scripts')]+'/proteomevis_scripts/utlts' sys.path.append(UTLTS_DIR) from parse_user_input import help_message from read_in_file import read_in from parse_data import organism from uniprot_api import UniProtAPI from output import writeout if __name__ == "__main__": args = help_message(help_msg, bool_add_verbose = True) d_ref = read_in('Entry', 'Gene names (ordered locus )', filename = 'proteome') uniprot_length = UniProtLength(args.verbose, d_ref) d_output = uniprot_length.run() if organism!='protherm': d_output = {d_ref[uniprot]: res for uniprot, res in d_output.iteritems()} xlabel = 'oln' else: #not supported for ProTherm xlabel = 'uniprot' writeout([xlabel, 'length'], d_output, filename = 'UniProt')
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 198, 16794, 62, 19662, 796, 705, 1136, 555, 541, 10599, 4129, 286, 2104, 5915, 462, 6, 198, 198, 11748, 28686, 11, 25064, 198, 198, 34, 22332, 796, 28686, 13, 1136, 66, 16993, 3419, 198, 38...
2.60177
339
""".""" # default packages import logging import pathlib import traceback import urllib.request as request # third party import pandas as pd import tqdm as tqdm_std # my packages import src.data.directory as directory # logger logger = logging.getLogger(__name__) def _main() -> None: """.""" logging.basicConfig(level=logging.INFO) filepath = get_raw_filepath() if filepath.exists() is False: url = get_raw_url() filepath.parent.mkdir(exist_ok=True, parents=True) with TqdmUpTo( unit="B", unit_scale=True, miniters=1, desc=filepath.name ) as pbar: request.urlretrieve( url, filename=filepath, reporthook=pbar.update_to, data=None ) else: logger.info(f"data already exists: {filepath}") # show dataset description. df = pd.read_csv(filepath) logger.info(df.info()) logger.info(df.head()) logger.info(df.tail()) if __name__ == "__main__": try: _main() except Exception as e: logger.error(e) logger.error(traceback.format_exc())
[ 37811, 526, 15931, 198, 2, 4277, 10392, 198, 11748, 18931, 198, 11748, 3108, 8019, 198, 11748, 12854, 1891, 198, 11748, 2956, 297, 571, 13, 25927, 355, 2581, 198, 198, 2, 2368, 2151, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 2...
2.307531
478
"""Primary application. """ import json import logging import logging.config import os import sys from flask import url_for, render_template, redirect, request from i_xero import Xero2 from i_xero.i_flask import FlaskInterface from utils import jsonify, serialize_model # initialize logging # The SlackBot app doesn't handle logging in the same way. # I tried to pass in a logger object from aracnid_logger, # but it seems to disable all loggers logging_filename = os.environ.get('LOGGING_CONFIG_FILE') command_dir = os.path.dirname(sys.argv[0]) logging_dir = os.path.join(os.getcwd(), command_dir) logging_path = os.path.join(os.getcwd(), logging_filename) with open(logging_path, 'rt') as file: logging_config = json.load(file) formatter = os.environ.get('LOGGING_FORMATTER') logging_config['handlers']['console']['formatter'] = formatter logging.config.dictConfig(logging_config) env_str = os.environ.get('LOG_UNHANDLED_EXCEPTIONS') LOG_UNHANDLED_EXCEPTIONS = env_str.lower() in ('true', 'yes') if env_str else False # configure flask application flask_app = FlaskInterface(__name__).get_app() # configure xero application xero_app = Xero2(flask_app) # start the app locally if __name__ == '__main__': flask_app.run(host='localhost', port=5000)
[ 37811, 35170, 3586, 13, 198, 37811, 198, 11748, 33918, 198, 11748, 18931, 198, 11748, 18931, 13, 11250, 198, 11748, 28686, 198, 11748, 25064, 198, 198, 6738, 42903, 1330, 19016, 62, 1640, 11, 8543, 62, 28243, 11, 18941, 11, 2581, 198, 6...
2.939675
431
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'F:\work\code\pyqt5\ui\main.ui' # # Created by: PyQt5 UI code generator 5.9 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets if __name__ == "__main__": import sys app = QtWidgets.QApplication(sys.argv) MainWindow = QtWidgets.QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show() sys.exit(app.exec_())
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 2, 5178, 7822, 7560, 422, 3555, 334, 72, 2393, 705, 37, 7479, 1818, 59, 8189, 59, 9078, 39568, 20, 59, 9019, 59, 12417, 13, 9019, 6, 198, 2, 198, 2, 15622, 41...
2.469388
196
# example.py import basic result = basic.add(1, 5) print(result)
[ 2, 1672, 13, 9078, 198, 198, 11748, 4096, 198, 198, 20274, 796, 4096, 13, 2860, 7, 16, 11, 642, 8, 198, 198, 4798, 7, 20274, 8, 198 ]
2.518519
27
import cocotb from cocotb.triggers import FallingEdge, RisingEdge, First, Timer, Event from ... import SpiSlaveBase, SpiConfig, SpiFrameError, SpiFrameTimeout
[ 198, 11748, 8954, 313, 65, 198, 6738, 8954, 313, 65, 13, 2213, 328, 5355, 1330, 42914, 37021, 11, 17658, 37021, 11, 3274, 11, 5045, 263, 11, 8558, 198, 6738, 2644, 1330, 1338, 72, 11122, 1015, 14881, 11, 1338, 72, 16934, 11, 1338, 7...
3.156863
51
from app import create_app,db from flask_script import Manager,Server from app.models import User,Comment,Blog from flask_migrate import Migrate, MigrateCommand #manage.shell # Creating app instance app = create_app('production') migrate = Migrate(app,db) manager = Manager(app) manager.add_command('db',MigrateCommand) manager.add_command('server',Server) if __name__== '__main__': manager.run() db.create_all()
[ 6738, 598, 1330, 2251, 62, 1324, 11, 9945, 198, 6738, 42903, 62, 12048, 1330, 9142, 11, 10697, 198, 6738, 598, 13, 27530, 1330, 11787, 11, 21357, 11, 42383, 198, 6738, 220, 42903, 62, 76, 42175, 1330, 337, 42175, 11, 337, 42175, 21575...
3.125
136
# -*- coding: utf-8 -*- # Generated by Django 1.11.7 on 2018-04-17 17:19 from __future__ import unicode_literals from django.db import migrations import django_extensions.db.fields
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2980, 515, 416, 37770, 352, 13, 1157, 13, 22, 319, 2864, 12, 3023, 12, 1558, 1596, 25, 1129, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, ...
2.772727
66
__author__ = 'Evan Cordell' __copyright__ = 'Copyright 2012-2015 Localmed, Inc.' __version__ = "0.1.6" __version_info__ = tuple(__version__.split('.')) __short_version__ = __version__
[ 834, 9800, 834, 796, 705, 36, 10438, 21119, 695, 6, 198, 834, 22163, 4766, 834, 796, 705, 15269, 2321, 12, 4626, 10714, 1150, 11, 3457, 2637, 628, 198, 834, 9641, 834, 796, 366, 15, 13, 16, 13, 21, 1, 198, 834, 9641, 62, 10951, ...
2.776119
67
from django.shortcuts import render, redirect from django.contrib.auth.forms import PasswordResetForm from django.core.mail import EmailMessage from django.template import loader from django.http import HttpResponse from django.contrib.auth.decorators import login_required from django.conf import settings from django.db.utils import IntegrityError from django.urls import reverse from django.template.loader import render_to_string, get_template from .forms import NewUserForm, NewAuditRecordForm from acl.models import Entitlement, PermitType from members.models import Tag, User, clean_tag_string, AuditRecord from mailinglists.models import Mailinglist, Subscription import logging import datetime import sys import re logger = logging.getLogger(__name__) def drop(request): if not request.user.can_escalate_to_priveleged: return HttpResponse("XS denied", status=403, content_type="text/plain") record = AuditRecord( user=request.user, final=True, action="Drop privs from webinterface" ) if request.user.is_privileged: record.changereason = f"DROP in webinterface by {request.user}" else: record.changereason = f"DROP in webinterface by {request.user} - but actual permission had already timed out." record.save() return redirect(request.META["HTTP_REFERER"])
[ 6738, 42625, 14208, 13, 19509, 23779, 1330, 8543, 11, 18941, 198, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 23914, 1330, 30275, 4965, 316, 8479, 198, 6738, 42625, 14208, 13, 7295, 13, 4529, 1330, 9570, 12837, 198, 198, 6738...
3.182898
421
# Copyright 2018 ZTE Corporation. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging from drf_yasg.utils import swagger_auto_schema from rest_framework import status from rest_framework.response import Response from rest_framework.views import APIView from lcm.ns.biz.ns_create import CreateNSService from lcm.ns.biz.ns_get import GetNSInfoService from lcm.ns.serializers.deprecated.ns_serializers import _CreateNsReqSerializer from lcm.ns.serializers.deprecated.ns_serializers import _CreateNsRespSerializer from lcm.ns.serializers.deprecated.ns_serializers import _QueryNsRespSerializer from lcm.pub.exceptions import NSLCMException from lcm.pub.exceptions import BadRequestException from lcm.pub.utils.values import ignore_case_get from .common import view_safe_call_with_log logger = logging.getLogger(__name__)
[ 2, 15069, 2864, 1168, 9328, 10501, 13, 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, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 198, 2, 921,...
3.473958
384
#!/usr/bin/env python3 import javalang
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 11748, 474, 9226, 648, 628, 628, 628 ]
2.5
18
import uuid import mongoengine as me from mist.api import config from mist.api.exceptions import BadRequestError from mist.api.users.models import Organization from mist.api.selectors.models import SelectorClassMixin from mist.api.rules.base import NoDataRuleController from mist.api.rules.base import ResourceRuleController from mist.api.rules.base import ArbitraryRuleController from mist.api.rules.models import RuleState from mist.api.rules.models import Window from mist.api.rules.models import Frequency from mist.api.rules.models import TriggerOffset from mist.api.rules.models import QueryCondition from mist.api.rules.models import BaseAlertAction from mist.api.rules.models import NotificationAction from mist.api.rules.plugins import GraphiteNoDataPlugin from mist.api.rules.plugins import GraphiteBackendPlugin from mist.api.rules.plugins import InfluxDBNoDataPlugin from mist.api.rules.plugins import InfluxDBBackendPlugin from mist.api.rules.plugins import ElasticSearchBackendPlugin from mist.api.rules.plugins import FoundationDBNoDataPlugin from mist.api.rules.plugins import FoundationDBBackendPlugin from mist.api.rules.plugins import VictoriaMetricsNoDataPlugin from mist.api.rules.plugins import VictoriaMetricsBackendPlugin class ArbitraryRule(Rule): """A rule defined by a single, arbitrary query string. Arbitrary rules permit the definition of complex query expressions by allowing users to define fully qualified queries in "raw mode" as a single string. In such case, a query expression may be a composite query that includes nested aggregations and/or additional queries. An `ArbitraryRule` must define a single `QueryCondition`, whose `target` defines the entire query expression as a single string. """ _controller_cls = ArbitraryRuleController class ResourceRule(Rule, SelectorClassMixin): """A rule bound to a specific resource type. Resource-bound rules are less elastic than arbitrary rules, but allow users to perform quick, more dynamic filtering given a resource object's UUID, tags, or model fields. Every subclass of `ResourceRule` MUST define its `selector_resource_cls` class attribute in order for queries to be executed against the intended mongodb collection. A `ResourceRule` may also apply to multiple resources, which depends on the rule's list of `selectors`. By default such a rule will trigger an alert if just one of its queries evaluates to True. """ _controller_cls = ResourceRuleController # FIXME All following properties are for backwards compatibility. def _populate_rules(): """Populate RULES with mappings from rule type to rule subclass. RULES is a mapping (dict) from rule types to subclasses of Rule. A rule's type is the concat of two strings: <str1>-<str2>, where str1 denotes whether the rule is arbitrary or not and str2 equals the `_data_type_str` class attribute of the rule, which is simply the type of the requesting data, like logs or monitoring metrics. The aforementioned concatenation is simply a way to categorize a rule, such as saying a rule on arbitrary logs or a resource-bound rule referring to the monitoring data of machine A. """ public_rule_map = {} hidden_rule_cls = (ArbitraryRule, ResourceRule, NoDataRule, ) for key, value in list(globals().items()): if not key.endswith('Rule'): continue if value in hidden_rule_cls: continue if not issubclass(value, (ArbitraryRule, ResourceRule, )): continue str1 = 'resource' if issubclass(value, ResourceRule) else 'arbitrary' rule_key = '%s-%s' % (str1, value._data_type_str) public_rule_map[rule_key] = value return public_rule_map RULES = _populate_rules()
[ 11748, 334, 27112, 198, 11748, 285, 25162, 18392, 355, 502, 198, 198, 6738, 4020, 13, 15042, 1330, 4566, 198, 198, 6738, 4020, 13, 15042, 13, 1069, 11755, 1330, 7772, 18453, 12331, 198, 198, 6738, 4020, 13, 15042, 13, 18417, 13, 27530, ...
3.376646
1,139
# -*- coding: utf-8 -*- import codecs from os.path import abspath from os.path import dirname from os.path import join from setuptools import find_packages from setuptools import setup import oidc_rp def read_relative_file(filename): """ Returns contents of the given file, whose path is supposed relative to this module. """ with codecs.open(join(dirname(abspath(__file__)), filename), encoding='utf-8') as f: return f.read() setup( name='django-oidc-rp', version=oidc_rp.__version__, author='impak Finance', author_email='tech@impakfinance.com', packages=find_packages(exclude=['tests.*', 'tests']), include_package_data=True, url='https://github.com/impak-finance/django-oidc-rp', license='MIT', description='A server side OpenID Connect Relying Party (RP/Client) implementation for Django.', long_description=read_relative_file('README.rst'), keywords='django openidconnect oidc client rp authentication auth', zip_safe=False, install_requires=[ 'django>=1.11', 'jsonfield2', 'pyjwkest>=1.4', 'requests>2.0', ], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', ], )
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 11748, 40481, 82, 198, 6738, 28686, 13, 6978, 1330, 2352, 6978, 198, 6738, 28686, 13, 6978, 1330, 26672, 3672, 198, 6738, 28686, 13, 6978, 1330, 4654, 198, 6738, 90...
2.612403
645
from nndet.evaluator.detection.froc import FROCMetric from nndet.evaluator.detection.coco import COCOMetric from nndet.evaluator.detection.hist import PredictionHistogram
[ 6738, 299, 358, 316, 13, 18206, 84, 1352, 13, 15255, 3213, 13, 69, 12204, 1330, 8782, 4503, 9171, 1173, 198, 6738, 299, 358, 316, 13, 18206, 84, 1352, 13, 15255, 3213, 13, 66, 25634, 1330, 327, 4503, 2662, 19482, 198, 6738, 299, 358...
2.948276
58
# from ankisync2.apkg import Apkg, db # Has to be done through normal database methods # def test_update(): # apkg = Apkg("example1.apkg") # for n in db.Notes.filter(db.Notes.data["field1"] == "data1"): # n.data["field3"] = "data2" # n.save() # apkg.close()
[ 2, 422, 16553, 271, 13361, 17, 13, 499, 10025, 1330, 5949, 10025, 11, 20613, 198, 198, 2, 7875, 284, 307, 1760, 832, 3487, 6831, 5050, 198, 2, 825, 1332, 62, 19119, 33529, 198, 2, 220, 220, 220, 220, 2471, 10025, 796, 5949, 10025, ...
2.223077
130
import torch import torch.nn as nn from torchvision.datasets.vision import VisionDataset from PIL import Image import os, sys, math import os.path import torch import json import torch.utils.model_zoo as model_zoo from Yolo_v2_pytorch.src.utils import * from Yolo_v2_pytorch.src.yolo_net import Yolo from Yolo_v2_pytorch.src.yolo_tunning import YoloD import numpy as np import torch.nn.functional as F from Yolo_v2_pytorch.src.rois_utils import anchorboxes from Yolo_v2_pytorch.src.anotherMissOh_dataset import FaceCLS from lib.person_model import person_model label_dict = {'' : 9, 'beach':0, 'cafe':1, 'car':2, 'convenience store':3, 'garden':4, 'home':5, 'hospital':6, 'kitchen':7, 'livingroom':8, 'none':9, 'office':10, 'park':11, 'playground':12, 'pub':13, 'restaurant':14, 'riverside':15, 'road':16, 'rooftop':17, 'room':18, 'studio':19, 'toilet':20, 'wedding hall':21 } label_dict_wo_none = {'beach':0, 'cafe':1, 'car':2, 'convenience store':3, 'garden':4, 'home':5, 'hospital':6, 'kitchen':7, 'livingroom':8, 'none':9, 'office':10, 'park':11, 'playground':12, 'pub':13, 'restaurant':14, 'riverside':15, 'road':16, 'rooftop':17, 'room':18, 'studio':19, 'toilet':20, 'wedding hall':21 } def conv3x3(in_planes, out_planes, stride=1): """3x3 convolution with padding""" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False) def accuracy(output, target, topk=(1,)): """Computes the accuracy over the k top predictions for the specified values of k""" with torch.no_grad(): maxk = max(topk) batch_size = target.size(0) _, pred = output.topk(maxk, 1, True, True) pred = pred.t() correct = pred.eq(target.view(1, -1).expand_as(pred)) res = [] for k in topk: correct_k = correct[:k].view(-1).float().sum(0, keepdim=True) res.append(correct_k.mul_(100.0 / batch_size)) return res sample_default = [105, 462, 953, 144, 108, 13, 123, 510, 1690, 19914, 1541, 126, 67, 592, 1010, 53, 2087, 0, 1547, 576, 74, 0] def CB_loss(labels, logits, beta=0.99, gamma=0.5, samples_per_cls=sample_default, no_of_classes=22, loss_type='softmax'): """Compute the Class Balanced Loss between `logits` and the ground truth `labels`. Class Balanced Loss: ((1-beta)/(1-beta^n))*Loss(labels, logits) where Loss is one of the standard losses used for Neural Networks. Args: labels: A int tensor of size [batch]. logits: A float tensor of size [batch, no_of_classes]. samples_per_cls: A python list of size [no_of_classes]. no_of_classes: total number of classes. int loss_type: string. One of "sigmoid", "focal", "softmax". beta: float. Hyperparameter for Class balanced loss. gamma: float. Hyperparameter for Focal loss. Returns: cb_loss: A float tensor representing class balanced loss """ effective_num = 1.0 - np.power(beta, samples_per_cls) weights = (1.0 - beta) / np.array(effective_num) weights = weights / np.sum(weights) * no_of_classes labels_one_hot = F.one_hot(labels, no_of_classes).cpu().float() weights = torch.tensor(weights).float() weights = weights.unsqueeze(0) weights = weights.repeat(labels_one_hot.shape[0],1) * labels_one_hot weights = weights.sum(1) weights = weights.unsqueeze(1) weights = weights.repeat(1,no_of_classes) if loss_type == "focal": cb_loss = focal_loss(labels_one_hot.cuda(), logits, weights.cuda(), gamma) elif loss_type == "sigmoid": cb_loss = F.binary_cross_entropy_with_logits(input = logits,target = labels_one_hot, weights = weights) elif loss_type == "softmax": pred = logits.softmax(dim = 1) cb_loss = F.binary_cross_entropy(input = pred, target = labels_one_hot.cuda(), weight = weights.cuda()) return cb_loss def focal_loss(labels, logits, alpha, gamma): """Compute the focal loss between `logits` and the ground truth `labels`. Focal loss = -alpha_t * (1-pt)^gamma * log(pt) where pt is the probability of being classified to the true class. pt = p (if true class), otherwise pt = 1 - p. p = sigmoid(logit). Args: labels: A float tensor of size [batch, num_classes]. logits: A float tensor of size [batch, num_classes]. alpha: A float tensor of size [batch_size] specifying per-example weight for balanced cross entropy. gamma: A float scalar modulating loss from hard and easy examples. Returns: focal_loss: A float32 scalar representing normalized total loss. """ BCLoss = F.binary_cross_entropy_with_logits(input = logits, target = labels,reduction = "none") if gamma == 0.0: modulator = 1.0 else: modulator = torch.exp(-gamma * labels * logits - gamma * torch.log(1 + torch.exp(-1.0 * logits))) loss = modulator * BCLoss weighted_loss = alpha * loss focal_loss = torch.sum(weighted_loss) focal_loss /= torch.sum(labels) return focal_loss
[ 11748, 28034, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 6738, 28034, 10178, 13, 19608, 292, 1039, 13, 10178, 1330, 19009, 27354, 292, 316, 198, 6738, 350, 4146, 1330, 7412, 198, 11748, 28686, 11, 25064, 11, 10688, 198, 11748, 286...
2.466374
2,052
""" Challenge Exercises for Chapter 1. """ import random import timeit from algs.table import DataTable, ExerciseNum, caption from algs.counting import RecordedItem def partition(A, lo, hi, idx): """ Partition using A[idx] as value. Note lo and hi are INCLUSIVE on both ends and idx must be valid index. Count the number of comparisons by populating A with RecordedItem instances. """ if lo == hi: return lo A[idx],A[lo] = A[lo],A[idx] # swap into position i = lo j = hi + 1 while True: while True: i += 1 if i == hi: break if A[lo] < A[i]: break while True: j -= 1 if j == lo: break if A[j] < A[lo]: break # doesn't count as comparing two values if i >= j: break A[i],A[j] = A[j],A[i] A[lo],A[j] = A[j],A[lo] return j def linear_median(A): """ Efficient implementation that returns median value in arbitrary list, assuming A has an odd number of values. Note this algorithm will rearrange values in A. """ # if len(A) % 2 == 0: # raise ValueError('linear_median() only coded to work with odd number of values.') lo = 0 hi = len(A) - 1 mid = hi // 2 while lo < hi: idx = random.randint(lo, hi) # select valid index randomly j = partition(A, lo, hi, idx) if j == mid: return A[j] if j < mid: lo = j+1 else: hi = j-1 return A[lo] def counting_sort(A, M): """ Update A in place to be sorted in ascending order if all elements are guaranteed to be in the range 0 to and not including M. """ counts = [0] * M for v in A: counts[v] += 1 pos = 0 v = 0 while pos < len(A): for idx in range(counts[v]): A[pos+idx] = v pos += counts[v] v += 1 def counting_sort_improved(A,M): """ Update A in place to be sorted in ascending order if all elements are guaranteed to be in the range 0 to and not including M. """ counts = [0] * M for val in A: counts[val] += 1 pos = 0 val = 0 while pos < len(A): if counts[val] > 0: A[pos:pos+counts[val]] = [val] * counts[val] pos += counts[val] val += 1 def run_counting_sort_trials(max_k=15, output=True): """Generate table for counting sort up to (but not including) max_k=15.""" tbl = DataTable([8,15,15], ['N', 'counting_sort', 'counting_sort_improved'], output=output) M = 20 # arbitrary value, and results are dependent on this value. trials = [2**k for k in range(8, max_k)] for n in trials: t_cs = min(timeit.repeat(stmt='counting_sort(a,{})\nis_sorted(a)'.format(M), setup=''' import random from ch01.challenge import counting_sort from algs.sorting import is_sorted w = [{0}-1] * {1} b = [0] * {1} a = list(range({0})) * {1} random.shuffle(a)'''.format(M,n), repeat=100, number=1)) t_csi = min(timeit.repeat(stmt='counting_sort_improved(a,{})\nis_sorted(a)'.format(M), setup=''' import random from ch01.challenge import counting_sort_improved from algs.sorting import is_sorted w = [{0}-1] * {1} b = [0] * {1} a = list(range({0})) * {1} random.shuffle(a)'''.format(M,n), repeat=100, number=1)) tbl.row([n, t_cs, t_csi]) return tbl def run_median_trial(): """Generate table for Median Trial.""" tbl = DataTable([10,15,15],['N', 'median_time', 'sort_median']) trials = [2**k+1 for k in range(8,20)] for n in trials: t_med = 1000*min(timeit.repeat(stmt='assert(linear_median(a) == {}//2)'.format(n), setup=''' import random from ch01.challenge import linear_median a = list(range({})) random.shuffle(a) '''.format(n), repeat=10, number=5))/5 t_sort = 1000*min(timeit.repeat(stmt='assert(median_from_sorted_list(a) == {0}//2)'.format(n), setup=''' import random from ch01.challenge import median_from_sorted_list a = list(range({})) random.shuffle(a) '''.format(n), repeat=10, number=5))/5 tbl.row([n, t_med, t_sort]) return tbl def run_median_less_than_trial(max_k=20, output=True): """Use RecordedItem to count # of times Less-than invoked up to (but not including) max_k=20.""" tbl = DataTable([10,15,15],['N', 'median_count', 'sort_median_count'], output=output) tbl.format('median_count', ',d') tbl.format('sort_median_count', ',d') trials = [2**k+1 for k in range(8, max_k)] for n in trials: A = list([RecordedItem(i) for i in range(n)]) random.shuffle(A) # Generated external sorted to reuse list RecordedItem.clear() med2 = median_from_sorted_list(A) sort_lt = RecordedItem.report()[1] RecordedItem.clear() med1 = linear_median(A) lin_lt = RecordedItem.report()[1] assert med1 == med2 tbl.row([n, lin_lt, sort_lt]) return tbl def is_palindrome1(w): """Create slice with negative step and confirm equality with w.""" return w[::-1] == w def is_palindrome2(w): """Strip outermost characters if same, return false when mismatch.""" while len(w) > 1: if w[0] != w[-1]: # if mismatch, return False return False w = w[1:-1] # strip characters on either end; repeat return True # must have been a Palindrome def is_palindrome3(w): """iterate from start and from end and compare, without copying arrays""" for i in range(0,round(len(w)/2)): if w[i] != w[-(i+1)]: return False return True # must have been a Palindrome def is_palindrome_letters_only(s): """ Confirm Palindrome, even when string contains non-alphabet letters and ignore capitalization. casefold() method, which was introduced in Python 3.3, could be used instead of this older method, which converts to lower(). """ i = 0 j = hi = len(s) - 1 while i < j: # This type of logic appears in partition. # Find alpha characters and compare while not s[i].isalpha(): i += 1 if i == hi: break while not s[j].isalpha(): j -= 1 if j == 0: break if s[i].lower() != s[j].lower(): return False i += 1 j -= 1 return True def tournament_allows_odd(A): """ Returns two largest values in A. Works for odd lists """ from ch01.largest_two import Match if len(A) < 2: raise ValueError('Must have at least two values') tourn = [] for i in range(0, len(A)-1, 2): tourn.append(Match(A[i], A[i+1])) odd_one_out = None if len(A) % 2 == 1: odd_one_out = A[-1] while len(tourn) > 1: tourn.append(Match.advance(tourn[0], tourn[1])) del tourn[0:2] # Find where second is hiding! m = tourn[0] largest = m.larger second = m.smaller # Wait until the end, and see where it belongs if odd_one_out: if odd_one_out > largest: largest,second = odd_one_out,largest elif odd_one_out > second: second = odd_one_out while m.prior: m = m.prior if second < m.smaller: second = m.smaller return (largest,second) def two_largest_attempt(A): """Failed attempt to implement two largest.""" m1 = max(A[:len(A)//2]) m2 = max(A[len(A)//2:]) if m1 < m2: return (m2, m1) return (m1, m2) ####################################################################### if __name__ == '__main__': chapter = 1 with ExerciseNum(1) as exercise_number: sample = 'A man, a plan, a canal. Panama!' print(sample,'is a palindrome:', is_palindrome_letters_only(sample)) print(caption(chapter, exercise_number), 'Palindrome Detector') with ExerciseNum(2) as exercise_number: run_median_less_than_trial() print() run_median_trial() print(caption(chapter, exercise_number), 'Median Counting') with ExerciseNum(3) as exercise_number: run_counting_sort_trials() print(caption(chapter, exercise_number), 'Counting Sort Trials') with ExerciseNum(4) as exercise_number: print('see tournament_allows_odd in ch01.challenge') print(caption(chapter, exercise_number), 'Odd tournament') with ExerciseNum(5) as exercise_number: print('Should print (9, 8)', two_largest_attempt([9, 3, 5, 7, 8, 1])) print('Fails to print (9, 8)', two_largest_attempt([9, 8, 5, 7, 3, 1])) print(caption(chapter, exercise_number), 'Failed Two largest')
[ 37811, 198, 41812, 3540, 1475, 2798, 2696, 329, 7006, 352, 13, 198, 37811, 198, 198, 11748, 4738, 198, 11748, 640, 270, 198, 198, 6738, 435, 14542, 13, 11487, 1330, 6060, 10962, 11, 32900, 33111, 11, 8305, 198, 6738, 435, 14542, 13, 9...
2.201481
4,050
from typing import Dict from exaslct_src.lib.data.image_info import ImageInfo from exaslct_src.lib.data.dependency_collector.dependency_collector import DependencyInfoCollector IMAGE_INFO = "image_info"
[ 6738, 19720, 1330, 360, 713, 198, 198, 6738, 409, 292, 75, 310, 62, 10677, 13, 8019, 13, 7890, 13, 9060, 62, 10951, 1330, 7412, 12360, 198, 6738, 409, 292, 75, 310, 62, 10677, 13, 8019, 13, 7890, 13, 45841, 1387, 62, 33327, 273, 1...
3
69
# Copyright 2017 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for tensorflow_transform.test_case.""" import re from tensorflow_transform import test_case import unittest if __name__ == '__main__': unittest.main()
[ 2, 15069, 2177, 3012, 3457, 13, 1439, 6923, 33876, 13, 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, 428, 2393, 2845, 287, 11846, 351, 262, 13789, ...
3.603774
212
# -*- coding: utf-8 -*- # Copyright (c) 2013 Australian Government, Department of the Environment # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. ''' base 64 encoded gif images for the GUI buttons '''
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 201, 198, 2, 15069, 357, 66, 8, 2211, 6638, 5070, 11, 2732, 286, 262, 9344, 201, 198, 2, 201, 198, 2, 2448, 3411, 318, 29376, 7520, 11, 1479, 286, 3877, 11, 284, 597, 1...
3.621701
341
import torch import pytest # NOTE: also registers the KL divergence from chmp.torch_utils import NormalModule, WeightsHS, fixed
[ 11748, 28034, 198, 11748, 12972, 9288, 198, 198, 2, 24550, 25, 635, 28441, 262, 48253, 43366, 198, 6738, 442, 3149, 13, 13165, 354, 62, 26791, 1330, 14435, 26796, 11, 775, 2337, 7998, 11, 5969, 628, 628, 198 ]
3.594595
37
from decimal import Decimal from unittest import TestCase from hummingbot.core.utils.fixed_rate_source import FixedRateSource
[ 6738, 32465, 1330, 4280, 4402, 198, 6738, 555, 715, 395, 1330, 6208, 20448, 198, 198, 6738, 41465, 13645, 13, 7295, 13, 26791, 13, 34021, 62, 4873, 62, 10459, 1330, 10832, 32184, 7416, 628 ]
3.878788
33
import torch from torch_geometric.data import Data from graphnet.components.pool import group_pulses_to_dom, group_pulses_to_pmt, sum_pool_and_distribute from graphnet.data.constants import FEATURES from graphnet.models.detector.detector import Detector
[ 11748, 28034, 198, 6738, 28034, 62, 469, 16996, 13, 7890, 1330, 6060, 198, 198, 6738, 4823, 3262, 13, 5589, 3906, 13, 7742, 1330, 1448, 62, 79, 5753, 274, 62, 1462, 62, 3438, 11, 1448, 62, 79, 5753, 274, 62, 1462, 62, 4426, 83, 11...
3.17284
81
import re t1 = 'Data !@[value1] and also !@[system:uptime] testing.' print("Content: " + t1) if re.search('!@\[[_a-zA-Z0-9:]*\]', t1): print("YES") else: print("NO") o = re.sub('!@\[[_a-zA-Z0-9:]*\]', '_B9yPrsE_\\g<0>_B9yPrsE_', t1) o2 = o.split("_B9yPrsE_") for i in o2: if i.startswith("!@["): i2 = re.sub('[^\w:]', "", i) print("Parse: " + str(i) + " " +str(i2)) else: print("Plain: '" + str(i) + "'")
[ 11748, 302, 198, 198, 83, 16, 796, 705, 6601, 5145, 31, 58, 8367, 16, 60, 290, 635, 5145, 31, 58, 10057, 25, 37623, 524, 60, 4856, 2637, 198, 198, 4798, 7203, 19746, 25, 366, 1343, 256, 16, 8, 198, 198, 361, 302, 13, 12947, 1078...
1.717557
262
############################################################################## # Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-647188 # # For details, see https://github.com/spack/spack # Please also see the NOTICE and LICENSE files for our notice and the LGPL. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License (as # published by the Free Software Foundation) version 2.1, February 1999. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and # conditions of the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ############################################################################## from spack import *
[ 29113, 29113, 7804, 4242, 2235, 198, 2, 15069, 357, 66, 8, 2211, 12, 5539, 11, 13914, 45036, 3549, 2351, 4765, 11, 11419, 13, 198, 2, 21522, 771, 379, 262, 13914, 45036, 3549, 2351, 18643, 13, 198, 2, 198, 2, 770, 2393, 318, 636, ...
4.077922
308
# License: BSD 3 clause import os import numpy as np import scipy from tick.array.build.array import ( tick_float_array_to_file, tick_float_array2d_to_file, tick_float_sparse2d_to_file, tick_double_array_to_file, tick_double_array2d_to_file, tick_double_sparse2d_to_file, tick_float_array_from_file, tick_float_array2d_from_file, tick_float_sparse2d_from_file, tick_double_array_from_file, tick_double_array2d_from_file, tick_double_sparse2d_from_file, ) def serialize_array(array, filepath): """Save an array on disk on a format that tick C++ modules can read This method is intended to be used by developpers only, mostly for benchmarking in C++ on real datasets imported from Python Parameters ---------- array : `np.ndarray` or `scipy.sparse.csr_matrix` 1d or 2d array filepath : `str` Path where the array will be stored Returns ------- path : `str` Global path of the serialized array """ if array.dtype not in [np.float32, np.float64]: raise ValueError('Only float32/64 arrays can be serrialized') if array.dtype == "float32": if isinstance(array, np.ndarray): if len(array.shape) == 1: serializer = tick_float_array_to_file elif len(array.shape) == 2: serializer = tick_float_array2d_to_file else: raise ValueError('Only 1d and 2d arrays can be serrialized') else: if len(array.shape) == 2: serializer = tick_float_sparse2d_to_file else: raise ValueError('Only 2d sparse arrays can be serrialized') elif array.dtype == "float64" or array.dtype == "double": if isinstance(array, np.ndarray): if len(array.shape) == 1: serializer = tick_double_array_to_file elif len(array.shape) == 2: serializer = tick_double_array2d_to_file else: raise ValueError('Only 1d and 2d arrays can be serrialized') else: if len(array.shape) == 2: serializer = tick_double_sparse2d_to_file else: raise ValueError('Only 2d sparse arrays can be serrialized') else: raise ValueError('Unhandled serrialization type') serializer(filepath, array) return os.path.abspath(filepath) def load_array(filepath, array_type='dense', array_dim=1, dtype="float64"): """Loaf an array from disk from a format that tick C++ modules can read This method is intended to be used by developpers only, mostly for benchmarking in C++ on real datasets imported from Python Parameters ---------- filepath : `str` Path where the array was stored array_type : {'dense', 'sparse'}, default='dense' Expected type of the array array_dim : `int` Expected dimension of the array Returns ------- array : `np.ndarray` or `scipy.sparse.csr_matrix` 1d or 2d array """ abspath = os.path.abspath(filepath) if not os.path.exists(filepath): raise FileNotFoundError('File {} does not exists'.format(abspath)) if dtype == "float32": if array_type == 'dense': if array_dim == 1: reader = tick_float_array_from_file elif array_dim == 2: reader = tick_float_array2d_from_file else: raise ValueError('Only 1d and 2d arrays can be loaded') elif array_type == 'sparse': if array_dim == 2: reader = tick_float_sparse2d_from_file else: raise ValueError('Only 2d sparse arrays can be loaded') else: raise ValueError('Cannot load this class of array') elif dtype == "float64" or dtype == "double": if array_type == 'dense': if array_dim == 1: reader = tick_double_array_from_file elif array_dim == 2: reader = tick_double_array2d_from_file else: raise ValueError('Only 1d and 2d arrays can be loaded') elif array_type == 'sparse': if array_dim == 2: reader = tick_double_sparse2d_from_file else: raise ValueError('Only 2d sparse arrays can be loaded') else: raise ValueError('Cannot load this class of array') else: raise ValueError('Unhandled serrialization type') return reader(filepath)
[ 2, 13789, 25, 347, 10305, 513, 13444, 198, 198, 11748, 28686, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 629, 541, 88, 198, 198, 6738, 4378, 13, 18747, 13, 11249, 13, 18747, 1330, 357, 198, 220, 220, 220, 4378, 62, 22468, ...
2.215772
2,067
__all__=["factory","frontend","lib","tools","creation","install","unittests"]
[ 834, 439, 834, 28, 14692, 69, 9548, 2430, 8534, 437, 2430, 8019, 2430, 31391, 2430, 38793, 2430, 17350, 2430, 403, 715, 3558, 8973, 198 ]
3.25
24
import dearpygui.dearpygui as dpg import datetime as dt import math from registry import * SUN_DATA.update_date() # FUNCTIONS # MAIN FUNCTIONS
[ 11748, 390, 5117, 88, 48317, 13, 67, 451, 9078, 48317, 355, 288, 6024, 220, 198, 11748, 4818, 8079, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 355, 288, 83, 198, 11748, 10688, 220, 198, 198, 6738, 20478, 220, 220, 220, ...
2.107143
84
""" Copyright 2019 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import config import time # for jwt signing. see https://google-auth.readthedocs.io/en/latest/reference/google.auth.jwt.html#module-google.auth.jwt from google.auth import crypt as cryptGoogle from google.auth import jwt as jwtGoogle ############################# # # class that defines JWT format for a Google Pay Pass. # # to check the JWT protocol for Google Pay Passes, check: # https://developers.google.com/pay/passes/reference/s2w-reference#google-pay-api-for-passes-jwt # # also demonstrates RSA-SHA256 signing implementation to make the signed JWT used # in links and buttons. Learn more: # https://developers.google.com/pay/passes/guides/get-started/implementing-the-api/save-to-google-pay # #############################
[ 37811, 198, 15269, 13130, 3012, 3457, 13, 1439, 6923, 33876, 13, 198, 198, 26656, 15385, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 5832, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13...
3.524064
374
# Includes some code derived from the cpython project. # Source: https://github.com/python/cpython/blob/master/Lib/zipfile.py # Excuse the mess. import argparse from hashlib import sha1 import os import struct from zipfile import _EndRecData, ZipFile from zlib import adler32 _ECD_SIGNATURE = 0 _ECD_DISK_NUMBER = 1 _ECD_DISK_START = 2 _ECD_ENTRIES_THIS_DISK = 3 _ECD_ENTRIES_TOTAL = 4 _ECD_SIZE = 5 _ECD_OFFSET = 6 _ECD_COMMENT_SIZE = 7 structEndArchive = b"<4s4H2LH" stringEndArchive = b"PK\005\006" structCentralDir = "<4s4B4HL2L5H2L" stringCentralDir = b"PK\001\002" _DEX_MAGIC = 0 _DEX_CHECKSUM = 1 _DEX_SIGNATURE = 2 _DEX_FILE_SIZE = 3 structDexHeader = "<8sI20sI" parser = argparse.ArgumentParser(description="Creates an APK exploiting the Janus vulnerability.") parser.add_argument("apk_in", metavar="original-apk", type=str, help="the source apk to use") parser.add_argument("dex_in", metavar="dex-file", type=str, help="the dex file to prepend") parser.add_argument("apk_out", metavar="output-apk", type=str, help="the file to output to") args = parser.parse_args() with ZipFile(args.apk_in, "r") as apk_in_zip, open(args.apk_in, "rb") as apk_in, open(args.dex_in, "rb") as dex_in, open(args.apk_out, "wb") as apk_out: dex_data = dex_in.read() dex_header = get_dex_header(dex_data) dex_size = os.path.getsize(args.dex_in) orig_endrec = get_endrec(apk_in) new_endrec = get_endrec(apk_in) new_endrec[_ECD_OFFSET] = new_endrec[_ECD_OFFSET] + dex_size final_size = os.path.getsize(args.apk_in) + dex_size apk_in_zip.filelist = sorted(apk_in_zip.filelist, key=sort_info) infolist = apk_in_zip.infolist() for info in infolist: info.date_time = (2042, 14, 3, 0, 62, 18) info.header_offset = info.header_offset + dex_size out_bytes = b"" out_bytes += dex_data[0x24:] out_bytes += apk_in.read()[:orig_endrec[_ECD_OFFSET]] out_bytes += get_centdirs(infolist) out_bytes += pack_endrec(new_endrec) out_bytes = make_dex_header(dex_header, out_bytes, final_size) + out_bytes apk_out.write(out_bytes)
[ 2, 29581, 617, 2438, 10944, 422, 262, 269, 29412, 1628, 13, 198, 2, 8090, 25, 3740, 1378, 12567, 13, 785, 14, 29412, 14, 13155, 7535, 14, 2436, 672, 14, 9866, 14, 25835, 14, 13344, 7753, 13, 9078, 198, 198, 2, 25268, 1904, 262, 20...
2.259454
952
ANNOUNCEMENT_ROLE = "941805571915513857" GUILD_ID = "878926572235665418"
[ 198, 22846, 2606, 7792, 12529, 62, 13252, 2538, 796, 366, 5824, 1507, 2713, 3553, 1129, 18742, 20107, 3553, 1, 198, 38022, 26761, 62, 2389, 796, 366, 23, 40401, 2075, 3553, 1828, 2327, 2791, 4051, 1507, 1, 198 ]
2
37
## ### Copyright (C) 2018-2019 Intel Corporation ### ### SPDX-License-Identifier: BSD-3-Clause ### from ....lib import * from ..util import * from .transcoder import TranscoderTest spec = load_test_spec("mpeg2", "transcode")
[ 2235, 198, 21017, 15069, 357, 34, 8, 2864, 12, 23344, 8180, 10501, 198, 21017, 198, 21017, 30628, 55, 12, 34156, 12, 33234, 7483, 25, 347, 10305, 12, 18, 12, 2601, 682, 198, 21017, 198, 198, 6738, 19424, 8019, 1330, 1635, 198, 6738, ...
3.026667
75
import os, time, mimetypes, glob from django.utils.translation import gettext_lazy as _ from django.urls import reverse from task.const import * from task.models import Task, detect_group from rusel.base.config import Config from rusel.base.forms import CreateGroupForm from rusel.context import get_base_context from rusel.utils import extract_get_params
[ 11748, 28686, 11, 640, 11, 17007, 2963, 12272, 11, 15095, 198, 6738, 42625, 14208, 13, 26791, 13, 41519, 1330, 651, 5239, 62, 75, 12582, 355, 4808, 198, 6738, 42625, 14208, 13, 6371, 82, 1330, 9575, 198, 6738, 4876, 13, 9979, 1330, 16...
3.57
100
import os,rootpath rootpath.append(pattern='main.py') # add the directory of main.py to PATH import glob from kivy.app import App from kivy.lang import Builder from kivy.properties import ObjectProperty,DictProperty,ListProperty from kivy.uix.boxlayout import BoxLayout import logging,importlib,pkgutil if __name__ == '__main__': Test().run()
[ 11748, 28686, 11, 15763, 6978, 198, 15763, 6978, 13, 33295, 7, 33279, 11639, 12417, 13, 9078, 11537, 1303, 751, 262, 8619, 286, 1388, 13, 9078, 284, 46490, 198, 11748, 15095, 198, 6738, 479, 452, 88, 13, 1324, 1330, 2034, 198, 6738, 4...
3.212963
108
import numpy as np
[ 11748, 299, 32152, 355, 45941, 628 ]
3.333333
6
import numpy as np from numba import guvectorize
[ 11748, 299, 32152, 355, 45941, 198, 6738, 997, 7012, 1330, 915, 31364, 1096, 628, 198 ]
3.4
15
import tcod from input_handlers import handle_keys from game_states import GameStates from render_functions import clear_all, render_all, RenderOrder from map_objects.game_map import GameMap from fov_functions import initialize_fov, recompute_fov from entity import Entity, get_blocking_entity_at_location from components.fighter import Fighter from death_functions import kill_monster, kill_player VERSION = "0.2" FONT = 'assets/arial10x10.png' screen_width = 80 screen_height = 50 map_width = 80 map_height = 45 room_max_size = 10 room_min_size = 6 max_rooms = 30 fov_algorithm = 0 fov_light_walls = False fov_radius = 10 max_monsters_per_room = 3 colors = { 'dark_wall': tcod.Color(0, 0, 0), 'light_wall': tcod.Color(120, 120, 80), 'dark_ground': tcod.Color(150, 150, 150), 'light_ground': tcod.Color(200, 200, 150) } def main(): """ Main game function """ fighter_component = Fighter(hp=30, defense=2, power=5) player = Entity(0, 0, '@', tcod.white, 'Player', blocks=True, render_order=RenderOrder.ACTOR, fighter=fighter_component) entities = [player] # Import font tcod.console_set_custom_font(FONT, tcod.FONT_TYPE_GREYSCALE | tcod.FONT_LAYOUT_TCOD) # Console initialization tcod.console_init_root(screen_width, screen_height, 'Pilferer %s'%VERSION, False, vsync=False) con = tcod.console.Console(screen_width, screen_height) # Mapping game_map = GameMap(map_width, map_height) game_map.make_map(max_rooms, room_min_size, room_max_size, map_width, map_height, player, entities, max_monsters_per_room) # FOV fov_recompute = True fov_map = initialize_fov(game_map) # Variables for holding input key = tcod.Key() mouse = tcod.Mouse() # Game state game_state = GameStates.PLAYERS_TURN # Main game loop while not tcod.console_is_window_closed(): # FOV if fov_recompute: recompute_fov(fov_map, player.x, player.y, fov_radius, fov_light_walls, fov_algorithm) # Draw render_all(con, entities, player, game_map, fov_map, fov_recompute, screen_width, screen_height, colors) fov_recompute = False tcod.console_flush() clear_all(con, entities) # INDPUT HANDLING tcod.sys_check_for_event(tcod.EVENT_KEY_PRESS, key, mouse) action = handle_keys(key) # Command move player_turn_results = [] move = action.get('move') if move and game_state == GameStates.PLAYERS_TURN: dx, dy = move destination_x = player.x + dx destination_y = player.y + dy if not game_map.is_blocked(destination_x, destination_y): target = get_blocking_entity_at_location(entities, destination_x, destination_y) if target: attack_results = player.fighter.attack(target) player_turn_results.extend(attack_results) else: player.move(dx, dy) fov_recompute = True game_state = GameStates.ENEMY_TURN # Command exit exit = action.get('exit') if exit: return True # Command Fullscreen fullscreen = action.get('fullscreen') if fullscreen: tcod.console_set_fullscreen(not tcod.console_is_fullscreen()) # Results for player_turn_result in player_turn_results: message = player_turn_result.get('message') dead_entity = player_turn_result.get('dead') if message: print(message) if dead_entity: if dead_entity == player: message, game_state = kill_player(dead_entity) else: message = kill_monster(dead_entity) print(message) # Monster turns if game_state == GameStates.ENEMY_TURN: for entity in entities: if entity.ai: enemy_turn_results = entity.ai.take_turn(player, fov_map, game_map, entities) for enemy_turn_result in enemy_turn_results: message = enemy_turn_result.get('message') dead_entity = enemy_turn_result.get('dead') if message: print(message) if dead_entity: if dead_entity == player: message, game_state = kill_player(dead_entity) else: message = kill_monster(dead_entity) print(message) if game_state == GameStates.PLAYER_DEAD: break if game_state == GameStates.PLAYER_DEAD: break else: game_state = GameStates.PLAYERS_TURN game_state = GameStates.PLAYERS_TURN if __name__ == '__main__': main()
[ 11748, 256, 19815, 198, 198, 6738, 5128, 62, 4993, 8116, 1330, 5412, 62, 13083, 198, 6738, 983, 62, 27219, 1330, 3776, 42237, 198, 198, 6738, 8543, 62, 12543, 2733, 1330, 1598, 62, 439, 11, 8543, 62, 439, 11, 46722, 18743, 198, 6738, ...
2.055936
2,485
# (c) 2012-2019, Ansible by Red Hat # # This file is part of Ansible Galaxy # # Ansible Galaxy is free software: you can redistribute it and/or modify # it under the terms of the Apache License as published by # the Apache Software Foundation, either version 2 of the License, or # (at your option) any later version. # # Ansible Galaxy 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 # Apache License for more details. # # You should have received a copy of the Apache License # along with Galaxy. If not, see <http://www.apache.org/licenses/>. from django.urls import path from galaxy.api.v2 import views app_name = 'api' urlpatterns = [ # Collection Imports URLs path('collection-imports/<int:pk>/', views.CollectionImportView.as_view(), name='collection-import-detail'), # Collection Version list URLs path('collections/<int:pk>/versions/', views.VersionListView.as_view(), name='version-list'), path('collections/<str:namespace>/<str:name>/versions/', views.VersionListView.as_view(), name='version-list'), # Collection Version detail URLs path('collection-versions/<int:version_pk>/', views.VersionDetailView.as_view(), name='version-detail'), path('collections/<str:namespace>/<str:name>/versions/<str:version>/', views.VersionDetailView.as_view(), name='version-detail'), # Collection Version Artifact download URLs path('collection-versions/<int:pk>/artifact/', views.CollectionArtifactView.as_view(), name='version-artifact'), path('collections/<namespace>/<name>/versions/<version>/artifact/', views.CollectionArtifactView.as_view(), name='version-artifact'), # Collection URLs path('collections/', views.CollectionListView.as_view(), name='collection-list'), path('collections/<int:pk>/', views.CollectionDetailView.as_view(), name='collection-detail'), # NOTE: needs to come after 'collections/<int:collection_pk>/versions/' path('collections/<str:namespace>/<str:name>/', views.CollectionDetailView.as_view(), name='collection-detail'), ]
[ 2, 357, 66, 8, 2321, 12, 23344, 11, 28038, 856, 416, 2297, 10983, 198, 2, 198, 2, 770, 2393, 318, 636, 286, 28038, 856, 9252, 198, 2, 198, 2, 28038, 856, 9252, 318, 1479, 3788, 25, 345, 460, 17678, 4163, 340, 290, 14, 273, 13096...
2.73014
856
# -*- coding: utf-8 -*- # Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and Contributors # See license.txt from __future__ import unicode_literals import frappe import unittest
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 15069, 357, 66, 8, 2177, 11, 39313, 27768, 21852, 18367, 83, 13, 12052, 13, 290, 25767, 669, 198, 2, 4091, 5964, 13, 14116, 198, 6738, 11593, 37443, 834, 1330, 2800...
3.033333
60
import logging import requests
[ 11748, 18931, 198, 11748, 7007 ]
6
5
#!/usr/bin/env python import rospy from std_msgs.msg import Float64 import random possibleLayers = [140, 50, 80, 200, 100] cur_position = 0.0 #Build the layers simulation, then publish material strengths. Lasts 100 seconds. #Get the strength of the next layer from the list of possible layer strengths. #Build the next layer of the simulation. if __name__ == '__main__': runLayersSim()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 11748, 686, 2777, 88, 198, 6738, 14367, 62, 907, 14542, 13, 19662, 1330, 48436, 2414, 198, 11748, 4738, 198, 198, 79, 4733, 43, 6962, 796, 685, 15187, 11, 2026, 11, 4019, 11, 939, 11...
3.15748
127
import scrapy import re from scrapy.linkextractors import LinkExtractor from scrapy.spiders import CrawlSpider, Rule from ..items import ImagescraperItem
[ 11748, 15881, 88, 198, 11748, 302, 198, 6738, 15881, 88, 13, 2815, 365, 742, 974, 669, 1330, 7502, 11627, 40450, 198, 6738, 15881, 88, 13, 2777, 4157, 1330, 327, 13132, 41294, 11, 14330, 198, 6738, 11485, 23814, 1330, 5382, 66, 38545, ...
3.604651
43
import os import argparse import subprocess import random import edlib from typing import List from collections import Counter import stanza parser = argparse.ArgumentParser(description='Evaluate analysis metrics') parser.add_argument('--prefix', type=str, choices=['inference', 'generation'], help='prediction file prefix') parser.add_argument('--exp-dir', type=str, help='output directory') args = parser.parse_args() fout = open(os.path.join(args.exp_dir, 'analysis_{}_res.txt'.format(args.prefix)), 'w') len_cut = 1000 prototypes, examples = read_file(os.path.join(args.exp_dir, '{}_analysis_input.txt'.format(args.prefix)), len_cut=len_cut) prototype_path = os.path.join(args.exp_dir, 'prototype.txt') prototype_pos_path = os.path.join(args.exp_dir, 'prototype_pos.txt') prototype_rand_path = os.path.join(args.exp_dir, 'prototype_rand.txt') prototype_pos_rand_path = os.path.join(args.exp_dir, 'prototype_pos_rand.txt') example_path = os.path.join(args.exp_dir, 'example.txt') example_pos_path = os.path.join(args.exp_dir, 'example_pos.txt') prototypes_rand = generate_rand_prototype(args.exp_dir, len(examples)) write_file(prototype_path, prototypes) write_file(example_path, examples) write_file(prototype_rand_path, prototypes_rand) # surface BLEU # bleu = subprocess.getoutput( # "./support_prototype/scripts/multi-bleu.perl {} < {}".format(prototype_path, example_rand_path)) bleu = sentence_bleu(prototype_rand_path, example_path) print('Regular BLEU (random baseline): \n{}'.format(bleu)) fout.write('Regular BLEU (random baseline): \n{}'.format(bleu)) fout.write('\n\n\n') # bleu = subprocess.getoutput( # "./support_prototype/scripts/multi-bleu.perl {} < {}".format(prototype_path, example_path)) bleu = sentence_bleu(prototype_path, example_path) print('Regular BLEU: \n{}'.format(bleu)) fout.write('Regular BLEU: \n{}'.format(bleu)) fout.write('\n\n\n') # POS tagging print('POS tagging') nlp = stanza.Pipeline(lang='en', processors='tokenize,mwt,pos', tokenize_pretokenized=True) prototype_doc = nlp('\n'.join(prototypes)) example_doc = nlp('\n'.join(examples)) prototype_rand_doc = nlp('\n'.join(prototypes_rand)) prototypes_pos = [[word.upos for word in sent.words] for sent in prototype_doc.sentences] examples_pos = [[word.upos for word in sent.words] for sent in example_doc.sentences] prototypes_pos_rand = [[word.upos for word in sent.words]for sent in prototype_rand_doc.sentences] write_file(prototype_pos_path, prototypes_pos) write_file(example_pos_path, examples_pos) write_file(prototype_pos_rand_path, prototypes_pos_rand) # POS BLEU # bleu = subprocess.getoutput( # "./support_prototype/scripts/multi-bleu.perl {} < {}".format(prototype_pos_path, example_pos_rand_path)) bleu = sentence_bleu(prototype_pos_rand_path, example_pos_path) print('POS BLEU (random baseline): \n{}'.format(bleu)) fout.write('POS BLEU (random baseline): \n{}'.format(bleu)) fout.write('\n\n\n') # bleu = subprocess.getoutput( # "./support_prototype/scripts/multi-bleu.perl {} < {}".format(prototype_pos_path, example_pos_path)) bleu = sentence_bleu(prototype_pos_path, example_pos_path) print('POS BLEU: \n{}'.format(bleu)) fout.write('POS BLEU: \n{}'.format(bleu)) fout.write('\n\n\n') # break down precision and recall print("compute precision, recall, f1") assert len(prototypes) == len(prototypes_pos) assert len(examples) == len(examples_pos) res = eval_f1(list(prototype_rand_doc.sentences), list(example_doc.sentences)) res = sorted(res.items(), key=lambda item: -item[1].f1) fout.write('random baseline precision-recall\n') fout.write('POS recall precision f1\n') for k, v in res: fout.write('{} {} {} {}\n'.format(k, v.recall, v.precision, v.f1)) fout.write('\n\n\n') res = eval_f1(list(prototype_doc.sentences), list(example_doc.sentences)) res = sorted(res.items(), key=lambda item: -item[1].f1) fout.write('precision-recall\n') fout.write('POS recall precision f1\n') for k, v in res: fout.write('{} {} {} {}\n'.format(k, v.recall, v.precision, v.f1)) fout.write('\n\n\n') # edit operations print("edit analysis") res = eval_edit(list(prototype_doc.sentences), list(example_doc.sentences)) total = sum([sum(v.values()) for k, v in res.items()]) fout.write('total: {}\n'.format(total)) res = sorted(res.items(), key=lambda item: (-sum(item[1].values()))) for k, v in res: fout.write('{}: {}\n'.format(k, sum(v.values()))) for k1, v1 in v.most_common(): fout.write('{}: {} ({:.3f}), '.format(k1, v1, v1 / sum(v.values()))) fout.write('\n\n') fout.close()
[ 11748, 28686, 198, 11748, 1822, 29572, 198, 11748, 850, 14681, 198, 11748, 4738, 198, 11748, 1225, 8019, 198, 6738, 19720, 1330, 7343, 198, 6738, 17268, 1330, 15034, 198, 198, 11748, 336, 35819, 628, 628, 628, 198, 198, 48610, 796, 1822, ...
2.65696
1,717
import pytest from thefuck.rules.git_stash_pop import get_new_command from thefuck.rules.git_stash_pop import match from thefuck.types import Command
[ 11748, 12972, 9288, 198, 198, 6738, 262, 31699, 13, 38785, 13, 18300, 62, 301, 1077, 62, 12924, 1330, 651, 62, 3605, 62, 21812, 198, 6738, 262, 31699, 13, 38785, 13, 18300, 62, 301, 1077, 62, 12924, 1330, 2872, 198, 6738, 262, 31699, ...
3.208333
48
""" The ARIMA model. """ import torch import numpy as np
[ 37811, 383, 5923, 3955, 32, 2746, 13, 37227, 198, 198, 11748, 28034, 198, 11748, 299, 32152, 355, 45941, 628 ]
3.105263
19
""" Sliding window Given a string S, return the number of substrings of length K with no repeated characters. Example 1: Input: S = "havefunonleetcode", K = 5 Output: 6 Explanation: There are 6 substrings they are : 'havef','avefu','vefun','efuno','etcod','tcode'. counter havefunonleetcode IDEA: 1) for each letter in the string setup a counter and 2) update unique counter each time when counter[let] hits 0, 1 or 2 (magic numbers) aaabac ||| 123 0) a:3 unique=0 1) a:2 b:1 unique=1 2) a:2 b:1 unique=1 3) a:2 b:1 c:1 unique=1+2=3 """
[ 37811, 220, 220, 220, 198, 220, 220, 3454, 2530, 4324, 198, 220, 220, 220, 198, 220, 220, 11259, 257, 4731, 311, 11, 1441, 262, 1271, 286, 850, 37336, 286, 4129, 509, 351, 645, 198, 220, 220, 5100, 3435, 13, 198, 220, 220, 220, 19...
2.219595
296
"""The File Propagator"""
[ 37811, 464, 9220, 8772, 363, 1352, 37811, 198 ]
3.25
8
#! /usr/bin/env python # -*- coding: utf-8 -*- # # Interpreter version: brython (http://brython.info) (like python3) # # Imports ===================================================================== from os.path import join from browser import window from browser import document # virtual filesystem / modules provided by REST API from virtual_fs import settings # Functions & classes ========================================================= UserKeywordHandler = KeywordListHandler("user_keyword_list") AlephKeywordHandler = KeywordListHandler("aleph_keyword_list") AanalysisKeywordHandler = KeywordListHandler("analysis_keyword_list") KeywordAdder.set_kw_typeahead_input()
[ 2, 0, 1220, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 2, 4225, 3866, 353, 2196, 25, 275, 563, 400, 261, 357, 4023, 1378, 65, 563, 400, 261, 13, 10951, 8, 357...
3.821229
179
from .grucell import MyGRUCell from .gru import MyGRU
[ 6738, 764, 48929, 3846, 1330, 2011, 10761, 9598, 695, 198, 6738, 764, 48929, 1330, 2011, 10761, 52 ]
3.117647
17
#!/usr/bin/python2.7 import os import KernelCollection # Check that weak binds can be missing, so long as we check for the magic symbol # [~]> xcrun -sdk iphoneos.internal cc -arch arm64 -Wl,-static -mkernel -nostdlib -Wl,-add_split_seg_info -Wl,-rename_section,__TEXT,__text,__TEXT_EXEC,__text -Wl,-e,__start -Wl,-pagezero_size,0x0 -Wl,-pie -Wl,-sectcreate,__LINKINFO,__symbolsets,SymbolSets.plist -Wl,-segprot,__LINKINFO,r--,r-- main.c -o main.kernel # [~]> xcrun -sdk iphoneos.internal cc -arch arm64 -Wl,-kext -mkernel -nostdlib -Wl,-add_split_seg_info foo.c -o extensions/foo.kext/foo # [~]> xcrun -sdk iphoneos.internal cc -arch arm64 -Wl,-kext -mkernel -nostdlib -Wl,-add_split_seg_info bar.c -o extensions/bar.kext/bar -Wl,-fixup_chains # [~]> rm -r extensions/*.kext/*.ld
[ 2, 48443, 14629, 14, 8800, 14, 29412, 17, 13, 22, 198, 198, 11748, 28686, 198, 11748, 32169, 36307, 198, 198, 2, 6822, 326, 4939, 37354, 460, 307, 4814, 11, 523, 890, 355, 356, 2198, 329, 262, 5536, 6194, 628, 198, 2, 685, 93, 60,...
2.339286
336
from elasticsearch_dsl import Boolean, Date, Double, Integer, Keyword, Long, Object, Text from datahub.search import dict_utils from datahub.search import fields from datahub.search.models import BaseESModel DOC_TYPE = 'investment_project' def _related_investment_project_field(): """Field for a related investment project.""" return Object(properties={ 'id': Keyword(), 'name': fields.NormalizedKeyword(), 'project_code': fields.NormalizedKeyword(), })
[ 6738, 27468, 12947, 62, 67, 6649, 1330, 41146, 11, 7536, 11, 11198, 11, 34142, 11, 7383, 4775, 11, 5882, 11, 9515, 11, 8255, 198, 198, 6738, 4818, 993, 549, 13, 12947, 1330, 8633, 62, 26791, 198, 6738, 4818, 993, 549, 13, 12947, 133...
3.061728
162
from collections import OrderedDict import torch from torch import nn
[ 6738, 17268, 1330, 14230, 1068, 35, 713, 198, 198, 11748, 28034, 198, 6738, 28034, 1330, 299, 77, 628 ]
4
18
#import import os #import torch #import torch.nn as nn import torch.utils.data as Data #import torchvision import matplotlib.pyplot as plt import h5py #from torch.autograd import Variable import numpy as np import torch #%hist -f rawdata_dataset.py
[ 2, 11748, 198, 11748, 28686, 198, 2, 11748, 28034, 198, 2, 11748, 28034, 13, 20471, 355, 299, 77, 198, 11748, 28034, 13, 26791, 13, 7890, 355, 6060, 198, 2, 11748, 28034, 10178, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458...
3.036585
82
from django.urls import path from . import views from .views import IndexView urlpatterns = [ # path('', views.index, name="index"), path('', IndexView.as_view(), name="index"), # path('create/', views.create, name="create"), path('create/', views.PythonCreateView.as_view(), name="create"), ]
[ 6738, 42625, 14208, 13, 6371, 82, 1330, 3108, 198, 6738, 764, 1330, 5009, 198, 6738, 764, 33571, 1330, 12901, 7680, 198, 198, 6371, 33279, 82, 796, 685, 198, 220, 220, 220, 1303, 3108, 10786, 3256, 5009, 13, 9630, 11, 1438, 2625, 9630...
2.980769
104
#~ Copyright 2014 Wieger Wesselink. #~ Distributed under the Boost Software License, Version 1.0. #~ (See accompanying file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt)
[ 2, 93, 15069, 1946, 370, 494, 1362, 370, 7878, 676, 13, 198, 2, 93, 4307, 6169, 739, 262, 19835, 10442, 13789, 11, 10628, 352, 13, 15, 13, 198, 2, 93, 357, 6214, 19249, 2393, 38559, 24290, 62, 16, 62, 15, 13, 14116, 393, 2638, 1...
2.919355
62
import datetime t1 = datetime.datetime(2019, 3, 9, 10, 55, 30, 991882) t2 = datetime.datetime(2019, 3, 10, 10, 55, 30, 991882) print((t2-t1).total_seconds())
[ 11748, 4818, 8079, 198, 198, 83, 16, 796, 4818, 8079, 13, 19608, 8079, 7, 23344, 11, 513, 11, 860, 11, 838, 11, 5996, 11, 1542, 11, 7388, 1507, 6469, 8, 198, 83, 17, 796, 4818, 8079, 13, 19608, 8079, 7, 23344, 11, 513, 11, 838, ...
2.271429
70
def is_descending(input_list: list, step: int = -1) -> bool: r"""llogic.is_descending(input_list[, step]) This function returns True if the input list is descending with a fixed step, otherwise it returns False. Usage: >>> alist = [3, 2, 1, 0] >>> llogic.is_descending(alist) True The final value can be other than zero: >>> alist = [12, 11, 10] >>> llogic.is_descending(alist) True The list can also have negative elements: >>> alist = [2, 1, 0, -1, -2] >>> llogic.is_descending(alist) True It will return False if the list is not ascending: >>> alist = [6, 5, 9, 2] >>> llogic.is_descending(alist) False By default, the function uses steps of size 1 so the list below is not considered as ascending: >>> alist = [7, 5, 3, 1] >>> llogic.is_descending(alist) False But the user can set the step argument to any value less than one: >>> alist = [7, 5, 3, 1] >>> step = -2 >>> llogic.is_descending(alist, step) True """ if not isinstance(input_list, list): raise TypeError('\'input_list\' must be \'list\'') if not isinstance(step, int): raise TypeError('\'step\' must be \'int\'') if step > 1: raise ValueError('\'step\' must be < 0') aux_list = list(range(max(input_list), min(input_list)-1, step)) return input_list == aux_list
[ 4299, 318, 62, 20147, 1571, 7, 15414, 62, 4868, 25, 1351, 11, 2239, 25, 493, 796, 532, 16, 8, 4613, 20512, 25, 198, 220, 220, 220, 374, 37811, 297, 519, 291, 13, 271, 62, 20147, 1571, 7, 15414, 62, 4868, 58, 11, 2239, 12962, 628...
2.54265
551
from functools import partial from pipe import select, where from pydash import chunk from pydash import filter_ as filter from pydash import flatten, get, omit from .primitives import parallel, pipeline, scatter __all__ = ( "parallel", "scatter", "pipeline", "partial", "select", "where", "flatten", "chunk", "omit", "get", "filter", )
[ 6738, 1257, 310, 10141, 1330, 13027, 198, 198, 6738, 12656, 1330, 2922, 11, 810, 198, 6738, 279, 5173, 1077, 1330, 16058, 198, 6738, 279, 5173, 1077, 1330, 8106, 62, 355, 8106, 198, 6738, 279, 5173, 1077, 1330, 27172, 268, 11, 651, 11...
2.577181
149
import yaml if __name__ == '__main__': main()
[ 11748, 331, 43695, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 1388, 3419, 628 ]
2.363636
22
""" Copyright 2012-2019 Ministerie van Sociale Zaken en Werkgelegenheid Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import datetime import unittest from unittest.mock import Mock import urllib.error from dateutil.tz import tzutc, tzlocal from hqlib.metric_source import JunitTestReport
[ 37811, 198, 15269, 2321, 12, 23344, 4139, 494, 5719, 5483, 68, 1168, 1685, 551, 370, 9587, 469, 1455, 268, 28420, 198, 198, 26656, 15385, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 5832, 743, 40...
3.616822
214
sort_functions = [ builtinsort, # see implementation above insertion_sort, # see [[Insertion sort]] insertion_sort_lowb, # ''insertion_sort'', where sequential search is replaced # by lower_bound() function qsort, # see [[Quicksort]] qsortranlc, # ''qsort'' with randomly choosen ''pivot'' # and the filtering via list comprehension qsortranpart, # ''qsortranlc'' with filtering via ''partition'' function qsortranpartis, # ''qsortranpart'', where for a small input sequence lengths ] # ''insertion_sort'' is called if __name__=="__main__": import sys sys.setrecursionlimit(10000) write_timings(npoints=100, maxN=1024, # 1 <= N <= 2**10 an input sequence length sort_functions=sort_functions, sequence_creators = (ones, range, shuffledrange)) plot_timings()
[ 30619, 62, 12543, 2733, 796, 685, 198, 220, 220, 220, 3170, 1040, 419, 11, 220, 220, 220, 220, 220, 220, 220, 220, 1303, 766, 7822, 2029, 198, 220, 220, 220, 36075, 62, 30619, 11, 220, 220, 220, 220, 220, 1303, 766, 16410, 44402, ...
2.275943
424
from rest_framework import status from rest_framework.test import APITestCase from rest_framework.test import APIClient from django.db.models import signals import factory from user_account.models import CustomUser from .models import Organization
[ 6738, 1334, 62, 30604, 1330, 3722, 198, 6738, 1334, 62, 30604, 13, 9288, 1330, 3486, 2043, 395, 20448, 198, 6738, 1334, 62, 30604, 13, 9288, 1330, 3486, 2149, 75, 1153, 198, 6738, 42625, 14208, 13, 9945, 13, 27530, 1330, 10425, 198, 1...
4.098361
61
# coding=utf-8 from math import log2, ceil # valid chars for a url path component: a-z A-Z 0-9 .-_~!$&'()*+,;=:@ # For the default set here (base 72) we have excluded $'();:@ radix_alphabet = ''.join(sorted( "0123456789" "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" ".-_~!&*+,=" )) radix = len(radix_alphabet) radix_lookup = {ch: i for i, ch in enumerate(radix_alphabet)} length_limit = ceil(128 / log2(radix)) # don't decode numbers much over 128 bits # TODO: add radix alphabet as parameter # TODO: fix format so length conveys m ore information (e.g. 0 and 00 and 000 are different with decimal alphabet) def natural_to_url(n): """Accepts an int and returns a url-compatible string representing it""" # map from signed int to positive int url = "" while n: n, digit = divmod(n, radix) url += radix_alphabet[digit] return url or radix_alphabet[0] def url_to_natural(url): """Accepts a string and extracts the int it represents in this radix encoding""" if not url or len(url) > length_limit: return None n = 0 try: for ch in reversed(url): n = n * radix + radix_lookup[ch] except KeyError: return None return n
[ 2, 19617, 28, 40477, 12, 23, 198, 6738, 10688, 1330, 2604, 17, 11, 2906, 346, 628, 198, 2, 4938, 34534, 329, 257, 19016, 3108, 7515, 25, 257, 12, 89, 317, 12, 57, 657, 12, 24, 764, 12, 62, 93, 0, 3, 5, 6, 3419, 9, 28200, 26,...
2.483168
505
from flaskapp import app, db, mail from flask import render_template, url_for from flask import request, flash, redirect # from flaskapp.model import User from flaskapp.form import SurveyForm from flask_mail import Message
[ 6738, 42903, 1324, 1330, 598, 11, 20613, 11, 6920, 201, 198, 6738, 42903, 1330, 8543, 62, 28243, 11, 19016, 62, 1640, 201, 198, 6738, 42903, 1330, 2581, 11, 7644, 11, 18941, 201, 198, 2, 422, 42903, 1324, 13, 19849, 1330, 11787, 201, ...
3.754098
61
import unittest from kameramera import camera
[ 11748, 555, 715, 395, 198, 198, 6738, 479, 2382, 18144, 1330, 4676 ]
3.833333
12
from pathlib import Path from PIL import Image # coordinates are sent as slightly weird URL parameters (e.g. 0.png?214,243) # parse them, will crash server if they are coming in unexpected format # image was not displayed in original size -> need to convert the coordinates
[ 6738, 3108, 8019, 1330, 10644, 198, 198, 6738, 350, 4146, 1330, 7412, 628, 198, 2, 22715, 389, 1908, 355, 4622, 7650, 10289, 10007, 357, 68, 13, 70, 13, 657, 13, 11134, 30, 22291, 11, 26660, 8, 198, 2, 21136, 606, 11, 481, 7014, 4...
4.102941
68
import matplotlib.pyplot as plt import numpy as np import math import cv2 kernel = np.ones((3, 3), np.int8) # # # # threshold1,2 # # if __name__ == '__main__': pic = cv2.imread('../captcha_Images/0.png') print(pic) cv2.imshow('pic', pic) cv2.waitKey(0) erosion = eraseImage(pic) blured = blurImage(erosion) edged = edgedImage(blured) dilated = dilateImage(edged) charBox = getCharBox(dilated) showCharBox(dilated, charBox) dilated = dilateImage(edged, (4, 4)) chars = resizeImage(dilated, charBox) # input("Press Enter to continue.") # c = result[0][0][0][0] # print(c) # plt.plot(c) cv2.waitKey(0) cv2.destroyAllWindows()
[ 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 10688, 198, 11748, 269, 85, 17, 198, 198, 33885, 796, 45941, 13, 1952, 19510, 18, 11, 513, 828, 45941, 13, 600, 23, 8, 198, 198...
2.309524
294
import pandas as pd import numpy as np from scipy.stats import mannwhitneyu, fisher_exact, ranksums def load_geneset(gmtfn, genes=None, minsize=0): ''' Load genesets stored in gmt format (e.g. as provided by msigdb) gmtfn : str path to gmt file genes : list, optional only include genes in this input minsize : int, optional minimum geneset size to keep Returns ------- gsets : dict gene_set_name : set of genes allsetgenes : set set of genes found in all genesets combined ''' allsetgenes = set() if genes is not None: genes = set(genes) gsets = {} effect_min_size = minsize+2 # account for gset name cols with open(gmtfn) as F: for l in F.readlines(): words = [x for x in l.rstrip().split('\t')] gsetname = words[0] setgenes = words[2:] if genes is not None: setgenes = set(setgenes).intersection(genes) else: setgenes = set(setgenes[2:]) if len(setgenes) >= effect_min_size: gsets[gsetname] = setgenes allsetgenes = allsetgenes.union(setgenes) return(gsets, allsetgenes)
[ 11748, 19798, 292, 355, 279, 67, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 629, 541, 88, 13, 34242, 1330, 582, 77, 1929, 270, 1681, 84, 11, 17685, 62, 1069, 529, 11, 9803, 5700, 198, 198, 4299, 3440, 62, 5235, 274, 316, 7, 70...
2.070261
612
from testlib_a.main_a import print_name print_name()
[ 6738, 1332, 8019, 62, 64, 13, 12417, 62, 64, 1330, 3601, 62, 3672, 198, 198, 4798, 62, 3672, 3419, 198 ]
2.7
20
import pprint from nn_wtf.parameter_optimizers.neural_network_optimizer import NeuralNetworkOptimizer __author__ = 'Lene Preuss <lene.preuss@gmail.com>'
[ 11748, 279, 4798, 198, 198, 6738, 299, 77, 62, 86, 27110, 13, 17143, 2357, 62, 40085, 11341, 13, 710, 1523, 62, 27349, 62, 40085, 7509, 1330, 47986, 26245, 27871, 320, 7509, 198, 198, 834, 9800, 834, 796, 705, 43, 1734, 3771, 1046, ...
2.854545
55
#!/usr/bin/env python from numpy.testing import assert_array_almost_equal, assert_array_less import numpy as np from heat import BmiHeat
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 6738, 299, 32152, 13, 33407, 1330, 6818, 62, 18747, 62, 28177, 62, 40496, 11, 6818, 62, 18747, 62, 1203, 198, 11748, 299, 32152, 355, 45941, 198, 198, 6738, 4894, 1330, 347, 11632, 395...
3.130435
46
import numpy as np import tensorflow as tf import sys, os sys.path.extend(['alg/', 'models/']) from visualisation import plot_images from encoder_no_shared import encoder, recon from utils import init_variables, save_params, load_params, load_data from eval_test_ll import construct_eval_func dimZ = 50 dimH = 500 n_channel = 128 batch_size = 50 lr = 1e-4 K_mc = 10 checkpoint = -1 if __name__ == '__main__': data_name = str(sys.argv[1]) method = str(sys.argv[2]) assert method in ['noreg', 'laplace', 'ewc', 'si', 'onlinevi'] if method == 'onlinevi': lbd = 1.0 # some placeholder, doesn't matter else: lbd = float(sys.argv[3]) main(data_name, method, dimZ, dimH, n_channel, batch_size, K_mc, checkpoint, lbd)
[ 11748, 299, 32152, 355, 45941, 198, 11748, 11192, 273, 11125, 355, 48700, 198, 11748, 25064, 11, 28686, 198, 17597, 13, 6978, 13, 2302, 437, 7, 17816, 14016, 14, 3256, 705, 27530, 14, 6, 12962, 198, 6738, 5874, 5612, 1330, 7110, 62, 1...
2.506623
302
import logging import os import cltl.combot.infra.config.local as local_config logger = logging.getLogger(__name__) K8_CONFIG_DIR = "/cltl_k8_config" K8_CONFIG = "config/k8.config"
[ 11748, 18931, 198, 11748, 28686, 198, 198, 11748, 537, 28781, 13, 785, 13645, 13, 10745, 430, 13, 11250, 13, 12001, 355, 1957, 62, 11250, 198, 198, 6404, 1362, 796, 18931, 13, 1136, 11187, 1362, 7, 834, 3672, 834, 8, 628, 198, 42, 2...
2.493333
75
#!/usr/bin/env python import os import argparse import yaml import numpy as np from colorama import init, Fore, Style from matplotlib import rc import matplotlib.pyplot as plt import plot_utils as pu init(autoreset=True) rc('font', **{'serif': ['Cardo'], 'size': 20}) rc('text', usetex=True) kMetrics = ['det', 'mineig', 'trace'] kMetricsLabels = ['$\det$', '$\lambda_{min}$', '${Tr}$'] kSecToUs = 1.0e6 kPallete = [ 'blue', 'green', 'red', 'gold', 'purple', 'gray', 'cyan', 'midnightblue', 'lime', 'lightcoral', 'darkgoldenrod', 'violet', 'dimgray', 'darkorange', 'black' ] if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--res_dir', required=True) parser.add_argument('--analyze_config', required=True) parser.add_argument('--save_dir', type=str, default='analysis_results') parser.add_argument('--pc_res_key', type=str, default='quad_info_0p5') parser.set_defaults(map_names=['quad_info', 'quad_trace', 'gp_info', 'gp_trace']) args = parser.parse_args() print(Fore.YELLOW + args.__dict__.__str__()) with open(args.analyze_config, 'r') as f: cfg = yaml.load(f, Loader=yaml.FullLoader) print("Read configurations:\n{}".format(cfg)) map_names = [] map_nm_to_label = {} for d in cfg['all_maps']: map_nm_to_label.update(d) for k in d: map_names.append(k) print(Fore.GREEN + "Maps to compare:\n- {}".format('\n- '.join(map_names))) print(Fore.GREEN + "Labels:\n{}".format(map_nm_to_label)) fim_map_nms = [v for v in map_names if 'info' in v] compare_orient_map_nms = [v for v in map_names if 'info' in v] compare_cont_motion_map_nms = [v for v in map_names if 'info' in v] print("Will analyze FIM for {}".format(fim_map_nms)) print("Will compare orientations for {}".format(compare_orient_map_nms)) print("Will compare cont. motion for {}".format(compare_cont_motion_map_nms)) save_dir = os.path.join(args.res_dir, args.save_dir) if not os.path.exists(save_dir): os.makedirs(save_dir) else: print(Fore.RED + "Save folder exists, will re-use and overwrite.") print("Going to save to {}".format(save_dir)) map_nm_to_res = {} for map_nm in map_names: print(Fore.GREEN + "====> Reading {}...".format(map_nm)) map_nm_to_res[map_nm] = readResults(args.res_dir, map_nm) print(Fore.YELLOW + Style.BRIGHT + "Start analysis.") print(Fore.GREEN + "1. Table of complexity.") _writeComplexityTable(map_nm_to_res, args.pc_res_key, map_names, map_nm_to_label, os.path.join(save_dir, 'complexity_table.txt')) print(Fore.GREEN + "2. FIM difference.") map_nm_to_fim_diff_perc = _computeAndWriteFIMDiff( map_nm_to_res, fim_map_nms, map_nm_to_label, save_dir) _boxplotFIMDiffs(map_nm_to_fim_diff_perc, fim_map_nms, map_nm_to_label, save_dir) print(Fore.GREEN + "3. Optimal views.") map_nm_to_orient_diff = _computeAndWriteOptimalOrientDiff( map_nm_to_res, compare_orient_map_nms, map_nm_to_label, save_dir) _boxplotOrientDiffs(map_nm_to_orient_diff, compare_orient_map_nms, map_nm_to_label, save_dir) print(Fore.GREEN + "4. Continous motion.") _compareContinuousMotion(map_nm_to_res, compare_cont_motion_map_nms, map_nm_to_label, save_dir) print(Fore.GREEN + Style.BRIGHT + "Start processing specified subsets...") sel_dir = os.path.join(save_dir, 'selected_results') if not os.path.exists(sel_dir): os.makedirs(sel_dir) if 'sel_complexity_table_entries' in cfg: print(Fore.GREEN + "- complexity table") _writeComplexityTable(map_nm_to_res, args.pc_res_key, cfg['sel_complexity_table_entries'], map_nm_to_label, os.path.join( sel_dir, 'complexity_table.txt')) if 'sel_fro_norm_table_entries' in cfg: print(Fore.GREEN + "- FIM diff. table") sel_fim_nms = cfg['sel_fro_norm_table_entries'] sel_nm_to_fim_diff = _computeAndWriteFIMDiff( map_nm_to_res, sel_fim_nms, map_nm_to_label, sel_dir) _boxplotFIMDiffs(sel_nm_to_fim_diff, sel_fim_nms, map_nm_to_label, sel_dir) if 'sel_hist_orient_entries' in cfg: sel_orient_nms = cfg['sel_hist_orient_entries'] print(Fore.GREEN + "- Orientation diff.") sel_nm_to_orient_diff = _computeAndWriteOptimalOrientDiff( map_nm_to_res, sel_orient_nms, map_nm_to_label, sel_dir) _boxplotOrientDiffs(sel_nm_to_orient_diff, sel_orient_nms, map_nm_to_label, sel_dir) if 'sel_cont_motion_plot' in cfg: print(Fore.GREEN + "- continuous motion") _compareContinuousMotion( map_nm_to_res, cfg['sel_cont_motion_plot'], map_nm_to_label, sel_dir)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 11748, 28686, 198, 11748, 1822, 29572, 198, 11748, 331, 43695, 198, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 3124, 1689, 1330, 2315, 11, 4558, 11, 17738, 198, 6738, 2603, 2948...
2.25
2,116
# see: https://stackoverflow.com/a/34520971/3238695
[ 2, 766, 25, 3740, 1378, 25558, 2502, 11125, 13, 785, 14, 64, 14, 27712, 22567, 4869, 14, 18, 23721, 37381, 198 ]
2.47619
21
import json import apiai import speech_recognition as sr #speechRecognition()
[ 11748, 33918, 198, 11748, 2471, 544, 72, 198, 11748, 4046, 62, 26243, 653, 355, 19677, 628, 198, 198, 2, 45862, 6690, 2360, 653, 3419, 198 ]
3.24
25
# raise NotImplementedError("Did not check!") """MSCOCO Semantic Segmentation pretraining for VOC.""" import os from tqdm import trange from PIL import Image, ImageOps, ImageFilter import numpy as np import pickle from gluoncv.data.segbase import SegmentationDataset
[ 2, 5298, 1892, 3546, 1154, 12061, 12331, 7203, 11633, 407, 2198, 2474, 8, 198, 198, 37811, 5653, 34, 4503, 46, 12449, 5109, 1001, 5154, 341, 2181, 24674, 329, 569, 4503, 526, 15931, 198, 11748, 28686, 198, 6738, 256, 80, 36020, 1330, ...
3.139535
86
# __author__ = 'sree' import urllib2 from lxml import html import requests
[ 2, 11593, 9800, 834, 796, 705, 82, 631, 6, 198, 11748, 2956, 297, 571, 17, 198, 198, 6738, 300, 19875, 1330, 27711, 198, 11748, 7007, 198 ]
2.923077
26
# encoding: utf-8 # Copyright 2009-2020 Greg Neagle. # # 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 # # https://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. """ adobeutils.adobeinfo Created by Greg Neagle on 2017-01-06. Utilities to get info about Adobe installers/uninstallers """ from __future__ import absolute_import, print_function import os import json import sqlite3 from glob import glob from xml.dom import minidom from .. import osutils from .. import pkgutils def find_install_app(dirpath): '''Searches dirpath and enclosed directories for Install.app. Returns the path to the actual executable.''' for (path, dummy_dirs, dummy_files) in os.walk(dirpath): if path.endswith("Install.app"): setup_path = os.path.join(path, "Contents", "MacOS", "Install") if os.path.exists(setup_path): return setup_path return '' def find_setup_app(dirpath): '''Search dirpath and enclosed directories for Setup.app. Returns the path to the actual executable.''' for (path, dummy_dirs, dummy_files) in os.walk(dirpath): if path.endswith("Setup.app"): setup_path = os.path.join(path, "Contents", "MacOS", "Setup") if os.path.exists(setup_path): return setup_path return '' def find_adobepatchinstaller_app(dirpath): '''Searches dirpath and enclosed directories for AdobePatchInstaller.app. Returns the path to the actual executable.''' for (path, dummy_dirs, dummy_files) in os.walk(dirpath): if path.endswith("AdobePatchInstaller.app"): setup_path = os.path.join( path, "Contents", "MacOS", "AdobePatchInstaller") if os.path.exists(setup_path): return setup_path return '' def find_adobe_deployment_manager(dirpath): '''Searches dirpath and enclosed directories for AdobeDeploymentManager. Returns path to the executable.''' for (path, dummy_dirs, dummy_files) in os.walk(dirpath): if path.endswith("pkg/Contents/Resources"): dm_path = os.path.join(path, "AdobeDeploymentManager") if os.path.exists(dm_path): return dm_path return '' def find_acrobat_patch_app(dirpath): '''Attempts to find an AcrobatPro patching application in dirpath. If found, returns the path to the bundled patching script.''' for (path, dummy_dirs, dummy_files) in os.walk(dirpath): if path.endswith(".app"): # look for Adobe's patching script patch_script_path = os.path.join( path, 'Contents', 'Resources', 'ApplyOperation.py') if os.path.exists(patch_script_path): return path return '' def get_payload_info(dirpath): '''Parses Adobe payloads, pulling out info useful to munki. .proxy.xml files are used if available, or for CC-era updates which do not contain one, the Media_db.db file, which contains identical XML, is instead used. CS3/CS4: contain only .proxy.xml CS5/CS5.5/CS6: contain both CC: contain only Media_db.db''' payloadinfo = {} # look for .proxy.xml file dir if os.path.isdir(dirpath): proxy_paths = glob(os.path.join(dirpath, '*.proxy.xml')) if proxy_paths: xmlpath = proxy_paths[0] dom = minidom.parse(xmlpath) # if there's no .proxy.xml we should hope there's a Media_db.db else: db_path = os.path.join(dirpath, 'Media_db.db') if os.path.exists(db_path): conn = sqlite3.connect(db_path) cur = conn.cursor() cur.execute("SELECT value FROM PayloadData WHERE " "PayloadData.key = 'PayloadInfo'") result = cur.fetchone() cur.close() if result: info_xml = result[0].encode('UTF-8') dom = minidom.parseString(info_xml) else: # no xml, no db, no payload info! return payloadinfo payload_info = dom.getElementsByTagName('PayloadInfo') if payload_info: installer_properties = payload_info[0].getElementsByTagName( 'InstallerProperties') if installer_properties: properties = installer_properties[0].getElementsByTagName( 'Property') for prop in properties: if 'name' in list(prop.attributes.keys()): propname = prop.attributes['name'].value.encode('UTF-8') propvalue = '' for node in prop.childNodes: propvalue += node.nodeValue if propname == 'AdobeCode': payloadinfo['AdobeCode'] = propvalue if propname == 'ProductName': payloadinfo['display_name'] = propvalue if propname == 'ProductVersion': payloadinfo['version'] = propvalue installmetadata = payload_info[0].getElementsByTagName( 'InstallDestinationMetadata') if installmetadata: totalsizes = installmetadata[0].getElementsByTagName( 'TotalSize') if totalsizes: installsize = '' for node in totalsizes[0].childNodes: installsize += node.nodeValue payloadinfo['installed_size'] = int(int(installsize)/1024) return payloadinfo def get_adobe_setup_info(installroot): '''Given the root of mounted Adobe DMG, look for info about the installer or updater''' info = {} payloads = [] # look for all the payloads folders for (path, dummy_dirs, dummy_files) in os.walk(installroot): if path.endswith('/payloads'): driverfolder = '' media_signature = '' setupxml = os.path.join(path, 'setup.xml') if os.path.exists(setupxml): dom = minidom.parse(setupxml) drivers = dom.getElementsByTagName('Driver') if drivers: driver = drivers[0] if 'folder' in list(driver.attributes.keys()): driverfolder = driver.attributes[ 'folder'].value.encode('UTF-8') if driverfolder == '': # look for mediaSignature (CS5 AAMEE install) setup_elements = dom.getElementsByTagName('Setup') if setup_elements: media_signature_elements = setup_elements[ 0].getElementsByTagName('mediaSignature') if media_signature_elements: element = media_signature_elements[0] for node in element.childNodes: media_signature += node.nodeValue for item in osutils.listdir(path): payloadpath = os.path.join(path, item) payloadinfo = get_payload_info(payloadpath) if payloadinfo: payloads.append(payloadinfo) if ((driverfolder and item == driverfolder) or (media_signature and payloadinfo['AdobeCode'] == media_signature)): info['display_name'] = payloadinfo['display_name'] info['version'] = payloadinfo['version'] info['AdobeSetupType'] = 'ProductInstall' if not payloads: # look for an extensions folder; almost certainly this is an Updater for (path, dummy_dirs, dummy_files) in os.walk(installroot): if path.endswith("/extensions"): for item in osutils.listdir(path): #skip LanguagePacks if item.find("LanguagePack") == -1: itempath = os.path.join(path, item) payloadinfo = get_payload_info(itempath) if payloadinfo: payloads.append(payloadinfo) # we found an extensions dir, # so no need to keep walking the install root break if payloads: if len(payloads) == 1: info['display_name'] = payloads[0]['display_name'] info['version'] = payloads[0]['version'] else: if 'display_name' not in info: info['display_name'] = "ADMIN: choose from payloads" if 'version' not in info: info['version'] = "ADMIN please set me" info['payloads'] = payloads installed_size = 0 for payload in payloads: installed_size = installed_size + payload.get('installed_size', 0) info['installed_size'] = installed_size return info def get_adobe_package_info(installroot): '''Gets the package name from the AdobeUberInstaller.xml file; other info from the payloads folder''' info = get_adobe_setup_info(installroot) info['description'] = "" installerxml = os.path.join(installroot, "AdobeUberInstaller.xml") if os.path.exists(installerxml): description = '' dom = minidom.parse(installerxml) installinfo = dom.getElementsByTagName("InstallInfo") if installinfo: packagedescriptions = \ installinfo[0].getElementsByTagName("PackageDescription") if packagedescriptions: prop = packagedescriptions[0] for node in prop.childNodes: description += node.nodeValue if description: description_parts = description.split(' : ', 1) info['display_name'] = description_parts[0] if len(description_parts) > 1: info['description'] = description_parts[1] else: info['description'] = "" return info else: installerxml = os.path.join(installroot, "optionXML.xml") if os.path.exists(installerxml): dom = minidom.parse(installerxml) installinfo = dom.getElementsByTagName("InstallInfo") if installinfo: pkgname_elems = installinfo[0].getElementsByTagName( "PackageName") if pkgname_elems: prop = pkgname_elems[0] pkgname = "" for node in prop.childNodes: pkgname += node.nodeValue info['display_name'] = pkgname if not info.get('display_name'): info['display_name'] = os.path.basename(installroot) return info def get_xml_text_element(dom_node, name): '''Returns the text value of the first item found with the given tagname''' value = None subelements = dom_node.getElementsByTagName(name) if subelements: value = '' for node in subelements[0].childNodes: value += node.nodeValue return value def parse_option_xml(option_xml_file): '''Parses an optionXML.xml file and pulls the items of interest, returning them in a dictionary''' info = {} dom = minidom.parse(option_xml_file) installinfo = dom.getElementsByTagName('InstallInfo') if installinfo: if 'id' in list(installinfo[0].attributes.keys()): info['packager_id'] = installinfo[0].attributes['id'].value if 'version' in list(installinfo[0].attributes.keys()): info['packager_version'] = installinfo[ 0].attributes['version'].value info['package_name'] = get_xml_text_element( installinfo[0], 'PackageName') info['package_id'] = get_xml_text_element(installinfo[0], 'PackageID') info['products'] = [] # CS5 to CC 2015.0-2015.2 releases use RIBS, and we retrieve a # display name, version and 'mediaSignature' for building installs # items. SAPCode is also stored so that we can later search by this # key across both RIBS and HyperDrive installer metadata. medias_elements = installinfo[0].getElementsByTagName('Medias') if medias_elements: media_elements = medias_elements[0].getElementsByTagName('Media') if media_elements: for media in media_elements: product = {} product['prodName'] = get_xml_text_element( media, 'prodName') product['prodVersion'] = get_xml_text_element( media, 'prodVersion') product['SAPCode'] = get_xml_text_element(media, 'SAPCode') setup_elements = media.getElementsByTagName('Setup') if setup_elements: media_signature_elements = setup_elements[ 0].getElementsByTagName('mediaSignature') if media_signature_elements: product['mediaSignature'] = '' element = media_signature_elements[0] for node in element.childNodes: product['mediaSignature'] += node.nodeValue info['products'].append(product) # HD (HyperDrive) media for new mid-June 2016 products. We need the # SAP codes, versions, and which ones are MediaType 'Product'. Support # payloads seem to all be 'STI', and are listed as STIDependencies under # the main product. hd_medias_elements = installinfo[0].getElementsByTagName('HDMedias') if hd_medias_elements: hd_media_elements = hd_medias_elements[0].getElementsByTagName( 'HDMedia') if hd_media_elements: for hd_media in hd_media_elements: product = {} product['hd_installer'] = True # productVersion is the 'full' version number # prodVersion seems to be the "customer-facing" version for # this update # baseVersion is the first/base version for this standalone # product/channel/LEID, # not really needed here so we don't copy it for elem in [ 'mediaLEID', 'prodVersion', 'productVersion', 'SAPCode', 'MediaType', 'TargetFolderName']: product[elem] = get_xml_text_element(hd_media, elem) info['products'].append(product) return info def get_hd_installer_info(hd_payload_root, sap_code): '''Attempts to extract some information from a HyperDrive payload application.json file and return a reduced set in a dict''' hd_app_info = {} app_json_path = os.path.join(hd_payload_root, sap_code, 'Application.json') json_info = json.loads(open(app_json_path, 'r').read()) # Copy some useful top-level keys, useful later for: # - Name: display_name pkginfo key # - ProductVersion: version pkginfo key and uninstall XML location # - SAPCode: an uninstallXml for an installs item if it's a 'core' Type # - BaseVersion and version: not currently used but may be useful once # there are more HD installers in the future for key in ['BaseVersion', 'Name', 'ProductVersion', 'SAPCode', 'version']: hd_app_info[key] = json_info[key] hd_app_info['SAPCode'] = json_info['SAPCode'] # Adobe puts an array of dicts in a dict with one key called 'Package' pkgs = [pkg for pkg in json_info['Packages']['Package']] hd_app_info['Packages'] = pkgs return hd_app_info def get_cs5_media_signature(dirpath): '''Returns the CS5 mediaSignature for an AAMEE CS5 install. dirpath is typically the root of a mounted dmg''' payloads_dir = "" # look for a payloads folder for (path, dummy_dirs, dummy_files) in os.walk(dirpath): if path.endswith('/payloads'): payloads_dir = path # return empty-handed if we didn't find a payloads folder if not payloads_dir: return '' # now look for setup.xml setupxml = os.path.join(payloads_dir, 'Setup.xml') if os.path.exists(setupxml) and os.path.isfile(setupxml): # parse the XML dom = minidom.parse(setupxml) setup_elements = dom.getElementsByTagName('Setup') if setup_elements: media_signature_elements = ( setup_elements[0].getElementsByTagName('mediaSignature')) if media_signature_elements: element = media_signature_elements[0] elementvalue = '' for node in element.childNodes: elementvalue += node.nodeValue return elementvalue return "" def get_cs5_uninstall_xml(option_xml_file): '''Gets the uninstall deployment data from a CS5 installer''' xml = '' dom = minidom.parse(option_xml_file) deployment_info = dom.getElementsByTagName('DeploymentInfo') if deployment_info: for info_item in deployment_info: deployment_uninstall = info_item.getElementsByTagName( 'DeploymentUninstall') if deployment_uninstall: deployment_data = deployment_uninstall[0].getElementsByTagName( 'Deployment') if deployment_data: deployment = deployment_data[0] xml += deployment.toxml('UTF-8') return xml def count_payloads(dirpath): '''Attempts to count the payloads in the Adobe installation item. Used for rough percent-done progress feedback.''' count = 0 for (path, dummy_dirs, files) in os.walk(dirpath): if path.endswith("/payloads"): # RIBS-style installers for subitem in osutils.listdir(path): subitempath = os.path.join(path, subitem) if os.path.isdir(subitempath): count = count + 1 elif "/HD/" in path and "Application.json" in files: # we're inside an HD installer directory. The payloads/packages # are .zip files zip_file_count = len( [item for item in files if item.endswith(".zip")]) count = count + zip_file_count return count def get_adobe_install_info(installdir): '''Encapsulates info used by the Adobe Setup/Install app.''' adobe_install_info = {} if installdir: adobe_install_info['media_signature'] = get_cs5_media_signature( installdir) adobe_install_info['payload_count'] = count_payloads(installdir) option_xml_file = os.path.join(installdir, "optionXML.xml") if os.path.exists(option_xml_file): adobe_install_info['uninstallxml'] = get_cs5_uninstall_xml( option_xml_file) return adobe_install_info # Disable PyLint complaining about 'invalid' camelCase names # pylint: disable=invalid-name def getAdobeCatalogInfo(mountpoint, pkgname=""): '''Used by makepkginfo to build pkginfo data for Adobe installers/updaters''' # look for AdobeDeploymentManager (AAMEE installer) deploymentmanager = find_adobe_deployment_manager(mountpoint) if deploymentmanager: dirpath = os.path.dirname(deploymentmanager) option_xml_file = os.path.join(dirpath, 'optionXML.xml') option_xml_info = {} if os.path.exists(option_xml_file): option_xml_info = parse_option_xml(option_xml_file) cataloginfo = get_adobe_package_info(dirpath) if cataloginfo: # add some more data if option_xml_info.get('packager_id') == u'CloudPackager': # CCP package cataloginfo['display_name'] = option_xml_info.get( 'package_name', 'unknown') cataloginfo['name'] = cataloginfo['display_name'].replace( ' ', '') cataloginfo['uninstallable'] = True cataloginfo['uninstall_method'] = "AdobeCCPUninstaller" cataloginfo['installer_type'] = "AdobeCCPInstaller" cataloginfo['minimum_os_version'] = "10.6.8" mediasignatures = [ item['mediaSignature'] for item in option_xml_info.get('products', []) if 'mediaSignature' in item] else: # AAMEE package cataloginfo['name'] = cataloginfo['display_name'].replace( ' ', '') cataloginfo['uninstallable'] = True cataloginfo['uninstall_method'] = "AdobeCS5AAMEEPackage" cataloginfo['installer_type'] = "AdobeCS5AAMEEPackage" cataloginfo['minimum_os_version'] = "10.5.0" cataloginfo['adobe_install_info'] = get_adobe_install_info( installdir=dirpath) mediasignature = cataloginfo['adobe_install_info'].get( "media_signature") mediasignatures = [mediasignature] # Determine whether we have HD media as well in this installer hd_metadata_dirs = [ product['TargetFolderName'] for product in option_xml_info['products'] if product.get('hd_installer')] hd_app_infos = [] for sap_code in hd_metadata_dirs: hd_app_info = get_hd_installer_info( os.path.join(dirpath, 'HD'), sap_code) hd_app_infos.append(hd_app_info) # 'installs' array will be populated if we have either RIBS # or HD installers, which may be mixed together in one # CCP package. # Acrobat Pro DC doesn't currently generate any useful installs # info if it's part of a CCP package. installs = [] # media signatures are used for RIBS (CS5 to CC mid-2015) if mediasignatures: # make a default <key>installs</key> array uninstalldir = "/Library/Application Support/Adobe/Uninstall" for mediasignature in mediasignatures: signaturefile = mediasignature + ".db" filepath = os.path.join(uninstalldir, signaturefile) installitem = {} installitem['path'] = filepath installitem['type'] = 'file' installs.append(installitem) # Custom installs items for HD installers seem to need only HDMedias # from optionXML.xml with a MediaType of 'Product' and their # 'core' packages (e.g. language packs are 'non-core') if hd_app_infos: if 'payloads' not in cataloginfo: cataloginfo['payloads'] = [] cataloginfo['payloads'].extend(hd_app_infos) # Calculate installed_size by counting packages in payloads # in these indexed HD medias. installed_size may exist already # if this package contained RIBS payloads, so try reading it # and default to 0. This will typically include several very # small packages (language or regional recommended settings) # which would not actually get installed. These seem to be # no larger than a few MB, so in practice it increases the # 'installed_size' value by only ~1%. installed_size = cataloginfo.get('installed_size', 0) for hd_payload in hd_app_infos: for package in hd_payload['Packages']: # Generally, all app installs will include 1-3 'core' # packages and then additional language/settings/color # packages which are regional or language-specific. # If we filter this by including both unconditional # installs and those which are language/region specific, # we get a rough approximation of the total size of # supplemental packages, as their equivalents for other # languages are very close to the same size. We also # get one included language package which would be the # case for any install. # # Because InDesign CC 2017 is not like any other package # and contains a 'Condition' key but as an empty # string, we explicitly test this case as well. if ('Condition' not in list(package.keys()) or package.get('Condition') == '' or '[installLanguage]==en_US' in package.get('Condition', '')): installed_size += int(package.get( 'ExtractSize', 0) / 1024) # We get much closer to Adobe's "HDSetup" calculated # install space requirement if we include both the # DownloadSize and ExtractSize data # (DownloadSize is just the zip file size) installed_size += int(package.get( 'DownloadSize', 0) / 1024) # Add another 300MB for the CC app and plumbing in case they've # never been installed on the system installed_size += 307200 cataloginfo['installed_size'] = installed_size uninstalldir = ( '/Library/Application Support/Adobe/Installers/uninstallXml' ) product_saps = [ prod['SAPCode'] for prod in option_xml_info['products'] if prod.get('MediaType') == 'Product' ] product_app_infos = [app for app in hd_app_infos if app['SAPCode'] in product_saps] # if we had only a single HD and no legacy apps, set a sane # version and display_name derived from the app's metadata if (len(product_app_infos) == 1) and not mediasignatures: cataloginfo.update({ 'display_name': product_app_infos[0]['Name'], 'version': product_app_infos[0]['ProductVersion'], }) for app_info in product_app_infos: for pkg in app_info['Packages']: # Don't assume 'Type' key always exists. At least the #'AdobeIllustrator20-Settings' # package doesn't have this key set. if pkg.get('Type') == 'core': # We can't use 'ProductVersion' from # Application.json for the part following the # SAPCode, because it's usually too specific and # won't match the "short" product version. # We can take 'prodVersion' from the optionXML.xml # instead. # We filter out any non-HD installers to avoid # matching up the wrong versions for packages that # may contain multiple different major versions of # a given SAPCode pkg_prod_vers = [ prod['prodVersion'] for prod in option_xml_info['products'] if prod.get('hd_installer') and prod['SAPCode'] == app_info['SAPCode']][0] uninstall_file_name = '_'.join([ app_info['SAPCode'], pkg_prod_vers.replace('.', '_'), pkg['PackageName'], pkg['PackageVersion']]) + '.pimx' filepath = os.path.join( uninstalldir, uninstall_file_name) installitem = {} installitem['path'] = filepath installitem['type'] = 'file' installs.append(installitem) if installs: cataloginfo['installs'] = installs return cataloginfo # Look for Install.app (Bare metal CS5 install) # we don't handle this type, but we'll report it # back so makepkginfo can provide an error message # installapp = find_install_app(mountpoint) # if installapp: # cataloginfo = {} # cataloginfo['installer_type'] = "AdobeCS5Installer" # return cataloginfo # Look for AdobePatchInstaller.app (CS5 updater) installapp = find_adobepatchinstaller_app(mountpoint) if os.path.exists(installapp): # this is a CS5 updater disk image cataloginfo = get_adobe_package_info(mountpoint) if cataloginfo: # add some more data cataloginfo['name'] = cataloginfo['display_name'].replace(' ', '') cataloginfo['uninstallable'] = False cataloginfo['installer_type'] = "AdobeCS5PatchInstaller" if pkgname: cataloginfo['package_path'] = pkgname # make some (hopefully functional) installs items from the payloads installs = [] uninstalldir = "/Library/Application Support/Adobe/Uninstall" # first look for a payload with a display_name matching the # overall display_name for payload in cataloginfo.get('payloads', []): if (payload.get('display_name', '') == cataloginfo['display_name']): if 'AdobeCode' in payload: dbfile = payload['AdobeCode'] + ".db" filepath = os.path.join(uninstalldir, dbfile) installitem = {} installitem['path'] = filepath installitem['type'] = 'file' installs.append(installitem) break if installs == []: # didn't find a payload with matching name # just add all of the non-LangPack payloads # to the installs list. for payload in cataloginfo.get('payloads', []): if 'AdobeCode' in payload: if ("LangPack" in payload.get("display_name") or "Language Files" in payload.get( "display_name")): # skip Language Packs continue dbfile = payload['AdobeCode'] + ".db" filepath = os.path.join(uninstalldir, dbfile) installitem = {} installitem['path'] = filepath installitem['type'] = 'file' installs.append(installitem) cataloginfo['installs'] = installs return cataloginfo # Look for AdobeUberInstaller items (CS4 install) pkgroot = os.path.join(mountpoint, pkgname) adobeinstallxml = os.path.join(pkgroot, "AdobeUberInstaller.xml") if os.path.exists(adobeinstallxml): # this is a CS4 Enterprise Deployment package cataloginfo = get_adobe_package_info(pkgroot) if cataloginfo: # add some more data cataloginfo['name'] = cataloginfo['display_name'].replace(' ', '') cataloginfo['uninstallable'] = True cataloginfo['uninstall_method'] = "AdobeUberUninstaller" cataloginfo['installer_type'] = "AdobeUberInstaller" if pkgname: cataloginfo['package_path'] = pkgname return cataloginfo # maybe this is an Adobe update DMG or CS3 installer # look for Adobe Setup.app setuppath = find_setup_app(mountpoint) if setuppath: cataloginfo = get_adobe_setup_info(mountpoint) if cataloginfo: # add some more data cataloginfo['name'] = cataloginfo['display_name'].replace(' ', '') cataloginfo['installer_type'] = "AdobeSetup" if cataloginfo.get('AdobeSetupType') == "ProductInstall": cataloginfo['uninstallable'] = True cataloginfo['uninstall_method'] = "AdobeSetup" else: cataloginfo['description'] = "Adobe updater" cataloginfo['uninstallable'] = False cataloginfo['update_for'] = ["PleaseEditMe-1.0.0.0.0"] return cataloginfo # maybe this is an Adobe Acrobat 9 Pro patcher? acrobatpatcherapp = find_acrobat_patch_app(mountpoint) if acrobatpatcherapp: cataloginfo = {} cataloginfo['installer_type'] = "AdobeAcrobatUpdater" cataloginfo['uninstallable'] = False plist = pkgutils.getBundleInfo(acrobatpatcherapp) cataloginfo['version'] = pkgutils.getVersionString(plist) cataloginfo['name'] = "AcrobatPro9Update" cataloginfo['display_name'] = "Adobe Acrobat Pro Update" cataloginfo['update_for'] = ["AcrobatPro9"] cataloginfo['RestartAction'] = 'RequireLogout' cataloginfo['requires'] = [] cataloginfo['installs'] = [ {'CFBundleIdentifier': 'com.adobe.Acrobat.Pro', 'CFBundleName': 'Acrobat', 'CFBundleShortVersionString': cataloginfo['version'], 'path': '/Applications/Adobe Acrobat 9 Pro/Adobe Acrobat Pro.app', 'type': 'application'} ] return cataloginfo # didn't find any Adobe installers/updaters we understand return None # pylint: enable=invalid-name if __name__ == '__main__': print('This is a library of support tools for the Munki Suite.')
[ 2, 21004, 25, 3384, 69, 12, 23, 198, 2, 15069, 3717, 12, 42334, 8547, 3169, 19345, 13, 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, 428, 2393, 2...
2.070576
17,017
from .. import util
[ 6738, 11485, 1330, 7736, 628 ]
4.2
5
#!/usr/bin/python #-*-coding:utf-8-*- from Component import Component
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 2, 12, 9, 12, 66, 7656, 25, 40477, 12, 23, 12, 9, 12, 198, 198, 6738, 35100, 1330, 35100, 198 ]
2.535714
28
import datetime, hashlib, base64, traceback, os, re import poshc2.server.database.DB as DB from poshc2.Colours import Colours from poshc2.server.Config import ModulesDirectory, DownloadsDirectory, ReportsDirectory from poshc2.server.Implant import Implant from poshc2.server.Core import decrypt, encrypt, default_response, decrypt_bytes_gzip, number_of_days, process_mimikatz, print_bad from poshc2.server.Core import load_module, load_module_sharp, encrypt, default_response from poshc2.server.payloads.Payloads import Payloads from poshc2.server.PowerStatus import translate_power_status from poshc2.Utils import randomuri
[ 11748, 4818, 8079, 11, 12234, 8019, 11, 2779, 2414, 11, 12854, 1891, 11, 28686, 11, 302, 198, 198, 11748, 1426, 71, 66, 17, 13, 15388, 13, 48806, 13, 11012, 355, 20137, 198, 6738, 1426, 71, 66, 17, 13, 5216, 4662, 1330, 1623, 4662, ...
3.253886
193
s = Solution() print(s.grayCode(3))
[ 198, 198, 82, 796, 28186, 3419, 198, 4798, 7, 82, 13, 44605, 10669, 7, 18, 4008, 198 ]
2.235294
17