repo_name stringlengths 5 100 | path stringlengths 4 231 | language stringclasses 1
value | license stringclasses 15
values | size int64 6 947k | score float64 0 0.34 | prefix stringlengths 0 8.16k | middle stringlengths 3 512 | suffix stringlengths 0 8.17k |
|---|---|---|---|---|---|---|---|---|
stvstnfrd/edx-platform | openedx/core/djangoapps/video_pipeline/migrations/0001_initial.py | Python | agpl-3.0 | 1,352 | 0.005178 | # -*- coding: utf-8 -*-
from django.db import migrations, models
import django.db.models.deletion
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel... | ed by')),
| ],
options={
'ordering': ('-change_date',),
'abstract': False,
},
),
]
|
zheguang/voltdb | lib/python/voltcli/cli.py | Python | agpl-3.0 | 28,839 | 0.008808 | # This file is part of VoltDB.
# Copyright (C) 2008-2014 VoltDB Inc.
#
# This file contains original code and/or modifications of original code.
# Any modifications made by VoltDB Inc. are licensed under the following
# terms and conditions:
#
# Permission is hereby granted, free of charge, to any person obtaining
# a... | (self.short_opt, self.long_opt) if a is not None]
def get_dest(self):
if 'dest' not in self.kwargs:
utility.abort('%s must specify a "dest" property.' % self.__class__.__name__)
return self.kwargs['dest']
def get_default(self):
return self.kwargs.get('default', None)
... | process_value(self, value):
# Hook for massaging the option instance value. Default to NOP.
return value
def __str__(self):
return '%s(%s/%s %s)' % (self.__class__.__name__,
self.short_opt, self.long_opt, self.kwargs)
def __cmp__(self, other):
#... |
Makeystreet/makeystreet | woot/apps/catalog/migrations/0036_auto__add_likecfiitem__add_cfistoreitem.py | Python | apache-2.0 | 27,149 | 0.007219 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'LikeCfiItem'
db.create_table(u'catalog_likecfiitem', (
... | 'True', 'blank': 'True'})
},
'catalog.emailcollect': {
'Meta': {'object_name': 'EmailCol | lect'},
'email': ('django.db.models.fields.EmailField', [], {'max_length': '30'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
},
'catalog.image': {
'Meta': {'object_name': 'Image', '_ormbases': ['catalog.BaseModel']},
u'basem... |
kazuyaujihara/osra_vs | GraphicsMagick/scripts/format_c_api_doc.py | Python | gpl-2.0 | 21,967 | 0.005281 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: ts=4:sw=4:expandtab:
# Copyright 2008 Mark Mitchell
# License: see __license__ below.
__doc__ = """
Reads a GraphicsMagick source file and parses the specially formatted
comment blocks which precede each function and writes the information
obtained from the commen... | %
# % X A n i m a t e B a c k g r o u n d I m a g e %
# Lines starting with '+' are pri | vate APIs which should not appear in
# in the output.
re_func_title = re.compile(r'^[+|%]\s+((\w )+)\s*%')
def proto_pretty(line):
"""fixes up inconsistent spaces in C function prototypes"""
line = re.sub(r',', ' , ', line)
line = re.sub(r'\(', ' ( ', line)
line = re.sub(r'\)', ' ) ', line)
l... |
icomms/rapidsms | lib/rapidsms/message.py | Python | lgpl-3.0 | 4,140 | 0.008454 | #!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4 encoding=utf-8
import copy
from rapidsms.connection import Connection
from rapidsms.person import Person
from datetime import datetime
from rapidsms import utils
class StatusCodes:
'''Enum for representing status types of a message or response.'''
NONE = "N... | target = self.connection.fork(identity)
if text is None: text = self.text
message = type(self)(connection=target, text=text)
self.responses.append(message)
return True
else:
return False
class EmailMessage(Message):
"""Email version of... | n
be consumed by email backends/apps."""
def __init__(self, connection=None, text=None, person=None, date=None,
subject=None, mime_type="text/plain"):
super(EmailMessage, self).__init__(connection=connection, text=text,
person=person, dat... |
aspuru-guzik-group/mission_control | mc/houston/utils.py | Python | apache-2.0 | 6,799 | 0.000147 | from pathlib import Path
from jobman.jobman import JobMan
from mc.clients.job_record_client import JobRecordClient
from mc.clients.flow_record_client import FlowRecordClient
from mc.flows.flow_engine import FlowEngine
from mc.db.db import Db
from mc.runners.flow_runner import FlowRunner
from mc.runners.jobman_job_run... | ject):
JOBS_SUBDIRS = ['pending', 'queued', 'executed', 'archive']
def __init__(self, houston=None):
self.houston = houston
@property
def cfg(self): return self.houston.cfg
@property
def db(self):
if not hasattr(self, '_db'):
self._db = self.generate_db(db_ur | i=self.cfg['MC_DB_URI'])
return self._db
def generate_db(self, db_uri=None, schema=None):
return Db(db_uri=db_uri, schema=schema)
@db.setter
def db(self, value): self._subcommands = value
def ensure_queues(self):
self.ensure_queue(queue_cfg=self.cfg['FLOW_QUEUE'])
self... |
cvandeplas/plaso | plaso/parsers/winprefetch_test.py | Python | apache-2.0 | 17,693 | 0.000396 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2013 The Plaso Project Authors.
# Please see the AUTHORS file for details on individual 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 L... | ests for the Windows prefetch parser."""
def setUp(self):
"""Sets up the needed objects used throughout the test."""
self._parser = winprefetch.WinPrefetchParser()
def testParse17(self):
"""Tests the Parse function on a version 17 Prefetch file."""
test_file = self._GetTestFilePath(['CMD.EXE-087B4... | .pf'])
event_queue_consumer = self._ParseFile(self._parser, test_file)
event_objects = self._GetEventObjectsFromQueue(event_queue_consumer)
self.assertEquals(len(event_objects), 2)
# The prefetch last run event.
event_object = event_objects[1]
self.assertEquals(event_object.version, 17)
e... |
edrex/minichess | minichess/eval.py | Python | gpl-2.0 | 605 | 0.028099 | from data import *
# white
pvals = {
PAWN: 100,\
BISH | OP: 300,\
KNIGHT: 300,\
ROOK: 500,\
QUEEN: 900,\
-PAWN: -100,\
-BISHOP: -300,\
-KNIGHT: -300,\
-ROOK: -500,\
-QUEEN: -900,\
KING: 10000,\
-KING: -10000,\
EMPTY: 0,\
}
def value(state):
return state.som * sum(pvals[state.board[cord]] for cord in fcords)
def game_lost... | board.index(KING*state.som)
return False
except ValueError:
return True
def game_drawn(state):
if state.turn >= 80:
return True
else:
return False
|
intel-analytics/analytics-zoo | pyzoo/zoo/pipeline/api/keras/models.py | Python | apache-2.0 | 3,962 | 0.000757 | #
# Copyright 2018 Analytics Zoo 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... | input_shape
else:
input_shapes = self.get_output_shape()
model = model.create(remove_batch(input_shapes))
self | .value.add(model.value)
return self
@staticmethod
def from_jvalue(jvalue, bigdl_type="float"):
"""
Create a Python Model base on the given java value
:param jvalue: Java object create by Py4j
:return: A Python Model
"""
model = Sequential(jvalue=jvalue)
... |
brain-research/acai | lib/layers.py | Python | apache-2.0 | 3,324 | 0 | # Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# y | ou may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://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 O... | layers.
Low-level primitives such as custom convolution with custom initialization.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import functools
import tensorflow as tf
def downscale2d(x, n):
"""Box downscaling.
Args:
x: 4D tensor i... |
yahya-idriss/Python-Personal-assistant | start.py | Python | mit | 4,231 | 0.038762 | #! /usr/bin/env python
import os
from function import function
import speech_recognition as sr
from server import EmailServer
from pygame import mixer
from subprocess import call
from send import SendEmail
from detect import face_rec
from face import face_detect
from trainer import face_train
mixer.init(... | = get_speech()
if "yes" in speech.lower():
conn.import_contact | ()
rec = face_rec()
if rec.rec() != "0":
computername = rec.rec()
else:
call(["espeak","-s","160","This is Your First Time using me"])
call(["espeak","-s","160","Do you want to create a new account?"])
speech = get_speech()
if "yes" in speech.lower() or "yeah" in speech.low... |
andrewnsk/dorokhin.moscow | imageboard/admin.py | Python | mit | 990 | 0.004082 | from django.contrib import admin
from image_cropping i | mport ImageCroppingMixin
from imageboard.models import Image
class ImageAdmin(ImageCroppingMixin, admin.ModelAdmin):
list_display = ['__str__', 'tag_list', 'owner', 'created', 'updated', 'visible', 'get_image_url']
list_filter = ['owner', 'visible', 'created', 'updated']
list_editable = ['visible']
d... | eAdmin, self).get_queryset(request).prefetch_related('tags')
def tag_list(self, obj):
return u", ".join(o.name for o in obj.tags.all())
def get_image_url(self, obj):
return '<a href="{0}"><img src="{0}" width="100px"></a>'.format(obj.img.url)
get_image_url.allow_tags = True
get_image_... |
dpcrook/timetemp | install/Archive/logging_sparkfun.py | Python | mit | 5,870 | 0.005281 | #!/usr/bin/python
# Google Spreadsheet BMP Sensor Data-logging Example
# Depends on the 'gspread' package being insta | lled. If you have pip installed
# execute:
# sudo pip install gspread
# Copyright (c) 2014 Adafruit Industries
# Author: Tony DiCola
# 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 witho... | 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 NO... |
ssmdevelopers/jklhoods | streamtweet.py | Python | gpl-2.0 | 1,889 | 0.022763 | from tweepy import Stream
from tweepy import OAuthHandler
from tweepy.streaming import StreamListener
import sqlite3 as sql3
import time
import json
import time
from dateti | me import datetime
import os
#import sys
#consumer key, consumer secret, access token, access secre | t.
ckey= 'TWITTER_CKEY' in os.environ
csecret= 'TWITTER_CSECRET' in os.environ
atoken= 'TWITTER_TOKEN'in os.environ
asecret= 'TWITTER_SECRET' in os.environ
new = 0
con = sql3.connect("tweets.db")
cur = con.cursor()
def newTweets():
if new == 0:
return
class Listener(StreamListener):
def on_... |
wdzhou/mantid | Testing/SystemTests/tests/analysis/WishCalibrate.py | Python | gpl-3.0 | 8,447 | 0.003315 | from __future__ import (absolute_import, division, print_function)
import filecmp
import numpy as np
import os
import stresstesting
import tempfile
import mantid.simpleapi as mantid
import mantid.kernel as kernel
from tube_calib_fit_params import TubeCalibFitParams
from tube_calib import getCalibratedPixelPositions, ... | ak centers across all tub | es.
Tubes are defined as have a bad fit if the absolute difference
between the fitted peak centers for a specific tube and the
mean of the fitted peak centers for all tubes differ more than
the threshold parameter.
@param peakTable: the table containing fitt... |
gpaOliveira/SuperDiffer | SuperDiffer/routes.py | Python | mit | 2,533 | 0.013423 | from SuperDiffer import app, db
from SuperDiffer.id import controllers as ID
from flask import Flask, render_template, request, abort, jsonify
import json,base64,pdb
"""Routes to allow clients to add left and right base64 encoded on JSON values and fetch their diff"""
#References: https://blog.miguelgrinberg.com/post... | .route('/v1/diff/<int: | id>/right', methods=['POST'])
def add_right_to_id(id):
"""Add a JSON base64 value (in the format: {"data":"base64value"}) to the right descriptor of a given ID"""
return _add_data_to_id_description(id, "right", request.json)
def _is_base64(value):
"""Returns true only if value only has base64 chars (A-Z,a-... |
araisrobo/linuxcnc | configs/gladevcp/probe/probe.py | Python | lgpl-2.1 | 7,589 | 0.011859 | #!/usr/bin/env python
# vim: sts=4 sw=4 et
# This is a component of EMC
# probe.py Copyright 2010 Michael Haberler
#
#
# 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 versi... | allback for 'Reset to defaults' button
currently unused |
'''
self.ini.create_default_ini()
self.ini.restore_state(self)
def __init__(self, halcomp,builder,useropts):
self.halcomp = halcomp
self.builder = builder
self.ini_filename = __name__ + '.ini'
self.defaults = { IniFile.vars: dict(),
... |
jmvrbanac/barbican | bin/barbican-keystone-listener.py | Python | apache-2.0 | 2,403 | 0.002913 | #!/usr/bin/env python
# Copyright 2014 Hewlett-Packard Development Company, L.P.
#
# 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 ... | NF, queue.KS_NOTIFICATIONS_GRP_NAME), 'enable'):
service.launch(
keystone_listener.MessageServer(CONF)
).wait()
else:
| LOG.info("Exiting as Barbican Keystone listener is not enabled...")
except RuntimeError as e:
fail(1, e)
|
AltSchool/django-allauth | allauth/socialaccount/providers/fake/views.py | Python | mit | 910 | 0 | import requests
from allauth.socialaccount.providers.oauth2.views import (
OAuth2Adapter,
OAuth2CallbackView,
OAuth2LoginView,
)
from .provider import FakeProvider
class FakeOAuth2Adapter(OAuth2Adapter):
provider_id = FakeProvider.id
access_token_url = 'https://localhost/o/oauth2/token'
auth... | profile_url = 'https://localhost/oauth2/v1/userinfo'
def complete_login(self, request, app, token, **kwargs):
resp = requests.get(self.profile_url,
params={'access_token': token.token,
'alt': 'json'})
extra_data = resp.json()
... | ogin = OAuth2LoginView.adapter_view(FakeOAuth2Adapter)
oauth2_callback = OAuth2CallbackView.adapter_view(FakeOAuth2Adapter)
|
heysion/deepin-auto-build | dab/webui/taskctrl.py | Python | gpl-3.0 | 2,297 | 0.01219 | #!/usr/bin/python
# -*- coding: utf-8 -*-
'''
@date: 2017-04-06
@author: Heysion Yuan
@copyright: 2017, Heysion Yuan <heysions@gmail.com>
@license: GPLv3
'''
from dab.webui import WebBase
from dab.core.db.models import Task
class TaskIndex(WebBase):
def get(self):
dataset = self.get_task_top_all()
... | def post(self):
req_data = { k: self.get_argument(k) for k in self.request.arguments }
if not ("arches" in req_data.keys()):
self.render("404.html")
if not ("name" in req_data and req_data["name"] is not None) :
self.render("404.html")
self.sa | ve_new_task(req_data)
self.render("/taskindex")
def save_new_task(self,data):
new_task = Task.select(Task.name).where(Task.name==data["name"])
if not new_task :
new_task = Task.create(name=data["name"],
suite=data["suite"],
... |
DIRACGrid/DIRAC | src/DIRAC/DataManagementSystem/Service/DataIntegrityHandler.py | Python | gpl-3.0 | 6,511 | 0.004147 | """
:mod: DataIntegrityHandler
.. module: DataIntegrityHandler
:synopsis: DataIntegrityHandler is the implementation of the Data Integrity service in
the DISET framework
"""
# from DIRAC
from DIRAC import S_OK
from DIRAC.Core.DISET.RequestHandler import RequestHandler
from DIRAC.DataManagementSystem.DB.DataInte... | .log.info("DataIntegrityHandler.getPrognosisProblematics: Getting files with %s prognosis." % prognosis)
res = self.dataIntegrityDB.getPrognosisProblematics(prognosis)
if not res["OK"]:
self.log.error(
"DataIntegrityHandler.getPrognosisProblematics: Failed to get prognosis fi... | essage"]
)
return res
types_setProblematicStatus = [int, str]
def export_setProblematicStatus(self, fileID, status):
"""Update the status of the problematics with the provided fileID"""
self.log.info("DataIntegrityHandler.setProblematicStatus: Setting file %s status to %s."... |
jolevq/odoopub | extra-addons/customize/res_company.py | Python | agpl-3.0 | 1,213 | 0.003298 | # -*- coding: utf-8 -*-
#################### | ##########################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2014 Cubic ERP SAC (<http://cubicerp.com>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# | published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ... |
dnaextrim/django_adminlte_x | adminlte/static/plugins/datatables/extensions/ColReorder/examples/predefined.html.py | Python | mit | 16,794 | 0.037752 | XXXXXXXXX XXXXX
XXXXXX
XXXXXX
XXXXX XXXXXXXXXXXXXXXX
XXXXX XXXXXXXXXXXXX XXXXX XXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXX XXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXX XXXXXXX X XXXXXXXXXX XXXXXX XXXXXXXXXXXXXXXX
XXXXX XXXXXXXXXXXXXXXX XXXXXXXXXXXXXXX ... | X
XXXXXXXXXXXXXXX
XXXXXXXXXXX
XXXXXXXXXXXXXXXXXXX
| XXXXXXXXXXXXXXXXXXX
XXXXX
XXXX
XXXXXXXXX XXXXXXXXXX
XXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXX
XXXXXXXXXXX
XXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXX
XXXXX
XXXX
XXXXXXXXXXXX XXXXXXXXXX
XXXXXXXXXXXX XXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXX
XXXXXXXXXXX
... |
Seek/LaTechNumeric | linearalg/linalg.py | Python | mit | 8,666 | 0.006577 | import numpy as np
import pdb
from scipy import linalg as splinalg
# A = np.array([
# [1, 1, -2, 1, 3, -1],
# [2, -1, 1, 2, 1, -3],
# [1, 3, -3, -1, 2, 1],
# [5, 2, -1, -1, 2, 1],
# [-3, -1, 2, 3, 1, 3],
# [4, 3, 1, -6, -3, -2]
# ], dtype=float)
# b = np.array([4, 20, -15, -3, 16, -27], dtype=fl... | 1], -1]
# Now we solve the remaining equations
# dim-2 starts means we begin at second row from the end and go until the 0th row
for i in range(dim - 2, | -1, -1):
# Grab the corresponding b value
sum = b[pv[i]]
# Now we sum from the last column (dim -1 ) to the current column (i-1)
for j in range(dim - 1, i - 1, -1):
sum -= x[j] * A[pv[i], j]
x[i] = sum / A[pv[i], i]
return x
def lu_factor(A, tol, err):
"""Ret... |
suutari-ai/shoop | shuup/admin/modules/users/views/permissions.py | Python | agpl-3.0 | 5,257 | 0.001332 | # -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2017, Shoop Commerce Ltd. All rights reserved.
#
# This source code is licensed under the OSL-3.0 license found in the
# LICENSE file in the root directory of this source tree.
from __future__ import unicode_literals
from django import forms
... | is user belongs to. "
"Permission groups are configured through Contacts - Permission Groups."
)
)
permission_groups_field.widget.choices = [(group.pk, force_text(group)) for group in initial_groups]
self.fields["permission_groups"] = permission_groups_field
def ... | lse:
return []
def clean_old_password(self):
"""
Validates that the old_password field is correct.
"""
old_password = self.cleaned_data["old_password"]
if not self.changing_user.check_password(old_password):
raise forms.ValidationError(
... |
mr-uuid/snippets | python/sockets/servers/blocking.py | Python | mit | 1,330 | 0.001504 | import socket
import random
import time
# A blocking server that simply sends hello to anyone who conncets to it
def blocking_server(bind='0.0.0.0', port=8080, queued_connections=5):
"""
This sets up a blocking socket. We will be listening for incomming
conncetions
"""
sock = socket.socket(socket... | cept a connection. The socket must be bound to an address and listening
# for c | onnections. The return value is a pair (conn, address) where conn is
# a new socket object usable to send and receive data on the connection,
# and address is the address bound to the socket on the other end of the
# connection.
sock, addr = server.accept() # this is a blocking call
time.sleep(rand... |
CZ-NIC/knot | tests-extra/tests/ddns/forward/test.py | Python | gpl-3.0 | 777 | 0 | #!/usr/bin/env python3
'''Test for DDNS forwarding'''
from dnstest.test import Test
t = Test()
master = t.server("knot")
slave = t.server("knot")
zone = t.zone("example.com.")
t.link(zone, master, slave, ddns=True)
t.start()
master.zones_wait(zone)
seri = slave.zones_wait(zon | e)
# OK
update = slave.update(zone)
update.add("forwarded.example.com.", 1, "TXT", "forwarded")
update.send("NOERROR")
resp = master.dig("forwarded.example.com.", "TXT")
resp.check("forwarded")
slave.zones_wait(zone, seri)
t.xfr_diff(master, slave, zone)
# NAME out of zone
update = slave.update(zone)
update.add("forw... | f(master, slave, zone)
t.end()
|
mazaclub/tate-server | src/networks.py | Python | agpl-3.0 | 413 | 0.004843 | # Main network and testnet3 definitions
params = {
'bitcoin_main': {
'pubkey_address': 50,
'script_address': 9,
'genesis_hash': '00000c7c73d8ce604178dae13f0fc6ec0be3275614366d44b1b4b5 | c6e238c60c'
},
'bitcoin_tes | t': {
'pubkey_address': 88,
'script_address': 188,
'genesis_hash': '000003ae7f631de18a457fa4fa078e6fa8aff38e258458f8189810de5d62cede'
}
}
|
matham/sniffer | sniffer/__init__.py | Python | mit | 97 | 0 | '''
'''
__ver | sion__ = '0.1-dev'
device_config_name = 'Devices'
exp_config_name = 'experimen | t'
|
0101a/Valid-IP-checker- | Ipv4.py | Python | gpl-2.0 | 918 | 0.051198 | # Valid-IP-checker-
#This program check whether a given IP is valid or not IPV4
def ip_checkv4(ip):
parts=ip.split(".")
if len(parts)<4 or len(parts)>4:
return "invalid IP length should be 4 not greater or less than 4"
else:
while len(parts)== 4:
a=int(parts[0])
b=int(parts[1])
c=int(parts[2])
d=int(... | return "should not be 255 or greater than 255 or less than 0 A"
elif b>=255 or b<0:
return "should not be 255 or greater than 255 or less than 0 B"
elif c>=255 or c<0:
retu | rn "should not be 255 or greater than 255 or less than 0 C"
elif d>=255 or c<0:
return "should not be 255 or greater than 255 or less than 0 D"
else:
return "Valid IP address ", ip
p=raw_input("Enter IP address")
print ip_checkv4(p)
|
rsvip/Django | django/forms/models.py | Python | bsd-3-clause | 55,046 | 0.001508 | """
Helper functions for creating Form classes from Django models
and database field objects.
"""
from __future__ import unicode_literals
from collections import OrderedDict
from itertools import chain
from django.core.exceptions import (
NON_FIELD_ERRORS, FieldError, ImproperlyConfigured, ValidationError,
)
fro... | fields will be included in the returned dict.
``exclude`` is an optional list of field names. If provided, the named
fields will be excluded from the returned dict, even if they are listed in
the ``fie | lds`` argument.
"""
# avoid a circular import
from django.db.models.fields.related import ManyToManyField
opts = instance._meta
data = {}
for f in chain(opts.concrete_fields, opts.virtual_fields, opts.many_to_many):
if not getattr(f, 'editable', False):
continue
if fi... |
Yam-cn/potato | stratlib/thrSMA.py | Python | apache-2.0 | 5,091 | 0.004953 | # -*- coding: utf-8 -*-
"""
Created on Tue Nov 03 13:06:56 2015
@author: Eunice
"""
if __name__ == '__main__':
import sys
sys.path.append("..")
from engine import bar
# 以上模块仅测试用
from engine.broker.fillstrategy import DefaultStrategy
from engine.broker.backtesting import TradePercentage
from engine import ... | self.__circ and m2 >= self.__circ:
return True
def sellCon1(self):
if cross.cross_below(self.__ma1, self.__ma2) > 0:
return True
def onBars(self, bars):
# If a position was not opened, check if we should enter a long position.
if self.__ma2[-1]is None:
... | self.__position.exitMarket()
#self.info("sell %s" % (bars.getDateTime()))
if self.__position is None:
if self.buyCon1() and self.buyCon2():
shares = int(self.getBroker().getCash() * 0.2 / bars[self.__instrument].getPrice())
self.__position =... |
viaregio/django-simple-captcha | captcha/views.py | Python | mit | 4,373 | 0.002058 | from captcha.conf import settings
from captcha.helpers import captcha_image_url
from captcha.models import CaptchaStore
from django.http import HttpResponse, Http404
from django.shortcuts import get_object_or_404
import random
import re
import tempfile
import os
import subprocess
try:
from cStringIO import StringI... | y=key)
text = store.challenge
if settings.CAPTCHA_FONT_PATH.lower().strip().endswith('ttf'):
font = ImageFont.truetype(settings.CAPTCHA_FONT_PATH, settings.CAPTCHA_FONT_SIZE * scale)
else:
font = ImageFont.load(settings.CAPTCHA_FONT_PATH)
size = getsize(font, text)
size = (size[0] ... | except:
PIL_VERSION = 116
xpos = 2
charlist = []
for char in text:
if char in settings.CAPTCHA_PUNCTUATION and len(charlist) >= 1:
charlist[-1] += char
else:
charlist.append(char)
for char in charlist:
fgimage = Image.new('RGB', size, settings.C... |
Freso/listenbrainz-server | listenbrainz/db/dump.py | Python | gpl-2.0 | 24,816 | 0.001531 | """ This module contains data dump creation and import functions.
Read more about the data dumps in our documentation here:
https://listenbrainz.readthedocs.io/en/production/dev/listenbrainz-dumps.html
"""
# listenbrainz-server - Server for the ListenBrainz project
#
# Copyright (C) 2017 MetaBrainz Foundation Inc.
#
... | ive_name}.tar.xz'.format(
archive_name=archive_name,
))
with open(archive_path, 'w') as archive:
pxz_command = ['pxz', '--compress',
'-T{threads}'.format(threads=threads)]
pxz = subprocess.Popen(
pxz_command, stdin=subprocess.PIPE, stdout=archive)
... | t |
dask/distributed | distributed/queues.py | Python | bsd-3-clause | 9,788 | 0.001124 | import asyncio
import logging
import uuid
from collections import defaultdict
from dask.utils import parse_timedelta, stringify
from .client import Client, Future
from .worker import get_client, get_worker
logger = logging.getLogger(__name__)
class QueueExtension:
"""An extension for the scheduler to manage qu... | ptional)
Client used for communication with the scheduler.
If not given, the default global client will be used.
maxsize: int (optional)
Number of items allowed in the queue. If 0 (the default), the queue
size is unbounded.
Examples
--------
>>> from dask.distributed imp... | ue.put(future) # doctest: +SKIP
See Also
--------
Variable: shared variable between clients
"""
def __init__(self, name=None, client=None, maxsize=0):
try:
self.client = client or Client.current()
except ValueError:
# Initialise new client
self.... |
sparkfun/usb-scale | scaleServer.py | Python | gpl-3.0 | 3,755 | 0.001065 | #! /usr/bin/env python
# This will run as a production ready server if something like eventlet is installed
import argparse
import json
import os
import threading
import time
import sys
from gevent import ssl
from geventwebsocket import WebSocketServer, WebSocketApplication, Resource
from readscale import set_scale... | cale is connected and not in use by another process")
sys.stdout.flush()
def on_open(self):
print "Connected!"
global clients
if clients:
clients += 1
return
clients += 1
self.send_weight()
def on_message(self, message, *args, **kwarg... | print reason
def send_weight(self, reschedule=0.2):
"""
broadcast the weight on the scale to listeners
:param weight: dictionary with
:param reschedule: time delay to reschedule the function
:return: None
"""
global scale
fakeweight = {
... |
vodkina/GlobaLeaks | backend/globaleaks/tests/jobs/test_notification_sched.py | Python | agpl-3.0 | 1,811 | 0.000552 | from twisted.internet.defer import inlineCallbacks, fail, succeed
from globaleaks import models
from globaleaks.orm import transact
from globaleaks.tests import helpers
from globaleaks.jobs.delivery_sched import DeliverySchedule
from globaleaks.jobs.notification_sched import NotificationSchedule, MailGenerator
cla... | ation_schedule_success(self):
count = yield self.get_scheduled_email_count()
self.assertEqual(count, 0)
yield DeliverySchedule().run()
notification_schedule = NotificationSchedule()
notification_schedule.skip_sleep = Tru | e
yield notification_schedule.run()
count = yield self.get_scheduled_email_count()
self.assertEqual(count, 0)
@inlineCallbacks
def test_notification_schedule_failure(self):
count = yield self.get_scheduled_email_count()
self.assertEqual(count, 0)
yield Delivery... |
ChinaMassClouds/copenstack-server | openstack/src/ceilometer-2014.2.2/ceilometer/tests/ipmi/notifications/ipmi_test_data.py | Python | gpl-2.0 | 30,224 | 0 | #
# Copyright 2014 Red Hat, Inc
#
# Author: Chris Dent <chdent@redhat.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 of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... | eading': '27 (+/- 0.500) degrees C',
'Entity ID': '20.4 (Power Module)',
'Assertions Enabled': 'unc+ ucr+ unr+',
'Positive Hysteresis': '4.000',
'Assertion Events': '',
'Upper non-critical': '95.000',
'Event Message Control': 'Per-threshold',
'Upper non-recoverabl... | 'Maximum sensor range': 'Unspecified',
'Sensor Type (Analog)': 'Temperature',
'Readable Thresholds': 'unc ucr unr',
'Negative Hysteresis': 'Unspecified',
'Threshold Read Mask': 'unc ucr unr',
'Upper critical': '100.000',
'Sensor ID': 'DIMM CD VR Temp (0x39)',
... |
danieljb/django-hybrid-filefield | hybrid_filefield/forms.py | Python | gpl-3.0 | 3,393 | 0.001768 | # - | *- coding: utf-8 -*-
import os
import re
from django.conf import settings
from django.core import validators
from django.core.exceptions import ValidationError
from django.forms.util import ErrorList
from django.forms.fields import MultiValueField, FilePathField, \
FileField, CharField
from django.utils.translati... | eld):
widget = FileSelectOrUploadWidget
default_error_messages = {
'optional_required': _('At least one value is required.'),
}
def __init__(self, upload_to='', path='', match='',
recursive=False, widget=None, initial=None,
optional=False, *args, **kwargs):
self.upload_... |
has2k1/plotnine | plotnine/positions/position_nudge.py | Python | gpl-2.0 | 698 | 0 | from .position import position
class position_nudge(position):
"""
Nudge points
Useful to nudge labels away from the points
being labels.
Parameters
----------
x : float
Horizontal nudge
y : float
Vertical nudge
"""
def __init__(self, x=0, y=0):
self.p... | ethod
def compute_layer(cls, data, params, layout):
trans_x, trans_y = None, None
if params['x']:
def trans_x(x):
return x + params['x']
if params['y']:
def trans_y(y):
return y + params['y']
| return cls.transform_position(data, trans_x, trans_y)
|
PearsonIOKI/compose-forum | askbot/migrations/0146_auto__add_field_threadtogroup_visibility.py | Python | gpl-3.0 | 33,877 | 0.00797 | # -*- coding: 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 'ThreadToGroup.visibility'
db.add_column('askbot_thread_groups', 'visibility',
... | 'wiki': ('django.db.models.fields.BooleanField', [], {'default': 'False'})
},
'askbot.an | onymousquestion': {
'Meta': {'object_name': 'AnonymousQuestion'},
'added_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'author': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True'}),
'id... |
blr246/traffic | phone_display_demo.py | Python | mit | 16,853 | 0.002492 | """
Copyright (C) 2011-2012 Brandon L. Reiss
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... | R COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING F | ROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Displays either day or nighttime traffic image processing in a mock-up UI
based on the HTC Desire smartphone.
"""
import numpy as np
import scipy
import scipy.ndimage as ndimg
from collections import deque
from copy... |
infobloxopen/infoblox-netmri | infoblox_netmri/api/remote/models/network_network_explorer_summaries_summary_grid_remote.py | Python | apache-2.0 | 1,486 | 0 | from ..remote import RemoteModel
class NetworkNetworkExplorerSummariesSummaryGridRemote(RemoteModel):
"""
| ``id:`` none
| ``attribute type:`` string
| ``DeviceID:`` none
| ``attribute type:`` string
| ``DeviceIPNumeric:`` none
| ``attribute type:`` string
| ``DeviceIPDott... | eName:`` no | ne
| ``attribute type:`` string
| ``DeviceType:`` none
| ``attribute type:`` string
| ``ifIndex:`` none
| ``attribute type:`` string
| ``ifName:`` none
| ``attribute type:`` string
| ``VirtualNetworkMemberName:`` none
| ``attribute type:`` string
| ``ifType:`` none... |
agile-geoscience/bruges | setup.py | Python | apache-2.0 | 117 | 0.008547 | from setuptools imp | ort setup
# Really only required so setup.cfg can pick up __version__
setup(
name="bru | ges",
) |
MaplePlan/djwp | oauth2app/token.py | Python | lgpl-3.0 | 16,845 | 0.00089 | #-*- coding: utf-8 -*-
"""OAuth 2.0 Token Generation"""
from base64 import b64encode
from django.http import HttpResponse
from django.contrib.auth import authenticate
from django.views.decorators.csrf import csrf_exempt
try: import simplejson as json
except ImportError: import json
from .exceptions import OAuth2Exc... | h2Exception):
"""The method requested requires a validated request to continue."""
pass
class InvalidRequest(AccessTokenException):
"""The request is missing a required parameter, includes an
unsupported parameter or parameter value, | repeats a
parameter, includes multiple credentials, utilizes more
than one mechanism for authenticating the client, or is
otherwise malformed."""
error = 'invalid_request'
class InvalidClient(AccessTokenException):
"""Client authentication failed (e.g. unknown client, no
client credentials inc... |
ghchinoy/tensorflow | tensorflow/contrib/distributions/python/ops/bijectors/softplus.py | Python | apache-2.0 | 5,563 | 0.003775 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | _ import division
from __future__ import print_function
from tensorflow.python.framework import ops
from tensorflow.python.ops import check_ops
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import nn_ops
from tensorflow.python.ops.distributions... | ",
]
class Softplus(bijector.Bijector):
"""Bijector which computes `Y = g(X) = Log[1 + exp(X)]`.
The softplus `Bijector` has the following two useful properties:
* The domain is the positive real numbers
* `softplus(x) approx x`, for large `x`, so it does not overflow as easily as
the `Exp` `Bijector`.
... |
awsdocs/aws-doc-sdk-examples | lambda_functions/secretsmanager/RDSPostgreSQL-Multiuser.py | Python | apache-2.0 | 16,740 | 0.004421 | # snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.]
# snippet-sourcedescription:[Lambda rotation for AWS Secrets Manager - RDS PostgreSQL with separate Master secret]
# snippet-service:[secretsmanager]
# snippet-keyword:[rotation function]
# snippet-keyword:[python]
# snippet-k... | % (step, arn))
def create_secret(service_client, arn, token):
"""Generate a new secret
This method first checks for the existence of a secret for the passed in token. If one does not exist, it will generate a
new secret and put it with the passed in token.
Args:
service_client (cl... | token (string): The ClientRequestToken associated with the secret version
Raises:
ValueError: If the current secret is not valid JSON
KeyError: If the secret json does not contain the expected keys
"""
# Make sure the current secret exists
current_dict = get_secret_dict(serv... |
Mte90/LearnHotkeys | cheatsheet.py | Python | gpl-3.0 | 5,629 | 0.007817 | #!/usr/bin/env python
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtXml import *
import sys, os
from ui_cheatsheet import Ui_CSDialo | g
class CSWindow ( QDialog , Ui_CSDialo | g):
settings = QSettings('Mte90','LearnHotkeys')
settings.setFallbacksEnabled(False)
theme_path = "./style"
theme_folder = theme_path+'/'
hotkeys_path = "./hotkeys"
hotkeys_folder = hotkeys_path+'/'
html_cs = ""
html_style = "<html>\n<head>\n<style>\n%s\n</style>\n</head>\n<body>\n"
... |
codewarrior0/Shiboken | tests/samplebinding/virtualmethods_test.py | Python | gpl-2.0 | 5,040 | 0.002381 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# This file is part of the Shiboken Python Bindings Generator project.
#
# Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
#
# Contact: PySide team <contact@pyside.org>
#
# This program is free software; you can redistribute it and/or
# modify it under t... | org/licenses/old-licenses/lgpl-2.1.html.
# #
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You | should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
# 02110-1301 USA
'''Test cases for virtual methods.'''
import sys
import unittest
from sample import *
import warnings
class... |
tensorflow/tensor2tensor | tensor2tensor/data_generators/image_utils.py | Python | apache-2.0 | 14,495 | 0.007934 | # coding=utf-8
# Copyright 2022 The Tensor2Tensor 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... | els: Number of channels in image.
Returns:
List of Tensors, one for each resolu | tion with shape given by
[resolutions[i], resolutions[i], num_channels] if resolutions properly
divide the original image's height; otherwise shape height and width is up
to valid skips.
"""
image_height = common_layers.shape_list(image)[0]
scaled_images = []
for height in resolutions:
dilation_... |
yaroslavprogrammer/django-filebrowser-no-grappelli | filebrowser/widgets.py | Python | bsd-3-clause | 3,673 | 0.004901 | # coding: utf-8
# DJANGO IMPORTS
from django.template.loader import render_to_string
from django.forms.widgets import FileInput as DjangoFileInput
from django.forms.widgets import ClearableFileInput as DjangoClearableFileInput
from django.forms.widgets import CheckboxInput
from django.forms.fields import FilePathField... | e
# FILEBROWSER IMPORTS
from filebrowser.base import FileObject
from filebrowser.settings import ADMIN_THUMBNAIL
class FileInput(DjangoClearableFileInput):
initial_text = ugettext_lazy('Currently')
input_text = ugettext_lazy('Change')
clear_checkbox_label = ugettext_lazy('Clear')
template_with_initi... | = {
'initial_text': self.initial_text,
'input_text': self.input_text,
'clear_template': '',
'preview': '',
'clear_checkbox_label': self.clear_checkbox_label,
}
template = u'%(input)s'
substitutions['input'] = super(DjangoClearableFileI... |
gkotian/zulip | tools/deprecated/finbot/money.py | Python | apache-2.0 | 7,737 | 0.003231 | #!/usr/bin/env python2.7
import datetime
import monthdelta
def parse_date(date_str):
return datetime.datetime.strptime(date_str, "%Y-%m-%d")
def unparse_date(date_obj):
return date_obj.strftime("%Y-%m-%d")
class Company(object):
def __init__(self, name):
self.name = name
self.flows = []
... | start)
def cashflow(self, start, end, days):
cur = self.start
delta = 0
while (cur <= end):
if cur >= start:
delta += self.amount
cur += monthdelta.MonthDelta(1)
re | turn delta
class TotalCost(CashFlow):
def __init__(self, name, *args):
self.name = name
self.flows = args
def cashflow(self, start, end, days):
return sum(cost.cashflow(start, end, days) for cost in self.flows)
class SemiMonthlyCost(TotalCost):
def __init__(self, name, amount, sta... |
veusz/veusz | veusz/document/emf_export.py | Python | gpl-2.0 | 14,778 | 0.002977 | # Copyright (C) 2009 Jeremy S. Sanders
# Email: Jeremy Sanders <jeremy@jeremysanders.net>
#
# 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 License, or
# ... | .emf.PolyBezierTo(params)
#print "C", params
i += 2
else:
assert False
i += 1
ef = path.elementAt(0)
el = path.elementAt(count-1)
if ef.x == el.x and ef.y == el.y:
self.emf.CloseFigure()
#print "cl... | ing"
self.emf.EndPath()
def drawPath(self, path):
"""Draw a path on the output."""
# print "path"
self._createPath(path)
self.emf.StrokeAndFillPath()
def drawTextItem(self, pt, textitem):
"""Convert text to a path and draw it.
"""
# print "text"... |
hugovk/diff-cover | diff_cover/violations_reporter.py | Python | agpl-3.0 | 15,153 | 0.000396 | """
Classes for querying the information in a test coverage report.
"""
from __future__ import unicode_literals
from abc import ABCMeta, abstractmethod
from collections import namedtuple, defaultdict
import re
import subprocess
import sys
import six
from diff_cover.git_path import GitPathTool
Violation = namedtuple('... | types to run on.
EXTENSIONS = []
def __init__(self, name, input_reports, user_options=None):
"""
Create a new quality reporter.
`name` is an identifier for the reporter
(usually the name of the t | ool used to generate
the report).
`input_reports` is an list of
file-like objects representing pre-generated
violation reports. The list can be empty.
If these are provided, the reporter will
use the pre-generated reports instead of invoking
the tool directly.
... |
yeyanchao/calibre | src/calibre/devices/mtp/defaults.py | Python | gpl-3.0 | 1,628 | 0.006143 | #!/usr/bin/env python
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:fdm=marker:ai
from __future__ import (unicode_literals, division, absolute_import,
print_function)
__license__ = 'GPL v3'
__copyright__ = '2012, Kovid Goyal <kovid at kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
... | dle'],
}
| ),
)
def __call__(self, device, driver):
if iswindows:
vid = pid = 0xffff
m = re.search(r'(?i)vid_([0-9a-fA-F]+)&pid_([0-9a-fA-F]+)', device)
if m is not None:
try:
vid, pid = int(m.group(1), 16), int(m.group(2), 16)
... |
AdamISZ/electrum-joinmarket-plugin | joinmarket/__init__.py | Python | gpl-3.0 | 721 | 0.011096 | from electrum.i18n import _
fullname = 'Joinmarket coinjoins'
description = _(" ".join(["Ability to send payments as coinjoins with counterparties.",
"Paying minimal fees, you can immediately send your coins",
"with much better privacy. See https://github.com/joinmar... | nmarket never loading.
#It seems that Electrum will not load a plugin on startup | if
#it has any setting here.
#requires_wallet_type = ['standard']
available_for = ['qt']
|
ralhei/PyHDB | pyhdb/auth.py | Python | apache-2.0 | 3,055 | 0 | # Copyright 2014, 2015 SAP SE
#
# 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,... | BytesIO(auth_part.methods[self.method])
)
self.client_proof = self.calculate_client_proof([salt], server_key)
return Authentication(self.user, {'SCRAMSHA256': self.client_proof})
def calculate_client_proof(self, salts, server_key):
proof = b"\x00"
proo | f += struct.pack('b', len(salts))
for salt in salts:
proof += struct.pack('b', CLIENT_PROOF_SIZE)
proof += self.scramble_salt(salt, server_key)
return proof
def scramble_salt(self, salt, server_key):
msg = salt + server_key + self.client_key
key = hashlib.... |
dims/glance | glance/async/flows/convert.py | Python | apache-2.0 | 3,951 | 0 | # Copyright 2015 OpenStack Foundation
# 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 requ... | ed" % image_id)
stdout, stderr = putils.trycmd('qemu-img', 'convert', '-O',
conversion_format, file_path, dest_path,
log_errors=putils.LOG_ALL_ERRORS)
if stderr:
raise RuntimeError(stderr)
os.rename(dest_... | elf, image_id, result=None, **kwargs):
# NOTE(flaper87): If result is None, it probably
# means this task failed. Otherwise, we would have
# a result from its execution.
if result is None:
return
fs_path = result.split("file://")[-1]
if os.path.exists(fs_path... |
Jumpscale/jumpscale6_core | lib/JumpScale/baselib/units/units.py | Python | bsd-2-clause | 787 | 0.005083 | order = ['','K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']
class Sizes(object):
_BASE = 1000.
def toSize(self, value, input='', output='K'):
"""
Convert value in other measurement
"""
input = order.index(input)
output = order.index(output)
factor = input - output
... | output > len(order):
output = len(order) - 1
elif output < 0:
output = 0
output = order[output]
return self.toSi | ze(value, input, output), output
class Bytes(Sizes):
_BASE = 1024.
|
openkamer/openkamer | website/views.py | Python | mit | 7,095 | 0.001409 | import os
import json
import datetime
from django.http import HttpResponse
from django.views.generic import TemplateView
from django.utils.safestring import mark_safe
from django.utils import timezone
from django.template.loader import render_to_string
from person.models import Person
from document.models import Doss... | ine_json(request):
governments = Government.objects.all()
eras = []
for government in governments:
if government.date_dissolved:
end_date = government.date_dissolved
else:
end_date = timezone.now()
text = {
'headline': government.name,
... | rnment.date_formed),
'end_date': create_timeline_date(end_date),
'text': text
}
eras.append(era)
events = []
if 'dossier_pk' in request.GET:
dossier = Dossier.objects.get(id=request.GET['dossier_pk'])
for kamerstuk in dossier.kamerstukken:
text... |
penzance/hdt_monitor | hdt_monitor/settings/gunicorn_config.py | Python | mit | 530 | 0.003774 | # gunicorn configuration
bind | = '0.0.0.0:8000'
workers = 3
# These log settings assume that gunicorn log config will be included in the django base.py logging configuration
accesslog = '-'
errorlog = '-'
access_log_format = '{"request": "%(r)s", "http_status_code": "%(s)s", "http_request_url": "%(U)s", "http_query_st | ring": "%(q)s", "http_verb": "%(m)s", "http_version": "%(H)s", "http_referer": "%(f)s", "x_forwarded_for": "%({x-forwarded-for}i)s", "remote_address": "%(h)s", "request_usec": "%(D)s", "request_sec": "%(L)s"}'
|
rasathus/pigredients | pigredients/ics/lpd6803.py | Python | mit | 7,299 | 0.01932 | import spidev
import time
import random
# All set commands set the state only, and so require a write command to be displayed.
class LPD6803_Chain(object):
def __init__(self, ics_in_chain=25, spi_address_hardware=0, spi_address_output=0):
# default to 25 ics in the chain, so it works with no params with the... | B' : 255})
byte_list.append(byte_pair[0])
byte_list.append(byte_pair[1])
self.spi.xfer2(byte_list)
# send out 'append pulse', one for each pixel.
append_pulses = []
for ic in self.ics:
append_pulses.append(0)
self.spi.xfer2(append_puls... | oes not affect pin state
byte_list = []
# write out our 32bit start frame
self.spi.xfer2([0,0,0,0])
for ic in self.ics:
byte_pair = self.two_byte_pack({'R' : 0, 'G' : 0, 'B' : 0})
byte_list.append(byte_pair[0])
byte_list.append(byte_pair[1])
s... |
ukhas/habitat | habitat/tests/test_parser_modules/test_ukhas_parser.py | Python | gpl-3.0 | 18,589 | 0.000592 | # Copyright 2010, 2011, 2013 (C) Adam Greig
#
# This file is part of habitat.
#
# habitat 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 versio... | e,
config_field_without_se | nsor)
# A configuration where a coordinate field lacks a format (should fail)
config_field_without_format = deepcopy(config_checksum_none)
del config_field_without_format["fields"][2]["format"]
assert_raises(ValueError, self.p.parse, sentence,
config_field_without_format... |
m00nlight/hackerrank | algorithm/Number-Theory/nCr/main.py | Python | gpl-2.0 | 7,426 | 0.005252 | from __future__ import division
from operator import add, mul
import cProfile
def memo(f):
cache = {}
def _f(*args):
try:
return cache[args]
except KeyError:
result = cache[args] = f(*args)
return result
except TypeError:
return f(*args)
... | g, x, y = exgcd(b, a % b)
return (g, y, x - (a // b) * y)
@memo
def modinv(a, m):
"""
Type :: (Int, Int) -> Int
Return :: Return module inverse of a * x = 1 (mod m)
"""
if gcd(a, m) is not 1: raise Exception("Not coprime")
_, x, y = exgcd(a, m)
return (m + x % m) % m
def... | [Int]
Generate primes number up to m, and return a list
"""
ret, judge = [], [True] * (m + 1)
judge[0] = judge[1] = False
ret.append(2)
for i in xrange(4, m + 1, 2): judge[i] = False
for i in xrange(3, m + 1, 2):
if judge[i]:
ret.append(i)
for j in xrange(i * ... |
cwolferh/heat-scratch | heat/engine/resources/openstack/neutron/lbaas/listener.py | Python | apache-2.0 | 7,961 | 0 | #
# Copyright 2015 IBM Corp.
#
# 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 require... | CONNECTION_LIMIT: properties.Schema(
| properties.Schema.INTEGER,
_('The maximum number of connections permitted for this '
'load balancer. Defaults to -1, which is infinite.'),
update_allowed=True,
default=-1,
constraints=[
constraints.Range(min=-1),
]
),... |
cossacklabs/acra | tests/test.py | Python | apache-2.0 | 375,193 | 0.003038 | # Copyright 2016, Cossack Labs Limited
#
# 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 an... |
vagonbar/GNUnetwork | gwn/blocks/libio/gnuradio/new/gwnChannelqpsk.py | Python | gpl-3.0 | 4,398 | 0.007731 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# This file is part of GNUWiNetwork,
# Copyright (C) 2014 by
# Pablo Belzarena, Gabriel Gomez Sena, Victor Gonzalez Barbone,
# Facultad de Ingenieria, Universidad de la Republica, Uruguay.
#
# GNUWiNetwork is free software: you can redistribute it ... | his stop function is required to stop GNU Radio threads. Overwrites generic block stop function; first stops locally started threads, waits on them, and finally invokes the generic stop function in PSK super class (generic block).
'''
self.tb_tx.stop()
self.tb_tx.wait()
print("tx top ... | inish
print("rx top block stopped")
super(ChannelQPSK, self).stop()
class dotdict(dict):
'''dot.notation access to dictionary attributes.
'''
def __getattr__(self, attr):
return self.get(attr)
__setattr__= dict.__setitem__
__delattr__= dict.__delitem... |
admiyo/keystone | keystone/routers/admin.py | Python | apache-2.0 | 6,755 | 0.009326 | # 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/... | or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import | logging
import routes
from keystone.common import wsgi
from keystone.controllers.token import TokenController
from keystone.controllers.roles import RolesController
from keystone.controllers.staticfiles import StaticFilesController
from keystone.controllers.tenant import TenantController
from keystone.controllers.user... |
ethanaward/mycroft-core | mycroft/skills/naptime/__init__.py | Python | gpl-3.0 | 1,477 | 0 | # Copyright 2016 Mycroft AI, Inc.
#
# This file is part of Mycroft Core.
#
# Mycroft Core | 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.
#
# Mycroft Core is distribu | ted in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mycroft Core. If not... |
alexgorban/models | research/object_detection/models/ssd_mobilenet_v1_fpn_feature_extractor_test.py | Python | apache-2.0 | 9,782 | 0.002249 | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | 4, 32),
| (2, 2, 2, 32)]
self.check_extract_features_returns_correct_shape(
2, image_height, image_width, depth_multiplier, pad_to_multiple,
expected_feature_map_shape, use_explicit_padding=False,
use_keras=use_keras)
self.check_extract_features_returns_correct_shape(
2, image_he... |
capturePointer/or-tools | examples/tests/issue4.py | Python | apache-2.0 | 1,031 | 0.022308 | from constraint_solver | import pywrapcp
def main():
solver = pywrapcp.Solver("time limit test")
n = 10
x = [solver.IntVar(1, n, "x[%i]" % i) for i in range(n)]
solver.Add(solver.AllDifferent(x, True))
solution = solver.Assignment()
solution.Add(x)
db = solver.Phase(x,
solver.CHOOSE_FIRST_UNBOUND,
... | ts = (
solver.Limit(
time_limit, branch_limit, failures_limit, solutions_limit, True))
search_log = solver.SearchLog(1000)
solver.NewSearch(db, [limits, search_log])
num_solutions = 0
while solver.NextSolution():
print "x:", [x[i].Value() for i in range(n)]
num_solutions += 1
solver.... |
mheap/ansible | lib/ansible/modules/cloud/openstack/os_flavor_facts.py | Python | gpl-3.0 | 6,809 | 0.000587 | #!/usr/bin/python
# Copyright (c) 2015 IBM
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
... | ephemeral storage.
- os_flavor_facts:
cloud: mycloud
ram: ">=1024"
vcpus: "2"
ephemeral: "<30"
'''
RETURN = '''
openstack_flavors:
description: Dictionary describing the flavors.
returned: On success.
type: complex
contains:
id:
description: Flavor ID.
... | type: string
sample: "tiny"
disk:
description: Size of local disk, in GB.
returned: success
type: int
sample: 10
ephemeral:
description: Ephemeral space size, in GB.
returned: success
type: int
... |
mflu/openvstorage_centos | openstack/tests/__init__.py | Python | apache-2.0 | 694 | 0 | # Cop | yright 2014 CloudFounders 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, ... | her express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
This package contains the unit tests for OVS Cinder Plugin for OpenStack
Tested on Plugin version 1.0.2a
"""
|
vsajip/django | django/views/i18n.py | Python | bsd-3-clause | 9,782 | 0.002556 | import os
import gettext as gettext_module
from django import http
from django.conf import settings
from django.utils import importlib
from django.utils.translation import check_for_language, activate, to_locale, get_language
from django.utils.text import javascript_quote
from django.utils.encoding import smart_unicod... | ror:
catalog = None
if catalog is not | None:
t.update(catalog._catalog)
# last load the currently selected language, if it isn't identical to the default.
if locale != default_locale:
# If the currently selected language is English but it doesn't have a
# translation catalog (presumably due to being the language trans... |
leifos/boxes | treasure-houses/asg/admin.py | Python | mit | 178 | 0 | __author | __ = 'leif'
from django.contrib import admin
from models import *
admin.site.register(GameExperiment)
admin.site.register(UserProfile)
admin.si | te.register(MaxHighScore)
|
rrustia/code-katas | src/test_is_thue_morse.py | Python | mit | 318 | 0 | """Test | ."""
import pytest
TM_TABLE = [
([0, 1, 1, 0, 1], True),
([0], True),
([1], False),
([0, 1, 0, 0], False),
]
@pytest.mark.parametrize("n, result", TM_TABLE)
def test_is_thue_morse(n, result):
"""Test."""
from is_thue_morse import is | _thue_morse
assert is_thue_morse(n) == result
|
astaninger/speakout | venv/lib/python3.6/site-packages/setuptools/command/upload.py | Python | mit | 1,493 | 0 | import getpass
from distutils import log
from distutils.command import upload as orig
class upload(orig.upload):
"""
Override default upload behavior to obtain password
in a variety of different ways.
"""
def run(self):
try:
orig.upload.run(self)
finally:
s... | Attempt to load password from keyring. Suppress Exceptions.
| """
try:
keyring = __import__('keyring')
return keyring.get_password(self.repository, self.username)
except Exception:
pass
def _prompt_for_password(self):
"""
Prompt for a password on the tty. Suppress Exceptions.
"""
try:
... |
varunarya10/ironic | ironic/drivers/fake.py | Python | apache-2.0 | 2,806 | 0 | # -*- encoding: utf-8 -*-
#
# Copyright 2013 Hewlett-Packard Development Company, L.P.
#
# 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
#
# ... | ack.common import import | utils
class FakeDriver(base.BaseDriver):
"""Example implementation of a Driver."""
def __init__(self):
self.power = fake.FakePower()
self.deploy = fake.FakeDeploy()
self.a = fake.FakeVendorA()
self.b = fake.FakeVendorB()
self.mapping = {'first_method': self.a,
... |
anhstudios/swganh | data/scripts/templates/object/weapon/ranged/vehicle/shared_vehicle_atst_ranged.py | Python | mit | 454 | 0.048458 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXA | MPLES
from swgpy.object import *
def create(kernel):
result = Weapon()
re | sult.template = "object/weapon/ranged/vehicle/shared_vehicle_atst_ranged.iff"
result.attribute_template_id = 10
result.stfName("obj_n","unknown_weapon")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
felixbb/forseti-security | google/cloud/security/common/data_access/violation_dao.py | Python | apache-2.0 | 3,393 | 0 | # Copyright 2017 Google 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, s... | violation_errors.append(formatted_violation)
return (inserted_rows, violation_errors)
def _format_violation(violation, resource_name):
"""Violation formating stub that uses a map to call the formating
function for the resource.
Args:
violation: An iterator of RuleViola... | e: String that defines a resource
Returns:
Formatted violations
"""
formatted_output = vm.VIOLATION_MAP[resource_name](violation)
return formatted_output
|
RackHD/RackHD | test/tests/amqp/test_amqp_node_rediscover.py | Python | apache-2.0 | 18,627 | 0.003382 | '''
Copyright 2017 Dell Inc. or its subsidiaries. All Rights Reserved.
Author(s):
Norton Luo
This test validate the AMQP message send out in the workflow, and node delete and discover.
It also validate the web hook api and node registeration function.
Ths test will choose a node and reset it. After the system... | = 0
webhook_body = str(self.rfile.read(length))
logs.tdl.debug('body is: %s', webhook_body)
self.send_response(200)
self.server.do_post_queue.put(webhook_body)
class HttpWorker(gevent.Greenlet):
def __init__(self, port, timeout=10):
super(HttpWorker, self).__init... | self.__server = HTTPServer(('', port), RequestHandler)
self.__server.timeout = timeout
self.__server.do_post_queue = gevent.queue.Queue()
testhost_ipv4 = env_ip_helpers.get_testhost_ip()
self.ipv4_address = testhost_ipv4
self.ipv4_port = port
@property
def ... |
clarkkarenl/brautbot | wordcount.py | Python | artistic-2.0 | 1,390 | 0 | #!/usr/bin/env python
from __future__ import print_function
from collections import Counter
from operator import itemgetter
import os
_path = os.path.abspath( | os.path.dirname(__file__))
SOURCE = os.path.join(_path, 'poems_for_wordcount.txt')
DESTINATION = os.path.join(_path, 'poem_words_out.txt')
def sort_word_counts(word_dict):
# first sort to get k by alpha
sorted_by_key = sorted(word_dict.items(), key=itemgetter(0))
# then reverse sort on number of occurrenc... | orted_by_key, key=itemgetter(1), reverse=1)
def main():
with open(SOURCE, 'rb') as source, open(DESTINATION, 'wb') as destination:
word_counts = Counter(source.read().lower().split())
for item in sort_word_counts(word_counts):
print("{} {}".format(*item), file=destination)
def test_s... |
napperley/OpenVPN_Tunneler | openvpn.py | Python | apache-2.0 | 1,290 | 0.003101 | __author__ = 'Nick Apperley'
# -*- c | oding: utf-8 -*-
#
# Establishes an OpenVPN connection using an OVPN file. Based on a Hacking Lab Python script
# (http://media.hacking-lab.com/largefiles/livecd/z_openvpn_config/backtrack/vpn-with-python.py). Requires Python 3
# and the pexpect library (module).
import pexpect
from invalid_credentials_error import In... | rocess = pexpect.spawn('openvpn %s' % ovpn_file, cwd=conf_dir, timeout=timeout)
try:
process.expect('Enter Auth Username:')
process.sendline(username)
process.expect('Enter Auth Password:')
process.sendline(password)
print('Connecting...')
process.expect('Initializa... |
chrisfilo/NeuroVault | scripts/prepare_sdr_package.py | Python | mit | 1,853 | 0.013492 | from __future__ import print_function
from future import standard_library
standard_library.install_aliases()
from builtins import str
import json, requests
import os, errno
import urllib.request, urllib.parse, urllib.error
def mkdir_p(path):
try:
os.makedirs(path)
except OSError as exc: # Python >2.5
... | pass
else: raise
collections = []
next_url_url = "http://neurovault.org/api/collections/?format=json"
target_folder = "D:/scratch/neurovault_backup"
while next_url_url:
print("fetching %s"%next_url_url)
resp = requests.get(url=next_url_url)
| data = json.loads(resp.text)
collections += [res for res in data['results'] if res['DOI'] != None]
next_url_url = data['next']
print("Fetched metadata of %d collections"%len(collections))
images_url_template = "http://neurovault.org/api/collections/%d/images/"
for collection in collections:
next_url =... |
esikachev/scenario | sahara/tests/tempest/scenario/data_processing/client_tests/test_jobs.py | Python | apache-2.0 | 2,479 | 0 | # Copyright (c) 2014 Mirantis 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 ... | heck_job_list | (job_id, job_name)
self._check_get_job(job_id, job_name)
self._check_delete_job(job_id)
|
netsec-ethz/scion | acceptance/cert_renewal/test.py | Python | apache-2.0 | 9,210 | 0.000326 | #!/usr/bin/env python3
# Copyright 2021 Anapaya Systems
#
# 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... | resp.reason)
continue
isd_as = scion_addr.ISD_AS(cs_config.stem[2:-2])
as_dir = self._to_as_dir(isd_as)
chain_name = "ISD%s-AS%s.pem" % (isd_as.isd_str(),
isd_as.as_file_fmt())
... | pld = json.loads(resp.read().decode("utf-8"))
if pld["subject_key_id"] != self._extract_skid(
as_dir / "crypto/as" / chain_name):
continue
logger.info(
"Control server successfully loaded new key and certificate: %s"
... |
toddself/beerlog2 | runserver.py | Python | apache-2.0 | 44 | 0 | from beerlog import app
app.run(debug=Tru | e)
| |
hiidef/pylogd | pylogd/twisted/socket.py | Python | mit | 1,335 | 0.001498 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""A twisted UDP interface that is similar to the built-in socket interface."""
import traceback
from twisted.internet import reactor
from twisted.internet.protocol import DatagramProtocol
class UDPSocket(DatagramProtocol):
def __init__(self, host, port):
se... | addr, becaus | e we only send to one place
try:
self.transport.write(msg)
except AttributeError:
# trying to log before twisted is running, nothing we can really do
pass
except AssertionError:
# trying to log before connection yields an assertion error
... |
cjaymes/pyscap | src/scap/model/oval_5/var/OvalVariablesElement.py | Python | gpl-3.0 | 1,169 | 0.004277 | # Copyright 2016 Case | y Jaymes
# This file is part of PySCAP.
#
# PySCAP 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.
#
# PySCAP is distributed in the ho... | e for more details.
#
# You should have received a copy of the GNU General Public License
# along with PySCAP. If not, see <http://www.gnu.org/licenses/>.
import logging
from scap.Model import Model
logger = logging.getLogger(__name__)
class OvalVariablesElement(Model):
MODEL_MAP = {
'tag_name' : 'oval_... |
goyal-sidd/BLT | comments/migrations/0004_auto_20170727_1308.py | Python | agpl-3.0 | 598 | 0.001672 | # | -*- coding: utf-8 -*-
# Generated by Django 1.11.1 on 2017-07-27 13:08
from __future__ import unicode_literals
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('comments', '0003_auto_20170726_1348'),
]
operations =... | y(default=-1, null=True, on_delete=django.db.models.deletion.CASCADE,
to='comments.Comment'),
),
]
|
theavey/ParaTemp | tests/test_sim_setup/conftest.py | Python | apache-2.0 | 584 | 0 | """
fixtures and setup for testing the sim_setup subpackage
"""
import pytest
|
@pytest.fixture(scope='function') # the created directories should be unique
def molecule(path_test_data, tmp_path):
from paratemp import cd
from paratemp.sim_setup import Molecule
path_gro = path_test_data / 'water.mol2'
# Note: this instantiation will make a new directory!
with cd(tmp_path):
... | |
kudrom/lupulo | lupulo/descriptors/date.py | Python | gpl-2.0 | 883 | 0 | # -*- encoding: utf-8 -*-
# Copyright (C) 2015 Alejandro López Espinosa (kudrom)
import datetime
import random
class Date(object):
"""
Descriptor for a date datum
"""
| def __init__(self, variance, **kwargs):
"""
@param variance is the maximum variance of time
allowed for the generation of random data.
"""
self.variance = variance
def generate(self):
"""
Generates random data for the descriptor.
... | the DataSchemaManager.generate
"""
now = datetime.datetime.now().strftime("%s")
return int(now) + random.randrange(0, self.variance)
def validate(self, data):
"""
Validates @param data against the descriptor.
This is called by the DataSchemaManager.validate
... |
Onager/plaso | tests/parsers/plist_plugins/timemachine.py | Python | apache-2.0 | 1,644 | 0.001825 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Tests for the timemachine plist plugin."""
import unittest
from plaso.parsers.plist_plugins import timemachine
from tests.parsers.plist_plugins import test_lib
class TimeMachinePluginTest(test_lib.PlistPluginTestCase):
"""Tests for the timemachine plist plugin.""... | tamps = [
1379165051000000, 1380098455000000, 1380810276000000, 1381883538000000,
1382647890000000, 1383351739000000, 1384090020000000, 1385130914000000,
1386265911000000, 1386689852000000, 1387723091000000, 1388840950000000,
1388842718000000]
timestamps = sorted( | [event.timestamp for event in events])
self.assertEqual(timestamps, expected_timestamps)
expected_event_values = {
'data_type': 'plist:key',
'desc': (
'TimeMachine Backup in BackUpFast '
'(5B33C22B-A4A1-4024-A2F5-C9979C4AAAAA)'),
'key': 'item/SnapshotDates',
... |
iw3hxn/LibrERP | data_migration/tests/__init__.py | Python | agpl-3.0 | 70 | 0 | # from . import test_partner_import
from . i | mport test_product_import | |
b3j0f/simpleneed | www/simpleneed/urls.py | Python | mit | 1,471 | 0 | """simpleneed URL Configuration.
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Exa | mples:
Function views
1. Add an import: from my_app import v | iews
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url,... |
abshkd/benzene | torrents/utils/__init__.py | Python | bsd-3-clause | 254 | 0.031496 | from django.uti | ls.datastructures import SortedDict
from bencode import bencode, bdecode
def sort_dict(D):
result = SortedDict()
for key in sorted(D.keys()):
if type(D[key]) is dict:
D[key] = sort_dict(D[key])
result[key] = D[ | key]
return result |
TimMaylon/corecoin | contrib/bitrpc/bitrpc.py | Python | mit | 7,838 | 0.038147 | from jsonrpc import ServiceProxy
import sys
import string
# ===== BEGIN USER SETTINGS =====
# if you do not set these you will be prompted for a password for every command
rpcuser = ""
rpcpass = ""
# ====== END USER SETTINGS ======
if rpcpass == "":
access = ServiceProxy("http://127.0.0.1:4496")
else:
access = Ser... | lance()
except:
print "\n---An error occurred---\n"
elif cmd == "getblockbycount":
try:
height = raw_input("Height: ")
print access.getblockbycount(height)
excep | t:
print "\n---An error occurred---\n"
elif cmd == "getblockcount":
try:
print access.getblockcount()
except:
print "\n---An error occurred---\n"
elif cmd == "getblocknumber":
try:
print access.getblocknumber()
except:
print "\n---An error occurred---\n"
elif cmd == "getconnectioncount":
try:
print ... |
yephper/django | django/urls/exceptions.py | Python | bsd-3-clause | 167 | 0 | from __future__ import unicode_literals
from django. | http im | port Http404
class Resolver404(Http404):
pass
class NoReverseMatch(Exception):
pass
|
shaunstanislaus/lemur | lemur/decorators.py | Python | apache-2.0 | 1,945 | 0.000514 | """
.. module: lemur.decorators
:copyr | ight: (c) 2015 by Netflix Inc., see AUTHORS for more
:license: Apache, see LICENSE for more details.
"""
from builtins import str
from datetime import timedelta
from flask import make_response, request, current_app
from functools import up | date_wrapper
# this is only used for dev
def crossdomain(origin=None, methods=None, headers=None,
max_age=21600, attach_to_all=True,
automatic_options=True): # pragma: no cover
if methods is not None:
methods = ', '.join(sorted(x.upper() for x in methods))
if headers ... |
alfred82santa/tarrabme2 | src/events/adminForms.py | Python | gpl-3.0 | 298 | 0.010067 | from models import Event, EventRole
from common.adminForms import CommonAd | minForm
class EventAdminForm(CommonAdminForm):
class Meta(CommonAdminForm.Meta):
model = Event
class EventRoleAdminForm | (CommonAdminForm):
class Meta(CommonAdminForm.Meta):
model = EventRole
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.