content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
# Copyright (c) 2018 Serguei Kalentchouk et al. All rights reserved. # Use of this source code is governed by an MIT license that can be found in the LICENSE file. from node_test_case import NodeTestCase, cmds
[ 2, 15069, 357, 66, 8, 2864, 2930, 18701, 72, 12612, 298, 354, 38960, 2123, 435, 13, 1439, 2489, 10395, 13, 198, 2, 5765, 286, 428, 2723, 2438, 318, 21825, 416, 281, 17168, 5964, 326, 460, 307, 1043, 287, 262, 38559, 24290, 2393, 13,...
3.637931
58
import pytest from models import TodoItem pytestmark = [ pytest.mark.usefixtures("use_db"), ] def test_format_without_strike(items, chat): lines = chat.get_formatted_items().split("\n") assert len(lines) == 2 assert "1. Hello" == lines[0] assert "2. Nice!" == lines[1] def test_format_with_strike(items, chat): items[0].is_checked = True items[0].save() lines = chat.get_formatted_items().split("\n") assert len(lines) == 2 assert "<s>1. Hello</s>" == lines[0] assert "2. Nice!" == lines[1] def test_respect_order_by_id(items, chat): TodoItem.update(id=100500).where(TodoItem.id == items[0].id).execute() lines = chat.get_formatted_items().split("\n") assert len(lines) == 2 assert "1. Nice!" == lines[0] assert "2. Hello" == lines[1] def test_no_items_is_okay(chat): assert chat.get_formatted_items() == ""
[ 11748, 12972, 9288, 198, 198, 6738, 4981, 1330, 309, 24313, 7449, 198, 198, 9078, 9288, 4102, 796, 685, 198, 220, 220, 220, 12972, 9288, 13, 4102, 13, 1904, 69, 25506, 7203, 1904, 62, 9945, 12340, 198, 60, 628, 628, 198, 4299, 1332, ...
2.487465
359
import copy import json from django.contrib import admin from django.db import models from web.multilingual.data_structures import MultiLingualTextStructure from web.multilingual.form import MultiLingualFormField, MultiLingualRichTextFormField, \ MultiLingualRichTextUploadingFormField from web.multilingual.widgets import MultiLingualTextInput, MultiLingualRichText, MultiLingualRichTextUploading
[ 11748, 4866, 198, 11748, 33918, 198, 198, 6738, 42625, 14208, 13, 3642, 822, 1330, 13169, 198, 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 198, 6738, 3992, 13, 16680, 34900, 13, 7890, 62, 7249, 942, 1330, 15237, 43, 278, 723, 8206, ...
3.457627
118
from django.test import TestCase from shop.models import Product from django.contrib.auth.models import User from coupons.forms import CouponForm
[ 6738, 42625, 14208, 13, 9288, 1330, 6208, 20448, 201, 198, 6738, 6128, 13, 27530, 1330, 8721, 201, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 27530, 1330, 11787, 201, 198, 6738, 45972, 13, 23914, 1330, 43156, 261, 8479, 201,...
2.8
60
from __future__ import annotations import asyncio from typing import Any import asynctest.mock # type: ignore import pytest # type: ignore import pytest_mock._util # type: ignore pytest_mock._util._mock_module = asynctest.mock
[ 6738, 11593, 37443, 834, 1330, 37647, 198, 198, 11748, 30351, 952, 198, 6738, 19720, 1330, 4377, 198, 198, 11748, 355, 2047, 310, 395, 13, 76, 735, 220, 1303, 2099, 25, 8856, 198, 11748, 12972, 9288, 220, 1303, 2099, 25, 8856, 198, 11...
3.012658
79
#=============================================================================# # # # MODIFIED: 15-Jan-2019 by C. Purcell # # # #=============================================================================# import cv2 #-----------------------------------------------------------------------------#
[ 2, 23926, 25609, 46249, 198, 2, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, ...
2.088983
236
# -*- coding: utf-8 -*- """ Physical or mathematical constants. Since every code has its own conversion units, this module defines what QE understands as for an eV or other quantities. Whenever possible, we try to use the constants defined in :py:mod:aiida.common.constants:, but if some constants are slightly different among different codes (e.g., different standard definition), we define the constants in this file. """ from aiida.common.constants import ( ang_to_m, bohr_si, bohr_to_ang, hartree_to_ev, invcm_to_THz, ry_si, ry_to_ev, timeau_to_sec, ) # From the definition of Quantum ESPRESSO, conversion from atomic mass # units to Rydberg units: # REAL(DP), PARAMETER :: AMU_SI = 1.660538782E-27_DP ! Kg # REAL(DP), PARAMETER :: ELECTRONMASS_SI = 9.10938215E-31_DP ! Kg # REAL(DP), PARAMETER :: AMU_AU = AMU_SI / ELECTRONMASS_SI # REAL(DP), PARAMETER :: AMU_RY = AMU_AU / 2.0_DP amu_Ry = 911.4442421323
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 31611, 393, 18069, 38491, 13, 220, 198, 6385, 790, 2438, 468, 663, 898, 11315, 4991, 11, 428, 8265, 15738, 644, 198, 48, 36, 14759, 355, 329, 281, 304, 53,...
2.4625
400
# This file is MACHINE GENERATED! Do not edit. # Generated by: tensorflow/python/tools/api/generator/create_python_api.py script. """Public API for tf.keras.applications namespace. """ from __future__ import print_function as _print_function import sys as _sys from keras.api._v2.keras.applications import densenet from keras.api._v2.keras.applications import efficientnet from keras.api._v2.keras.applications import imagenet_utils from keras.api._v2.keras.applications import inception_resnet_v2 from keras.api._v2.keras.applications import inception_v3 from keras.api._v2.keras.applications import mobilenet from keras.api._v2.keras.applications import mobilenet_v2 from keras.api._v2.keras.applications import mobilenet_v3 from keras.api._v2.keras.applications import nasnet from keras.api._v2.keras.applications import resnet from keras.api._v2.keras.applications import resnet50 from keras.api._v2.keras.applications import resnet_v2 from keras.api._v2.keras.applications import vgg16 from keras.api._v2.keras.applications import vgg19 from keras.api._v2.keras.applications import xception from keras.applications.densenet import DenseNet121 from keras.applications.densenet import DenseNet169 from keras.applications.densenet import DenseNet201 from keras.applications.efficientnet import EfficientNetB0 from keras.applications.efficientnet import EfficientNetB1 from keras.applications.efficientnet import EfficientNetB2 from keras.applications.efficientnet import EfficientNetB3 from keras.applications.efficientnet import EfficientNetB4 from keras.applications.efficientnet import EfficientNetB5 from keras.applications.efficientnet import EfficientNetB6 from keras.applications.efficientnet import EfficientNetB7 from keras.applications.inception_resnet_v2 import InceptionResNetV2 from keras.applications.inception_v3 import InceptionV3 from keras.applications.mobilenet import MobileNet from keras.applications.mobilenet_v2 import MobileNetV2 from keras.applications.mobilenet_v3 import MobileNetV3Large from keras.applications.mobilenet_v3 import MobileNetV3Small from keras.applications.nasnet import NASNetLarge from keras.applications.nasnet import NASNetMobile from keras.applications.resnet import ResNet101 from keras.applications.resnet import ResNet152 from keras.applications.resnet import ResNet50 from keras.applications.resnet_v2 import ResNet101V2 from keras.applications.resnet_v2 import ResNet152V2 from keras.applications.resnet_v2 import ResNet50V2 from keras.applications.vgg16 import VGG16 from keras.applications.vgg19 import VGG19 from keras.applications.xception import Xception del _print_function
[ 2, 770, 2393, 318, 337, 16219, 8881, 24700, 1137, 11617, 0, 2141, 407, 4370, 13, 198, 2, 2980, 515, 416, 25, 11192, 273, 11125, 14, 29412, 14, 31391, 14, 15042, 14, 8612, 1352, 14, 17953, 62, 29412, 62, 15042, 13, 9078, 4226, 13, ...
2.951902
894
from flash.vision.embedding.image_embedder_model import ImageEmbedder, ImageEmbedderDataPipeline
[ 6738, 7644, 13, 10178, 13, 20521, 12083, 13, 9060, 62, 20521, 1082, 62, 19849, 1330, 7412, 31567, 276, 1082, 11, 7412, 31567, 276, 1082, 6601, 47, 541, 4470, 198 ]
3.344828
29
import os import sys import logging from configparser import ConfigParser from .open_struct import OpenStruct from .section_struct import SectionStruct # TODO: use file lock when read/write def choose_theirs(section, option, mine, theirs): '''Always prefer values for keys from file.''' return theirs def choose_mine(section, option, mine, theirs): '''Always prefer values for keys in memory.''' return mine LOG_LEVELS = ['debug-all', 'debug', 'info', 'warning', 'error', 'critical'] LOG_OPTIONS = {'log_level': 'info', 'log_file': 'STDERR'}
[ 11748, 28686, 198, 11748, 25064, 198, 11748, 18931, 198, 198, 6738, 4566, 48610, 1330, 17056, 46677, 198, 6738, 764, 9654, 62, 7249, 1330, 4946, 44909, 198, 6738, 764, 5458, 62, 7249, 1330, 7275, 44909, 198, 198, 2, 16926, 46, 25, 779, ...
3.227273
176
import origen # pylint: disable=import-error import pytest, pathlib, os, stat, abc from os import access, W_OK, X_OK, R_OK from tests.shared import clean_falcon, clean_compiler, tmp_dir def user_compiler(): ''' End users should access the compiler via ``origen.app.compiler``. ''' return origen.app.compiler MakoRenderer = origen.compiler.MakoRenderer # JinjaRenderer = origen.compiler.JinjaRenderer def test_render_file(self): ''' Test that the renderer can render a given file ''' rendered = user_compiler().render(self.input_filename, syntax=self.syntax, direct_src=False, output_dir=tmp_dir(), context=self.additional_context) assert isinstance(rendered, pathlib.Path) assert rendered == self.output_filename assert rendered.exists assert open(rendered, 'r').read() == self.expected_dut_info_output def test_render_str(self): ''' Test that the renderer can render a given string ''' rendered = user_compiler().render(self.str_render, syntax=self.syntax, direct_src=True) assert rendered == self.expected_str_render def test_render_with_standard_context(self): ''' Renders output using the standard context ''' rendered = user_compiler().render( self.str_render_with_standard_context, syntax=self.syntax, direct_src=True) assert rendered == self.expected_str_render_with_standard_context def test_render_with_additional_context(self): ''' Renders output using additional context given as an option -> Test that the renderer supports the 'additional_context' option ''' rendered = user_compiler().render( self.str_render_with_additional_context, syntax=self.syntax, direct_src=True, context={'test_renderer_name': self.syntax}) assert rendered == self.expected_str_render_with_additional_context # class TestJinjaCompiler: # pass
[ 11748, 1796, 268, 220, 1303, 279, 2645, 600, 25, 15560, 28, 11748, 12, 18224, 201, 198, 11748, 12972, 9288, 11, 3108, 8019, 11, 28686, 11, 1185, 11, 450, 66, 201, 198, 6738, 28686, 1330, 1895, 11, 370, 62, 11380, 11, 1395, 62, 11380...
2.12099
1,091
from flask import Flask, jsonify, request import predict import socket app = Flask(__name__) #to spedicy route after url if __name__ == '__main__': #for remote host ip = socket.gethostbyname(socket.gethostname()) app.run(port=5000,host=ip) #for local host #app.run(debug=True, port=5000)
[ 6738, 42903, 1330, 46947, 11, 33918, 1958, 11, 2581, 198, 11748, 4331, 198, 11748, 17802, 198, 198, 1324, 796, 46947, 7, 834, 3672, 834, 8, 198, 198, 2, 1462, 40424, 4611, 6339, 706, 19016, 628, 198, 198, 361, 11593, 3672, 834, 6624, ...
2.721739
115
# (c) 2016, Hao Feng <whisperaven@gmail.com> __version__ = '0.1.0'
[ 2, 357, 66, 8, 1584, 11, 367, 5488, 18164, 1279, 1929, 271, 525, 4005, 31, 14816, 13, 785, 29, 198, 198, 834, 9641, 834, 796, 705, 15, 13, 16, 13, 15, 6, 198 ]
2.060606
33
from Dimension_Reduction import Viewer import pandas as pd view_tool = Viewer() reduc = 'pca' suffix = '5' data_plot = pd.read_csv(f"{reduc}_dim2_{suffix}.csv", delimiter=",") models = ['km', 'fuzz', 'gmm', 'dbsc', 'hier', 'spec' ] for model in models: print(model) labels = pd.read_csv(f"labels_{model}_{suffix}.csv", delimiter=",") view_tool.view_vs_target(data_plot, labels, suffix, model)
[ 6738, 34024, 62, 7738, 8110, 1330, 3582, 263, 201, 198, 11748, 19798, 292, 355, 279, 67, 201, 198, 201, 198, 1177, 62, 25981, 796, 3582, 263, 3419, 201, 198, 445, 1229, 796, 705, 79, 6888, 6, 201, 198, 37333, 844, 796, 705, 20, 6,...
2.335196
179
from collections import UserList from dataclasses import dataclass, field from datetime import datetime from typing import List, Dict, Any, Optional, Type DATE_FORMAT = '%Y-%m-%d %H:%M:%S %Z' _link_classes = {'navigation': NavigationLink, 'action': ActionLink} # a type -> class dict POST_CLASSES: Dict[str, Type] = { 'photo': LegacyPhotoPost, 'quote': LegacyQuotePost, 'link': LegacyLinkPost, 'chat': LegacyChatPost, 'audio': LegacyAudioPost, 'video': LegacyVideoPost, 'answer': LegacyAnswerPost, }
[ 6738, 17268, 1330, 11787, 8053, 198, 6738, 4818, 330, 28958, 1330, 4818, 330, 31172, 11, 2214, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 6738, 19720, 1330, 7343, 11, 360, 713, 11, 4377, 11, 32233, 11, 5994, 198, 198, 35, 6158, 62,...
2.618834
223
from jobs_scraper import JobsScraper # Let's create a new JobsScraper object and perform the scraping for a given query. position_var = "Python" scraper = JobsScraper(country="ca", position=position_var, location="Toronto", pages=3) df = scraper.scrape() df.to_csv(rf'{position_var} jobs.csv', index = False)
[ 6738, 3946, 62, 1416, 38545, 1330, 19161, 3351, 38545, 198, 198, 2, 3914, 338, 2251, 257, 649, 19161, 3351, 38545, 2134, 290, 1620, 262, 46743, 329, 257, 1813, 12405, 13, 198, 9150, 62, 7785, 796, 366, 37906, 1, 198, 198, 1416, 38545,...
3.206186
97
import tarfile, sys,os from PyQt4.QtCore import * from PyQt4.QtGui import * app = QApplication(sys.argv) try: zfile = tarfile.open(sys.argv[1], "r:gz" ) zfile.extractall(sys.argv[2]) zfile.close() mb = QMessageBox('Red-R Updated', "Red-R has been updated'", QMessageBox.Information, QMessageBox.Ok | QMessageBox.Default, QMessageBox.NoButton, QMessageBox.NoButton) except: mb = QMessageBox('Red-R Updated', "There was an Error in updating Red-R.\n\n%s" % sys.exc_info()[0], QMessageBox.Information, QMessageBox.Ok | QMessageBox.Default, QMessageBox.NoButton, QMessageBox.NoButton) app.setActiveWindow(mb) mb.setFocus() mb.show() app.exit(0) #mb.exec_() sys.exit(app.exec_()) os.remove(sys.argv[1])
[ 11748, 13422, 7753, 11, 25064, 11, 418, 198, 6738, 9485, 48, 83, 19, 13, 48, 83, 14055, 1330, 1635, 198, 6738, 9485, 48, 83, 19, 13, 48, 83, 8205, 72, 1330, 1635, 198, 1324, 796, 1195, 23416, 7, 17597, 13, 853, 85, 8, 198, 198, ...
2.114883
383
from ctypes import * #from multiprocessing import Process, Queue import queue import time from threading import Lock,Thread from fastapi import FastAPI from fastapi import Request from fastapi import WebSocket, WebSocketDisconnect import uvicorn #from yolo_service import * import socket import random from typing import List import darknet import cv2 import time import io import struct import os import numpy as np import base64 import json from jtracer.tracing import init_tracer import pynng from PIL import Image from opentracing.propagation import Format def convert2relative(bbox,darknet_height,darknet_width): """ YOLO format use relative coordinates for annotation """ x, y, w, h = bbox _height = darknet_height _width = darknet_width return x/_width, y/_height, w/_width, h/_height app = FastAPI() manager = ConnectionManager() if __name__ == "__main__": uvicorn.run("darknet_websocket_demo:app",host="0.0.0.0",port=int(os.getenv("SUPB_SERVICE_PORT")),log_level="info")
[ 6738, 269, 19199, 1330, 1635, 198, 2, 6738, 18540, 305, 919, 278, 1330, 10854, 11, 4670, 518, 198, 11748, 16834, 198, 11748, 640, 198, 6738, 4704, 278, 1330, 13656, 11, 16818, 198, 6738, 3049, 15042, 1330, 12549, 17614, 198, 6738, 3049,...
2.92437
357
import numpy as np from pyqmc.slater import sherman_morrison_row from pyqmc.slater import sherman_morrison_ms if __name__ == "__main__": r_err, inv_err = list(zip(*[run_sherman_morrison() for i in range(2000)])) print(np.amax(r_err)) print(np.amax(inv_err)) counts, bins = np.histogram(np.log10(inv_err), bins=np.arange(-16, 0)) print(np.stack([counts, bins[1:]]))
[ 11748, 299, 32152, 355, 45941, 198, 6738, 12972, 80, 23209, 13, 6649, 729, 1330, 15059, 805, 62, 4491, 7426, 62, 808, 198, 6738, 12972, 80, 23209, 13, 6649, 729, 1330, 15059, 805, 62, 4491, 7426, 62, 907, 628, 628, 628, 198, 361, 11...
2.333333
168
#!/usr/bin/env python3 import sys import socket import time import numpy as np import matplotlib.pyplot as plt HOST = '10.49.234.234' PORT = 2055 if __name__ == '__main__': # Select TR command_select='SELECT 0' rsp=repr(command_to_licel(command_select)) print('Received',rsp) # Clear memory command_clear='MCLEAR' rsp=repr(command_to_licel(command_clear)) print('Received',rsp) # Start TR command_start='MSTART' rsp=repr(command_to_licel(command_start)) print('Received',rsp) time.sleep(5) # Stop TR command_stop='MSTOP' rsp=repr(command_to_licel(command_stop)) print('Received',rsp) # Get data command_data='DATA? 0 4001 LSW A' rsp=command_to_licel(command_data) #print('Received',rsp) # with open('outputlicel', 'w') as f: # f.write(rsp) data_output=rsp # Plot t = np.arange(0, len(data_output), 1) data_arr=[] for data_byte in data_output: data_arr.append(int(data_byte)) fig, ax = plt.subplots() ax.plot(t, data_arr) ax.set(xlabel='time (s)', ylabel='voltage (mV)',title='SMN LICEL') ax.grid() fig.savefig("test.png") plt.show()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 11748, 25064, 198, 11748, 17802, 198, 11748, 640, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 198, 39, 10892, 796, 705, 9...
2.128521
568
# Copyright 2012 Nebula, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import logging import json from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ungettext_lazy from django.conf import settings from horizon import forms from horizon import tables from horizon.utils import filters from openstack_dashboard import api from openstack_dashboard import policy LOG = logging.getLogger(__name__) POLICY_CHECK = getattr(settings, "POLICY_CHECK_FUNCTION", lambda p, r: True) def action(self, request, obj_id): try: user = api.keystone.user_get(request, obj_id) default_user_role = api.keystone.get_default_role(request) default_project_admin_role = api.keystone.get_default_project_admin_role(request) api.keystone.remove_tenant_user_role(request, project=user.default_project_id, user=user.id, role=default_user_role.id) api.keystone.user_update(request, obj_id, **{'default_role_id': default_project_admin_role.id}) api.keystone.add_tenant_user_role(request, project=user.default_project_id, user=user.id, role=default_project_admin_role.id) # operation log config = _('Old role %s, new role %s') % (default_user_role.name, default_project_admin_role.name) api.logger.Logger(request).create(resource_type='account', action_name='Role_Change', resource_name='Account', config=config, status='Success') except Exception: # operation log config = _('Old role %s, new role %s') % (default_user_role.name, default_project_admin_role.name) api.logger.Logger(request).create(resource_type='account', action_name='Role_Change', resource_name='Account', config=config, status='Error') class ChangePasswordLink(policy.PolicyTargetMixin, tables.LinkAction): name = "change_password" verbose_name = _("Change Password") url = "horizon:identity:account:change_password" classes = ("ajax-modal",) icon = "key" policy_rules = (("identity", "identity:change_password"),) policy_target_attrs = (("user_id", "id"),) class UpdateRegionsLink(policy.PolicyTargetMixin, tables.LinkAction): name = "regions" verbose_name = _("Update Regions") url = "horizon:identity:account:regions" classes = ("ajax-modal",) icon = "pencil" policy_rules = (("identity", "identity:update_user_regions"),) class UpdateMembersLink(tables.LinkAction): name = "users" verbose_name = _("Manage Members") url = "horizon:identity:account:update_member" classes = ("ajax-modal",) icon = "pencil" policy_rules = (("identity", "identity:list_users"), ("identity", "identity:list_grants")) STATUS_DISPLAY_CHOICES = ( (False, _("Delete")), (True, _("Normal")), )
[ 2, 15069, 2321, 46915, 11, 3457, 13, 198, 2, 198, 2, 220, 220, 220, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 345, 743, 198, 2, 220, 220, 220, 407, 779, 428, 2393, 2845, 287, 11846, 351, ...
2.407115
1,518
## Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. ## Note: ## The solution set must not contain duplicate triplets. ## Example: ## Given array nums = [-1, 0, 1, 2, -1, -4], ## A solution set is: ## [ ## [-1, 0, 1], ## [-1, -1, 2] ## ]
[ 2235, 11259, 281, 7177, 997, 82, 286, 299, 37014, 11, 389, 612, 4847, 257, 11, 275, 11, 269, 287, 997, 82, 884, 326, 257, 1343, 275, 1343, 269, 796, 657, 30, 9938, 477, 3748, 15055, 912, 287, 262, 7177, 543, 3607, 262, 2160, 286, ...
2.477419
155
from django.db import models from user.models import UserModel
[ 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 6738, 2836, 13, 27530, 1330, 11787, 17633, 628 ]
4
16
import os import click from developers_chamber.git_utils import get_current_branch_name from developers_chamber.gitlab_utils import \ create_merge_request as create_merge_request_func from developers_chamber.scripts import cli DEFAULT_API_URL = os.environ.get('GITLAB_API_URL', 'https://gitlab.com/api/v4') DEFAULT_PROJECT = os.environ.get('GITLAB_PROJECT') DEFAULT_TARGET_BRANCH = os.environ.get('GITLAB_TARGET_BRANCH', 'next') DEFAULT_TOKEN = os.environ.get('GITLAB_TOKEN')
[ 11748, 28686, 198, 198, 11748, 3904, 198, 198, 6738, 6505, 62, 354, 7789, 13, 18300, 62, 26791, 1330, 651, 62, 14421, 62, 1671, 3702, 62, 3672, 198, 6738, 6505, 62, 354, 7789, 13, 18300, 23912, 62, 26791, 1330, 3467, 198, 220, 220, ...
2.664835
182
# Copyright 2021 IBM Corp. # # 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. """ Test base autoinstall machine A smallest implementation on SmBase is used to test common features """ # pylint: disable=invalid-name # we have really long test names # pylint: disable=redefined-outer-name # use of fixtures # pylint: disable=unused-argument # use of fixtures for their side effects # # IMPORTS # from pathlib import Path from tessia.baselib.hypervisors.hmc.volume_descriptor import FcpVolumeDescriptor from tessia.server.config import Config from tessia.server.state_machines.autoinstall import plat_lpar, plat_zvm, plat_kvm from tessia.server.state_machines.autoinstall import plat_base, sm_base from tessia.server.state_machines.autoinstall.model import AutoinstallMachineModel from tessia.server.state_machines.autoinstall.sm_base import SmBase from tests_pytest.decorators import tracked from tests_pytest.state_machines.ssh_stub import SshClient from tests_pytest.state_machines.null_hypervisor import NullHypervisor import pytest import yaml # # CONSTANTS AND DEFINITIONS # CREDS = {'user': 'unit', 'password': 'test'} # # CODE # # wait_install() class NullPostInstallChecker: """ PostInstallChecked that checks that it has been called """ def test_boot_and_postinstall_check_on_lpar_dasd( lpar_dasd_system, default_os_tuple, tmpdir): """ Attempt to install "nothing" on an LPAR on DASD disk Verify that hypervisor is called with correct parameters and post-install checker is run """ model = AutoinstallMachineModel(*default_os_tuple, lpar_dasd_system, CREDS) checker = NullPostInstallChecker() hyp = plat_lpar.PlatLpar.create_hypervisor(model) platform = plat_lpar.PlatLpar(model, hyp) # autoinstall machines use their own working directory # and have to be initialized in a temporary environment with tmpdir.as_cwd(): smbase = NullMachine(model, platform, checker) smbase.start() assert checker.verify.called_once sys, cpus, mem, attrs, *_ = hyp.start.calls[0] assert sys == lpar_dasd_system.hypervisor.boot_options['partition-name'] assert cpus == lpar_dasd_system.cpus assert mem == lpar_dasd_system.memory # installation device does not show up in HmcHypervisor boot, # it is only used later during installation assert attrs['boot_params']['boot_method'] == 'dasd' assert attrs['boot_params']['devicenr'] == \ lpar_dasd_system.hypervisor.boot_options['boot-device'] def test_boot_and_postinstall_check_on_lpar_scsi( lpar_scsi_system, default_os_tuple, tmpdir): """ Attempt to install "nothing" on an LPAR on SCSI disk Verify that hypervisor is called with correct parameters and post-install checker is run """ model = AutoinstallMachineModel(*default_os_tuple, lpar_scsi_system, CREDS) checker = NullPostInstallChecker() hyp = plat_lpar.PlatLpar.create_hypervisor(model) platform = plat_lpar.PlatLpar(model, hyp) # autoinstall machines use their own working directory # and have to be initialized in a temporary environment with tmpdir.as_cwd(): smbase = NullMachine(model, platform, checker) smbase.start() assert checker.verify.called_once sys, cpus, mem, attrs, *_ = hyp.start.calls[0] assert sys == lpar_scsi_system.hypervisor.boot_options['partition-name'] assert cpus == lpar_scsi_system.cpus assert mem == lpar_scsi_system.memory # installation device does not show up in HmcHypervisor boot, # it is only used later during installation assert attrs['boot_params']['boot_method'] == 'dasd' assert attrs['boot_params']['devicenr'] == \ lpar_scsi_system.hypervisor.boot_options['boot-device'] def test_boot_and_postinstall_check_on_vm_dasd( vm_dasd_system, default_os_tuple, tmpdir): """ Attempt to install "nothing" on a VM on DASD disk Verify that hypervisor is called with correct parameters and post-install checker is run """ model = AutoinstallMachineModel(*default_os_tuple, vm_dasd_system, CREDS) checker = NullPostInstallChecker() hyp = plat_zvm.PlatZvm.create_hypervisor(model) platform = plat_zvm.PlatZvm(model, hyp) # autoinstall machines use their own working directory # and have to be initialized in a temporary environment with tmpdir.as_cwd(): smbase = NullMachine(model, platform, checker) smbase.start() assert checker.verify.called_once sys, cpus, mem, attrs, *_ = hyp.start.calls[0] assert sys == vm_dasd_system.system_name assert cpus == vm_dasd_system.cpus assert mem == vm_dasd_system.memory assert vm_dasd_system.volumes[0].device_id == \ attrs['storage_volumes'][0]['devno'] def test_boot_and_postinstall_check_on_vm_scsi( vm_scsi_system, default_os_tuple, tmpdir): """ Attempt to install "nothing" on a VM on SCSI disk Verify that hypervisor is called with correct parameters and post-install checker is run """ model = AutoinstallMachineModel(*default_os_tuple, vm_scsi_system, CREDS) checker = NullPostInstallChecker() hyp = plat_zvm.PlatZvm.create_hypervisor(model) platform = plat_zvm.PlatZvm(model, hyp) # autoinstall machines use their own working directory # and have to be initialized in a temporary environment with tmpdir.as_cwd(): smbase = NullMachine(model, platform, checker) smbase.start() assert checker.verify.called_once sys, cpus, mem, attrs, *_ = hyp.start.calls[0] assert sys == vm_scsi_system.system_name assert cpus == vm_scsi_system.cpus assert mem == vm_scsi_system.memory assert vm_scsi_system.volumes[0].lun == \ attrs['storage_volumes'][0]['lun'] def testboot_and_postinstall_check_on_kvm_scsi( kvm_scsi_system, default_os_tuple, tmpdir): """ Attempt to install "nothing" on a KVM on SCSI disk Verify correct device paths and that hypervisor is called with correct parameters and post-install checker is run """ model = AutoinstallMachineModel(*default_os_tuple, kvm_scsi_system, CREDS) checker = NullPostInstallChecker() hyp = plat_kvm.PlatKvm.create_hypervisor(model) platform = plat_kvm.PlatKvm(model, hyp) # autoinstall machines use their own working directory # and have to be initialized in a temporary environment with tmpdir.as_cwd(): smbase = NullMachine(model, platform, checker) smbase.start() assert checker.verify.called_once sys, cpus, mem, attrs, *_ = hyp.start.calls[0] assert sys == kvm_scsi_system.system_name assert cpus == kvm_scsi_system.cpus assert mem == kvm_scsi_system.memory assert kvm_scsi_system.volumes[0].lun == \ attrs['storage_volumes'][0]['volume_id'] for volume in model.system_profile.volumes: assert '/dev/disk/by-path/ccw' in volume.device_path def test_network_boot_on_lpar_scsi( scsi_volume, osa_iface, default_os_tuple, tmpdir): """ Attempt to install "nothing" on an LPAR on SCSI disk using network boot Verify that hypervisor is called with correct parameters """ ins_file = 'user@password:inst.local/some-os/boot.ins' hmc_hypervisor = AutoinstallMachineModel.HmcHypervisor( 'hmc', 'hmc.local', {'user': '', 'password': ''}, { 'partition-name': 'LP10', 'boot-method': 'network', 'boot-uri': 'ftp://' + ins_file, }) system = AutoinstallMachineModel.SystemProfile( 'lp10', 'default', hypervisor=hmc_hypervisor, hostname='lp10.local', cpus=2, memory=8192, volumes=[scsi_volume], interfaces=[(osa_iface, True)] ) model = AutoinstallMachineModel(*default_os_tuple, system, CREDS) hyp = plat_lpar.PlatLpar.create_hypervisor(model) platform = plat_lpar.PlatLpar(model, hyp) with tmpdir.as_cwd(): smbase = NullMachine(model, platform) smbase.start() sys, cpus, mem, attrs, *_ = hyp.start.calls[0] assert sys == hmc_hypervisor.boot_options['partition-name'] assert cpus == system.cpus assert mem == system.memory assert attrs['boot_params']['boot_method'] == 'ftp' assert attrs['boot_params']['insfile'] == ins_file def test_template_lpar_dasd(lpar_dasd_system, default_os_tuple, tmpdir): """ Test major template parameters """ *os_tuple, _, _ = default_os_tuple package_repo = AutoinstallMachineModel.PackageRepository( 'aux', 'http://example.com/repo', 'package repo') model = AutoinstallMachineModel( *os_tuple, [], [package_repo], lpar_dasd_system, CREDS) hyp = plat_lpar.PlatLpar.create_hypervisor(model) platform = plat_lpar.PlatLpar(model, hyp) with tmpdir.as_cwd(): smbase = NullMachine(model, platform) autofile_path = (Path.cwd() / 'lp10-default') smbase.start() autofile = yaml.safe_load(autofile_path.read_text()) assert autofile['system']['type'] == 'LPAR' assert autofile['system']['hostname'] == 'lp10.local' assert autofile['gw_iface']['type'] == 'OSA' assert autofile['gw_iface']['osname'] == 'enccw0b01' assert autofile['gw_iface']['search_list'] == ['example.com', 'local'] assert autofile['ifaces'][0]['osname'] == 'enccw0b01' assert autofile['volumes'][0]['type'] == 'DASD' assert autofile['volumes'][0]['partitions'] == [ {'fs': 'ext4', 'mp': '/', 'size': '18000M'} ] assert autofile['repos'][0]['name'] == 'os-repo' assert autofile['repos'][1]['name'] == 'aux' def test_template_kvm_scsi(kvm_scsi_system, default_os_tuple, tmpdir): """ Test major template parameters """ model = AutoinstallMachineModel(*default_os_tuple, kvm_scsi_system, CREDS) hyp = plat_kvm.PlatKvm.create_hypervisor(model) platform = plat_kvm.PlatKvm(model, hyp) with tmpdir.as_cwd(): smbase = NullMachine(model, platform) autofile_path = (Path.cwd() / 'kvm54-default') smbase.start() autofile = yaml.safe_load(autofile_path.read_text()) assert autofile['system']['type'] == 'KVM' assert autofile['system']['hostname'] == 'kvm54.local' assert autofile['gw_iface']['type'] == 'MACVTAP' assert autofile['gw_iface']['osname'] == 'eth0' assert autofile['ifaces'][0]['is_gateway']
[ 2, 15069, 33448, 19764, 11421, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 198, 2, 921, 743...
2.514033
4,418
import unittest from os import getcwd from click.testing import CliRunner from openvariant.commands.openvar import cat
[ 11748, 555, 715, 395, 198, 6738, 28686, 1330, 651, 66, 16993, 198, 198, 6738, 3904, 13, 33407, 1330, 1012, 72, 49493, 198, 198, 6738, 1280, 25641, 415, 13, 9503, 1746, 13, 9654, 7785, 1330, 3797, 628 ]
3.388889
36
import torch import torch.nn as nn
[ 11748, 28034, 198, 11748, 28034, 13, 20471, 355, 299, 77, 628, 628 ]
3.166667
12
from camera import Camera if __name__ == '__main__': main()
[ 198, 6738, 4676, 1330, 20432, 628, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 1388, 3419, 198 ]
2.72
25
from calendarApp import shell, models import os if __name__ == "__main__": main()
[ 6738, 11845, 4677, 1330, 7582, 11, 4981, 198, 11748, 28686, 628, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 1388, 3419, 198 ]
2.966667
30
import time import numpy as np import scipy.sparse as sps from gensim.models import Word2Vec from tqdm import tqdm from recommenders.recommender import Recommender from utils.datareader import Datareader from utils.evaluator import Evaluator from utils.post_processing import eurm_to_recommendation_list from recommenders.similarity.s_plus import dot_product if __name__ == '__main__': dr = Datareader(only_load=True, mode='offline', test_num='1', verbose=False) pid = dr.get_test_playlists().transpose()[0] urm = dr.get_urm() urm.data = np.ones(urm.data.shape[0]) ev = Evaluator(datareader=dr) model = W2VRecommender() model.fit(urm, pid) model.compute_model(verbose=True, size=50) model.compute_rating(verbose=True, small=True, top_k=750) ev.evaluate(recommendation_list=eurm_to_recommendation_list(model.eurm, remove_seed=True, datareader=dr), name="W2V", old_mode=False)
[ 11748, 640, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 629, 541, 88, 13, 82, 29572, 355, 599, 82, 198, 6738, 308, 641, 320, 13, 27530, 1330, 9678, 17, 53, 721, 198, 6738, 256, 80, 36020, 1330, 256, 80, 36020, 198, 6738, 4313, ...
2.547684
367
from ._version import __version__ # noqa from .pyesasky import ESASkyWidget # noqa from .catalogue import Catalogue # noqa from .catalogueDescriptor import CatalogueDescriptor # noqa from .cooFrame import CooFrame # noqa from .footprintSet import FootprintSet # noqa from .footprintSetDescriptor import FootprintSetDescriptor # noqa from .HiPS import HiPS # noqa from .imgFormat import ImgFormat # noqa from .jupyter_server import load_jupyter_server_extension # noqa from .metadataDescriptor import MetadataDescriptor # noqa from .metadataType import MetadataType # noqa import json from pathlib import Path HERE = Path(__file__).parent.resolve() with (HERE / "labextension" / "package.json").open() as fid: data = json.load(fid) # Jupyter Extension points
[ 6738, 47540, 9641, 1330, 220, 11593, 9641, 834, 1303, 645, 20402, 198, 6738, 764, 79, 8505, 2093, 88, 1330, 13380, 1921, 2584, 38300, 1303, 645, 20402, 198, 6738, 764, 9246, 30326, 1330, 16758, 5119, 1303, 645, 20402, 198, 6738, 764, 92...
3.130612
245
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author: Jared """ import numpy as np import pandas as pd import myConfig import matplotlib.pyplot as plt from ast import literal_eval from plotter import getTrendPlot1 from matplotlib.pyplot import figure df = pd.read_csv(myConfig.extOutput) dffExt = pd.read_csv(myConfig.featurePathExt) dffExt = dffExt.copy().dropna(axis=0, how='any').reset_index() y_predict_ext = df['yhat_ext'] print('Num dummy crystals: {}'.format(len(y_predict_ext))) print([n for n in dffExt.columns if 'p_' not in n]) s = 'fracCl' dffExt['yhat_ext'] = df['yhat_ext'] ylabel = '$E_{g}$ (eV)' getTrendPlot1(dffExt, y_predict_ext, s, ylabel = ylabel, xlabel = s, title = 'Trend') plt.show() ''' s = 'volume' g = dffExt.groupby('fracCl') for i, group in g: getTrendPlot1(group, y_predict_ext, s, ylabel = ylabel, xlabel = s, title = 'Trend', scatter = False) plt.show() ''' s = 'fracCs' g = dffExt.groupby('fracSn') for i, group in g: getTrendPlot1(group, y_predict_ext, s, ylabel = ylabel, xlabel = s, title = 'Trend', scatter = False) plt.show() ''' print(dffExt[['fracCs', 'fracRb', 'fracK', 'fracNa', 'fracSn' , 'fracGe', 'fracCl', 'fracI', 'fracBr', 'yhat_ext']].head(10)) ''' g = dffExt.groupby([ 'fracCs', 'fracRb', 'fracK', 'fracNa', 'fracSn' , 'fracGe', 'fracCl', 'fracI', 'fracBr']) x = [] y = [] x_all = [] y_all = [] for (gr, gi) in g: labels = ['Cs', 'Rb', 'K', 'Na', 'Sn', 'Ge', 'Cl', 'I', 'Br'] #print(gr) sarr = [] for i, n in enumerate(gr): if i < 6: m = 1 else: m = 3 if n != 0: #if n == 1.0: sarr.append(labels[i] + '$_{' + str(int(4*m*n)) + '}$') #else: #sarr.append(labels[i] + '$_{' + str(4*m*n) + '}$') #print(sarr, gr) x += [''.join(sarr)] y.append(gi['yhat_ext'].mean()) x_all += [''.join(sarr)]*len(gi) y_all += gi['yhat_ext'].tolist() print(len(x_all), len(x)) fig = plt.figure(figsize=(13, 4), dpi=200) #(Atomic 3%, Lattice 10%) #plt.title('Stability Trends') plt.title('Direct Bandgap Trends') #plt.ylabel('$\Delta E_{hull}$ (meV/atom)') plt.ylabel('$E_{g}$ (eV)') plt.xticks(rotation=90) plt.scatter(x, y) #figure(num=None, figsize=(8, 6), dpi=200, facecolor='w', edgecolor='k') plt.savefig('/Users/Jared/Documents/test.png', bbox_inches='tight') plt.show() ''' plt.title('Bandgap Trends (Atomic 5%, Lattice 5%)') plt.ylabel('E$_{g}$ (eV)') plt.xticks(rotation=90) plt.scatter(x_all, y_all) figure(num=None, figsize=(8, 6), dpi=200, facecolor='w', edgecolor='k') '''
[ 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, 31, 9800, 25, 19116, 198, 37811, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, ...
1.857958
1,577
name = input("Enter your name? ") if name == "guna": print("1234567890") elif name == "david": print("0987654321") elif name == "rakulan": print("12345") elif name == "raj": print("1234455667") else: print("No contacts found")
[ 3672, 796, 5128, 7203, 17469, 534, 1438, 30, 366, 8, 628, 198, 361, 1438, 6624, 366, 7145, 64, 1298, 198, 197, 4798, 7203, 10163, 2231, 30924, 3829, 4943, 198, 198, 417, 361, 1438, 6624, 366, 67, 8490, 1298, 198, 197, 4798, 7203, 29...
2.443299
97
from selenium import webdriver from selenium.webdriver.common.keys import Keys import time import emoji import string import csv import os browser = webdriver.Chrome() user = input('Masukkan username akun anda: ') passwo = input('Masukkan password akun anda: ') url = 'https://www.instagram.com' username = user password = passwo mulaiProgram(url, username, password) browser.quit()
[ 6738, 384, 11925, 1505, 1330, 3992, 26230, 201, 198, 6738, 384, 11925, 1505, 13, 12384, 26230, 13, 11321, 13, 13083, 1330, 26363, 201, 198, 11748, 640, 201, 198, 11748, 44805, 201, 198, 11748, 4731, 201, 198, 11748, 269, 21370, 201, 198...
2.670886
158
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 import plotly.graph_objects as go import plotly.express as px import plotly.figure_factory as ff from sklearn.metrics import roc_curve import pandas as pd from joblib import load from app import app column1 = dbc.Col( [ dcc.Markdown( """ ## Process ******** To build this model, two datasets with similar labels were combined to form a dataset with 102,840 observations. I would like to thank the research team behind [this study](https://arxiv.org/pdf/1802.00393.pdf), as they promptly gave me access to their data, which was labeled through Crowdflower. This model builds largely on their work, as well as that of [this previous study](https://aaai.org/ocs/index.php/ICWSM/ICWSM17/paper/view/15665). After gaining access to both datasets, I proceeded to retrieve the corresponding tweet text for all IDs in the second set (as it was not provided) via Twitter's API. This was [the code](https://stackoverflow.com/questions/44581647/retrieving-a-list-of-tweets-using-tweet-id-in-tweepy) I used to retrieve the text, without exceeding the rate limit. """ ), html.Iframe(src='data:text/html;charset=utf-8,%3Cbody%3E%3Cscript%20src%3D%22https%3A%2F%2Fgist.github.com%2Fnchibana%2F20d6d9f8ae62a6cc36b773d37dd7dc70.js%22%3E%3C%2Fscript%3E%3C%2Fbody%3E', style=dict(border=0, padding=40), height=780, width=1000), dcc.Markdown( """ After that, I proceeded to combine the datasets and eliminate all duplicate tweets. I also defined a baseline accuracy score of 56%, which is the percent accuracy the model would achieve if it predicted the majority class for all tweets. Using some of the processes followed by the studies mentioned above, I also continued to preprocess the data by eliminating excess spaces, removing punctuation and retrieving the stem words of terms used in tweets. Next, I used Scikit-learn's [TfidVectorizer](https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.TfidfVectorizer.html) to convert tweet text into a matrix of TF-IDF features, which is a statistic that calculates how important a word is to a document or collection of words. """ ), html.Iframe(src='data:text/html;charset=utf-8,%3Cbody%3E%3Cscript%20src%3D%22https://gist.github.com/nchibana/c15cbc4a1d97af02fa62fff5868bc36e.js%22%3E%3C%2Fscript%3E%3C%2Fbody%3E', style=dict(border=0, padding=40), height=460, width=1000), dcc.Markdown( """ To increase the accuracy of the model, additional features were engineered, such as the number of syllables per word, the total number of characters, the number of words, the number of unique terms, as well as readability and sentiment scores for each tweet. Additionally, the number of mentions, hashtags and links in each tweet were also counted. For this study, images or any other type of media content were not analyzed. """ ), html.Iframe(src='data:text/html;charset=utf-8,%3Cbody%3E%3Cscript%20src%3D%22https%3A%2F%2Fgist.github.com%2Fnchibana%2F5cebfbfa700974edcd9f5fa6e43cc513.js%22%3E%3C%2Fscript%3E%3C%2Fbody%3E', style=dict(border=0, padding=40), height=600, width=1000), dcc.Markdown( """ After testing several models such as Linear SVC, I finally settled on a logistic regression model which I trained on the data and used for the final model and app. I also used grid search to find the optimal parameters for this logistic regression model. Finally, I computed all accuracy scores and proceeded to plot visualizations to help me get a deeper understanding of the model, such as a confusion matrix to visualize misclassified tweets. """ ), html.Iframe(src='data:text/html;charset=utf-8,%3Cbody%3E%3Cscript%20src%3D%22https%3A%2F%2Fgist.github.com%2Fnchibana%2F0cc0c44c9b5a991adbc2690c97023d0c.js%22%3E%3C%2Fscript%3E%3C%2Fbody%3E', style=dict(border=0, padding=40), height=300, width=1000), dcc.Markdown( """ ## Sources ******** 1. Automated Hate Speech Detection and the Problem of Offensive Language Davidson, Thomas and Warmsley, Dana and Macy, Michael and Weber, Ingmar Proceedings of the 11th International AAAI Conference on Web and Social Media p. 512-515. 2017 2. Large Scale Crowdsourcing and Characterization of Twitter Abusive Behavior Founta, Antigoni-Maria and Djouvas, Constantinos and Chatzakou, Despoina and Leontiadis, Ilias and Blackburn, Jeremy and Stringhini, Gianluca and Vakali, Athena and Sirivianos, Michael and Kourtellis, Nicolas 11th International Conference on Web and Social Media, ICWSM 2018 2018 """ ), ], md=12, ) layout = dbc.Row([column1])
[ 11748, 14470, 198, 11748, 14470, 62, 18769, 26418, 62, 5589, 3906, 355, 288, 15630, 198, 11748, 14470, 62, 7295, 62, 5589, 3906, 355, 288, 535, 198, 11748, 14470, 62, 6494, 62, 5589, 3906, 355, 27711, 198, 6738, 14470, 13, 45841, 3976, ...
2.535817
2,094
from katana.sdk.service import get_component from katana.sdk.service import Service
[ 6738, 479, 43777, 13, 21282, 74, 13, 15271, 1330, 651, 62, 42895, 198, 6738, 479, 43777, 13, 21282, 74, 13, 15271, 1330, 4809, 628 ]
3.541667
24
from .base_controller import BaseController from ..helper.utils import render_template from ..helper.constants import STATUS_OK
[ 6738, 764, 8692, 62, 36500, 1330, 7308, 22130, 198, 6738, 11485, 2978, 525, 13, 26791, 1330, 8543, 62, 28243, 198, 6738, 11485, 2978, 525, 13, 9979, 1187, 1330, 15486, 2937, 62, 11380, 628 ]
3.909091
33
# -*- coding: utf-8 -*- # Copyright 2017 GIG Technology NV # # 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. # # @@license_version:1.3@@ import time from google.appengine.api import users from google.appengine.ext import ndb from framework.utils import now from mcfw.rpc import returns, arguments from plugins.rogerthat_api.exceptions import BusinessException from plugins.tff_backend.models.payment import ThreeFoldTransaction, ThreeFoldPendingTransaction from plugins.tff_backend.to.payment import WalletBalanceTO
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 15069, 2177, 402, 3528, 8987, 23973, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 7...
3.622776
281
from django.conf import settings from selenium import webdriver from selenium.webdriver.chrome.options import Options import pytest import os
[ 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 6738, 384, 11925, 1505, 1330, 3992, 26230, 198, 6738, 384, 11925, 1505, 13, 12384, 26230, 13, 46659, 13, 25811, 1330, 18634, 198, 11748, 12972, 9288, 198, 11748, 28686, 628, 628, 628 ]
3.769231
39
# Generated by Django 3.0.3 on 2020-02-05 08:50 from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 513, 13, 15, 13, 18, 319, 12131, 12, 2999, 12, 2713, 8487, 25, 1120, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
2.84375
32
import os, sys import json if __name__ == '__main__': c = Convert() c.apply() # c.mips_gcc_c() # c.mips_objcopy() # c.mips_bin2mem() # config = Config()
[ 11748, 28686, 11, 25064, 198, 11748, 33918, 628, 628, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 269, 796, 38240, 3419, 198, 220, 220, 220, 269, 13, 39014, 3419, 198, 220, 220, 220, 1303, 269, ...
2.056818
88
#!/bin/python3 # Copyright (C) 2021, Michigan State University. # # 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 csv import json import argparse import sys import datetime from dateutil.parser import parse parser = argparse.ArgumentParser(description='Convert JSON to CSV', epilog='P.S. Trust The Plan') parser.add_argument('--format', help='either JSON or CSV', required=True) parser.add_argument('input', help='JSON File, or stdin if not specified', type=argparse.FileType('r', encoding='utf-8'), default=sys.stdin) parser.add_argument('output', help='output to File, or stdout if not specified', type=argparse.FileType('w', encoding='utf-8'), default=sys.stdout) args = parser.parse_args() today = datetime.date.today() if args.format.upper() == 'CSV': process_csv(args.input, args.output) elif args.format.upper() == 'JSON': process_json(args.input, args.output) else: print(f"Error: '{args.format}' is an invalid format, must be CSV or JSON.", end="\n\n") parser.print_help() exit(-1)
[ 2, 48443, 8800, 14, 29412, 18, 198, 198, 2, 15069, 357, 34, 8, 33448, 11, 7055, 1812, 2059, 13, 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...
3.415825
594
import torch from torch import nn import torch.nn.functional as F import torch.optim as optim from preprocess import * from torch.utils.data import Dataset, DataLoader from blazeface import BlazeFace import os import cv2 import numpy as np from matplotlib import pyplot as plt import random import pickle DATA_FOLDER = '../input/deepfake-detection-challenge' TRAIN_SAMPLE_FOLDER = 'train_sample_videos' TEST_FOLDER = 'test_videos' device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") NET = BlazeFace().to(device) NET.load_weights("../input/blazeface.pth") NET.load_anchors("../input/anchors.npy") sequence = 24 # 1 sec of video feature_size = 167 # length of spatial frequency def main(): # prepare_data() ''' stack = read_video(os.path.join(DATA_FOLDER, TRAIN_SAMPLE_FOLDER, 'aagfhgtpmv.mp4')) print(stack.shape) stack = stack.mean(axis=-1) / 255 spects = get_spects(stack) # print(spects.shape) print(spects[0]) plt.plot(spects[0]) plt.xlabel('Spatial Frequency') plt.ylabel('Power Spectrum') plt.show() ''' training_data = read_data() train(training_data) if __name__ == '__main__': main()
[ 11748, 28034, 201, 198, 6738, 28034, 1330, 299, 77, 201, 198, 11748, 28034, 13, 20471, 13, 45124, 355, 376, 201, 198, 11748, 28034, 13, 40085, 355, 6436, 201, 198, 6738, 662, 14681, 1330, 1635, 201, 198, 6738, 28034, 13, 26791, 13, 78...
2.350093
537
# Copyright 2020 Makani Technologies 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. """Plots relating to the estimator.""" from makani.analysis.plot.python import mplot from makani.avionics.common import plc_messages from makani.control import control_types from makani.lib.python import c_helpers from makani.lib.python.h5_utils import numpy_utils from matplotlib.pyplot import plot from matplotlib.pyplot import yticks import numpy as np from scipy import interpolate MFig = mplot.PlotGroup.MFig # pylint: disable=invalid-name _WING_GPS_RECEIVER_HELPER = c_helpers.EnumHelper( 'WingGpsReceiver', control_types) _GROUND_STATION_MODE_HELPER = c_helpers.EnumHelper( 'GroundStationMode', plc_messages) # TODO: Create separate 'simulator' plot group.
[ 2, 15069, 12131, 15841, 3216, 21852, 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, ...
3.225888
394
#!/usr/bin/env python ########################################################################### # This software is graciously provided by HumaRobotics # under the Simplified BSD License on # github: git@www.humarobotics.com:baxter_tasker # HumaRobotics is a trademark of Generation Robots. # www.humarobotics.com # Copyright (c) 2013, Generation Robots. # All rights reserved. # www.generationrobots.com # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS # BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF # THE POSSIBILITY OF SUCH DAMAGE. # # The views and conclusions contained in the software and documentation are # those of the authors and should not be interpreted as representing official # policies, either expressed or implied, of the FreeBSD Project. import rospy from modbus.modbus_wrapper_server import ModbusWrapperServer from std_msgs.msg import Int32MultiArray as HoldingRegister if __name__=="__main__": rospy.init_node("modbus_server") port = 1234 # custom modbus port without requirement of sudo rights # port = 502 # default modbus port if rospy.has_param("~port"): port = rospy.get_param("~port") else: rospy.loginfo("For not using the default port %d, add an arg e.g.: '_port:=1234'",port) # Init modbus server with specific port mws = ModbusWrapperServer(port) # Stop the server if ros is shutdown. This should show that the server is stoppable rospy.on_shutdown(mws.stopServer) # Starts the server in a non blocking call mws.startServer() print "Server started" ############### # Example 1 # write to the Discrete Input mws.setDigitalInput(0,1) # args: address , value. sets address to value # Example 2 # read from clients coil output print "waiting for line 0 to be set to True" result = mws.waitForCoilOutput(0,5) # args: address,timeout in sec. timeout of 0 is infinite. waits until address is true if result: print "got line 0 is True from baxter" else: print "timeout waiting for signal on line 0" ############### # Example 3 # Listen for the writeable modbus registers in any node sub = rospy.Subscriber("modbus_server/read_from_registers",HoldingRegister,callback,queue_size=500) ############### ############### # Example 4 # Publisher to write first 20 modbus registers from any node pub = rospy.Publisher("modbus_server/write_to_registers",HoldingRegister,queue_size=500) rospy.sleep(1) msg = HoldingRegister() msg.data = range(20) msg2 = HoldingRegister() msg2.data = range(20,0,-1) while not rospy.is_shutdown(): pub.publish(msg) rospy.sleep(1) pub.publish(msg2) rospy.sleep(1) ################ rospy.spin() mws.stopServer()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 29113, 29113, 7804, 21017, 220, 198, 2, 770, 3788, 318, 1036, 45289, 2810, 416, 49387, 14350, 23891, 220, 198, 2, 739, 262, 45157, 1431, 347, 10305, 13789, 319, 198, 2, 33084, 25, 1760...
2.964418
1,349
from siptrackdlib import errors from siptrackdlib import log object_registry = ObjectRegistry()
[ 6738, 264, 10257, 39638, 67, 8019, 1330, 8563, 198, 6738, 264, 10257, 39638, 67, 8019, 1330, 2604, 198, 198, 15252, 62, 2301, 4592, 796, 9515, 8081, 4592, 3419, 198 ]
3.344828
29
from GenericAdventuringRequest import GenericAdventuringRequest
[ 6738, 42044, 2782, 1151, 870, 18453, 1330, 42044, 2782, 1151, 870, 18453, 198 ]
4.923077
13
''' myclient1.py - imports mymod.py and check its operation. ''' from mymod import test, countChars, countChars1, countLines, countLines1 text = 'test.txt' file = open(text) print(test(text), test(file)) print(countChars(text), countChars1(file)) print(countLines(text), countLines1(file)) print('\nedited again version')
[ 7061, 6, 198, 1820, 16366, 16, 13, 9078, 532, 17944, 616, 4666, 13, 9078, 290, 2198, 663, 4905, 13, 198, 7061, 6, 198, 6738, 616, 4666, 1330, 1332, 11, 954, 1925, 945, 11, 954, 1925, 945, 16, 11, 954, 43, 1127, 11, 954, 43, 1127...
2.801724
116
from .date import Date from ..response import handleResponse from datetime import datetime
[ 6738, 764, 4475, 1330, 7536, 198, 6738, 11485, 26209, 1330, 5412, 31077, 198, 6738, 4818, 8079, 1330, 4818, 8079, 628 ]
4.6
20
#!/usr/bin/python import sys from pyspark import SparkContext from shutil import rmtree import os.path as path if len(sys.argv) > 1: if path.exists("output"): rmtree("output") sc = SparkContext() localidad = sys.argv[1] localidadRDD = sc.textFile("Gasolineras.csv") localidadRDD = localidadRDD.map(lambda line: line.encode("ascii", "ignore")) localidadRDD = localidadRDD.map(lambda rows: rows.split(",")) localidadRDD = localidadRDD.filter(lambda rows: localidad == rows[5]) localidadRDD = localidadRDD.map(lambda rows: (rows[5], rows[7], rows[8], rows[9],rows[10], rows[11], rows[12], rows[13], rows[14], rows[15], rows[16], rows[17], rows[18], rows[19], rows[20], rows[21], rows[22], rows[23], rows[24])) datosRDD = localidadRDD.map(generar) if datosRDD.isEmpty(): result = sc.parallelize("0") result.saveAsTextFile("output") else: precioRDD = datosRDD.map(lambda rows: ([rows[0], float(rows[5])])) precioRDD = precioRDD.reduceByKey(lambda x,y: x+y) tamRDD = datosRDD.count() mediaTotal = precioRDD.map(lambda rows: ([rows[1], int(tamRDD)])) mediaTotal = mediaTotal.map(lambda calc:(calc[0]/calc[1])) mediaTotal.saveAsTextFile("output/media_localidad_gasolina_95.txt") precioRDD = datosRDD.map(lambda rows: ([rows[0], float(rows[6])])) precioRDD = precioRDD.reduceByKey(lambda x,y: x+y) tamRDD = datosRDD.count() mediaTotal = precioRDD.map(lambda rows: ([rows[1], int(tamRDD)])) mediaTotal = mediaTotal.map(lambda calc:(calc[0]/calc[1])) mediaTotal.saveAsTextFile("output/media_localidad_gasoleo_a.txt") precioRDD = datosRDD.map(lambda rows: ([rows[0], float(rows[7])])) precioRDD = precioRDD.reduceByKey(lambda x,y: x+y) tamRDD = datosRDD.count() mediaTotal = precioRDD.map(lambda rows: ([rows[1], int(tamRDD)])) mediaTotal = mediaTotal.map(lambda calc:(calc[0]/calc[1])) mediaTotal.saveAsTextFile("output/media_localidad_gasoleo_b.txt") precioRDD = datosRDD.map(lambda rows: ([rows[0], float(rows[8])])) precioRDD = precioRDD.reduceByKey(lambda x,y: x+y) tamRDD = datosRDD.count() mediaTotal = precioRDD.map(lambda rows: ([rows[1], int(tamRDD)])) mediaTotal = mediaTotal.map(lambda calc:(calc[0]/calc[1])) mediaTotal.saveAsTextFile("output/media_localidad_bioetanol.txt") precioRDD = datosRDD.map(lambda rows: ([rows[0], float(rows[9])])) precioRDD = precioRDD.reduceByKey(lambda x,y: x+y) tamRDD = datosRDD.count() mediaTotal = precioRDD.map(lambda rows: ([rows[1], int(tamRDD)])) mediaTotal = mediaTotal.map(lambda calc:(calc[0]/calc[1])) mediaTotal.saveAsTextFile("output/media_localidad_nuevo_gasoleo_a.txt") precioRDD = datosRDD.map(lambda rows: ([rows[0], float(rows[10])])) precioRDD = precioRDD.reduceByKey(lambda x,y: x+y) tamRDD = datosRDD.count() mediaTotal = precioRDD.map(lambda rows: ([rows[1], int(tamRDD)])) mediaTotal = mediaTotal.map(lambda calc:(calc[0]/calc[1])) mediaTotal.saveAsTextFile("output/media_localidad_biodiesel.txt") precioRDD = datosRDD.map(lambda rows: ([rows[0], float(rows[11])])) precioRDD = precioRDD.reduceByKey(lambda x,y: x+y) tamRDD = datosRDD.count() mediaTotal = precioRDD.map(lambda rows: ([rows[1], int(tamRDD)])) mediaTotal = mediaTotal.map(lambda calc:(calc[0]/calc[1])) mediaTotal.saveAsTextFile("output/media_localidad_ester_metilico.txt") precioRDD = datosRDD.map(lambda rows: ([rows[0], float(rows[12])])) precioRDD = precioRDD.reduceByKey(lambda x,y: x+y) tamRDD = datosRDD.count() mediaTotal = precioRDD.map(lambda rows: ([rows[1], int(tamRDD)])) mediaTotal = mediaTotal.map(lambda calc:(calc[0]/calc[1])) mediaTotal.saveAsTextFile("output/media_localidad_bioalcohol.txt") precioRDD = datosRDD.map(lambda rows: ([rows[0], float(rows[13])])) precioRDD = precioRDD.reduceByKey(lambda x,y: x+y) tamRDD = datosRDD.count() mediaTotal = precioRDD.map(lambda rows: ([rows[1], int(tamRDD)])) mediaTotal = mediaTotal.map(lambda calc:(calc[0]/calc[1])) mediaTotal.saveAsTextFile("output/media_localidad_gasolina_98.txt") precioRDD = datosRDD.map(lambda rows: ([rows[0], float(rows[14])])) precioRDD = precioRDD.reduceByKey(lambda x,y: x+y) tamRDD = datosRDD.count() mediaTotal = precioRDD.map(lambda rows: ([rows[1], int(tamRDD)])) mediaTotal = mediaTotal.map(lambda calc:(calc[0]/calc[1])) mediaTotal.saveAsTextFile("output/media_localidad_gas_natural_comprimido.txt") precioRDD = datosRDD.map(lambda rows: ([rows[0], float(rows[15])])) precioRDD = precioRDD.reduceByKey(lambda x,y: x+y) tamRDD = datosRDD.count() mediaTotal = precioRDD.map(lambda rows: ([rows[1], int(tamRDD)])) mediaTotal = mediaTotal.map(lambda calc:(calc[0]/calc[1])) mediaTotal.saveAsTextFile("output/media_localidad_gas_natural_licuado.txt") precioRDD = datosRDD.map(lambda rows: ([rows[0], float(rows[16])])) precioRDD = precioRDD.reduceByKey(lambda x,y: x+y) tamRDD = datosRDD.count() mediaTotal = precioRDD.map(lambda rows: ([rows[1], int(tamRDD)])) mediaTotal = mediaTotal.map(lambda calc:(calc[0]/calc[1])) mediaTotal.saveAsTextFile("output/media_localidad_gas_licuados_del_petr.txt") else: print "Error no ha introducido localidad."
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 198, 11748, 25064, 198, 6738, 279, 893, 20928, 1330, 17732, 21947, 198, 6738, 4423, 346, 1330, 374, 16762, 631, 198, 11748, 28686, 13, 6978, 355, 3108, 198, 198, 361, 18896, 7, 17597, 13, 853...
2.170591
2,591
from django.contrib.auth.decorators import login_required from django.core.exceptions import ObjectDoesNotExist from django.core.urlresolvers import reverse, reverse_lazy from django.http import HttpResponseRedirect from django.shortcuts import render,HttpResponse from django.views.generic.edit import CreateView, UpdateView, DeleteView import csv, json from datetime import date,datetime from itertools import chain from operator import attrgetter from forms.models import Questionnaire from forms.views import replicate from core.models import * from core.forms import * from .nomi_cr import get_access_and_post_for_result, get_access_and_post ''' mark_as_interviewed, reject_nomination, accept_nomination: Changes the interview status/ nomination_instance status of the applicant ''' ''' append_user, replace_user: Adds and Removes the current post-holders according to their selection status ''' ## ------------------------------------------------------------------------------------------------------------------ ## ############################################ PROFILE VIEWS ################################################## ## ------------------------------------------------------------------------------------------------------------------ ## def UserProfileUpdate(request,pk): profile = UserProfile.objects.get(pk = pk) if profile.user == request.user: form = ProfileForm(request.POST or None, instance=profile) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('profile')) return render(request, 'nomi/userprofile_form.html', context={'form': form}) else: return render(request, 'no_access.html') class CommentUpdate(UpdateView): model = Commment fields = ['comments'] class CommentDelete(DeleteView): model = Commment def all_nominations(request): all_nomi = Nomination.objects.all().exclude(status='Nomination created') return render(request, 'all_nominations.html', context={'all_nomi': all_nomi})
[ 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 12501, 273, 2024, 1330, 17594, 62, 35827, 198, 6738, 42625, 14208, 13, 7295, 13, 1069, 11755, 1330, 9515, 13921, 3673, 3109, 396, 198, 6738, 42625, 14208, 13, 7295, 13, 6371, 411, 349, ...
3.526405
587
#!/usr/bin/env python3 import logging import os import pickle import time from os.path import join as pjoin import matplotlib.pyplot as plt import numpy as np import scipy from matplotlib import rc from scipy.optimize import least_squares import asymptotic_formulae from asymptotic_formulae import GaussZ0 from asymptotic_formulae import GaussZ0_MC from asymptotic_formulae import nCRZ0 from asymptotic_formulae import nCRZ0_MC from asymptotic_formulae import nSRZ0 from asymptotic_formulae import nSRZ0_MC rc('font', **{'family': 'sans-serif','sans-serif': ['Helvetica']}) rc('text', usetex = True) logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) sh = logging.StreamHandler() sh.setFormatter(logging.Formatter('%(asctime)s : %(name)s : %(levelname)s : %(message)s')) logger.addHandler(sh) # For creating a set of uniformly-spaced points on a log scale # As described in Section 2.1.4 def nCRZ0_DiagTau(s, b, tau): ''' Calculate the asymptotic significance for a 1 SR + N CRs, diagonal tau measurement s := expected signal yield in SR (float) b := expected background yields in SR (vector of floats, size N) tau := transfer coefficients, tau[i] carries background i yield in SR to CR i (vector of floats, size N) Returns Z0 (float) ''' # Argument checking b, tau = np.array(b), np.array(tau) s, b, tau = float(s), b.astype(float), tau.astype(float) assert b.ndim == 1 # b should be a vector assert tau.ndim == 1 # tau should be a vector assert len(b) == len(tau) assert (tau >= 0.).all() # Assert tau contains transfer factors (i.e., all positive) n = s + np.sum(b) # System of equations # Perform our minimization res = least_squares(func, x0 = b, bounds = [tuple(len(b) * [0.]), tuple(len(b) * [np.inf])]) if not res.success: raise RuntimeError('Minimization failed: status = %s, message = \'%s\'' % (res.status, res.message)) bhh = np.array(res.x) # Calculate our significance Z0 = np.sqrt(-2. * np.log((np.sum(bhh) / n) ** n * np.prod([(bhh[k] / b[k]) ** (tau[k] * b[k]) for k in range(len(b))]))) return Z0 # As described in Section 2.4.2 def GaussZ0_Decorr(s, b, sigma): ''' Calculate the asymptotic significance for a 1 SR + N CRs, diagonal tau measurement s := expected signal yield in SR (float) b := expected background yields in SR (vector of floats, size N) sigma := width of Gaussian constraint ("absolute uncertainty") for each background yield (vector of floats, size N) Returns Z0 (float) ''' # Argument checking b, sigma = np.array(b), np.array(sigma) s, b, sigma = float(s), b.astype(float), sigma.astype(float) assert b.ndim == 1 # b should be a vector assert sigma.ndim == 1 # sigma should be a vector assert len(b) == len(sigma) assert (sigma >= 0.).all() # Assert sigma contains widths (i.e., all positive) n = s + np.sum(b) # System of equations # Perform our minimization res = least_squares(func, x0 = b, bounds = [tuple(len(b) * [0.]), tuple(len(b) * [np.inf])]) if not res.success: raise RuntimeError('Minimization failed: status = %s, message = \'%s\'' % (res.status, res.message)) bhh = np.array(res.x) # Calculate our significance Z0 = np.sqrt(-2. * (n * np.log(np.sum(bhh) / n) + n - np.sum(bhh + 0.5 * ((b - bhh) / sigma) ** 2))) return Z0 if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 11748, 18931, 198, 11748, 28686, 198, 11748, 2298, 293, 198, 11748, 640, 198, 6738, 28686, 13, 6978, 1330, 4654, 355, 279, 22179, 198, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487,...
2.528384
1,374
import pytest from pxtrade.assets import reset, Stock, Portfolio from pxtrade.compliance import ( Compliance, UnitLimit, WeightLimit, )
[ 11748, 12972, 9288, 198, 6738, 279, 742, 27585, 13, 19668, 1330, 13259, 11, 10500, 11, 4347, 13652, 198, 6738, 279, 742, 27585, 13, 47587, 1330, 357, 198, 220, 220, 220, 40536, 11, 198, 220, 220, 220, 11801, 39184, 11, 198, 220, 220, ...
3.040816
49
from article.serializers.serializers import ( ArticleListSerializer, ArticleDetailSerializer )
[ 6738, 2708, 13, 46911, 11341, 13, 46911, 11341, 1330, 357, 198, 220, 220, 220, 10172, 8053, 32634, 7509, 11, 198, 220, 220, 220, 10172, 11242, 603, 32634, 7509, 198, 8, 198 ]
3.322581
31
# set up the environment by reading in libraries: # os... graphics... data manipulation... time... math... statistics... import sys import os from urllib.request import urlretrieve import matplotlib as mpl import matplotlib.pyplot as plt import PIL as pil from IPython.display import Image import pandas as pd from pandas import DataFrame, Series import pandas_datareader from datetime import datetime import scipy as sp import numpy as np import math import random import seaborn as sns import statsmodels import statsmodels.api as sm import statsmodels.formula.api as smf # graphics setup: seaborn-darkgrid and figure size... plt.style.use('seaborn-darkgrid') figure_size = plt.rcParams["figure.figsize"] figure_size[0] = 7 figure_size[1] = 7 plt.rcParams["figure.figsize"] = figure_size # import delong functions from delong_functions.data_functions import getdata_read_or_download # get or download data file from delong_functions.stat_functions import initialize_basic_figure # initialize graphics from delong_functions.data_functions import data_FREDseries # construct a useful dict with source # and notes info from a previously # downloaded FRED csv file # check to see if functions successfully created... # NOW COMMENTED OUT: getdata_read_or_download? initialize_basic_figure?
[ 2, 900, 510, 262, 2858, 416, 3555, 287, 12782, 25, 220, 198, 2, 28686, 986, 9382, 986, 1366, 17512, 986, 640, 986, 10688, 986, 7869, 986, 198, 198, 11748, 25064, 198, 11748, 28686, 198, 6738, 2956, 297, 571, 13, 25927, 1330, 19016, ...
2.750951
526
# # Bentobox # SDK - Graph # Graph Value # from typing import Any from bento.value import wrap from bento.protos.graph_pb2 import Node def wrap_const(val: Any): """Wrap the given native value as a Constant graph node. If val is a Constant node, returns value as is. Args: val: Native value to wrap. Returns: The given value wrapped as a constant graph node. """ # check if already constant node, return as is if true. if isinstance(val, Node) and val.WhichOneof("op") == "const_op": return val return Node(const_op=Node.Const(held_value=wrap(val)))
[ 2, 198, 2, 20421, 672, 1140, 198, 2, 26144, 532, 29681, 198, 2, 29681, 11052, 198, 2, 198, 198, 6738, 19720, 1330, 4377, 198, 6738, 17157, 78, 13, 8367, 1330, 14441, 198, 6738, 17157, 78, 13, 11235, 418, 13, 34960, 62, 40842, 17, ...
2.788991
218
from marshmallow import Schema, fields from marshmallow.validate import Length, Range
[ 6738, 22397, 42725, 1330, 10011, 2611, 11, 7032, 198, 6738, 22397, 42725, 13, 12102, 378, 1330, 22313, 11, 13667 ]
4.473684
19
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. import os import sys import numpy as np from joblib import Parallel, delayed import joblib import argparse import importlib from itertools import product import collections from copy import deepcopy from mcpy.utils import filesafe from mcpy import plotting def check_valid_config(config): """ Performs a basic check of the config file, checking if the necessary subsections are present. If multiple config files are being made that use the same dgps and/or methods, it may be helpful to tailor the config check to those dgps and methods. That way, one can check that the correct parameters are being provided for those dgps and methods. This is specific to one's implementation, however. """ assert 'type' in config, "config dict must specify config type" assert 'dgps' in config, "config dict must contain dgps" assert 'dgp_opts' in config, "config dict must contain dgp_opts" assert 'method_opts' in config, "config dict must contain method_opts" assert 'mc_opts' in config, "config dict must contain mc_opts" assert 'metrics' in config, "config dict must contain metrics" assert 'methods' in config, "config dict must contain methods" assert 'plots' in config, "config dict must contain plots" assert 'single_summary_metrics' in config, "config dict must specify which metrics are plotted in a y-x plot vs. as a single value per dgp and method" assert 'target_dir' in config, "config must contain target_dir" assert 'reload_results' in config, "config must contain reload_results" assert 'n_experiments' in config['mc_opts'], "config[mc_opts] must contain n_experiments" assert 'seed' in config['mc_opts'], "config[mc_opts] must contain seed"
[ 2, 15069, 357, 66, 8, 5413, 10501, 13, 1439, 2489, 10395, 13, 198, 2, 49962, 739, 262, 17168, 13789, 13, 198, 198, 11748, 28686, 198, 11748, 25064, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 1693, 8019, 1330, 42945, 11, 11038, 198...
3.39777
538
#------------------------------------------------------------------------------------------------------ # File Name: MusicGame.py # Author: Kyle Parrish # Date: 7/4/2014 # Description: This is a simple program that I wrote for the raspberry pi so that my daughter can # play with. It is a simple program that plays a different sound with every keystroke. It also # displays a simple shape pattern on the screen with each keypress. The pi can also be setup to # allow users to change the sounds by uploading them to a web form on the pi itself. This code # will be included when it is finished. # Change log: # 4.30.15 - Updated the header to test out Visual Studio Code git integration # 9.18.15 - Started making some changes to the application. Natalie is starting to enjoy # the application so I'm starting to make it do more: # - Updated the code to put circles as well as squares on the screen. #------------------------------------------------------------------------------------------------------ # Basic imports for the game import os,sys,datetime, sqlite3 import pygame # I don't believe that I need the time references anymore, to be removed with next commit #from time import strftime, localtime from random import randint from pygame.locals import * # Setup basic constants test = 640 # Screen height and width SCREEN_WIDTH = test SCREEN_HEIGHT = 480 #CENTER_POINT = (SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2) #LOWER_CENTER = (SCREEN_WIDTH / 2, SCREEN_HEIGHT / 4) #CENTER_RECT_HEIGHT = 40 #CLOCK_TEXT_FONT = 48 # Colors, any of these can be used in the program WHITE = (255, 255, 255) BLACK = (0, 0, 0) RED = (255, 0, 0) GREEN = (0, 255, 0) BLUE = (0, 0, 255) MATRIX_GREEN = (0, 255, 21) # Code taken from: http://code.activestate.com/recipes/521884-play-sound-files-with-pygame-in-a-cross-platform-m/ # global constants FREQ = 44100 # same as audio CD BITSIZE = -16 # unsigned 16 bit CHANNELS = 2 # 1 == mono, 2 == stereo BUFFER = 1024 # audio buffer size in no. of samples FRAMERATE = 30 # how often to check if playback has finished sounds = ["Typewrit-Intermed-538_hifi.ogg", "Typewrit-Bell-Patrick-8344_hifi.ogg", "Arcade_S-wwwbeat-8528_hifi.ogg", "Arcade_S-wwwbeat-8529_hifi.ogg", "Arcade_S-wwwbeat-8530_hifi.ogg", "Arcade_S-wwwbeat-8531_hifi.ogg", "PowerUp-Mark_E_B-8070_hifi.ogg", "PulseGun-Mark_E_B-7843_hifi.ogg", "PulseSho-Mark_E_B-8071_hifi.ogg", "SineySpa-Mark_E_B-7844_hifi.ogg", "ToySpace-Mark_E_B-7846_hifi.ogg", "ZipUp-Mark_E_B-8079_hifi.ogg"] soundFiles = [] def playsound(soundfile): """Play sound through default mixer channel in blocking manner. This will load the whole sound into memory before playback """ soundfile.play() #sound = pygame.mixer.Sound(soundfile) #clock = pygame.time.Clock() #sound.play() #while pygame.mixer.get_busy(): #clock.tick(FRAMERATE) if __name__ == '__main__': main()
[ 2, 10097, 3880, 23031, 198, 2, 9220, 6530, 25, 220, 220, 220, 7849, 8777, 13, 9078, 198, 2, 6434, 25, 220, 220, 220, 220, 220, 220, 14316, 2547, 37518, 198, 2, 7536, 25, 220, 220, 220, 220, 220, 220, 220, 220, 767, 14, 19, 14, ...
2.659776
1,161
from __future__ import print_function from robin.utils import img_processing_utils import numpy as np
[ 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 198, 6738, 3857, 259, 13, 26791, 1330, 33705, 62, 36948, 62, 26791, 198, 11748, 299, 32152, 355, 45941, 628 ]
3.714286
28
#4) ##########KEYWORD############### ################################ # . # .. # (Feed Forward NN) . # . # () . # Layer . # . # . # 2 400% 10% . # . # 0 9 10 3 . # 3 . . #25 P35 # #Layer Node Node Shape Weight Shape Bias Shape # 2 2 2 X 3 Matrix 3 Vector (1) = ((*1) + 1) #(1) 3 3 3 X 2 Matrix 2 Vector (2) = ((1) * 2 + 2) #(2) 2 2 2 X 2 Matrix 2 Vector = ((2) * 3 + 3) # 2 2 # 3 . # 2 . 2 2. # #w12^(1), a2(1) . (1) 1 . # 12 1 2 . w12^(!) 1 2 1 # . # 3 2 1 1 . # a1(1) ... . #a1(1) = w11^(1)x1 + w12^(1)x2 + b1^(1) . # 1 A^(1) = (a1^(1),a2^(1),a3^(1)), 1 #W^(1) ... # numpy 1 . # 1 2 (1 ), , # 2 . # 1 1 2 2 2 # 2 . # 30 2 # . . # . # . # , . # . f(x) = x . # # . # . # . # 1 . # 0 1 #1 . # . # #y[0] = 0.018, y[1] = 0.245, y[2] = 0.737 1.8% 0 , 24.5% 1 , 73.7% 2 # 2 2 . . # () . \ # exp() . # . # ( ) # . . # . (Overflow) . # 100 exp(100) 10 40 . . # . [ 13] P40 # C . . # x = a ^ log(a,x) C exp() . # C exp() log(e,C) = ln C ln C C` . # import numpy as np a = np.array([1010,1000,990]) np.exp(a) / np.sum(np.exp(a)) # # softmax c = np.max(a) np.exp(a-c) / np.sum(np.exp(a-c)) # # . # . # . . # , 2 . # 2 ( . 3 ) # . # . # 2 . import numpy as np # #identify function # . . # . , # 3 network = init_network() # x = np.array([1.0,0.5]) y = forward(network ,x) print(y) # . # .
[ 2, 19, 8, 220, 220, 198, 198, 7804, 2235, 20373, 54, 12532, 7804, 4242, 21017, 628, 628, 198, 198, 29113, 628, 198, 2, 220, 220, 220, 220, 220, 764, 220, 220, 220, 220, 220, 220, 198, 2, 220, 220, 220, 220, 220, 220, 220, 11485,...
1.370629
1,573
import os import pandas as pd dictt = {} i = 0 for label in ['down', 'up', 'left', 'right']: img_lst = os.listdir("./data/img_data/" + label + "/") temp_label = [0] * 4 temp_label[i] = 1 for img in img_lst: print(label + " " + img) dictt[img] = temp_label i += 1 label_df = pd.DataFrame(data=dictt, index=['down', 'up', 'left', 'right']).transpose() label_df = label_df.sample(frac=1) label_df.to_csv("./data/label_data.csv")
[ 11748, 28686, 198, 198, 11748, 19798, 292, 355, 279, 67, 198, 198, 11600, 83, 796, 23884, 198, 72, 796, 657, 198, 198, 1640, 6167, 287, 37250, 2902, 3256, 705, 929, 3256, 705, 9464, 3256, 705, 3506, 6, 5974, 198, 220, 220, 220, 3370...
2.187793
213
''' Created on Jun 27, 2017 @author: lawrencezeng ''' import unittest from rubiks_race import solver if __name__ == "__main__": #import sys;sys.argv = ['', 'Test.test_solve'] unittest.main()
[ 7061, 6, 198, 41972, 319, 7653, 2681, 11, 2177, 198, 198, 31, 9800, 25, 1099, 6784, 89, 1516, 198, 7061, 6, 198, 11748, 555, 715, 395, 198, 6738, 6437, 72, 591, 62, 16740, 1330, 1540, 332, 198, 220, 220, 220, 220, 220, 220, 220, ...
2.265957
94
# -*- coding: utf-8 -*- from __future__ import unicode_literals from modeltranslation import settings as mt_settings from modeltranslation.utils import build_localized_fieldname, get_translation_fields from django.db import migrations, models
[ 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, 953, 2120, 26084, 7592, 1330, 6460, 355, 45079, 62, 33692, 198, 6738, 953, 2120, 26084, 7592, ...
3.416667
72
#!/usr/bin/env python # Copyright 2016-2021 Biomedical Imaging Group Rotterdam, Departments of # Medical Informatics and Radiology, Erasmus MC, Rotterdam, The Netherlands # # 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 os import yaml import fastr import graphviz import configparser from pathlib import Path from random import randint import WORC.IOparser.file_io as io from fastr.api import ResourceLimit from WORC.tools.Slicer import Slicer from WORC.tools.Elastix import Elastix from WORC.tools.Evaluate import Evaluate import WORC.addexceptions as WORCexceptions import WORC.IOparser.config_WORC as config_io from WORC.detectors.detectors import DebugDetector from WORC.export.hyper_params_exporter import export_hyper_params_to_latex from urllib.parse import urlparse from urllib.request import url2pathname
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 2, 15069, 1584, 12, 1238, 2481, 8436, 35914, 48656, 4912, 18481, 353, 11043, 11, 2129, 32514, 286, 198, 2, 8366, 554, 18982, 873, 290, 5325, 12371, 11, 5256, 8597, 385, 13122, 11,...
3.488127
379
import argparse import json import re if __name__ == "__main__": parser = argparse.ArgumentParser(description = 'JSON tweet converter', epilog = 'lol tw33tz', add_help = 'How to use', prog = 'python json_to_txt.py <options>') # Required arguments. parser.add_argument("-i", "--input", required = True, help = "JSON file to convert.") # Optional arguments. parser.add_argument("-o", "--output", default = "output.txt", help = "Output file containing tweet content, one per line. [DEFAULT: output.txt]") # Parse out the arguments. args = vars(parser.parse_args()) content = json.load(open(args['input'], "r")) fp = open(args['output'], "w") item = 0 for obj in content: tweet = obj['tweet']['full_text'] # STEP 1: Strip out RT. tweet = remove_rt(tweet) # STEP 2: Remove URLs, mentions, hashtags, emojis. tweet = remove_urls(tweet) tweet = remove_mentions(tweet) tweet = remove_hashtags(tweet) tweet = remove_emojis(tweet) # STEP 3: Other random fixes. tweet = tweet.strip() tweet = fix_amp(tweet) if len(tweet) == 0 or len(tweet) == 1: continue tweet = tweet.replace("\"\"", "") if tweet[0] == ":": tweet = tweet[1:] tweet = tweet.replace("\n", " ") tweet = tweet.strip() # Write out! fp.write(f"{tweet}\n") item += 1 if item % 1000 == 0: print(f"{item} of {len(content)} done.") fp.close() print(f"{item} tweets processed!")
[ 11748, 1822, 29572, 198, 11748, 33918, 198, 11748, 302, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 30751, 796, 1822, 29572, 13, 28100, 1713, 46677, 7, 11213, 796, 705, 40386, 6126, 38394, 3256...
2.29
700
# Generated by Django 2.2.5 on 2019-10-26 20:20 from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 362, 13, 17, 13, 20, 319, 13130, 12, 940, 12, 2075, 1160, 25, 1238, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
2.84375
32
# -*- coding: utf-8 -*- # # Copyright (c) 2020 CPV.BY # # For suggestions and questions: # <7664330@gmail.com> # # LICENSE: Commercial import webbrowser from kivymd.theming import ThemableBehavior from kivymd.uix.screen import MDScreen
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 2, 15069, 357, 66, 8, 12131, 16932, 53, 13, 17513, 198, 2, 198, 2, 1114, 11776, 290, 2683, 25, 198, 2, 1279, 4304, 2414, 26073, 31, 14816, 13, 785, 29, 198...
2.704545
88
import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt from gym import Env from scipy.spatial import distance from typing import Optional, Tuple, Any from causal_rl.environments import CausalEnv
[ 11748, 299, 32152, 355, 45941, 198, 11748, 2603, 29487, 8019, 355, 285, 489, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 198, 6738, 11550, 1330, 2039, 85, 198, 6738, 629, 541, 88, 13, 2777, 34961, 1330, 5253, 19...
3.283582
67
from flask import Flask app = Flask(__name__) if __name__ == "__main__": app.run(port=5000)
[ 6738, 42903, 1330, 46947, 198, 1324, 796, 46947, 7, 834, 3672, 834, 8, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 598, 13, 5143, 7, 634, 28, 27641, 8, 198 ]
2.552632
38
#!/usr/bin/env python3 import pandas as pd import sys import json from Bio import SeqIO sample_name=sys.argv[1] pango=pd.read_csv('pango.csv') nextclade=pd.read_csv('nextclade.tsv', sep='\t') aln2type=pd.read_csv('aln2type.csv') pango['sampleName']=sample_name nextclade['sampleName']=sample_name aln2type['sampleName']=sample_name df=pango.merge(nextclade, on='sampleName', how='left', suffixes=("_pango","_nextclade")) df=df.merge(aln2type, on='sampleName', how='left', suffixes=(None,"_aln2type")) # versions wf=open('workflow_commit.txt').read() df['workflowCommit']=str(wf).strip() df['manifestVersion']=sys.argv[2] nextclade_version=open('nextclade_files/version.txt').read() df['nextcladeVersion']=str(nextclade_version).strip() aln2type_variant_commit=open('variant_definitions/aln2type_variant_git_commit.txt').read() aln2type_variant_version=open('variant_definitions/aln2type_variant_version.txt').read() aln2type_source_commit=open('variant_definitions/aln2type_commit.txt').read() df['aln2typeVariantCommit']=str(aln2type_variant_commit).strip() df['aln2typeVariantVersion']=str(aln2type_variant_version).strip() df['aln2typeSourceVommit']=str(aln2type_source_commit).strip() df.to_csv('{0}_report.tsv'.format(sys.argv[1]), sep='\t', index=False) ### convert to json pango['program']='pango' pango.set_index('program',inplace=True) p=pango.to_dict(orient='index') nextclade['program']='nextclade' nextclade['nextcladeVersion']=str(nextclade_version).strip() nextclade.set_index('program',inplace=True) n=nextclade.to_dict(orient='index') with open('nextclade.json','rt', encoding= 'utf-8') as inf: nj=json.load(inf) n['nextcladeOutputJson']=nj aln2type['program']='aln2type' aln2type['label']=aln2type['phe-label'] aln2type['aln2typeVariantCommit']=str(aln2type_variant_commit).strip() aln2type['aln2typeSourceCommit']=str(aln2type_source_commit).strip() aln2type.set_index(['program','phe-label'],inplace=True) a={level: aln2type.xs(level).to_dict('index') for level in aln2type.index.levels[0]} w={'WorkflowInformation':{}} w['WorkflowInformation']['workflowCommit']=str(wf).strip() w['WorkflowInformation']['manifestVersion']=sys.argv[2] w['WorkflowInformation']['sampleIdentifier']=sample_name # add fasta to json record = SeqIO.read('ref.fasta', "fasta") w['WorkflowInformation']['referenceIdentifier']=record.id #f={'FastaRecord':{'SeqId':record.id, # 'SeqDescription': record.description, # 'Sequence':str(record.seq), # 'sampleName':sample_name}} s={'summary':{}} s['summary']['completeness']=completeness(n['nextcladeOutputJson']) d={sample_name:{}} d[sample_name].update(p) d[sample_name].update(n) d[sample_name].update(a) d[sample_name].update(w) #d[sample_name].update(f) d[sample_name].update(s) with open('{0}_report.json'.format(sample_name), 'w', encoding='utf-8') as f: json.dump(d, f, indent=4, sort_keys=True, ensure_ascii=False)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 25064, 198, 11748, 33918, 198, 6738, 16024, 1330, 1001, 80, 9399, 198, 198, 39873, 62, 3672, 28, 17597, 13, 853, 85, 58, 16, 60, 198,...
2.49354
1,161
from alerta.models.alert import Alert from alerta.webhooks import WebhookBase from alerta.exceptions import RejectException import os import hashlib
[ 6738, 7995, 64, 13, 27530, 13, 44598, 1330, 23276, 198, 6738, 7995, 64, 13, 12384, 25480, 82, 1330, 5313, 25480, 14881, 198, 6738, 7995, 64, 13, 1069, 11755, 1330, 797, 752, 16922, 198, 11748, 28686, 198, 11748, 12234, 8019, 198 ]
3.725
40
# 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 eventlet eventlet.monkey_patch(thread=False) import json import logging import sys from flask import Flask, request # noqa from keystoneclient import exceptions from ironic_discoverd import conf from ironic_discoverd import discoverd from ironic_discoverd import firewall from ironic_discoverd import node_cache from ironic_discoverd import utils app = Flask(__name__) LOG = discoverd.LOG def periodic_update(period): while True: LOG.debug('Running periodic update of filters') try: firewall.update_filters() except Exception: LOG.exception('Periodic update failed') eventlet.greenthread.sleep(period)
[ 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, 257, 4866, 286, 262, 13789, 379, 198, 2,...
3.292225
373
################################################## # # ################################################## # []"", # ignore_user = ["Nightbot","Streamelements","Moobot"] # # URL del_word = ["88+","+"] # # https://cloud.google.com/translate/docs/languages ignore_lang = ["",""] # home_lang = "ja" # home_lang default_to_lang = "en" # translate.googleURL url_suffix = "co.jp" # TrueFalse sender = True # True # "displayname" # "loginid" ID sender_name = "displayname" # (en ja)TrueFalse language = True # Google Apps ScriptAPITrueFalse # Google Apps ScriptReadme gas = False # Google Apps ScriptURL gas_url = ""
[ 29113, 14468, 2235, 198, 2, 220, 198, 2, 220, 198, 29113, 14468, 2235, 198, 2, 17635, 1, 1600, 198, 198, 2, 220, 198, 46430, 62, 7220, 796, 14631, 24732, 13645, 2430, 30611, 480, 3639, 2430, 16632, 672, 313, 8973, 198, 198, 2, 220, ...
2.859091
220
import logging from sqlalchemy.exc import OperationalError from wxcloudrun import db from wxcloudrun.model import Counters # logger = logging.getLogger('log') logger.info("aaaaaaa") def query_counterbyid(id): """ IDCounter :param id: CounterID :return: Counter """ logger.info("bbbbbbbbb") try: return Counters.query.filter(Counters.id == id).first() except OperationalError as e: logger.info("query_counterbyid errorMsg= {} ".format(e)) return None def delete_counterbyid(id): """ IDCounter :param id: CounterID """ try: counter = Counters.query.get(id) if counter is None: return db.session.delete(counter) db.session.commit() except OperationalError as e: logger.info("delete_counterbyid errorMsg= {} ".format(e)) def insert_counter(counter): """ Counter :param counter: Counters """ try: db.session.add(counter) db.session.commit() except OperationalError as e: logger.info("insert_counter errorMsg= {} ".format(e)) def update_counterbyid(counter): """ IDcounter :param counter """ try: counter = query_counterbyid(counter.id) if counter is None: return db.session.flush() db.session.commit() except OperationalError as e: logger.info("update_counterbyid errorMsg= {} ".format(e))
[ 11748, 18931, 198, 198, 6738, 44161, 282, 26599, 13, 41194, 1330, 6564, 864, 12331, 198, 198, 6738, 266, 87, 17721, 5143, 1330, 20613, 198, 6738, 266, 87, 17721, 5143, 13, 19849, 1330, 3545, 1010, 198, 198, 2, 220, 198, 6404, 1362, 79...
2.388158
608
# -*- encoding: utf-8 -*- import os import sys import uuid import pytest from django.apps import apps from django.contrib.auth.models import Group from django.core.files.base import ContentFile try: from django.core.urlresolvers import reverse except ImportError: from django.urls import reverse from django.db import transaction from django.http import Http404 from django.test.utils import override_settings from django.utils import timezone from model_mommy import mommy from bpp.models import Typ_KBN, Jezyk, Charakter_Formalny, Typ_Odpowiedzialnosci from bpp.tests.tests_legacy.testutil import UserTestCase, UserTransactionTestCase from bpp.tests.util import any_jednostka, any_autor, any_ciagle from bpp.util import rebuild_contenttypes from bpp.views.raporty import RaportSelector, PodgladRaportu, KasowanieRaportu from celeryui.models import Report from django.conf import settings
[ 2, 532, 9, 12, 21004, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 11748, 28686, 198, 11748, 25064, 198, 11748, 334, 27112, 198, 198, 11748, 12972, 9288, 198, 6738, 42625, 14208, 13, 18211, 1330, 6725, 198, 6738, 42625, 14208, 13, 36...
3.109215
293
from typing import List from typing import Tuple from bot.utilities.api.constants import SCORE_TEMPLATE
[ 6738, 19720, 1330, 7343, 198, 6738, 19720, 1330, 309, 29291, 198, 198, 6738, 10214, 13, 315, 2410, 13, 15042, 13, 9979, 1187, 1330, 6374, 6965, 62, 51, 3620, 6489, 6158, 628 ]
3.419355
31
# -*- coding: utf-8 -*- # @Time : 2021/4/6 9:21 # @Author : # @File : carousel_serializers.py # @Software: Pycharm from rest_framework import serializers from Emall.exceptions import DataFormatError from shop_app.models.commodity_models import Carousel
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2488, 7575, 220, 1058, 33448, 14, 19, 14, 21, 860, 25, 2481, 198, 2, 2488, 13838, 1058, 220, 198, 2, 2488, 8979, 1058, 1097, 48355, 62, 46911, 11341, 13, 9078, 19...
2.826087
92
from itertools import chain from typing import List, Tuple from .br.br_nud import *
[ 6738, 340, 861, 10141, 1330, 6333, 198, 6738, 19720, 1330, 7343, 11, 309, 29291, 198, 198, 6738, 764, 1671, 13, 1671, 62, 77, 463, 1330, 1635, 628, 628, 628, 628 ]
3.066667
30
import argparse import gc import pathlib import sys import typing import uvicorn # type: ignore from attack_surface_pypy import __service_name__, __version__, asgi from attack_surface_pypy import logging as app_logging from attack_surface_pypy import settings # logger = structlog.get_logger() gc.disable() parser = argparse.ArgumentParser(description="App initial arguments.", prog=__service_name__) parser.add_argument( "-f", "--file-path", help="provide path to a file with initial data.", type=pathlib.Path, metavar=".fixtures/xxx.json", required=True, choices=[ pathlib.Path(".fixtures/input-1.json"), pathlib.Path(".fixtures/input-2.json"), pathlib.Path(".fixtures/input-3.json"), pathlib.Path(".fixtures/input-4.json"), pathlib.Path(".fixtures/input-5.json"), ], ) parser.add_argument( "-n", "--host", help="set host for the service.", type=str, metavar="localhost", ) parser.add_argument( "-p", "--port", type=int, help="set port for the service.", ) parser.add_argument( "-v", "--version", action="version", version=f"%(prog)s {__version__}", ) if __name__ == "__main__": ns = parser.parse_args() domain_settings = settings.Domain(file_path=ns.file_path) service_settings = settings.Service() if ns.host or ns.port: service_settings = settings.Service(host=ns.host, port=ns.port) app_settings = settings.Settings(domain=domain_settings, service=service_settings) log_config = app_logging.LoggingConfig( log_level=app_settings.log_level, traceback_depth=app_settings.traceback_depth ).prepare_logger() # context = types.Context(file_path=ns.file_path, host=ns.host, port=ns.port) # TODO: update settings from args? sys.exit(run_uvicorn(app_settings, log_config)) # TODO: hardcoded name, awry fabric
[ 11748, 1822, 29572, 198, 11748, 308, 66, 198, 11748, 3108, 8019, 198, 11748, 25064, 198, 11748, 19720, 198, 198, 11748, 334, 25531, 1211, 220, 1303, 2099, 25, 8856, 198, 198, 6738, 1368, 62, 42029, 62, 79, 4464, 88, 1330, 11593, 15271, ...
2.568521
737
# Generated by Django 2.2.5 on 2020-06-30 11:57 from django.db import migrations
[ 2, 2980, 515, 416, 37770, 362, 13, 17, 13, 20, 319, 12131, 12, 3312, 12, 1270, 1367, 25, 3553, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 628 ]
2.766667
30
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jun 2 16:54:10 2021 @author: sdn1 """ import numpy as np import os i=0 while(i<1): 1/0 print(bcolors.OKGREEN + chr(np.random.randint(250,400)) + bcolors.ENDC, end='') os.system('python $(pwd)/main.py') i=i+1 print(i)
[ 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, 3300, 7653, 220, 362, 1467, 25, 4051, 25, 940, 33448, 198, 198, 31, 9800, 25, 264, 32656,...
1.98125
160
import datetime from pathlib import Path from typing import Optional, Tuple from .common import _IMAGE_SUFFIXES, _PERMITTED_EXTENSIONS, PathDetails, rebuild_event_store if __name__ == "__main__": import argparse from dateutil.tz import tzoffset parser = argparse.ArgumentParser() parser.add_argument("-r", "--root-path", type=str, required=True) parser.add_argument("-j", "--json-path", type=str, required=True) args = parser.parse_args() rebuild_event_store( root_path=args.root_path, tzinfo=tzoffset(name="WST-8", offset=8 * 60 * 60), json_path=args.json_path, parse_method=parse_path, get_key_methods=[_get_key] )
[ 11748, 4818, 8079, 198, 6738, 3108, 8019, 1330, 10644, 198, 6738, 19720, 1330, 32233, 11, 309, 29291, 198, 198, 6738, 764, 11321, 1330, 4808, 3955, 11879, 62, 12564, 5777, 10426, 1546, 11, 4808, 18973, 44, 22470, 1961, 62, 13918, 16938, ...
2.492857
280
# ESnet Network Operating System (ENOS) Copyright (c) 2015, The Regents # of the University of California, through Lawrence Berkeley National # Laboratory (subject to receipt of any required approvals from the # U.S. Dept. of Energy). All rights reserved. # # If you have questions about your rights to use or distribute this # software, please contact Berkeley Lab's Innovation & Partnerships # Office at IPO@lbl.gov. # # NOTICE. This Software was developed under funding from the # U.S. Department of Energy and the U.S. Government consequently retains # certain rights. As such, the U.S. Government has been granted for # itself and others acting on its behalf a paid-up, nonexclusive, # irrevocable, worldwide license in the Software to reproduce, # distribute copies to the public, prepare derivative works, and perform # publicly and display publicly, and to permit other to do so. from java.lang import Thread, ThreadGroup import jarray rootThreadGroup = None if __name__ == '__main__': argv = sys.argv if len(argv) == 1: print_syntax() sys.exit() cmd = argv[1] if cmd == "help": print_syntax() elif cmd == "show-thread": gri = argv[2] if gri == 'all': match = None if 'grep' in argv: match = argv[4] threads = getAllThreads(match=match) if threads != None: for thread in threads: displayThread(thread=thread) print else: thread = getThread(long(argv[2])) if (thread == None): print "unknown",argv[2] sys.exit() displayThread(thread)
[ 2, 13380, 3262, 7311, 24850, 4482, 357, 1677, 2640, 8, 15069, 357, 66, 8, 1853, 11, 383, 3310, 658, 198, 2, 286, 262, 2059, 286, 3442, 11, 832, 13914, 14727, 2351, 198, 2, 18643, 357, 32796, 284, 14507, 286, 597, 2672, 45818, 422, ...
2.60061
656
import math
[ 11748, 10688 ]
5.5
2
from __future__ import division import inspect import types from functools import wraps function_type = type(lambda x: x) # using this instead of callable() because classes are callable, for instance no_default = NoDefault() def inject_method(self, method_function, method_name=None): """ method_function could be: * a function * a {method_name: function, ...} dict (for multiple injections) * a list of functions or (function, method_name) pairs """ if isinstance(method_function, function_type): if method_name is None: method_name = method_function.__name__ setattr(self, method_name, types.MethodType(method_function, self)) else: if isinstance(method_function, dict): method_function = [(func, func_name) for func_name, func in method_function.items()] for method in method_function: if isinstance(method, tuple) and len(method) == 2: self = inject_method(self, method[0], method[1]) else: self = inject_method(self, method) return self def transform_args(**trans_func_for_arg): """ Make a decorator that transforms function arguments before calling the function. For example: * original argument: a relative path --> used argument: a full path * original argument: a pickle filepath --> used argument: the loaded object :param rootdir: rootdir to be used for all name arguments of target function :param name_arg: the position (int) or argument name of the argument containing the name :return: a decorator >>> def f(a, b, c): ... return "a={a}, b={b}, c={c}".format(a=a, b=b, c=c) >>> >>> print(f('foo', 'bar', 3)) a=foo, b=bar, c=3 >>> ff = transform_args()(f) >>> print(ff('foo', 'bar', 3)) a=foo, b=bar, c=3 >>> ff = transform_args(a=lambda x: 'ROOT/' + x)(f) >>> print(ff('foo', 'bar', 3)) a=ROOT/foo, b=bar, c=3 >>> ff = transform_args(b=lambda x: 'ROOT/' + x)(f) >>> print(ff('foo', 'bar', 3)) a=foo, b=ROOT/bar, c=3 >>> ff = transform_args(a=lambda x: 'ROOT/' + x, b=lambda x: 'ROOT/' + x)(f) >>> print(ff('foo', b='bar', c=3)) a=ROOT/foo, b=ROOT/bar, c=3 """ return transform_args_decorator def resolve_filepath_of_name(name_arg=None, rootdir=''): """ Make a decorator that applies a function to an argument before using it. For example: * original argument: a relative path --> used argument: a full path * original argument: a pickle filepath --> used argument: the loaded object :param rootdir: rootdir to be used for all name arguments of target function :param name_arg: the position (int) or argument name of the argument containing the name :return: a decorator >>> def f(a, b, c): ... return "a={a}, b={b}, c={c}".format(a=a, b=b, c=c) >>> >>> print(f('foo', 'bar', 3)) a=foo, b=bar, c=3 >>> ff = resolve_filepath_of_name()(f) >>> print(ff('foo', 'bar', 3)) a=foo, b=bar, c=3 >>> ff = resolve_filepath_of_name('a', 'ROOT')(f) >>> print(ff('foo', 'bar', 3)) a=ROOT/foo, b=bar, c=3 >>> ff = resolve_filepath_of_name('b', 'ROOT')(f) >>> print(ff('foo', 'bar', 3)) a=foo, b=ROOT/bar, c=3 """ if name_arg is not None: return transform_args(**{name_arg: lambda x: os.path.join(rootdir, x)}) else: return lambda x: x def arg_dflt_dict_of_callable(f): """ Get a {arg_name: default_val, ...} dict from a callable. See also :py:mint_of_callable: :param f: A callable (function, method, ...) :return: """ argspec = inspect.getfullargspec(f) args = argspec.args or [] defaults = argspec.defaults or [] return {arg: dflt for arg, dflt in zip(args, [no_default] * (len(args) - len(defaults)) + list(defaults))} def infer_if_function_might_be_intended_as_a_classmethod_or_staticmethod(func): """ Tries to infer if the input function is a 'classmethod' or 'staticmethod' (or just 'normal') When is that? When: * the function's first argument is called 'cls' and has no default: 'classmethod' * the function's first argument is called 'self' and has no default: 'staticmethod' * otherwise: 'normal' >>> def a_normal_func(x, y=None): ... pass >>> def a_func_that_is_probably_a_classmethod(cls, y=None): ... pass >>> def a_func_that_is_probably_a_staticmethod(self, y=None): ... pass >>> def a_func_that_is_probably_a_classmethod_but_is_not(cls=3, y=None): ... pass >>> def a_func_that_is_probably_a_staticmethod_but_is_not(self=None, y=None): ... pass >>> list_of_functions = [ ... a_normal_func, ... a_func_that_is_probably_a_classmethod, ... a_func_that_is_probably_a_staticmethod, ... a_func_that_is_probably_a_classmethod_but_is_not, ... a_func_that_is_probably_a_staticmethod_but_is_not, ... ] >>> >>> for func in list_of_functions: ... print("{}: {}".format(func.__name__, ... infer_if_function_might_be_intended_as_a_classmethod_or_staticmethod(func))) ... a_normal_func: normal a_func_that_is_probably_a_classmethod: classmethod a_func_that_is_probably_a_staticmethod: staticmethod a_func_that_is_probably_a_classmethod_but_is_not: normal_with_cls a_func_that_is_probably_a_staticmethod_but_is_not: normal_with_self """ argsspec = inspect.getfullargspec(func) if len(argsspec.args) > 0: first_element_has_no_defaults = bool(len(argsspec.args) > len(argsspec.defaults)) if argsspec.args[0] == 'cls': if first_element_has_no_defaults: return 'classmethod' else: return 'normal_with_cls' elif argsspec.args[0] == 'self': if first_element_has_no_defaults: return 'staticmethod' else: return 'normal_with_self' return 'normal' if __name__ == '__main__': import os import re key_file_re = re.compile('setup.py') rootdir = '/D/Dropbox/dev/py/proj' cumul = list() for f in filter(lambda x: not x.startswith('.'), os.listdir(rootdir)): filepath = os.path.join(rootdir, f) if os.path.isdir(filepath): if dir_is_a_pip_installable_dir(filepath): cumul.append(filepath) for f in cumul: print(f)
[ 6738, 11593, 37443, 834, 1330, 7297, 198, 198, 11748, 10104, 198, 11748, 3858, 198, 6738, 1257, 310, 10141, 1330, 27521, 198, 198, 8818, 62, 4906, 796, 2099, 7, 50033, 2124, 25, 2124, 8, 220, 1303, 1262, 428, 2427, 286, 869, 540, 3419...
2.323738
2,814
#!/usr/bin/env python from setuptools import setup, find_packages from codecs import open from os import path here = path.abspath(path.dirname(__file__)) # Test version numbering before running setup test_version() setup( name='MIPPY', version=get_version(), description='Modular Image Processing in Python', author='Robert Flintham', author_email='robert.flintham@uhb.nhs.uk', install_requires=['numpy','scipy','dicom','pillow','nibabel','matplotlib'], license='BSD-3-Clause', classifiers=[ 'Programming Language :: Python :: 2.7', ], packages=['mippy','mippy.mdicom','mippy.mviewer'], package_data={'':['resources/*','mviewer/config']} )
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 6738, 900, 37623, 10141, 1330, 9058, 11, 1064, 62, 43789, 198, 6738, 40481, 82, 1330, 1280, 198, 6738, 28686, 1330, 3108, 198, 198, 1456, 796, 3108, 13, 397, 2777, 776, 7, 6978, ...
2.734694
245
"""Run a sample problem to test full system.""" # pylint: disable=invalid-name,missing-docstring import unittest from collections import namedtuple import math import os from physprog import classfunctions from physprog import optimize THIS_DIR = os.path.dirname(__file__) SAMPLE_INPUT = os.path.join(THIS_DIR, 'sample-input.yaml') SampleDesign = namedtuple('SampleDesign', ['d1', 'd2', 'd3', 'b', 'L']) if __name__ == '__main__': unittest.main()
[ 37811, 10987, 257, 6291, 1917, 284, 1332, 1336, 1080, 526, 15931, 198, 198, 2, 279, 2645, 600, 25, 15560, 28, 259, 12102, 12, 3672, 11, 45688, 12, 15390, 8841, 198, 11748, 555, 715, 395, 198, 6738, 17268, 1330, 3706, 83, 29291, 198, ...
2.834356
163
import os import sys from collections import defaultdict import tensorflow as tf import tensorflow.keras.backend as K import numpy as np import scipy.stats as ss import matplotlib.pyplot as plt from sklearn.metrics import roc_curve from sklearn.linear_model import LogisticRegression from utils import process_texts, load_texts, load_users, load_sated_data_by_user, \ build_nmt_model, words_to_indices, \ SATED_TRAIN_USER, SATED_TRAIN_FR, SATED_TRAIN_ENG MODEL_PATH = 'checkpoints/model/' OUTPUT_PATH = 'checkpoints/output/' tf.compat.v1.disable_eager_execution() # ================================ GENERATE RANKS ================================ # # Code adapted from https://github.com/csong27/auditing-text-generation def save_users_rank_results(users, user_src_texts, user_trg_texts, src_vocabs, trg_vocabs, prob_fn, save_dir, member_label=1, cross_domain=False, save_probs=False, mask=False, rerun=False): """ Save user ranks in the appropriate format for attacks. """ for i, u in enumerate(users): save_path = save_dir + 'rank_u{}_y{}{}.npz'.format(i, member_label, '_cd' if cross_domain else '') prob_path = save_dir + 'prob_u{}_y{}{}.npz'.format(i, member_label, '_cd' if cross_domain else '') if os.path.exists(save_path) and not save_probs and not rerun: continue user_src_data = words_to_indices(user_src_texts[u], src_vocabs, mask=mask) user_trg_data = words_to_indices(user_trg_texts[u], trg_vocabs, mask=mask) rtn = get_ranks(user_src_data, user_trg_data, prob_fn, save_probs=save_probs) if save_probs: probs = rtn np.savez(prob_path, probs) else: ranks, labels = rtn[0], rtn[1] np.savez(save_path, ranks, labels) if (i + 1) % 500 == 0: sys.stderr.write('Finishing saving ranks for {} users'.format(i + 1)) def get_target_ranks(num_users=200, num_words=5000, mask=False, h=128, emb_h=128, user_data_ratio=0., tied=False, save_probs=False): """ Get ranks of target machine translation model. """ user_src_texts, user_trg_texts, test_user_src_texts, test_user_trg_texts, src_vocabs, trg_vocabs \ = load_sated_data_by_user(num_users, num_words, test_on_user=True, user_data_ratio=user_data_ratio) train_users = sorted(user_src_texts.keys()) test_users = sorted(test_user_src_texts.keys()) # Get model save_dir = OUTPUT_PATH + 'target_{}{}/'.format(num_users, '_dr' if 0. < user_data_ratio < 1. else '') if not os.path.exists(save_dir): os.mkdir(save_dir) model_path = 'sated_nmt'.format(num_users) if 0. < user_data_ratio < 1.: model_path += '_dr{}'.format(user_data_ratio) heldout_src_texts, heldout_trg_texts = load_train_users_heldout_data(train_users, src_vocabs, trg_vocabs) for u in train_users: user_src_texts[u] += heldout_src_texts[u] user_trg_texts[u] += heldout_trg_texts[u] model = build_nmt_model(Vs=num_words, Vt=num_words, mask=mask, drop_p=0., h=h, demb=emb_h, tied=tied) model.load_weights(MODEL_PATH + '{}_{}.h5'.format(model_path, num_users)) src_input_var, trg_input_var = model.inputs prediction = model.output trg_label_var = K.placeholder((None, None), dtype='float32') # Get predictions prediction = K.softmax(prediction) prob_fn = K.function([src_input_var, trg_input_var, trg_label_var, K.learning_phase()], [prediction]) # Save user ranks for train and test dataset save_users_rank_results(users=train_users, save_probs=save_probs, user_src_texts=user_src_texts, user_trg_texts=user_trg_texts, src_vocabs=src_vocabs, trg_vocabs=trg_vocabs, cross_domain=False, prob_fn=prob_fn, save_dir=save_dir, member_label=1) save_users_rank_results(users=test_users, save_probs=save_probs, user_src_texts=test_user_src_texts, user_trg_texts=test_user_trg_texts, src_vocabs=src_vocabs, trg_vocabs=trg_vocabs, cross_domain=False, prob_fn=prob_fn, save_dir=save_dir, member_label=0) # ================================ ATTACK ================================ # def avg_rank_feats(ranks): """ Averages ranks to get features for deciding the threshold for membership inference. """ avg_ranks = [] for r in ranks: avg = np.mean(np.concatenate(r)) avg_ranks.append(avg) return avg_ranks def load_ranks_by_label(save_dir, num_users=300, cross_domain=False, label=1): """ Helper method to load ranks by train/test dataset. If label = 1, train set ranks are loaded. If label = 0, test set ranks are loaded. Ranks are generated by running sated_nmt_ranks.py. """ ranks = [] labels = [] y = [] for i in range(num_users): save_path = save_dir + 'rank_u{}_y{}{}.npz'.format(i, label, '_cd' if cross_domain else '') if os.path.exists(save_path): f = np.load(save_path, allow_pickle=True) train_rs, train_ls = f['arr_0'], f['arr_1'] ranks.append(train_rs) labels.append(train_ls) y.append(label) return ranks, labels, y def load_all_ranks(save_dir, num_users=5000, cross_domain=False): """ Loads all ranks generated by the target model. Ranks are generated by running sated_nmt_ranks.py. """ ranks = [] labels = [] y = [] # Load train ranks train_label = 1 train_ranks, train_labels, train_y = load_ranks_by_label(save_dir, num_users, cross_domain, train_label) ranks = ranks + train_ranks labels = labels + train_labels y = y + train_y # Load test ranks test_label = 0 test_ranks, test_labels, test_y = load_ranks_by_label(save_dir, num_users, cross_domain, test_label) ranks = ranks + test_ranks labels = labels + test_labels y = y + test_y return ranks, labels, np.asarray(y) def run_average_rank_thresholding(num_users=300, dim=100, prop=1.0, user_data_ratio=0., top_words=5000, cross_domain=False, rerun=False): """ Runs average rank thresholding attack on the target model. """ result_path = OUTPUT_PATH if dim > top_words: dim = top_words attack1_results_save_path = result_path + 'mi_data_dim{}_prop{}_{}{}_attack1.npz'.format( dim, prop, num_users, '_cd' if cross_domain else '') if not rerun and os.path.exists(attack1_results_save_path): f = np.load(attack1_results_save_path) X, y = [f['arr_{}'.format(i)] for i in range(4)] else: save_dir = result_path + 'target_{}{}/'.format(num_users, '_dr' if 0. < user_data_ratio < 1. else '') # Load ranks train_ranks, _, train_y = load_ranks_by_label(save_dir, num_users, label=1) test_ranks, _, test_y = load_ranks_by_label(save_dir, num_users, label=0) # Convert to average rank features train_feat = avg_rank_feats(train_ranks) test_feat = avg_rank_feats(test_ranks) # Create dataset X, y = np.concatenate([train_feat, test_feat]), np.concatenate([train_y, test_y]) np.savez(attack1_results_save_path, X, y) # print(X.shape, y.shape) # Find threshold using ROC clf = LogisticRegression() clf.fit(X.reshape(-1, 1), y) probs = clf.predict_proba(X.reshape(-1, 1)) fpr, tpr, thresholds = roc_curve(y, probs[:, 1]) plt.figure(1) plt.plot(fpr, tpr, label='Attack 1') plt.xlabel('False positive rate') plt.ylabel('True positive rate') plt.title('ROC curve') plt.savefig('sateduser_attack1_roc_curve.png') if __name__ == '__main__': num_users = 300 save_probs = False rerun = True print("Getting target ranks...") get_target_ranks(num_users=num_users, save_probs=save_probs) print("Running average rank thresholding attack...") run_average_rank_thresholding(num_users=num_users, rerun=True)
[ 11748, 28686, 198, 11748, 25064, 198, 6738, 17268, 1330, 4277, 11600, 198, 198, 11748, 11192, 273, 11125, 355, 48700, 198, 11748, 11192, 273, 11125, 13, 6122, 292, 13, 1891, 437, 355, 509, 198, 11748, 299, 32152, 355, 45941, 198, 11748, ...
2.244751
3,620
from django.test import TestCase from django.urls import reverse from django.contrib.auth import get_user_model from rest_framework.test import APIClient from rest_framework import status from core.models import Tag from recipe.serializers import TagSerializer TAGS_URL = reverse("recipe:tag-list")
[ 6738, 42625, 14208, 13, 9288, 1330, 6208, 20448, 198, 6738, 42625, 14208, 13, 6371, 82, 1330, 9575, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 1330, 651, 62, 7220, 62, 19849, 198, 198, 6738, 1334, 62, 30604, 13, 9288, 1330, 34...
3.465909
88
import numpy as np # import open3d as o3d from . import BaseAnnotationDefinition # from scipy.spatial.transform import Rotation as R import logging logger = logging.getLogger(name=__name__)
[ 11748, 299, 32152, 355, 45941, 198, 2, 1330, 1280, 18, 67, 355, 267, 18, 67, 198, 6738, 764, 1330, 7308, 2025, 38983, 36621, 198, 2, 422, 629, 541, 88, 13, 2777, 34961, 13, 35636, 1330, 371, 14221, 355, 371, 198, 11748, 18931, 198, ...
3.2
60
#!/usr/bin/env python # coding: utf-8 from my_module.exceptions import InvalidArgumentsError if __name__ == "__main__": my_adder = SimpleCalculator(operator="add") print('Case01:', my_adder.execute(4, 2)) print('Case02:', my_adder.execute(5, "a")) my_subtractor = SimpleCalculator(operator="sub") print('Case03:', my_subtractor.execute(3, 5)) my_multiplier = SimpleCalculator(operator="mul") print('Case04:', my_multiplier.execute(2, 7)) my_divider = SimpleCalculator(operator="div") print('Case05:', my_divider.execute(17, 5)) print('Case06:', my_divider.execute(6, 0)) print('Case07:') my_unknown = SimpleCalculator(operator="unknown") import sys; sys.exit(0)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 19617, 25, 3384, 69, 12, 23, 198, 198, 6738, 616, 62, 21412, 13, 1069, 11755, 1330, 17665, 28100, 2886, 12331, 628, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 6...
2.533101
287
import keras from keras.layers import Conv2D, Conv3D, Flatten, Dense, Reshape, BatchNormalization from keras.layers import Dropout, Input from keras.models import Model from keras.optimizers import Adam from keras.callbacks import ModelCheckpoint from keras.utils import np_utils from sklearn.decomposition import PCA from sklearn.model_selection import train_test_split from sklearn.metrics import confusion_matrix, accuracy_score, classification_report, cohen_kappa_score from operator import truediv from plotly.offline import init_notebook_mode import numpy as np import tensorflow as tf from keras import layers from keras.layers import Input, Add, Dense, Activation, ZeroPadding2D, BatchNormalization, Flatten, Conv2D, AveragePooling2D, MaxPooling2D, GlobalMaxPooling2D from keras.models import Model, load_model from keras.preprocessing import image from keras.utils import layer_utils from keras.utils.data_utils import get_file from keras.applications.imagenet_utils import preprocess_input from keras.utils.vis_utils import model_to_dot from keras.utils import plot_model from keras.initializers import glorot_uniform import pydot from IPython.display import SVG import scipy.misc from matplotlib.pyplot import imshow import keras.backend as K K.set_image_data_format('channels_last') K.set_learning_phase(1) from keras.utils import to_categorical import numpy as np import matplotlib.pyplot as plt import scipy.io as sio import os import spectral ## GLOBAL VARIABLES dataset = 'IP' test_ratio = 0.8 windowSize = 25 # X, y = loadData(dataset) K = 30 if dataset == 'IP' else 15 X,pca = applyPCA(X,numComponents=K) X, y = createImageCubes(X, y, windowSize=windowSize) ## Xtrain, Xtest, ytrain, ytest = splitTrainTestSet(X, y, test_ratio) # print("Xtrain.shape:",Xtrain.shape) # print("ytrain.shape:",ytrain.shape) # print("ytrain:",ytrain) ytrain = convert_one_hot(ytrain,16) ytest = convert_one_hot(ytest,16) # print("ytrain.shape:",ytrain.shape) # ResNet50 ; def identity_block(X, f, filters, stage, block): """ 3 X - tensor( m, n_H_prev, n_W_prev, n_H_prev ) f - CONV filters - stage - block block - stage X - tensor(n_H, n_W, n_C) """ # conv_name_base = "res" + str(stage) + block + "_branch" bn_name_base = "bn" + str(stage) + block + "_branch" # F1, F2, F3 = filters # X_shortcut = X # ## X = Conv2D(filters=F1, kernel_size=(1,1), strides=(1,1) ,padding="valid", name=conv_name_base+"2a", kernel_initializer=glorot_uniform(seed=0))(X) ## X = BatchNormalization(axis=3,name=bn_name_base+"2a")(X) ##ReLU X = Activation("relu")(X) # ## X = Conv2D(filters=F2, kernel_size=(f,f),strides=(1,1), padding="same", name=conv_name_base+"2b", kernel_initializer=glorot_uniform(seed=0))(X) ## X = BatchNormalization(axis=3,name=bn_name_base+"2b")(X) ##ReLU X = Activation("relu")(X) # ## X = Conv2D(filters=F3, kernel_size=(1,1), strides=(1,1), padding="valid", name=conv_name_base+"2c", kernel_initializer=glorot_uniform(seed=0))(X) ## X = BatchNormalization(axis=3,name=bn_name_base+"2c")(X) ##ReLU # ## X = Add()([X,X_shortcut]) ##ReLU X = Activation("relu")(X) return X def convolutional_block(X, f, filters, stage, block, s=2): """ 5 X - tensor( m, n_H_prev, n_W_prev, n_C_prev) f - CONV filters - stage - block block - stage s - X - tensor(n_H, n_W, n_C) """ # conv_name_base = "res" + str(stage) + block + "_branch" bn_name_base = "bn" + str(stage) + block + "_branch" # F1, F2, F3 = filters # X_shortcut = X # ## X = Conv2D(filters=F1, kernel_size=(1,1), strides=(s,s), padding="valid", name=conv_name_base+"2a", kernel_initializer=glorot_uniform(seed=0))(X) X = BatchNormalization(axis=3,name=bn_name_base+"2a")(X) X = Activation("relu")(X) ## X = Conv2D(filters=F2, kernel_size=(f,f), strides=(1,1), padding="same", name=conv_name_base+"2b", kernel_initializer=glorot_uniform(seed=0))(X) X = BatchNormalization(axis=3,name=bn_name_base+"2b")(X) X = Activation("relu")(X) ## X = Conv2D(filters=F3, kernel_size=(1,1), strides=(1,1), padding="valid", name=conv_name_base+"2c", kernel_initializer=glorot_uniform(seed=0))(X) X = BatchNormalization(axis=3,name=bn_name_base+"2c")(X) # X_shortcut = Conv2D(filters=F3, kernel_size=(1,1), strides=(s,s), padding="valid", name=conv_name_base+"1", kernel_initializer=glorot_uniform(seed=0))(X_shortcut) X_shortcut = BatchNormalization(axis=3,name=bn_name_base+"1")(X_shortcut) # X = Add()([X,X_shortcut]) X = Activation("relu")(X) return X def ResNet50(input_shape=(25,25,30),classes=16): """ ResNet50 CONV2D -> BATCHNORM -> RELU -> MAXPOOL -> CONVBLOCK -> IDBLOCK*2 -> CONVBLOCK -> IDBLOCK*3 -> CONVBLOCK -> IDBLOCK*5 -> CONVBLOCK -> IDBLOCK*2 -> AVGPOOL -> TOPLAYER input_shape - classes - model - Keras """ #tensor X_input = Input(input_shape) #0 X = ZeroPadding2D((3,3))(X_input) #stage1 X = Conv2D(filters=64, kernel_size=(7,7), strides=(2,2), name="conv1", kernel_initializer=glorot_uniform(seed=0))(X) X = BatchNormalization(axis=3, name="bn_conv1")(X) X = Activation("relu")(X) X = MaxPooling2D(pool_size=(3,3), strides=(2,2))(X) #stage2 X = convolutional_block(X, f=3, filters=[64,64,256], stage=2, block="a", s=1) X = identity_block(X, f=3, filters=[64,64,256], stage=2, block="b") X = identity_block(X, f=3, filters=[64,64,256], stage=2, block="c") #stage3 X = convolutional_block(X, f=3, filters=[128,128,512], stage=3, block="a", s=2) X = identity_block(X, f=3, filters=[128,128,512], stage=3, block="b") X = identity_block(X, f=3, filters=[128,128,512], stage=3, block="c") X = identity_block(X, f=3, filters=[128,128,512], stage=3, block="d") #stage4 X = convolutional_block(X, f=3, filters=[256,256,1024], stage=4, block="a", s=2) X = identity_block(X, f=3, filters=[256,256,1024], stage=4, block="b") X = identity_block(X, f=3, filters=[256,256,1024], stage=4, block="c") X = identity_block(X, f=3, filters=[256,256,1024], stage=4, block="d") X = identity_block(X, f=3, filters=[256,256,1024], stage=4, block="e") X = identity_block(X, f=3, filters=[256,256,1024], stage=4, block="f") #stage5 X = convolutional_block(X, f=3, filters=[512,512,2048], stage=5, block="a", s=2) X = identity_block(X, f=3, filters=[512,512,2048], stage=5, block="b") X = identity_block(X, f=3, filters=[512,512,2048], stage=5, block="c") # X = AveragePooling2D(pool_size=(2,2),padding="same")(X) # X = Flatten()(X) X = Dense(classes, activation="softmax", name="fc"+str(classes), kernel_initializer=glorot_uniform(seed=0))(X) # model = Model(inputs=X_input, outputs=X, name="ResNet50") return model # # x_train : (3074,25,25,30) y_train: (3074) # model = ResNet50(input_shape=(25,25,30),classes=16) # model.compile(optimizer="adam", loss="categorical_crossentropy", metrics=["accuracy"]) # # # model.fit(Xtrain,ytrain,epochs=2,batch_size=25) # preds = model.evaluate(Xtest,ytest) # # print(":",str(preds[0])) # print(":",str(preds[1])) if __name__ == "__main__": main()
[ 11748, 41927, 292, 201, 198, 6738, 41927, 292, 13, 75, 6962, 1330, 34872, 17, 35, 11, 34872, 18, 35, 11, 1610, 41769, 11, 360, 1072, 11, 1874, 71, 1758, 11, 347, 963, 26447, 1634, 201, 198, 6738, 41927, 292, 13, 75, 6962, 1330, 14...
2.059667
3,905
#!/usr/bin/env python3 from setuptools import setup, find_packages requirements = ["pyp2rpm~=3.3.1"] setup( name="utest", version="0.1.0", description="Micro test module", license="GPLv2+", author="pyp2rpm Developers", author_email='bkabrda@redhat.com, rkuska@redhat.com, mcyprian@redhat.com, ishcherb@redhat.com', url='https://github.com/fedora-python/pyp2rpm', install_requires=requirements, include_package_data=True, packages=find_packages(exclude=["test"]), classifiers=( "License :: OSI Approved :: GNU General Public License v2 or later (GPLv2+)", "Operating System :: POSIX :: Linux", "Programming Language :: Python", "Programming Language :: Python :: 3", ), )
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 6738, 900, 37623, 10141, 1330, 9058, 11, 1064, 62, 43789, 198, 198, 8897, 18883, 796, 14631, 79, 4464, 17, 48235, 93, 28, 18, 13, 18, 13, 16, 8973, 198, 198, 40406, 7, 198...
2.480263
304
# coding=utf-8 # Copyright 2022 The Google Research Authors. # # 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. """Data preprocessing for ImageNet2012 and CIFAR-10.""" from typing import Any, Callable # pylint: disable=unused-import from big_vision.pp import ops_general from big_vision.pp import ops_image # pylint: enable=unused-import from big_vision.pp import utils from big_vision.pp.builder import get_preprocess_fn as _get_preprocess_fn from big_vision.pp.registry import Registry import tensorflow as tf CIFAR_MEAN = [0.4914, 0.4822, 0.4465] CIFAR_STD = [0.247, 0.243, 0.261] def preprocess_cifar(split, **_): """Preprocessing functions for CIFAR-10 training.""" mean_str = ",".join([str(m) for m in CIFAR_MEAN]) std_str = ",".join([str(m) for m in CIFAR_STD]) if split == "train": pp = ("decode|" "value_range(0,1)|" "random_crop_with_pad(32,4)|" "flip_lr|" f"vgg_value_range(({mean_str}),({std_str}))|" "onehot(10, key='label', key_result='labels')|" "keep('image', 'labels')") else: pp = ("decode|" "value_range(0,1)|" "central_crop(32)|" f"vgg_value_range(({mean_str}),({std_str}))|" "onehot(10, key='label', key_result='labels')|" "keep('image', 'labels')") return _get_preprocess_fn(pp) def preprocess_imagenet(split, autoaugment = False, label_smoothing = 0.0, **_): """Preprocessing functions for ImageNet training.""" if split == "train": pp = ("decode_jpeg_and_inception_crop(224)|" "flip_lr|") if autoaugment: pp += "randaug(2,10)|" pp += "value_range(-1,1)|" if label_smoothing: confidence = 1.0 - label_smoothing low_confidence = (1.0 - confidence) / (1000 - 1) pp += ("onehot(1000, key='label', key_result='labels', " f"on_value={confidence}, off_value={low_confidence})|") else: pp += "onehot(1000, key='label', key_result='labels')|" pp += "keep('image', 'labels')" else: pp = ("decode|" "resize_small(256)|" "central_crop(224)|" "value_range(-1,1)|" "onehot(1000, key='label', key_result='labels')|" "keep('image', 'labels')") return _get_preprocess_fn(pp) PREPROCESS = { "cifar10": preprocess_cifar, "imagenet2012": preprocess_imagenet, } def get_preprocess_fn(dataset, split, **preprocess_kwargs): """Makes a preprocessing function.""" preprocess_fn_by_split = PREPROCESS.get(dataset, lambda _: (lambda x: x)) split = "train" if "train" in split else "val" preprocess_fn = preprocess_fn_by_split(split, **preprocess_kwargs) return preprocess_fn
[ 2, 19617, 28, 40477, 12, 23, 198, 2, 15069, 33160, 383, 3012, 4992, 46665, 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, ...
2.334525
1,399
from math import log from PIL import Image, ImageDraw from collections import Counter import numpy as np from pandas import DataFrame # my_data = [['slashdot', 'USA', 'yes', 18, 213.2, 'None'], # ['google', 'France', 'yes', 23, 121.2, 'Premium'], # ['digg', 'USA', 'yes', 24, 21.32, 'Basic'], # ['kiwitobes', 'France', 'yes', 23, 1.2, 'Basic'], # ['google', 'UK', 'no', 21, .2, 'Premium'], # ['(direct)', 'New Zealand', 'no', 12, 71.2, 'None'], # ['(direct)', 'UK', 'no', 21, -21.2, 'Basic'], # ['google', 'USA', 'no', 24, 241.2, 'Premium'], # ['slashdot', 'France', 'yes', 19, 20, 'None'], # ['digg', 'USA', 'no', 18, 1.0, 'None'], # ['google', 'UK', 'no', 18, 2, 'None'], # ['kiwitobes', 'UK', 'no', 19, 44, 'None'], # ['digg', 'New Zealand', 'yes', 12, 27, 'Basic'], # ['slashdot', 'UK', 'no', 21, 86, 'None'], # ['google', 'UK', 'yes', 18, 2, 'Basic'], # ['kiwitobes', 'France', 'yes', 19, 0.0, 'Basic']] my_data = [[213.2, 'None'], [121.2, 'Premium'], [21.32, 'Basic'], [1.2, 'Basic'], [.2, 'Premium'], [71.2, 'None'], [-21.2, 'Basic'], [241.2, 'Premium'], [20, 'None'], [1.0, 'None'], [2, 'None'], [44, 'None'], [27, 'Basic'], [86, 'None'], [2, 'Basic'], [0.0, 'Basic']] data = np.array(DataFrame(my_data)) # my_data = [['slashdot', 'USA', 'yes', 18, 'None'], # ['google', 'France', 'yes', 23, 'None'], # ['digg', 'USA', 'yes', 24, 'None'], # ['kiwitobes', 'France', 'yes', 23, 'None'], # ['google', 'UK', 'no', 21, 'None'], # ['(direct)', 'New Zealand', 'no', 12, 'None'], # ['(direct)', 'UK', 'no', 21, 'None'], # ['google', 'USA', 'no', 24, 'None'], # ['slashdot', 'France', 'yes', 19, 'None'], # ['digg', 'USA', 'no', 18, 'None'], # ['google', 'UK', 'no', 18, 'None'], # ['kiwitobes', 'UK', 'no', 19, 'None'], # ['digg', 'New Zealand', 'yes', 12, 'None'], # ['slashdot', 'UK', 'no', 21, 'None'], # ['google', 'UK', 'yes', 18, 'None'], # ['kiwitobes', 'France', 'yes', 19, 'None']]
[ 6738, 10688, 1330, 2604, 198, 6738, 350, 4146, 1330, 7412, 11, 7412, 25302, 198, 6738, 17268, 1330, 15034, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 19798, 292, 1330, 6060, 19778, 198, 198, 2, 616, 62, 7890, 796, 16410, 6, 6649, ...
1.792975
1,338
from datetime import datetime
[ 6738, 4818, 8079, 1330, 4818, 8079, 628, 198 ]
4
8
#!/usr/bin/env python3 from __future__ import print_function import sys sys.path.append('./method') import os import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import model as m """ Run fit. """ predict_list = ['sinewave', 'staircase', 'activation', 'ap'] try: which_predict = sys.argv[1] except: print('Usage: python %s [str:which_predict]' % os.path.basename(__file__)) sys.exit() if which_predict not in predict_list: raise ValueError('Input data %s is not available in the predict list' \ % which_predict) # Get all input variables import importlib sys.path.append('./mmt-model-files') info_id_a = 'model_A' info_a = importlib.import_module(info_id_a) info_id_b = 'model_B' info_b = importlib.import_module(info_id_b) data_dir = './data' savedir = './fig/compare' if not os.path.isdir(savedir): os.makedirs(savedir) data_file_name = 'data-%s.csv' % which_predict print('Predicting ', data_file_name) saveas = 'compare-sinewave-' + which_predict # Protocol protocol = np.loadtxt('./protocol-time-series/%s.csv' % which_predict, skiprows=1, delimiter=',') protocol_times = protocol[:, 0] protocol = protocol[:, 1] # Load data data = np.loadtxt(data_dir + '/' + data_file_name, delimiter=',', skiprows=1) # headers times = data[:, 0] data = data[:, 1] # Model model_a = m.Model(info_a.model_file, variables=info_a.parameters, current_readout=info_a.current_list, set_ion=info_a.ions_conc, transform=None, temperature=273.15 + info_a.temperature, # K ) model_b = m.Model(info_b.model_file, variables=info_b.parameters, current_readout=info_b.current_list, set_ion=info_b.ions_conc, transform=None, temperature=273.15 + info_b.temperature, # K ) # Update protocol model_a.set_fixed_form_voltage_protocol(protocol, protocol_times) model_b.set_fixed_form_voltage_protocol(protocol, protocol_times) # Load calibrated parameters load_seed = 542811797 fix_idx = [1] calloaddir_a = './out/' + info_id_a calloaddir_b = './out/' + info_id_b cal_params_a = [] cal_params_b = [] for i in fix_idx: cal_params_a.append(np.loadtxt('%s/%s-solution-%s-%s.txt' % \ (calloaddir_a, 'sinewave', load_seed, i))) cal_params_b.append(np.loadtxt('%s/%s-solution-%s-%s.txt' % \ (calloaddir_b, 'sinewave', load_seed, i))) # Predict predictions_a = [] for p in cal_params_a: predictions_a.append(model_a.simulate(p, times)) predictions_b = [] for p in cal_params_b: predictions_b.append(model_b.simulate(p, times)) # Plot fig, axes = plt.subplots(2, 1, sharex=True, figsize=(10, 4), gridspec_kw={'height_ratios': [1, 3]}) is_predict = ' prediction' if which_predict != 'sinewave' else '' sim_protocol = model_a.voltage(times) # model_b should give the same thing axes[0].plot(times, sim_protocol, c='#7f7f7f') axes[0].set_ylabel('Voltage\n(mV)', fontsize=16) axes[1].plot(times, data, alpha=0.5, label='Data') for i, p in zip(fix_idx, predictions_a): axes[1].plot(times, p, label='Model A' + is_predict) for i, p in zip(fix_idx, predictions_b): axes[1].plot(times, p, label='Model B' + is_predict) # Zooms from mpl_toolkits.axes_grid1.inset_locator import inset_axes, mark_inset sys.path.append('./protocol-time-series') zoom = importlib.import_module(which_predict + '_to_zoom') axes[1].set_ylim(zoom.set_ylim) for i_zoom, (w, h, loc) in enumerate(zoom.inset_setup): axins = inset_axes(axes[1], width=w, height=h, loc=loc, axes_kwargs={"facecolor" : "#f0f0f0"}) axins.plot(times, data, alpha=0.5) for i, p in zip(fix_idx, predictions_a): axins.plot(times, p) for i, p in zip(fix_idx, predictions_b): axins.plot(times, p) axins.set_xlim(zoom.set_xlim_ins[i_zoom]) axins.set_ylim(zoom.set_ylim_ins[i_zoom]) #axins.yaxis.get_major_locator().set_params(nbins=3) #axins.xaxis.get_major_locator().set_params(nbins=3) axins.set_xticklabels([]) axins.set_yticklabels([]) pp, p1, p2 = mark_inset(axes[1], axins, loc1=zoom.mark_setup[i_zoom][0], loc2=zoom.mark_setup[i_zoom][1], fc="none", lw=0.75, ec='k') pp.set_fill(True); pp.set_facecolor("#f0f0f0") axes[1].legend() axes[1].set_ylabel('Current (pA)', fontsize=16) axes[1].set_xlabel('Time (ms)', fontsize=16) plt.subplots_adjust(hspace=0) plt.savefig('%s/%s' % (savedir, saveas), bbox_inches='tight', dpi=200) plt.close()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 11748, 25064, 198, 17597, 13, 6978, 13, 33295, 7, 4458, 14, 24396, 11537, 198, 11748, 28686, 198, 11748, 299, 32152, 355, 45941, ...
2.203523
2,044
''' python3 classifier_service.py data.csv This service runs a scikit-learn classifier on data provided by the csv file data.csv. The idea of this is a simple spam detector. In the file, you will see a number, 1 or -1, followed by a pipe, followed by a piece of text. The text is designed to be a subject email, and the number its label: 1 for spam and -1 for not spam. The service loads the csv file, trains the classifier, and then waits for you to send it a list of texts via the 'classify' route. This service can be tested using: ./test_classifier_service.sh ''' from flask import Flask,request,jsonify from pype import pype as p from pype import _,_0,_1,_p from pype import _assoc as _a from pype import _dissoc as _d from pype import _do from statistics import mean,stdev from pype.vals import lenf from sklearn.ensemble import RandomForestClassifier as Classifier from sklearn.feature_extraction.text import TfidfVectorizer as Vectorizer import sys import csv ''' We have to use lambda to define the read function because pype functions can't yet deal with keyword args. ''' read=lambda f: csv.reader(f,delimiter='|') def train_classifier(texts,y): ''' Here is a perfect example of the "feel it ... func it" philosophy: The pype call uses the function arguments and function body to specify three variables, texts, a list of strings, y, a list of floats, and vectorizer, a scikit-learn object that vectorizes text. This reiterates the adivce that you should use the function body and function arguments to declare your scope, whenever you can. Line-by-line, here we go: {'vectorizer':vectorizer.fit, 'X':vectorizer.transform}, We build a dict, the first element of which is the fit vectorizer. Luckily, the 'fit' function returns an instance of the trained vectorizer, so we do not need to use _do. This vectorizer is then assigned to 'vectorizer'. Because iterating through dictionaries in Python3.6 preserves the order of the keys in which they were declared, we can apply the fit function to the vectorizer on the texts, assign that to the 'vectorizer' key. We need this instance of the vectorizer to run the classifier for unknown texts. After this, we apply the 'transform' to convert the texts into a training matrix keyed by 'X', whose rows are texts and whose columns are words. _a('classifier',(Classifier().fit,_['X'],y)), Finally, we can build a classifier. _a, or _assoc, means we are adding a key-value pair to the previous dictionary. This will be a new instance of our Classifier, which is trained through the fit function on the text-word matrix 'X' and the labels vector y. _d('X'), Since we don't need the X matrix anymore, we delete it from the returned JSON, which now only contains 'vectorizer' and 'classifier', the two things we will need to classify unknown texts. ''' vectorizer=Vectorizer() return p( texts, {'vectorizer':vectorizer.fit, 'X':vectorizer.transform}, _a('classifier',(Classifier().fit,_['X'],y)), _d('X'), ) ''' We train the model in a global variable containing our vectorizer and classifier. This use of global variables is only used for microservices, by the way. Here is a line-by-line description: sys.argv[1], open, Open the file. read, We build a csv reader with the above-defined 'read' function, which builds a csv reader with a '|' delimiter. I chose this delimeter because the texts often have commas. list, Because csv.reader is a generator, it cannot be accessed twice, so I cast it to a list. This list is a list of 2-element lists, of the form [label,text], where label is a string for the label ('1' or '-1'), and text is a string for the training text. So an example of this would be ['1','free herbal viagra buy now']. (train,[_1],[(float,[_0])]) This is a lambda which calls the 'train' function on two arguments, the first being a list of texts, the second being a list of numerical labels. We know that the incoming argument is a list of 2-element lists, so [_1] is a map, which goes through this list - [] - and builds a new list containing only the second element of each 2-element list, referenced by _1. With the first elements of the 2-element lists, we must extract the first element and cast it to a float. In [(float,[_0])], the [] specifies a map over the list of 2-element lists. (float,_0) specifies we are accessing the first element of the 2-element list ('1' or '-1'), and calls the float function on it, to cast it to a float. If we do not cast it to a float, sklearn will not be able to process it as a label. ''' MODEL=p( sys.argv[1], open, read, list, (train_classifier,[_1],[(float,_0)]), ) app = Flask(__name__) if __name__=='__main__': app.run(host='0.0.0.0',port=10004,debug=True)
[ 7061, 6, 198, 29412, 18, 1398, 7483, 62, 15271, 13, 9078, 1366, 13, 40664, 198, 198, 1212, 2139, 4539, 257, 629, 1134, 270, 12, 35720, 1398, 7483, 319, 1366, 2810, 416, 262, 269, 21370, 2393, 1366, 13, 40664, 13, 198, 198, 464, 2126...
3.089672
1,617
# SPDX-License-Identifier: MIT import os import idaapi import idautils from PyQt5 import QtWidgets from uefi_analyser import dep_browser, dep_graph, prot_explorer, ui AUTHOR = "yeggor" VERSION = "1.2.0" NAME = "UEFI_RETool" WANTED_HOTKEY = "Ctrl+Alt+U" HELP = "This plugin performs automatic analysis of the input UEFI module" def PLUGIN_ENTRY(): try: return UefiAnalyserPlugin() except Exception as err: import traceback print(f"[{NAME} error] {str(err)}\n{traceback.format_exc()}")
[ 2, 30628, 55, 12, 34156, 12, 33234, 7483, 25, 17168, 198, 198, 11748, 28686, 198, 198, 11748, 220, 3755, 15042, 198, 11748, 4686, 2306, 4487, 198, 6738, 9485, 48, 83, 20, 1330, 33734, 54, 312, 11407, 198, 198, 6738, 334, 891, 72, 62...
2.430556
216