content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
import asyncio import json import os import pty import shutil import sys import tty import termios import time import threading import tornado.iostream from tornado.ioloop import IOLoop from tornado.websocket import websocket_connect ioloop = tornado.ioloop.IOLoop.instance() SSH_LOGIN = "root" SSH_PASSWORD = "algorave" SCREEN_TO_SCREEN_0_SEQ = b"ls -l\r\x1bOC" + b"\x010" # ^A 0 class Client: mode: str
[ 11748, 30351, 952, 198, 11748, 33918, 198, 11748, 28686, 198, 11748, 279, 774, 198, 11748, 4423, 346, 198, 11748, 25064, 198, 11748, 256, 774, 198, 11748, 3381, 4267, 198, 11748, 640, 198, 11748, 4704, 278, 198, 198, 11748, 33718, 13, 7...
2.602484
161
import abc import logging from typing import Any, Dict, List, Optional from homeassistant.components.water_heater import WaterHeaterEntity from homeassistant.const import ( TEMP_FAHRENHEIT, TEMP_CELSIUS ) from gehomesdk import ErdCode, ErdMeasurementUnits from ...const import DOMAIN from .ge_erd_entity import GeEntity _LOGGER = logging.getLogger(__name__)
[ 11748, 450, 66, 198, 11748, 18931, 198, 6738, 19720, 1330, 4377, 11, 360, 713, 11, 7343, 11, 32233, 198, 198, 6738, 1363, 562, 10167, 13, 5589, 3906, 13, 7050, 62, 258, 729, 1330, 5638, 1544, 729, 32398, 198, 6738, 1363, 562, 10167, ...
3.016393
122
import json from scrapy.item import BaseItem from scrapy.http import Request from scrapy.exceptions import ContractFail from scrapy.contracts import Contract # contracts
[ 11748, 33918, 198, 198, 6738, 15881, 88, 13, 9186, 1330, 7308, 7449, 198, 6738, 15881, 88, 13, 4023, 1330, 19390, 198, 6738, 15881, 88, 13, 1069, 11755, 1330, 17453, 39044, 198, 198, 6738, 15881, 88, 13, 28484, 82, 1330, 17453, 628, 1...
3.847826
46
from keras import backend as K import tensorflow as tf import numpy as np custom_dice_coef = custom_dice_coefficient custom_dice_loss = custom_dice_coefficient_loss dice_coef = dice_coefficient dice_coef_loss = dice_coefficient_loss weighted_crossentropy = weighted_crossentropy_pixelwise predicted_count = prediction_count predicted_sum = prediction_sum ground_truth_count = label_count ground_truth_sum = label_sum pixel_recall = segmentation_recall obj_recall = lession_recall
[ 6738, 41927, 292, 1330, 30203, 355, 509, 198, 11748, 11192, 273, 11125, 355, 48700, 198, 11748, 299, 32152, 355, 45941, 628, 628, 628, 628, 628, 628, 198, 23144, 62, 67, 501, 62, 1073, 891, 796, 2183, 62, 67, 501, 62, 1073, 16814, 1...
2.964286
168
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html from scrapy.exceptions import DropItem from hashlib import md5 from scrapy import log from twisted.enterprise import adbapi from scrapy_template.items import ScrapyTemplateItem
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 2, 2896, 500, 534, 2378, 31108, 994, 198, 2, 198, 2, 2094, 470, 6044, 284, 751, 534, 11523, 284, 262, 7283, 3620, 62, 47, 4061, 3698, 1268, 1546, 4634, 198, 2, ...
3.083333
120
import click import pickle import numpy as np from collections import defaultdict from utils import reset_seeds, get_dataset, load_embeddings from mlp_multilabel_wrapper import PowersetKerasWrapper, MultiOutputKerasWrapper from mlp_utils import CrossLabelDependencyLoss if __name__ == '__main__': run()
[ 11748, 3904, 198, 11748, 2298, 293, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 17268, 1330, 4277, 11600, 198, 6738, 3384, 4487, 1330, 13259, 62, 325, 5379, 11, 651, 62, 19608, 292, 316, 11, 3440, 62, 20521, 67, 654, 198, 6738, 259...
3.12
100
#!/usr/bin/env python # encoding: utf-8 """ evaluate.py Created by Shuailong on 2016-12-2. Evaluate model accuracy on test set. """ from __future__ import print_function from time import time from keras.models import load_model import os from utils import true_accuracy from dataset import get_data from train import MODEL_FILE, MODEL_DIR from train import data_generator if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 21004, 25, 3384, 69, 12, 23, 198, 198, 37811, 198, 49786, 13, 9078, 198, 198, 41972, 416, 32344, 603, 506, 319, 1584, 12, 1065, 12, 17, 13, 198, 198, 36, 2100, 4985, 2746, 9922,...
3.058394
137
#!/usr/bin/env python # Copyright (c) 2013, Digium, Inc. # Copyright (c) 2014-2016, Yelp, Inc. import os from setuptools import setup import bravado setup( name="bravado", # cloudlock version, no twisted dependency version=bravado.version + "cl", license="BSD 3-Clause License", description="Library for accessing Swagger-enabled API's", long_description=open(os.path.join(os.path.dirname(__file__), "README.rst")).read(), author="Digium, Inc. and Yelp, Inc.", author_email="opensource+bravado@yelp.com", url="https://github.com/Yelp/bravado", packages=["bravado"], classifiers=[ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "Topic :: Software Development :: Libraries :: Python Modules", "License :: OSI Approved :: BSD License", "Operating System :: OS Independent", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3.4", ], install_requires=[ "bravado-core >= 4.2.2", "yelp_bytes", "python-dateutil", "pyyaml", "requests", "six", ], extras_require={ }, )
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 15069, 357, 66, 8, 2211, 11, 7367, 1505, 11, 3457, 13, 198, 2, 15069, 357, 66, 8, 1946, 12, 5304, 11, 44628, 11, 3457, 13, 198, 198, 11748, 28686, 198, 198, 6738, 900, 37623, ...
2.367159
542
# Copyright 2013 - Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import pecan from pecan import rest import wsme import wsmeext.pecan as wsme_pecan from solum.api.controllers.v1.datamodel import assembly import solum.api.controllers.v1.userlog as userlog_controller from solum.api.handlers import assembly_handler from solum.common import exception from solum.common import request from solum import objects from solum.openstack.common.gettextutils import _
[ 2, 15069, 2211, 532, 2297, 10983, 11, 3457, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 345, 743, 198, 2, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 921...
3.539855
276
# -*- coding: utf-8 -*- # Generated by Django 1.10.1 on 2018-08-02 07:58 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2980, 515, 416, 37770, 352, 13, 940, 13, 16, 319, 2864, 12, 2919, 12, 2999, 8753, 25, 3365, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, ...
2.73913
69
from agility.usc.enumeration import uscSerialMode, ChannelMode, HomeMode from agility.usc.reader import BytecodeReader
[ 6738, 33546, 13, 16241, 13, 268, 6975, 341, 1330, 514, 66, 32634, 19076, 11, 11102, 19076, 11, 5995, 19076, 198, 6738, 33546, 13, 16241, 13, 46862, 1330, 30589, 8189, 33634, 628, 198 ]
3.78125
32
from .dbApiInterface import DbApiTableInterface from .dbApiTableInterface import DbApiTableInterface from .cacheInterface import CacheInterface from .loggerInterface import LoggerInterface from .envReaderInterface import EnvReaderInterface from .driverInterface import DriverInterface from .jobsInterface import JobsInterface from .jobsInventoryInterface import JobsInventoryInterface from .emailInterface import EmailInterface from .sqlTableInterface import SqlTableInterface
[ 6738, 764, 9945, 32, 14415, 39317, 1330, 360, 65, 32, 14415, 10962, 39317, 198, 6738, 764, 9945, 32, 14415, 10962, 39317, 1330, 360, 65, 32, 14415, 10962, 39317, 198, 6738, 764, 23870, 39317, 1330, 34088, 39317, 198, 6738, 764, 6404, 13...
4.576923
104
import sys import csv import os sys.path.append('../../') import h_lib import h_lib_noSeqSearch in_strFastaFilename = '{!s}/data/protein/18mix/18mix_db_plus_contaminants_20081209.fasta'.format(os.environ.get('HOME')) in_strPeptideFilename = '{!s}/data/protein/18mix/18_mixtures_peptide_identification.txt'.format(os.environ.get('HOME')) out_strOutputBaseDir = './sparseData_h' out_strFile = out_strOutputBaseDir + "/h_noSeqSearch.csv" YInfo = h_lib.getPeptides(in_strPeptideFilename, "\t", 0, 2) ###assuming proteins are already broken to individual files under in_strProtRefsDir #XMatchProb = h_lib.getYInfo(YInfo, in_strProtRefsDir, strXMatchProb_filename, True) XMatchProb = h_lib_noSeqSearch.getXInfo(YInfo, in_strPeptideFilename, "\t", 0, 1) YMatchProbCount = h_lib.getPeptideProteinMatches(YInfo, XMatchProb) h_lib.updateXMatchingProbabilities(XMatchProb, YMatchProbCount) XPred = h_lib.getAccumulatedXMatchingProbabilities(XMatchProb) XPred.sort() with open(out_strFile, "w") as bfFile: for row in XPred: bfFile.write('{!s},{:.6f}\n'.format(row[0], row[1])) print("result saved in:" + out_strFile)
[ 11748, 25064, 198, 11748, 269, 21370, 198, 11748, 28686, 198, 198, 17597, 13, 6978, 13, 33295, 10786, 40720, 40720, 11537, 198, 11748, 289, 62, 8019, 198, 11748, 289, 62, 8019, 62, 3919, 4653, 80, 18243, 198, 198, 259, 62, 2536, 22968, ...
2.473568
454
# for normalization we need to have the maxima of x and y values with the help of which # we can normalise the given values import csv filename = "values.csv" fields = [] rows = [] with open(filename,'r') as csvfile: reader = csv.reader(csvfile) fields = next(reader) for row in reader: rows.append(row) for row in rows: for col in row: a = col[0] norm=50 #a = float(input("enter the x cordinate:")) #b = float(input("enter the y cordinate:")) if (a>norm or b>norm or a<-(norm) or b<-(norm)): print("the value given is invalid/out of bound") else: a = a/norm b = b/norm print("the normalized values are "+str(a)+","+str(b))
[ 2, 329, 3487, 1634, 356, 761, 284, 423, 262, 3509, 8083, 286, 2124, 290, 331, 3815, 351, 262, 1037, 286, 543, 220, 201, 198, 2, 356, 460, 3487, 786, 262, 1813, 3815, 201, 198, 11748, 269, 21370, 201, 198, 34345, 796, 366, 27160, 1...
2.473498
283
from pygdp import _execute_request from pygdp import _get_geotype from owslib.util import log def submitFeatureWeightedGridStatistics(geoType, dataSetURI, varID, startTime, endTime, attribute, value, gmlIDs, verbose, coverage, delim, stat, grpby, timeStep, summAttr, weighted, WFS_URL, outputfname, sleepSecs): """ Makes a featureWeightedGridStatistics algorithm call. The web service interface implemented is summarized here: https://my.usgs.gov/confluence/display/GeoDataPortal/Generating+Area+Weighted+Statistics+Of+A+Gridded+Dataset+For+A+Set+Of+Vector+Polygon+Features Note that varID and stat can be a list of strings. """ # test for dods: dataSetURI = _execute_request.dodsReplace(dataSetURI) log.info('Generating feature collection.') featureCollection = _get_geotype._getFeatureCollectionGeoType(geoType, attribute, value, gmlIDs, WFS_URL) if featureCollection is None: return processid = 'gov.usgs.cida.gdp.wps.algorithm.FeatureWeightedGridStatisticsAlgorithm' if weighted==False: processid = 'gov.usgs.cida.gdp.wps.algorithm.FeatureGridStatisticsAlgorithm' solo_inputs = [("FEATURE_ATTRIBUTE_NAME",attribute), ("DATASET_URI", dataSetURI), ("TIME_START",startTime), ("TIME_END",endTime), ("REQUIRE_FULL_COVERAGE",str(coverage).lower()), ("DELIMITER",delim), ("GROUP_BY", grpby), ("SUMMARIZE_TIMESTEP", str(timeStep).lower()), ("SUMMARIZE_FEATURE_ATTRIBUTE",str(summAttr).lower()), ("FEATURE_COLLECTION", featureCollection)] if isinstance(stat, list): num_stats=len(stat) if num_stats > 7: raise Exception('Too many statistics were submitted.') else: num_stats=1 if isinstance(varID, list): num_varIDs=len(varID) else: num_varIDs=1 inputs = [('','')]*(len(solo_inputs)+num_varIDs+num_stats) count=0 rmvCnt=0 for solo_input in solo_inputs: if solo_input[1]!=None: inputs[count] = solo_input count+=1 else: rmvCnt+=1 del inputs[count:count+rmvCnt] if num_stats > 1: for stat_in in stat: if stat_in not in ["MEAN", "MINIMUM", "MAXIMUM", "VARIANCE", "STD_DEV", "SUM", "COUNT"]: raise Exception('The statistic %s is not in the allowed list: "MEAN", "MINIMUM", "MAXIMUM", "VARIANCE", "STD_DEV", "SUM", "COUNT"' % stat_in) inputs[count] = ("STATISTICS",stat_in) count+=1 elif num_stats == 1: if stat not in ["MEAN", "MINIMUM", "MAXIMUM", "VARIANCE", "STD_DEV", "SUM", "COUNT"]: raise Exception('The statistic %s is not in the allowed list: "MEAN", "MINIMUM", "MAXIMUM", "VARIANCE", "STD_DEV", "SUM", "COUNT"' % stat) inputs[count] = ("STATISTICS",stat) count+=1 if num_varIDs > 1: for var in varID: inputs[count] = ("DATASET_ID",var) count+=1 elif num_varIDs == 1: inputs[count] = ("DATASET_ID",varID) output = "OUTPUT" return _execute_request._executeRequest(processid, inputs, output, verbose, outputfname, sleepSecs)
[ 6738, 12972, 21287, 79, 1330, 4808, 41049, 62, 25927, 198, 6738, 12972, 21287, 79, 1330, 4808, 1136, 62, 469, 8690, 198, 6738, 12334, 6649, 571, 13, 22602, 1330, 2604, 198, 198, 4299, 9199, 38816, 25844, 276, 41339, 48346, 7, 469, 78, ...
2.047703
1,698
import sys import socket conn = socket.create_connection(('0.0.0.0', 8080)) msgs = [ # 0 Keep-Alive, Transfer-Encoding chunked 'GET / HTTP/1.1\r\nConnection: Keep-Alive\r\n\r\n', # 1,2,3 Close, EOF "encoding" 'GET / HTTP/1.1\r\n\r\n', 'GET / HTTP/1.1\r\nConnection: close\r\n\r\n', 'GET / HTTP/1.0\r\nConnection: Keep-Alive\r\n\r\n', # 4 Bad Request 'GET /%20%20% HTTP/1.1\r\n\r\n', # 5 Bug #14 'GET /%20abc HTTP/1.0\r\n\r\n', # 6 Content-{Length, Type} 'GET / HTTP/1.0\r\nContent-Length: 11\r\n' 'Content-Type: text/blah\r\nContent-Fype: bla\r\n' 'Content-Tength: bla\r\n\r\nhello world', # 7 POST memory leak 'POST / HTTP/1.0\r\nContent-Length: 1000\r\n\r\n%s' % ('a'*1000), # 8,9 CVE-2015-0219 'GET / HTTP/1.1\r\nFoo_Bar: bad\r\n\r\n', 'GET / HTTP/1.1\r\nFoo-Bar: good\r\nFoo_Bar: bad\r\n\r\n' ] conn.send(msgs[int(sys.argv[1])].encode()) while 1: data = conn.recv(100) if not data: break print(repr(data)) if data.endswith(b'0\r\n\r\n'): if raw_input('new request? Y/n') == 'n': exit() conn.send(b'GET / HTTP/1.1\r\nConnection: Keep-Alive\r\n\r\n')
[ 11748, 25064, 198, 11748, 17802, 198, 198, 37043, 796, 17802, 13, 17953, 62, 38659, 7, 10786, 15, 13, 15, 13, 15, 13, 15, 3256, 4019, 1795, 4008, 198, 907, 14542, 796, 685, 198, 220, 220, 220, 1303, 657, 9175, 12, 2348, 425, 11, 2...
1.864139
633
# -*- coding: utf-8 -*- from odoo import models
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 6738, 16298, 2238, 1330, 4981, 628 ]
2.380952
21
#WIZARD BOT IS LIVE import calendar import discord as dc from discord.ext.commands import Bot from discord.ext import commands from functools import partial import asyncio as aio import time from random import randint from datetime import datetime from discord.ext import commands from guildconfig import GuildConfig from rolesaver import RoleSaver #initializes bot, sets up command sign bot = commands.Bot(command_prefix = '!') bot.remove_command('help') guild_config = GuildConfig(bot, 'config.pkl') role_saver = RoleSaver(bot, 'roles.pkl') #GAME STUFF #WIZBOT OLD STUFF ENDS HERE #FUNCTIONS HERE def get_token(): with open('token.dat', 'r') as tokenfile: return ''.join( chr(int(''.join(c), 16)) for c in zip(*[iter(tokenfile.read().strip())]*2) ) def monthdelta(date, delta): m, y = (date.month+delta) % 12, date.year + ((date.month)+delta-1) // 12 if not m: m = 12 d = min(date.day, calendar.monthrange(y, m)[1]) return date.replace(day=d, month=m, year=y) #START OF EVENTS #END OF EVENTS #GAME EVENT #ABANDON ALL HOPE YE WHO GO BELOW HERE #END DUEL if __name__ == '__main__': bot.run(get_token())
[ 2, 54, 14887, 9795, 347, 2394, 3180, 28323, 198, 198, 11748, 11845, 198, 11748, 36446, 355, 30736, 220, 198, 6738, 36446, 13, 2302, 13, 9503, 1746, 1330, 18579, 198, 6738, 36446, 13, 2302, 1330, 9729, 198, 6738, 1257, 310, 10141, 1330, ...
2.468813
497
""" Django settings for TusPachangas project. For more information on this file, see https://docs.djangoproject.com/en/1.7/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.7/ref/settings/ """ import django import dj_database_url # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) TEMPLATE_PATH = os.path.join(BASE_DIR, 'templates') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '26*swq94+rg+-2tc2es6j&d#&(g4@@xe7vh1hu1)6*z^v@pd2q' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True TEMPLATE_DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'registration', #add in the registration package 'rest_framework', 'restaurante', 'easy_maps', ) if django.VERSION < (1, 7): INSTALLED_APPS += ( 'south', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = 'ProyectoDAI.urls' WSGI_APPLICATION = 'ProyectoDAI.wsgi.application' TEMPLATE_DIRS = (TEMPLATE_PATH,) # Database # https://docs.djangoproject.com/en/1.7/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } ON_HEROKU = os.environ.get('PORT') if ON_HEROKU: DATABASE_URL='postgres://kytzveedsclzaf:eIJAAuElYvSxPK-vmSdXG9Hjv8@ec2-107-21-219-235.compute-1.amazonaws.com:5432/df9sfr7a9b8vjf' DATABASES = {'default': dj_database_url.config(default=DATABASE_URL)} # Internationalization # https://docs.djangoproject.com/en/1.7/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.7/howto/static-files/ STATIC_PATH = os.path.join(BASE_DIR,'static') STATIC_URL = '/static/' STATICFILES_DIRS = ( STATIC_PATH, ) #Media MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
[ 37811, 198, 35, 73, 14208, 6460, 329, 46233, 47, 620, 648, 292, 1628, 13, 198, 1890, 517, 1321, 319, 428, 2393, 11, 766, 198, 5450, 1378, 31628, 13, 28241, 648, 404, 305, 752, 13, 785, 14, 268, 14, 16, 13, 22, 14, 4852, 873, 14,...
2.371795
1,170
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Utilities for testing tfe code.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.framework import ops as _ops from tensorflow.python.platform import test as _test from tensorflow.python.platform.test import * # pylint: disable=wildcard-import # TODO(akshayka): Do away with this file.
[ 2, 15069, 2177, 383, 309, 22854, 37535, 46665, 13, 1439, 6923, 33876, 13, 201, 198, 2, 201, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 201, 198, 2, 345, 743, 407, 779, 428, 2393, 2...
3.695946
296
import time import pyautogui import win32gui
[ 11748, 640, 198, 11748, 12972, 2306, 519, 9019, 198, 11748, 1592, 2624, 48317, 198 ]
3.214286
14
# # Copyright 2020, Data61, CSIRO (ABN 41 687 119 230) # # SPDX-License-Identifier: BSD-2-Clause # import re import graph_refine.syntax as syntax import graph_refine.problem as problem import graph_refine.stack_logic as stack_logic from graph_refine.syntax import true_term, false_term, mk_not from graph_refine.check import * import graph_refine.search as search import elf_parser import graph_refine.target_objects as target_objects from imm_utils import * from elf_file import * from addr_utils import * from call_graph_utils import gFuncsCalled from dot_utils import toDot,toGraph from addr_utils import gToPAddrP,callNodes
[ 2, 198, 2, 15069, 12131, 11, 6060, 5333, 11, 9429, 43708, 357, 6242, 45, 6073, 718, 5774, 15136, 18395, 8, 198, 2, 198, 2, 30628, 55, 12, 34156, 12, 33234, 7483, 25, 347, 10305, 12, 17, 12, 2601, 682, 198, 2, 198, 198, 11748, 30...
3.048309
207
# Copyright (c) 2010-2017 Samuel Abels # # 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. import os import codecs from simpleparse import parser from .Newline import Newline from .Indent import Indent from .Dedent import Dedent from .util import error _ebnf_file = os.path.join(os.path.dirname(__file__), 'syntax.ebnf') with open(_ebnf_file) as _thefile: _ebnf = _thefile.read()
[ 2, 15069, 357, 66, 8, 3050, 12, 5539, 17100, 2275, 1424, 198, 2, 198, 2, 2448, 3411, 318, 29376, 7520, 11, 1479, 286, 3877, 11, 284, 597, 1048, 16727, 257, 4866, 198, 2, 286, 428, 3788, 290, 3917, 10314, 3696, 357, 1169, 366, 2542...
3.548469
392
BIG_CONSTANT = "YES" print(group_by([1, 2, 3, 4, 5, 6], lambda x: "even" if x % 2 == 0 else "odd"))
[ 3483, 38, 62, 10943, 2257, 8643, 796, 366, 43335, 1, 628, 198, 198, 4798, 7, 8094, 62, 1525, 26933, 16, 11, 362, 11, 513, 11, 604, 11, 642, 11, 718, 4357, 37456, 2124, 25, 366, 10197, 1, 611, 2124, 4064, 362, 6624, 657, 2073, 36...
2.145833
48
# Copyright 2019 StreamSets Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from datetime import datetime import json import logging import os import string import time from streamsets.sdk.models import Configuration from streamsets.testframework.markers import aws, sftp, sdc_min_version from streamsets.testframework.utils import get_random_string logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) # Sandbox prefix for S3 bucket S3_BUCKET_PREFIX = 'sftp_upload'
[ 2, 15069, 13130, 13860, 50, 1039, 3457, 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,...
3.523132
281
import os # Use this as a package level setup
[ 11748, 28686, 628, 198, 2, 5765, 428, 355, 257, 5301, 1241, 9058, 198 ]
3.692308
13
# -*- coding: utf-8 -*- from gi.repository.GdkPixbuf import Pixbuf from os import makedirs if __name__ == "__main__": main()
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 308, 72, 13, 260, 1930, 37765, 13, 38, 34388, 47, 844, 29325, 1330, 21642, 29325, 198, 198, 6738, 28686, 1330, 285, 4335, 17062, 628, 198, 198, 361, 11593, 3672, ...
2.293103
58
# Generated by Django 3.2.8 on 2021-11-21 12:01 from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 513, 13, 17, 13, 23, 319, 33448, 12, 1157, 12, 2481, 1105, 25, 486, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
2.84375
32
from typing import Optional import pandas as pd from ruptures import Binseg from ruptures.base import BaseCost from sklearn.linear_model import LinearRegression from etna.transforms.base import PerSegmentWrapper from etna.transforms.decomposition.change_points_trend import BaseEstimator from etna.transforms.decomposition.change_points_trend import TDetrendModel from etna.transforms.decomposition.change_points_trend import _OneSegmentChangePointsTrendTransform
[ 6738, 19720, 1330, 32233, 198, 198, 11748, 19798, 292, 355, 279, 67, 198, 6738, 31580, 942, 1330, 20828, 325, 70, 198, 6738, 31580, 942, 13, 8692, 1330, 7308, 13729, 198, 6738, 1341, 35720, 13, 29127, 62, 19849, 1330, 44800, 8081, 2234,...
3.55303
132
import xarray as xr import pytest import warnings import argopy from argopy import IndexFetcher as ArgoIndexFetcher from argopy.errors import InvalidFetcherAccessPoint, InvalidFetcher, ErddapServerError, DataNotFound from . import ( AVAILABLE_INDEX_SOURCES, requires_fetcher_index, requires_connected_erddap_index, requires_localftp_index, requires_connection, safe_to_server_errors )
[ 11748, 2124, 18747, 355, 2124, 81, 198, 11748, 12972, 9288, 198, 11748, 14601, 198, 198, 11748, 1822, 11081, 198, 6738, 1822, 11081, 1330, 12901, 37, 316, 2044, 355, 943, 2188, 15732, 37, 316, 2044, 198, 6738, 1822, 11081, 13, 48277, 13...
2.861111
144
import voluptuous as vol from homeassistant.config_entries import ConfigFlow from homeassistant.const import CONF_HOST, CONF_NAME from .acthor import test_connection from .const import DEVICE_NAME, DOMAIN
[ 11748, 2322, 37623, 5623, 355, 2322, 198, 6738, 1363, 562, 10167, 13, 11250, 62, 298, 1678, 1330, 17056, 37535, 198, 6738, 1363, 562, 10167, 13, 9979, 1330, 7102, 37, 62, 39, 10892, 11, 7102, 37, 62, 20608, 198, 198, 6738, 764, 529, ...
3.45
60
NOTES = { 'notes': [ {'date': '2014-05-22T00:00:00Z', 'note': 'Second Note'}, {'date': '2014-05-21T14:02:45Z', 'note': 'First Note'} ] } SUBJECT = { "subject": ['HB1-3840', 'H'] } OWNER = { "owner": "Owner" } EDITORIAL = { "editor_group": "editorgroup", "editor": "associate" } SEAL = { "doaj_seal": True, }
[ 11929, 1546, 796, 1391, 198, 220, 220, 220, 705, 17815, 10354, 685, 198, 220, 220, 220, 220, 220, 220, 220, 1391, 6, 4475, 10354, 705, 4967, 12, 2713, 12, 1828, 51, 405, 25, 405, 25, 405, 57, 3256, 705, 11295, 10354, 705, 12211, 5...
1.913978
186
""" docnado.py A rapid documentation tool that will blow you away. """ import os import re import sys import csv import glob import time import signal import shutil import urllib import base64 import hashlib import argparse import tempfile import datetime import threading import traceback import subprocess import platform import requests from bs4 import BeautifulSoup from multiprocessing import Pool from urllib.parse import urlparse from watchdog.observers import Observer from watchdog.events import PatternMatchingEventHandler from xml.etree import ElementTree from flask import Flask, url_for, abort, send_from_directory, \ render_template, Markup, make_response, render_template_string import markdown import markdown.util from markdown.extensions import Extension from markdown.postprocessors import Postprocessor from markdown.inlinepatterns import LinkPattern, IMAGE_LINK_RE, dequote, handleAttributes from markdown.blockprocessors import HashHeaderProcessor from http.client import responses if __package__: from .navtree import NavItem, parse_nav_string else: from navtree import NavItem, parse_nav_string def as_video(self, m): """ Return a video element """ src, parts = self.get_src(m) el = ElementTree.Element('video') el.set('src', src) el.set("controls", "true") handleAttributes(m.group(2), el) return el def as_image(self, m): """ Return an image element """ el = ElementTree.Element('img') src, parts = self.get_src(m) el.set('src', src) # Set the title if present. if len(parts) > 1: el.set('title', dequote(self.unescape(" ".join(parts[1:])))) # Set the attributes on the element, if enabled. # Set the 'alt' attribute with whatever is left from `handleAttributes`. attrs = self.markdown.enable_attributes alt_text = handleAttributes(m.group(2), el) if attrs else m.group(2) el.set('alt', self.unescape(alt_text)) return el def as_download(self, m): """ Create card layers used to make a download button. """ src, parts = self.get_src(m) # Returns a human readable string representation of bytes # Get information required for card. split_src = os.path.split(src) file_path = os.path.join(self.markdown.page_root, *split_src) file_size = os.path.getsize(file_path) file_basename = os.path.basename(file_path) card_text = dequote(self.unescape(" ".join(parts[1:]))) if len(parts) > 1 else '' # If its a pptx, extract the thumbnail previews. # NOTE: This works, but is is removed until we support other # file types, which for now is not a priority. # preview_uri = None # import zipfile # if (file_path.endswith('pptx')): # with zipfile.ZipFile(file_path) as zipper: # with zipper.open('docProps/thumbnail.jpeg', 'r') as fp: # mime = 'image/jpeg' # data64 = base64.b64encode(fp.read()).decode('utf-8') # preview_uri = u'data:%s;base64,%s' % (mime, data64) # Card and structure. card = ElementTree.Element("div") card.set('class', 'card download-card') header = ElementTree.SubElement(card, 'div') header.set('class', 'download-card-header') body = ElementTree.SubElement(card, 'div') body.set('class', 'download-card-body') # Add preview image. # if preview_uri: # img = ET.SubElement(header, 'img') # img.set('src', preview_uri) # Filename link heading. heading = ElementTree.SubElement(body, 'a') heading.set('class', 'download-card-title') heading.set('href', src) download_icon = ElementTree.SubElement(heading, 'i') download_icon.set('class', 'fa fa-download') download_text = ElementTree.SubElement(heading, 'span') download_text.text = file_basename # Title element from the "quote marks" part. body_desc = ElementTree.SubElement(body, 'span') body_desc.text = card_text # File size span at the bottom. body_size = ElementTree.SubElement(body, 'span') body_size.set('class', 'small text-muted') body_size.text = f'{_human_size(file_size)}' return card def as_raw(self, m): """ Load the HTML document specified in the link, parse it to HTML elements and return it. """ src, parts = self.get_src(m) # Find the path to the HTML document, relative to the current markdown page. file_path = os.path.join(self.markdown.page_root, src) raw_html_string = read_html_for_injection(file_path) if len(parts) < 2: parts.append("nothing_one=1||nothing_two=2") # Helper function. # Split arg string on double pipe. Joins them to undo automattic splitting from the markdown. arg_strings = " ".join(parts[1:]).strip('\"').split("||") # Parse into dictionary of key-value pairs based on the '=' notation. try: named_args = dict([_argify(args) for args in arg_strings]) except Exception as e: raise Exception(f"Error parsing ![INJECT] arguments in {self.markdown.page_file} {repr(e)}") # Take the template renderer and give it our string, and named args. # Capture the output as a string. try: injectable_templated_str = render_template_string(raw_html_string, **named_args) except Exception as e: raise Exception(f"Error rendering ![INJECT] template for file {file_path} {repr(e)}") # Feed that string to the XML parser. try: return ElementTree.fromstring(injectable_templated_str) except Exception as e: raise Exception(f"Error parsing ![INJECT] template for file {file_path} {repr(e)}") def handleMatch(self, m): """ Use the URL extension to render the link. """ src, parts = self.get_src(m) if self._is_download(m): return self.as_download(m) elif self._is_inject(m): return self.as_raw(m) youtube = self.youtube_url_validation(src) if youtube: return self.as_youtube(m, youtube) src_lower = src.lower() if src_lower.endswith(self.SUPPORTED_TABLES): return self.as_csv(m) elif src_lower.endswith(self.SUPPORTED_PDF): return self.as_pdf(m) elif src_lower.endswith(self.SUPPORTED_VIDEO): return self.as_video(m) return self.as_image(m) class OffsetHashHeaderProcessor(HashHeaderProcessor): """ Process hash headers with an offset to control the type of heading DOM element that is generated. """ HEADING_LEVEL_OFFSET = 1 class ChecklistPostprocessor(Postprocessor): """ Adds checklist class to list element. Adapted from: `markdown_checklist.extension` """ pattern = re.compile(r'<li>\[([ Xx])\]') # Remove the `video`, `iframe`, `aside`, and `table` elements as block elements. markdown.util.BLOCK_LEVEL_ELEMENTS = re.compile( r"^(p|div|h[1-6]|blockquote|pre|dl|ol|ul" r"|script|noscript|form|fieldset|math" r"|hr|hr/|style|li|dt|dd|thead|tbody" r"|tr|th|td|section|footer|header|group|figure" r"|figcaption|article|canvas|output" r"|progress|nav|main)$", re.IGNORECASE ) # https://python-markdown.github.io/extensions/ mdextensions = [MultiExtension(), 'markdown.extensions.tables', 'markdown.extensions.meta', 'markdown.extensions.def_list', 'markdown.extensions.headerid', 'markdown.extensions.fenced_code', 'markdown.extensions.attr_list'] def build_meta_cache(root): """ Recursively search for Markdown files and build a cache of `Meta` from metadata in the Markdown. :param root: str: The path to search for files from. """ doc_files = glob.iglob(root + '/**/*.md', recursive=True) doc_files_meta = {os.path.relpath(path, start=root): _meta(path) for path in doc_files} doc_files_meta = {path: value for path, value in doc_files_meta.items() if value is not None} # If a nav filter is set, exclude relevant documents. # This takes the comma separated string supplied to `nav_limit` # and excludes certain documents if they are NOT in this list. global CMD_ARGS if CMD_ARGS.nav_limit: nav_filters = CMD_ARGS.nav_limit.split(',') nav_filters = [nav_filter.strip().lower() for nav_filter in nav_filters] nav_filters = [nav_filter for nav_filter in nav_filters if nav_filter] doc_files_meta = {path: value for path, value in doc_files_meta.items() if _should_include(value)} return doc_files_meta def build_nav_menu(meta_cache): """ Given a cache of Markdown `Meta` data, compile a structure that can be used to generate the NAV menu. This uses the `nav: Assembly>Bench>Part` variable at the top of the Markdown file. """ root = NavItem('root', 0) # Pre-sort the nav-items alphabetically by nav-string. This will get overridden with the arange() # function, but this avoids-un arranged items moving round between page refreshes due to Dicts being # unordered. sorted_meta_cache = sorted( meta_cache.items(), key = lambda items: items[1].get('nav', [''])[0].split('>')[-1] # Sort by the last part of the nav string for each page. ) for path, meta in sorted_meta_cache: nav_str = meta.get('nav', [None])[0] nav_chunks = parse_nav_string(nav_str) node = root for name, weight in nav_chunks: n = NavItem(name, weight) node = node.add(n) node.bind(meta=meta, link=path) root.arrange() return root def build_reload_files_list(extra_dirs): """ Given a list of directories, return a list of files to watch for modification and subsequent server reload. """ extra_files = extra_dirs[:] for extra_dir in extra_dirs: for dirname, dirs, files in os.walk(extra_dir): for filename in files: filename = os.path.join(dirname, filename) if os.path.isfile(filename): extra_files.append(filename) return extra_files def read_html_for_injection(path): """ Open an HTML file at the given path and return the contents as a string. If the file does not exist, we raise an exception. """ # TODO: In the future, consider adding some caching here. However, # beware of reloading / refereshing the page UX implications. with open(path) as file: return file.read() def _render_markdown(file_path, **kwargs): """ Given a `file_path` render the Markdown and return the result of `render_template`. """ global NAV_MENU, PROJECT_LOGO, PDF_GENERATION_ENABLED default_template = 'document' with open(file_path, 'r', encoding='utf-8') as f: md = markdown.Markdown(extensions=mdextensions) md.page_root = os.path.dirname(file_path) md.page_file = file_path markup = Markup(md.convert(f.read())) # Fetch the template defined in the metadata. template = md.Meta.get('template', None) template = template[0] if template else default_template if not template: raise Exception('no template found for document') template = f'{template}.html' # Load any HTML to be injected from the meta-data. injections = md.Meta.get('inject', []) injections = [os.path.join(md.page_root, file) for file in injections] injections = [read_html_for_injection(file) for file in injections] # Render it out with all the prepared data. return render_template(template, content=markup, nav_menu=NAV_MENU, project_logo=PROJECT_LOGO, pdf_enabled=PDF_GENERATION_ENABLED, injections=injections, **md.Meta, **kwargs) def configure_flask(app, root_dir): """ Setup the flask application within this scope. """ # Store the reference to the function that rebuilds the navigation cache. app.build_navigation_cache = build_navigation_cache def generate_static_pdf(app, root_dir, output_dir, nav_filter=None): """ Generate a static PDF directory for the documentation in `root_dir` into `output_dir`. """ global PORT_NUMBER # Find all markdown document paths that are in the nav. documents = build_meta_cache(root_dir) markdown_docs_urls = ['pdf/' + file.replace('\\', '/') for file in documents.keys()] # Generate URl to file pairs. pairs = [(f'http://localhost:{PORT_NUMBER}/{url}', f'{os.path.join(output_dir, *os.path.split(url))}.pdf') for url in markdown_docs_urls] # Download each pair. for source, target in pairs: os.makedirs(os.path.dirname(target), exist_ok=True) print(f'Source: {source} \n Target: {target}') urllib.request.urlretrieve(source, target) # Helper function to return the domain if present. def is_absolute(url): """ Returns True if the passed url string is an absolute path. False if not """ links = urlparse(url) return bool(links.netloc) def generate_static_html(app, root_dir, output_dir): """ Generate a static HTML site for the documentation in `root_dir` into `output_dir`. """ from flask_frozen import Freezer, MissingURLGeneratorWarning import warnings warnings.filterwarnings("ignore", category=MissingURLGeneratorWarning) # Update the flask config. app.config['FREEZER_RELATIVE_URLS'] = True app.config['FREEZER_IGNORE_MIMETYPE_WARNINGS'] = True app.config['FREEZER_DESTINATION'] = output_dir # Create the freezer app. Make it use specific URLs. freezer = Freezer(app, with_no_argument_rules=False, log_url_for=False) # Register a generator that passes ALL files in the docs directory into the # `wiki` flask route. # Save all the URLs using the correct extension and MIME type. freezer.freeze() # For each `.md` file in the output directory: for markdown_file in glob.iglob(f'{output_dir}/**/*.md', recursive=True): # Rewrite all relative links to other `.md` files to `.html.` output = '' with open(markdown_file, 'r', encoding="utf-8") as f: html = f.read() output = re.sub('href="(.*md)"', _href_replace, html) # Rename the file from `.md` to HTML. with open(markdown_file[:-3] + '.html', 'w', encoding="utf-8") as f: f.write(output) # Delete the Markdown file. os.remove(markdown_file) def load_project_logo(logo_file=None): """ Attempt to load the project logo from the specified path. If this fails, return None. If this succeeds, convert it to a data-uri. """ if not logo_file: return None if not os.path.exists(logo_file): return None with open(logo_file, 'rb') as fp: mime = 'image/png' data64 = base64.b64encode(fp.read()).decode('utf-8') preview_uri = u'data:%s;base64,%s' % (mime, data64) return preview_uri def check_pdf_generation_cap(): """ Check to see if we can use PDF generation by attempting to use the binary. """ global WKHTMLTOPDF_BINARY retcode = subprocess.call(f'{WKHTMLTOPDF_BINARY} --version', shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) return retcode == 0 def copy_local_project(force=False): """ Copy the sample docs and style into the local working directory. Note: This will overwrite anything currently in those folders. """ source_root = os.path.dirname(__file__) target_root = os.getcwd() targets = ['docs', 'style', 'logo.png'] pairs = [(os.path.join(source_root, path), os.path.join(target_root, path)) for path in targets] for source, target in pairs: if os.path.isdir(source): if os.path.exists(target): if force: print(f'Deleting existing {target} and replacing it with {target}') shutil.rmtree(target) shutil.copytree(source, target) else: print(f'Warning: {target} already exists.') else: print(f'Copying: {source} -> {target}') shutil.copytree(source, target) else: if os.path.exists(target): if force: print(f'Deleting existing {target} and replacing it with {target}') os.remove(target) shutil.copyfile(source, target) else: print(f'Warning: {target} already exists.') else: print(f'Copying: {source} -> {target}') shutil.copyfile(source, target) def find_references(document_path): """ Search through the markdown 'document_path' and make a list of referenced files with paths that are relative to the directory containing the `document_path`. """ # Open the file to search. with open(document_path, 'r', encoding='utf-8') as f: markdown_raw_data = f.read() # Render as HTML. md = markdown.Markdown(extensions=mdextensions) document_dir = os.path.dirname(document_path) md.page_root = document_dir # Interpret with the BeautifulSoup HTML scraping library. soup = BeautifulSoup(md.convert(markdown_raw_data), 'html.parser') tags_to_search = { 'img': 'src', 'a': 'href', 'video': 'src', 'table': 'source', 'embed': 'src', } # For each entry in the `tags_to_search` table, extract the tag attribute value. references = set() for k, v in tags_to_search.items(): for tag in soup.find_all(k): val = tag.get(v) if val: references.add(val) # Normalise the referenced assets (to take into account relative paths). references = [os.path.join(document_dir, urllib.request.url2pathname(ref)) for ref in references] # Make unique. return set(references) def has_nav(markdown_text): """ Returns True if the passed string of text contains navbar metadata. Returns False if it does not. """ expression = re.compile(r'(?=\n|)nav:\s+\w+(?=\n |)') return True if expression.search(markdown_text) else False def find_orphans(files): """ Searches all files and folders recursively in the given path for image and video assets that are unused by markdown files. """ # Find all references in pages = {} for file in files: if file.endswith('.md'): pages[file] = find_references(file) # Remove the markdown documents that have a navbar metadata. md_with_nav = [] for file in files: if file.endswith('.md'): with open(file, encoding='utf-8') as f: if has_nav(f.read().lower()): md_with_nav.append(file) files = [x for x in files if x not in md_with_nav] # Create a flat list of all references in the markdown files all_references = [] for i in pages.values(): all_references += [k for k in i] # Output unused assets return [i for i in files if i not in all_references] def generate_metadata(path): """ Add relevant metadata to the top of the markdown file at the passed path. Title is drawn from the filename, Date from the last modified timestamp, Version defaults at 1.0.0, Nav is generated from the filepath, and Authors are generated from the git contributors (if applicable) and are otherwise left blank. Warning: Does not check if there is existing metadata. """ s = subprocess.getoutput(f"git log -p {path}") lines = s.split(os.linesep) authors = set([re.search(r'<(.*)>', line).group(1)for line in lines if 'Author:' in line]) file_status = os.stat(path) nav_path = os.path.sep.join(path.split(os.path.sep)[1:]) metadata = { 'title': ' '.join( path .split('.')[0] .split(os.path.sep)[-1] .replace('_', ' ') .replace('-', ' ') .title() .split() ), 'desc': '', 'date': datetime.datetime.utcfromtimestamp(file_status.st_mtime).strftime('%Y/%m/%d'), 'version': '1.0.0', 'template': '', 'nav': nav_path.replace(os.path.sep, '>').title().split('.')[0], 'percent': '100', 'authors': ' '.join(authors), } result = "" for key in metadata.keys(): result += ('{}:{}{}\n'.format(key, '\t' if len(key) > 6 else '\t\t', metadata[key])) with open(path, 'r+', encoding='utf-8') as f: content = f.read() f.seek(0, 0) f.write(result) f.write(content) class ReloadHandler(PatternMatchingEventHandler): """ Rebuild the document metadata / navigation cache when markdown files are updated in the documents directory. """ global CMD_ARGS, NAV_MENU, PROJECT_LOGO, WKHTMLTOPDF_BINARY, PDF_GENERATION_ENABLED, PORT_NUMBER CMD_ARGS = None NAV_MENU = {} PROJECT_LOGO = None WKHTMLTOPDF_BINARY = None PDF_GENERATION_ENABLED = False def main(): """ Application entrypoint. """ global PORT_NUMBER PORT_NUMBER = 5000 # Parse the command line arguments. parser = argparse.ArgumentParser(description='docnado: Lightweight tool for rendering \ Markdown documentation with different templates.') parser.add_argument('--html', action='store', dest='html_output_dir', help='Generate a static site from the server and output to the \ specified directory.') parser.add_argument('--pdf', action='store', dest='pdf_output_dir', help='Generate static PDFs from the server and output to the \ specified directory.') parser.add_argument('--nav-limit', action='store', dest='nav_limit', default=None, help='Include certain document trees only based on a comma separated \ list of nav strings. e.g. Tooling,Document') parser.add_argument('--new', action="store_true", dest='new_project', default=False, help='Copy the `docs` and `styles` folder into the working directory \ and output a config file that addresses them. Does not overwrite existing files.') parser.add_argument('--new-force', action="store_true", dest='new_project_force', default=False, help='Copy the `docs` and `styles` folder into the working directory \ and output a config file that addresses them. Force deletion of existing files.') parser.add_argument('--dirs', action="store_true", dest='show_dirs', default=False, help='Display the different directories the software is using \ to search for documentation and styles.') parser.add_argument('--generate-meta', action="store", dest='generate_meta', default=False, help='Generate metadata for markdown files in the specified directory.') parser.add_argument('--find-orphans', action="store_true", dest='find_orphans', default=False, help='Identify unused media assets (orphans)') parser.add_argument('--find-broken-links', action="store_true", dest='find_broken_links', default=False, help='Identify broken external links.') parser.add_argument('--port', action="store", dest='new_port_number', default=False, help='Specify a port for the docnado server') parser.add_argument('--host', action="store", dest='set_host', default=False, help='Set the docnado development server to listen on IP addresses.') # Import the command line args and make them application global. global CMD_ARGS args = parser.parse_args() CMD_ARGS = args # Load config from the environment and validate it. global PROJECT_LOGO, PDF_GENERATION_ENABLED, NAV_MENU, WKHTMLTOPDF_BINARY TRUE = 'TRUE' FALSE = 'FALSE' flask_debug = os.environ.get('DN_FLASK_DEBUG', FALSE) == TRUE watch_changes = os.environ.get('DN_RELOAD_ON_CHANGES', TRUE) == TRUE WKHTMLTOPDF_BINARY = ('wkhtmltopdf_0.12.5.exe' if platform.system() == 'Windows' else 'wkhtmltopdf') PDF_GENERATION_ENABLED = check_pdf_generation_cap() dir_documents = os.environ.get('DN_DOCS_DIR', os.path.join(os.getcwd(), 'docs')) dir_style = os.environ.get('DN_STYLE_DIR', os.path.join(os.getcwd(), 'style')) logo_location = os.environ.get('DN_PROJECT_LOGO', os.path.join(os.getcwd(), 'logo.png')) # If `style` folder does not exist, use the one in site-packages. if not os.path.exists(dir_style) and not os.path.isdir(dir_style): dir_style = os.path.join(os.path.dirname(__file__), 'style') # Attempt to load the project logo into a base64 data uri. PROJECT_LOGO = load_project_logo(logo_location) # Compute the static and template directories. dir_static = os.path.join(dir_style, 'static') dir_templates = os.path.join(dir_style, 'templates') # If the user is asking to create a new project. if args.new_project: copy_local_project() sys.exit() if args.new_project_force: copy_local_project(force=True) return 0 if args.new_port_number: PORT_NUMBER = int(args.new_port_number) if args.generate_meta: doc_files = glob.iglob(args.generate_meta + '/**/*.md', recursive=True) for i in doc_files: generate_metadata(i) return 0 if args.find_orphans: # Find all the assets in the directory/subdirectories recursively and append their file path to a list. files = glob.glob((dir_documents + '/**/*.*'), recursive=True) files = [f for f in files if not os.path.isdir(f)] orphans = find_orphans(files) if orphans: print(f'{len(orphans)} Unused assets (orphans):\n\t' + '\n\t'.join(orphans)) return -1 return 0 if args.find_broken_links: process_pool = Pool(processes=10) md_files = glob.glob((dir_documents + '/**/*.md'), recursive=True) md_reports = tuple((md, list(DocumentLinks(md).detect_broken_links(process_pool))) for md in md_files) num_broken = 0 for file, report in md_reports: if report: num_broken += len(report) print(f'{file}\n\t' + '\n\t'.join(report)) return -1 if num_broken else 0 if args.show_dirs: print('The following directories are being used: ') print('\t', f'Documents -> {dir_documents}') print('\t', f'Logo -> {logo_location}') print('\t', f'Style -> {dir_style}') print('\t', f' Static -> {dir_static}') print('\t', f' Templates -> {dir_templates}') sys.exit() if not os.path.exists(dir_documents) and not os.path.isdir(dir_documents): print(f'Error: Documents directory "{dir_documents}" does not exist. \ Create one called `docs` and fill it with your documentation.', file=sys.stderr) sys.exit(-1) if not os.path.exists(dir_static) and not os.path.isdir(dir_static): print(f'Error: Static directory "{dir_static}" does not exist.', file=sys.stderr) sys.exit(-1) if not os.path.exists(dir_templates) and not os.path.isdir(dir_templates): print(f'Error: Templates directory "{dir_templates}" does not exist.', file=sys.stderr) sys.exit(-1) # Create the server. app = Flask(__name__, static_url_path='', template_folder=dir_templates, static_folder=dir_static) # Attach routes and filters. configure_flask(app, dir_documents) # Output PDF files. if args.pdf_output_dir: if not check_pdf_generation_cap(): print(f'Error: PDF generation requires WkHTMLtoPDF.', file=sys.stderr) sys.exit(-1) t1 = threading.Thread(target=gen_pdfs) t1.start() app.run(debug=flask_debug, threaded=True, port=PORT_NUMBER) sys.exit() # Output a static site. if args.html_output_dir: PDF_GENERATION_ENABLED = False try: generate_static_html(app, dir_documents, os.path.join(os.getcwd(), args.html_output_dir)) index_html = """ <!DOCTYPE html> <html> <head> <meta http-equiv="refresh" content="0; url=./w/"> </head> <body> </body> </html>""" with open(os.path.join(os.getcwd(), args.html_output_dir, 'index.html'), 'w') as f: f.write(index_html) except Exception: traceback.print_exc(file=sys.stderr) sys.exit(-1) sys.exit() # Watch for any changes in the docs or style directories. dn_watch_files = [] observer = None if watch_changes: observer = Observer() observer.schedule(ReloadHandler(app), path=dir_documents, recursive=True) observer.start() dn_watch_files = build_reload_files_list([__name__, dir_style]) # Run the server. if args.set_host: try: print('Attempting set sevelopment server listen on public IP address: ' + args.set_host) print('WARNING: The Docnado development environment is intended to be used as a development tool ONLY, ' 'and is not recommended for use in a production environment.') app.run(debug=flask_debug, port=PORT_NUMBER, extra_files=dn_watch_files, host=args.set_host) except OSError as e: print(e) print(f'Error initialising server.') except KeyboardInterrupt: pass finally: if observer: observer.stop() observer.join() else: try: app.run(debug=flask_debug, port=PORT_NUMBER, extra_files=dn_watch_files) except OSError as e: print(e) print(f'Error initialising server.') except KeyboardInterrupt: pass finally: if observer: observer.stop() observer.join() # if running brainerd directly, boot the app if __name__ == "__main__": main()
[ 37811, 2205, 77, 4533, 13, 9078, 198, 198, 32, 5801, 10314, 2891, 326, 481, 6611, 345, 1497, 13, 198, 198, 37811, 198, 198, 11748, 28686, 198, 11748, 302, 198, 11748, 25064, 198, 11748, 269, 21370, 198, 11748, 15095, 198, 11748, 640, ...
2.347627
13,339
from decimal import Decimal as D from django.core import exceptions from django.test import TestCase from oscar.test import factories from oscar.test.basket import add_product, add_products from django_redis import get_redis_connection from oscarbluelight.offer.models import ( Range, Benefit, BluelightCountCondition, BluelightValueCondition, BluelightPercentageDiscountBenefit, ) from unittest import mock
[ 6738, 32465, 1330, 4280, 4402, 355, 360, 198, 6738, 42625, 14208, 13, 7295, 1330, 13269, 198, 6738, 42625, 14208, 13, 9288, 1330, 6208, 20448, 198, 6738, 267, 13034, 13, 9288, 1330, 17590, 198, 6738, 267, 13034, 13, 9288, 13, 65, 11715,...
3.214815
135
# Moving around directories with pushd & popd # You can save directries to go back to later. These can be built up in a stack. #pushd i/like/icecream # current stack: ~temp/i/like/icecream #pushd i/like # current stack: ~temp/i/like ~temp/i/like/icecream #popd # PS ~temp/i/like #popd # PS ~temp/i/like/icecream # You can also add a directory as an argument to a pushd command to also immediately change to that directory
[ 2, 26768, 1088, 29196, 351, 4574, 67, 1222, 1461, 67, 201, 198, 201, 198, 2, 921, 460, 3613, 1277, 1678, 284, 467, 736, 284, 1568, 13, 2312, 460, 307, 3170, 510, 287, 257, 8931, 13, 201, 198, 2, 14689, 67, 1312, 14, 2339, 14, 50...
2.919463
149
# -*- coding: utf-8 -*- import json from nose.tools import eq_, ok_ from rest_framework.exceptions import ParseError from django.contrib.auth.models import AnonymousUser from django.test.client import RequestFactory from django.test.utils import override_settings import mkt from mkt.constants.applications import DEVICE_CHOICES_IDS from mkt.constants.features import FeatureProfile from mkt.search.filters import (DeviceTypeFilter, ProfileFilter, PublicAppsFilter, PublicSearchFormFilter, RegionFilter, SearchQueryFilter, SortingFilter, ValidAppsFilter) from mkt.search.forms import TARAKO_CATEGORIES_MAPPING from mkt.search.views import SearchView from mkt.site.tests import TestCase from mkt.webapps.indexers import WebappIndexer
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 33918, 198, 198, 6738, 9686, 13, 31391, 1330, 37430, 62, 11, 12876, 62, 198, 6738, 1334, 62, 30604, 13, 1069, 11755, 1330, 2547, 325, 12331, 198, 198, 6738, 42625...
2.647799
318
# MIT License # # Copyright (c) 2019 Johan Brichau # # 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. import sys CRITICAL = 50 ERROR = 40 WARNING = 30 INFO = 20 DEBUG = 10 NOTSET = 0 _level_dict = { CRITICAL: "CRIT", ERROR: "ERROR", WARNING: "WARN", INFO: "INFO", DEBUG: "DEBUG", } _stream = sys.stderr _level = INFO _loggers = {}
[ 2, 17168, 13789, 198, 2, 220, 198, 2, 15069, 357, 66, 8, 13130, 16053, 272, 1709, 488, 559, 198, 2, 220, 198, 2, 2448, 3411, 318, 29376, 7520, 11, 1479, 286, 3877, 11, 284, 597, 1048, 16727, 257, 4866, 198, 2, 286, 428, 3788, 29...
3.299043
418
# Generated by Django 3.1.6 on 2021-02-12 19:43 from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 513, 13, 16, 13, 21, 319, 33448, 12, 2999, 12, 1065, 678, 25, 3559, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
2.84375
32
import nox SOURCE_FILES = ( "setup.py", "noxfile.py", "elastic_workplace_search/", "tests/", )
[ 11748, 645, 87, 628, 198, 47690, 62, 46700, 1546, 796, 357, 198, 220, 220, 220, 366, 40406, 13, 9078, 1600, 198, 220, 220, 220, 366, 35420, 7753, 13, 9078, 1600, 198, 220, 220, 220, 366, 417, 3477, 62, 1818, 5372, 62, 12947, 14, 1...
2.071429
56
# !/usr/bin/env python import rospy import numpy as np from gazebo_msgs.srv import SpawnModel, SpawnModelRequest, SpawnModelResponse from copy import deepcopy from tf.transformations import quaternion_from_euler sdf_cube = """<?xml version="1.0" ?> <sdf version="1.4"> <model name="MODELNAME"> <static>0</static> <link name="link"> <inertial> <mass>1.0</mass> <inertia> <ixx>0.01</ixx> <ixy>0.0</ixy> <ixz>0.0</ixz> <iyy>0.01</iyy> <iyz>0.0</iyz> <izz>0.01</izz> </inertia> </inertial> <collision name="stairs_collision0"> <pose>0 0 0 0 0 0</pose> <geometry> <box> <size>SIZEXYZ</size> </box> </geometry> <surface> <bounce /> <friction> <ode> <mu>1.0</mu> <mu2>1.0</mu2> </ode> </friction> <contact> <ode> <kp>10000000.0</kp> <kd>1.0</kd> <min_depth>0.0</min_depth> <max_vel>0.0</max_vel> </ode> </contact> </surface> </collision> <visual name="stairs_visual0"> <pose>0 0 0 0 0 0</pose> <geometry> <box> <size>SIZEXYZ</size> </box> </geometry> <material> <script> <uri>file://media/materials/scripts/gazebo.material</uri> <name>Gazebo/Wood</name> </script> </material> </visual> <velocity_decay> <linear>0.000000</linear> <angular>0.000000</angular> </velocity_decay> <self_collide>0</self_collide> <kinematic>0</kinematic> <gravity>1</gravity> </link> </model> </sdf> """ sdf_sand = """<?xml version='1.0'?> <sdf version='1.6'> <model name="MODELNAME"> <link name='link'> <pose frame=''>0 0 0.01 0 0 0 </pose> <inertial> <mass>1</mass> <inertia> <ixx>0.1</ixx> <ixy>0</ixy> <ixz>0</ixz> <iyy>0.1</iyy> <iyz>0</iyz> <izz>0.1</izz> </inertia> </inertial> <visual name='visual'> <pose frame=''>0 0 0 0 -0 0</pose> <geometry> <mesh> <scale>SIZEXYZ</scale> <uri>model://sand/sand_particle.stl</uri> </mesh> </geometry> <material> <lighting>1</lighting> <script> <uri>file://media/materials/scripts/gazebo.material</uri> <name>Gazebo/Yellow</name> </script> <ambient>0.3 0.25 0.1 1</ambient> <diffuse>0.7 0.6 0.4 1</diffuse> <specular>0.01 0.005 0.001 1</specular> <emissive>0 0 0 1</emissive> </material> <transparency>0</transparency> <cast_shadows>1</cast_shadows> </visual> <collision name='collision'> <laser_retro>0</laser_retro> <max_contacts>10</max_contacts> <pose frame=''>0 0 0 0 -0 0</pose> <geometry> <mesh> <scale>SIZEXYZ</scale> <uri>model://sand/sand_particle.stl</uri> </mesh> </geometry> <surface> <friction> <ode> <mu>1</mu> <mu2>1</mu2> <fdir1>0 0 0</fdir1> <slip1>0</slip1> <slip2>0</slip2> </ode> <torsional> <coefficient>1</coefficient> <patch_radius>0</patch_radius> <surface_radius>0</surface_radius> <use_patch_radius>1</use_patch_radius> <ode> <slip>0</slip> </ode> </torsional> </friction> <bounce> <restitution_coefficient>0.2</restitution_coefficient> <threshold>1.01</threshold> </bounce> <contact> <collide_without_contact>0</collide_without_contact> <collide_without_contact_bitmask>1</collide_without_contact_bitmask> <collide_bitmask>1</collide_bitmask> <ode> <soft_cfm>0</soft_cfm> <soft_erp>0.2</soft_erp> <kp>1e+13</kp> <kd>1</kd> <max_vel>0.01</max_vel> <min_depth>0</min_depth> </ode> <bullet> <split_impulse>1</split_impulse> <split_impulse_penetration_threshold>-0.01</split_impulse_penetration_threshold> <soft_cfm>0</soft_cfm> <soft_erp>0.2</soft_erp> <kp>1e+13</kp> <kd>1</kd> </bullet> </contact> </surface> </collision> </link> <static>0</static> <allow_auto_disable>1</allow_auto_disable> </model> </sdf> """ sdf_sand_box = """<sdf version='1.6'> <model name='sand_box_osher'> <link name='sand_box_osher'> <pose frame=''>0 0 0 0 -0 0</pose> <inertial> <pose frame=''>-0.35285 -0.305 0.11027 0 -0 0</pose> <mass>2000.892</mass> <inertia> <ixx>130.2204</ixx> <ixy>-220.5538e-15</ixy> <ixz>-4.85191</ixz> <iyy>276.363</iyy> <iyz>-77.9029e-15</iyz> <izz>135.62</izz> </inertia> </inertial> <collision name='sand_box_osher_collision'> <pose frame=''>0 0 0 1.5708 -0 0</pose> <geometry> <mesh> <scale>1 0.8 1</scale> <uri>model://sand_box_osher/meshes/sand_box_osher.STL</uri> </mesh> </geometry> </collision> <visual name='sand_box_osher_visual'> <pose frame=''>0 0 0 1.5708 -0 0</pose> <geometry> <mesh> <scale>1 0.8 1</scale> <uri>model://sand_box_osher/meshes/sand_box_osher.STL</uri> </mesh> </geometry> <material> <ambient>0.3 0.25 0.1 1</ambient> <diffuse>0.7 0.6 0.4 1</diffuse> <specular>0.01 0.005 0.001 1</specular> <emissive>0 0 0 1</emissive> </material> <transparency>0.5</transparency> </visual> </link> </model> </sdf> """ sdf_unit_sphere = """<?xml version='1.0'?> <sdf version='1.6'> <model name="MODELNAME"> <link name='link'> <pose frame=''>0 0 0 0 -0 0</pose> <inertial> <mass>0.1</mass> <inertia> <ixx>0.0000490147</ixx> <ixy>0</ixy> <ixz>0</ixz> <iyy>0.000049147</iyy> <iyz>0</iyz> <izz>0.000049147</izz> </inertia> <pose frame=''>0 0 0 0 -0 0</pose> </inertial> <self_collide>0</self_collide> <kinematic>0</kinematic> <visual name='visual'> <geometry> <sphere> <radius>RADIUS</radius> </sphere> </geometry> <material> <lighting>1</lighting> <script> <uri>file://media/materials/scripts/gazebo.material</uri> <name>Gazebo/Yellow</name> </script> <ambient>0.3 0.25 0.1 1</ambient> <diffuse>0.7 0.6 0.4 1</diffuse> <specular>0.01 0.005 0.001 1</specular> <emissive>0 0 0 1</emissive> </material> <pose frame=''>0 0 0 0 -0 0</pose> <transparency>0</transparency> <cast_shadows>1</cast_shadows> </visual> <collision name='collision'> <laser_retro>0</laser_retro> <max_contacts>10</max_contacts> <pose frame=''>0 0 0 0 -0 0</pose> <geometry> <sphere> <radius>RADIUS</radius> </sphere> </geometry> <surface> <friction> <ode> <mu>1</mu> <mu2>1</mu2> <fdir1>0 0 0</fdir1> <slip1>0</slip1> <slip2>0</slip2> </ode> <torsional> <coefficient>1</coefficient> <patch_radius>0</patch_radius> <surface_radius>0</surface_radius> <use_patch_radius>1</use_patch_radius> <ode> <slip>0</slip> </ode> </torsional> </friction> <bounce> <restitution_coefficient>0</restitution_coefficient> <threshold>1e+06</threshold> </bounce> <contact> <collide_without_contact>0</collide_without_contact> <collide_without_contact_bitmask>1</collide_without_contact_bitmask> <collide_bitmask>1</collide_bitmask> <ode> <soft_cfm>0</soft_cfm> <soft_erp>0.2</soft_erp> <kp>1e+13</kp> <kd>1</kd> <max_vel>0.01</max_vel> <min_depth>0</min_depth> </ode> <bullet> <split_impulse>1</split_impulse> <split_impulse_penetration_threshold>-0.01</split_impulse_penetration_threshold> <soft_cfm>0</soft_cfm> <soft_erp>0.2</soft_erp> <kp>1e+13</kp> <kd>1</kd> </bullet> </contact> </surface> </collision> </link> <static>0</static> <allow_auto_disable>1</allow_auto_disable> </model> </sdf> """ sdf_sand2 = """<?xml version='1.0'?> <sdf version='1.6'> <model name="MODELNAME"> <link name='link'> <pose frame=''>0 0 0.01 0 0 0 </pose> <inertial> <mass>1</mass> <inertia> <ixx>0.1</ixx> <ixy>0</ixy> <ixz>0</ixz> <iyy>0.1</iyy> <iyz>0</iyz> <izz>0.1</izz> </inertia> </inertial> <visual name='visual'> <pose frame=''>0 0 0 0 -0 0</pose> <geometry> <mesh> <scale>SIZEXYZ</scale> <uri>model://sand/sand_particle.stl</uri> </mesh> </geometry> <material> <lighting>1</lighting> <script> <uri>file://media/materials/scripts/gazebo.material</uri> <name>Gazebo/Yellow</name> </script> <ambient>0.3 0.25 0.1 1</ambient> <diffuse>0.7 0.6 0.4 1</diffuse> <specular>0.01 0.005 0.001 1</specular> <emissive>0 0 0 1</emissive> </material> <transparency>0</transparency> <cast_shadows>1</cast_shadows> </visual> <collision name='collision'> <laser_retro>0</laser_retro> <max_contacts>10</max_contacts> <pose frame=''>0 0 0 0 -0 0</pose> <geometry> <mesh> <scale>SIZEXYZ</scale> <uri>model://sand/sand_particle.stl</uri> </mesh> </geometry> <surface> <friction> <ode> <mu>1</mu> <mu2>1</mu2> <fdir1>0 0 0</fdir1> <slip1>0</slip1> <slip2>0</slip2> </ode> <torsional> <coefficient>1</coefficient> <patch_radius>0</patch_radius> <surface_radius>0</surface_radius> <use_patch_radius>1</use_patch_radius> <ode> <slip>0</slip> </ode> </torsional> </friction> <bounce> <restitution_coefficient>0</restitution_coefficient> <threshold>1e+06</threshold> </bounce> <contact> <collide_without_contact>0</collide_without_contact> <collide_without_contact_bitmask>1</collide_without_contact_bitmask> <collide_bitmask>1</collide_bitmask> <ode> <soft_cfm>0</soft_cfm> <soft_erp>0.2</soft_erp> <kp>1e+13</kp> <kd>1</kd> <max_vel>0.01</max_vel> <min_depth>0</min_depth> </ode> <bullet> <split_impulse>1</split_impulse> <split_impulse_penetration_threshold>-0.01</split_impulse_penetration_threshold> <soft_cfm>0</soft_cfm> <soft_erp>0.2</soft_erp> <kp>1e+13</kp> <kd>1</kd> </bullet> </contact> </surface> </collision> </link> <static>0</static> <allow_auto_disable>1</allow_auto_disable> </model> </sdf> """
[ 2, 5145, 14, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 11748, 686, 2777, 88, 198, 11748, 299, 32152, 355, 45941, 198, 198, 6738, 308, 1031, 1765, 78, 62, 907, 14542, 13, 27891, 85, 1330, 36356, 17633, 11, 36356, 17633, 18453, 11, ...
1.531626
9,138
from output.models.ms_data.regex.re_l32_xsd.re_l32 import ( Regex, Doc, ) __all__ = [ "Regex", "Doc", ]
[ 6738, 5072, 13, 27530, 13, 907, 62, 7890, 13, 260, 25636, 13, 260, 62, 75, 2624, 62, 87, 21282, 13, 260, 62, 75, 2624, 1330, 357, 198, 220, 220, 220, 797, 25636, 11, 198, 220, 220, 220, 14432, 11, 198, 8, 198, 198, 834, 439, 8...
1.833333
66
# Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from kfp.components.structures import ComponentSpec, InputSpec, OutputSpec import unittest
[ 2, 15069, 2864, 3012, 11419, 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, 743, 7330...
3.83908
174
import math test_cases = int(input()) numbers = [] for test_case in range(test_cases): numbers.append(int(input())) for n in numbers: if is_prime_number(n): print('Prime') else: print('Not prime')
[ 11748, 10688, 628, 198, 198, 9288, 62, 33964, 796, 493, 7, 15414, 28955, 198, 77, 17024, 796, 17635, 198, 1640, 1332, 62, 7442, 287, 2837, 7, 9288, 62, 33964, 2599, 198, 220, 220, 220, 3146, 13, 33295, 7, 600, 7, 15414, 3419, 4008, ...
2.410526
95
#!/usr/bin/env python # -*- coding: UTF-8 -*- """ Minimal example of the CEFBrowser widget use. Here you don't have any controls (back / forth / reload) or whatsoever. Just a kivy app displaying the chromium-webview. In this example we demonstrate how the cache path of CEF can be set. """ import os from kivy.app import App from kivy.garden.cefpython import CEFBrowser from kivy.logger import Logger if __name__ == '__main__': SimpleBrowserApp().run()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 41002, 12, 23, 532, 9, 12, 198, 198, 37811, 198, 9452, 4402, 1672, 286, 262, 18671, 26001, 808, 2655, 26295, 779, 13, 3423, 345, 836, 470, 423, 597, 6973,...
3.012987
154
#!/usr/bin/python3 # If F(a) is any function that can be defined as composition of bitwise XORs, ANDs and left shifts # Then the dynac system x_(n+1) = F(x_n) is Turing complete # Proof by simulation (rule110) a = 1 while a: print(bin(a)) a = a ^ (a << 1) ^ (a & (a << 1)) ^ (a & (a << 1) & (a << 2))
[ 2, 48443, 14629, 14, 8800, 14, 29412, 18, 198, 198, 2, 1002, 376, 7, 64, 8, 318, 597, 2163, 326, 460, 307, 5447, 355, 11742, 286, 1643, 3083, 1395, 1581, 82, 11, 5357, 82, 290, 1364, 15381, 198, 2, 3244, 262, 37860, 330, 1080, 2...
2.456693
127
from abc import ( abstractmethod, ) from typing import ( Any, Callable, cast, FrozenSet, Generic, Type, TypeVar, ) from cancel_token import ( CancelToken, ) from p2p.exceptions import ( PeerConnectionLost, ) from p2p.kademlia import Node from p2p.peer import ( BasePeer, PeerSubscriber, ) from p2p.peer_pool import ( BasePeerPool, ) from p2p.protocol import ( Command, PayloadType, ) from p2p.service import ( BaseService, ) from trinity.endpoint import ( TrinityEventBusEndpoint, ) from .events import ( ConnectToNodeCommand, DisconnectPeerEvent, HasRemoteEvent, PeerCountRequest, PeerCountResponse, ) TPeer = TypeVar('TPeer', bound=BasePeer) TStreamEvent = TypeVar('TStreamEvent', bound=HasRemoteEvent)
[ 6738, 450, 66, 1330, 357, 198, 220, 220, 220, 12531, 24396, 11, 198, 8, 198, 6738, 19720, 1330, 357, 198, 220, 220, 220, 4377, 11, 198, 220, 220, 220, 4889, 540, 11, 198, 220, 220, 220, 3350, 11, 198, 220, 220, 220, 23673, 7248, ...
2.487578
322
""" Test to verify performance of PVC creation and deletion for RBD, CephFS and RBD-Thick interfaces """ import time import logging import datetime import pytest import ocs_ci.ocs.exceptions as ex import threading import statistics from concurrent.futures import ThreadPoolExecutor from uuid import uuid4 from ocs_ci.framework.testlib import performance from ocs_ci.ocs.perftests import PASTest from ocs_ci.helpers import helpers, performance_lib from ocs_ci.ocs import constants from ocs_ci.helpers.helpers import get_full_test_logs_path from ocs_ci.ocs.perfresult import PerfResult from ocs_ci.framework import config log = logging.getLogger(__name__)
[ 37811, 198, 14402, 284, 11767, 2854, 286, 46377, 6282, 290, 39948, 198, 1640, 371, 14529, 11, 327, 27446, 10652, 290, 371, 14529, 12, 817, 624, 20314, 198, 37811, 198, 11748, 640, 198, 11748, 18931, 198, 11748, 4818, 8079, 198, 11748, 1...
3.199029
206
#!/usr/bin/python3 from jinja2 import Environment, FileSystemLoader results = [ dict( description="Noodles and Company steak Stromboli", comment="", size="small", cals=530, carbs=50, fat=25, protein=27, score=30), dict( description="Steak sandwich", comment="", size="4 oz and bun", cals=480, carbs=44, fat=20, protein=27, score=30), dict( description="chipotle tacos", comment="Steak, no beans, gu...", size="", cals=285, carbs=None, fat=16, protein=None, score=30), dict( description="Steak Sandwich", comment="", size="", cals=380, carbs=45, fat=3.5, protein=34, score=30), ] input_ = dict( title="Search for Courses", h1="Full Text Search: steak NOT shake", results=results, ) env = Environment(loader=FileSystemLoader("..")) env.filters['spacenone'] = spacenone template = env.get_template("searchresult.html") output = template.render(input_) print(output)
[ 2, 48443, 14629, 14, 8800, 14, 29412, 18, 198, 198, 6738, 474, 259, 6592, 17, 1330, 9344, 11, 9220, 11964, 17401, 198, 198, 43420, 796, 685, 198, 220, 220, 220, 8633, 7, 198, 220, 220, 220, 220, 220, 220, 220, 6764, 2625, 45, 702,...
2.036778
571
from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt from payments.models import Invoice, RazorpayKeys from payments.razorpay.razorpay_payments import RazorpayPayments from payments.models import Payment, Order import json
[ 6738, 42625, 14208, 13, 4023, 1330, 449, 1559, 31077, 198, 6738, 42625, 14208, 13, 33571, 13, 12501, 273, 2024, 13, 6359, 41871, 1330, 269, 27891, 69, 62, 42679, 198, 198, 6738, 7524, 13, 27530, 1330, 10001, 2942, 11, 36065, 15577, 4072...
3.540541
74
import configparser import os import sys from time import localtime, strftime, mktime import torch import torch.nn as nn import torch.optim as optim from torch.autograd import Variable from net import Net from geo_helper import store_image_bounds from image_helper import CLASSES from image_helper import save_image from image_helper import test_set_loader from image_helper import train_set_loader from image_helper import validation_set_loader CONFIG = configparser.ConfigParser() CONFIG.read('./src/config.ini') ########################################### # Training Stage ########################################### ##################################### # Validation stage ##################################### ##################################### # Prediction stage ##################################### ################################################################ # Train network or use existing one for prediction ################################################################ main()
[ 11748, 4566, 48610, 198, 11748, 28686, 198, 11748, 25064, 198, 6738, 640, 1330, 1957, 2435, 11, 965, 31387, 11, 33480, 2435, 198, 198, 11748, 28034, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 11748, 28034, 13, 40085, 355, 6436, 19...
4.777251
211
import tkinter as tk from tkinter import filedialog import csv import matplotlib.pyplot as plt root = tk.Tk(screenName=':0.0') root.withdraw() file_path = filedialog.askopenfilename() lastIndex = len(file_path.split('/')) - 1 v0 = [0, 0, 0] x0 = [0, 0, 0] fToA = 1 error = 0.28 errorZ = 3 t = [] time = [] m = [[] for i in range(3)] magnitude = [[] for i in range(3)] shift_x = 0 shift_y = 0 # For when the data starts at (2,1) if file_path.split('/')[lastIndex].split('.')[2] == "pocket": shift_x = 2 shift_y = 1 error = 0.3 fToA = 1 # For when the data starts at (0,0) elif file_path.split('/')[lastIndex].split('.')[2] == "pocket_mobile": shift_x = 0 shift_y = 0 error = 0.3 fToA = 1 # For when the data starts at (1,0) elif file_path.split('/')[lastIndex].split('.')[2] == "android": shift_x = 0 shift_y = 1 error = 0.02 fToA = 9.81 errorZ = 100 shift = 0 uselessboolean = True with open(file_path, 'r+') as csvfile: readCSV = csv.reader(csvfile, delimiter=',') for row in readCSV: if shift < shift_y: shift += 1 else: t = row[shift_x] m[0] = row[1 + shift_x] m[1] = row[2 + shift_x] m[2] = row[3 + shift_x] time.append(float(t)) for i in range(0, 3): magnitude[i].append(float(m[i]) if abs(float(m[i])) > error else 0) acceleration = [[(j * fToA) for j in i] for i in magnitude] acceleration[2] = [i - 9.805 for i in acceleration[2]] # Translates Data into Position velocity = [[0 for i in time] for i in range(3)] position = [[0 for i in time] for i in range(3)] for j in range(3): velocity[j][0] = v0[j] for i in range(1, len(time)): velocity[j][i] = velocity[j][i - 1] + acceleration[j][i - 1] * (time[i] - time[i - 1]) for j in range(3): position[j][0] = x0[j] for i in range(1, len(time)): position[j][i] = position[j][i - 1] + velocity[j][i - 1] * (time[i] - time[i - 1]) for i in range(len(acceleration[2])): if abs(velocity[2][i]) > errorZ: position[0][i] = 0 position[1][i] = 0 fig, axs = plt.subplots(2) axs[0].plot(time, acceleration[0]) axs[0].set_xlabel('Time (s)') axs[0].set_ylabel('AccelerationX (m/s^2)') axs[1].plot(time, acceleration[1]) axs[1].set_xlabel('Time (s)') axs[1].set_ylabel('AccelerationY (m/s^2)') ''' axs[2].scatter(time, acceleration[2]) axs[2].set_xlabel('Time (s)') axs[2].set_ylabel('AccelerationZ (m/s^2)') axs[3].scatter(time, velocity[2]) axs[3].set_xlabel('Time (s)') axs[3].set_ylabel('VelocityZ (m/s)') axs[4].scatter(time, position[2]) axs[4].set_xlabel('Time (s)') axs[4].set_ylabel('PositionZ (m)') axs.scatter(position[0], position[1], marker = "_", linewidth = 70) axs.set_xlabel('PositionX') axs.set_ylabel('PositionY') plt.plot(position[0], position[1], marker = '_', markersize = 30, linewidth = 3, markeredgewidth = 10)''' plt.show()
[ 11748, 256, 74, 3849, 355, 256, 74, 201, 198, 6738, 256, 74, 3849, 1330, 5717, 498, 519, 201, 198, 11748, 269, 21370, 201, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 201, 198, 201, 198, 15763, 796, 256, 74, 13, ...
2.035547
1,491
# Generated by Django 2.2.3 on 2019-07-15 19:24 from django.db import migrations, models def backpopulate_incomplete_profiles(apps, schema): """Backpopulate users who don't have a profile record""" User = apps.get_model("users", "User") Profile = apps.get_model("users", "Profile") for user in User.objects.annotate( has_profile=models.Exists(Profile.objects.filter(user=models.OuterRef("pk"))) ).filter(has_profile=False): Profile.objects.get_or_create(user=user) def remove_incomplete_profiles(apps, schema): """Delete records that will cause rollbacks on nullable/blankable fields to fail""" Profile = apps.get_model("users", "Profile") Profile.objects.filter( models.Q(birth_year__isnull=True) | models.Q(gender__exact="") | models.Q(job_title__exact="") | models.Q(company__exact="") ).delete()
[ 2, 2980, 515, 416, 37770, 362, 13, 17, 13, 18, 319, 13130, 12, 2998, 12, 1314, 678, 25, 1731, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628, 198, 4299, 736, 12924, 5039, 62, 259, 20751, 62, 5577, 2915, 7,...
2.662687
335
from __future__ import division import torch import torch.autograd as autograd import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import numpy as np import sys import os import time # # TORCH INSTALLATION: refer to https://pytorch.org/get-started/locally/ # cls() ################################################################################################################ # Initialize torch tensor for coordiantes coords_data = [[ 0.0 , 0.0 , 0.0 ], [ 1.0/(2.0**0.5), 0.0 , 1.0/(2.0**0.5)], [ 1.0/(2.0**0.5), 0.0 ,-1.0/(2.0**0.5)], [ 2.0**0.5 , 0.0 , 0.0 ], [ 0.0 , 1.0 , 0.0 ], [ 1.0/(2.0**0.5), 1.0 , 1.0/(2.0**0.5)], [ 1.0/(2.0**0.5), 1.0 ,-1.0/(2.0**0.5)], [ 2.0**0.5 , 1.0 , 0.0 ], ] coords = torch.tensor(coords_data,requires_grad=True,dtype=torch.float64) nnodes_r = coords.size(0) nnodes_ie = 8 nnodes_if = 4 nterms_s = 8 ndirs = 3 coord_sys = 'CARTESIAN' # Define matrix of polynomial basis terms at support nodes val_r_data = [[ 1.0,-1.0,-1.0,-1.0, 1.0, 1.0, 1.0,-1.0], [ 1.0,-1.0,-1.0, 1.0,-1.0,-1.0, 1.0, 1.0], [ 1.0, 1.0,-1.0,-1.0,-1.0, 1.0,-1.0, 1.0], [ 1.0, 1.0,-1.0, 1.0, 1.0,-1.0,-1.0,-1.0], [ 1.0,-1.0, 1.0,-1.0, 1.0,-1.0,-1.0, 1.0], [ 1.0,-1.0, 1.0, 1.0,-1.0, 1.0,-1.0,-1.0], [ 1.0, 1.0, 1.0,-1.0,-1.0,-1.0, 1.0,-1.0], [ 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0], ] val_r = torch.tensor(val_r_data,requires_grad=False,dtype=torch.float64) # Define matrices at interpolation nodes (quadrature, level = 1) val_i_data = [[ 1.0,-np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0), 1.0/3.0, 1.0/3.0, 1.0/3.0,-1.0/3.0*np.sqrt(1.0/3.0)], [ 1.0,-np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0), np.sqrt(1.0/3.0),-1.0/3.0,-1.0/3.0, 1.0/3.0, 1.0/3.0*np.sqrt(1.0/3.0)], [ 1.0, np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0),-1.0/3.0, 1.0/3.0,-1.0/3.0, 1.0/3.0*np.sqrt(1.0/3.0)], [ 1.0, np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0), np.sqrt(1.0/3.0), 1.0/3.0,-1.0/3.0,-1.0/3.0,-1.0/3.0*np.sqrt(1.0/3.0)], [ 1.0,-np.sqrt(1.0/3.0), np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0), 1.0/3.0,-1.0/3.0,-1.0/3.0, 1.0/3.0*np.sqrt(1.0/3.0)], [ 1.0,-np.sqrt(1.0/3.0), np.sqrt(1.0/3.0), np.sqrt(1.0/3.0),-1.0/3.0, 1.0/3.0,-1.0/3.0,-1.0/3.0*np.sqrt(1.0/3.0)], [ 1.0, np.sqrt(1.0/3.0), np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0),-1.0/3.0,-1.0/3.0, 1.0/3.0,-1.0/3.0*np.sqrt(1.0/3.0)], [ 1.0, np.sqrt(1.0/3.0), np.sqrt(1.0/3.0), np.sqrt(1.0/3.0), 1.0/3.0, 1.0/3.0, 1.0/3.0, 1.0/3.0*np.sqrt(1.0/3.0)], ] val_i = torch.tensor(val_i_data,requires_grad=False,dtype=torch.float64) ddxi_i_data = [[ 0.0,0.0,0.0,1.0,-np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0),0.0, 1.0/3.0], [ 0.0,0.0,0.0,1.0,-np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0),0.0, 1.0/3.0], [ 0.0,0.0,0.0,1.0, np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0),0.0,-1.0/3.0], [ 0.0,0.0,0.0,1.0, np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0),0.0,-1.0/3.0], [ 0.0,0.0,0.0,1.0,-np.sqrt(1.0/3.0), np.sqrt(1.0/3.0),0.0,-1.0/3.0], [ 0.0,0.0,0.0,1.0,-np.sqrt(1.0/3.0), np.sqrt(1.0/3.0),0.0,-1.0/3.0], [ 0.0,0.0,0.0,1.0, np.sqrt(1.0/3.0), np.sqrt(1.0/3.0),0.0, 1.0/3.0], [ 0.0,0.0,0.0,1.0, np.sqrt(1.0/3.0), np.sqrt(1.0/3.0),0.0, 1.0/3.0], ] ddxi_i = torch.tensor(ddxi_i_data,requires_grad=False,dtype=torch.float64) ddeta_i_data = [[ 0.0,1.0,0.0,0.0,-np.sqrt(1.0/3.0),0.0,-np.sqrt(1.0/3.0), 1.0/3.0], [ 0.0,1.0,0.0,0.0, np.sqrt(1.0/3.0),0.0,-np.sqrt(1.0/3.0),-1.0/3.0], [ 0.0,1.0,0.0,0.0,-np.sqrt(1.0/3.0),0.0,-np.sqrt(1.0/3.0), 1.0/3.0], [ 0.0,1.0,0.0,0.0, np.sqrt(1.0/3.0),0.0,-np.sqrt(1.0/3.0),-1.0/3.0], [ 0.0,1.0,0.0,0.0,-np.sqrt(1.0/3.0),0.0, np.sqrt(1.0/3.0),-1.0/3.0], [ 0.0,1.0,0.0,0.0, np.sqrt(1.0/3.0),0.0, np.sqrt(1.0/3.0), 1.0/3.0], [ 0.0,1.0,0.0,0.0,-np.sqrt(1.0/3.0),0.0, np.sqrt(1.0/3.0),-1.0/3.0], [ 0.0,1.0,0.0,0.0, np.sqrt(1.0/3.0),0.0, np.sqrt(1.0/3.0), 1.0/3.0], ] ddeta_i = torch.tensor(ddeta_i_data,requires_grad=False,dtype=torch.float64) ddzeta_i_data= [[ 0.0,0.0,1.0,0.0,0.0,-np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0), 1.0/3.0], [ 0.0,0.0,1.0,0.0,0.0, np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0),-1.0/3.0], [ 0.0,0.0,1.0,0.0,0.0,-np.sqrt(1.0/3.0), np.sqrt(1.0/3.0),-1.0/3.0], [ 0.0,0.0,1.0,0.0,0.0, np.sqrt(1.0/3.0), np.sqrt(1.0/3.0), 1.0/3.0], [ 0.0,0.0,1.0,0.0,0.0,-np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0), 1.0/3.0], [ 0.0,0.0,1.0,0.0,0.0, np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0),-1.0/3.0], [ 0.0,0.0,1.0,0.0,0.0,-np.sqrt(1.0/3.0), np.sqrt(1.0/3.0),-1.0/3.0], [ 0.0,0.0,1.0,0.0,0.0, np.sqrt(1.0/3.0), np.sqrt(1.0/3.0), 1.0/3.0], ] ddzeta_i = torch.tensor(ddzeta_i_data,requires_grad=False,dtype=torch.float64) # Define element interpolation nodes weights for linear element weights_e_data = [1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0] weights_e = torch.tensor(weights_e_data,requires_grad=False,dtype=torch.float64) # Define val_f for each face # Face 1, XI_MIN val_1_data = [[ 1.0,-np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0),-1.0, np.sqrt(1.0/3.0), np.sqrt(1.0/3.0), 1.0/3.0,-1.0/3.0], [ 1.0, np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0),-1.0,-np.sqrt(1.0/3.0), np.sqrt(1.0/3.0),-1.0/3.0, 1.0/3.0], [ 1.0,-np.sqrt(1.0/3.0), np.sqrt(1.0/3.0),-1.0, np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0),-1.0/3.0, 1.0/3.0], [ 1.0, np.sqrt(1.0/3.0), np.sqrt(1.0/3.0),-1.0,-np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0), 1.0/3.0,-1.0/3.0], ] val_1 = torch.tensor(val_1_data,requires_grad=False,dtype=torch.float64) # Face 2, XI_MAX val_2_data = [[ 1.0,-np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0),1.0,-np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0), 1.0/3.0, 1.0/3.0], [ 1.0, np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0),1.0, np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0),-1.0/3.0,-1.0/3.0], [ 1.0,-np.sqrt(1.0/3.0), np.sqrt(1.0/3.0),1.0,-np.sqrt(1.0/3.0), np.sqrt(1.0/3.0),-1.0/3.0,-1.0/3.0], [ 1.0, np.sqrt(1.0/3.0), np.sqrt(1.0/3.0),1.0, np.sqrt(1.0/3.0), np.sqrt(1.0/3.0), 1.0/3.0, 1.0/3.0], ] val_2 = torch.tensor(val_2_data,requires_grad=False,dtype=torch.float64) # Face 3, ETA_MIN val_3_data = [[ 1.0,-1.0,-np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0), np.sqrt(1.0/3.0), 1.0/3.0, np.sqrt(1.0/3.0),-1.0/3.0], [ 1.0,-1.0,-np.sqrt(1.0/3.0), np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0),-1.0/3.0, np.sqrt(1.0/3.0), 1.0/3.0], [ 1.0,-1.0, np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0), np.sqrt(1.0/3.0),-1.0/3.0,-np.sqrt(1.0/3.0), 1.0/3.0], [ 1.0,-1.0, np.sqrt(1.0/3.0), np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0), 1.0/3.0,-np.sqrt(1.0/3.0),-1.0/3.0], ] val_3 = torch.tensor(val_3_data,requires_grad=False,dtype=torch.float64) # Face 4, ETA_MAX val_4_data = [[ 1.0,1.0,-np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0), 1.0/3.0,-np.sqrt(1.0/3.0), 1.0/3.0], [ 1.0,1.0,-np.sqrt(1.0/3.0), np.sqrt(1.0/3.0), np.sqrt(1.0/3.0),-1.0/3.0,-np.sqrt(1.0/3.0),-1.0/3.0], [ 1.0,1.0, np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0),-1.0/3.0, np.sqrt(1.0/3.0),-1.0/3.0], [ 1.0,1.0, np.sqrt(1.0/3.0), np.sqrt(1.0/3.0), np.sqrt(1.0/3.0), 1.0/3.0, np.sqrt(1.0/3.0), 1.0/3.0], ] val_4 = torch.tensor(val_4_data,requires_grad=False,dtype=torch.float64) # Face 5, ZETA_MIN val_5_data = [[ 1.0,-np.sqrt(1.0/3.0),-1.0,-np.sqrt(1.0/3.0), 1.0/3.0, np.sqrt(1.0/3.0), np.sqrt(1.0/3.0),-1.0/3.0], [ 1.0,-np.sqrt(1.0/3.0),-1.0, np.sqrt(1.0/3.0),-1.0/3.0,-np.sqrt(1.0/3.0), np.sqrt(1.0/3.0), 1.0/3.0], [ 1.0, np.sqrt(1.0/3.0),-1.0,-np.sqrt(1.0/3.0),-1.0/3.0, np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0), 1.0/3.0], [ 1.0, np.sqrt(1.0/3.0),-1.0, np.sqrt(1.0/3.0), 1.0/3.0,-np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0),-1.0/3.0], ] val_5 = torch.tensor(val_5_data,requires_grad=False,dtype=torch.float64) # Face 6, ZETA_MAX val_6_data = [[ 1.0,-np.sqrt(1.0/3.0),1.0,-np.sqrt(1.0/3.0), 1.0/3.0,-np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0), 1.0/3.0], [ 1.0,-np.sqrt(1.0/3.0),1.0, np.sqrt(1.0/3.0),-1.0/3.0, np.sqrt(1.0/3.0),-np.sqrt(1.0/3.0),-1.0/3.0], [ 1.0, np.sqrt(1.0/3.0),1.0,-np.sqrt(1.0/3.0),-1.0/3.0,-np.sqrt(1.0/3.0), np.sqrt(1.0/3.0),-1.0/3.0], [ 1.0, np.sqrt(1.0/3.0),1.0, np.sqrt(1.0/3.0), 1.0/3.0, np.sqrt(1.0/3.0), np.sqrt(1.0/3.0), 1.0/3.0], ] val_6 = torch.tensor(val_6_data,requires_grad=False,dtype=torch.float64) #-------------------------------------------------------------------- # Matrix modes_to_nodes val_r_inv = torch.inverse(val_r) # Computes coordiantes modes coords_modes = torch.mm(val_r_inv,coords) # Initialized coordiantes interp_coords = torch.mm(val_i,coords_modes) # Initialized jacobian jacobian = torch.empty(3,3,nnodes_ie, dtype=torch.float64) for inode in range(0,nnodes_ie): jacobian[0,0,inode] = torch.dot(ddxi_i[inode,:] , coords_modes[:,0]) jacobian[0,1,inode] = torch.dot(ddeta_i[inode,:] , coords_modes[:,0]) jacobian[0,2,inode] = torch.dot(ddzeta_i[inode,:] , coords_modes[:,0]) jacobian[1,0,inode] = torch.dot(ddxi_i[inode,:] , coords_modes[:,1]) jacobian[1,1,inode] = torch.dot(ddeta_i[inode,:] , coords_modes[:,1]) jacobian[1,2,inode] = torch.dot(ddzeta_i[inode,:] , coords_modes[:,1]) jacobian[2,0,inode] = torch.dot(ddxi_i[inode,:] , coords_modes[:,2]) jacobian[2,1,inode] = torch.dot(ddeta_i[inode,:] , coords_modes[:,2]) jacobian[2,2,inode] = torch.dot(ddzeta_i[inode,:] , coords_modes[:,2]) update_progress("Computing Jacobian ", inode/(nnodes_ie-1)) if coord_sys == 'CYLINDRICAL': scaling_factor = torch.mm(val_i,coords_modes[:,0]) for inode in range(0,nnodes_ie): jacobian[1,0,inode] = jacobian[1,0,inode] * scaling_factor[inode] jacobian[1,1,inode] = jacobian[1,1,inode] * scaling_factor[inode] jacobian[1,2,inode] = jacobian[1,2,inode] * scaling_factor[inode] # Matrics and Determinant metrics = torch.empty(3,3,nnodes_ie, dtype=torch.float64) jinv = torch.empty(nnodes_ie, dtype=torch.float64) for inode in range(0,nnodes_ie): ijacobian = torch.empty(3,3, dtype=torch.float64) imetric = torch.empty(3,3, dtype=torch.float64) for irow in range(0,3): for icol in range(0,3): ijacobian[irow,icol] = jacobian[irow,icol,inode] # Compute jacobian for the ith node update_progress("Computing Jinv and Metric ", inode/(nnodes_ie-1)) jinv[inode] = torch.det(ijacobian) imetric = torch.inverse(ijacobian) for irow in range(0,3): for icol in range(0,3): metrics[irow,icol,inode] = imetric[irow,icol] # Compute inverse Mass matrix invmass = torch.empty(nterms_s,nterms_s,nnodes_ie, dtype=torch.float64) mass = torch.empty(nterms_s,nterms_s,nnodes_ie, dtype=torch.float64) val_tmp = torch.empty(nterms_s,nnodes_ie, dtype=torch.float64) i = 1 for iterm in range(0,nterms_s): for inode in range(0,nnodes_ie): val_tmp[inode,iterm] = val_i[inode,iterm] * weights_e[inode] * jinv[inode] update_progress("Computing invmass ", i/(nterms_s*nnodes_ie)) i += 1 mass = torch.mm(torch.t(val_tmp),val_i) invmass = torch.inverse(mass) # Compute BR2_VOL for each face br2_vol_face1 = torch.mm(val_i,torch.mm(invmass,torch.t(val_1))) br2_vol_face2 = torch.mm(val_i,torch.mm(invmass,torch.t(val_2))) br2_vol_face3 = torch.mm(val_i,torch.mm(invmass,torch.t(val_3))) br2_vol_face4 = torch.mm(val_i,torch.mm(invmass,torch.t(val_4))) br2_vol_face5 = torch.mm(val_i,torch.mm(invmass,torch.t(val_5))) br2_vol_face6 = torch.mm(val_i,torch.mm(invmass,torch.t(val_6))) update_progress("Computing br2_vol ", 1) # Compute BR2_FACE for each face br2_face_face1 = torch.mm(val_1,torch.mm(invmass,torch.t(val_1))) br2_face_face2 = torch.mm(val_2,torch.mm(invmass,torch.t(val_2))) br2_face_face3 = torch.mm(val_3,torch.mm(invmass,torch.t(val_3))) br2_face_face4 = torch.mm(val_4,torch.mm(invmass,torch.t(val_4))) br2_face_face5 = torch.mm(val_5,torch.mm(invmass,torch.t(val_5))) br2_face_face6 = torch.mm(val_6,torch.mm(invmass,torch.t(val_6))) update_progress("Computing br2_face ", 1) # Grad1, Grad2, and Grad3 grad1 = torch.empty(nnodes_ie,nterms_s, dtype=torch.float64) grad2 = torch.empty(nnodes_ie,nterms_s, dtype=torch.float64) grad3 = torch.empty(nnodes_ie,nterms_s, dtype=torch.float64) i = 1 for iterm in range(0,nterms_s): for inode in range(0,nnodes_ie): grad1[inode,iterm] = metrics[0,0,inode] * ddxi_i[inode,iterm] + metrics[1,0,inode] * ddeta_i[inode,iterm] + metrics[2,0,inode] * ddzeta_i[inode,iterm] grad2[inode,iterm] = metrics[0,1,inode] * ddxi_i[inode,iterm] + metrics[1,1,inode] * ddeta_i[inode,iterm] + metrics[2,1,inode] * ddzeta_i[inode,iterm] grad3[inode,iterm] = metrics[0,2,inode] * ddxi_i[inode,iterm] + metrics[1,2,inode] * ddeta_i[inode,iterm] + metrics[2,2,inode] * ddzeta_i[inode,iterm] update_progress("Computing grad1, grad2, grad3 ", i/(nnodes_ie*nterms_s)) i += 1 #WRITE_____________________ # # Metrics # f = open("metrics.txt","w") i = 1 for inode in range (0,nnodes_ie): f.write("Metric interpolation node %d \n" % (inode+1)) array = np.zeros([3, 3]) for irow in range(0,3): for icol in range(0,3): array[irow,icol] = metrics[irow,icol,inode].item() update_progress("Writing metrics to file ", i/(nnodes_ie*9)) i += 1 np.savetxt(f,array) f.close() # # jinv # f = open("jinv.txt","w") array = np.zeros([1]) i = 1 for inode in range (0,nnodes_ie): f.write("Jinv interpolation node %d \n" % (inode+1)) array[0] = jinv[inode].item() np.savetxt(f,array) update_progress("Writing jinv to file ", i/(nnodes_ie)) i += 1 f.close() # # Grad1 # f = open("grad1.txt","w") f.write("Grad1 \n") array = np.zeros([nnodes_ie,nterms_s]) i = 1 for inode in range (0,nnodes_ie): for iterm in range(0,nterms_s): array[inode,iterm] = grad1[inode,iterm].item() update_progress("Writing grad1 to file ", i/(nnodes_ie*nterms_s)) i += 1 np.savetxt(f,array) f.close() # # Grad2 # f = open("grad2.txt","w") f.write("Grad2 \n") array = np.zeros([nnodes_ie,nterms_s]) i = 1 for inode in range (0,nnodes_ie): for iterm in range(0,nterms_s): array[inode,iterm] = grad2[inode,iterm].item() update_progress("Writing grad2 to file ", i/(nnodes_ie*nterms_s)) i += 1 np.savetxt(f,array) f.close() # # Grad3 # f = open("grad3.txt","w") f.write("Grad3 \n") array = np.zeros([nnodes_ie,nterms_s]) i = 1 for inode in range (0,nnodes_ie): for iterm in range(0,nterms_s): array[inode,iterm] = grad3[inode,iterm].item() update_progress("Writing grad3 to file ", i/(nnodes_ie*nterms_s)) i += 1 np.savetxt(f,array) f.close() # # dmetric_dx # f = open("dmetric_dx.txt","w") i = 1 for inode in range (0,nnodes_ie): for inode_diff in range(0,nnodes_r): for idir in range(0,ndirs): array = np.zeros([3,3]) f.write("dmetric_dx interpolation node %s, diff_node %s, diff_dir %s \n" % (inode+1,inode_diff+1,idir+1)) for irow in range(0,3): for icol in range(0,3): data = metrics[irow,icol,inode] data.backward(retain_graph=True) ddata = coords.grad ddata_np = ddata.numpy() array[irow,icol] = ddata_np[inode_diff,idir] update_progress("Writing dmetric_dx to file ", i/(nnodes_ie*nnodes_r*ndirs*3*3)) # This avoid to accumulate derivatives dummy = coords.grad.data.zero_() i += 1 np.savetxt(f,array) f.close() # # interp_coords_dx # f = open("dinterp_xcoords_dx.txt","w") i = 1 f.write("xcoord interpolation, coord 1, row=node, col=nnodes_r*dir \n") array = np.zeros([nnodes_ie,nnodes_r*ndirs]) for inode in range (0,nnodes_ie): data = interp_coords[inode,0] data.backward(retain_graph=True) ddata = coords.grad ddata_np = ddata.numpy() for inode_diff in range(0,nnodes_r): for idir in range(0,ndirs): if idir == 0: index = inode_diff elif idir == 1: index = nnodes_r + inode_diff elif idir == 2: index = 2*nnodes_r + inode_diff array[inode,index] = ddata_np[inode_diff,idir] update_progress("Writing interp_xcoords_dx to file ", i/(nnodes_ie*nnodes_r*3)) i += 1 # This avoid to accumulate derivatives dummy = coords.grad.data.zero_() np.savetxt(f,array) f.close() f = open("dinterp_ycoords_dx.txt","w") i = 1 f.write("ycoord interpolation, coord 2, row=node, col=nnodes_r*dir \n") array = np.zeros([nnodes_ie,nnodes_r*ndirs]) for inode in range (0,nnodes_ie): data = interp_coords[inode,1] data.backward(retain_graph=True) ddata = coords.grad ddata_np = ddata.numpy() for inode_diff in range(0,nnodes_r): for idir in range(0,ndirs): if idir == 0: index = inode_diff elif idir == 1: index = nnodes_r + inode_diff elif idir == 2: index = 2*nnodes_r + inode_diff array[inode,index] = ddata_np[inode_diff,idir] update_progress("Writing interp_ycoords_dx to file ", i/(nnodes_ie*nnodes_r*3)) i += 1 # This avoid to accumulate derivatives dummy = coords.grad.data.zero_() np.savetxt(f,array) f.close() f = open("dinterp_zcoords_dx.txt","w") i = 1 f.write("zcoord interpolation, coord 3, row=node, col=nnodes_r*dir \n") array = np.zeros([nnodes_ie,nnodes_r*ndirs]) for inode in range (0,nnodes_ie): data = interp_coords[inode,2] data.backward(retain_graph=True) ddata = coords.grad ddata_np = ddata.numpy() for inode_diff in range(0,nnodes_r): for idir in range(0,ndirs): if idir == 0: index = inode_diff elif idir == 1: index = nnodes_r + inode_diff elif idir == 2: index = 2*nnodes_r + inode_diff array[inode,index] = ddata_np[inode_diff,idir] update_progress("Writing interp_zcoords_dx to file ", i/(nnodes_ie*nnodes_r*3)) i += 1 # This avoid to accumulate derivatives dummy = coords.grad.data.zero_() np.savetxt(f,array) f.close() # # djinv_dx # f = open("djinv_dx.txt","w") i = 1 for inode in range (0,nnodes_ie): array = np.zeros([nnodes_r,ndirs]) f.write("djinv_dx interpolation node %s, row=inode_diff, col=dir \n" % (inode+1)) for inode_diff in range(0,nnodes_r): for idir in range(0,ndirs): data = jinv[inode] data.backward(retain_graph=True) ddata = coords.grad ddata_np = ddata.numpy() array[inode_diff,idir] = ddata_np[inode_diff,idir] update_progress("Writing djinv_dx to file ", i/(nnodes_ie*nnodes_r*ndirs)) dummy = coords.grad.data.zero_() i += 1 np.savetxt(f,array) f.close() # # dmass_dx # f = open("dmass_dx.txt","w") i = 1 for inode_diff in range(0,nnodes_r): for idir in range(0,ndirs): f.write("dmass_dx => diff_node %s, diff_dir %s \n" % (inode_diff+1,idir+1)) array = np.zeros([nterms_s,nterms_s]) for irow in range(0,nterms_s): for icol in range(0,nterms_s): data = mass[irow,icol] data.backward(retain_graph=True) ddata = coords.grad ddata_np = ddata.numpy() array[irow,icol] = ddata_np[inode_diff,idir] update_progress("Writing dmass_dx to file ", i/(nterms_s*nnodes_r*ndirs*nterms_s)) dummy = coords.grad.data.zero_() i += 1 np.savetxt(f,array) f.close() # # dinvmass_dx # f = open("dinvmass_dx.txt","w") i = 1 for inode_diff in range(0,nnodes_r): for idir in range(0,ndirs): f.write("dinvmass_dx => diff_node %s, diff_dir %s \n" % (inode_diff+1,idir+1)) array = np.zeros([nterms_s,nterms_s]) for irow in range(0,nterms_s): for icol in range(0,nterms_s): data = invmass[irow,icol] data.backward(retain_graph=True) ddata = coords.grad ddata_np = ddata.numpy() array[irow,icol] = ddata_np[inode_diff,idir] update_progress("Writing dinvmass_dx to file ", i/(nterms_s*nnodes_r*ndirs*nterms_s)) dummy = coords.grad.data.zero_() i += 1 np.savetxt(f,array) f.close() # # dbr2_vol_dx # # f = open("dbr2_vol_face1_dx.txt","w") i = 1 for inode_diff in range(0,nnodes_r): for idir in range(0,ndirs): f.write("dbr2_vol_face1_dx => diff_node %s, diff_dir %s \n" % (inode_diff+1,idir+1)) array = np.zeros([nnodes_ie,nnodes_if]) for irow in range(0,nnodes_ie): for icol in range(0,nnodes_if): data = br2_vol_face1[irow,icol] data.backward(retain_graph=True) ddata = coords.grad ddata_np = ddata.numpy() array[irow,icol] = ddata_np[inode_diff,idir] update_progress("Writing dbr2_vol_face1_dx to file ", i/(nnodes_ie*nnodes_r*ndirs*nnodes_if)) dummy = coords.grad.data.zero_() i += 1 np.savetxt(f,array) f.close() f = open("dbr2_vol_face2_dx.txt","w") i = 1 for inode_diff in range(0,nnodes_r): for idir in range(0,ndirs): f.write("dbr2_vol_face2_dx => diff_node %s, diff_dir %s \n" % (inode_diff+1,idir+1)) array = np.zeros([nnodes_ie,nnodes_if]) for irow in range(0,nnodes_ie): for icol in range(0,nnodes_if): data = br2_vol_face2[irow,icol] data.backward(retain_graph=True) ddata = coords.grad ddata_np = ddata.numpy() array[irow,icol] = ddata_np[inode_diff,idir] update_progress("Writing dbr2_vol_face2_dx to file ", i/(nnodes_ie*nnodes_r*ndirs*nnodes_if)) dummy = coords.grad.data.zero_() i += 1 np.savetxt(f,array) f.close() f = open("dbr2_vol_face3_dx.txt","w") i = 1 for inode_diff in range(0,nnodes_r): for idir in range(0,ndirs): f.write("dbr2_vol_face3_dx => diff_node %s, diff_dir %s \n" % (inode_diff+1,idir+1)) array = np.zeros([nnodes_ie,nnodes_if]) for irow in range(0,nnodes_ie): for icol in range(0,nnodes_if): data = br2_vol_face3[irow,icol] data.backward(retain_graph=True) ddata = coords.grad ddata_np = ddata.numpy() array[irow,icol] = ddata_np[inode_diff,idir] update_progress("Writing dbr2_vol_face3_dx to file ", i/(nnodes_ie*nnodes_r*ndirs*nnodes_if)) dummy = coords.grad.data.zero_() i += 1 np.savetxt(f,array) f.close() f = open("dbr2_vol_face4_dx.txt","w") i = 1 for inode_diff in range(0,nnodes_r): for idir in range(0,ndirs): f.write("dbr2_vol_face4_dx => diff_node %s, diff_dir %s \n" % (inode_diff+1,idir+1)) array = np.zeros([nnodes_ie,nnodes_if]) for irow in range(0,nnodes_ie): for icol in range(0,nnodes_if): data = br2_vol_face4[irow,icol] data.backward(retain_graph=True) ddata = coords.grad ddata_np = ddata.numpy() array[irow,icol] = ddata_np[inode_diff,idir] update_progress("Writing dbr2_vol_face4_dx to file ", i/(nnodes_ie*nnodes_r*ndirs*nnodes_if)) dummy = coords.grad.data.zero_() i += 1 np.savetxt(f,array) f.close() f = open("dbr2_vol_face5_dx.txt","w") i = 1 for inode_diff in range(0,nnodes_r): for idir in range(0,ndirs): f.write("dbr2_vol_face5_dx => diff_node %s, diff_dir %s \n" % (inode_diff+1,idir+1)) array = np.zeros([nnodes_ie,nnodes_if]) for irow in range(0,nnodes_ie): for icol in range(0,nnodes_if): data = br2_vol_face5[irow,icol] data.backward(retain_graph=True) ddata = coords.grad ddata_np = ddata.numpy() array[irow,icol] = ddata_np[inode_diff,idir] update_progress("Writing dbr2_vol_face5_dx to file ", i/(nnodes_ie*nnodes_r*ndirs*nnodes_if)) dummy = coords.grad.data.zero_() i += 1 np.savetxt(f,array) f.close() f = open("dbr2_vol_face6_dx.txt","w") i = 1 for inode_diff in range(0,nnodes_r): for idir in range(0,ndirs): f.write("dbr2_vol_face6_dx => diff_node %s, diff_dir %s \n" % (inode_diff+1,idir+1)) array = np.zeros([nnodes_ie,nnodes_if]) for irow in range(0,nnodes_ie): for icol in range(0,nnodes_if): data = br2_vol_face6[irow,icol] data.backward(retain_graph=True) ddata = coords.grad ddata_np = ddata.numpy() array[irow,icol] = ddata_np[inode_diff,idir] update_progress("Writing dbr2_vol_face6_dx to file ", i/(nnodes_ie*nnodes_r*ndirs*nnodes_if)) dummy = coords.grad.data.zero_() i += 1 np.savetxt(f,array) f.close() # # dbr2_face_dx # # f = open("dbr2_face_face1_dx.txt","w") i = 1 for inode_diff in range(0,nnodes_r): for idir in range(0,ndirs): f.write("dbr2_face_face1_dx => diff_node %s, diff_dir %s \n" % (inode_diff+1,idir+1)) array = np.zeros([nnodes_if,nnodes_if]) for irow in range(0,nnodes_if): for icol in range(0,nnodes_if): data = br2_face_face1[irow,icol] data.backward(retain_graph=True) ddata = coords.grad ddata_np = ddata.numpy() array[irow,icol] = ddata_np[inode_diff,idir] update_progress("Writing dbr2_face_face1_dx to file ", i/(nnodes_if*nnodes_r*ndirs*nnodes_if)) dummy = coords.grad.data.zero_() i += 1 np.savetxt(f,array) f.close() f = open("dbr2_face_face2_dx.txt","w") i = 1 for inode_diff in range(0,nnodes_r): for idir in range(0,ndirs): f.write("dbr2_face_face2_dx => diff_node %s, diff_dir %s \n" % (inode_diff+1,idir+1)) array = np.zeros([nnodes_if,nnodes_if]) for irow in range(0,nnodes_if): for icol in range(0,nnodes_if): data = br2_face_face2[irow,icol] data.backward(retain_graph=True) ddata = coords.grad ddata_np = ddata.numpy() array[irow,icol] = ddata_np[inode_diff,idir] update_progress("Writing dbr2_face_face2_dx to file ", i/(nnodes_if*nnodes_r*ndirs*nnodes_if)) dummy = coords.grad.data.zero_() i += 1 np.savetxt(f,array) f.close() f = open("dbr2_face_face3_dx.txt","w") i = 1 for inode_diff in range(0,nnodes_r): for idir in range(0,ndirs): f.write("dbr2_face_face3_dx => diff_node %s, diff_dir %s \n" % (inode_diff+1,idir+1)) array = np.zeros([nnodes_if,nnodes_if]) for irow in range(0,nnodes_if): for icol in range(0,nnodes_if): data = br2_face_face3[irow,icol] data.backward(retain_graph=True) ddata = coords.grad ddata_np = ddata.numpy() array[irow,icol] = ddata_np[inode_diff,idir] update_progress("Writing dbr2_face_face3_dx to file ", i/(nnodes_if*nnodes_r*ndirs*nnodes_if)) dummy = coords.grad.data.zero_() i += 1 np.savetxt(f,array) f.close() f = open("dbr2_face_face4_dx.txt","w") i = 1 for inode_diff in range(0,nnodes_r): for idir in range(0,ndirs): f.write("dbr2_face_face4_dx => diff_node %s, diff_dir %s \n" % (inode_diff+1,idir+1)) array = np.zeros([nnodes_if,nnodes_if]) for irow in range(0,nnodes_if): for icol in range(0,nnodes_if): data = br2_face_face4[irow,icol] data.backward(retain_graph=True) ddata = coords.grad ddata_np = ddata.numpy() array[irow,icol] = ddata_np[inode_diff,idir] update_progress("Writing dbr2_face_face4_dx to file ", i/(nnodes_if*nnodes_r*ndirs*nnodes_if)) dummy = coords.grad.data.zero_() i += 1 np.savetxt(f,array) f.close() f = open("dbr2_face_face5_dx.txt","w") i = 1 for inode_diff in range(0,nnodes_r): for idir in range(0,ndirs): f.write("dbr2_face_face5_dx => diff_node %s, diff_dir %s \n" % (inode_diff+1,idir+1)) array = np.zeros([nnodes_if,nnodes_if]) for irow in range(0,nnodes_if): for icol in range(0,nnodes_if): data = br2_face_face5[irow,icol] data.backward(retain_graph=True) ddata = coords.grad ddata_np = ddata.numpy() array[irow,icol] = ddata_np[inode_diff,idir] update_progress("Writing dbr2_face_face5_dx to file ", i/(nnodes_if*nnodes_r*ndirs*nnodes_if)) dummy = coords.grad.data.zero_() i += 1 np.savetxt(f,array) f.close() f = open("dbr2_face_face6_dx.txt","w") i = 1 for inode_diff in range(0,nnodes_r): for idir in range(0,ndirs): f.write("dbr2_face_face6_dx => diff_node %s, diff_dir %s \n" % (inode_diff+1,idir+1)) array = np.zeros([nnodes_if,nnodes_if]) for irow in range(0,nnodes_if): for icol in range(0,nnodes_if): data = br2_face_face6[irow,icol] data.backward(retain_graph=True) ddata = coords.grad ddata_np = ddata.numpy() array[irow,icol] = ddata_np[inode_diff,idir] update_progress("Writing dbr2_face_face6_dx to file ", i/(nnodes_if*nnodes_r*ndirs*nnodes_if)) dummy = coords.grad.data.zero_() i += 1 np.savetxt(f,array) f.close() # # dgrad1_dx # f = open("dgrad1_dx.txt","w") i = 1 for inode_diff in range(0,nnodes_r): for idir in range(0,ndirs): f.write("dgrad1_dx => diff_node %s, diff_dir %s \n" % (inode_diff+1,idir+1)) array = np.zeros([nnodes_ie,nterms_s]) for irow in range(0,nnodes_ie): for icol in range(0,nterms_s): data = grad1[irow,icol] data.backward(retain_graph=True) ddata = coords.grad ddata_np = ddata.numpy() array[irow,icol] = ddata_np[inode_diff,idir] update_progress("Writing dgrad1_dx to file ", i/(nnodes_ie*nnodes_r*ndirs*nterms_s)) dummy = coords.grad.data.zero_() i += 1 np.savetxt(f,array) f.close() # # dgrad2_dx # f = open("dgrad2_dx.txt","w") i = 1 for inode_diff in range(0,nnodes_r): for idir in range(0,ndirs): f.write("dgrad2_dx => diff_node %s, diff_dir %s \n" % (inode_diff+1,idir+1)) array = np.zeros([nnodes_ie,nterms_s]) for irow in range(0,nnodes_ie): for icol in range(0,nterms_s): data = grad2[irow,icol] data.backward(retain_graph=True) ddata = coords.grad ddata_np = ddata.numpy() array[irow,icol] = ddata_np[inode_diff,idir] update_progress("Writing dgrad2_dx to file ", i/(nnodes_ie*nnodes_r*ndirs*nterms_s)) dummy = coords.grad.data.zero_() i += 1 np.savetxt(f,array) f.close() # # dgrad3_dx # f = open("dgrad3_dx.txt","w") i = 1 for inode_diff in range(0,nnodes_r): for idir in range(0,ndirs): f.write("dgrad3_dx => diff_node %s, diff_dir %s \n" % (inode_diff+1,idir+1)) array = np.zeros([nnodes_ie,nterms_s]) for irow in range(0,nnodes_ie): for icol in range(0,nterms_s): data = grad3[irow,icol] data.backward(retain_graph=True) ddata = coords.grad ddata_np = ddata.numpy() array[irow,icol] = ddata_np[inode_diff,idir] update_progress("Writing dgrad3_dx to file ", i/(nnodes_ie*nnodes_r*ndirs*nterms_s)) dummy = coords.grad.data.zero_() i += 1 np.savetxt(f,array) f.close()
[ 6738, 11593, 37443, 834, 1330, 7297, 198, 198, 11748, 28034, 198, 11748, 28034, 13, 2306, 519, 6335, 355, 1960, 519, 6335, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 11748, 28034, 13, 20471, 13, 45124, 355, 376, 198, 11748, 28034,...
1.699638
19,623
""" OSR (LOTFP) stat generator. """ import random def d(num_sides): """ Represents rolling a die of size 'num_sides'. Returns random number from that size die """ return random.randint(1, num_sides) def xdy(num_dice, num_sides): """ represents rolling num_dice of size num_sides. Returns random number from that many dice being 'rolled'. """ return sum(d(num_sides) for i in range(num_dice)) class Stat_Set(object): """ Define a package of OSR/DnD stats """ _Stat_Name = ["CON", "DEX", "INT", "WIS", "STR", "CHA"] def generate_stats (nrof_sets:int=1, no_hopeless_char:bool=True)->list: """ Generate stats for a character. """ stat_sets = [] while (nrof_sets > 0): stats = [] for i in range (0, 6): stats.append(xdy(3,6)) stat_set = Stat_Set(stats) # no "hopeless" characters if no_hopeless_char and stat_set.is_hopeless: continue stat_sets.append(stat_set) nrof_sets -= 1 return stat_sets
[ 198, 198, 37811, 220, 198, 2640, 49, 357, 43, 2394, 5837, 8, 1185, 17301, 13, 220, 198, 37811, 198, 198, 11748, 4738, 198, 198, 4299, 288, 7, 22510, 62, 82, 1460, 2599, 198, 220, 220, 220, 37227, 220, 198, 220, 220, 220, 1432, 662...
2.270213
470
# -*- coding: utf-8 -*- # Copyright 2021 Cohesity Inc. import cohesity_management_sdk.models.alert
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 15069, 33448, 1766, 956, 414, 3457, 13, 198, 198, 11748, 763, 956, 414, 62, 27604, 62, 21282, 74, 13, 27530, 13, 44598, 628, 198 ]
2.615385
39
import os import sys import copy import collections import nltk import nltk.tokenize sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..")) import pagerank ''' textrank.py ----------- This module implements TextRank, an unsupervised keyword significance scoring algorithm. TextRank builds a weighted graph representation of a document using words as nodes and coocurrence frequencies between pairs of words as edge weights. It then applies PageRank to this graph, and treats the PageRank score of each word as its significance. The original research paper proposing this algorithm is available here: https://web.eecs.umich.edu/~mihalcea/papers/mihalcea.emnlp04.pdf ''' ## TextRank ##################################################################################### def __preprocessDocument(document, relevantPosTags): ''' This function accepts a string representation of a document as input, and returns a tokenized list of words corresponding to that document. ''' words = __tokenizeWords(document) posTags = __tagPartsOfSpeech(words) # Filter out words with irrelevant POS tags filteredWords = [] for index, word in enumerate(words): word = word.lower() tag = posTags[index] if not __isPunctuation(word) and tag in relevantPosTags: filteredWords.append(word) return filteredWords def textrank(document, windowSize=2, rsp=0.15, relevantPosTags=["NN", "ADJ"]): ''' This function accepts a string representation of a document and three hyperperameters as input. It returns Pandas matrix (that can be treated as a dictionary) that maps words in the document to their associated TextRank significance scores. Note that only words that are classified as having relevant POS tags are present in the map. ''' # Tokenize document: words = __preprocessDocument(document, relevantPosTags) # Build a weighted graph where nodes are words and # edge weights are the number of times words cooccur # within a window of predetermined size. In doing so # we double count each coocurrence, but that will not # alter relative weights which ultimately determine # TextRank scores. edgeWeights = collections.defaultdict(lambda: collections.Counter()) for index, word in enumerate(words): for otherIndex in range(index - windowSize, index + windowSize + 1): if otherIndex >= 0 and otherIndex < len(words) and otherIndex != index: otherWord = words[otherIndex] edgeWeights[word][otherWord] += 1.0 # Apply PageRank to the weighted graph: wordProbabilities = pagerank.powerIteration(edgeWeights, rsp=rsp) wordProbabilities.sort_values(ascending=False) return wordProbabilities ## NLP utilities ################################################################################ ## tests ######################################################################################## if __name__ == "__main__": main()
[ 11748, 28686, 198, 11748, 25064, 198, 11748, 4866, 198, 11748, 17268, 198, 198, 11748, 299, 2528, 74, 198, 11748, 299, 2528, 74, 13, 30001, 1096, 198, 198, 17597, 13, 6978, 13, 28463, 7, 15, 11, 28686, 13, 6978, 13, 22179, 7, 418, 1...
3.193449
977
import logging import os import random import string import time import unittest import neurolib.utils.paths as paths import neurolib.utils.pypetUtils as pu import numpy as np import pytest import xarray as xr from neurolib.models.aln import ALNModel from neurolib.models.fhn import FHNModel from neurolib.models.multimodel import MultiModel from neurolib.models.multimodel.builder.fitzhugh_nagumo import FitzHughNagumoNetwork from neurolib.optimize.exploration import BoxSearch from neurolib.utils.loadData import Dataset from neurolib.utils.parameterSpace import ParameterSpace def randomString(stringLength=10): """Generate a random string of fixed length""" letters = string.ascii_lowercase return "".join(random.choice(letters) for i in range(stringLength)) if __name__ == "__main__": unittest.main()
[ 11748, 18931, 198, 11748, 28686, 198, 11748, 4738, 198, 11748, 4731, 198, 11748, 640, 198, 11748, 555, 715, 395, 198, 198, 11748, 7669, 8019, 13, 26791, 13, 6978, 82, 355, 13532, 198, 11748, 7669, 8019, 13, 26791, 13, 79, 4464, 316, 1...
3.187023
262
# -*- coding: utf-8 -*- ''' Module offering 2 functions, encode() and decode(), to transcode between IRCv3.2 tags and python dictionaries. ''' import re import random import string _escapes = ( ("\\", "\\\\"), (";", r"\:"), (" ", r"\s"), ("\r", r"\r"), ("\n", r"\n"), ) # make the possibility of the substitute actually appearing in the text # negligible. Even for targeted attacks _substitute = (";TEMP:%s;" % ''.join(random.choice(string.ascii_letters) for i in range(20))) _unescapes = ( ("\\\\", _substitute), (r"\:", ";"), (r"\s", " "), (r"\r", "\r"), (r"\n", "\n"), (_substitute, "\\"), ) # valid tag-keys must contain of alphanumerics and hyphens only. # for vendor-tagnames: TLD with slash appended _valid_key = re.compile("^([\w.-]+/)?[\w-]+$") # valid escaped tag-values must not contain # NUL, CR, LF, semicolons or spaces _valid_escaped_value = re.compile("^[^ ;\n\r\0]*$") def encode(tags): '''Encodes a dictionary of tags to fit into an IRC-message. See IRC Message Tags: http://ircv3.net/specs/core/message-tags-3.2.html >>> from collections import OrderedDict >>> encode({'key': 'value'}) 'key=value' >>> d = {'aaa': 'bbb', 'ccc': None, 'example.com/ddd': 'eee'} >>> d_ordered = OrderedDict(sorted(d.items(), key=lambda t: t[0])) >>> encode(d_ordered) 'aaa=bbb;ccc;example.com/ddd=eee' >>> d = {'key': 'value;with special\\\\characters', 'key2': 'with=equals'} >>> d_ordered = OrderedDict(sorted(d.items(), key=lambda t: t[0])) >>> print(encode(d_ordered)) key=value\\:with\\sspecial\\\characters;key2=with=equals >>> print(encode({'key': r'\\something'})) key=\\\\something ''' tagstrings = [] for key, value in tags.items(): if not _valid_key.match(key): raise ValueError("dictionary key is invalid as tag key: " + key) # if no value, just append the key if value: tagstrings.append(key + "=" + _escape(value)) else: tagstrings.append(key) return ";".join(tagstrings) def decode(tagstring): '''Decodes a tag-string from an IRC-message into a python dictionary. See IRC Message Tags: http://ircv3.net/specs/core/message-tags-3.2.html >>> from pprint import pprint >>> pprint(decode('key=value')) {'key': 'value'} >>> pprint(decode('aaa=bbb;ccc;example.com/ddd=eee')) {'aaa': 'bbb', 'ccc': None, 'example.com/ddd': 'eee'} >>> s = r'key=value\\:with\\sspecial\\\\characters;key2=with=equals' >>> pprint(decode(s)) {'key': 'value;with special\\\\characters', 'key2': 'with=equals'} >>> print(decode(s)['key']) value;with special\\characters >>> print(decode(r'key=\\\\something')['key']) \\something ''' if not tagstring: # None/empty = no tags return {} tags = {} for tag in tagstring.split(";"): # value is either everything after "=", or None key, value = (tag.split("=", 1) + [None])[:2] if not _valid_key.match(key): raise ValueError("invalid tag key: " + key) if value: if not _valid_escaped_value.match(value): raise ValueError("invalid escaped tag value: " + value) value = _unescape(value) tags[key] = value return tags
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 7061, 6, 198, 26796, 6011, 362, 5499, 11, 37773, 3419, 290, 36899, 22784, 284, 1007, 8189, 1022, 198, 49060, 85, 18, 13, 17, 15940, 290, 21015, 48589, 3166, 13, 198, 7...
2.328938
1,441
from django import forms from django.contrib.auth.forms import PasswordResetForm, SetPasswordForm # from .models import RegionModel # from .models import SERVICE_CHOICES, REGION_CHOICES from django.contrib.auth import authenticate # from django.contrib.auth.forms import UserCreationForm, UserChangeForm # from .models import CustomUser # class PassResetForm(PasswordResetForm): # email = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Enter email', # 'type':'email'}), max_length=100) # # # class PassResetConfirmForm(SetPasswordForm): # new_password1 = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control', # 'placeholder':'Enter new password', # 'type':'password'}), max_length=100) # new_password2 = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', # 'placeholder': 'Enter new password again', # 'type': 'password'}), max_length=100) # class CustomUserCreationForm(UserCreationForm): # # class Meta(UserCreationForm): # model = CustomUser # fields = UserCreationForm.Meta.fields + ('region_name',) # # # class CustomUserChangeForm(UserChangeForm): # email = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'}), max_length=100) # username = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'}), max_length=254) # # class Meta: # model = CustomUser # fields = ('email','username')
[ 6738, 42625, 14208, 1330, 5107, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 23914, 1330, 30275, 4965, 316, 8479, 11, 5345, 35215, 8479, 198, 2, 422, 764, 27530, 1330, 17718, 17633, 198, 2, 422, 764, 27530, 1330, 47453, 62, ...
2.149218
831
# newly added libraries import copy import wandb import time import math import csv import shutil from tqdm import tqdm import torch import numpy as np import pandas as pd from client import Client from config import * import scheduler as sch
[ 2, 8308, 2087, 12782, 198, 11748, 4866, 198, 11748, 11569, 65, 198, 11748, 640, 198, 11748, 10688, 198, 11748, 269, 21370, 198, 11748, 4423, 346, 198, 6738, 256, 80, 36020, 1330, 256, 80, 36020, 198, 198, 11748, 28034, 198, 11748, 299, ...
3.588235
68
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import time import cv2 import matplotlib.pyplot as plt import numpy as np from progress.bar import Bar import torch import pickle import motmetrics as mm from lib.opts import opts from lib.logger import Logger from lib.utils.utils import AverageMeter from lib.dataset.dataset_factory import dataset_factory from lib.utils.pixset_metrics import compute_metrics pixset_categories = [ 'car', 'truck', 'bus', 'pedestrian', 'motorcyclist', 'cyclist', 'van' ] opt = opts().parse() filename = '../options/test_opt_pixset.txt' with open(filename, 'wb') as f: pickle.dump(opt, f) # # print('dataset -> ', opt.dataset) # print('lstm -> ', opt.lstm) # print(f'saved {filename}') # with open(filename, 'rb') as f: # opt = pickle.load(f) # print('use pixell ->', opt.use_pixell) from lib.detector import Detector from lib.utils.image import plot_tracking, plot_tracking_ddd import json min_box_area = 20 _vehicles = ["car", "truck", "bus", "van"] _cycles = ["motorcyclist", "cyclist"] _pedestrians = ["pedestrian"] attribute_to_id = { "": 0, "cycle.with_rider": 1, "cycle.without_rider": 2, "pedestrian.moving": 3, "pedestrian.standing": 4, "pedestrian.sitting_lying_down": 5, "vehicle.moving": 6, "vehicle.parked": 7, "vehicle.stopped": 8, } id_to_attribute = {v: k for k, v in attribute_to_id.items()} nuscenes_att = np.zeros(8, np.float32) if __name__ == "__main__": # opt = opts().parse() prefetch_test(opt)
[ 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 6738, 11593, 37443, 834, 1330, 7297, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 198, 11748, 28686, 198, 11748, 640, 198, 198, 11748, 269, 85, 17, 198, 11748, 2603, 29487...
2.483283
658
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import logging import shutil import subprocess import tempfile from pathlib import Path from threading import Lock from typing import Iterable, Optional, Union import numpy as np from fasteners import InterProcessLock from compiler_gym.datasets import Benchmark, BenchmarkSource, Dataset from compiler_gym.datasets.benchmark import BenchmarkWithSource from compiler_gym.envs.gcc.gcc import Gcc from compiler_gym.util.decorators import memoized_property from compiler_gym.util.runfiles_path import runfiles_path from compiler_gym.util.shell_format import plural from compiler_gym.util.truncate import truncate # The maximum value for the --seed argument to csmith. UINT_MAX = (2 ** 32) - 1 _CSMITH_BIN = runfiles_path("compiler_gym/third_party/csmith/csmith/bin/csmith") _CSMITH_INCLUDES = runfiles_path( "compiler_gym/third_party/csmith/csmith/include/csmith-2.3.0" ) _CSMITH_INSTALL_LOCK = Lock() # TODO(github.com/facebookresearch/CompilerGym/issues/325): This can be merged # with the LLVM implementation. def benchmark(self, uri: str) -> CsmithBenchmark: return self.benchmark_from_seed(int(uri.split("/")[-1])) def _random_benchmark(self, random_state: np.random.Generator) -> Benchmark: seed = random_state.integers(UINT_MAX) return self.benchmark_from_seed(seed) def benchmark_from_seed( self, seed: int, max_retries: int = 3, retry_count: int = 0 ) -> CsmithBenchmark: """Get a benchmark from a uint32 seed. :param seed: A number in the range 0 <= n < 2^32. :return: A benchmark instance. :raises OSError: If Csmith fails. :raises BenchmarkInitError: If the C program generated by Csmith cannot be lowered to LLVM-IR. """ if retry_count >= max_retries: raise OSError( f"Csmith failed after {retry_count} {plural(retry_count, 'attempt', 'attempts')} " f"with seed {seed}" ) self.install() # Run csmith with the given seed and pipe the output to clang to # assemble a bitcode. self.logger.debug("Exec csmith --seed %d", seed) csmith = subprocess.Popen( [str(self.csmith_bin_path), "--seed", str(seed)], stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) # Generate the C source. src, stderr = csmith.communicate(timeout=300) if csmith.returncode: try: stderr = "\n".join( truncate(stderr.decode("utf-8"), max_line_len=200, max_lines=20) ) logging.warning("Csmith failed with seed %d: %s", seed, stderr) except UnicodeDecodeError: # Failed to interpret the stderr output, generate a generic # error message. logging.warning("Csmith failed with seed %d", seed) return self.benchmark_from_seed( seed, max_retries=max_retries, retry_count=retry_count + 1 ) # Pre-process the source. with tempfile.TemporaryDirectory() as tmpdir: src_file = f"{tmpdir}/src.c" with open(src_file, "wb") as f: f.write(src) preprocessed_src = self.gcc( "-E", "-I", str(self.site_data_path / "includes"), "-o", "-", src_file, cwd=tmpdir, timeout=60, volumes={ str(self.site_data_path / "includes"): { "bind": str(self.site_data_path / "includes"), "mode": "ro", } }, ) return self.benchmark_class.create( f"{self.name}/{seed}", preprocessed_src.encode("utf-8"), src )
[ 2, 15069, 357, 66, 8, 3203, 11, 3457, 13, 290, 663, 29116, 13, 198, 2, 198, 2, 770, 2723, 2438, 318, 11971, 739, 262, 17168, 5964, 1043, 287, 262, 198, 2, 38559, 24290, 2393, 287, 262, 6808, 8619, 286, 428, 2723, 5509, 13, 198, ...
2.151403
1,889
__author__ = "Daniel Winklehner" __doc__ = "Find out if a number is a power of two" def power_of_two(number): """ Function that checks if the input value (data) is a power of 2 (i.e. 2, 4, 8, 16, 32, ...) """ res = 0 while res == 0: res = number % 2 number /= 2.0 print("res: {}, data: {}".format(res, number)) if number == 1 and res == 0: return True return False
[ 834, 9800, 834, 796, 366, 19962, 370, 19894, 22277, 1, 198, 834, 15390, 834, 796, 366, 16742, 503, 611, 257, 1271, 318, 257, 1176, 286, 734, 1, 628, 198, 4299, 1176, 62, 1659, 62, 11545, 7, 17618, 2599, 198, 220, 220, 220, 37227, ...
2.300518
193
from viewdom import html, render, use_context, Context expected = '<h1>My Todos</h1><ul><li>Item: first</li></ul>' # start-after title = 'My Todos' todos = ['first'] result = render(html(''' <{Context} prefix="Item: "> <h1>{title}</h1> <{TodoList} todos={todos} /> <//> ''')) # '<h1>My Todos</h1><ul><li>Item: first</li></ul>'
[ 6738, 1570, 3438, 1330, 27711, 11, 8543, 11, 779, 62, 22866, 11, 30532, 198, 198, 40319, 796, 705, 27, 71, 16, 29, 3666, 309, 375, 418, 3556, 71, 16, 6927, 377, 6927, 4528, 29, 7449, 25, 717, 3556, 4528, 12240, 377, 29, 6, 198, ...
2.10119
168
from django.views.generic import DetailView, ListView, TemplateView from .models import Books
[ 6738, 42625, 14208, 13, 33571, 13, 41357, 1330, 42585, 7680, 11, 7343, 7680, 11, 37350, 7680, 198, 198, 6738, 764, 27530, 1330, 13661 ]
4.086957
23
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved from .evaluator import DatasetEvaluator, DatasetEvaluators, inference_context, inference_on_dataset from .testing import print_csv_format, verify_results from .hico_evaluation import HICOEvaluator from .swig_evaluation import SWIGEvaluator # from .doh_evaluation import DOHDetectionEvaluator __all__ = [k for k in globals().keys() if not k.startswith("_")]
[ 2, 15069, 357, 66, 8, 3203, 11, 3457, 13, 290, 663, 29116, 13, 1439, 6923, 33876, 198, 6738, 764, 18206, 84, 1352, 1330, 16092, 292, 316, 36, 2100, 84, 1352, 11, 16092, 292, 316, 36, 2100, 84, 2024, 11, 32278, 62, 22866, 11, 32278...
3.064286
140
import datetime as dt from django.db import models from django.core.validators import MinValueValidator, MaxValueValidator from django.core.exceptions import ValidationError from users.models import CustomUser def validate_year(value): """ . """ if value > dt.datetime.now().year: raise ValidationError( ' !') return value
[ 11748, 4818, 8079, 355, 288, 83, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 6738, 42625, 14208, 13, 7295, 13, 12102, 2024, 1330, 1855, 11395, 47139, 1352, 11, 5436, 11395, 47139, 1352, 198, 6738, 42625, 14208, 13, 7295, 13...
2.652778
144
### ### This file was automatically generated ### from archinfo.arch import register_arch, Endness, Register from .common import ArchPcode register_arch(['powerpc:le:32:quicc'], 32, Endness.LE, ArchPcode_PowerPC_LE_32_QUICC)
[ 21017, 198, 21017, 770, 2393, 373, 6338, 7560, 198, 21017, 198, 198, 6738, 3934, 10951, 13, 998, 1330, 7881, 62, 998, 11, 5268, 1108, 11, 17296, 198, 198, 6738, 764, 11321, 1330, 5579, 47, 8189, 628, 198, 30238, 62, 998, 7, 17816, 6...
3.013158
76
# -*- coding: utf-8 -*- import json import pdb import os from os.path import join as pj import networkx as nx import pandas as pd from networkx.readwrite.json_graph import node_link_data def plot_graph(self): """ Plot the transmission graph of the simulation. TODO: Draw arrows and have a directed graph. http://goo.gl/Z697dH TODO: Graph with big nodes for big transmissions """ fig = plt.figure() ax1 = fig.add_subplot(111) ax1.set_title("Transmission / RPL tree") ax1.axis("off") val_color = {"udp_server": 0.5714285714285714} pos = {node: data["pos"] for node, data in self.radio_tree.nodes(data=True)} # color for all nodes node_color = [val_color.get(data["mote_type"], 0.25) for node, data in self.radio_tree.nodes(data=True)] # Drawing the nodes nx.draw_networkx_nodes(self.radio_tree, pos, node_color=node_color, ax=ax1) nx.draw_networkx_labels(self.radio_tree, pos, ax=ax1) # Drawing radio edges nx.draw_networkx_edges(self.radio_tree, pos, edgelist=self.radio_tree.edges(), width=8, alpha=0.5, ax=ax1) # Adding the depth of each node. with open(PJ(self.result_dir, "depth.csv")) as depth_f: reader = DictReader(depth_f) for row in reader: node = int(row["node"]) depth = row["depth"] ax1.text(pos[node][0] + 5, pos[node][1] + 5, depth, bbox=dict(facecolor='red', alpha=0.5), horizontalalignment='center') # Drawing RPL edges nx.draw_networkx_edges( self.rpl_tree, pos, edge_color='r', nodelist=[], arrows=True, ax=ax1) img_path = PJ(self.img_dir, "graph.pdf") fig.savefig(img_path, format="pdf") update_report(self.result_dir, "plot_graph", { "img_src": "img/graph.pdf", "comment": """ When the edge is thick it means edges are in an RPL instance. Otherwise it means that the two nodes can see each others. """, "text": """ We generate a random geometric graph then use information coming to the RPL root to construct the gateway representation of the RPL tree. We add into this tree representation the traffic generated. """}) def transmission_graph(self): """ Plot the transmission graph of the simulation. """ settings = self.settings["transmission_graph"] output_path = pj(self.result_folder_path, *settings["output_path"]) fig_rplinfo, ax_transmission_graph = plt.subplots() net = nx.Graph() # nodes mote_types = self.settings["mote_types"] motes = self.settings["motes"] position = {} for mote in motes: mote_type = mote["mote_type"] mote_id = mote["mote_id"] position[mote_id] = (mote["x"], mote["y"]) mote_types[mote_type] \ .setdefault("nodes", []) \ .append(mote["mote_id"]) # edges transmitting_range = self.settings["transmitting_range"] for couple in itertools.product(motes, motes): if 0 < distance(couple) <= transmitting_range: net.add_edge(couple[0]["mote_id"], couple[1]["mote_id"]) for mote_type in mote_types: color = mote_types[mote_type]["color"] nodelist = mote_types[mote_type]["nodes"] nx.draw_networkx_nodes(net, position, nodelist=nodelist, node_color=color, ax=ax_transmission_graph) nx.draw_networkx_edges(net, pos=position, ax=ax_transmission_graph) # labels nx.draw_networkx_labels(net, position, ax=ax_transmission_graph) plt.axis('off') plt.savefig(output_path) # save as PNG return ax_transmission_graph def rpl_graph(folder): """ Build up the RPL representation at the gateway """ output_folder = pj(folder, "results", "graph") if not os.path.exists(output_folder): os.makedirs(output_folder) df = pd.read_csv(pj(folder, "results", "messages.csv")) parent_df = df[df.message_type == "parent"] rpl_graph = nx.DiGraph() for c, p in parent_df.iterrows(): rpl_graph.add_edge(p["mote_id"], p["node"]) with open(pj(output_folder, "rpl_graph.json"), "w") as f: f.write(json.dumps(node_link_data(rpl_graph), sort_keys=True, indent=4))
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 11748, 33918, 198, 11748, 279, 9945, 198, 11748, 28686, 198, 6738, 28686, 13, 6978, 1330, 4654, 355, 279, 73, 198, 11748, 3127, 87, 355, 299, 87, 198, 11748, 19798,...
2.216717
1,998
# auto_telnet.py - remote control via telnet import os, sys, string, telnetlib from getpass import getpass if __name__ == '__main__': basename = os.path.splitext(os.path.basename(sys.argv[0]))[0] logname = os.environ.get("LOGNAME", os.environ.get("USERNAME")) host = 'localhost' import getopt optlist, user_list = getopt.getopt(sys.argv[1:], 'c:f:h:') usage = """ usage: %s [-h host] [-f cmdfile] [-c "command"] user1 user2 ... -c command -f command file -h host (default: '%s') Example: %s -c "echo $HOME" %s """ % (basename, host, basename, logname) if len(sys.argv) < 2: print usage sys.exit(1) cmd_list = [] for (opt, optarg) in optlist: if opt == '-f': for r in open(optarg).readlines(): if string.rstrip(r): cmd_list.append(r) elif opt == '-c': command = optarg if command[0] == '"' and command[-1] == '"': command = command[1:-1] cmd_list.append(command) elif opt == '-h': host = optarg autoTelnet = AutoTelnet(user_list, cmd_list, host=host)
[ 2, 8295, 62, 37524, 3262, 13, 9078, 532, 6569, 1630, 2884, 13632, 3262, 198, 11748, 28686, 11, 25064, 11, 4731, 11, 13632, 3262, 8019, 198, 6738, 651, 6603, 1330, 651, 6603, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834,...
2.051237
566
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon May 7 09:46:10 2018 @author: sungkyun FFTNet model using 2x1 dil-conv """ import numpy as np import torch import torch.nn as nn import torch.nn.functional as F # Models with Preset (for convenience) ''' dim_input: dimension of input (256 for 8-bit mu-law input) num_layer: number of layers (11 in paper). receptive field = 2^11 (2,048) io_ch: number of input(=output) channels in each fft layers skip_ch: number of skip-channels, only required for fft-residual net. Annotations: B: batch dimension C: channel dimension L: length dimension ''' # FFT_Block: define a basic FFT Block ''' FFT_Block: - using 2x1 dilated-conv, instead of LR split 1x1 conv. - described in the paper, section 2.2. - in case of the first layer used in the first FFT_Block, we use nn.embedding layer for one-hot index(0-255) entries. ''' ''' FFTNet: - [11 FFT_blocks] --> [FC_layer] --> [softmax] '''
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41972, 319, 2892, 1737, 220, 767, 7769, 25, 3510, 25, 940, 2864, 198, 198, 31, 9800, 25, 23568, 2584,...
2.66756
373
""" Copy - copy fields into other (possibly new) fields configuration: on: list of 'alert', 'revoke', 'report', 'reset' (optional: def 'alert' only) cp: ( (in,out), ... ) Field names take the form of dir1/dir2/dir3, which in the payload will be data[dir1][dir2][dir3] """ import logging from snewpdag.dag import Node
[ 37811, 198, 29881, 532, 4866, 7032, 656, 584, 357, 39363, 649, 8, 7032, 198, 198, 11250, 3924, 25, 198, 220, 319, 25, 1351, 286, 705, 44598, 3256, 705, 18218, 2088, 3256, 705, 13116, 3256, 705, 42503, 6, 357, 25968, 25, 825, 705, 44...
2.927928
111
''' houses each team member's link to personal GitHub io or website or blog space RJProctor ''' # Imports from 3rd party libraries import dash import dash_bootstrap_components as dbc import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output from app import app # 1 column layout # https://dash-bootstrap-components.opensource.faculty.ai/l/components/layout column1 = dbc.Col( [ dcc.Markdown( """ ## The Team: Select a link to learn more about each of our team members. """ ), ], ) # create footer column2 = dbc.Col( [ dcc.Markdown( """ **Debbie Cohen** https://github.com/dscohen75/dscohen75.github.io https://medium.com/@debbiecohen_22419 **Moe Fa** --- **Eduardo Padilla** https://medium.com/@eprecendez --- **R. Jeannine Proctor** https://jproctor-rebecca.github.io/ https://medium.com/@jproctor.m.ed.tn --- **Code Review Team Members:** Taylor Curran, Regina Dircio, Robert Giuffrie, Ryan Herr, Brendon Hoss, Anika Nacey, Tomas Phillips, Raymond Tan, and Rebecca Duke-Wiesenberg """ ), ], ) layout = dbc.Row([column1, column2])
[ 7061, 6, 220, 198, 20089, 1123, 1074, 2888, 338, 198, 8726, 284, 2614, 21722, 33245, 393, 198, 732, 12485, 393, 4130, 2272, 198, 49, 41, 2964, 2715, 198, 7061, 6, 198, 2, 1846, 3742, 422, 513, 4372, 2151, 12782, 198, 11748, 14470, 1...
1.926017
811
from importlib import _bootstrap from . import util import collections import imp import sys import unittest if __name__ == '__main__': test_main()
[ 6738, 1330, 8019, 1330, 4808, 18769, 26418, 198, 6738, 764, 1330, 7736, 198, 198, 11748, 17268, 198, 11748, 848, 198, 11748, 25064, 198, 11748, 555, 715, 395, 628, 628, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198,...
3.204082
49
import os from glob import iglob from concurrent.futures import ThreadPoolExecutor
[ 11748, 28686, 198, 6738, 15095, 1330, 220, 38686, 672, 198, 6738, 24580, 13, 69, 315, 942, 1330, 14122, 27201, 23002, 38409, 628, 628 ]
3.73913
23
#!/usr/bin/env python from livereload import Server, shell server = Server() server.watch('*.rst', shell('make html')) server.serve()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 201, 198, 6738, 2107, 260, 2220, 1330, 9652, 11, 7582, 201, 198, 201, 198, 15388, 796, 9652, 3419, 201, 198, 15388, 13, 8340, 10786, 24620, 81, 301, 3256, 7582, 10786, 15883, 27711, 6, 4008...
2.764706
51
# -*- coding: UTF-8 -*- # !/usr/bin/python # @time :2019/6/5 21:04 # @author :Mo # @function :file of path import os import pathlib import sys # path_root = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir)) path_root = path_root.replace('\\', '/') path_top = str(pathlib.Path(os.path.abspath(__file__)).parent.parent.parent) path_top = path_top.replace('\\', '/') # path of embedding path_embedding_user_dict = path_root + '/data/embeddings/user_dict.txt' path_embedding_random_char = path_root + '/data/embeddings/term_char.txt' path_embedding_random_word = path_root + '/data/embeddings/term_word.txt' path_embedding_bert = path_root + '/data/embeddings/chinese_L-12_H-768_A-12/' path_embedding_xlnet = path_root + '/data/embeddings/chinese_xlnet_mid_L-24_H-768_A-12/' path_embedding_albert = path_root + '/data/embeddings/albert_base_zh' path_embedding_vector_word2vec_char = path_root + '/data/embeddings/multi_label_char.vec' path_embedding_vector_word2vec_word = path_root + '/data/embeddings/multi_label_word.vec' path_embedding_vector_word2vec_char_bin = path_root + '/data/embeddings/multi_label_char.bin' path_embedding_vector_word2vec_word_bin = path_root + '/data/embeddings/multi_label_word.bin' # classify data of baidu qa 2019 path_baidu_qa_2019_train = path_root + '/data/baidu_qa_2019/baike_qa_train.csv' path_baidu_qa_2019_valid = path_root + '/data/baidu_qa_2019/baike_qa_valid.csv' # path_byte_multi_news_train = path_root + '/data/byte_multi_news/train.csv' path_byte_multi_news_valid = path_root + '/data/byte_multi_news/valid.csv' path_byte_multi_news_label = path_root + '/data/byte_multi_news/labels.csv' # classify data of baidu qa 2019 path_sim_webank_train = path_root + '/data/sim_webank/train.csv' path_sim_webank_valid = path_root + '/data/sim_webank/valid.csv' path_sim_webank_test = path_root + '/data/sim_webank/test.csv' # classfiy multi labels 2021 path_multi_label_train = path_root + '/data/multi_label/train.csv' path_multi_label_valid = path_root + '/data/multi_label/valid.csv' path_multi_label_labels = path_root + '/data/multi_label/labels.csv' path_multi_label_tests = path_root + '/data/multi_label/tests.csv' # path_label = path_multi_label_labels path_train = path_multi_label_train path_valid = path_multi_label_valid path_tests = path_multi_label_tests path_edata = path_root + "/../out/error_data.csv" # fast_text config path_out = path_top + "/out/" # path_model_dir = path_root + "/data/model/fast_text/" # path_model = path_root + '/data/model/fast_text/model_fast_text.h5' # path_hyper_parameters = path_root + '/data/model/fast_text/hyper_parameters.json' # embedding path_fineture = path_root + "/data/model/fast_text/embedding_trainable.h5" # - path_category = path_root + '/data/multi_label/category2labels.json' # l2i_i2l path_l2i_i2l = path_root + '/data/multi_label/l2i_i2l.json'
[ 2, 532, 9, 12, 19617, 25, 41002, 12, 23, 532, 9, 12, 201, 198, 2, 5145, 14, 14629, 14, 8800, 14, 29412, 201, 198, 2, 2488, 2435, 220, 220, 220, 220, 1058, 23344, 14, 21, 14, 20, 2310, 25, 3023, 201, 198, 2, 2488, 9800, 220, ...
2.425759
1,219
#!/usr/bin/env python # -*- coding: UTF-8 -*- # Created by Roberto Preste import pytest import asyncio from pandas.testing import assert_frame_equal from apyhgnc import apyhgnc # apyhgnc.info # apyhgnc.fetch # apyhgnc.search
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 41002, 12, 23, 532, 9, 12, 198, 2, 15622, 416, 32076, 24158, 68, 198, 11748, 12972, 9288, 198, 11748, 30351, 952, 198, 6738, 19798, 292, 13, 33407, 1330, ...
2.459184
98
import os.path import argparse from xml.etree import ElementTree as ET if __name__ == "__main__": main()
[ 11748, 28686, 13, 6978, 198, 11748, 1822, 29572, 198, 198, 6738, 35555, 13, 316, 631, 1330, 11703, 27660, 355, 12152, 628, 628, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 1388, 3419, 198 ]
2.804878
41
libro = Libro("HyP", "JK") libro1 = Libro("La Isla M", "JCortazar") libro2 = Libro("El tunel", "Sabato") biblio = Biblioteca() biblio.agregar_libro(libro) biblio.agregar_libro(libro1) biblio.agregar_libro(libro2) print(biblio.contiene_libro("HyP", "JK")) print(biblio.sacar_libro("HyP", "JK")) print(biblio.contiene_libro("HyP", "JK"))
[ 198, 8019, 305, 796, 7980, 305, 7203, 21217, 47, 1600, 366, 41, 42, 4943, 198, 8019, 305, 16, 796, 7980, 305, 7203, 14772, 1148, 5031, 337, 1600, 366, 34382, 419, 29413, 4943, 198, 8019, 305, 17, 796, 7980, 305, 7203, 9527, 6278, 41...
2.011976
167
# -*- coding: utf-8 -*- import unittest from xml.etree import ElementTree as ET from parser_tool import tokenizer from parser_tool import htmlgenerator
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 555, 715, 395, 198, 6738, 35555, 13, 316, 631, 1330, 11703, 27660, 355, 12152, 198, 198, 6738, 30751, 62, 25981, 1330, 11241, 7509, 198, 6738, 30751, 62, 25981, 1...
3.208333
48
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.core.files import File
[ 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, 198, 6738, 42625, 14208, 13, 7295, 13, 16...
3.021277
47
load("//tools/bzl:maven_jar.bzl", "maven_jar")
[ 2220, 7203, 1003, 31391, 14, 65, 48274, 25, 2611, 574, 62, 9491, 13, 65, 48274, 1600, 366, 2611, 574, 62, 9491, 4943, 198 ]
2.043478
23
# Este programa muestra la suma de dos variables, de tipo int y float print("Este programa muestra la suma de dos variables, de tipo int y float") print("Tambin muestra que la variable que realiza la operacin es de tipo float") numero1 = 7 numero2 = 3.1416 sumadeambos = numero1 + numero2 print("El resultado de la suma es: ") print(sumadeambos) print(type(sumadeambos)) # Este programa fue escrito por Emilio Carcao Bringas
[ 2, 412, 4169, 1430, 64, 38779, 395, 430, 8591, 2160, 64, 390, 23430, 9633, 11, 390, 8171, 78, 493, 331, 12178, 201, 198, 201, 198, 4798, 7203, 36, 4169, 1430, 64, 38779, 395, 430, 8591, 2160, 64, 390, 23430, 9633, 11, 390, 8171, 7...
2.709877
162
# -*- coding: utf-8 -*- from sklearn import preprocessing from torch.autograd import Variable from models_gat import GAT import os import torch import numpy as np import argparse import pickle import sklearn.metrics as metrics import cross_val import time import random torch.manual_seed(0) np.random.seed(0) random.seed(0) device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') def evaluate(dataset, model_GAT, args, threshold_value, model_name): """ Parameters ---------- dataset : dataloader (dataloader for the validation/test dataset). model_GCN : nn model (GAT model). args : arguments threshold_value : float (threshold for adjacency matrices). Description ---------- This methods performs the evaluation of the model on test/validation dataset Returns ------- test accuracy. """ model_GAT.eval() labels = [] preds = [] for batch_idx, data in enumerate(dataset): adj = Variable(data['adj'].float(), requires_grad=False).to(device) labels.append(data['label'].long().numpy()) adj = torch.squeeze(adj) features = np.identity(adj.shape[0]) features = Variable(torch.from_numpy(features).float(), requires_grad=False).cpu() if args.threshold in ["median", "mean"]: adj = torch.where(adj > threshold_value, torch.tensor([1.0]), torch.tensor([0.0])) ypred = model_GAT(features, adj) _, indices = torch.max(ypred, 1) preds.append(indices.cpu().data.numpy()) labels = np.hstack(labels) preds = np.hstack(preds) simple_r = {'labels':labels,'preds':preds} with open("./gat/Labels_and_preds/"+model_name+".pickle", 'wb') as f: pickle.dump(simple_r, f) result = {'prec': metrics.precision_score(labels, preds, average='macro'), 'recall': metrics.recall_score(labels, preds, average='macro'), 'acc': metrics.accuracy_score(labels, preds), 'F1': metrics.f1_score(labels, preds, average="micro")} if args.evaluation_method == 'model assessment': name = 'Test' if args.evaluation_method == 'model selection': name = 'Validation' print(name, " accuracy:", result['acc']) return result['acc'] def train(args, train_dataset, val_dataset, model_GAT, threshold_value, model_name): """ Parameters ---------- args : arguments train_dataset : dataloader (dataloader for the validation/test dataset). val_dataset : dataloader (dataloader for the validation/test dataset). model_GAT : nn model (GAT model). threshold_value : float (threshold for adjacency matrices). Description ---------- This methods performs the training of the model on train dataset and calls evaluate() method for evaluation. Returns ------- test accuracy. """ params = list(model_GAT.parameters()) optimizer = torch.optim.Adam(params, lr=args.lr, weight_decay=args.weight_decay) test_accs = [] train_loss=[] val_acc=[] for epoch in range(args.num_epochs): print("Epoch ",epoch) print("Size of Training Set:" + str(len(train_dataset))) print("Size of Validation Set:" + str(len(val_dataset))) model_GAT.train() total_time = 0 avg_loss = 0.0 preds = [] labels = [] for batch_idx, data in enumerate(train_dataset): begin_time = time.time() adj = Variable(data['adj'].float(), requires_grad=False).to(device) label = Variable(data['label'].long()).to(device) #adj_id = Variable(data['id'].int()).to(device) adj = torch.squeeze(adj) features = np.identity(adj.shape[0]) features = Variable(torch.from_numpy(features).float(), requires_grad=False).cpu() if args.threshold in ["median", "mean"]: adj = torch.where(adj > threshold_value, torch.tensor([1.0]), torch.tensor([0.0])) ypred = model_GAT(features, adj) _, indices = torch.max(ypred, 1) preds.append(indices.cpu().data.numpy()) labels.append(data['label'].long().numpy()) loss = model_GAT.loss(ypred, label) model_GAT.zero_grad() loss.backward() #nn.utils.clip_grad_norm_(model_DIFFPOOL.parameters(), args.clip) optimizer.step() avg_loss += loss elapsed = time.time() - begin_time total_time += elapsed if epoch == args.num_epochs-1: model_GAT.is_trained = True preds = np.hstack(preds) labels = np.hstack(labels) print("Train accuracy : ", np.mean( preds == labels )) test_acc = evaluate(val_dataset, model_GAT, args, threshold_value, model_name) print('Avg loss: ', avg_loss, '; epoch time: ', total_time) test_accs.append(test_acc) train_loss.append(avg_loss) val_acc.append(test_acc) path = './gat/weights/W_'+model_name+'.pickle' if os.path.exists(path): os.remove(path) os.rename('GAT_W.pickle',path) los_p = {'loss':train_loss} with open("./gat/training_loss/Training_loss_"+model_name+".pickle", 'wb') as f: pickle.dump(los_p, f) torch.save(model_GAT,"./gat/models/GAT_"+model_name+".pt") return test_acc def load_data(args): """ Parameters ---------- args : arguments Description ---------- This methods loads the adjacency matrices representing the args.view -th view in dataset Returns ------- List of dictionaries{adj, label, id} """ #Load graphs and labels with open('data/'+args.dataset+'/'+args.dataset+'_edges','rb') as f: multigraphs = pickle.load(f) with open('data/'+args.dataset+'/'+args.dataset+'_labels','rb') as f: labels = pickle.load(f) adjacencies = [multigraphs[i][:,:,args.view] for i in range(len(multigraphs))] #Normalize inputs if args.NormalizeInputGraphs==True: for subject in range(len(adjacencies)): adjacencies[subject] = minmax_sc(adjacencies[subject]) #Create List of Dictionaries G_list=[] for i in range(len(labels)): G_element = {"adj": adjacencies[i],"label": labels[i],"id": i,} G_list.append(G_element) return G_list def arg_parse(dataset, view, num_shots=2, cv_number=5): """ arguments definition method """ parser = argparse.ArgumentParser(description='Graph Classification') parser.add_argument('--mode', type=str, default='train', choices=['train', 'test']) parser.add_argument('--v', type=str, default=1) parser.add_argument('--data', type=str, default='Sample_dataset', choices = [ f.path[5:] for f in os.scandir("data") if f.is_dir() ]) parser.add_argument('--dataset', type=str, default=dataset, help='Dataset') parser.add_argument('--view', type=int, default=view, help = 'view index in the dataset') parser.add_argument('--num_epochs', type=int, default=1, #50 help='Training Epochs') parser.add_argument('--num_shots', type=int, default=num_shots, #100 help='number of shots') parser.add_argument('--cv_number', type=int, default=cv_number, help='number of validation folds.') parser.add_argument('--NormalizeInputGraphs', default=False, action='store_true', help='Normalize Input adjacency matrices of graphs') parser.add_argument('--evaluation_method', type=str, default='model assessment', help='evaluation method, possible values : model selection, model assessment') parser.add_argument('--threshold', dest='threshold', default='mean', help='threshold the graph adjacency matrix. Possible values: no_threshold, median, mean') parser.add_argument('--no-cuda', action='store_true', default=False, help='Disables CUDA training.') parser.add_argument('--num-classes', dest='num_classes', type=int, default=2, help='Number of label classes') parser.add_argument('--lr', type=float, default=0.001, help='Initial learning rate.') parser.add_argument('--weight_decay', type=float, default=5e-4, help='Weight decay (L2 loss on parameters).') parser.add_argument('--hidden', type=int, default=8, help='Number of hidden units.') parser.add_argument('--nb_heads', type=int, default=8, help='Number of head attentions.') parser.add_argument('--dropout', type=float, default=0.8, help='Dropout rate (1 - keep probability).') parser.add_argument('--alpha', type=float, default=0.2, help='Alpha for the leaky_relu.') return parser.parse_args() def benchmark_task(args, model_name): """ Parameters ---------- args : Arguments Description ---------- Initiates the model and performs train/test or train/validation splits and calls train() to execute training and evaluation. Returns ------- test_accs : test accuracies (list) """ G_list = load_data(args) num_nodes = G_list[0]['adj'].shape[0] test_accs = [] folds = cross_val.stratify_splits(G_list,args) [random.shuffle(folds[i]) for i in range(len(folds))] for i in range(args.cv_number): train_set, validation_set, test_set = cross_val.datasets_splits(folds, args, i) if args.evaluation_method =='model selection': train_dataset, val_dataset, threshold_value = cross_val.model_selection_split(train_set, validation_set, args) if args.evaluation_method =='model assessment': train_dataset, val_dataset, threshold_value = cross_val.model_assessment_split(train_set, validation_set, test_set, args) print("CV : ",i) model_GAT = GAT(nfeat=num_nodes, nhid=args.hidden, nclass=args.num_classes, dropout=args.dropout, nheads=args.nb_heads, alpha=args.alpha) test_acc = train(args, train_dataset, val_dataset, model_GAT, threshold_value, model_name+"_CV_"+str(i)+"_view_"+str(args.view)) test_accs.append(test_acc) return test_accs
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 1341, 35720, 1330, 662, 36948, 198, 6738, 28034, 13, 2306, 519, 6335, 1330, 35748, 198, 6738, 4981, 62, 41268, 1330, 402, 1404, 198, 198, 11748, 28686, 198, 11748, ...
2.235147
4,797
import copy import numbers import struct from ._common import * from ._exif import * TIFF_HEADER_LENGTH = 8 def dump(exif_dict_original): """ py:function:: piexif.load(data) Return exif as bytes. :param dict exif: Exif data({"0th":dict, "Exif":dict, "GPS":dict, "Interop":dict, "1st":dict, "thumbnail":bytes}) :return: Exif :rtype: bytes """ exif_dict = copy.deepcopy(exif_dict_original) header = b"Exif\x00\x00\x4d\x4d\x00\x2a\x00\x00\x00\x08" exif_is = False gps_is = False interop_is = False first_is = False if "0th" in exif_dict: zeroth_ifd = exif_dict["0th"] else: zeroth_ifd = {} if (("Exif" in exif_dict) and len(exif_dict["Exif"]) or ("Interop" in exif_dict) and len(exif_dict["Interop"]) ): zeroth_ifd[ImageIFD.ExifTag] = 1 exif_is = True exif_ifd = exif_dict["Exif"] if ("Interop" in exif_dict) and len(exif_dict["Interop"]): exif_ifd[ExifIFD. InteroperabilityTag] = 1 interop_is = True interop_ifd = exif_dict["Interop"] elif ExifIFD. InteroperabilityTag in exif_ifd: exif_ifd.pop(ExifIFD.InteroperabilityTag) elif ImageIFD.ExifTag in zeroth_ifd: zeroth_ifd.pop(ImageIFD.ExifTag) if ("GPS" in exif_dict) and len(exif_dict["GPS"]): zeroth_ifd[ImageIFD.GPSTag] = 1 gps_is = True gps_ifd = exif_dict["GPS"] elif ImageIFD.GPSTag in zeroth_ifd: zeroth_ifd.pop(ImageIFD.GPSTag) if (("1st" in exif_dict) and ("thumbnail" in exif_dict) and (exif_dict["thumbnail"] is not None)): first_is = True exif_dict["1st"][ImageIFD.JPEGInterchangeFormat] = 1 exif_dict["1st"][ImageIFD.JPEGInterchangeFormatLength] = 1 first_ifd = exif_dict["1st"] zeroth_set = _dict_to_bytes(zeroth_ifd, "0th", 0) zeroth_length = (len(zeroth_set[0]) + exif_is * 12 + gps_is * 12 + 4 + len(zeroth_set[1])) if exif_is: exif_set = _dict_to_bytes(exif_ifd, "Exif", zeroth_length) exif_length = len(exif_set[0]) + interop_is * 12 + len(exif_set[1]) else: exif_bytes = b"" exif_length = 0 if gps_is: gps_set = _dict_to_bytes(gps_ifd, "GPS", zeroth_length + exif_length) gps_bytes = b"".join(gps_set) gps_length = len(gps_bytes) else: gps_bytes = b"" gps_length = 0 if interop_is: offset = zeroth_length + exif_length + gps_length interop_set = _dict_to_bytes(interop_ifd, "Interop", offset) interop_bytes = b"".join(interop_set) interop_length = len(interop_bytes) else: interop_bytes = b"" interop_length = 0 if first_is: offset = zeroth_length + exif_length + gps_length + interop_length first_set = _dict_to_bytes(first_ifd, "1st", offset) thumbnail = _get_thumbnail(exif_dict["thumbnail"]) thumbnail_max_size = 64000 if len(thumbnail) > thumbnail_max_size: raise ValueError("Given thumbnail is too large. max 64kB") else: first_bytes = b"" if exif_is: pointer_value = TIFF_HEADER_LENGTH + zeroth_length pointer_str = struct.pack(">I", pointer_value) key = ImageIFD.ExifTag key_str = struct.pack(">H", key) type_str = struct.pack(">H", TYPES.Long) length_str = struct.pack(">I", 1) exif_pointer = key_str + type_str + length_str + pointer_str else: exif_pointer = b"" if gps_is: pointer_value = TIFF_HEADER_LENGTH + zeroth_length + exif_length pointer_str = struct.pack(">I", pointer_value) key = ImageIFD.GPSTag key_str = struct.pack(">H", key) type_str = struct.pack(">H", TYPES.Long) length_str = struct.pack(">I", 1) gps_pointer = key_str + type_str + length_str + pointer_str else: gps_pointer = b"" if interop_is: pointer_value = (TIFF_HEADER_LENGTH + zeroth_length + exif_length + gps_length) pointer_str = struct.pack(">I", pointer_value) key = ExifIFD.InteroperabilityTag key_str = struct.pack(">H", key) type_str = struct.pack(">H", TYPES.Long) length_str = struct.pack(">I", 1) interop_pointer = key_str + type_str + length_str + pointer_str else: interop_pointer = b"" if first_is: pointer_value = (TIFF_HEADER_LENGTH + zeroth_length + exif_length + gps_length + interop_length) first_ifd_pointer = struct.pack(">L", pointer_value) thumbnail_pointer = (pointer_value + len(first_set[0]) + 24 + 4 + len(first_set[1])) thumbnail_p_bytes = (b"\x02\x01\x00\x04\x00\x00\x00\x01" + struct.pack(">L", thumbnail_pointer)) thumbnail_length_bytes = (b"\x02\x02\x00\x04\x00\x00\x00\x01" + struct.pack(">L", len(thumbnail))) first_bytes = (first_set[0] + thumbnail_p_bytes + thumbnail_length_bytes + b"\x00\x00\x00\x00" + first_set[1] + thumbnail) else: first_ifd_pointer = b"\x00\x00\x00\x00" zeroth_bytes = (zeroth_set[0] + exif_pointer + gps_pointer + first_ifd_pointer + zeroth_set[1]) if exif_is: exif_bytes = exif_set[0] + interop_pointer + exif_set[1] return (header + zeroth_bytes + exif_bytes + gps_bytes + interop_bytes + first_bytes)
[ 11748, 4866, 198, 11748, 3146, 198, 11748, 2878, 198, 198, 6738, 47540, 11321, 1330, 1635, 198, 6738, 47540, 1069, 361, 1330, 1635, 628, 198, 51, 29267, 62, 37682, 1137, 62, 43, 49494, 796, 807, 628, 198, 4299, 10285, 7, 1069, 361, 62...
1.952814
2,861
import pygame import random from pygame import * pygame.init() width, height = 740, 500 screen = pygame.display.set_mode((width, height)) player = [pygame.transform.scale(pygame.image.load("Resources/Balljump-1(2).png"), (100,100)), pygame.transform.scale(pygame.image.load("Resources/Balljump-1.png"),(100,100))] launch = [pygame.transform.scale(pygame.image.load("Resources/Balljump-1.png"), (100,100)), pygame.transform.scale(pygame.image.load("Resources/Balljump-1(2).png"), (100,100)),pygame.transform.scale(pygame.image.load("Resources/Balljump-2.png"), (100,100)),pygame.transform.scale(pygame.image.load("Resources/Balljump-3.png"), (100,100)), pygame.transform.scale(pygame.image.load("Resources/Balljump-4.png"),(100,100))] shoot = [pygame.transform.scale(pygame.image.load("Resources/Balljump-5.png"), (100, 100)), pygame.transform.scale(pygame.image.load("Resources/Balljump-6.png"), (100, 100))] ball = pygame.transform.scale(pygame.image.load("Resources/ball.png"), (100,100)) blue = (0, 0, 128) white = (255, 255, 255) janimation, danimation, movable, motionactivate, limit_reached, nojump = False, False, False, False, False, False jumplock = True ballrelease, ballregain = False, False fr = pygame.time.Clock() c = 0 i = 0 p = 0 x, y = 0, 300 score = 0 a, b, rpos = 0, 0, 0 xpos, ypos = 17, 313 # Background image source: https://www.freepik.com/free-vector/floral-ornamental-abstract-background_6189902.htm#page=1&query=black%20background&position=40 background = pygame.image.load("Resources/back.jpg") gamestart = False while 1: keypress = pygame.key.get_pressed() fr.tick(30) screen.fill(0) if keypress[K_RETURN]: gamestart = True if gamestart == False: #screen.fill(0) screen.blit(background, (0,0)) # Draw opening texts font = pygame.font.Font("Resources/android.ttf", 64) text = font.render("Portal Hoop", True, white) textRect = text.get_rect() textRect.center = (width // 2, height // 2 - 100) screen.blit(text, textRect) font = pygame.font.Font("Resources/android.ttf", 18) text2 = font.render("Press Return to start", True, white) textRect2 = text2.get_rect() textRect2.center = (width // 2, height // 2 + 100) screen.blit(text2, textRect2) nojump = True # Check if any if gamestart == True: #screen.fill(0) player_animations() player_jump() basketball() screen_text() pygame.display.flip() pygame.display.set_caption("Portal Hoop") for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() exit(0)
[ 11748, 12972, 6057, 198, 11748, 4738, 198, 198, 6738, 12972, 6057, 1330, 1635, 198, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 198, 220, 198, 220, 220, 220, 220, 2...
2.300485
1,238
# (C) Datadog, Inc. 2021-present # All rights reserved # Licensed under a 3-clause BSD style license (see LICENSE) from typing import Any, Dict from datadog_checks.base.stubs.aggregator import AggregatorStub from datadog_checks.datadog_cluster_agent import DatadogClusterAgentCheck from datadog_checks.dev.utils import get_metadata_metrics NAMESPACE = 'datadog.cluster_agent' METRICS = [ 'admission_webhooks.certificate_expiry', 'admission_webhooks.mutation_attempts', 'admission_webhooks.mutation_errors', 'admission_webhooks.reconcile_errors', 'admission_webhooks.reconcile_success', 'admission_webhooks.webhooks_received', 'aggregator.flush', 'aggregator.processed', 'api_requests', 'cluster_checks.busyness', 'cluster_checks.configs_dangling', 'cluster_checks.configs_dispatched', 'cluster_checks.failed_stats_collection', 'cluster_checks.nodes_reporting', 'cluster_checks.rebalancing_decisions', 'cluster_checks.rebalancing_duration_seconds', 'cluster_checks.successful_rebalancing_moves', 'cluster_checks.updating_stats_duration_seconds', 'datadog.rate_limit_queries.limit', 'datadog.rate_limit_queries.period', 'datadog.rate_limit_queries.remaining', 'datadog.rate_limit_queries.reset', 'datadog.requests', 'external_metrics', 'external_metrics.datadog_metrics', 'external_metrics.delay_seconds', 'external_metrics.processed_value', 'secret_backend.elapsed', 'go.goroutines', 'go.memstats.alloc_bytes', 'go.threads', ]
[ 2, 357, 34, 8, 16092, 324, 519, 11, 3457, 13, 33448, 12, 25579, 198, 2, 1439, 2489, 10395, 198, 2, 49962, 739, 257, 513, 12, 565, 682, 347, 10305, 3918, 5964, 357, 3826, 38559, 24290, 8, 198, 6738, 19720, 1330, 4377, 11, 360, 713,...
2.506452
620
import pylab import numpy import sys if (len(sys.argv) < 2): fn = raw_input("Please enter data file to be plotted\n") else: fn = sys.argv[1] data = np.loadtxt(fn) # if the first line contains crap use skiprows=1 #data = np.loadtxt(fn, skiprows=1) fig = pylab.figure() ax = fig.add_subplot(111) # if you want to use multiple figures in one, use #ax1 = fig.add_subplot(211) #ax2 = fig.add_subplot(212) # and if (data.ndim == 1): x_axis = numpy.arange(data.size) ax.plot(x_axis, data) else: # ax.errorbar(data[:,0], data[:,1], yerr=data[:, 2]) # print 'mean y-value:', data[:, 1].mean() ax.plot(data[:, 0], data[:, 1], ls='-', lw=3, c='b') # ax.scatter(data[:,0], data[:,2]) # ax.plot(data[:,3], data[:,6]) # saving: # fig.savefig('output_figure.png') # otherwise nothing is shown pylab.show()
[ 11748, 279, 2645, 397, 198, 11748, 299, 32152, 198, 11748, 25064, 198, 198, 361, 357, 11925, 7, 17597, 13, 853, 85, 8, 1279, 362, 2599, 198, 220, 220, 220, 24714, 796, 8246, 62, 15414, 7203, 5492, 3802, 1366, 2393, 284, 307, 37515, ...
2.236074
377
from __future__ import division from lib import env_config from lib.senior_env import BetterEnvironment from keras.optimizers import Adam from rl.agents.dqn import DQNAgent from rl.policy import LinearAnnealedPolicy, BoltzmannQPolicy, EpsGreedyQPolicy from rl.memory import SequentialMemory from lib import models import random choices = [0,1,2] if __name__ == '__main__': config_ = env_config.EnvConfig('config/debug.json') env = BetterEnvironment(config_) INPUT_SHAPE = (30, 180) WINDOW_LENGTH = 4 model = models.build_paper_model() # Get the environment and extract the number of actions. nb_actions = 3 # Next, we build our model. We use the same model that was described by Mnih et al. (2015). input_shape = (WINDOW_LENGTH,) + INPUT_SHAPE # Finally, we configure and compile our agent. You can use every built-in Keras optimizer and # even the metrics! memory = SequentialMemory(limit=10000000, window_length=WINDOW_LENGTH) # Select a policy. We use eps-greedy action selection, which means that a random action is selected # with probability eps. We anneal eps from 1.0 to 0.1 over the course of 1M steps. This is done so that # the agent initially explores the environment (high eps) and then gradually sticks to what it knows # (low eps). We also set a dedicated eps value that is used during testing. Note that we set it to 0.05 # so that the agent still performs some random actions. This ensures that the agent cannot get stuck. policy = LinearAnnealedPolicy(EpsGreedyQPolicy(), attr='eps', value_max=1., value_min=.1, value_test=.05, nb_steps=1000000) # The trade-off between exploration and exploitation is difficult and an on-going research topic. # If you want, you can experiment with the parameters or use a different policy. Another popular one # is Boltzmann-style exploration: # policy = BoltzmannQPolicy(tau=1.) # Feel free to give it a try! dqn = DQNAgent(model=model, nb_actions=nb_actions, policy=policy, memory=memory, nb_steps_warmup=50000, gamma=.99, target_model_update=10000, train_interval=4, delta_clip=1.) dqn.compile(Adam(lr=.00025), metrics=['mae']) # Okay, now it's time to learn something! We capture the interrupt exception so that training # can be prematurely aborted. Notice that now you can use the built-in Keras callbacks! weights_filename = 'dqn_{}_weights.h5f'.format('god_help_me.weights') dqn.fit(env, nb_steps=100000, log_interval=10000) print(env.portfolio.print_portfolio_results())
[ 6738, 11593, 37443, 834, 1330, 7297, 198, 198, 6738, 9195, 1330, 17365, 62, 11250, 198, 6738, 9195, 13, 6248, 1504, 62, 24330, 1330, 11625, 31441, 198, 6738, 41927, 292, 13, 40085, 11341, 1330, 7244, 198, 6738, 374, 75, 13, 49638, 13, ...
2.924612
902
# I'm just the one that executes the instructions! import sys, math, json, operator, time import mcpi.minecraft as minecraft from PIL import Image as pillow from blockid import get_block import mcpi.block as block import functions as pymc from tqdm import tqdm import tkinter as tk # Functions # Main code mc = minecraft.Minecraft.create() try: json_file = open("blocks.json") json_put = json.load(json_file) except: pymc.chat(mc, "blocks.json not found, exiting!", 0) sys.exit(1) try: rim = pillow.open(sys.argv[1]) except: pymc.chat(mc, "bad image, exiting!", 0) sys.exit(1) orders = [] used = [] imwid, imhei = rim.size if imhei > 200: maxheight = 200 rim.thumbnail((200, maxheight), pillow.ANTIALIAS) imwid, imhei = rim.size pymc.chat(mc, "image is over 200 pixels, reducing height.", 1) rim.convert('RGB') im = rim.load() pbar = tqdm(total=imhei*imwid) for hei in range(imhei): for wid in range(imwid): smal = pymc.comp_pixel((im[wid, hei][0], im[wid, hei][1], im[wid, hei][2]), json_put) im[wid, hei] = smal[1] used.append(str(smal[2])) pbar.update(1) pbar.close() rim.save("result.GIF") # The result json_file.close() oldPos = mc.player.getPos() playerPos = [round(oldPos.x), round(oldPos.y), round(oldPos.z)] pymc.chat(mc, "Ready!") pbar = tqdm(total=imhei*imwid) num_temp = imhei*imwid-1 for hei in range(imhei): for wid in range(imwid): #print(used[wid + (imhei * hei)]) gblock = get_block(used[num_temp]) mc.setBlock(playerPos[0]+wid, playerPos[1]+hei, playerPos[2], gblock) num_temp -= 1 pbar.update(1) pbar.close() pymc.chat(mc, "Done!!") pymc.chat(mc, "Please star us on github if you like the result!", 2)
[ 2, 314, 1101, 655, 262, 530, 326, 42985, 262, 7729, 0, 198, 11748, 25064, 11, 10688, 11, 33918, 11, 10088, 11, 640, 198, 11748, 285, 13155, 72, 13, 17761, 355, 6164, 3323, 198, 6738, 350, 4146, 1330, 7412, 355, 28774, 198, 6738, 251...
2.329787
752
#!/usr/bin/python import optparse import os import re import sys import cairo from gaphas.painter import Context, ItemPainter from gaphas.view import View import gaphor.UML as UML from gaphor.application import Application from gaphor.storage import storage def pkg2dir(package): """ Return directory path from UML package class. """ name = [] while package: name.insert(0, package.name) package = package.package return "/".join(name)
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 198, 11748, 2172, 29572, 198, 11748, 28686, 198, 11748, 302, 198, 11748, 25064, 198, 198, 11748, 1275, 7058, 198, 6738, 308, 6570, 292, 13, 35436, 353, 1330, 30532, 11, 9097, 38490, 353, 198, ...
2.841176
170
# -*- coding: utf-8 -*- """ Created on Fri Apr 08 11:33:01 2016 @author: Leander Kotzur """ import tsib
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41972, 319, 19480, 2758, 8487, 1367, 25, 2091, 25, 486, 1584, 198, 198, 31, 9800, 25, 1004, 4066, 21702, 89, 333, 198, 37811, 628, 198, 11748, 40379, 571, ...
2.4
45
from abc import ABC, abstractmethod from collections import defaultdict from collections.abc import Sequence from functools import partial from itertools import product import numpy as np from pycompss.api.api import compss_wait_on from scipy.stats import rankdata from sklearn import clone from sklearn.model_selection import ParameterGrid, ParameterSampler from numpy.ma import MaskedArray from dislib.model_selection._split import infer_cv from dislib.model_selection._validation import check_scorer, fit_and_score, \ validate_score, aggregate_score_dicts
[ 6738, 450, 66, 1330, 9738, 11, 12531, 24396, 198, 6738, 17268, 1330, 4277, 11600, 198, 6738, 17268, 13, 39305, 1330, 45835, 198, 6738, 1257, 310, 10141, 1330, 13027, 198, 6738, 340, 861, 10141, 1330, 1720, 198, 198, 11748, 299, 32152, 3...
3.641026
156
import os from django.test import TestCase from mock import patch from ui.views import parse_search_results FIXTURES_ROOT = os.path.join(os.path.dirname(__file__), 'fixtures') FX = lambda *relpath: os.path.join(FIXTURES_ROOT, *relpath)
[ 11748, 28686, 198, 198, 6738, 42625, 14208, 13, 9288, 1330, 6208, 20448, 198, 6738, 15290, 1330, 8529, 198, 198, 6738, 334, 72, 13, 33571, 1330, 21136, 62, 12947, 62, 43420, 628, 198, 47084, 51, 29514, 62, 13252, 2394, 796, 28686, 13, ...
2.811765
85
""" Copyright (C) 2021 Clariteia SL This file is part of minos framework. Minos framework can not be copied and/or distributed without the express permission of Clariteia SL. """ from typing import ( Any, Type, )
[ 37811, 198, 15269, 357, 34, 8, 33448, 15420, 578, 544, 12419, 198, 198, 1212, 2393, 318, 636, 286, 949, 418, 9355, 13, 198, 198, 9452, 418, 9355, 460, 407, 307, 18984, 290, 14, 273, 9387, 1231, 262, 4911, 7170, 286, 15420, 578, 544,...
3.141026
78
""" Extensions for pylearn2 training algorithms. Those are either reimplemented to suit the execution model of this package, or new ones for recording metrics. """ import os import cPickle as pkl import numpy as np from pylearn2.train_extensions import TrainExtension from .abcs import Buildable
[ 37811, 198, 11627, 5736, 329, 279, 2349, 1501, 17, 3047, 16113, 13, 5845, 389, 2035, 21123, 1154, 12061, 284, 198, 6063, 262, 9706, 2746, 286, 428, 5301, 11, 393, 649, 3392, 329, 8296, 20731, 13, 198, 37811, 628, 198, 11748, 28686, 19...
3.642857
84
import asyncio from io import BytesIO import logging import os import random import time from typing import List from urllib.parse import urlparse import aiohttp from aiohttp import ClientSession, TCPConnector import requests from requests import Response from tqdm import tqdm from nogi import REQUEST_HEADERS from nogi.db.nogi_blog_content import NogiBlogContent from nogi.db.nogi_blog_summary import NogiBlogSummary from nogi.storages.gcs import GCS from nogi.utils.parsers import PostParser, generate_post_key logger = logging.getLogger() HEADERS = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36' }
[ 11748, 30351, 952, 198, 6738, 33245, 1330, 2750, 4879, 9399, 198, 11748, 18931, 198, 11748, 28686, 198, 11748, 4738, 198, 11748, 640, 198, 6738, 19720, 1330, 7343, 198, 6738, 2956, 297, 571, 13, 29572, 1330, 19016, 29572, 198, 198, 11748,...
3.021459
233
from Jumpscale import j import signal from .. import templates DNSMASQ = "/bin/dnsmasq --conf-file=/etc/dnsmasq.conf -d"
[ 6738, 449, 8142, 38765, 1330, 474, 198, 11748, 6737, 198, 6738, 11485, 1330, 24019, 198, 198, 35, 8035, 31180, 48, 796, 12813, 8800, 14, 67, 5907, 5356, 80, 1377, 10414, 12, 7753, 33223, 14784, 14, 67, 5907, 5356, 80, 13, 10414, 532, ...
2.733333
45
hensu_int = 17 # hensu_float = 1.7 #() hensu_str = "HelloWorld" # hensu_bool = True # hensu_list = [] # hensu_tuple = () # hensu_dict = {} # print(type(hensu_int)) print(type(hensu_float)) print(type(hensu_str)) print(type(hensu_bool)) print(type(hensu_list)) print(type(hensu_tuple)) print(type(hensu_dict))
[ 831, 2385, 62, 600, 796, 1596, 1303, 198, 831, 2385, 62, 22468, 796, 352, 13, 22, 1303, 3419, 198, 831, 2385, 62, 2536, 796, 366, 15496, 10603, 1, 1303, 198, 831, 2385, 62, 30388, 796, 6407, 1303, 198, 831, 2385, 62, 4868, 796, 17...
2.296296
135