text
stringlengths
17
737k
#!/usr/bin/python import MySQLdb, datetime, httplib, json, os # requires MySQLdb python 2 library which is not ported to python 3 yet class mysql_database: def __init__(self): credentials_file = os.path.join(os.path.dirname(__file__), "credentials.mysql") f = open(credentials_file, "r") credential...
#!/usr/bin/env python # # Copyright (c) 2011-2013 Corey Goldberg (http://goldb.org) # # This file is part of linux-metrics # # License :: OSI Approved :: MIT License: # http://www.opensource.org/licenses/mit-license # # Permission is hereby granted, free of charge, to any person obtaining a copy # of...
from __future__ import absolute_import from __future__ import print_function from __future__ import division import os import h5py import pickle as p import numpy as np from PIL import Image from glob import glob from tqdm import tqdm from multiprocessing import Pool from scipy.misc import imread, imresize from sklea...
# encoding: utf-8 from __future__ import unicode_literals from inspect import ismethod from inspect import getfullargspec class AnnotationExtension(object): """Utilize Python 3 function annotations as a method to filter arguments coming in from the web. Argument annotations are treated as callbacks to execute,...
#!/usr/bin/python # -*- coding: utf-8 -*- # api.py # Copyright 2017 # Fábio Beranizo (fabio.beranizo@gmail.com) # Guilherme Folego (gfolego@gmail.com) # # 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 ...
""" The aim of this script is to visualize the data stored in the SQLite db from sims The questions that this script should answer are: 1- list existing fields in the DB 2- list unique values in each field 3- count how many trials exist per triplet (duration, h, SNR) 4- for fixed triplet, compute the average differenc...
#invenvi core file import logging import os from model_data import ModelData class invenaviKernel: def __init__(self, config, debug=False): self.config = config self.debug = debug # sensors self._gps_sensor = config.gps_sensor #self._compass_sensor = config.compass_sensor...
#!/usr/bin/env python # Based on previous work by # Charles Menguy (see: http://stackoverflow.com/questions/10217067/implementing-a-full-python-unix-style-daemon-process) # and Sander Marechal (see: http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/) # Adapted by M.Hendrix [2015] # daemon23....
# -*- coding: utf-8 -*- """ Security Knowledge Framework is an expert system application that uses OWASP Application Security Verification Standard, code examples, helps developers in pre-development and post-development. Copyright (C) 2015 Glenn ten Cate, Riccardo ten Cate This program is free...
from sqlalchemy import create_engine from sqlalchemy import Column, String, Boolean, Integer, DateTime, ForeignKey from sqlalchemy.orm import scoped_session, sessionmaker, relationship from sqlalchemy.ext.declarative import declarative_base import datetime import json engine = create_engine('sqlite:///db.sqlite', co...
#!/usr/bin/python # vim: set ai sw=4 sta fo=croql ts=8 expandtab syntax=python # die, PEP8's 80-column punched card requirement! import time import sys import gzip import os import csv import re import fnmatch from sensors import rths_sites...
from typing import Dict, Any, Optional from pathlib import Path from wasabi import msg from thinc.api import require_gpu, fix_random_seed, set_dropout_rate, Adam, Config from thinc.api import Model, data_validation import typer from ._util import Arg, Opt, debug_cli, show_validation_error, parse_config_overrides from ...
#!/usr/bin/env python3 # # Copyright (C) 2019 VyOS maintainers and contributors # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 or later as # published by the Free Software Foundation. # # This program is distributed in the hope t...
# # ber.py # Created by pira on 2017/08/05. # #coding: utf-8 u"""Calculate BER(Bit Error Rate).""" import sys def calcBER(data1, data2): u"""Calculate Bit Error Rate. @param data1 : result data @param data2 : answer data @return ber : bit error rate [%]. """ if len(data1) != len(data2): print('The input ...
from django.core.management import call_command from django.core.management.base import CommandError from django.test import TestCase from django.core import mail from django.conf import settings from geotrek.authent.factories import StructureFactory from geotrek.common.factories import AttachmentFactory from geotrek...
from datetime import datetime from django.db.models import Q from graphene_django import DjangoObjectType from wagtail.wagtailcore.fields import StreamField from wagtail.wagtailimages.models import Filter from taggit.managers import TaggableManager import graphene from graphene_django.converter import convert_django_fi...
from django.views.generic import View from django.conf.urls import patterns, url, include from rest_framework.routers import DefaultRouter from xosapi_helpers import XOSIndexViewSet import os, sys import inspect import importlib try: from rest_framework.serializers import DictField except: raise Exception("Fai...
#!/usr/bin/env python3 # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # A RPyC server which wraps ChessEnginePool import os import json import multiprocessing import...
from rest_framework import generics from rest_framework import permissions as drf_permissions from django.db.models import Q, Exists, OuterRef from framework.auth.oauth_scopes import CoreScopes from osf.models import AbstractNode, Subject, PreprintProvider, Contributor from api.base import permissions as base_permi...
from . import app, mongo from alexandria.decorators import * from flask import request, jsonify, url_for, session from flask.ext.classy import FlaskView, route import json from bson import json_util from bson.objectid import ObjectId class BookView(FlaskView): route_prefix = '/api/' @authenticated def ge...
import os import numpy as np import menpo.io as mio from menpo.visualize.text_utils import print_dynamic, progress_bar_str from menpo.fitmultilevel.aam import AAMBuilder, LucasKanadeAAMFitter from menpo.fit.fittingresult import FittingResultList from menpo.landmark import labeller from menpo.visualize.base import Grap...
# -*- coding: utf-8 -*- from selenium import webdriver from selenium.common.exceptions import NoSuchElementException import unittest class AddFilm(unittest.TestCase): def setUp(self): self.driver = webdriver.Firefox() self.driver.implicitly_wait(10) self.base_url = "http://hub.wart.ru/" ...
"""This is a helper which provides a set of definitions and Actors that can be used to run external commands and gather responses from them. Create a RunCommand Actor and send it a Command object defining the command to be run; the RunCommand will execute the command, monitoring its progress, and sends a CommandResult...
import csv from csv import excel_tab from sklearn.feature_extraction.text import CountVectorizer as CV from sklearn.feature_extraction.text import TfidfVectorizer as TFIDF from sklearn.linear_model import LogisticRegression as LR from sklearn.cross_validation import cross_val_score import cPickle import numpy as np imp...
#!/usr/bin/env python # Mosflm.py # Copyright (C) 2006 CCLRC, Graeme Winter # # This code is distributed under the BSD license, a copy of which is # included in the root directory of this package. # # 23rd June 2006 # # A wrapper for the data processing program Mosflm, with the following # methods to provide fu...
import abc import asyncio import socket import ssl as ssl_mod from ...errors import InvalidChecksumError class Connection(abc.ABC): """ The `Connection` class is a wrapper around ``asyncio.open_connection``. Subclasses will implement different transport modes as atomic operations, which this class e...
import logging import socket import pika.compat try: SOL_TCP = socket.SOL_TCP except AttributeError: SOL_TCP = socket.IPPROTO_TCP LOGGER = logging.getLogger(__name__) _SUPPORTED_TCP_OPTIONS = {} try: _SUPPORTED_TCP_OPTIONS['TCP_USER_TIMEOUT'] = socket.TCP_USER_TIMEOUT except AttributeError: if pika....
#!/usr/bin/env python # 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 # # Authors: # - Paul Nilsson, paul.nilsson@cern.ch, 2018 from os import envi...
import os.path import pickle import operator from files import InvertedFile, Reader from algorithm import NaiveAlgorithm, SimpleScanAlgorithm from algorithm import VectorsSimilarity ALGORITHMS = { "NAIVE": NaiveAlgorithm, "SIMPLE": SimpleScanAlgorithm } ALGORITHMS_DESC = { "NAIVE": "A naive Top-K algorit...
from collections import namedtuple from cStringIO import StringIO from ModestMaps.Core import Coordinate from multiprocessing.pool import ThreadPool from tilequeue.command import make_queue from tilequeue.command import parse_layer_data from tilequeue.format import extension_to_format from tilequeue.format import json_...
""" GUI-related functions for the Tcl/Tk framework. """ import tkinter import tkinter.ttk # optional image support, only needed for ImageCanvas try: import numpy as np import PIL import PIL.ImageTk import dh.image except ImportError as e: _IMAGECANVAS_ERROR=e else: _IMAGECANVAS_ERROR=None de...
#!/usr/bin/env python ######################################################################## # # To build panda using this script, type 'makepanda.py' on unix # or 'makepanda.bat' on windows, and examine the help-text. # Then run the script again with the appropriate options to compile # panda3d. # ##################...
# Some useful functions to extract data out of emails # Copyright (C) 2002-2015 John Goerzen & contributors # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the Lic...
# Create your views here. from django.core.urlresolvers import reverse from django.shortcuts import redirect, get_object_or_404 from django.views.generic import ListView from django.views.generic import View from django.db.models import Count from taggit.models import Tag from hitcount.views import HitCountDetailView ...
"""This module provides the HaaS service's public API. haas.api_server translates between this and HTTP. TODO: Spec out and document what sanitization is required. """ import model class APIError(Exception): """An exception indicating an error that should be reported to the user. i.e. If such an error occu...
# Standard libs import json import os import datetime import time import re import sys import csv import httplib2 from webapp2_extras import sessions from webapp2_extras import i18n import webapp2 import jinja2 from google.appengine._internal.django.utils.encoding import smart_str # Google libs import endpoints from go...
#Depends on web.py, psycopg2, PyYaml, pytz, python-dateutil import web, psycopg2 import json, yaml, xmlrpclib import datetime, pytz import skysql from dateutil.parser import parse as datetimeparse from dblogin import dbname, dbuser, dbpass categories = {} #The temptation to name this cat_herder was extraordinary def c...
""" Mapping between obograph-JSON format and networkx """ from ontobio.ontol import LogicalDefinition, PropertyChainAxiom from ontobio.vocabulary.relations import map_legacy_pred from ontobio.util.scigraph_util import get_curie_map from ontobio.golr.golr_associations import search_associations import json import netw...
"""A Python package for analysing and manipulating OOMMF vector fields. This module is a Python package that provides: - Opening OOMMF vector field files (.omf and .ohf) - Analysing vector fields, such as sampling, averaging, plotting, etc. - Saving arbitrary vector fields to OOMMF vector field files. oommffield is ...
#coding=utf-8 from django.db import models from django.db.models.base import ModelBase from django.db.models.fields import Field from django.utils.translation import ugettext_lazy as _ from pagebase.models.fields import IntegerArrayField, AutoSlugField SECTIONS = ( ('main', _('Main')), ('eyebrow', _('Eyebrow'...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import time import numpy as np import matplotlib matplotlib.use('GTKAgg') from matplotlib import pyplot as plt from koheron import connect from drivers import Spectrum from drivers import Laser host = os.getenv('HOST','192.168.1.100') client = connect(host, nam...
from collections import defaultdict from collections.abc import MutableSequence, Iterable import io import numpy as np from numpy.polynomial import Polynomial import pandas as pd from .data import NEUTRON_MASS from .endf import get_head_record, get_cont_record, get_tab1_record, get_list_record try: from .reconstr...
# -*- coding: utf-8 -*- """ =============================================================================== Cubic: Generate lattice-like networks =============================================================================== """ import numpy as np import scipy as sp from openpnm.network import GenericNetwork from ope...
import dxpy import string import random import sys import argparse # to find the magic library sys.path.append('/usr/local/lib/') import magic import subprocess def id_generator(size=10, chars=string.ascii_uppercase + string.digits): return ''.join(random.choice(chars) for x in range(size)) def unpack(input):...
# Mimic the hggit extension. try: from hggit import * hggit_reposetup = reposetup except ImportError: # Allow this module to be imported without # hg-git installed, eg for setup.py pass __version__ = "0.1.0" def reposetup(ui, repo, **kwargs): """ Automatically adds Bitbucket->GitHub mir...
import pygame import tkinter as tk import tkinter.filedialog import time, random, os # constants K_LEFT = pygame.K_LEFT K_RIGHT = pygame.K_RIGHT K_DOWN = pygame.K_DOWN K_UP = pygame.K_UP K_ESCAPE = pygame.K_ESCAPE K_o = pygame.K_o K_w = pygame.K_w K_h = pygame.K_h # create some colors BLACK = (0,0,0) GREY = (200,200,...
"""Tools for running tasks locally or in a cluster environment.""" import abc import os import stat import shutil import time import subprocess import math # Shell environment variable to specify which environment to use." AMDTK_PARALLEL_ENV = 'AMDTK_PARALLEL_ENV' # Possible environment. If the AMDTK_PARALLEL_ENV i...
import csv import datetime from functools import partial import io import logging import re import requests from django.conf import settings from django.contrib import messages from django.contrib.auth import update_session_auth_hash from django.contrib.auth.decorators import permission_required from django.contrib.au...
#! /usr/bin/python # Unbound Attack Interception "Geigeki" module # # Author: Stephane LAPIE <stephane.lapie@asahinet.com> # Copyright (c) 2017 AsahiNet, Inc. # All rights reserved. import socket, errno import select import threading import traceback import sys import time import ipaddress DEBUG = False GEIGEKI_HEAD...
import sys from PyQt5 import QtCore, QtGui from PyQt5.QtCore import QObject, Qt from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QSlider, QLabel, QSpinBox, QHBoxLayout, QGridLayout, QComboBox from mypyqt_widgets import Power2SteppedSlider, Power2SteppedSpinBox from pyqt_matplotlib import MatplotlibCanva...
#! /usr/bin/env python import sys import os import numpy as np import glob try: # Python2 import urllib2 as urllib except: # Python3 import urllib import argparse import scipy.interpolate as si from copy import copy try: import pyfits as fits except: import astropy.io.fits as fits ########## OPTIONS ###...
import os import yaml from astropy import units as u from astropy.coordinates import SkyCoord from astropy.time import Time from ..utils import * @has_logger class AbstractMount(object): def __init__(self, config=dict(), commands=dict(), location=None, ...
#!/usr/env/python from __future__ import division, print_function # Import General Tools import sys import os import argparse import ephem import datetime import time import importlib # from panoptes import Panoptes import panoptes import panoptes.mount as mount import panoptes.camera as camera import panoptes.wea...
""" Implementation from Goodfellow, Ian, Jean Pouget-Abadie, Mehdi Mirza, Bing Xu, David Warde-Farley, Sherjil Ozair, Aaron Courville, and Yoshua Bengio. "Generative adversarial nets." In Advances in Neural Information Processing Systems, pp. 2672-2680. 2014. """ from yann.special.gan import gan from theano import...
#!/usr/bin/env python from __future__ import print_function, absolute_import, division import socket import boto3 import mock import os import time import unittest2 from spotnik.main import main from spotnik.spotnik import ReplacementPolicy from subprocess import check_call, call import boto3 class SpotnikTestsBa...
#!/usr/bin/env python # # Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file # for details. All rights reserved. Use of this source code is governed by a # BSD-style license that can be found in the LICENSE file. import os import os.path import shutil import sys import subprocess import bot im...
import sys import time import os import signal import atexit from bson.objectid import ObjectId from models import DB from app import app # TODO - dynamic import from twitter import ThreadedCollector, preprocess, mongoBatchInsert # wd is the directory used to generate filenames for the Controller / Worker wd = app....
# Copyright (c) 2013 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """VM-related helper functions/classes.""" import logging import os from chromite.buildbot import constants from chromite.lib import cros_build_lib ...
"""The ArcGIS Server REST API, short for Representational State Transfer, provides a simple, open Web interface to services hosted by ArcGIS Server. All resources and operations exposed by the REST API are accessible through a hierarchy of endpoints or Uniform Resource Locators (URLs) for each GIS ser...
import logging from django import forms from django.contrib.auth import authenticate from django.contrib.auth.forms import AuthenticationForm from django.utils.translation import gettext as _ from .models import AuthenticatorModel from .utils import is_int logger = logging.getLogger(__name__) class AuthenticatorAd...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ gittime ~~~~~~~ Estimate time spent programming, aided by git commit metadata. More documentation and stuff is in the readme. Example usage:: python gittime.py git@github.com:uniphil/commit--blog.git For full usage details:: ...
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Aparajita Fishman # Copyright (c) 2015-2016 The SublimeLinter Community # Copyright (c) 2013-2014 Aparajita Fishman # # License: MIT # """This module exports the Annotations plugin class.""" import re from SublimeLi...
# -*- coding: utf-8 -*- """ This preprocessor removes lines in code cells that have been marked as `folded` by the codefolding extension """ from nbconvert.preprocessors import Preprocessor class CodeFoldingPreprocessor(Preprocessor): fold_mark = u'↔' def fold_cell(self, cell, folded): """ ...
from allgo_utils import PCA9685,ultrasonic,ir_sens import wiringpi as wp import time DIR_DISTANCE_ALERT = 20 preMillis = 0 ULTRASONIC_TRIG = 3 # TRIG port is to use as output signal ULTRASONIC_ECHO = 23 # ECHO port is to use as input signal OUT = {'front_left_led':5, 'front_right_led':0, 'rear_right_le...
# vim: tabstop=4 fileencoding=utf-8 # copyright Michael Weber (michael at xmw dot de) 2014 from config import STORAGE_DIR, LINK_DIR, FILE_SIZE_MAX, MIME_ALLOWED, BASE_PROTO, BASE_PATH OUTPUT = 'default', 'raw', 'html', 'link', 'qr', 'qr_png', 'qr_text', 'qr_text_big' import base64, hashlib, mod_python.apache, os hsh...
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import math from typing import Any, Dict, List, Optional, Tuple import torch import torch.nn as nn import torch.nn.functional as F from fairs...
import httplib2 import json import datetime import hmac from hashlib import sha1,md5 import base64 class Mailin: def __init__(self,base_url,access_key,secret_key): self.base_url = base_url self.access_key = access_key self.secret_key = secret_key def do_request(self,resource,method,indata): ...
# This file is part of beets. # Copyright 2013, Adrian Sampson. # # 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, ...
class dstat_plugin(dstat): def __init__(self): self.name = 'snooze' self.vars = ('snooze',) self.type = 's' self.width = 6 self.scale = 0 self.before = time.time() def extract(self): now = time.time() if loop != 0: self.val['snooze'] =...
import os import numpy as np from astropy.table import Table from pyraf import iraf from iraf import pysalt from saltobslog import obslog DATADIR = os.path.dirname(__file__) + '/data/' def rssmodelwave(grating,grang,artic,cbin,cols): """compute wavelengths from model of RSS TODO: replace using PySpectrog...
import math from operator import and_, or_, xor from hwt.hdlObjects.constants import DIRECTION from hwt.hdlObjects.operatorDefs import concatFn from hwt.hdlObjects.typeShortcuts import hInt, vec, vecT from hwt.hdlObjects.types.defs import BIT from hwt.hdlObjects.types.enum import Enum from hwt.hdlObjects.types.typeCas...
import base64 import json import os import re import uuid from collections import OrderedDict from operator import attrgetter from textwrap import dedent from urllib.parse import unquote from django.apps import apps from django.conf import settings from django.contrib.staticfiles import finders from django.core.urlres...
import datetime from PIL import Image from django.core.exceptions import ValidationError, PermissionDenied from django.core.files.base import ContentFile from django.conf import settings from django.views.decorators.http import require_http_methods from django.views.decorators.csrf import csrf_exempt from django.http ...
import traceback import web import os import random from optf2.backend import log from optf2.backend import config from optf2 import app virtual_root = config.ini.get("resources", "virtual-root") valid_languages = [str(code).strip() for code in config.ini.get("misc", "languages").split(',')] valid_modes = [op[0] for ...
#!/usr/bin/env python import sys, csv, random from gensim.models.word2vec import Word2Vec import numpy as np RANDOM_SEED = 228 random.seed(RANDOM_SEED) w2v = Word2Vec.load_word2vec_format('all.norm-sz100-w10-cb0-it1-min100.w2v', binary=True, unicode_errors='ignore') w2v.init_sims(replace=True) with np.load('test.np...
import tensorflow as tf import numpy as np import hyperchamber as hc from hypergan.util.hc_tf import * def standard_block(net, config, activation, batch_size,id,name, resize=None, output_channels=None, stride=2, noise_shape=None, dtype=tf.float32,filter=3, batch_norm=None, sigmoid_gate=None, reshaped_z_proj=None): ...
from typing import Optional import os import json import sys import re import logging import asyncio import random import traceback import base64 import uuid import shutil import aiohttp import aiohttp.client_exceptions from aiohttp import web import async_timeout import concurrent import aiodocker from aiodocker.excep...
# Copyright 2012 Colin Scott # # This file is part of POX. # # POX is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # POX is distribut...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import six import json import logging from django.conf import settings from collections import Sequence from bigbuild.exceptions import ( MissingMetadataWarning, MissingRecommendedMetadataWarning ) from bigbuild.models import Page, RetiredPage from dateuti...
#!/usr/bin/env python # This document is part of scraper # https://github.com/SkyTruth/scraper # =================================================================================== # # # The MIT License (MIT) # # Copyright (c) 2014 SkyTruth # # Permission is hereby granted, free of charge, to any person obtainin...
import mistune import re import copy import urlparse import posixpath #TODO disable embedded HTML ? __version__ = '0.0.0' __author__ = 'John Pickerill <me@curiouscrab.com>' __all__ = [ 'BlockGrammar', 'BlockLexer', 'InlineGrammar', 'InlineLexer', 'Renderer', 'Markdown', 'markdown', 'escape', ] ...
import collections import functools import re import rpy2.robjects as robjects import rpy2.rinterface as rinterface from . import reval from .ri2pi import ri2pi from . import rparser from .tree import Node, Operator class GLM(): def __init__(self, obj=None): self.__rclass = tuple(obj.rclass)[0] self.dict =...
from models import Value from proso.django.response import pass_get_parameters from django.core.urlresolvers import reverse def values(request, json_list, nested): if nested: return json_list object_ids = map(lambda x: x['id'], json_list) values = Value.objects.filter(experiment_id__in=object_ids)...
"""Generates constants for use in blinkpy.""" import os MAJOR_VERSION = 0 MINOR_VERSION = 14 PATCH_VERSION = '0.dev0' __version__ = '{}.{}.{}'.format(MAJOR_VERSION, MINOR_VERSION, PATCH_VERSION) REQUIRED_PYTHON_VER = (3, 5, 3) PROJECT_NAME = 'blinkpy' PROJECT_PACKAGE_NAME = 'blinkpy' PROJECT_LICENSE = 'MIT' PROJEC...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function import io import math import optparse import os.path import signal import struct import zlib import starbound import starbound.btreedb4 try: # Don't break on pipe signal. signal.signal(signal.SIGPIPE, signal.SIG_DFL) except...
"""Main hangman game. Use Python 3. """ from string import ascii_lowercase from words import get_random_word def _get_num_attempts(): while True: num_attempts = input('How many attempts do you want? [1-25] ') try: num_attempts = int(num_attempts) if num_attempts <= 0 or n...
class AttributeObject: def __init__(self, *excluded_keys): self._excluded_keys = excluded_keys def __getattr__(self, item): return self._getattr(item) def __setattr__(self, key, value): if key == "_excluded_keys" or key in self._excluded_keys: super().__setattr__(key, v...
# -*- coding: utf-8 -*- import unittest import intelmq.lib.test as test from intelmq.bots.experts.cymru_whois.expert import CymruExpertBot EXAMPLE_INPUT = {"__type": "Event", "source.ip": "93.184.216.34", # example.com "time.observation": "2015-01-01T00:00:00+00:00", ...
# # Created as part of the StratusLab project (http://stratuslab.eu), # co-funded by the European Commission under the Grant Agreement # INFSO-RI-261552." # # Copyright (c) 2011, SixSq Sarl # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the Lice...
#!/usr/bin/env python """ Created on Thu Jul 16 09:46:37 2015 Author: Oren Freifeld Email: freifeld@csail.mit.edu """ import numpy as np from of.utils import * from pycuda.compiler import SourceModule from pycuda.driver import Context from of.gpu import * from scipy.linalg import expm krnl=""" __device__ inline d...
import socket import os import subprocess import csv import sys import re # Creates the /output directory def makeDir(): try: os.makedirs("./output") except OSError: pass # Verifies correct format of IP xxx.xxx.xxx.xxx def ipCheck(inputIP): ipregex = '\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9...
"""Implement configuration file parsing.""" # Copyright (C) 2015 Brad Cowie, Christopher Lorier and Joe Stringer. # Copyright (C) 2015 Research and Education Advanced Network New Zealand Ltd. # Copyright (C) 2015--2017 The Contributors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not u...
# -*- coding: utf-8 -*- # 使用tag matching的信息 # # Feature List: # T - 0/1 - q/u是否有完全match的tag # F - float - sum(q的tag u回答过,在所有回答中的占比) # F - float - sum(q的tag u拒绝过,在所有拒绝中的占比) import os import config from feature_abstract import FeatureGenerator from itertools import izip data_folder = '../data/' def load_tags(): ...
import base64 from collections import defaultdict from collections import namedtuple import datetime import io import json import time from absl import logging from tensorboard.backend.event_processing import event_multiplexer import tensorflow as tf import google.api_core.exceptions from google.cloud import bigquery ...
from django.http import HttpResponse, HttpResponseRedirect, HttpResponseBadRequest from django.shortcuts import render from django.views.generic import (ListView, DetailView, CreateView, UpdateView, DeleteView) from django.views.generic.edit import ModelFormMixin from django.core.urlresolvers import reverse_lazy fr...
import numpy as np import minipnm as mini class ArrayModel(object): global F, R, nO2, nH F = 96487 R = 8.314 nO2 = 4 nH = 2 def __init__(self, radii_array, node_spacing): ''' Define what the network looks like based on an array of radii and distances ''' ...
""" Was installing pygame and then trying to play the songs with it. Finished installing hg, next up is to install pygame really and see if it's playing. sudo pip install hg+http://bitbucket.org/pygame/pygame Also take a look at pyglet python module for playing mp3. """ import os from random import randint from time ...
from django.contrib.auth.models import AbstractBaseUser from django.db.models import TextField, ForeignKey, FloatField, DateTimeField, OneToOneField, ManyToManyField, EmailField, BooleanField from django.utils import timezone from yunity.models.abstract import MapItem, Conversation, Request from yunity.models.utils imp...
import itertools import os import logging import atexit import random import pickle import threading import inspect from datetime import datetime from concurrent.futures import Future from functools import partial import parsl import libsubmit from parsl.dataflow.error import * from parsl.dataflow.states import State...
import datetime import os import ujson from django.http import HttpResponse from django.test import override_settings from mock import MagicMock, patch from six.moves import urllib from typing import Any, Dict, List, Text from zerver.lib.actions import do_create_user from zerver.lib.test_classes import ZulipTestCase...