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 |
|---|---|---|---|---|---|---|---|---|
flaing/gemrb | gemrb/GUIScripts/Spellbook.py | Python | gpl-2.0 | 22,628 | 0.033543 | # -*-python-*-
# GemRB - Infinity Engine Emulator
# Copyright (C) 2011 The GemRB Project
#
# 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 (at your option) ... | d others in iwd2)
# Offset is a control ID offset here for iwd2 purposes
def SetupSpellIcons(Window, BookType, Start=0, Offset=0):
actor = GemRB.GameGetFirstSelectedActor ()
# check if we're dealing with a temporary spellbook
if GemRB.GetVar("ActionLevel") == 11:
allSpells = GetSpellinfoSpells (actor, BookType)
... | construct the spellbook of usable (not depleted) memorized spells
# the getters expect the BookType as: 0 priest, 1 mage, 2 innate
if BookType == -1:
# Nahal's reckless dweomer can use any known spell
allSpells = GetKnownSpells (actor, IE_SPELL_TYPE_WIZARD)
else:
allSpells = []
for i in range(16):
... |
codelucas/flask_reddit | server/gunicorn_config.py | Python | mit | 425 | 0 | # Refer to the following link for help:
# http://docs.gunicorn.org/en/latest/settings.html
command = '/home/luc | as/www/redd | it.lucasou.com/reddit-env/bin/gunicorn'
pythonpath = '/home/lucas/www/reddit.lucasou.com/reddit-env/flask_reddit'
bind = '127.0.0.1:8040'
workers = 1
user = 'lucas'
accesslog = '/home/lucas/logs/reddit.lucasou.com/gunicorn-access.log'
errorlog = '/home/lucas/logs/reddit.lucasou.com/gunicorn-error.log'
|
the-zebulan/CodeWars | tests/kyu_7_tests/test_guess_my_number.py | Python | mit | 693 | 0 | import unittest
from katas.kyu_7.guess_my_number import guess_my_number
class GuessMyNumberTestCase(unittest.TestCase):
def test_equals( | self):
self.assertEqual(guess_my_number('0'), '###-###-####')
def test_equals_2(self):
self.assertEqual(guess_my_number('01'), '1##-##1-####')
def test_equals_3(self):
self.assertEqual(guess_my_number('012'), '12#-##1-2###')
def test_equals_4(self):
self.assertEqual(guess_... | qual(guess_my_number('012345'), '123-451-2345')
|
vitorhirota/QgisImageAnalysis | analysis_widget.py | Python | gpl-2.0 | 9,304 | 0.00129 | # -*- coding: utf-8 -*-
#***********************************************************************
#
# Image Analysis
# ----------------------------------------------------------------------
# QGIS Image Analysis plugin for image segmentation and classification
#
# Vitor Hirota (vitor.hirota [at] gmail.com), INPE 2013
#... | .get_layers(ltype) if l.name() == name][0]
def update_combo_box(self, ltype, ipt):
ipt.clear()
ipt.addItems([u'',] + [l.name() for l in self.get_layers(ltype)])
def update_tab_order(self, inputs) | :
ipts = [self.tabWidget, self.ok_btn]
ipts[1:1] = inputs
for i in range(len(ipts)-1):
self.setTabOrder(ipts[i], ipts[i+1])
def update_tab_focus(self, index):
getattr(self, 'update_focus_%s' % self.tabs[index])()
self.tabWidget.setFocus()
def update_focus_se... |
penoud/GrovePi | Software/Python/grove_light_sensor.py | Python | mit | 2,674 | 0.004114 | #!/usr/bin/env python
#
# GrovePi Example for using the Grove Light Sensor and the LED together to turn the LED On and OFF if the background light is greater than a threshold.
# Modules:
# http://www.seeedstudio.com/wiki/Grove_-_Light_Sensor
# http://www.seeedstudio.com/wiki/Grove_-_LED_Socket_Kit
#
# The GrovePi con... | value = grovepi.analogRead(light_sensor)
# Calculate resistance of sensor in K
resistance = (float)(1023 - sensor_value) * 10 / sensor_value
if resistance > threshold:
# Send HIGH to switch on LED
grovepi.digitalWrite(led,1)
else:
| # Send LOW to switch off LED
grovepi.digitalWrite(led,0)
print("sensor_value = %d resistance =%.2f" %(sensor_value, resistance))
time.sleep(.5)
except IOError:
print ("Error")
|
bingopodcast/bingos | bingo_emulator/spelling_bee/game.py | Python | gpl-3.0 | 36,799 | 0.010489 | #!/usr/bin/python
import logging
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")
import procgame.game, sys, os
import procgame.config
import random
import procgame.sound
sys.path.insert(0,os.path.pardir)
import bingo_emulator.common.units as units
import bingo_em... | sel | f.game.coils.lifter.enable()
self.game.returned = False
def sw_smRunout_active_for_1ms(self, sw):
if self.game.start.status == True:
self.check_shutter(1)
else:
self.check_shutter()
def sw_trough1_closed(self, sw):
if self.game.sw... |
mzdun/uml-seq | src/uml/sequence/_anchor.py | Python | mit | 1,902 | 0.005783 | # encoding: utf-8
#
# Copyright (C) 2013 midnightBITS/Marcin Zdun
#
# 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, c... | G FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
'''
Created on 09-05-2017
@author: Marcin Zdun
'''
|
def getAnchor(index, defndx, *points):
if index < 0: return points[defndx]
index %= len(points)
return points[index]
def getAnchorDiag(diag, index, defndx, *points):
if index < 0: return points[defndx]
index %= len(points)
return points[index]
def boxAnchor(index, defndx, x1, y1, x2, y2):
... |
bd-j/prospector | prospect/utils/smoothing.py | Python | mit | 24,897 | 0.000843 | # Spectral smoothing functionality
# To do:
# 3) add extra zero-padding for FFT algorithms so they don't go funky at the
# edges?
import numpy as np
from numpy.fft import fft, ifft, fftfreq, rfftfreq
__all__ = ["smoothspec", "smooth_wave", "smooth_vel", "smooth_lsf",
"smooth_wave_fft", "smooth_vel_fft",... | type {} is not valid".format(smoothtype))
# Mask the input spectrum depending on outwave or the wave_smooth kwargs
mask = mask_wave(wave, width=width, outwave=outwave, linear=linear,
wlo=min_wave_smooth, whi=max_wave_smooth, **kwargs)
w = wave[mask]
s = spec[mask]
if outwave is... | method = smooth_lsf_fft
if sigma is not None:
# mask the resolution vector
sigma = resolution[mask]
else:
smooth_method = smooth_lsf
if sigma is not None:
# convert to resolution on the output wavelength grid
sig... |
DataONEorg/d1LocalCopy | d1_local_copy.py | Python | apache-2.0 | 1,400 | 0.015714 | # -*- coding: utf-8 -*-
'''Python command line tool to maange a local cache of content fom DataONE.
Output is a folder with structure:
cache/
meta.json: Basic metadata about the content in the cache
index.json: An index to entries in the cache. Downlaods are renamed using a
hash of the iden... | anager
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO)
# name of a folder that will contain the downloaded content,
cache_folder="cache"
# hostname of coordinating node to use
host="cn.dataone.org"
# Query to retrieve all METADATA entries that are not obsoleted
q = "formatType:M... | imiting the total downloads to max_records
manager.populate(q, max_records=1000)
|
Bennson/Projects | Automate the boring stuff/Chapter 7/strongPasswordDetection.py | Python | gpl-2.0 | 410 | 0.012195 | def passChecker(password):
import re
passlength = 8
uppercaseRegex = re.compile(r'[A-Z]')
lowercaseRegex = re.compile(r'[a-z]')
numberRegex = re.compile(r'[0-9]')
if ((uppercaseRegex.search(password) == None) or (lo | wercaseRegex.search(password) == None) or (numberRegex.search(password) == None) or (len(password) < pass | length)):
return False
return True
|
JulienMcJay/eclock | windows/Python27/Lib/site-packages/pywin32-218-py2.7-win32.egg/rasutil.py | Python | gpl-2.0 | 1,737 | 0.039724 | import win32ras
stateStrings = {
win32ras.RASCS_OpenPort : "OpenPort",
win32ras.RASCS_Port | Opened : "PortOpened",
win32ras.RASCS_ConnectDevice : "ConnectDevice",
win32ras.RASCS_DeviceConnected : "DeviceConnected",
win32ras.RASCS_AllDevicesConnected : "AllDevicesConnected",
win32ras.RASCS_Authenticate : "Authenticate",
win32ras.RASCS_AuthNotify : "AuthNotify",
win32ras.RASCS_AuthRetry ... | : "AuthProject",
win32ras.RASCS_AuthLinkSpeed : "AuthLinkSpeed",
win32ras.RASCS_AuthAck : "AuthAck",
win32ras.RASCS_ReAuthenticate : "ReAuthenticate",
win32ras.RASCS_Authenticated : "Authenticated",
win32ras.RASCS_PrepareForCallback : "PrepareForCallback",
win32ras.RASCS_WaitForModemReset : "Wa... |
MisterPup/OpenStack-Neat-Ceilometer | alarm_test/info_logger.py | Python | apache-2.0 | 6,034 | 0.009115 | """
Logger di varie info per ogni host
"""
from novaclient import client as novaclient
from ceilometerclient import client as ceiloclient
import os
from os import environ as env
import time
def start(hosts, sleep_sec, base_dir):
print 'You must be admin to use this script'
# start logger
time_dir = get_... | erload and underload alarms
alarms = ceilo.alarms.list(q=[{'field':'meter',
'op':'eq',
'value':'host.cpu.util.memory.usage'}])
hostname = [x.strip() for x in host_id.split('_')][0]
for alarm in alarms:
name = alarm.name
s... |
name_state = ''
if state == 'ok':
name_state = name + ': ' + '0'
elif state == 'alarm':
name_state = name + ': ' + '1'
else:
name_state = name + ': ' + '2'
content = get_string_to_write(name_state)
... |
mjirik/imtools | tests/qmisc_test.py | Python | mit | 3,908 | 0.001281 | #! /usr/bin/python
# -*- coding: utf-8 -*-
# import funkcí z jiného adresáře
import os.path
path_to_script = os.path.dirname(os.path.abspath(__file__))
# sys.path.append(os.path.join(path_to_script, "../extern/pyseg_base/src/"))
import unittest
import numpy as np
import os
from imtools import qmisc
from imtools i... | s(misc.obj_to_file(test_object, filename ,'yaml'))
def test_obj_to_and_from_file_with_directories(self):
import shutil
testdata = np.random.random([4, 4, 3])
test_object = {'a': 1, 'data': testdata}
dirname = '__test_write_and_read'
| filename = '__test_write_and_read/test_obj_to_and_from_file.pkl'
misc.obj_to_file(test_object, filename, 'pickle')
saved_object = misc.obj_from_file(filename, 'pickle')
self.assertTrue(saved_object['a'] == 1)
self.assertTrue(saved_object['data'][1, 1, 1] == testdata[1, 1, 1])
... |
akimach/tfgraphviz | tfgraphviz/__init__.py | Python | mit | 239 | 0.008368 | # c | oding: utf-8
from .graphviz_wrapper import board, add_digraph, add_digraph_node, add_digraph_edge
from .jupyter_helper import jupyter_pan_and_zoom, jupyter_show_as_svg
__author__ = "akimach"
__version__ = "0.0.7"
__license__ | = "MIT"
|
maurizioandreotti/D-Rats-0.3.ev | d_rats/wl2k.py | Python | gpl-3.0 | 16,452 | 0.003404 | import sys
import os
import socket
import tempfile
import subprocess
import shutil
import | email
import threading
import gobject
import struct
import time
import re
sys.path.insert(0, "..")
if __name__=="__main__":
import gettext
gettext.install("D-RATS")
from d_rats import version
from d_rats import platform
from d_rats import formgui
from d_rats import utils
from d_rats import signals
from d_rat... | calc_checksum
from d_rats.ui import main_events
from d_rats import agw
FBB_BLOCK_HDR = 1
FBB_BLOCK_DAT = 2
FBB_BLOCK_EOF = 4
FBB_BLOCK_TYPES = { FBB_BLOCK_HDR : "header",
FBB_BLOCK_DAT : "data",
FBB_BLOCK_EOF : "eof",
}
def escaped(string):
return strin... |
selective-inference/selective-inference | selectinf/randomized/tests/test_group_lasso.py | Python | bsd-3-clause | 10,569 | 0.011922 | from __future__ import division, print_function
import numpy as np
import nose.tools as nt
import regreg.api as rr
from ..group_lasso import (group_lasso,
selected_targets,
full_targets,
debiased_targets)
from ...tests.instance import... | conv._W,
nonzero,
conv.penalty)
elif target == 'debiased':
(observed_target,
group_assignments,
cov_target,
cov_target_score,
alternatives) = debiased_targets(conv.loglike,
... | ary(observed_target,
group_assignments,
cov_target,
cov_target_score,
alternatives,
ndraw=ndraw,
... |
stack-of-tasks/rbdlpy | tutorial/lib/python2.7/site-packages/FontTools/fontTools/misc/homeResFile.py | Python | lgpl-3.0 | 2,148 | 0.035847 | """Mac-only module to find the home file of a resource."""
import sstruct
import array
import calldll
import macfs, Res
def HomeResFile(res):
"""Return a path to the file in which resource 'res' lives."""
return GetFileLocation(res.HomeResFile())
def GetFileLocation(refNum):
"""Return a path to the open file id... | h
ioFCBEOF: l
ioFCBPLen: l
ioFCBCrPs: l
ioFCBVRefNum: h
ioFCBClpSiz: l
ioFCBParID: l
"""
class ParamBlock:
"""Wrapper for the very low level FCBPB record."""
def __init__(self, refNum):
self.__fileName = array.array("c", "\0" * 64)
sstruct.unpack(_FCBPBFormat,
"\0" * sstruct.calcsi... | e.buffer_info()[0]
self.ioRefNum = refNum
self.ioVRefNum = GetVRefNum(refNum)
self.__haveInfo = 0
def getInfo(self):
if self.__haveInfo:
return
data = sstruct.pack(_FCBPBFormat, self)
buf = array.array("c", data)
ptr = buf.buffer_info()[0]
err = _getInfo(ptr)
if err:
raise Res.Error, ("can't ... |
batxes/4Cin | Six_zebra_models/Six_zebra_models_final_output_0.1_-0.1_13000/mtx1_models/Six_zebra_models30110.py | Python | gpl-3.0 | 13,927 | 0.025203 | import _surface
import chimera
try:
import chimera.runCommand
except:
pass
from VolumePath import markerset as ms
try:
from VolumePath import Marker_Set, Link
new_marker_set=Marker_Set
except:
from VolumePath import volume_path_dialog
d= volume_path_dialog(True)
new_marker_set= d.new_marker_set
marker_set... | r((13215.9, 13710.7, 6892.86), (0.7, 0.7, 0.7), 708.61)
if "particle_15 g | eometry" not in marker_sets:
s=new_marker_set('particle_15 geometry')
marker_sets["particle_15 geometry"]=s
s= marker_sets["particle_15 geometry"]
mark=s.place_marker((11980.5, 13227.6, 7763.68), (0.7, 0.7, 0.7), 490.595)
if "particle_16 geometry" not in marker_sets:
s=new_marker_set('particle_16 geometry')
mar... |
pjryan126/solid-start-careers | store/api/zillow/extract.py | Python | gpl-2.0 | 1,175 | 0.043404 | import json
from multiprocessing import Pool, Manager
import os
import requests
import Quandl as quandl
# set working directory to script directory.
abspath = os.path.abspath(__file__)
dname = os.path.dirname(abspath)
os.chdir(dname)
errors = []
def get_url(url, vars=None):
if vars is not None:
var_string = '?'
... | l.com/api/v3/datasets.csv'
for i in range(1, 12663):
vars = {'database_code': 'ZILL',
'per_page': '100',
'sort_by': 'id',
'page': str(i),
'api_key': 'sWyovn27HuCobNWR2xyz'}
requests | .append(dict(url=get_url(url, vars), id=str(i))
pool = Pool(8)
pool.map(get_csv, urls)
pool.close()
pool.join()
print('Errors: ' + errors)
if __name__ == '__main__':
main()
|
doukremt/distance | tests/tests.py | Python | gpl-2.0 | 5,836 | 0.038897 | import os, sys
from array import array
try:
from distance import cdistance
except ImportError:
cdistance = None
from distance import _pyimports as pydistance
if sys.version_info.major < 3:
t_unicode = unicode
t_bytes = lambda s: s
else:
t_unicode = lambda s: s
t_bytes = lambda s: s.encode()
all_types = [
("un... | *kwargs):
if kwargs["lang"] == "C":
# types check; only need to do it for C impl to avoid an eventual segfaults.
try: func(1, t("foo"))
except ValueError: pass
itor = func(t("foo"), [t("foo"), 3333])
next(itor)
try: next(itor)
except ValueError: pass
# values drop
itor | = func(t("aa"), [t("aa"), t("abcd"), t("ba")])
assert next(itor) == (0, t("aa"))
assert next(itor) == (1, t("ba"))
def ilevenshtein(func, t, **kwargs):
itors_common(lambda a, b: func(a, b, max_dist=2), t, **kwargs)
def ifast_comp(func, t, **kwargs):
itors_common(func, t, **kwargs)
#transpositions
g = func(t(... |
ManiacalLabs/PixelWeb | pixelweb/config.py | Python | mit | 3,791 | 0.008441 | import json
from util import d
import os
__home = os.path.expanduser("~").replace('\\', '/') + "/PixelWeb/"
BASE_SERVER_CONFIG = d({
"id":"server_config",
"display": "server_config",
"preconfig": False,
"presets":[],
"params": [{
"id": "exter... | data = {}
except Exception, e:
pass
return d(data)
def writeConfig(file, data, key = None, path=None):
if not path:
path = __home
base = data
if key:
base = readConfig(file, path=path)
base[key] = data
with open(path + "/" + file + ".json", "w") as fp:
j... | on.dump(base, fp, indent=4, sort_keys=True)
def paramsToDict(params):
data = {}
for p in params:
if "default" not in p:
p.default = None
data[p.id] = p.default
return data
def readServerConfig():
data = readConfig("config", path=__home)
base = paramsToDict(BASE_SERVER_... |
rajalokan/nova | nova/scheduler/filters/compute_capabilities_filter.py | Python | apache-2.0 | 4,838 | 0 | # Copyright (c) 2011 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 ... | : cap,
'error': e} | )
return None
if not isinstance(cap, dict):
if getattr(cap, scope[index], None) is None:
# If can't find, check stats dict
cap = cap.stats.get(scope[index], None)
else:
... |
zsiki/ulyxes | pyapi/camerastation.py | Python | gpl-2.0 | 5,445 | 0.008448 | #!/usr/bin/env python
"""
.. module:: camerastation.py
:platform: Unix, Windows
:synopsis: Ulyxes - an open source project to drive total stations and
publish observation results. GPL v2.0 license Copyright (C)
2010- Zoltan Siki <siki.zoltan@epito.bme.hu>
.. moduleauthor:: Bence Turak <bence.turak... | argetType = None):
'''Measure angles between the target and the optical axis
:param photoName: name of the photo
:param targetType: type of the target
:returns: horizontal (hz) and vertical (v) correction angle in dictionary
'''
ok = False
while not o... | [0,3]), int(self._affinParams[1,3])))
ang = self.GetAngles()
self.TakePhoto(file, (int(self._affinParams[0,3]), int(self._affinParams[1,3])))
file.close()
try:
img = cv2.imread(photoName, 1)
picCoord = rec.recogChessPattern(img)
... |
jjimenezlopez/pyutils | srt/any2utf.py | Python | apache-2.0 | 2,015 | 0.007448 | #!/usr/bin/env python
from subprocess import Popen, PIPE
from sys import argv
__autor__ = "Jose Jiménez"
__email__ = "jjimenezlopez@gmail.com"
__date__ = "2012/05/03"
if len(argv) == 1 or len(argv) > 2:
print 'Wrong execution format.'
print 'Correct format: any2utf /path/to/the/files'
exit(0)
path = argv... | te()[0]
if proc.returncode == 0:
#proc = Popen('rm ' + aux_f, stdout=PIPE, shell=True)
proc = Popen('mv \"' + aux_f + '.utf\" \"' + aux_f + '\"', stdout=PIPE, shell=True)
proc.wait()
| proc = Popen('file --mime \"' + aux_f + '\"', stdout=PIPE, shell=True)
text = proc.communicate()[0]
print f.split('/')[-1] + ' | ' + charset + ' --> ' + text.split('charset=')[1].replace('\n', '')
else:
proc = Popen('file --mime \"' + aux_f + '\"', stdout=PIPE, shel... |
neo5g/server-gsrp5 | server-gsrp5/modules/__init__.py | Python | agpl-3.0 | 72 | 0.013889 | # -*- coding:utf-8 -*-
from . import loading
fro | m . | import registry
|
dnxbjyj/python-basic | gui/wxpython/wxPython-demo-4.0.1/demo/ColorPanel.py | Python | mit | 577 | 0.008666 | #!/usr/bin/env python
# No | te: this module is not a demo per se, but is used by many of
# the demo modules for various purposes.
import wx
#---------------------------------------------------------------------------
class ColoredPanel(wx.Window):
def __init__(self, parent, color):
wx.Window.__init__(self, parent, -1, style = wx.... | etBackgroundStyle(wx.BG_STYLE_CUSTOM)
#---------------------------------------------------------------------------
|
3n73rp455/api | manage.py | Python | gpl-3.0 | 535 | 0 | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE" | , "api.settings")
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
| "available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
|
kastnerkyle/sklearn-theano | sklearn_theano/feature_extraction/caffe/tests/test_googlenet.py | Python | bsd-3-clause | 908 | 0.001101 | from skimage.data import coffee, camera
from sklearn_theano.feature_extraction.caffe.googlenet import (
GoogLeNetTransformer, GoogLeNetClassifier)
import numpy as np
from nose import SkipTest
import os
co = coffee().astype(np.float32)
ca = camera().astype(np.float32)[:, :, np.newaxis] * np.ones((1, 1, 3),
... | dtype='float32')
def test_googlenet_transformer():
"""smoke test for googlenet transformer"""
if os.environ.get('CI', None) is not None:
raise SkipTest("Skipping heavy data loading on CI")
t = GoogLeNetTransformer()
t.transform(co)
t.transform(ca)
def test_googlenet_classifier... | googlenet classifier"""
if os.environ.get('CI', None) is not None:
raise SkipTest("Skipping heavy data loading on CI")
c = GoogLeNetClassifier()
c.predict(co)
c.predict(ca)
|
danfleck/Class-Chord | network-client/src/tests/ParallelStressTest.py | Python | apache-2.0 | 6,454 | 0.01255 | '''
Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
This module creates N nodes and sends X messages randomly between nodes and records
any failures. The messages are sent in blocks of 100 and then it waits and does it again.
Created on Jul 7, 2014
@author... | uccess, _) in results:
#print("DEBUG: doStressTest Result is %s" % success)
self.assertTrue(success, "doStressTest Message returned False!" )
|
# Wait a bit... just to ease up a smidge.
yield TestUtils.wait(0.1)
defer.returnValue(True)
def messageReceived(self, msg, dummy_Envelope):
'''This is a receiver for the bootstrap node only!
We got a message. For flooding pingbacks th... |
amitdhiman000/dais | error/views.py | Python | apache-2.0 | 920 | 0.022826 | from django.shortcuts import render
from django.http imp | ort HttpResponse, JsonResponse, HttpResponseRedirect
from django.template.context_processors import csrf
from common import post_required, login_required, redirect_if_loggedin, __redirect
# Create your views here.
def index(request):
da | ta = {'title': 'Error', 'page':'home'};
# return HttpResponse ('This is Invalid Request')
file = device.get_template(request, 'error_error.html')
return render(request, file, data)
def invalid_request_view(request):
data = {'title': 'Invalid Request', 'page':'home'};
# return HttpResponse ('This is Invalid Request'... |
socradev/django-fancypages | fancypages/templatetags/fp_block_tags.py | Python | bsd-3-clause | 2,534 | 0 | from django import template
from django.conf import settings
from django.db.models import get_model
from django.template import defaultfilters, loader
from .. import library
from .. import renderers
from ..dashboard import forms
ContentType = get_model('contenttypes', 'ContentType')
register = template.Library()
@... | le_tag(takes_context=True)
def render_block_form(context, form):
model = form._meta.model
model_name = model.__name__.lower()
template_names = [
"%s/%s_form.html" % (model._meta.app_label, model_name),
"fancypages/blocks/%s_form.html" % model_name, form.template_name]
| tmpl = loader.select_template(template_names)
context['missing_image_url'] = "%s/%s" % (
settings.MEDIA_URL, getattr(settings, "OSCAR_MISSING_IMAGE_URL", ''))
return tmpl.render(context)
@register.filter
def depth_as_range(depth):
# reduce depth by 1 as treebeard root depth is 1
return range(... |
MicroPasts/MicroPasts-Scripts | photoMasking/photoMasking.py | Python | apache-2.0 | 4,679 | 0.006412 | #!/usr/bin/python
## Download files from Amazon S3 (e.g. raw photos for 3D models)
## Andy Bevan 15-Jun-2014, updated 21-Nov-2014
## Daniel Pett updated 05-Jan-2016
__author__ = 'ahb108'
## Currently for Python 2.7.5 (tested on MacOSX 10.9.2) launched in a virtual environment:
from PIL import Image # Pillow with libj... | ne just in case)
imtasks = []
for elm in range(0, len(jtasks)):
onetask = jtasks[elm]
| onetaskurl = onetask['info']['url_b'].encode('utf-8')
if re.search(files[q], onetaskurl): imtasks.extend([onetask['id']])
# Get JSON data for task runs (even if they are duplicated)
jtaskruns = []
for a in range(0, len(imtasks)):
downloadURL = str(pybinst) + '/project/' + str(app) + ... |
jieyu/maple | script/maple/systematic/testing.py | Python | apache-2.0 | 3,528 | 0.003401 | """Copyright 2011 The University of Michigan
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 writi... | sting
from maple.race import testing as race_testing
from maple.systematic import program
from maple.systematic import search
class ChessTestCase(testing.DeathTestCase):
""" Run a test under the CHESS scheduler.
"" | "
def __init__(self, test, mode, threshold, controller):
testing.DeathTestCase.__init__(self, test, mode, threshold)
self.controller = controller
def threshold_check(self):
if self.search_done():
return True
if testing.DeathTestCase.threshold_check(self):
... |
adsabs/ADSOrcid | scripts/count.py | Python | gpl-3.0 | 863 | 0.008111 | from __future__ import print_function
from ADSOrcid.models import ClaimsLog
from ADSOrcid import tasks
from collections import defaultdict
app = tasks.app
def run():
stats = defaultdict(lambda: 0)
authors = {}
i = 0
with app.session_scope() as session:
for r in session.query(ClaimsLog).or... | , 'forced': 0, '#full-import': 0, 'updated': 0, 'removed': 0, 'unchanged': 0}
authors[r.orcidid][r.status] += 1
if i % 100000 == 0:
print('read ', i, 'rows')
i += 1
print('read', i, 'rows')
print(stats)
print(auth | ors)
if __name__ == '__main__':
run() |
lafactura/datea-api | datea_api/apps/comment/resources.py | Python | agpl-3.0 | 3,337 | 0.007192 | from tastypie import fields
from tastypie.bundle import Bundle
from tastypie.resources import ModelResource, ALL, ALL_WITH_RELATIONS
from api.authorization import DateaBaseAuthorization
from api.authentication import ApiKeyPlusWebAuthentication
from api.base_resources import JSONDefaultMixin
from api.serializers import... | name'],
'image_small': bundle.data['user'].data['image_small'],
'id': bundle.data['user'].data['id']
}
bundle.data['user'] = user_data
bundle.data['content_type'] = bundle.obj.content_type.model
return bundle
def hydrate(se... | , 'published', 'content_type', 'object_id', 'created', 'client_domain']
orig_obj = Comment.objects.get(pk=int(bundle.data['id']))
for f in fields:
if f in request.data:
request.data[f] = getattr(orig_obj, f)
elif bundle.request.method == '... |
joshrule/LOTlib | LOTlib/Hypotheses/FunctionHypothesis.py | Python | gpl-3.0 | 3,317 | 0.006331 | """
A special type of hypothesis whose value is a function.
The function is automatically eval-ed when we set_value, and is automatically hidden and unhidden when we pickle
This can also be called like a function, as in fh(data)!
"""
from Hypothesis import Hypothesis
from copy import copy
clas... | the function to f, ignoring value.
:param f: - a python function (object)
:return:
"""
self.set_value( "<FORCED_FUNCTION>", f=f)
def compute_single_likelihood(self, datum):
"""
A function that must be implemented by subclasses to compute the likelihood of a ... | gle datum/response pair.
This should NOT implement the temperature (that is handled by compute_likelihood)
"""
raise NotImplementedError
# ~~~~~~~~~
# Make this thing pickleable
def __getstate__(self):
""" We copy the current dict so that when we pickle, we destroy ... |
projecthamster/hamster-gtk | setup.py | Python | gpl-3.0 | 1,564 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Packing metadata for setuptools."""
from io import open
try:
from setuptools import setup, find_packages
except ImportError:
from distutils.core import setup
with open('README.rst', encoding='utf-8') as readme_file:
readme = readme_file.read()
with open(... | ckages=find_packages(exclude=['tests*']),
install_requires=requirements,
license="GPL3",
zip_safe=False,
keywords='hamster-gtk',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: End Users/Desktop',
'License :: OSI Approved :: GNU General Public Licen... | :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
],
entry_points='''
[gui_scripts]
hamster-gtk=hamster_gtk.hamster_gtk:_main
''',
package_data={
'hamster_gtk': ['resources/hamster-gtk.gresource'],
},
)
|
mpauly/psych-simulation | simulate.py | Python | apache-2.0 | 1,499 | 0.011341 | import numpy as np
NR_PER_CONDITION = 1000
neuro_sigma = 4
neuro_mean = 0
satis_sigma = 4
satis_mean = 0
print "Start drawing"
bins = {
5: np.array([-6, -3, 0, 3, 6]),
7: np.array([-6, -4, -2, 0, 2, 4, 6])
}
borders = {
5: np.array([-4.5,-1.5,1.5,4.5]),
7: np.array([-5.,-3.,-1.,1,3,5])
}
'outpu... | (neuro, borders[cond['first']])
neuro_vals[i] = bins[cond['first']][neuro_index]
satis = satis_sigma * np.random.randn(NR_PER_CONDITION) + satis_mean
satis_index = np.digitize(satis, borders[cond['second']])
satis_vals[i] = bins[cond['second']][satis_index]
cond_arr = np.full([1,NR... | output = np.concatenate((cond_arr, neuro_vals, satis_vals) )
np.savetxt(outfile, output.transpose(), fmt="%2i")
outfile.close()
print "Finished"
|
jaredscarr/django-imager | imagersite/imager_images/apps.py | Python | mit | 238 | 0 | from __future__ import unicode_l | iterals
from django.apps import AppConfig
class ImagerImagesConfig(AppConfig):
name = 'imager_images'
def rea | dy(self):
"""Run when app ready."""
from imager_images import signals
|
octopus-platform/bjoern | python/octopus-tools/octopus/server/project_manager.py | Python | gpl-3.0 | 237 | 0 | clas | s ProjectManager(object):
def create(self, project_nam | e):
pass
def delete(self, project_name):
pass
def list_projects(self):
pass
def upload_file(self, project_name, filename):
pass
|
algorythmic/bash-completion | test/t/test_service.py | Python | gpl-2.0 | 133 | 0 | import pytest
class TestService:
@pytest.mark.complet | e("service ")
def test_1(self, completion):
assert com | pletion
|
googlefonts/ots-python | setup.py | Python | bsd-3-clause | 9,371 | 0.00096 | from __future__ import print_function, absolute_import
from setuptools import setup, find_packages, Extension, Command
from setuptools.command.build_ext import build_ext
from setuptools.command.egg_info import egg_info
from distutils.file_util import copy_file
from distutils.dir_util import mkpath, remove_tree
from dis... | l import bdist_wheel
except ImportError:
pass
else:
class UniversalBdist | Wheel(bdist_wheel):
def get_tag(self):
return ("py2.py3", "none") + bdist_wheel.get_tag(self)[2:]
cmdclass["bdist_wheel"] = UniversalBdistWheel
class Download(Command):
user_options = [
("version=", None, "ots source version number to download"),
("sha256=", None, "expect... |
baoboa/Crystal-Space | scripts/python/tutorial2.py | Python | lgpl-2.1 | 8,916 | 0.012225 | #!/usr/bin/env python
"""
CsPython Tutorial Example 2
By Mark Gossage (mark@gossage.cjb.net)
A pure-Python script to show the use of Crystal Space.
To use this, ensure that your PYTHONPATH, CRYSTAL, and LD_LIBRARY_PATH
(or DYLD_LIBRARY_PATH for MacOS/X; or PATH for Windows) variables are set
approrpriately, and then ... | - 4, g2d.GetHeight() - 4)
def SetupFrame (self):
#print 'SetupFrame called',
elapsed_time = self.vc.GetElapsedTicks()
# Now rotate the camera according to keyboard state
speed = (elapsed_time / 1000.) * (0.03 * 20);
if | self.keybd.GetKeyState(CSKEY_RIGHT):
self.view.GetCamera().GetTransform().RotateThis(CS_VEC_ROT_RIGHT, speed)
if self.keybd.GetKeyState(CSKEY_LEFT):
self.view.GetCamera().GetTransform().RotateThis(CS_VEC_ROT_LEFT, speed)
if self.keybd.GetKeyState(CSKEY_PGUP):
self.vie... |
zizon/TinyTemplate | tiny_template_engine.py | Python | mit | 18,193 | 0.014346 | #!/usr/bin/env python
# -*- coding: utf8 -*-
import codecs
import xml.sax
import json
import copy
import logging
import math
import atexit
import tarfile
from datetime import datetime
from xml.sax.handler import ContentHandler
class IO(object):
def __init__(self):
self.defers = []
atexit.register... | ',compress=False):
dir = self.tempdir()
# make file
file_name = None
if name is not None:
file_name = name
else:
file_name = str(content.__hash__())
# final path
full_ | path = os.path.join(dir,file_name)
# do write
temp_file = codecs.open(full_path,u'w',encoding)
temp_file.write(content)
temp_file.close()
if compress:
compress_path = os.path.join(dir,u'%s.tar.bz2' % file_name)
compress_out = tarfile.open... |
ec429/harris | stats/fkmonthgraph.py | Python | gpl-3.0 | 2,243 | 0.022737 | #!/usr/bin/python2
"""fkmonthgraph - graph of enemy fighter kills & losses, by month
Requires matplotlib, see http://matplotlib.org or search your package
manager (Debian: apt-get install python-matplotlib)
"""
import sys
import hdata, fighterkill
from extra_data import Fighters as extra
import matplotlib.pyplot as p... | ot in sys.argv
legend = '--nolegend' not in sys.argv
data = fighterkill.extract_kills(sys.stdin)
monthly = {}
month = min(data.keys())
last = max(data.keys())
while month <= last:
next = month.nextmonth()
monthly[month] = {'total':{'kills':0, 'losses':0}, 'kills':[0 for i,f in enumerate(hdata.Fighters)], 'los... | d < next:
if d in data:
monthly[month]['total']['kills'] += data[d]['total']['kills']
monthly[month]['total']['losses'] += data[d]['total']['losses']
for i,f in enumerate(hdata.Fighters):
monthly[month]['kills'][i] += data[d]['kills'][i]
monthly[month]['losses'][i] += data[d]['losses'][i]
d ... |
obi-two/Rebelion | data/scripts/templates/object/tangible/ship/attachment/engine/shared_hutt_medium_engine_s02.py | Python | mit | 470 | 0.046809 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/ship/attac | hment/engine/shared_hutt_medium_engine_s02.iff"
result.attribute_template_id = 8
result.stfName("item_n","ship_attachment")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
ret | urn result |
LethusTI/supportcenter | vendor/django/tests/regressiontests/signals_regress/models.py | Python | gpl-3.0 | 323 | 0.003096 | from django.db import models
class Author(models.Model):
name = models.CharFiel | d(max_length=20)
def __unicode__(self):
return self.name
class Book(models.Model):
name = models.CharField(max_length=20)
authors = models.ManyToManyField(Author)
def __unicode__(self):
return | self.name
|
benfinke/ns_python | nssrc/com/citrix/netscaler/nitro/resource/config/responder/responderparam.py | Python | apache-2.0 | 4,282 | 0.031761 | #
# Copyright (c) 2008-2015 Citrix Systems, 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 l... | otected server.
* RESET - Reset the request and notify the user's browser, so that the user can resend the request.
* DROP - Drop the request without sending a response to the user.<br/>Default value: "NOOP"
"""
try :
self._undefaction = undefaction
except Exception as e:
raise e
def _get_nitro_respon... | ray in case of get request.
"""
try :
result = service.payload_formatter.string_to_resource(responderparam_response, response, self.__class__.__name__)
if(result.errorcode != 0) :
if (result.errorcode == 444) :
service.clear_session(self)
if result.severity :
if (result.severity == "ERROR") ... |
nikatjef/python-zabbix | zabbix/zabbix/get.py | Python | lgpl-2.1 | 990 | 0.014141 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Simple lib to connect to a Zabbix agent and request the value of an item.
"""
import socket
def query_agent(**kwargs):
"""
Open a socket to port 10050 on the remote server and query for the number of
processes running via proc.num[<FOO>], where FOO is either za... | cket.AF_INET, socket.SOCK_STREAM)
connection.connect((query_host, query_port))
except:
return (99999, 'ERROR: {} :: {}:{}'.format(e, que | ry_host, query_port))
else:
connection.send(query_string)
result = connection.recv(8192)
connection.close()
retval = ''.join(x for x in result if x.isdigit())
return (0, retval)
return (0 ,'')
if __name__ == '__main__':
import doctest
doctest.testmod()
|
robclark/chromium | ppapi/native_client/ppapi_scons_files.py | Python | bsd-3-clause | 2,682 | 0.000746 | # Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
trusted_scons_files = [
'src/shared/ppapi/build.scons',
'src/shared/ppapi_proxy/build.scons',
'src/trusted/plugin/build.scons',
'tests/p... | # TODO(dspringer): re-enable test once the 3D ABI has stabilized. See
# http://code.google.com/p/nativeclient/issues/detail?id=2060
# 'tests/ppapi_example_gles2/nacl.scons',
'tests/ppapi_example_post_message/nacl.scons',
'tests/ppapi_geturl/nacl.scons',
'tests/ppapi_gles_book/nacl.scons',
'test... | m/p/nativeclient/issues/detail?id=2480
#'tests/ppapi_simple_tests/nacl.scons',
'tests/ppapi_test_example/nacl.scons',
'tests/ppapi_test_lib/nacl.scons',
'tests/ppapi_tests/nacl.scons',
]
|
insequent/calico-docker | tests/st/utils/data.py | Python | apache-2.0 | 17,951 | 0.000223 | # Copyright (c) 2015-2016 Tigera, 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 applicabl... | f',
},
'spec': {
'node': 'node2',
'peerIP': 'fd5f::6:ee',
'asNumber': 64590,
},
}
#
# Network Policy
#
networkpolicy_name1_rev1 = {
'apiVersion': API_VERSION,
'kind': 'NetworkPolic | y',
'metadata': {
'name': 'policy-mypolicy1',
'namespace': 'default'
},
'spec': {
'order': 100,
'selector': "type=='database'",
'types': ['Ingress', 'Egress'],
'egress': [
{
'action': 'Allow',
'source': {
... |
kumar303/rockit | vendor-local/kombu/common.py | Python | bsd-3-clause | 8,390 | 0.001073 | """
kombu.common
============
Common Utilities.
:copyright: (c) 2009 - 2012 by Ask Solem.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
from __future__ import with_statement
import socket
import sys
from collections import defaultdict, deque
from functools import partial
f... |
def isend_reply(pool, exchange, req, msg, props, **retry_policy):
return ipublish(pool, send_reply,
(exchange, req, msg), props, **retry_policy)
def collect_replies(conn, channel, queue, *args, **kwargs):
| no_ack = kwargs.setdefault("no_ack", True)
received = False
for body, message in itermessages(conn, channel, queue, *args, **kwargs):
if not no_ack:
message.ack()
received = True
yield body
if received:
channel.after_reply_message_received(queue.name)
def _ens... |
eurogiciel-oss/Tizen-development-report | bin/checkRpmSrc.py | Python | mit | 3,700 | 0.026216 | #!/usr/bin/python
#
# Copyright 2014, Intel Inc.
#
# Thi | s 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; version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warr... | Library General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
# native
'''
Created on 13 oct. 2014
@author: ronan.le... |
robtandy/AutobahnPython | examples/twisted/wamp/basic/rpc/complex/backend.py | Python | apache-2.0 | 1,506 | 0.017928 | ###############################################################################
##
## Copyright (C) 2014 Tavendo GmbH
##
## 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:/... | twisted.internet import reactor
from twisted.internet.defer import inlineCallbacks
from autobahn.wamp.types import CallResult
from autobahn.twisted.wamp i | mport ApplicationSession
class Component(ApplicationSession):
"""
Application component that provides procedures which
return complex results.
"""
def onConnect(self):
self.join("realm1")
def onJoin(self, details):
def add_complex(a, ai, b, bi):
return CallResult(c = a + b,... |
vlegoff/tsunami | src/primaires/scripting/commandes/scripting/alerte_info.py | Python | bsd-3-clause | 3,352 | 0.002688 | # -*-coding:Utf-8 -*
# Copyright (c) 2010-2017 LE GOFF Vincent
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright n | otice, this
# list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduc | e the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of its contributors
# may be used to endorse or promote products derived from this software
... |
barrachri/aiodocker | aiodocker/tasks.py | Python | apache-2.0 | 1,131 | 0.001768 | from typing import List, Any, Mapping
from .utils import clean_filters
class DockerTasks(object):
def __init__(self, docker):
self.docker = docker
async def list(self, *, filters: Mapping=None) -> List[Mapping]:
"""
Return a list of tasks
Args:
filters: a collecti... |
Available filters:
desired-state=(running | shutdown | accepted)
id=<task id>
label=key or label="key=value"
name=<task name>
node=<node id or name>
service=<service name>
"""
params = {"filters": clean_filters(filters)}
response = awa... | r._query_json(
"tasks",
method='GET',
params=params
)
return response
async def inspect(self, task_id: str) -> Mapping[str, Any]:
"""
Return info about a task
Args:
task_id: is ID of the task
"""
response = a... |
zstackio/zstack-woodpecker | integrationtest/vm/mini/multiclusters/test_disconnect_host_volume_create_negative1.py | Python | apache-2.0 | 2,411 | 0.001244 | import zstackwoodpecker.operations.host_operations as host_ops
import zstackwoodpecker.operations.resource_operations as res_ops
import zstackwoodpecker.operations.volume_operations as vol_ops
import zstackwoodpecker.test_util as test_util
volume = None
disconnect = False
host = None
def test():
global disconnec... | rce(res_ops.HOST, cond)
cond = res_ops.gen_query_conditions('clusterUuid', '=', cluster2.uuid)
clust | er2_host = res_ops.query_resource(res_ops.HOST, cond)
# disconnect mn_host1
host = cluster1_host[0]
host_ops.update_kvm_host(host.uuid, 'username', "root1")
try:
host_ops.reconnect_host(host.uuid)
except:
test_util.test_logger("host: [%s] is disconnected" % host.uuid)
disconnect... |
dmchu/selenium_gr_5 | git_tests/second_file.py | Python | apache-2.0 | 93 | 0.010753 | # 1. Convert 1024 to binary and hexadecimal repre | sentation:
x = 1024
y = bin(x)
z = hex | (x) |
weihautin/anki | aqt/forms/getaddons.py | Python | agpl-3.0 | 2,703 | 0.00333 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'designer/getaddons.ui'
#
# Created: Fri Aug 22 00:57:31 2014
# by: PyQt4 UI code generator 4.10.4
# |
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except | AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtG... |
googleapis/python-websecurityscanner | samples/generated_samples/websecurityscanner_v1alpha_generated_web_security_scanner_get_finding_sync.py | Python | apache-2.0 | 1,528 | 0.001309 | # -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | name="name_value",
)
# Make the request
response = client.get_finding(request=request)
# Handle the response
print(response)
# [END websecurityscanner_v1alpha_g | enerated_WebSecurityScanner_GetFinding_sync]
|
nestlabs/nlbuild | scripts/elf_sign.py | Python | apache-2.0 | 10,383 | 0.006549 | #
# Copyright (c) 2016-2018 Nest Labs, 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
#
# ... | offset = sections[i].offset, \
size = sections[i].size)
sections[i] = s
# Find the sectio | n we want to update
sectionIndex = -1
for i in range(0, e_shnum):
if sections[i].name == sectionName:
sectionIndex = i
assert sectionIndex >= 0, "Section %s not found in ELF" % sectionName
assert len(sectionData) == sections[sectionIndex].size, "Size of signature data file (%d) does... |
ClinicalGraphics/scikit-image | skimage/filters/thresholding.py | Python | bsd-3-clause | 14,107 | 0.000496 | __all__ = ['threshold_adaptive',
'threshold_otsu',
'threshold_yen',
'threshold_isodata',
'threshold_li', ]
import numpy as np
from scipy import ndimage as ndi
from ..exposure import histogram
from .._shared.utils import assert_nD
import warnings
def threshold_adaptive(imag... | ply median rank filter
By default the 'gaussian' method is used.
offset : float, optional
Constant subtracted from weighted mean of neighborhood to c | alculate
the local threshold value. Default offset is 0.
mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional
The mode parameter determines how the array borders are handled, where
cval is the value when mode is equal to 'constant'.
Default is 'reflect'.
param : ... |
woddx/privacyidea | privacyidea/lib/audit.py | Python | agpl-3.0 | 4,198 | 0.000715 | # -*- coding: utf-8 -*-
#
# privacyIDEA is a fork of LinOTP
# May 08, 2014 Cornelius Kölbel
# License: AG | PLv3
# contact: http: | //www.privacyidea.org
#
# 2014-10-17 Fix the empty result problem
# Cornelius Kölbel, <cornelius@privacyidea.org>
#
# Copyright (C) 2010 - 2014 LSE Leading Security Experts GmbH
# License: AGPLv3
# contact: http://www.linotp.org
# http://www.lsexperts.de
# linotp@lsexperts.de
#
#... |
ksrajkumar/openerp-6.1 | openerp/addons/itara_multi_payment/__init__.py | Python | agpl-3.0 | 1,080 | 0.000926 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... | See the
# GNU Affero General Public Licens | e for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import wizard
import account_inv
# vim:expandtab:smartindent:t... |
slyphon/pants | src/python/pants/engine/exp/configuration.py | Python | apache-2.0 | 10,107 | 0.010488 | # coding=utf-8
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
from collections imp... | 'merging with {} were requested.'
.format(se | lf.extends.address, self.merges.address))
if self.extends:
attributes = self._extract_inheritable_attributes(self.extends)
attributes.update((k, v) for k, v in self._asdict().items()
if k not in self._SPECIAL_FIELDS and v is not None)
configuration_type = type(self)
... |
dsweet04/rekall | rekall-agent/rekall_agent/flows/find.py | Python | gpl-2.0 | 8,647 | 0.000231 | #!/usr/bin/env python2
# Rekall Memory Forensics
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Author: Michael Cohen scudette@google.com
#
# 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... | ction."""
if self.is_hunt():
return self._config.server.hunt_vfs_pat | h_for_client(
self.flow_id, self.path, vfs_type="metadata",
expiration=self.expiration())
return self._config.server.vfs_path_for_client(
self.client_id, "%s/%s" % (self.path, self.flow_id),
expiration=self.expiration(), vfs_type="collections",
... |
kevinseelbach/generic_utils | src/generic_utils/execution_context/exceptions.py | Python | bsd-3-clause | 835 | 0.003593 | """Custom exceptions for ExecutionContext package
"""
from generic_utils.exceptions import GenUtilsException
from generic_utils.exceptions import GenUtilsKeyError
from generic_util | s.exceptions import GenUtilsRuntimeError
class ExecutionContextStackEmptyError(GenUtilsException):
"""Raised when stack is empty and | blocks proper execution
"""
pass
class ExecutionContextValueDoesNotExist(GenUtilsKeyError):
"""Raised when attempting to get a value that does not exist in a backend"""
message = "Could not get key={key} from ExecutionContext."
key = None
class ExecutionContextRuntimeError(GenUtilsRuntimeError)... |
paultag/decodex | decodex/utils/words.py | Python | agpl-3.0 | 2,313 | 0.001297 | # decodex - simple enigma decoder.
#
# Copyright (c) 2013 Paul R. Tagliamonte <tag@pault.ag>
#
# 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 ... | ,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.o... | at):
return what.strip().lower().replace("'", "")
def issubset(superstr, substr):
superstr = list(superstr)
for ch in substr:
if ch not in superstr:
return False
superstr.remove(ch)
return True
def strsub(superstr, substr):
superstr = list(superstr)
substr = list(... |
lucalianas/ProMort | promort/clinical_annotations_manager/models.py | Python | mit | 10,721 | 0.003638 | # Copyright (c) 2019, CRS4
#
# 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, distribu... | ls.PROTECT, blank=False)
core = models.ForeignKey(Core, on_delete=models.PROTECT, blank=False,
related_name='clinical_annotations')
annotation_step = models.ForeignKey(ClinicalAnnotationStep, on_delete=models.PROTECT,
blank=False, related_name... | e = models.DateTimeField(null=True, default=None)
action_complete_time = models.DateTimeField(null=True, default=None)
creation_date = models.DateTimeField(default=timezone.now)
primary_gleason = models.IntegerField(blank=False)
secondary_gleason = models.IntegerField(blank=False)
gleason_group = mo... |
OpenChemistry/tomviz | tomviz/python/ClearVolume.py | Python | bsd-3-clause | 490 | 0 | def trans | form(dataset, XRANGE=None, YRANGE=None, ZRANGE=None):
"""Define this method for Python operators that
transform input scalars"""
import numpy as np
array = dataset.active_scalars
if array is None:
raise RuntimeError("No scalars found!")
# Transform the dataset.
result = np.copy(a... | dataset.active_scalars = result
|
twitter/pycascading | python/pycascading/operators.py | Python | apache-2.0 | 2,199 | 0.00091 | #
# Copyright 2011 Twitter, 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, so... | 0])
else:
(fields_from, fields_to) = (args[0], args[1])
return SubAssembly(cascading.pipe.assembly.Rename, \
coerce_to_fields(fields_from), \
coerce_to_fields(fiel | ds_to))
|
lyn716/deep_stack | django_server/RobotKiller/tasks.py | Python | apache-2.0 | 1,115 | 0 | # -*- coding: utf-8 -*-
"""
@file: tasks.py
@author: lyn
@contact: tonylu716@gmail.com
@python: 3.5
@editor: Vim
@create: 3/29/17 2:20 AM
@description:
用于反爬虫的一些异步任务,主要是刷新数据表中某些临时记录。
"""
from __future__ import absolute_import, unicode_literals
from celery import task as celery_task
from .model... | e.now():
ban.delete()
| print("clear {} from Ban".format(ban.ip))
clear_bans.append(ban.ip)
return clear_bans
@celery_task(name="refresh_ip_activity")
def refresh_ip_activity():
clear_act_ips = []
for ip_activity in RecentIpActivity.objects.all():
if ip_activity.destroy_time < timezone.now():
... |
bros-bioinfo/bros-bioinfo.github.io | COURS/M1/SEMESTRE1/ALGO_PROG/ALGO/Eliot/anales.py | Python | mit | 7,701 | 0.000781 | import random as rd
class Pile:
def __init__(self, data=None):
if data:
self.data = [i for i in data]
else:
self.data = []
def __repr__(self):
max_sp = len(str(max(self.data)))
out = ""
for i in range(len(self.data) - 1, -1, -1):
out... | :
| temp.empiler(elem)
else:
self.p1.empiler(elem)
print(self)
for i in range(len(temp)):
self.p2.empiler(temp.depiler())
print(self)
# pile = Pile([1, 2, 3, 4])
# print(multiplication(pile))
# print(pile)
#
# p1 = Pile([rd.randint(0, 9) for _... |
Cospel/rbm-ae-tf | test-ae-rbm.py | Python | mit | 4,382 | 0.005933 | import os
from rbm import RBM
from au import AutoEncoder
import tensorflow as tf
import input_data
from utilsnn import show_image, min_max_scale
import matplotlib.pyplot as plt
flags = tf.app.flags
FLAGS = flags.FLAGS
flags.DEFINE_string('data_dir', '/tmp/data/', 'Directory for storing data')
flags.DEFINE_integer('epo... | h_xs)
rbmobject3.partial_fit(batch_xs)
print(rbmobject3.compute_cost(rbmobject2.transform(rbmobject1.transform(trX))))
show_image("out/3rbm.jpg", rbmobject3.n_w, (25, 20), | (25, 10))
rbmobject3.save_weights('./out/rbmw3.chp')
# Train Third RBM
print('fourth rbm')
for i in range(FLAGS.epochs):
for j in range(iterations):
batch_xs, batch_ys = mnist.train.next_batch(FLAGS.batchsize)
# Transform features
batch_xs = rbmobject1.transform(batch_xs)
batch_xs = rbmobject2.transf... |
andresriancho/django-moth | moth/views/vulnerabilities/core/headers.py | Python | gpl-2.0 | 1,103 | 0.00544 | from django.shortcuts import render
from moth.views.base.vulnerable_template_view import VulnerableTemplateView
class EchoHeadersView(VulnerableTemplateView):
description = title = 'Echoes all request headers'
url_path = 'echo-headers.py'
KNOWN_HEADERS = ('CONTENT_LENGTH',)
def is_http_header(self, ... | TP_') or hname in self.KNOWN_HEADERS
def translate_header(self, hname):
hname = hname.replace('HTTP_', '')
hname = hname.replace('_', '-')
hname = hname.lower | ()
hname = hname.title()
return hname
def get(self, request, *args, **kwds):
context = self.get_context_data()
html = ''
msg_fmt = 'Header "%s" with value "%s" <br/>\n'
for hname in request.META:
if self.is_http_header(hname):
... |
weolar/miniblink49 | v8_7_5/tools/testrunner/testproc/sigproc.py | Python | apache-2.0 | 1,059 | 0.003777 | # Copyright 2018 the V8 project authors. All rights reserved.
# Use of this source code is governed by | a BSD-style license that can be
# found in the LICENSE file.
# for py2/py3 compatibility
from __future__ import print_function
import signal
from . import base
from testrunner.local import utils
class SignalProc(base.TestProcObserver):
def __init__(self):
super(SignalProc, self).__init__()
self.exit_code... | e chained together to not loose
# catched signal.
signal.signal(signal.SIGINT, self._on_ctrlc)
signal.signal(signal.SIGTERM, self._on_sigterm)
def _on_ctrlc(self, _signum, _stack_frame):
print('>>> Ctrl-C detected, early abort...')
self.exit_code = utils.EXIT_CODE_INTERRUPTED
self.stop()
d... |
FireBladeNooT/Medusa_1_6 | lib/tvdbapiv2/models/series_actors.py | Python | gpl-3.0 | 3,002 | 0.000666 | # coding: utf-8
"""
Copyright 2015 SmartBear Software
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... | f __ne__(self, other):
"""
Returns true if both objects are not equal
| """
return not self == other
|
daicang/Leetcode-solutions | 382-linked-list-random-node.py | Python | mit | 1,372 | 0 | import random
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
_largesize = 300
def __init__(self, head):
self.head = head
self.lsize = 0
while head.next:
h... | self._getN(se | lf.m1_idx)
self.m2_idx = self.m1_idx * 2 # start from 2/3
self.m2 = self._getN(self.m2_idx)
def _getN(self, n):
n -= 1
p = self.head
while n:
p = p.next
n -= 1
return p
def getRandom(self):
def _get(delta, start):
... |
ya-induhvidual/libfs | setup.py | Python | mit | 1,167 | 0 | from setuptools import setup
from | os | import path, environ
from sys import argv
here = path.abspath(path.dirname(__file__))
try:
if argv[1] == "test":
environ['PYTHONPATH'] = here
except IndexError:
pass
with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='libfs',
version=... |
ingadhoc/sale | sale_require_purchase_order_number/__manifest__.py | Python | agpl-3.0 | 1,515 | 0 | ##############################################################################
#
# Copyright (C) 2015 ADHOC SA (http://www.adhoc.com.ar)
# | All Rights Reserved.
#
# 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 dis... | r FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#############################################################... |
conan-io/conan | conans/test/unittests/client/conan_output_test.py | Python | mit | 3,440 | 0.001453 | # coding=utf-8
import unittest
from types import MethodType
from parameterized import parameterized
from six import StringIO
from conans.client.output import ConanOutput, colorama_initialize
from mock import mock
class ConanOutputTest(unittest.TestCase):
def test_blocked_output(self):
# https://github... | (True, {"PYCHARM_HOSTED": "1"}),
(False, {"CLICOLOR_FORCE": "1"}),
(True, {"CLICOLOR_FORCE": "1", "CLICOLOR": "0"}),
(True, {"CLICOLOR_FORCE": "1", "CONAN_COLO | R_DISPLAY": "0"})])
def test_output_color_prevent_strip(self, isatty, env):
with mock.patch("colorama.init") as init:
with mock.patch("sys.stdout.isatty", return_value=isatty), \
mock.patch.dict("os.environ", env, clear=True):
assert colorama_initialize()
... |
MTG/sms-tools | software/models_interface/hpsModel_GUI_frame.py | Python | agpl-3.0 | 8,438 | 0.03425 | # GUI frame for the hprModel_function.py
try:
# for Python2
from Tkinter import * ## notice capitalized T in Tkinter
import tkFileDialog, tkMessageBox
except ImportError:
# for Python3
from tkinter import * ## notice lowercase 't' in tkinter here
from tkinter import filedialog as tkFileDia... | "
Label(self.parent, text=nH_label).grid(row=8, column=0, sticky=W, padx=5, pady=(10,2))
self.nH = Entry(self.parent, justify=CENTER)
self.nH["width"] = 5
self.nH.grid(row=8, column=0, sticky=W, padx=(215,5), pady=(10,2))
self.nH.delete | (0, END)
self.nH.insert(0, "100")
#MIN FUNDAMENTAL FREQUENCY
minf0_label = "Minimum fundamental frequency:"
Label(self.parent, text=minf0_label).grid(row=9, column=0, sticky=W, padx=5, pady=(10,2))
self.minf0 = Entry(self.parent, justify=CENTER)
self.minf0["width"] = 5
self.minf0.grid(row=9, column=0, st... |
xbfool/hackerrank_xbfool | src/algorithms/arrays_and_sorting/running_time_of_algorithms.py | Python | mit | 325 | 0.036923 | number = input()
number_array = [(int)(x) | for x in raw_input().split()]
total = 0
for i in range(1, number):
for j in range(i):
ii = number_array[i]
jj = number_array[j]
if ii < jj:
total += i - j
number_array = number_array[:j] + [ii] + [jj] + number_array[j+1:i] + number_arra | y[i+1:]
break
print total
|
lbybee/reddit_spelling_index | reddit_spelling_scraper.py | Python | gpl-2.0 | 4,746 | 0.006532 | import json
import requests
import time
import csv
from datetime import datetime
#----------------------------------------------------------------------
def login(client_id, client_secret, username, password):
"""logs into reddit using Oauth2"""
client_auth = requests.auth.HTTPBasicAuth(client_id, client_sec... | sr_comments.extend(threadComments(l["data"]["permalink"]))
| print ((i + ind) * 100.) / sr_ln, (j * 100.) / sr_info_ln, datetime.now() - t_1, i + ind, j, sr_info_ln
time.sleep(2)
except Exception as e:
print e
time.sleep(60)
try:
sr_comments.extend(threadComments(l["data"]["permali... |
cmcbean/pynet_test | my-str-ex1.py | Python | apache-2.0 | 251 | 0.003984 | a_str1 = "Craig McBean"
a_str2 = "Sheree-Annm Lewis-McBean"
| a_str3 = 'Sheyenne Lewis'
a_str4 = raw_input("Enter fourth Name: ") |
print "{:>30}".format(a_str1)
print "{:>30}".format(a_str2)
print "{:>30}".format(a_str3)
print "{:>30}".format(a_str4)
|
ctrlaltdel/neutrinator | vendor/openstack/tests/unit/identity/v2/test_extension.py | Python | gpl-3.0 | 2,340 | 0 | # 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 t... | body = {
"extensions": {
"values": [
{"name": "a"},
{"name | ": "b"},
]
}
}
resp.json = mock.Mock(return_value=resp.body)
session = mock.Mock()
session.get = mock.Mock(return_value=resp)
sot = extension.Extension(**EXAMPLE)
result = sot.list(session)
self.assertEqual(next(result).name, 'a')
... |
jmborr/confinedBSA | simulation/silica/cristobalite/confineBSA/poretop/nobonds/adaptPDB.py | Python | mit | 1,589 | 0.010069 | #!/usr/bin/env/python
"""
We treat each silica atom as its own residue. As a consequence,
we have more than 10000 residues in the system.
The silly PDB format only allows up to 9999 residues. We solve
this issue by manually creating a .gro file, which allows for
up to 99999 residues
" | ""
from __future__ import print_function
import re
import MDAnalysis as mda
pdbf = 'SiO2carved_ovl1.5_protein_0.17.pdb'
# retrieve atom info
u = mda.Universe(pdbf)
GRO_FMT = ('{resid:>5d}{resname:<5s}{name:>5s}{id:>5d}'
'{pos[0]:8.3f}{pos[1]:8.3f}{pos[2]:8.3f}'
'\n')
gro = 'confined BSA, t= 0.0... | resid = 0
for atom in u.atoms:
iat += 1
vals['id'] = atom.id
vals['name'] = atom.name
# residue name
vals['resname'] = atom.resname
if atom.name in ('SIO', 'OSI', 'OA'):
vals['resname'] = atom.name
elif atom.resname == 'SPC':
vals['resname'] = 'SOL'
# residue number
v... |
xuleiboy1234/autoTitle | tensorflow/tensorflow/python/ops/math_ops.py | Python | mit | 83,640 | 0.004639 | # Copyright 2015 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... | low.python.framework import graph_util
from tensorflow.python.framewor | k import ops
from tensorflow.python.framework import sparse_tensor
from tensorflow.python.framework import tensor_shape
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import gen_control_flow_ops
from tensorflow.python.ops import gen_data_flow_ops
from tensorflow.python.ops import gen_math_ops
fr... |
TheoryInPractice/CONCUSS | lib/pattern_counting/pattern_counter.py | Python | bsd-3-clause | 8,882 | 0.000788 | #
# This file is part of CONCUSS, https://github.com/theoryinpractice/concuss/,
# and is Copyright (C) North Carolina State University, 2015. It is licensed
# under the three-clause BSD license; see LICENSE.
#
from collections import deque
from dp import KPattern, DPTable
from double_count import InclusionExclusion
... | rn class to use in dynamic programming
| table_hints: probably-respected options for the DP table
decomp_class: DecompGenerator subclass
combiner_class: CountCombiner subclass
verbose: whether or not to print debugging information
"""
self.G = G
self.multi = multi
self.coloring = coloring
... |
mitodl/micromasters | profiles/migrations/0029_merge_address_fields.py | Python | bsd-3-clause | 794 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2017-01-10 18:33
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('profiles', '0028_auto_20170113_2133'),
]
operations = [
migrations.RemoveFi... | (
model_name='profi | le',
name='address',
field=models.CharField(blank=True, max_length=100, null=True),
),
]
|
aliyun/oss-ftp | ossftp/__init__.py | Python | mit | 176 | 0 | __version__ = '1.2.0'
from .oss_authorizers import OssAuthorizer
from .oss_file_operation import OssFileOp | eration
from .oss_fs import OssFS
f | rom .oss_fs_impl import OssFsImpl
|
dmonroy/spa | spa/static/smart.py | Python | bsd-3-clause | 8,271 | 0.000484 | import hashlib
import mimetypes
import os
import posixpath
import re
from time import time
from urlparse import urlsplit, urlunsplit
from werkzeug.exceptions import NotFound
from werkzeug.http import is_resource_modified, http_date
from spa.static.handlers import StaticHandler
from spa.utils import clean_path
class... | urn NotFound()
if self.hash_cache.get_path_hash(unhashed_path) is None:
# compute hash, and cache it.
file = self.get_file(unhashed_path)
if file is None:
return NotFound()
| try:
hash_str = get_hash(file.handle)
self.hash_cache.set_path_hash(unhashed_path, hash_str)
finally:
file.handle.close()
# If hash we were passed doesn't equal the one we've computed and
# cached, then 404.
if path_hash != se... |
maxtorete/frappe | frappe/tests/test_website.py | Python | mit | 649 | 0.020031 | from __future__ import unicode_literals
import frappe, unittest
from werkzeug.wrappers import R | equest
from werkzeug.test import EnvironBuilder
from frappe.website import render
def set_request(**kwargs):
builder = EnvironBuilder(**kwargs)
frappe.local.request = Request(builder.get_environ())
class TestWebsite(unittest.TestCase):
def test_page_load(self):
set_request(method='POST', path='login')
respon... | tTrue('/* login-css */' in html)
self.assertTrue('// login.js' in html)
self.assertTrue('<!-- login.html -->' in html)
|
dermoth/gramps | gramps/gui/editors/editnote.py | Python | gpl-2.0 | 15,225 | 0.00335 | #
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2000-2006 Donald N. Allingham
# Copyright (C) 2009 Gary Burton
# Copyright (C) 2009 Benny Malengier
# Copyright (C) 2010 Nick Hall
# Copyright (C) 2011 Tim G L Lyons
#
# This program is free software; you can redistribute it an... | ------------------------------ | -----------------------
#
# Constants
#
#-------------------------------------------------------------------------
WIKI_HELP_PAGE = URL_MANUAL_SECT2
WIKI_HELP_SEC = _('manual|Editing_information_about_notes')
#-------------------------------------------------------------------------
#
# NoteTab
#
#-------------------... |
HPPTECH/hpp_IOSTressTest | IOST_0.23/Libs/IOST_AboutDialog/IOST_AboutDialog.py | Python | mit | 3,089 | 0.00777 | #!/usr/bin/python
#======================================================================
#
# Project : hpp_IOStressTest
# File : Libs/IOST_WAboutDialog/IOST_AboutDialog.py
# Date : Sep 21, 2016
# Author : HuuHoang Nguyen
# Contact : hhnguyen@apm.com
# : hoangnh.hpp@gmail.com
# License : MIT Licen... | w_name][window_name+ object_name].set_version(self.IOST_Data["ProjectVersion"])
self.CreateObjsDictFromDict(self.IOST_AboutDialog_WindowName,
self.IOST_Objs[self.IOST_AboutDialog_WindowName],
self.IOST_AboutDialog_Builder,
... | , window_name, object_name):
self.IOST_Objs[window_name][object_name].run()
self.IOST_Objs[window_name][object_name].hide()
def ActiveLink(self, object_name):
self.IOST_Objs[self.IOST_AboutDialog_WindowName][ self.IOST_AboutDialog_object_name].hide()
def on_IOST_WHelpAbout_destroy(self... |
greg-hellings/Automated-FTP-Dominator | gui/window.py | Python | gpl-3.0 | 9,748 | 0.029442 | '''
Copyright 2010 - Greg Hellings
This file is part of the Automated FTP Dominator.
The Automated FTP Dominator 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, version 3 of the License.
The... | st menu entry - File, as always
file = menubar.addMenu('&File')
# Last file entry - as always
file.addSeparator()
exit = QtGui.QAction('E&xit', self)
exit.setShortcut('Ctrl+Q')
self.connect(exit, QtCore.SIGNAL('triggered()'), QtCore.SLOT('close()'))
file.addAction(exit)
return menubar
# Returns a ... | Button = QtGui.QPushButton(QtGui.QIcon('icons/add_16x16.png'), 'Add Entry')
self.connect(addButton, QtCore.SIGNAL('clicked()'), self.addEntry)
editButton = QtGui.QPushButton(QtGui.QIcon('icons/edit_16x16.png'), 'Edit Entry')
self.connect(editButton, QtCore.SIGNAL('clicked()'), self.editEntry)
delButton = QtGui.... |
QLGu/django-oscar | tests/unit/search/munger_tests.py | Python | bsd-3-clause | 3,715 | 0.000269 | from collections import OrderedDict
from django.test import TestCase
from django.test.utils import override_settings
from django.utils.translation import ugettext_lazy as _
from oscar.apps.search import facets
FACET_COUNTS = {
u'dates': {},
u'fields': {
'category': [('Fiction', 12), ('Horror', 6), ('... | rice_ | range',
{
'name': _('Price range'),
'field': 'price',
'queries': [
(_('0 to 20'), u'[0 TO 20]'),
(_('20 to 40'), u'[20 TO 40]'),
(_('40 to 60'), u'[40 TO 60]'),
(_('60+'), u'[60 TO *]'),
]
... |
humangeo/rawes | rawes/thrift_elasticsearch/constants.py | Python | apache-2.0 | 220 | 0 | #
# Autogenerated by Thr | ift Compiler (0.8.0)
#
# DO NOT EDIT UNLESS YOU ARE SURE | THAT YOU KNOW WHAT YOU ARE DOING
#
# options string: py
#
from thrift.Thrift import TType, TMessageType, TException
from ttypes import *
|
mrshu/scikit-learn | sklearn/lda.py | Python | bsd-3-clause | 9,304 | 0.000215 | """
The :mod:`sklearn.lda` module implements Linear Discriminant Analysis (LDA).
"""
# Authors: Matthieu Perrot
# Mathieu Blondel
import warnings
import numpy as np
from scipy import linalg
from .base import BaseEstimator, ClassifierMixin, TransformerMixin
from .utils.extmath import logsumexp
from .utils.fi... | rn the decision function values related to each
class on an array of test vectors X.
Parameters
----------
| X : array-like, shape = [n_samples, n_features]
Returns
-------
C : array, shape = [n_samples, n_classes] or [n_samples,]
Decision function values related to each class, per sample.
In the two-class case, the shape is [n_samples,], giving the
log likelihoo... |
vistadataproject/nodeVISTA | setupDocker/pySetup/simpleSetup2.py | Python | agpl-3.0 | 5,139 | 0.018681 | """
simpleSetup2: runs POST the JS setup
NOTE: for 1.2 USERS (and their signatures) still done here. Next jsSetup will take this over and the User setup part
will be removed from here.
"""
import os
import sys
import logging
import time
sys.path = ['rasUtilities'] + sys.path
import OSEHRASetup
from OSEHRAHelper impo... | ow. It's the reset signature that will be used from
now on
"""
OSEHRASetup.addDoctor(VistA,"ALEXANDER,ROBERT","RA","000000029","M","fakedoc1","2Doc!@#$")
#Enter the Nurse Mary Smith
OSEHRASetup.addNurse(VistA,'SMITH,MARY','MS','000000030','F','fakenurse1','2Nur!@#$')
# Add a clerk user wit... | OSEHRASetup.addPharmacist(VistA,"SHARMA,FRED","FS","000000031","M","fakepharma1","2Pha!@#$");
#Create a new Order Menu
OSEHRASetup.createOrderMenu(VistA)
#Give all users of the instance permission to mark allergies as "Entered in error')
OSEHRASetup.addAllergiesPermission(VistA)
#Give Mar... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.