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
filippog/pysnmp
examples/v3arch/asyncore/agent/cmdrsp/multiple-usm-users.py
Python
bsd-3-clause
2,660
0.015414
""" Multiple SNMP USM users +++++++++++++++++++++++ Listen and respond to SNMP GET/SET/GETNEXT/GETBULK queries with the following options: * SNMPv3 * with USM user 'usr-md5-des', auth: MD5, priv DES or with USM user 'usr-sha-none', auth: SHA, no privacy with USM user 'usr-sha-aes128', auth: SHA, priv AES * allow ...
ivkey1 localhost .1.3.6 """# from pysnmp.entity import engine, config from pysnmp.entity.rfc3413 import cmdrsp, context from pysnmp.carrier.asyncore.dgram import udp # Create SNMP engine snmpEngine = engine.SnmpEngine() # Transport setup # UDP over IPv4 config.addTransport( snmpEngine, udp.domainName, u...
Pv3/USM setup # user: usr-md5-des, auth: MD5, priv DES config.addV3User( snmpEngine, 'usr-md5-des', config.usmHMACMD5AuthProtocol, 'authkey1', config.usmDESPrivProtocol, 'privkey1' ) # user: usr-sha-none, auth: SHA, priv NONE config.addV3User( snmpEngine, 'usr-sha-none', config.usmHMACSHAAuthProtoc...
mrquim/mrquimrepo
script.module.exodus/lib/resources/lib/sources/de/serienstream.py
Python
gpl-2.0
6,729
0.006687
# -*- coding: utf-8 -*- """ Exodus Add-on 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 3 of the License, or (at your option) any later version. This progra...
r = sorted(r, key=lambda i: int(i[2]), reverse=True) # with year > no year r = [i[0] for i in r if cleantitle.get(i[1]) in t and i[2] in y][0] return source_utils.strip_domain(r) except: return def __login(self): try: if (self.login == '...
k, '/login') post = urllib.urlencode({'email': self.login, 'password': self.password, 'autoLogin': 'on'}) header = {'User-Agent': self.user_agent, 'Accept': 'text/html'} cookie = client.request(url, headers=header, referer=url, post=post, output='cookie') data = client.re...
GISAElkartea/amv2
manage.py
Python
agpl-3.0
255
0
#!/usr/bin/env python import os
import sys if __name__ == "__m
ain__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "antxetamedia.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
CLVsol/odoo_addons
clv_medicament_dispensation_mng/clv_insured_card/__init__.py
Python
agpl-3.0
1,428
0.011905
# -*- encoding: utf-8 -*- ################################################################################ # # # Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol # # ...
ABILITY 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 # # alon...
###################################### import clv_insured_card
hlin117/statsmodels
statsmodels/formula/api.py
Python
bsd-3-clause
1,392
0.010776
from statsmodels.regression.linear_model import GLS gls = GLS.from_formula from statsmodels.regression.linear_model import WLS wls = WLS.from_formula from statsmodels.regression.linear_model import OLS ols = OLS.from_formula from statsmodels.regression.linear_model import GLSAR glsar = GLSAR.from_formula from statsmode...
tiveBinomial.from_formula from statsmodels.regression.quantile_regression import
QuantReg quantreg = QuantReg.from_formula from statsmodels.duration.hazard_regression import PHReg phreg = PHReg.from_formula from statsmodels.genmod.generalized_estimating_equations import (GEE, OrdinalGEE, NominalGEE) gee = GEE.from_formula ordinal_gee = OrdinalGEE.from_formula nominal_gee = NominalGEE.from_form...
ptrgags/linux-login
prompt/prompt.py
Python
gpl-2.0
2,429
0.04611
#!/usr/bin/env python import sys import re #Escape code for a color escape='\[\033[{}m\]' normal=escape.format(0) #Special effects effects = { 'normal': '0', 'bold': '1', 'underline': '4' } #8-color mode colors colors8 = { 'black': '30', 'red': '31', 'green': '32', 'yellow': '33', 'blue'...
sh
variables (ex. \\u or \h) prompt -- the original prompt returns the prompt with substitutions made """ for key in bash_vars: if key in prompt: prompt = prompt.replace(key, bash_vars[key]) return prompt def color_prompt(prompt, colors): ''' color the prompt, replacing |1|, |2|, ... with e...
superboonie/mps-youtube
mps_youtube/playlist.py
Python
gpl-3.0
985
0
import time class Playlist(object): """ Representation of a playist, has list of songs. """ def __init__(self, name=None, songs=None): """ class members. """ self.name = name self.creation = time.time() self.songs = songs or [] @property def is_empty(self): "...
perty def size(self): """ Return number of tracks. """ return len(self.songs)
@property def duration(self): """ Sum duration of the playlist. """ duration = sum(s.length for s in self.songs) duration = time.strftime('%H:%M:%S', time.gmtime(int(duration))) return duration class Video(object): """ Class to represent a YouTube video. """ def __i...
hypernicon/pyec
pyec/distribution/boltzmann/sample.py
Python
mit
29,509
0.022807
""" Copyright (C) 2012 Alan J Lockett 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, distribute,...
(1. / (1. + exp(-v)))[clampIdx:] else: x[clampIdx:vsize] = random.binomial(1, 1. / (1. + exp(-v)), vsize)[clampIdx:] h = dot(x[:vs
ize], w) + dot(lh, x[vsize:]) + bh x[vsize:] = 1. / (1. + exp(-h)) if self.binary and not self.meanField: x[vsize:] = random.binomial(1, x[vsize:], hsize) # left -> right v = dot(w, x[vsize:]) + dot(x[:vsize], lv) + bv h = dot(x[...
dwdm/splash
splash/tests/mockserver.py
Python
bsd-3-clause
23,343
0.0012
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import import os import optparse import urllib import base64 import random from functools import wraps from twisted.web.server import Site, NOT_DONE_YET from twisted.web.resource import Resource from twisted.web import proxy, http from twiste...
ml> <body> <img src="http://non-existing"> </body> </ht
ml> """) EggSpamScript = _html_resource("function egg(){return 'spam';}") class BaseUrl(Resource): @use_chunked_encoding def render_GET(self, request): return """ <html> <body> <p id="p1">Before</p> <script src="script.js"></script> </body> </html> """ def getChild(self, name, request): ...
mhdella/scipy_2015_sklearn_tutorial
check_env.py
Python
cc0-1.0
2,301
0.002608
from __future__ import print_function try: import curses curses.setupterm() assert curses.tigetnum("colors") > 2 OK = "\x1b[1;%dm[ OK ]\x1b[0m" % (30 + curses.COLOR_GREEN) FAIL = "\x1b[1;%dm[FAIL]\x1b[0m" % (30 + curses.COLOR_RED) except: OK = '[ OK ]' FAIL = '[FAIL]' import sys try: i...
pyversion >= "2": if pyversion < "2.7": print(FAIL, "Python version 2.7 is require
d, but %s is installed." % sys.version) else: print(FAIL, "Unknown Python version: %s" % sys.version) print() requirements = {'numpy': "1.6.1", 'scipy': "0.9", 'matplotlib': "1.0", 'IPython': "3.0", 'sklearn': "0.15"} # now the dependencies for lib, required_version in list(requirements.items()): ...
sparkslabs/kamaelia
Sketches/MPS/ArduinoRelated/slideshow.py
Python
apache-2.0
1,942
0.021627
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1) # # (1) Kamaelia Contributors are listed in the AUTHORS file and at # http://www.kamaelia.org/AUTHORS - please extend this file, # not this notice. # # Licensed under the Apache License, Ve...
S, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ------------------------------------------------------------------------- # from Kamaelia.UI.Pygame.Butto
n import Button from Kamaelia.UI.Pygame.Image import Image from Kamaelia.Util.Chooser import Chooser from Kamaelia.Chassis.Graphline import Graphline import os path = "Slides" extn = ".jpg" allfiles = os.listdir(path) files = list() for fname in allfiles: if fname[-len(extn):]==extn: files.append(os.path....
Hydrosys4/Master
loggerconfig.py
Python
gpl-3.0
1,697
0.007071
LOG_SETTINGS = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'detailed': { 'format': '%(asctime)s | %(process)d | %(levelname)s | %(filename)s | %(lineno)d | %(funcName)s | %(message)s', 'datefmt': '%Y-%m-%d %H:%M:%S' }, 'simpl...
lers.TimedRotatingFileHandler', 'level': 'DEBUG', 'formatter': 'simple', 'filename': 'logfiles/hydrosystem.log', 'backupCount': 3, 'encoding': 'utf8',
'when': 'midnight', 'interval': 1, 'delay': True }, 'exception_file_handler':{ 'class': 'logging.handlers.TimedRotatingFileHandler', 'level': 'ERROR', 'formatter': 'detailed', 'filename': 'logfiles/ex_hydrosystem.log', ...
mikefeneley/topcoder
src/SRM-152/fixed_point_theorem.py
Python
mit
351
0.014245
class FixedPointTheorem: def cyc
leRange(self, R): x = 0.25 high = -1 low = 999 for i in range(0, 201001): x = R * x * (1-x) if(i > 200000): if(x > high): high = x if(x < l
ow): low = x return high - low
triAGENS/markdown-pp
MarkdownPP/Transform.py
Python
mit
566
0.038869
# Copyright (C) 2010 John Reese # Licensed under the MIT license class Transform: """ This class represents a single modification to the data set, designed to be applied in descending order by line number. The operation deter
mines
where the new data will be applied, and how. """ lineum = -1 oper = "noop" data = "" def __init__(self, linenum = -1, oper = "noop", data = ""): self.linenum = linenum self.oper = oper self.data = data def __str__(self): return "Transform: (line: %d, oper: %s, data: %s)" % (self.linenum, self.oper, se...
digitalocean/netbox
netbox/dcim/tests/test_filters.py
Python
apache-2.0
132,317
0.002358
from django.contrib.auth.models import User from django.test import TestCase from dcim.choices import * from dcim.filters import * from dcim.models import ( Cable, ConsolePort, ConsolePortTemplate, ConsoleServerPort, ConsoleServerPortTemplate, Device, DeviceBay, DeviceBayTemplate, DeviceRole, DeviceType, Front...
am.models import IPAddress from tenancy.models import Tenant, TenantGroup from virtualization.models import Cluster, ClusterType class RegionTestCase(TestCase): queryset = Region.obje
cts.all() filterset = RegionFilterSet @classmethod def setUpTestData(cls): regions = ( Region(name='Region 1', slug='region-1', description='A'), Region(name='Region 2', slug='region-2', description='B'), Region(name='Region 3', slug='region-3', description='C')...
makinacorpus/django-social-auth
social_auth/backends/__init__.py
Python
bsd-3-clause
31,390
0.000414
""" Base backends structures. This module defines base classes needed to define custom OpenID or OAuth auth services from third parties. This customs must subclass an Auth and and Backend class, check current implementation for examples. Also the modules *must* define a BACKENDS dictionary with the backend name (whic...
<user last name if any>} """ raise NotImplementedError('Implement in subclass') @classmethod def tokens(cls, instance): """Return the tokens needed to authenticate the access to any API the service might provide. The return value will be a dictionary with the tok
en type name as key and the token value. instance must be a UserSocialAuth instance. """ if instance.extra_data and 'access_token' in instance.extra_data: return { 'access_token': instance.extra_data['access_token'] } else: return {} ...
legoktm/pywikipedia-rewrite
pywikibot/__init__.py
Python
mit
15,844
0.002211
# -*- coding: utf-8 -*- """ The initialization file for the Pywikibot framework. """ # # (C) Pywikipedia bot team, 2008 # # Distributed under the terms of the MIT license. # __version__ = '$Id$' import datetime import difflib import logging import math import re import sys import threading from Queue import Queue # ...
n thus ignore the latitudinal error. The longitudinal can be derived as follows: In small angle approximation (and thus i
n radians): Δλ ≈ Δpos / r_φ, where r_φ is the radius of earth at the given latitude. Δλ is the error in longitude. r_φ = r cos φ, where r is the radius of earth, φ the latitude Therefore: precision = math.degrees( self._dim / ( radius * math.cos( math.radians( self.lat ) ) ) ) """ ...
jmakov/ggrc-core
test/selenium/src/lib/page/widget/__init__.py
Python
apache-2.0
1,032
0
# Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: jernej@reciprocitylabs.com # Maintained By: jernej@reciprocitylabs.com # flake8: noqa from lib.page.widget.add import AddWidget from lib.page.widge...
age.widget.info import AccessGroupInfo from lib.page.widget.info import AssessmentsInfo from lib.page.widget.info import ClausesInfo from lib.page.widget.info import ContractsInfo from lib.page.widget.info import ControlsInf
o from lib.page.widget.info import DataAssetInfo from lib.page.widget.info import DashboardInfo from lib.page.widget.info import InfoWidget from lib.page.widget.info import ProgramInfo from lib.page.widget.info import ProcessInfo
xombiemp/CouchPotatoServer
couchpotato/core/helpers/variable.py
Python
gpl-3.0
11,486
0.008097
import collections import ctypes import hashlib import os import platform import random import re import string import sys import traceback from couchpotato.core.helpers.encoding import simplifyString, toSafeString, ss, sp from couchpotato.core.logger import CPLog import six from six.moves import map, zip, filter lo...
rn os.path.commonprefix([
subfolder, base]) == base return False # From SABNZBD re_password = [re.compile(r'(.+){{([^{}]+)}}$'), re.compile(r'(.+)\s+password\s*=\s*(.+)$', re.I)] def scanForPassword(name): m = None for reg in re_password: m = reg.search(name) if m: brea
mvendra/mvtools
audio/flac_to_mp3.py
Python
mit
823
0.00486
#!/usr/bin/env python3 import sys import os import path_utils import generic_run def puaq(): print("Usage: %s input_file.flac" % path_utils.basename_filtered(__file__)) sys.exit(
1) def convert_flac_
to_mp3(input_file, output_file, bitrate): cmd = ["ffmpeg", "-i", input_file, "-ab", bitrate, "-map_metadata", "0", "-id3v2_version", "3", output_file] v, r = generic_run.run_cmd_simple(cmd) if not v: print("Failed to convert file from flac to mp3: %s" % r) if __name__ == "__main__": if len(sys...
ychen820/microblog
y/google-cloud-sdk/platform/google_appengine/lib/django-1.5/django/contrib/auth/hashers.py
Python
bsd-3-clause
15,109
0.000265
from __future__ import unicode_literals import base64 import hashlib from django.dispatch import receiver from django.conf import settings from django.test.signals import setting_changed from django.utils import importlib from django.utils.datastructures import SortedDict from django.utils.encoding import force_bytes...
' not in encoded) or (len(encoded) == 37 and encoded.startswith('md5$$'))):
algorithm = 'unsalted_md5' # Ancient versions of Django accepted SHA1 passwords with an empty salt. elif len(encoded) == 46 and encoded.startswith('sha1$$'): algorithm = 'unsalted_sha1' else: algorithm = encoded.split('$', 1)[0] return get_hasher(algorithm) def mask_hash(hash, ...
huahbo/pyamg
pyamg/aggregation/adaptive.py
Python
mit
32,425
0.000031
"""Adaptive Smoothed Aggregation""" __docformat__ = "restructuredtext en" from warnings import warn import numpy as np import scipy as sp from scipy.sparse import csr_matrix, bsr_matrix, isspmatrix_csr,\ isspmatrix_csc, isspmatrix_bsr, eye, SparseEfficiencyWarning from pyamg.multilevel import multilevel_solver f...
import smoothed_aggregation_solver from aggregate import standard_aggregation, lloyd_aggregation from smooth import jacobi_prolongation_smoother, energy_prolongation_smoother,\ richardson_prolongation_smoother from tentative import fit_candidates from pyamg.util.utils import amalgamate, levelize_strength_or_aggreg...
'adaptive_sa_solver'] def eliminate_local_candidates(x, AggOp, A, T, Ca=1.0, **kwargs): """ Helper function that determines where to eliminate candidates locally on a per aggregate basis. Parameters --------- x : {array} n x 1 vector of new candidate AggOp : {CSR or CSC sparse mat...
spotify/docker-stress
setup.py
Python
apache-2.0
396
0.002525
#! /usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2014 Spotify AB import os.path from distutils.core import setup # Read and s
tore version from latest changelog entry version = open('debian/changelog').readline().split()[1][1:-1] setup(version=version, packages=['spotify', 'spotify
.docker_stress'], scripts=['docker-monitor', 'docker-stress'] )
marcelohg/NasajonWebTeamplateProject
web/js/google-closure/closure/bin/build/source_test.py
Python
mit
1,422
0.002813
#!/usr/bin/env python # # Copyright 2010 The Closure Library 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 ...
e input.""" def testSourceScan(self): test_source = source.Source(_TEST_SOURCE) self.assertEqual(set(['foo', 'foo.test']), test_source.provides) self.assertEqual(test_source.requires, set(['goog.dom', 'goog.events.EventTyp
e'])) _TEST_SOURCE = """// Fake copyright notice /** Very important comment. */ goog.provide('foo'); goog.provide('foo.test'); goog.require('goog.dom'); goog.require('goog.events.EventType'); function foo() { // Set bar to seventeen to increase performance. this.bar = 17; } """ if __name__ == '__main__': u...
axt/angr
angr/procedures/definitions/kernel32.py
Python
bsd-2-clause
240
0
from . import SimLibrary from .. impor
t SIM_PROCEDURES as P from ...calling_conventions import SimCCStdcall lib = SimLibrary() lib.set
_library_names('kernel32.dll') lib.add_all_from_dict(P['win32']) lib.set_default_cc('X86', SimCCStdcall)
doged/electrum-doged-tor
plugins/labels.py
Python
gpl-3.0
6,913
0.003906
import socket import requests import threading import hashlib import json try: import PyQt4 except Exception: sys.exit("Error: Could not import PyQt4 on Linux systems, you may try 'sudo apt-get install python-qt4'") from PyQt4.QtGui import * from PyQt4.QtCore import * import PyQt4.QtCore as QtCore import PyQt...
("wallet_nonce"), "externalId": self.encode(item), "encryptedLabel": self.encode(label)} t = threading.Thread(target=self.do_request, args=["POST", "/label", False, bundle]) t.setDaemon(True) t.start() self.set_nonce(self.wallet.storage.get("wallet_nonce") + 1) def settings_widget(s...
s'), self.settings_dialog) def settings_dialog(self): d = QDialog() vbox = QVBoxLayout(d) layout = QGridLayout() vbox.addLayout(layout) layout.addWidget(QLabel("Label sync options: "),2,0) self.upload = ThreadedButton("Force upload", self.push_thread, self.done_pro...
Frankkkkk/arctic
arctic/date/_mktz.py
Python
lgpl-2.1
1,145
0.000873
import bisec
t import os import dateutil import tzlocal import six class TimezoneError(Exception): pass def mktz(zone=None): """ Return a new timezone (tzinfo object) based on the zone using the python-dateutil package. The concise name 'mktz' is for convenient when using it on the console. Paramet...
defaults to local, returning: tzlocal.get_localzone() Returns ------- An instance of a timezone which implements the tzinfo interface. Raises - - - - - - TimezoneError : Raised if a user inputs a bad timezone name. """ if zone is None: zone = tzlocal.get_localzone()...
siavooshpayandehazad/SoCDep2
src/main/python/ArchGraphUtilities/Arch_Graph_Reports.py
Python
gpl-2.0
11,459
0.004974
# Copyright (C) 2015 Siavoosh Payandeh Azad import matplotlib.pyplot as plt import networkx from ConfigAndPackages import Config from ArchGraphUtilities.AG_Functions import return_node_location, return_node_number import math def draw_ag(ag, file_name): """ Generates Visualizations of the Architecture Graph ...
\033[0mVL OPTIMIZATION PROCESS GRAPH CREATED AT: GraphDrawings/v
l_opt_process.png") return None def gen_latex_ag(ag, shm): """ Generates a latex (.tex) file that will draw the architecture graph along with health of links and partitioning information :param ag: Architecture graph :param shm: System Health Map :return: None """ if Config.ag.z_si...
enalisnick/stick-breaking_dgms
train_scripts/train_stickBreaking_ssDGM.py
Python
mit
11,669
0.007284
import numpy as np import cPickle import os import sys import time from os.path import join as pjoin import theano import theano.tensor as T from models.ss_StickBreaking_DGM import SS_StickBreaking_DGM from models.neural_net.activation_fns import Sigmoid, Identity, Softmax from models.neural_net.loss_fns import * fro...
_name, 'w') stop_training = False for epoch_counter in range(n_epochs): if stop_training: break # Train this epoch epoch_start_time = time.time() avg_training_sup_nll_tracker = 0. avg_training_sup_kl_tracker = 0. avg_training_unsup_nll_tracker = 0. ...
avg_training_sup_nll, avg_training_unsup_nll, avg_training_sup_kl, avg_training_unsup_kl = train_model(minibatch_index) # check for NaN, test model anyway even if one is detected if (np.isnan(avg_training_sup_nll) or np.isnan(avg_training_unsup_nll) or np.isnan(avg_training_sup_kl) or np....
tensorflow/model-optimization
tensorflow_model_optimization/python/core/internal/tensor_encoding/encoders/common_encoders_test.py
Python
apache-2.0
4,757
0.005886
# Copyright 2019, 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 appli...
tensorflow_model_optimization.python.core.internal.tensor_encoding.core import gather_encoder from tensorflow_model_optimization.python.core.internal.tensor_encoding.core import simple_encoder from tensorflow_model_optimization.python.core.internal.tensor_encoding.encoders import common_encoders from tensorflow_model_...
ntization(8), lambda: common_encoders.hadamard_quantization(8), ] class EncoderLibraryTest(parameterized.TestCase): """Tests for the `common_encoders` methods.""" @parameterized.parameters(_ENCODER_FNS) def test_as_simple_encoder(self, encoder_fn): encoder = common_encoders.as_simple_encoder(encoder_fn...
jayvdb/pywikibot-core
scripts/pagefromfile.py
Python
mit
12,110
0.000165
#!/usr/bin/python # -*- coding: utf-8 -*- r""" Bot to upload pages from a file. This bot takes its input from a file that contains a number of pages to be put on the wiki. The pages should all have the same begin and end text (which may not overlap). By default the text should have the intended title of the page as t...
ore calling treat.""" pass def treat(self, page_tuple): """Process page tuple, set page to current page and
treat it.""" title, content = page_tuple page = pywikibot.Page(self.site, title) page.text = content.strip() super(PageFromFileRobot, self).treat(page) def treat_page(self): """Upload page content.""" page = self.current_page title = page.title() # s...
sharph/forklift
forklift/backup.py
Python
agpl-3.0
14,454
0.000069
#!/usr/bin/env python import os import os.path import msgpack import json from base64 import b64encode, b64decode from binascii import hexlify from time import time import compression import crypto from transports.metatransport import MetaTransport from transports.transport import NotRedundant from flexceptions im...
f.read(self.config['chunksize']) while data != '': digest = self._digest(data) if not self.transport.chunk_exists(digest): encdata = self._enc(data) else: encdata = None yield (digest, encdata) data = f.read(self.config[...
config = msgpack.loads(config) self.__init__(config, self.status) def save_config_remote(self): config = msgpack.dumps(self.config) config = crypto.encrypt_config(self.config, config) self.transport.write_config(config) def _local_config_path(self): if 'local_co...
dmsurti/mayavi
mayavi/tools/probe_data.py
Python
bsd-3-clause
2,853
0.000701
""" A helper function to retrieve the data from Mayavi structures on arbitrary points. """ import numpy as np from tvtk.api import tvtk from . import tools import tvtk.common as tvtk_common def probe_data(mayavi_object, x, y, z, type='scalars', location='points'): """ Retrieve the data from a described by Mayavi...
beFilter() tvtk_common.configure_input_data(probe, probe_data) tvtk_common.configure_source_data(probe, dataset) probe.update() if location == 'points': data = probe.output.point_data elif location == 'cells': data = probe.output.cell_data else: raise ValueError("Invalid...
, type) if values is None: raise ValueError("The object given has no %s data of type %s" % (location, type)) values = values.to_array() if type == 'scalars': values = np.reshape(values, shape) elif type == 'vectors': values = np.reshape(values, shape + [3...
cadencewatches/frappe
frappe/widgets/reportview.py
Python
mit
4,655
0.03072
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt from __future__ import unicode_literals """build query for doclistview and return results""" import frappe, json import frappe.permissions from frappe.model.db_query import DatabaseQuery from frappe import _ @frapp...
: """rebuild tag list for tags""" rdict = {} tagdict = dict(tagcount) for t in tagdict: alltags = t.split(',') for tag in alltags: if tag: if not tag in rdict: rdict[tag] = 0 rdict[tag] += tagdict[t] rlist = [] for tag in rdict: rlist.append([tag, rdict[tag]]) return rlist # used in bui...
d) if cond else "" def build_match_conditions(doctype, as_condition=True): return DatabaseQuery(doctype).build_match_conditions(as_condition=as_condition)
jdurbin/sandbox
python/plotting/plotnormal.py
Python
mit
568
0.008803
#!/usr/bin/env python3 import matplotlib.pyplot as plt import numpy as
np import scipy.stats as stats import math mu = 0 variance1 = 20000**2 variance2 = 2000**2 sigma1 = math.sqrt(variance1) sigma2 = math.sqrt(variance2) x = np.linspace(mu - 3*sigma1, mu + 3*sigma1, 100) plt.plot(x, stats.norm.pdf(x, mu, sigma1)) x2 = np.linspace(mu - 3*sigma2, mu + 3*sigma2,100) #x2 = [i for i in x2...
.axes.yaxis.set_ticklabels([]) plt.show()
tuxology/bcc
tools/swapin.py
Python
apache-2.0
2,336
0.003853
#!/usr/bin/python # @lint-avoid-python-3-compatibility-imports # # swapin Count swapins by process. # For Linux, uses BCC, eBPF. Embedded C. # # TODO: add -s for total swapin time column (sum) # # Copyright (c) 2019 Brendan Gregg. # Licensed under the Apache License, Version 2.0 (the "License"). # ...
rmance Tools book # published by Addison Wesley. ISBN-13: 9780136554820 # When copying or porting, include this comment. # # 03-Jul-2019 Brendan Gregg Ported from bpftrace to BCC. from __future__ import print_function from bcc import BPF from time i
mport sleep, strftime import argparse # arguments parser = argparse.ArgumentParser( description="Count swapin events by process.") parser.add_argument("-T", "--notime", action="store_true", help="do not show the timestamp (HH:MM:SS)") parser.add_argument("interval", nargs="?", default=1, help="output inter...
beeftornado/sentry
src/sentry/tasks/email.py
Python
bsd-3-clause
2,317
0.001295
from __future__ import absolute_import, print_function import logging from sentry.auth import access from sentry.tasks.base import instrumented_task from sentry.utils.email import send_messages logger = logging.getLogger(__name__) def _get_user_from_email(group, email): from sentry.models import User # TO...
user @instrumented_task( name="sentry.tasks.email.process_inbound_email", queue="email", default_retry_delay=60 * 5, max_retries=None, ) def process_inbound_email(mailfrom, group_id, payload): """ """ from sentry.models import Group
from sentry.web.forms import NewNoteForm try: group = Group.objects.select_related("project").get(pk=group_id) except Group.DoesNotExist: logger.warning("Group does not exist: %d", group_id) return user = _get_user_from_email(group, mailfrom) if user is None: logge...
xaibeing/cn-deep-learning
tutorials/sentiment-rnn/Sentiment_RNN_x.py
Python
mit
8,810
0.007832
# <makedowncell> # # Sentiment Analysis with an RNN # # In this notebook, you'll implement a recurrent neural network that performs sentiment analysis. Using an RNN rather than a feedfoward network is more accurate since we can include information about the *sequence* of words. Here we'll use a dataset of movie review...
input_dim=embed_size, output_dim=lstm_size, return_sequences=False)) #model.add(LSTM( # lstm_size, # return_sequences=False)) model.add(Dropout(dropout_rate)) #model.add(Dense(20)) model.add(Dense(output_dim=1, activation='sigmoid')) #model.compile(loss='mse', optimizer='rmsprop', metrics=...
sentropy', optimizer='rmsprop', metrics=['accuracy']) #model.compile(loss='mse', optimizer='adam', metrics=['accuracy']) model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) # <codecell> # training history = model.fit( train_x, train_y, batch_size=batch_size, nb_epoch=epoch...
empty/django-switch-user
su/views.py
Python
mit
838
0.001193
from django.http import HttpResponseRedirect, Http404 from django.contrib import auth from django.contrib.auth import get_user_mode
l from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User @login_required def switch_user(request, username): if request.user.is_superuser: try: user = get_user_model().objects.get(username=username) auth.login(request, user, backend='d...
contrib.auth.backends.ModelBackend') from_url = request.META.get("HTTP_ORIGIN", "") if not from_url: from_url = request.META.get("HTTP_HOST", "") from_url = from_url and ("http://" + from_url) or "/" return HttpResponseRedirect(from_url) ex...
CSUChico-CINS465/CINS465-Fall2016-Lecture-Examples
lecture8/dbexample/people/views.py
Python
mit
267
0.022472
from
django.shortcuts import render from .models import Student # Create your views here. def index(request): listOfStudents = Student.objects.all() context = { 'page_name':"List Site", "list":listOfStudents} return render(request,'lis
t.html',context)
chetan51/nupic
nupic/engine/__init__.py
Python
gpl-3.0
23,538
0.014742
#!/usr/bin/env python # ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2013, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions...
t. It prints just the error message to the screen and tells the user about the error.txt file. """ # Print the exception info to a string IO buffer for manipulation buff = cStringIO.StringIO() traceback.print_exception(type, value, tb, file=buff) text = buff.getvalue() # get the ...
merate(lines): if line.startswith('RuntimeError:'): begin = i # # elif line.startswith('Traceback (most recent call last):'): # end = i # break # message = '\n'.join(lines[begin:end]) message = message[len('Runtime Error:'):] #stacktrace = lines[end:] # Ge...
ultimate-pa/benchexec
benchexec/tools/dartagnan.py
Python
apache-2.0
1,416
0
# This file is part of BenchExec, a framework for reliable benchmarking: # https://github.com/sosy-lab/benchexec # # SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org> # # SPDX-License-Identifier: Apache-2.0 import benchexec.tools.template import benchexec.result as result class Tool(benchexec.t...
executable(self, tool_locator): return tool_locator.find_executable("Dartagnan-SVCOMP.sh") def name(self): return "Dartagnan" def cmdline(self, executable, options, task, rlimits): if task.property_file: options += [
task.property_file] return [executable] + options + list(task.input_files_or_identifier) def version(self, executable): return self._version_from_tool(executable) def determine_result(self, run): status = result.RESULT_ERROR if run.output: result_str = run.output[-1...
JohnKendrick/PDielec
Examples/Castep/AsparticAcid/script.py
Python
mit
1,981
0.007572
# # mainTab # tab = self.notebook.main
Tab tab.settings['Program'] = 'castep' tab.settings['Output file name'] = 'phonon.castep' # # SettingsTab # tab = self.notebook.settingsTab tab.settings['Eckart flag'] = False tab.settings['Neutral Born charges'] = False tab.settings['Sigma value'] = 2 tab.set
tings['Mass definition'] = 'average' # # 0th Scenario tabs # tab = self.notebook.scenarios[0] tab.settings['Matrix'] = 'ptfe' tab.settings['Volume fraction'] = 0.1 tab.settings['Ellipsoid a/b'] = 0.5 tab.settings['Unique direction - h'] = 0 tab.settings['Unique direction - k'] = 0 tab.settings['Unique direction - l'] =...
djsedulous/namecoind
libs/boost_1_50_0/libs/mpl/preprocessed/preprocess_set.py
Python
mit
552
0.016304
# Copyright Aleksey Gurtovoy 2001-2006 # # Distributed under the Boost Software License, Version 1.0. # (See accompanying file LICENSE_1_0.txt or copy at # http://www.boost.org/LICENSE_1_0.txt) # # See http:
//www.boost.org/libs/mpl for documentation. # $Id: preprocess_set.py 49269 2008-10-11 06:30:50Z agurtovoy $ # $Date: 2008-10-11 02:30:50 -0400 (S
at, 11 Oct 2008) $ # $Revision: 49269 $ import preprocess import os.path preprocess.main( [ "plain" ] , "set" , os.path.join( "boost", "mpl", "set", "aux_", "preprocessed" ) )
lcplj123/video-dl
progressbar.py
Python
mit
630
0.07047
#!/usr/bin/env python3 import sys class ProgressBar: ''' 进度条类定义 默认格式 [###### ] 43% ''' def __init__(self,fill = '#',empty = ' ',width = 50): self.fill = fill self.empty = empt
y self.width = width def update(self,percent): ''' 更新 ''' length = int(percent*self.width) s = '[%s%s] %d%%\r' % (length*self.fill,(self.width-length)*self.
empty,int(percent*100)) sys.stdout.write(s) sys.stdout.flush() def done(self): ''' 完成时调用 ''' print() #For test #import time #bar = ProgressBar() #for i in range(101): # bar.update(i/100.0) # time.sleep(0.1) #bar.done()
DXCanas/kolibri
kolibri/core/content/utils/channel_import.py
Python
mit
30,988
0.003743
import logging from django.apps import apps from django.db.models.fields.related import ForeignKey from sqlalchemy.exc import OperationalError from sqlalchemy.exc import SQLAlchemyError from sqlalchemy.sql import text from .annotation import recurse_availability_up_tree from .annotation import set_leaf_node_availabil...
return ids[0] + 1 return find_hole_in_list(ids[:middle]) # Otherwise check if there is a hole in the second half if ids[last] - ids[middle] != last - middle: # Second half is only two ids so hole must be between them if
last - middle == 1: return ids[middle] + 1 return find_hole_in_list(ids[middle:]) # We should only reach this point in the first iteration, if there are no holes in either # the first or the last half of the list, therefore, we just take the max of the list p...
dreid/cql3parser
setup.py
Python
mit
168
0
from setuptools im
port setup, find_packages setup( name='cql3parser', version='0.0.0', install_req
uires=['Parsley == 1.1'], packages=find_packages() )
gioman/QGIS
python/plugins/processing/algs/gdal/slope.py
Python
gpl-2.0
3,918
0.000766
# -*- coding: utf-8 -*- """ *************************************************************************** slope.py --------------------- Date : October 2013 Copyright : (C) 2013 by Alexander Bruy Email : alexander dot bruy at gmail dot com *******************...
* *************************************************************************** """ from builtins import str __author__ = 'Alexander Bruy' __date__ = 'October 2013
' __copyright__ = '(C) 2013, Alexander Bruy' # This will get replaced with a git SHA1 when you do a git archive __revision__ = '$Format:%H$' import os from processing.algs.gdal.GdalAlgorithm import GdalAlgorithm from processing.core.parameters import ParameterRaster from processing.core.parameters import Parameter...
D4wN/brickv
src/build_data/windows/OpenGL/GL/NV/transform_feedback.py
Python
gpl-2.0
2,570
0.015175
'''OpenGL extension NV.transform_feedback This module customises the behaviour of the OpenGL.raw.GL.NV.transform_feedback to provide a more Python-friendly API Overview (from the spec) This extension provides a new mode to the GL, called transform feedback, which records vertex attributes of the primitives proc...
nsform feedback results are complete, as well as the number of primitives processed and written back to buffer objects while in transform feedback mode. This extension also provides a new rasterizer discard enable, which allows applicat
ions to use transform feedback to capture vertex attributes without rendering anything. The official definition of this extension is available here: http://www.opengl.org/registry/specs/NV/transform_feedback.txt ''' from OpenGL import platform, constants, constant, arrays from OpenGL import extensions, wrapper from O...
RevansChen/online-judge
Codewars/7kyu/consecutive-letters/Python/test.py
Python
mit
203
0
# Pyth
on - 3.6.0 Test.it('Basic tests') Test.assert_equals(solve('abc'), True) Test.assert_equals(solve('abd'), False) Test.assert_equals(solve('dabc'), True) Test.assert_equals(solve('abbc')
, False)
carvalhomb/tsmells
src/dump/DuplicatedCode.py
Python
gpl-2.0
17,214
0.005112
# # This file is part of TSmells # # TSmells 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) any later version. # # TSmells is distributed in the hope ...
NrofReferences() return mtds def __parseLine(self, line, mtds): ''' add the information from a single line ''' #ComInvoke;11;217;178;7;MyTest.testOne();Uut.a();MyTest.java # invokerid, iid invokeeid, line, tc, invo, file splitted = line[:-1].split('\t') #...
') mtdName = splitted[6].strip('"') mtdId = int(splitted[2]) fileName = splitted[7].strip('"') if not mtds.has_key(mtdId): # add the method mtds[mtdId] = TestMethod(mtdId, mtdName, fileName) mtd = mtds[mtdId] # add the reference refI...
mbevila/cltk
cltk/utils/frequency.py
Python
mit
2,334
0.001714
"""This module's main class reads a text corpus and assembles a list of n most common words.""" __author__ = 'Kyle P. Johnson <kyle@kyle-p-johnson.com>' __license__ = 'MIT License. See LICENSE.' from cltk.corpus.utils.formatter import assemble_tlg_author_filepaths from cltk.corpus.utils.formatter import assemble_phi...
orpus): """Build word frequency list from one of several available corpora. TODO: Make this count iteratively, not all at once """
assert corpus in ['phi5', 'tlg'], \ "Corpus '{0}' not available. Choose from 'phi5' or 'tlg'.".format(corpus) all_strings = self._assemble_corpus_string(corpus=corpus) return self.counter_from_str(all_strings) def _assemble_corpus_string(self, corpus): """Takes a list of fil...
suutari/shoop
shuup_tests/core/test_payments_api.py
Python
agpl-3.0
3,959
0.000253
# -*- coding: utf-8 -*- # This file is part of Shuup. # # Copyright (c) 2012-2016, Shoop Commerce Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from __future__ import unicode_literals import json from rest_fra...
order = create_order_with_product( product, shop=shop, supplier=supplier, quantity=1,
taxless_base_unit_price=10, ) order.cache_prices() order.save() return order def get_client(admin_user): client = APIClient() client.force_authenticate(user=admin_user) return client def get_create_payment_url(order_pk): return "/api/shuup/order/%s/create_payment/" % order_p...
obi-two/Rebelion
data/scripts/templates/object/mobile/shared_shaupaut.py
Python
mit
430
0.048837
#### 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 = Creature() result.template = "object/mobile/shared_shaupaut.iff" result.attribute_template_id = 9 result.stfName("monster_name","shaupaut")
#### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
junhuac/MQUIC
src/buildtools/checkdeps/checkdeps_test.py
Python
mit
8,256
0.005208
#!/usr/bin/env python # 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. """Tests for checkdeps. """ import os import unittest import builddeps import checkdeps import results class CheckDepsTest(uni...
ddedCppIncludes( [['checkdeps/testdata/allowed/test.cc', ['#include "checkdeps/testdata/disallowed/temporarily_allowed.h"'] ]]) self.fai
lUnless(problems) def testCopyIsDeep(self): # Regression test for a bug where we were making shallow copies of # Rules objects and therefore all Rules objects shared the same # dictionary for specific rules. # # The first pair should bring in a rule from testdata/allowed/DEPS # into that glob...
sstocker46/pyrobotlab
home/bwjustice1/InMoov.1.py
Python
apache-2.0
1,161
0.012059
inMoov = Runtim
e.createAndStart("inMoov", "InMoov") rightSerialPort = "COM8" cameraIndex = 1 # attach an arduino to InM
oov # possible board types include uno atmega168 atmega328p atmega2560 atmega1280 atmega32u4 # the MRLComm.ino sketch must be loaded into the Arduino for MyRobotLab control ! # set COM number according to the com of your Arduino board inMoov.attachArduino("right","uno", rightSerialPort) # attach the right hand inMoo...
dbbhattacharya/kitsune
vendor/packages/pylint/pyreverse/diagrams.py
Python
bsd-3-clause
8,677
0.003112
# Copyright (c) 2004-2010 LOGILAB S.A. (Paris, FRANCE). # http://www.logilab.fr/ -- mailto:contact@logilab.fr # # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU General Public L
icense as published by the Free Softwa
re # Foundation; either version 2 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. See the GNU General Public License for mo...
Osmose/pontoon
pontoon/base/migrations/0015_remove_project_last_synced.py
Python
bsd-3-clause
355
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, m
igrations class Migration(migrations.Migration): dependencies = [ ('base', '0014_auto_20150806_0948'), ] operations = [ migrations.RemoveField( model_name='p
roject', name='last_synced', ), ]
Royal-Society-of-New-Zealand/NZ-ORCID-Hub
orcid_api_v3/models/amount_v30_rc1.py
Python
mit
3,888
0.000257
# coding: utf-8 """ ORCID Member No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501 OpenAPI spec version: Latest Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import si...
= dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value if issubclass(AmountV30Rc1, dict):
for key, value in self.items(): result[key] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() ...
team-xue/xue
xue/prepopulate/parse.py
Python
bsd-3-clause
718
0
# -*- coding: utf-8 -*- # simple prepopulated tables querier -- input parser from __future__ import unicode_literals, division INPUT_ENCODING = 'utf-8
' FIELDS = ('name', 'gender', 'phone', 'role', 'ident', ) def parse_line(ln): lst = ln.split('$') # may silently eat some items... maybe return lst[0], dict(zip(FI
ELDS, lst[1:])) def parse_lines(lst): result_dct = {} for ln in lst: if ln: num, entry = parse_line(ln) result_dct[num] = entry return result_dct def parse_file(fn): with open(fn, 'rb') as fp: content = fp.read() return parse_lines(content.decode(INPUT_...
janusnic/shoop
shoop/core/api/__init__.py
Python
agpl-3.0
983
0
# -*- coding: utf-8 -*-
# This file is part of Shoop. # # Copyright (c) 2012-2015, Shoop Ltd. All rights reserved. # # This
source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from shoop.api.factories import viewset_factory from shoop.core.api.orders import OrderViewSet from shoop.core.api.products import ProductViewSet, ShopProductViewSet from shoop.core.models import Cont...
ajmendez/timerasp
bin/notify.py
Python
mit
261
0
#!/usr/bin/env python
import sys import time from timera
sp import gmail if __name__ == '__main__': time.sleep(300) gmail.send_email('notify.py: IP:{}'.format(' '.join(sys.argv[1:])), 'Notify was run and is telling you something')
googleads/google-ads-python
google/ads/googleads/v9/services/services/conversion_adjustment_upload_service/client.py
Python
apache-2.0
20,499
0.001317
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
registry is used. Returns: The transport class to use. """ # If a specific transport is requested, return that one. if label: return cls._transport_registry[label] # No transport is requested; return the default (that is, the first one # in the d...
=ConversionAdjustmentUploadServiceClientMeta ): """Service to upload conversion adjustments.""" @staticmethod def _get_default_mtls_endpoint(api_endpoint): """Convert api endpoint to mTLS endpoint. Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleap...
django-leonardo/django-constance
tests/storage.py
Python
bsd-3-clause
3,902
0.001026
# -*- encoding: utf-8 -*- from datetime import datetime, date, time from decimal import Decimal from django.utils import six if six.PY3: def long(value): return value from constance.base import Config class StorageTestsMixin(object): def setUp(self): self.config = Config() super(Sto...
.config.NON_EXISTENT except Exception as e: self.assertEqual(type(e), AttributeError) try: self.config.NON_EXISTENT = 1 except Exception as e: self.assertEqual(type(e), AttributeError) def test_missing_values(self): # set some values and leave ou...
Decimal('1.2') self.config.DATETIME_VALUE = datetime(1977, 10, 2) self.config.DATE_VALUE = date(2001, 12, 20) self.config.TIME_VALUE = time(1, 59, 0) self.assertEqual(self.config.INT_VALUE, 1) # this should be the default value self.assertEqual(self.config.LONG_VALUE, long(654...
Carpe-Noctem/Small-Projects
Basic_Calculator.py
Python
mit
2,337
0.015431
""" This simple Python script embodies its namesake by acting as a basic calculator. Currently, It can perform addition, subtraction, division, multiplication, exponentiation, and square roots. More functions may be added at a later date, or you could add your own! """ from __future__ import division # Importing the p...
tions are inputted break else: print"\nChoose a number (1, 2, 3, 4, 5, 6) for your intended operation." # Error message continue while True: try: a = raw_input("\nChoose your first number: ") ia = float(a) except ValueError: print "\nNegative/positve
integers or decimals only." # Only options allowed continue else: break while True and c != "6": try: b = raw_input("\nChoose your second number: ") ib = float(b) except ValueError: print "\nNegative/positive integers or decimals only." # Only options allowed ...
TrailingDots/async_py_messaging
async_py_messaging/async_server_create_class.py
Python
gpl-3.0
6,718
0.002679
import sys import os import threading import time import types import signal import zmq import pdb import utils # Default port for receiving/sending messages. DEFAULT_PORT = 5590 class AsyncServerCreateClass(threading.Thread): """ Create an asynchronous server class that receives requests and provides ...
worker = self.context.socket(zmq.DEALER) worker.setsockopt(zmq.LINGER, 0) worker.connect('inproc://backend') scheme = self.config.get('scheme', 'tcp') self.control_pub = self.context.socket(zmq.PUB) self.control_pub.setsockopt(zmq.LINGER, 0) endpoint = 'inproc://cont...
r as err: # Common problem: someone else using this port. sys.stderr.write('control bind endpoint: %s: %s\n' % (endpoint, str(err))) self.control_pub.close() self.context.term() os.kill(os.getpid(), signal.SIGINT) # Create a subscr...
glenn-edgar/local_controller_3
py_cf_new_py3/common_functions_py3.py
Python
mit
461
0.036876
class Common_Functions(object): def __init__( self ): pass def cf_counter( self, cf_handle, chainObj, parameters, event ): return_value = True if event["name"] == "INIT": parameters.append(0) return_value = True if ev
ent["name"] == "TIME_TICK": parameters[-1] = parameters[-1]
+1 if parameters[-1] >= parameters[-2]: return_value = False return return_value
sdwebster/learn-python-the-hard-way-solutions
02/ex2.py
Python
mit
84
0.035714
print "here we go
" #comment comment co
mment #more comments herei print 'hi # there'
BhallaLab/moose-thalamocortical
pymoose/gui/qt/PyGLWidget.py
Python
lgpl-2.1
20,528
0.025234
#Author:Chaitanya CH #FileName: PyGLWidget.py (modified from Arne Schmitz code) #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 3, or # (at your option) any later version. # # Th...
e_() #self.catbutt = QtGui.QToolButton(self.toolbar) #self.catbutt.setGeometry(10,0,40,40) #self.catbutt.setIcon(QtGui.QIcon("Search.png")) #self.catbutt2 = QtGui.QToo
lButton(self.toolbar) #self.catbutt2.setGeometry(50,0,40,40) #self.catbutt2.setIcon(QtGui.QIcon("resize.png")) #self.toolbar.allowedAreas(Qt.BottomToolBarArea) self.setMouseTracking(True) self.modelview_matrix_ = [] self.translate_vector_ = [0.0, 0.0,...
matysek/pip-accel
pip_accel/caches/__init__.py
Python
mit
8,425
0.001306
# Accelerator for pip, the Python package manager. # # Author: Peter Odding <peter.odding@paylogic.com> # Last Change: October 31, 2015 # URL: https://github.com/paylogic/pip-accel """ Support for multiple cache backends. This module defines an abstract base class (:class:`AbstractCacheBackend`) to be inherited by cu...
nally based on the article `Using Metaclasses to Creat
e Self-Registering Plugins <http://effbot.org/zone/metaclass-plugins.htm>`_. I've since had to introduce some additional magic to make this mechanism compatible with both Python 2.x and Python 3.x because the syntax for metaclasses is very much inco...
orlandov/parpg-game
scripts/objects/containers.py
Python
gpl-3.0
1,128
0.018617
#!/usr/bin/python #
This file is part of PARPG. # PARPG 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. # PARPG is distributed in the hope th...
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 PARPG. If not, see <http://www.gnu.org/licenses/>. """Containes classes definin...
krahman/BuildingMachineLearningSystemsWithPython
ch10/figure13.py
Python
mit
791
0
# This code is supporting material for the book # Building Machine Learning Systems with Python # by Willi Richert and Luis Pedro Coelho # published by PACKT Publishing # # It is made available under the MIT License import mahotas as mh from mahotas.colors import rgb2grey import numpy as np # Adds a little salt-n-pep...
# Salt & pepper arrays salt = np.random.random(im.shape) > .975 pepper = np.random.random(im.shape) > .975 # salt is 170 & pepper is 30 # Some playing around showed that setting these to more extreme values looks # very artificial. These
look nicer im = np.maximum(salt * 170, mh.stretch(im)) im = np.minimum(pepper * 30 + im * (~pepper), im) mh.imsave('../1400OS_10_13+.jpg', im.astype(np.uint8))
himaaaatti/qtile
libqtile/layout/columns.py
Python
mit
13,874
0.000432
# 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, distribute, sublicense, and/or sell # copi...
d def focus(self, client): for i, c in enumerate(self.columns): if
client in c: c.focus(client) self.current = i break @property def cc(self): return self.columns[self.current] def add_column(self, prepend=False): c = _Column(self.autosplit) if prepend: self.columns.insert(0, c) ...
uncled1023/pygments
Pygments/pygments-lib/pygments/lexers/bibtex.py
Python
bsd-2-clause
4,686
0.002347
# -*- coding: utf-8 -*- """ pygments.lexers.bibtex ~~~~~~~~~~~~~~~~~~~~~~ Lexers for BibTeX bibliography data and styles :copyright: Copyright 2005-2015 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ import re from pygments.lexer import RegexLexer, ExtendedRegexLe...
lexer for BibTeX bibliography styles. .. versionadded:: 2.2 """ name = 'BST' aliases = ['bst', 'bst-pybtex'] filenames = ['*.bst'] flags = re.IGNORECASE | re.MULTILINE tokens = { 'root': [ include('whitespace'), (words(['read', 'sort']), Keyword), ...
s(['function', 'macro']), Keyword, ('group', 'group')), (words(['entry']), Keyword, ('group', 'group', 'group')), ], 'group': [ include('whitespace'), (r'\{', Punctuation, ('#pop', 'group-end', 'body')), ], 'group-end': [ include('whitespac...
jcass77/mopidy
mopidy/m3u/__init__.py
Python
apache-2.0
839
0
import logging import os import mopidy from mopidy import config, ext logger = logging.getLogger(__name__) cla
ss Extension(ext.Extension): dist_name = "Mopidy-M3U" ext_name = "m3u" version = mopidy.__version__ def get_default_config(self): conf_file = os.path.join(os.path.dirname(__file__), "ext.conf") return config.read(conf_file) def get_config_schema(self): schema = super().get...
= config.String() schema["default_extension"] = config.String(choices=[".m3u", ".m3u8"]) schema["playlists_dir"] = config.Path(optional=True) return schema def setup(self, registry): from .backend import M3UBackend registry.add("backend", M3UBackend)
simonwydooghe/ansible
lib/ansible/module_utils/network/eos/facts/facts.py
Python
gpl-3.0
2,719
0.004413
# -*- coding: utf-8 -*- # Copyright 2019 Red Hat # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) """ The facts class for eos this file validates each subset of facts and selectively calls the appropriate facts gathering function """ from __future__ import (absolute_import, ...
.eos.facts.lldp_interfaces.lldp_interfaces import Lldp_interfacesFacts from ansible.module_utils.network.eos.facts.vlans.vlans import VlansFacts from ansible.module_utils.network.eos.facts.legacy.base import Default, Hardware, Config, Interfaces FACT_LEGACY_SUBSETS = dict( default=Default, hardware=Hardware, ...
interfaces=InterfacesFacts, l2_interfaces=L2_interfacesFacts, l3_interfaces=L3_interfacesFacts, lacp=LacpFacts, lacp_interfaces=Lacp_interfacesFacts, lag_interfaces=Lag_interfacesFacts, lldp_global=Lldp_globalFacts, lldp_interfaces=Lldp_interfacesFacts, vlans=VlansFacts, ) class F...
smlbiobot/SML-Cogs
fake/fake.py
Python
mit
3,596
0
# -*- coding: utf-8 -*- """ The MIT License (MIT) Copyright (c) 2017 SML 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...
v = '\n'.join(v) em.add_field(name=k.title(), value=v) await self.bot.say(embed=em) def check_folder(): """Check folder.""" os.makedirs(PATH, exist_ok=T
rue) def check_file(): """Check files.""" if not dataIO.is_valid_json(JSON): dataIO.save_json(JSON, {}) def setup(bot): """Setup.""" check_folder() check_file() n = Fake(bot) bot.add_cog(n)
vejuhust/snippet-crawler
Parser.py
Python
mit
3,773
0.002915
#!/usr/bin/env python3 """JSON data parser for snippet crawler""" from BaseLogger import BaseLogger from DatabaseAccessor import DatabaseAccessor from bs4 import BeautifulSoup from config import config_queue_page, config_idle_sleep, config_parse_domain, config_parse_process from contextlib import closing from datetime...
]["digg_count"], "bury": data["group"]["bury_count"], "favorite": data["group"]["favorite_count"], "comment": data["group"]["comment_count"], } if len(data["comments"]) > 0: comment_text = [] comment_digg = [] ...
comment_digg.append(comment["digg_count"]) snippet["comments"] = comment_text snippet["count"]["commdigg"] = comment_digg if len(snippet["content"].strip()) == 0: snippet = None except Exception as e: snippet = None return sn...
gimli-org/gimli
pygimli/core/base.py
Python
apache-2.0
3,243
0.004009
# -*- coding: utf-8 -*- """ Misc stuff also needed for core imports and monkey patching """ import numpy as np from .core import (RVector3, R3Vector, RMatrix) def isScalar(v, val=None): """Check if v is scalar, i.e. int, float or complex. Optional compare with val. Examples -------- >>> import ...
"" if N is None: return isinstance(v, R3Vector) or \ ( isinstance(v, list) and isPos(v[0])) or \ (not isinstance(v, list) and hasattr(v, '__iter__') and \ not isinstance(v, (str)) and v.ndim == 2 and isPos(v[0])) return isR3Array(v) and len(v) == N isPos...
instance(v, RMatrix) or \ hasattr(v, 'ndim') and v.ndim == 2 or \ isinstance(v, list) and isArray(v[0]) return isMatrix(v) and (hasattr(v, 'shape') and v.shape == shape)
TrevorEdwards/Jauffre
jauffre/interpreter.py
Python
mit
284
0.070423
import command command
_list = ["joke","weather","play","pause","stop","skip","light","security",
"created","name","mood","selfie"] def interpret(s): print "meow" for cmd in command_list: if s.find(cmd) != -1: print cmd return command.Command(cmd).do()
Teagan42/home-assistant
tests/components/fan/test_init.py
Python
apache-2.0
1,122
0
"""Tests for fan platforms.""" import unittest import pytest from homeassistant.components.fan import FanEntity class BaseFan(FanEntity): """Implementation of the abstract FanEntity.""" def __init__(self): """Initialize the fan.""" pass class TestFanEntity(unittest.TestCase): """Test...
elf.fan = None def test_fanentity(self): """Test fan entity methods.""" assert "off" == self.fan.state assert 0 == len(self.fan.speed_list) assert 0 == self.fan.supported_features
assert {"speed_list": []} == self.fan.capability_attributes # Test set_speed not required self.fan.oscillate(True) with pytest.raises(NotImplementedError): self.fan.set_speed("slow") with pytest.raises(NotImplementedError): self.fan.turn_on() with pyt...
twitter/pycascading
examples/word_count.py
Python
apache-2.0
1,485
0.001347
# # 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, s...
rate on is passed in as the first parameter. We are yielding the results in a for loop back. Each word becomes the only field in a new tuple stream, and the string to be split is the 2nd field of the input tuple. """ for word in tuple.get(1).split(): yield [word] def main(): flow = Flo...
the line in the file, and the second is the line as a string. input = flow.source(Hfs(TextLine(), 'pycascading_data/town.txt')) output = flow.tsv_sink('pycascading_data/out') input | split_words | group_by('word', native.count()) | output flow.run(num_reducers=2)
bohdan7/python_koans
python3/koans/about_iteration.py
Python
mit
3,923
0.004333
#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * class AboutIteration(Koan): def test_iterators_are_a_type(self): it = iter(range(1,6)) total = 0 for num in it: total += num self.assertEqual(15 , total) def test_iterating_with_next(self):...
oted from a builtin function # to the functools modul
e. result = functools.reduce(self.add, [2, 3, 4]) self.assertEqual(int, result.__class__) # Reduce() syntax is same as Python 2 self.assertEqual(9, result) result2 = functools.reduce(self.multiply, [2, 3, 4], 1) self.assertEqual(24, result2) # Extra Credit: ...
cloudevents/sdk-python
cloudevents/tests/test_http_json_methods.py
Python
apache-2.0
3,779
0
# All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in...
.dumps(raw_data).encode() data_base64_str = base64.b64encode(data).decode() # Create json
payload payload = { "type": "com.example.string", "source": "https://example.com/event-producer", "id": "1234", "specversion": specversion, "data_base64": data_base64_str, } payload_json = json.dumps(payload) # Create event event = from_json(payload_json) ...
unnikrishnankgs/va
venv/lib/python3.5/site-packages/tensorflow/models/real_nvp/celeba_formatting.py
Python
bsd-2-clause
3,106
0
# Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
============================================ r"""CelebA dataset formating. Download img_align_celeba.zip from http://mmlab.ie.cuhk.edu.hk/projects/CelebA.html under the link "Align&Cropped Images" in the "Img" directory and list_eval_partition.txt under the link "Train/Val/Test Partitions" in the "Eval" directory. Th...
Use the script as follow: python celeba_formatting.py \ --partition_fn [PARTITION_FILE_PATH] \ --file_out [OUTPUT_FILE_PATH_PREFIX] \ --fn_root [CELEBA_FOLDER] \ --set [SUBSET_INDEX] """ import os import os.path import scipy.io import scipy.io.wavfile import scipy.ndimage import tensorflow as tf t...
mppmu/secdec
nodist_examples/Zbb_vertex_correction_finite/F1diminc2_37_bubble.py
Python
gpl-3.0
1,812
0.032561
#! /usr/bin/env python from pySecDec.loop_integral import loop_package import pySecDec as psd li = psd.loop_integral.LoopIntegralFromPropagators( propagators = ['k1^2', '(k1-k2)^2', '(k1-k2+p1)^2-mZ^2', '(k2)^2', '(k2+p2)^2', '(k1+p1+p2)^2', '(k2+p1)^2'], loop_momenta = ['k1'], external_momenta = ['p1','p2','p3','p4...
level = 2, # the WorkSpace parameter for FORM form_work_space = '1G', # the method to be used for the sector decomposition # valid values are ``iterative`` or ``geometric`` or ``geometric_ku`` decomposition_method = 'iterative', # if you choose ``geometric[_ku]`` and 'normaliz' is not in your # $PATH, you can set the...
maliz_executable='/path/to/normaliz', # whether or not to produce code to perform the contour deformation # contour deformation is not required if we only want to compute euclidean points (all Mandelstam invariants negative) contour_deformation = True )
facebook/sparts
sparts/tasks/thrift/nbserver.py
Python
bsd-3-clause
3,112
0.000321
# Copyright (c) 2014, Facebook, Inc. All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. An additional grant # of patent rights can be found in the PATENTS file in the same directory. # """Thrift Server task using TNon...
(host, port) def stop(self): """Overridden to tell the thrift server to shutdown asynchronously""" self.server.stop() self.server.cl
ose() self._stopped = True def _runloop(self): """Overridden to execute TNonblockingServer's main loop""" while not self.server._stop: self.server.serve() while not self._stopped: time.sleep(0.1)
pignacio/chorddb
test/test_chords/__init__.py
Python
gpl-3.0
1,372
0
import random from nose.tools import eq_ from chorddb.chords import Chord from chorddb.notes import Key __KEYS = ["A", "A#", "B", "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#"] _KEYS = [Key.parse(k) for k in __KEYS] _VARIATIONS = ["m", "7", "m7", "maj7"] def _check_text_parsing(chord): eq_(Chord.parse(chord.t...
parsed = Chord.parse(text)
eq_(parsed.key, key) eq_(parsed.variation, variation if variation else None) eq_(parsed.bass, bass)
lparam/xsocks
.ycm_extra_conf.py
Python
gpl-3.0
3,005
0.034942
import os import ycm_core flags = [ '-Wall', '-std=gnu99', '-x', 'c', '-isystem', '/usr/include', '-isystem', '/usr/local/include', '-Isrc', '-I3rd/c-ares', '-I3rd/libuv/include', '-I3rd/libsodium/src/libsodium/include', '-I3rd/libancillary', '-I3rd/libcork/include', '-I3rd/libipset/include', ] compilation_database_...
gs: new_flag = flag if make_next_absolute: make_next_absolute = False if not flag.startswith( '/' ): new_flag = os.path.join( working_directory, flag ) for path_flag in path_flags: if flag == path_flag: make_next_absolute = True br
eak if flag.startswith( path_flag ): path = flag[ len( path_flag ): ] new_flag = path_flag + os.path.join( working_directory, path ) break if new_flag: new_flags.append( new_flag ) return new_flags def IsHeaderFile( filename ): extension = os.path.splitext( filename )[ 1 ...
rkmaddox/mne-python
mne/io/persyst/__init__.py
Python
bsd-3-clause
151
0
"""Persyst module for conversion to
FIF.""" # Author: Adam Li <adam2392@gmail.com> # # License: BSD (3-clause) from .persyst import
read_raw_persyst
eske/seq2seq
scripts/speech/extract.py
Python
apache-2.0
2,752
0.001817
#!/usr/bin/env python2 # -*- coding: utf-8 -*- from __future__ import division import argparse import numpy as np import yaafelib import tarfile import tempfile import os from collections import Counter parser = argparse.ArgumentParser() parser.add_argument('inputs', nargs='+', help='tar archive which contains all the...
, 'energy'] df = fp.getDataFlow() engine = yaafelib.Engine() engine.load(df) afp = yaafelib.AudioFileProcessor() frame_counter = Counter() outfile = open(args.output, 'wb') total = 0 for filename in args.inputs: tar = tarfile.open(filename) total += len([f for f in tar if f.isfile()]) _, tmp_file = tempfil...
r = tarfile.open(filename) files = sorted([f for f in tar if f.isfile()], key=lambda f: f.name) for i, fileinfo in enumerate(files): file_ = tar.extractfile(fileinfo) with open(tmp_file, 'wb') as f: f.write(file_.read()) afp.processFile(engine, tmp_file) feats = eng...
Shrews/PyGerrit
webapp/django/views/i18n.py
Python
apache-2.0
6,587
0.003036
from django import http from django.utils.translation import check_for_language, activate, to_locale, get_language from django.utils.text import javascript_quote from django.conf import settings import os import gettext as gettext_module def set_language(request): """ Redirect to a given url while setting the ...
): packages = packages.split('+') packages = [p for p in packages if p == 'django.conf' or p in settings.INSTALLED_APPS] default_locale = to_locale(settings.LANGUAGE_CODE) locale = to_locale(get_language()) t = {} paths = [] # first load all english languages files for defaults for p...
try: catalog = gettext_module.translation(domain, path, ['en']) t.update(catalog._catalog) except IOError: # 'en' catalog was missing. This is harmless. pass # next load the settings.LANGUAGE_CODE translations if it isn't english if default_locale != '...
Spiderlover/Toontown
toontown/toon/BoardingGroupInviterPanels.py
Python
mit
6,463
0.002166
from pandac.PandaModules import * from toontown.toonbase.ToontownGlobals import * from direct.showbase import DirectObject from direct.directnotify import DirectNotifyGlobal from toontown.toontowngui import TTDialog from otp.otpbase import OTPLocalizer from toontown.toontowngui import ToonHeadDialog from direct.gui.Dir...
rams(self): self.dialogName = 'BoardingGroupInvitationRejectedPanel' self.inviterText = TTLocalizer.BoardingInvitationRejected % self.avata
rName self.panelStyle = TTDialog.Acknowledge self.buttonTextList = [OTPLocalizer.GuildInviterOK]
ANLAB-KAIST/NBA
configs/rss-singlecore.py
Python
mit
2,088
0.002874
#! /usr/bin/env python3 import nba, os import sys for netdev in nba.get_netdevices(): print(netdev) for coproc in nba.get_coprocessors(): print(coproc) node_cpus = nba.get_cpu_node_mapping() for node_id, cpus in enumerate(node_cpus): print('Cores in NUMA node {0}: [{1}]'.format(node_id, ', '.join(map(str, ...
OC_PPDEPTH': int(os.environ.get('NBA_COPROC_PPDEPTH', 2 if no_huge else 32)), 'COPROC_CTX_PER_COMPTHREAD': 1, } print("# logical cores: {0}, # physical cores {1} (hyperthreading {2})".format( nba.n
um_logical_cores, nba.num_physical_cores, "enabled" if nba.ht_enabled else "disabled" )) _ht_diff = nba.num_physical_cores if nba.ht_enabled else 0 io_threads = [ # core_id, list of (port_id, rxq_idx) nba.IOThread(core_id=node_cpus[0][0], attached_rxqs=[(0, 0), (1, 0), (2, 0), (3, 0)], mode='normal'), ] co...
charlesbreeze/eFORGE
docs/eforge-db-construction/construct_erc2-chromatin15state-all_files.py
Python
gpl-3.0
3,559
0.006182
#!/usr/bin/env python import sys import os output_dir = "erc2-chromatin15state-all-files" if not os.path.exists(output_dir): sys.stderr.write("Creating dir [%s]...\n" % (output_dir)) os.makedirs(output_dir) prefix = "/home/cbreeze/for_Alex" suffix = "_15_coreMarks_mnemonics.bed" marks = [ '1_TssA', ...
ile psm_fn = "%s/%s%s" % (prefix, sample, suffix) sys.stderr.write("Reading PSM [%s]...\n" % (psm_fn)) with open(psm_fn, "r") as psm_fh: f
or line in psm_fh: (chr, start, stop, state_call) = line.strip().split('\t') fhs[state_call].write('\t'.join([chr, start, stop]) + '\n') # close handles for mark in marks: sys.stderr.write("Closing output handle to [%s]...\n" % (fns[mark])) fhs[mark].close() fns[mark] = None fhs[mark] = ...
thaihungle/deepexp
deep-process/utility.py
Python
mit
3,652
0.006298
import numpy as np import tensorflow as tf def pairwise_add(u, v=None, is_batch=False): """ performs a pairwise summation between vectors (possibly the same) Parameters: ---------- u: Tensor (n, ) | (n, 1) v: Tensor (n, ) | (n, 1) [optional] is_batch: bool a flag for whether the ve...
the size of the array to be used if shape inference resulted in None Returns: TensorArray the unpacked TensorArray """ shape = value.get_shape().as_list() rank = len(shape)
dtype = value.dtype array_size = shape[axis] if not shape[axis] is None else size if array_size is None: raise ValueError("Can't create TensorArray with size None") array = tf.TensorArray(dtype=dtype, size=array_size) #size of the axis dim_permutation = [axis] +list(range(1, axis)) + [0] + lis...
fstagni/DIRAC
WorkloadManagementSystem/JobWrapper/JobWrapper.py
Python
gpl-3.0
63,187
0.009622
######################################################################## # File : JobWrapper.py # Author : Stuart Paterson ######################################################################## """ The Job Wrapper Class is instantiated with arguments tailored for running a particular job. The JobWrapper starts ...
AC version %s' % DIRAC.buildVersion self.maxPeekLines = gConfig.getValue(self.section + '/MaxJobPeekLines', 20) if self.maxPeekLines < 0: self.maxPeekLines = 0 self.defaultCPUTime = gConfig.getValue(self.section + '/DefaultCPUTime', 600) self.
defaultOutputFile = gConfig.getValue(self.section + '/DefaultOutputFile', 'std.out') self.defaultErrorFile = gConfig.getValue(self.section + '/DefaultErrorFile', 'std.err') self.diskSE = gConfig.getValue(self.section + '/DiskSE', ['-disk', '-DST', '-USER']) self.tapeSE = gConfig.getValue(self.section + '/Ta...
MSzalowski/Pjs2
Pjs/Pjs/wsgi.py
Python
mit
384
0
""" WSGI config for Pjs project. It exposes the WSGI calla
ble as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Pjs.settings") application = get_w
sgi_application()
tjamet/dynker
dynker/builder.py
Python
gpl-2.0
6,135
0.00652
import glob import fnmatch import itertools import logging import os import re import six import sys import yaml from .dockerfile import Dockerfile from .image import ImageBuilder from .config import Config class Builder(object) : def __init__(self, config=None, **kwds) : self.logger = logging.getLogger...
atching_pattern(img_cfg, 'name', path) context_path = self.get_matching_pattern(img_cfg, 'path', path) if found_image_name == image_name: image = ImageBuilder(image_name, contextPath=context_path, doc...
images[image_name] = image return image raise KeyError("Cannot find image %s" % image_name) def imageTag(self, imgName) : imgBuilder = self.images.get(imgName, None) if imgBuilder : return imgBuilder.buildTag() return None def build(self, cli...
emad8878/is210-week-02-warmup
task_02.py
Python
mpl-2.0
113
0
#!/usr/b
in/env python # -*- coding: utf-8 -*- """A file to just
echo your name.""" print 'Hello Emadul Islam!'