content stringlengths 4 20k |
|---|
from math import pi, sqrt
from itertools import chain
from state import noticeboard
from state.constants import accent_light
from olivia.basictypes import interpret_int
from meredith.box import Null
from IO import un
def _draw_broken_bar(cr, x1, y1, x2, color_rgba, top):
cr.set_source_rgba( * color_rgba)
... |
# encoding: utf-8
#
# utility functions for deformable cohesive elements
#
# burak er <EMAIL>
import math,random,doctest,geom,numpy
from yade import *
from yade.wrapper import *
from yade.utils import *
try: # use psyco if available
import psyco
psyco.full()
except ImportError: pass
from minieigen import *
# c++... |
import re
import stix2patterns.inspector
HASHES_REGEX = {
"MD5": (r"^[a-fA-F0-9]{32}$", "MD5"),
"MD6": (r"^[a-fA-F0-9]{32}|[a-fA-F0-9]{40}|[a-fA-F0-9]{56}|\
[a-fA-F0-9]{64}|[a-fA-F0-9]{96}|[a-fA-F0-9]{128}$", "MD6"),
"RIPEMD160": (r"^[a-fA-F0-9]{40}$", "RIPEMD-160"),
"SHA1": (r"^[a-fA-F0-9]{40}$",... |
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from rest_framework import status
from rest_framework.test import APITestCase, APIClient
from rest_api_example.custom import utilities
import json
class UserTests_v2(APITestCase):
fixtures = ['users.json','snippets.json']
d... |
""" Broadcom b43legacy driver installation """
import os
try:
from hardware.hardware import Hardware
except ImportError:
from hardware import Hardware
CLASS_NAME = "BroadcomB43Legacy"
CLASS_ID = "0x02"
VENDOR_ID = "0x14e4"
DEVICES = ['0x4301', '0x4306', '0x4320', '0x4324', '0x4325']
class BroadcomB43Legacy... |
"""Misc. exception related tests
Made for Jython.
"""
import sys
import unittest
from javatests import StackOverflowErrorTest
from test import test_support
class C:
def __str__(self):
raise Exception("E")
def __repr__(self):
raise Exception("S")
class ExceptionsTestCase(unittest.TestCase):
... |
"""PV Arch Module."""
from copy import deepcopy as _dcopy
from .client import ClientArchiver as _ClientArchiver
from .time import Time as _Time, get_time_intervals as _get_time_intervals
class PVDetails:
"""Archive PV Details."""
_field2type = {
'Number of elements': ('nelms', int),
'Units:... |
from indico.core.db import DBMgr
from MaKaC.conference import ConferenceHolder
from indico.util.console import conferenceHolderIterator
dbi = DBMgr.getInstance()
dbi.startRequest()
ENCODINGS = ['Windows-1252', 'iso-8859-1', 'latin1']
def fix(getter, setter):
txt = getter()
print "fixing... ",
for encodin... |
from collections import OrderedDict
from yaml.loader import Reader, Scanner, Parser, Composer, SafeConstructor, Resolver
from yaml.nodes import SequenceNode, MappingNode
from yaml.constructor import ConstructorError
class SafeOrderedDictConstructor(SafeConstructor):
def construct_yaml_omap(self, node):
... |
from .gen.webhooks import _Webhooks
class Webhooks(_Webhooks):
"""Webhooks resource"""
def create(self, params={}, **options):
"""Establishing a webhook is a two-part process. First, a simple HTTP POST
similar to any other resource creation. Since you could have multiple
webhooks we rec... |
"""``ndb`` is a library for Google Cloud Datastore.
It was originally included in the Google App Engine runtime as a "new"
version of the ``db`` API (hence ``ndb``).
.. autodata:: __version__
.. autodata:: __all__
"""
__version__ = "0.0.1.dev1"
"""Current ``ndb`` version."""
__all__ = [
"AutoBatcher",
"Conte... |
import pytest
from PIL import Image
import pyavagen
from pyavagen import generators, validators
class TestAvatar:
@pytest.mark.parametrize(
argnames="avatar_type,avatar_class,avatar_kwargs",
argvalues=[
(pyavagen.CHAR_AVATAR, pyavagen.CharAvatar, {'string': 'string'}),
(py... |
import warnings
from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union
from google.api_core import gapic_v1 # type: ignore
from google.api_core import grpc_helpers_async # type: ignore
from google.auth import credentials as ga_credentials # type: ignore
from google.auth.transport.grpc import... |
from django.db import models
from thing.models.character import Character
from thing.models.station import Station
from thing.models.system import System
class AssetSummary(models.Model):
character = models.ForeignKey(Character, on_delete=models.DO_NOTHING)
corporation_id = models.IntegerField(default=0)
... |
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.db.models.signals import pre_delete, post_save
from django.contrib.auth.models import User
from hub.models.pod import Pod
from hub.models.coalition import Coalition
from django.db.models import Q
class InvitationManager(m... |
import os.path as op
import warnings
from numpy.testing import assert_raises, assert_equal, assert_array_equal
from nose.tools import assert_true
from mne import read_events, Epochs, read_cov, pick_types
from mne.io import read_raw_fif
from mne.preprocessing import ICA, create_ecg_epochs, create_eog_epochs
from mne.u... |
import asyncio
import logging
import time
import hbmqtt.client
from . import AbstractActor
LOG = logging.getLogger('mahno.' + __name__)
def match_topic(mask, topic):
mask_parts = mask.split('/')
topic_parts = topic.split('/')
if mask_parts[0] == '#':
return True
if len(topic_parts) < len(... |
import time
import unittest
import config
import node
CHANNEL_INIT = 19
PANID_INIT = 0xface
CHANNEL_FINAL = 16
PANID_FINAL = 0xafce
COMMISSIONER = 1
LEADER = 2
ROUTER1 = 3
ED1 = 4
SED1 = 5
MTDS = [ED1, SED1]
class Cert_9_2_10_PendingPartition(unittest.TestCase):
def setUp(self):
self.simulator = confi... |
from __future__ import (absolute_import, division, print_function)
from os.path import isdir, exists, dirname, abspath, realpath, expanduser, sep
import string
import sys
ALLOWED_KEYS = string.ascii_letters + string.digits + string.punctuation
class Tags(object):
default_tag = '*'
def __init__(self, filena... |
"""Tests specific to `Sequential` model."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl.testing import parameterized
import numpy as np
from tensorflow.python import keras
from tensorflow.python.data.ops import dataset_ops
from tensorflow.pyt... |
from twisted.words.xish import domish
from uuid import uuid4
import types
class XmppInstance(object):
"""
Helper class to setup XMPP Observers
"""
def __init__(self):
self._observers = {}
def addObserver(self, elem, cb):
self._observers[elem] = cb
def removeObs... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
# This exploit template was generated via:
# $ pwn template ./vuln_newoverflow
from pwn import *
context.terminal = ['tmux', 'splitw', '-h']
# Set up pwntools for the correct architecture
exe = context.binary = ELF('./vuln')
# Many built-in settings can be controlled on... |
# -*- coding: UTF-8 -*-
"""
.. code-block:: gherkin
Given I setup the current values for active tags with:
| category | value |
| foo | xxx |
Then the following active tag combinations are enabled:
| tags | enabled? |
| @active.with_foo=xxx ... |
from spack import *
class Miniamr(MakefilePackage):
"""Proxy Application. 3D stencil calculation with
Adaptive Mesh Refinement (AMR)
"""
homepage = "https://mantevo.org"
url = "https://github.com/Mantevo/miniAMR/archive/v1.4.0.tar.gz"
tags = ['proxy-app', 'ecp-proxy-app']
versio... |
import arrow
from mendeley.models import Person
from test import load_config, get_user_session
def __delete_all(doc_resource):
for doc in doc_resource.iter():
doc.delete()
def delete_all_documents():
config = load_config()
if config['recordMode'] != 'none':
session = get_user_session()
... |
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Visitor.time_on_site'
db.add_column('tracking_visitor', 'time_on_site', self.gf('django.db... |
from msrest.serialization import Model
class KeyVaultKeyReference(Model):
"""Describes a reference to Key Vault Key.
All required parameters must be populated in order to send to Azure.
:param source_vault: Required. Fully qualified resource Id for the Key
Vault.
:type source_vault: ~azure.mgmt... |
from avango.menu.widget import WidgetBase
import avango.script
from avango.script import field_has_changed
import avango.menu.Preferences
import avango.osg
class Slider(WidgetBase):
Min = avango.SFFloat()
Max = avango.SFFloat()
Value = avango.SFFloat()
Step = avango.SFFloat()
SliderBarFilenames = a... |
import os
import unittest
from telemetry.core import browser_finder
from telemetry.core import extension_to_load
from telemetry.core import util
from telemetry.core.backends.chrome import cros_interface
from telemetry.unittest import options_for_unittests
class CrOSTestCase(unittest.TestCase):
def setUp(self):
... |
import heroespy
import pandas
import numpy as np
files = heroespy.sas.get_all_files(type="pyasf")
offset=[]
offsetx=[]
offsety=[]
targetx=[]
targety=[]
dates = []
angle = []
pointingx = []
pointingy = []
ctlaz = []
ctlel = []
file_list = files
i = 0
for f in file_list:
p = heroespy.sas.pyas(f)
offset.append(p... |
# -*- coding: utf-8 -*-
from functools import wraps
import logging
from psycopg2 import IntegrityError, OperationalError, errorcodes
import random
import threading
import time
import odoo
from odoo.exceptions import UserError, ValidationError, QWebException
from odoo.models import check_method_name
from odoo.tools.tr... |
#!/usr/bin/env python
"""
Problem 22 - Names Sources
Using names.txt, a 46K text file containing over five-thousand first names,
begin by sorting it into alphabetical order. Then working out the alphabetical
value for each name, multiply this value by its alphabetical position in the
list to obtain a name score.
F... |
import gtk
from baseview import BaseView
from widgets.storetreeview import StoreTreeView
# XXX: ASSUMPTION: The model to display is self.controller.store
# TODO: Add event handler for store controller's cursor-creation event, so that
# the store view can connect to the new cursor's "cursor-changed" event
# ... |
################################################################################
# Home page.
################################################################################
# Import Statements.
import sys
from PyQt4 import QtGui, QtCore
from core.repository import MovieRepository
from core.repository import Wait
f... |
#!/usr/bin/python
# vim:fileencoding=utf-8
'''
ns-lookup.py: Example shows how to lookup for NS records
Authors: Zdenek Vasicek (vasicek AT fit.vutbr.cz)
Marek Vavrusa (xvavru00 AT stud.fit.vutbr.cz)
Copyright (c) 2008. All rights reserved.
This software is open source.
Redistribution and use in s... |
# -*- coding: utf-8 -*-
"""Convert a BEL graph to HiPathia inputs.
Input
-----
SIF File
~~~~~~~~
- Text file with three columns separated by tabs.
- Each row represents an interaction in the pathway. First column is the source
node, third column the target node, and the second is the type of relation
between them... |
from firehose.model import (Analysis, Generator, Metadata,
DebianBinary, DebianSource)
from ethel.commands import PLUGINS, load_module
from ethel.client import get_proxy, checkout
from contextlib import contextmanager
from ethel.utils import tdir, cd, run_command
from ethel.config import lo... |
# -*- coding: utf-8 -*-
"""
zine.parsers
~~~~~~~~~~~~
This module holds the base parser information and the dict of
default parsers.
:copyright: (c) 2010 by the Zine Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from zine.i18n import lazy_gettext
from zin... |
import pytest
from unittest import mock
from django.core.urlresolvers import reverse
from .. import factories as f
from taiga.base.utils import json
pytestmark = pytest.mark.django_db
def test_invalid_project_export(client):
user = f.UserFactory.create()
client.login(user)
url = reverse("exporter-de... |
"""
Authentication utilities
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import os
from botocore.credentials import RefreshableCredentials
from botocore.session import get_session
from boto3 import Session
from c7n.version import version
from c7n.utils import get_retry
# ... |
"""A little script to parse TODO-like statements in source files.
The script parses all (supported) source files in a given path, tries to read
"TODO: do this and that"-like comments and writes these commands to the
terminal.
Source formats supported so far:
*.f90: free-form Fortran 90
*.c, *.h, *.cpp, *.hpp, *.cxx,... |
"""
Tests for TradingCalendarDispatcher.
"""
from zipline.errors import (
CalendarNameCollision,
CyclicCalendarAlias,
InvalidCalendarName,
)
from zipline.testing import ZiplineTestCase
from zipline.utils.calendars.calendar_utils import TradingCalendarDispatcher
from zipline.utils.calendars.exchange_calendar... |
from __future__ import absolute_import, division, print_function
import abc
import six
from cryptography import utils
from cryptography.exceptions import AlreadyFinalized
from cryptography.hazmat.bindings._padding import lib
@six.add_metaclass(abc.ABCMeta)
class PaddingContext(object):
@abc.abstra... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# vim: set et sw=4 ts=4 sts=4 ff=unix fenc=utf8:
# http://binux.me
# Created on 2014-11-21 22:32:35
import os
import json
import shutil
import unittest2 as unittest
from pyspider import run
from pyspider.libs.utils import ObjectDict
class TestRun(unittest.Test... |
"""
NLTK corpus readers. The modules in this package provide functions
that can be used to read corpus files in a variety of formats. These
functions can be used to read both the corpus files that are
distributed in the NLTK corpus package, and corpus files that are part
of external corpora.
Available Corpora
======... |
import numpy as np
from sklearn import metrics
import pandas
import tensorflow as tf
from tensorflow.models.rnn import rnn, rnn_cell
import skflow
### Training data
# Download dbpedia_csv.tar.gz from
# https://drive.google.com/folderview?id=0Bz8a_Dbh9Qhbfll6bVpmNUtUcFdjYmF2SEpmZUZUcVNiMUw1TWN6RDV3a0JHT3kxLVhVR2M
# U... |
"""
Quantum base exception handling.
"""
from quantum.openstack.common.exception import Error
from quantum.openstack.common.exception import OpenstackException
class QuantumException(OpenstackException):
"""Base Quantum Exception
To correctly use this class, inherit from it and define
a 'message' proper... |
import time
import numpy as np
import matplotlib.pyplot as plt
from IPython import display
def scatter_error_vs_time(estimator, ax):
losses = estimator.trials.losses()
ax.set_ylabel('Validation error rate')
ax.set_xlabel('Iteration')
ax.scatter(range(len(losses)), losses)
def plot_minvalid_vs_time(e... |
#Caoimhe Harvey
from skyscanner.skyscanner import Flights
flights_service = Flights('<Your API Key>')
# http://stackoverflow.com/questions/7047790/how-can-i-input-data-into-a-webpage-to-scrape-the-resulting-output-using-python
#QPX Express API Key
QAPI_key = 'AIzaSyC74E3Vu_dY0ZfxMIhQlXonC8yklxhVYqU'
#user_airports ... |
#!/usr/bin/env python
import os
import argparse
import numpy as np
import scipy.misc
import deeppy as dp
from matconvnet import vgg_net
from style_network import StyleNetwork
def weight_tuple(s):
try:
conv_idx, weight = map(float, s.split(','))
return conv_idx, weight
except:
raise a... |
from os.path import exists
import shutil
from tempfile import mkdtemp
from django.contrib.auth.models import User
import json
from projects.models import Project
from projects import tasks
from rtd_tests.utils import make_test_git
from rtd_tests.base import RTDTestCase
from rtd_tests.mocks.mock_api import MockApi
c... |
# -*- coding: utf-8 -*-
import biplist
import os.path
application = defines.get('app', 'dist/Syncplay.app')
appname = os.path.basename(application)
def icon_from_app(app_path):
plist_path = os.path.join(app_path, 'Contents', 'Info.plist')
plist = biplist.readPlist(plist_path)
icon_name = plist['CFBundl... |
import itertools # For grouping pair-end reads together
import sys, getopt # For parsing command line args
import os.path # For checking whether a given file exists
from itertools import combinations, product
# from Bio.Seq import reverse_complement # working with strings
import sys
class Tee: # log file generation
... |
# Inspired from http://stackoverflow.com/a/8759188/817766
from threading import currentThread
from meteography.dataset import DataSet
_request_cache = {}
_installed_middleware = False
def get_dataset_cache():
assert _installed_middleware, 'RequestCacheMiddleware not loaded'
return _request_cache[currentThr... |
from __future__ import print_function, division, absolute_import
import numpy as np
from scipy.stats import entropy
def scipy_kl_divergence(P, Q, scalar=True):
result = entropy(P.T, Q.T)
if scalar:
return np.sum(result)
else:
return result
def manual_kl_divergence(P, Q, scalar=True):
... |
#!/usr/bin/env python3
import unittest
from framework import VppTestCase, VppTestRunner
from vpp_sub_interface import VppDot1QSubint
from vpp_ip import DpoProto
from vpp_ip_route import VppIpRoute, VppRoutePath, VppMplsRoute, \
VppMplsLabel, VppMplsTable, FibPathProto
import scapy.compat
from scapy.packet import... |
#! /usr/bin/env python
import warnings
warnings.filterwarnings("ignore")
import sys,os
import os.path
import time
import subprocess
import numpy as np
import pyfits
import multiprocessing, Queue
import ctypes
import matplotlib.pyplot as plt
import scipy.interpolate
from astropy.convolution import convolve, convolve_f... |
"""
Unit tests for the stem.connection.authenticate function.
Under the covers the authentiate function really just translates a
PROTOCOLINFO response into authenticate_* calls, then does prioritization
on the exceptions if they all fail.
This monkey patches the various functions authenticate relies on to exercise
va... |
from __future__ import annotations # isort:skip
import pytest ; pytest
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
# Bokeh imports
from bokeh.core.has_props import HasProps
# Module under test... |
import pytest
from sentry.utils.csp import is_valid_csp_report
@pytest.mark.parametrize('report', (
{},
{'effective-directive': 'lolnotreal'},
{'effective-directive': 'style-src'},
{'effective-directive': 'style-src', 'blocked-uri': 'about'},
{'effective-directive': 'style-src', 'source-file': 'ch... |
import socket
import time
import struct
import sys # for exit
import random
from math import*
import numpy as np
def Main():
try:
host = 'localhost'
port = 3030
server = ('localhost', 3031)
except host.error:
print 'Failed to create host and port'
sys.exit()
try:
... |
#!/usr/bin/env python
import math,cmath
import collections
from numpy.linalg import norm
class hamiltonian(object):
"""
n_wann:
"""
def __init__(n_wann,n_R):
n_wann=0
n_R=0
degeneracy=dict()
HmnR=dict()
def ham_parser(filename='wannier90_hr.dat',cutoff=None):
"""
... |
"""
Provides various authentication policies.
"""
from __future__ import unicode_literals
import base64
from django.contrib.auth import authenticate
from django.core.exceptions import ImproperlyConfigured
from rest_framework import exceptions, HTTP_HEADER_ENCODING
from rest_framework.compat import CsrfViewMiddleware
f... |
import threading
from asyncio.futures import Future
from asyncio import get_event_loop, set_event_loop
from .guievents import GuiEventLoop
class TkEventLoop(GuiEventLoop):
_default_executor = None
def __init__(self, app):
super().__init__()
self.app = app
def mainloop(self):... |
import random
import os.path
import supybot.ircutils as utils
import supybot.callbacks as callbacks
try:
from supybot.i18n import PluginInternationalization
_ = PluginInternationalization('OnJoin')
except ImportError:
# Placeholder that allows to run the plugin on a bot
# without the i18n module
_ ... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import taiga.base.db.models.fields
class Migration(migrations.Migration):
dependencies = [
('projects', '0010_project_modules_config'),
]
operations = [
migrations.CreateModel(
... |
# -*- coding: utf-8 -*-
"""The SQLite blob file system implementation."""
from dfvfs.lib import definitions
from dfvfs.lib import errors
from dfvfs.path import sqlite_blob_path_spec
from dfvfs.resolver import resolver
from dfvfs.vfs import sqlite_blob_file_entry
from dfvfs.vfs import file_system
class SQLiteBlobFile... |
"""Tests for the Withings component."""
import datetime
import re
from typing import Any
from unittest.mock import MagicMock
from urllib.parse import urlparse
from aiohttp.test_utils import TestClient
import pytest
import requests_mock
from withings_api.common import NotifyAppli, NotifyListProfile, NotifyListResponse
... |
"""
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 agreed to in... |
#!/usr/bin/python
import json
import sys
G = None
XY2LL = None
NAME_SUFFIXES = [
' Forest Preserve',
' Forest Reserve',
' National Conservation Area',
' National Monument',
' NM',
' ONA',
' Outstanding Natural Area',
]
BLM_CA_NAME_MAP = {
'BAKERSFIELD FIELD OFFICE': 'Bakersfield Field Offi... |
import os
import sys
import cv2
import numpy as np
import math
import matplotlib.pyplot as plt
from BoW import getImmediateSubdirectories,getWordsInImages,getCentroids,computeHistrogram,computeHistrogramByLevel
if len(sys.argv)<3:
print "the dataset folder with subfolder name as label, not provied"
sys.exit(0)
if ... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
Classes to handle the .psl files
"""
import sys
import math
import re
from jcvi.formats.base import LineFile, must_open
from jcvi.apps.base import OptionParser, ActionDispatcher
class PslLine(object):
def __init__(self, sline):
args = sline.strip().split... |
# -*- coding: utf-8 -*-
"""
This provides the REST classes used to access the service.
"""
import json
import logging
from urllib.parse import urljoin
import requests
def get_log(e=None):
return logging.getLogger("{0}.{1}".format(__name__, e) if e else __name__)
class CloudSearchService(object):
"""This p... |
import sys
import optparse
import os.path
import shutil
import multiprocessing
import common
#------------------------------------------------------------------------------
# constants
#------------------------------------------------------------------------------
#----------------------------------------------------... |
from __future__ import print_function
import paddle.fluid as fluid
import paddle.fluid.core as core
import numpy as np
import unittest
import os
import sys
import math
def simple_fc_net():
img = fluid.layers.data(name='image', shape=[784], dtype='float32')
label = fluid.layers.data(name='label', shape=[1], d... |
import json
import socket
import eventlet
from eventlet import queue
from .base import ExitMessage
from .base import NodeListLockedException
class UDPMessenger(object):
def __init__(self, address, message_callback):
self._nodes = []
self._send_queue = queue.Queue()
self._message_callback... |
import string
import os
import re
import math
from SCons.Script import *
# -----------------------------------------------------------------------------
template_source = """
#include <xpcc/architecture/driver/accessor.hpp>
namespace bitmap
{
FLASH_STORAGE(uint8_t ${name}[]) =
{
${width}, ${height},
${array}
}... |
from getpass import getuser
from TCLIService import TCLIService
from ImpalaService import ImpalaHiveServer2Service
from thrift.transport.TSocket import TSocket
from thrift.transport.TTransport import TBufferedTransport
from thrift.protocol import TBinaryProtocol
from tests.common.impala_test_suite import ImpalaTestSuit... |
import argparse
import numpy
import copy
import mir3.data.feature_track as track
import mir3.module
class Diff(mir3.module.Module):
def get_help(self):
return """Differentiate (y[t] = x[t]-x[t-1]) a track"""
def build_arguments(self, parser):
parser.add_argument('infile', type=argparse.FileTy... |
import json
import logging
import os
from odoo import api, exceptions, models, tools
from odoo.modules.module import get_module_path
from ..addon_hash import addon_hash
PARAM_INSTALLED_CHECKSUMS = \
'module_auto_update.installed_checksums'
PARAM_EXCLUDE_PATTERNS = \
'module_auto_update.exclude_patterns'
DEFA... |
import hashlib
import uuid
from functools import wraps
def make_pass(password):
salt = uuid.uuid4().hex
hash_ = hashlib.sha512(password.encode('utf-8') +
salt.encode('utf-8')).hexdigest()
return salt, hash_
def check_pass(password, hash_, salt):
return hash_ == hashlib.sha... |
from __future__ import division
import hashlib
import random
import warnings
import p2pool
from p2pool.util import math, pack
def hash256(data):
return pack.IntType(256).unpack(hashlib.sha256(hashlib.sha256(data).digest()).digest())
def hash160(data):
if data == '04ffd03de44a6e11b9917f3a29f9443283d9871c9d74... |
"""Logging that uses pickles.
TODO: add log that logs to a file.
"""
# twisted imports
from twisted.spread import banana
from twisted.persisted import dirdbm
from twisted.internet import defer
# sibling imports
import base
class DirDBMLog:
"""Log pickles to DirDBM directory."""
__implements__ = base.IComm... |
{
'name': 'Email gateway - folders',
'summary': 'Attach mails in an IMAP folder to existing objects',
'version': '8.0.1.0.1',
'author': "Therp BV,Odoo Community Association (OCA)",
'website': 'http://www.therp.nl',
'license': 'AGPL-3',
"category": "Tools",
"depends": ['fetchmail'],
'... |
import os
from unittest import TestCase
from packstack.installer.processors import *
from ..test_base import PackstackTestCaseMixin
class ProcessorsTestCase(PackstackTestCaseMixin, TestCase):
def test_process_host(self):
"""Test packstack.installer.processors.process_host."""
proc_local = process... |
import pygtk
pygtk.require('2.0')
import gtk, gtk.glade
import subprocess, os, sys
class cbtest:
def __init__(self):
self.builder = gtk.Builder()
self.builder.add_from_file("AdvancedCoilEditor.glade")
self.window = self.builder.get_object("window1")
self.window.show()
stor... |
from meantemps import *
import urllib
import sys, os
import gzip
verbose = True
# Table of NOAA fields and their positions within the file.
NOAA_fields = {
'STN': [0, 6], # Station number (WMO/DATSAV3 number)
'WBAN': [7, 12], # WBAN number
'YEAR': [14, 18], # year
'MODA': [18... |
import email
import time
import pytest
from unittest import mock
from mitmproxy.net.http import Headers
from mitmproxy.net.http import Response
from mitmproxy.net.http.cookies import CookieAttrs
from mitmproxy.test.tutils import tresp
from .test_message import _test_passthrough_attr
class TestResponseData:
def t... |
import frappe, os
import unittest, email
test_records = frappe.get_test_records('Email Account')
from frappe.core.doctype.communication.communication import make
from frappe.desk.form.load import get_attachments
from frappe.utils.file_manager import delete_file_from_filesystem
class TestEmailAccount(unittest.TestCas... |
import Tkinter
import calendar
import time
import tkFont
import ttk
def sequence(*functions): # to run 2 or more functions on button click
for function in functions:
function()
def update(y, m, tx, curdate): # generate calendar with right colors
calstr = calendar.month(y, m)
tx.configure(state=Tki... |
"""
andandand: Health checker
Does not support (local) endpoints with dot separators for hypothetical
security reasons.
. is where the configuration comes from. So use uwsgi's --chdir2 or
--chroot to set . appropriately.
"""
from urllib2 import urlopen
import os
TIMEOUT = 2
def application(env, start_response):
... |
import numpy as np
import pytest
from pandas import DataFrame, Index, PeriodIndex, Series
import pandas._testing as tm
@pytest.mark.parametrize("by", ["A", "B", ["A", "B"]])
def test_size(df, by):
grouped = df.groupby(by=by)
result = grouped.size()
for key, group in grouped:
assert result[key] ==... |
from __future__ import absolute_import, division, print_function
import os
import argparse
import six
from . import events, configuration, singleton, director, scraper, __version__
from .output import out
from .util import internal_error, strlimit
class ArgumentParser(argparse.ArgumentParser):
"""Custom argumen... |
# -*- coding: utf-8 -*-
# Copyright 2008, 2009 Mr.Z-man
# This file is part of wikitools.
# wikitools 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 opt... |
#!/usr/bin/env python
##
## Interface for running MISO locally or on cluster
##
import os
import sys
import time
import glob
import misopy
from misopy.settings import Settings
from misopy.settings import miso_path as miso_settings_path
import misopy.hypothesis_test as ht
import misopy.as_events as as_events
import mi... |
from unittest import TestCase
import unittest
from equadratures import *
import numpy as np
from scipy.stats import skew, linregress, multivariate_normal
def fun(x):
return 5.0 * x[0] ** 3 - x[0] * x[1] + 3.0 * x[1] * x[2] ** 3 + 32.0
class TestF(TestCase):
def test_nataf(self):
np.random.seed(1)
... |
"""
===================================================================
Compute MNE inverse solution on evoked data in a mixed source space
===================================================================
Create a mixed source space and compute an MNE inverse solution on an
evoked dataset.
"""
#
# License: BSD (3-c... |
import utils
import sqlite3
from PyQt4.QtGui import *
from query_window import QueryWindow
class MainWindow:
def __init__(self, geometry, title):
self.__create_window_widget(geometry, title)
self.__create_ui()
self.update()
def __create_window_widget(self, geometry, title):
self.__qt_widget_object = QWidget... |
"""
Holds the X{event} structures in Lyntin. All events inherit from
Event. This is pretty standard, nothing really exciting here.
Each event class implements the execute function which gets called
by the event handler thread when it pulls the event object off the
event queue. You can use the __init__ function to i... |
#!/usr/bin/env python
# -*- Mode: Python; py-indent-offset: 4 -*-
#
# This litte script outputs the C doc comments to an XML format.
# So far it's only used by gtkmm (The C++ bindings). Murray Cumming.
# Usage example:
# # ./docextract_to_xml.py -s /gnome/head/cvs/gtk+/gtk/ -s /gnome/head/cvs/gtk+/docs/reference/gtk/tm... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.