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
datafolklabs/cement
cement/ext/ext_plugin.py
Python
bsd-3-clause
7,652
0
""" Cement plugin extension module. """ import os import sys import imp import re from ..core import plugin, exc from ..utils.misc import is_true, minimal_logger from ..utils.fs import abspath LOG = minimal_logger(__name__) # FIX ME: This is a redundant name... ? class CementPluginHandler(plugin.PluginHandler): ...
plugin_dir)) if not os.path.exists(plugin_dir): LOG.debug("plugin directory '%s' does not exist." % plugin_dir) return False try: f, path, desc = imp.find_module(plugin_name, [plugin_dir]) except ImportError: LOG.debug("plugin '%s' does not exist...
(plugin_name, plugin_dir)) return False # We don't catch this because it would make debugging a # nightmare mod = imp.load_module(plugin_name, f, path, desc) if mod and hasattr(mod, 'load'): mod.load(self.app) return True def _load_plugin_from_boots...
hgiemza/DIRAC
WorkloadManagementSystem/private/DIRACPilotDirector.py
Python
gpl-3.0
13,788
0.023789
######################################################################## # $HeadURL$ # File : DIRACPilotDirector.py # Author : Ricardo Graciani ######################################################################## """ Dirac PilotDirector class, it uses DIRAC CE backends to submit and monitor pilots. It include...
a CE object for the current CE is available, instantiate one if necessary """ for CE in
ceList: if CE not in self.computingElementDict: ceFactory = ComputingElementFactory( ) ceInstance = ceFactory.getCE( ceName = CE ) if not ceInstance['OK']: self.log.error('Can not create CE object:', ceInstance['Message']) return self.computingElementDict[CE] =...
xplv/qtile
libqtile/layout/zoomy.py
Python
mit
5,680
0.000176
# Copyright (c) 2011 Mounier Florian # Copyright (c) 2011 Paul Colomiets # Copyright (c) 2012 Craig Barnes # Copyright (c) 2012, 2014 Tycho Andersen # Copyright (c) 2013 Tao Sauvage # Copyright (c) 2014 ramnes # Copyright (c) 2014 Sean Vig # Copyright (c) 2014 dmpayton # Copyright (c) 2014 dequis # # Permission is here...
next(self, client): if client not in self.clients:
return idx = self.clients.index(client) return self.clients[(idx + 1) % len(self.clients)] def focus_previous(self, client): if not self.clients: return idx = self.clients.index(client) return self.clients[idx - 1] def clone(self, group): c ...
Alaxe/judgeSystem
judge/views/testgroup.py
Python
gpl-2.0
4,074
0.011537
from django.core.urlresolvers import reverse from django.contrib import messages from django.contrib.auth.mixins import PermissionRequiredMixin from django.db.models import Q from django.forms import ModelForm from django.shortcuts import render, get_object_or_404, redirect from django.views.generic import View, Templa...
= pk) form = TestGroupForm(request.POST, instance = testGroup) if form.is_valid(): testGroup = form.save() self.update_tests(testGroup, request)
testGroup.problem.update_max_score() return redirect(self.redir_pattern, problem_id = testGroup.problem.pk) else: context = self.get_context(form = form, pk = pk) return render(request, self.template_name, context) class TestGroupNew(TestGroupEdit): permissio...
Azure/azure-sdk-for-python
sdk/eventhub/azure-mgmt-eventhub/azure/mgmt/eventhub/v2021_06_01_preview/aio/operations/_namespaces_operations.py
Python
mit
59,471
0.005061
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request async def extract_data(pipeline_response): deserialized = self._deserialize('EHNamespaceListResult', pipeline_r
esponse) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link)
Esri/executive-dashboard
ExecutiveReportingScript/arcrest/agol/helperservices/__init__.py
Python
apache-2.0
160
0.00625
from __future__ import absolute_import from .analysis
import * from .elevation import * from .hydrology import * #from .geocoder import *
__version__ = "3.5.3"
Lyla-Fischer/client_side_authoring
setup.py
Python
agpl-3.0
1,001
0.001998
"""Setup for client_side_authoring XBlock.""" import os from setuptools import setup def package_data(pkg, roots): """Generic function to find package_data. All of the files under each of the `roots` will be declared as package data for package `pkg`. """ data = [] for root in roots: ...
d(os.path.relpath(os.path.join(dirname, fname), pkg)) return {pkg: data} setup( name='client_side_authoring-xblock', version='0.1', description='client_side_authoring XBlock', # TODO: write a better description. packages=[ 'client_side_authoring', ], install_requires=[ '...
ints={ 'xblock.v1': [ 'client_side_authoring = client_side_authoring:ClientSideAuthoringXBlock', ] }, package_data=package_data("client_side_authoring", ["static", "public"]), )
gr4viton/gr4Dalek
spine/dd/spine/lcd_i2c.py
Python
gpl-3.0
7,727
0.015142
#!/usr/bin/python # # lcd_i2c.py # lcd1602 class for character display initialization and usage via micropython # Supports 16x2 and 20x4 screens. # # Author : gr4vion # Date : 28-10-2016 # # On the base of: Matt Hawkins # http://www.raspberrypi-spy.co.uk/ # and 2013-2015 Danilo Bargen RPILCD # # Copyright 2015 Mat...
LCD_MOVERIGHT = 0x04 LCD_MOVELEFT = 0x00 # Flags for function set LCD_8BITMODE = 0x10 LCD_4BITMODE = 0x00 LCD_2LINE = 0x08 LCD_1LINE = 0x00 LCD_5x10DOTS = 0x04 LCD_5x8DOTS = 0x00 # Flags for RS pin modes RS_INSTRUCTION = 0x00 RS_DATA = 0x01 null_char = ' ' de...
s=True): self.i2c = i2c self.I2C_ADDR = lcd_addr self.LCD_WIDTH = LCD_WIDTH self.NUM_LINES = NUM_LINES self.backlight_status = backlight_status self.update_backligth() self._cursor_pos = [0,0] # self.lcd_a = lcd_addr self.row_offsets = [0x00, 0x40...
cooktheryan/commissaire
test/test_handlers_status.py
Python
gpl-3.0
2,512
0
# Copyright (C) 2016 Red Hat, Inc # # 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 program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even t
he 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 this program. If not, see <http://www.gnu.org/licenses/>. """ Test cases for the commissaire.handlers....
RoyalDev/RoyalCommands-converter
converter/__init__.py
Python
gpl-3.0
3,485
0.007461
from os.path import exists, isdir try: from yaml import CLoader as Loader, CDumper as Dumper except ImportError: from yaml import Loader, Dumper PROMPT = "> " def chunks(l, n): # noinspection PyArgumentList for i in range(0, len(l), n): yield l[i:i + n] # noinspection PyUnusedLocal def good_...
d_dir = None while True: wanted_dir = get_str(screen, header=header + [error], prompt=prompt, clear=clear, default=default) if exists(wanted_dir) and isdir(wanted_dir): break if not exists(wanted_dir): error = "That directory didn't e
xist!" elif not isdir(wanted_dir): error = "That is not a directory." return wanted_dir def convert(old_plugin, conversion): royalcommands = {} for k, v in conversion.items(): if "." in k: conversion.pop(k) conversion[".".join(k.split(".")[1:])] = v ...
schreiberx/sweet
mule_local/python/mule_local/rexi/quadrature.py
Python
mit
2,629
0.003423
#! /usr/bin/env python3 import numpy as np import sys def _quad_coeffs_hq(M, collocation_type, digits=20): if M == 1: x = np.array([0.0]) w = np.array([2.0]) elif collocation_type == "gauss_legendre": from sympy.integrals.quadrature import gauss_legendre x, w = gauss_legendre...
w, dtype=float) elif collocation_type == "gauss_chebyshev_t": from sympy.integrals.quadrature import gau
ss_chebyshev_t x, w = gauss_chebyshev_t(M, 30) x = np.array(x, dtype=float) w = np.array(w, dtype=float) else: raise Exception("Unknown collocation method '"+str(collocation_type)+"'") assert len(x) == M return x, w def quad_coeffs(M, collocation_type): if M == 1:...
aaronkurtz/gourmand
gourmand/tools/utils.py
Python
gpl-2.0
374
0
from django.conf import settings def show_toolbar(request):
if settings.DEBUG or request.user.is_superuser: debug = request.GET.get("debug", None) if debug == "on":
request.session["debug"] = True elif debug == "off" and "debug" in request.session: del request.session["debug"] return "debug" in request.session
tdegeus/pybind11_examples
09_numpy_cpp-custom-matrix/test.py
Python
mit
277
0.032491
im
port numpy as np import example A = np.arange(5) B = np.arange(5) print(example.mul(A,B)) A = np.arange(25).reshape(5,5) B = np.arange(25).reshape(5,5) print(example.mul(A,B)) A = np.arange(125).reshape(5,5,5) B = np.arange(125).reshape(5,5,5) print(example.mul(A,B))
fabsx00/chucky-old
sourceutils/expressionTrees/embedding/ExpressionTreeToStringConverter.py
Python
gpl-3.0
964
0.005187
from libjoern.pythonast.TreeToStringsConverter import TreeToStringsConverter class ExpressionTreeToStringsConverter(TreeToStringsConverter): def __init__(self): TreeToStringsConverter.__init__(self) def leafNodeToString(self, node): return '@+%s+@' % (str(node.row[1])) def nonLea...
e.row[1] == 'NULL': return False return True def skipChildExpansion(self, child): # discards arguments of
calls! # might want to remove this but need tracking then if child.getType() == 'ARGUMENT': return True return False
stympy/ansible-modules-extras
packaging/os/pkgng.py
Python
gpl-3.0
11,133
0.007545
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2013, bleader # Written by bleader <bleader@ratonland.org> # Based on pkgin module written by Shaun Zinck <shaun.zinck at gmail.com> # that was based on pacman module written by Afterburn <http://github.com/afterburn> # that was based on apt module written by Matthew W...
fying an annotation. If setting or modifying annotations, a value must be prov
ided. required: false version_added: "1.6" pkgsite: description: - for pkgng versions before 1.1.4, specify packagesite to use for downloading packages, if not specified, use settings from /usr/local/etc/pkg.conf for newer pkgng versions,...
petrjasek/superdesk-ntb
server/ntb/io/feeding_services/newsworthy.py
Python
agpl-3.0
6,489
0.002466
# -*- coding: utf-8; -*- # # This file is part of Superdesk. # # Copyright 2013, 2014 Sourcefabric z.u. and contributors. # # For the full copyright and license information, please see the # AUTHORS and LICENSE files distributed with this source code, or # at https://www.sourcefabric.org/superdesk/license import logg...
expires=update_ingest.get_task_ttl(provider), kwargs=kwargs) class NewsworthyFeedingService(FeedingService): """ Feeding Service class which can retrieve articles fro
m Newsworthy web service """ NAME = 'newsworthy' ERRORS = [IngestApiError.apiRequestError().get_error_description(), SuperdeskIngestError.notConfiguredError().get_error_description()] label = 'Newsworthy' fields = [ { 'id': 'url', 'type': 'text', 'label': 'Use t...
kmackay/emk
tutorial/5_modules/emk_rules.py
Python
bsd-2-clause
149
0
emk.module_paths.append(emk.abspath("modules")) c, revision = emk.module("c", "revision") e
mk.depend("$:build:$/revision" + c.o
bj_ext, "revision.h")
rohithpr/bookmark-manager
bookmarks/models.py
Python
mit
1,003
0.000997
from django.core.validators import MinLengthValidator, MinValueValidator from django.db import models from model_utils.models import TimeStampedModel class Item(TimeStampedModel): class Kinds(models.TextChoices): BOOKMARK = "bookmark" key = models.CharField(max_length=20, validators=[MinLengthValidat...
s.TextField(validators=[MinLengthValidator(1)]) kind = models.CharField(max_length=20, choices=Kinds.choices, default=Kinds.BOOKMARK) row = models.IntegerField(MinValueValidator(0),) collection = models.ForeignKey(
"Collection", on_delete=models.CASCADE) def __str__(self): return f"{self.key}::{self.row}::{self.collection.key}" class Collection(TimeStampedModel): key = models.CharField(max_length=20, validators=[MinLengthValidator(1)]) column = models.IntegerField(MinValueValidator(0)) row = models.Inte...
theguardian/JIRA-APPy
lib/pytz/tests/test_tzinfo.py
Python
gpl-2.0
29,501
0.002034
# -*- coding: ascii -*- import sys, os, os.path import unittest, doctest try: import cPickle as pickle except ImportError: import pickle from datetime import datetime, time, timedelta, tzinfo import warnings if __name__ == '__main__': # Only munge path if invoked as a script. Testrunners should have setup...
_tz, '%s did not roundtrip' % tz.zone) def testDst(self): tz = pytz.timezone('Europe/Amsterdam') dt = datetime(2004, 2, 1, 0, 0, 0) for localized_tz in tz._tzinfos.values(): self._roundtrip_tzinfo(localized_tz) self._roundtrip_datetime(dt.replace(tzinfo=localized_tz...
(self): dt = datetime(2004, 2, 1, 0, 0, 0) for zone in pytz.all_timezones: tz = pytz.timezone(zone) self._roundtrip_tzinfo(tz) def testDatabaseFixes(self): # Hack the pickle to make it refer to a timezone abbreviation # that does not match anything. The unpic...
zoni/Rocket
rocket/main.py
Python
mit
6,710
0.00924
# -*- coding: utf-8 -*- # This file is part of the Rocket Web Server # Copyright (c) 2010 Timothy Farrell # Import System Modules import sys import time import socket import logging import traceback from threading import Lock try: from queue import Queue except ImportError: from Queue import Queue # Import P...
monitor_queue = self.monitor_queue, min_threads = min_threads, max_threads = max_threads) # Build our
socket listeners self.listeners = [Listener(i, queue_size, self.active_queue) for i in self.interfaces] for ndx in range(len(self.listeners)-1, 0, -1): if not self.listeners[ndx].ready: del self.listeners[ndx] if not self.listeners: log.critical("No inter...
carlgao/lenga
images/lenny64-peon/usr/share/python-support/mercurial-common/mercurial/copies.py
Python
mit
7,357
0.002583
# copies.py - copy detection for Mercurial # # Copyright 2008 Matt Mackall <mpm@selenic.com> # # This software may be used and distributed according to the terms # of the GNU General Public License, incorporated herein by reference. from node import nullid, nullrev from i18n import _ import util, heapq def _nonoverla...
_dirname(src), _dirname(dst) if dsrc in invalid: # already seen to be uninteresting continue elif dsrc in d1 and ddst in d1: # directory wasn't entirely moved locally invalid[dsrc] = True elif
dsrc in d2 and ddst in d2: # directory wasn't entirely moved remotely invalid[dsrc] = True elif dsrc in dirmove and dirmove[dsrc] != ddst: # files from the same directory moved to two different places invalid[dsrc] = True else: # looks good so...
dezelin/scons
scons-local/SCons/Tool/MSCommon/netframework.py
Python
mit
2,754
0.002542
# # Copyright (c) 2001 - 2014 The SCons Foundation # # 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...
n import read_reg, debug # Original value recorded by dcournapeau _FRAMEWORKDIR_HKEY_ROOT = r'Software\Microsoft\.NETFramework\InstallRoot' # On SGK's system _FRAMEWORKDIR_HKEY_ROOT = r'Software\Microsoft\Microsoft SDKs\.NETFramework\v2.0\InstallationFolder' def find_framework_root(): # XXX: find it from environm...
try: froot = read_reg(_FRAMEWORKDIR_HKEY_ROOT) debug("Found framework install root in registry: %s" % froot) except WindowsError, e: debug("Could not read reg key %s" % _FRAMEWORKDIR_HKEY_ROOT) return None if not os.path.exists(froot): debug("%s not found on fs" % froot)...
radioteria/file-server
config.py
Python
mit
1,264
0.012739
# -*- coding: utf-8 -*- import os, argparse from flask import Flask parser = argparse.ArgumentParser() #настройка аргументов принимаемых с консоли parser.add_argument("--port", default='7000', type=int, help='Port to listen'), parser.add_argument("--hash-algo", default='sha1', type=str, help='Hashing algorithm to ...
p='secret key'), args = parser.parse_args() port = args.port #обработка параметров получаемых с консоли hash_algo = args.hash_algo content_dir = args.content_dir secret = args.secret BASE_DIR = os.path.abspath('.') if os.path.exists(os.path.join(BASE_DIR, content_dir)) == False: #если нету папки 'UPLOADS', в кот...
lask(__name__) app.config['UPLOAD_FOLDER'] = os.path.join(BASE_DIR, content_dir) app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 #Максимальный размер загружаемых файлов (16 mb)
RadioCampusClermontFerrand/paulo-rebuild
paulo-consolidation.py
Python
gpl-3.0
5,019
0.009364
#!/usr/bin/env python # -*- coding: utf-8 -*- import paulo import getopt import sys import os.path # usage: # export PYTHONUNBUFFERED=1 # ./paulo-consolidation.py -c backup-titres.csv -i /media/jm/Elements/backup/musique/ -o /mnt/paulo/home/sound/ -I 0.4 | tee -a log-copy.txt def usage(): print "Usage: paulo-co...
ulo.setTags(outputDir + "/" + entry.getTargetFile(), entry) log.append(entry.toCSVLine()) else: if interactiveThresold != None: print "Score: " + str(bestScore) + "\n" + str(entry) + "\n" + str(result[entry][1]) if paulo.prompt("Do you...
ile?"): print "Manual copy: " + outputDir + "/" + entry.getTargetFile() paulo.copy(outputDir + "/" + entry.getTargetFile(), result[entry][1].filename) paulo.setTags(outputDir + "/" + entry.getTargetFile(), entry) log.append(...
voyagersearch/voyager-py
extractors/VoyagerWorkerPy.py
Python
apache-2.0
3,354
0.003876
# -*- coding: utf-8 -*- # (C) Copyright 2014 Voyager Search # # 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...
ion() }, 'extractors': extractors } def extract(self, infile, job, name): extkls = self.get_extractor(name) if extkls is None: # No such extractor pass else:
extinst = extkls() extinst.extract(infile, job) def get_extractor(self, name): if self.extmap is None: self.extmap = {} if self.extmap.has_key(name): return self.extmap[name] return None if __name__ == "__main__": VoyagerExtractorPy().run(...
guedou/scapy-bpf
scapy/layers/l2.py
Python
gpl-2.0
25,633
0.011548
## This file is part of Scapy ## See http://www.secdev.org/projects/scapy for more informations ## Copyright (C) Philippe Biondi <phil@secdev.org> ## This program is published under a GPLv2 license """ Classes and functions for layer 2 protocols. """ import os, struct, time, socket from scapy.base_classes import Net...
turn cls class LLC(Packet): name = "LLC" fields_desc = [ XByteField("dsap", 0x00), XByteField("ssap", 0x00), ByteField("ctrl", 0) ] conf.neighbor.register_l3(Ether, LLC, lambda l2,l3: co
nf.neighbor.resolve(l2,l3.payload)) conf.neighbor.register_l3(Dot3, LLC, lambda l2,l3: conf.neighbor.resolve(l2,l3.payload)) class CookedLinux(Packet): name = "cooked linux" fields_desc = [ ShortEnumField("pkttype",0, {0: "unicast", 4:"sent-by-us"}), #XXX incom...
sjsrey/pysal_core
pysal_core/io/util/wkb.py
Python
bsd-3-clause
7,872
0.0047
""" Load WKB into pysal shapes. Where pysal shapes support multiple parts, "MULTI"type shapes will be converted to a single multi-part shape: MULTIPOLYGON -> Polygon MULTILINESTRING -> Chain Otherwise a list of shapes will be returned: MULTIPOINT -> [pt0, ..., ptN] Some concepts aren't well supported by...
# To allow recursive calls, read only the bytes we need. if hasattr(s, 'read'): dat = s else: dat = StringIO(s) endian = ENDIAN[dat.read(1)] typ = struct.unpack('I', dat.read(4))[0] if typ == 1:
""" WKBPoint { byte byteOrder; uint32 wkbType; 1 Point point; } Point { double x; double y; }; """ x,y = struct.unpack(endian+'dd', dat.read(16)) r...
atzengin/OCC
occ/python/Platform.py
Python
gpl-3.0
2,394
0.002506
__doc__ = """ Copyright 2008-2011 Free Software Foundation, Inc. This file is part of GNU Radio OpenCV Companion 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...
(self): """ Make a platform for ocvc. """ #ensure hier dir if not os.path.exists(HIER_BLOCKS_LIB_DIR): os.mkdir(HIER_BLOCKS_LIB_DIR) #convert block paths to absolute paths block_paths = set(map(os.path.abspath, BLOCKS_DIRS)) #init _Platform.__init_...
te='http://http://project.kotto.com.tr', block_paths=block_paths, block_dtd=BLOCK_DTD, default_flow_graph=DEFAULT_FLOW_GRAPH, generator=Generator, colors=COLORS, ) _GUIPlatform.__init__(self) ############################################## ...
loopingz/nuxeo-drive
nuxeo-drive-client/nxdrive/tests/test_drive_edit.py
Python
lgpl-2.1
18,778
0.001544
import os import time from nose.plugins.skip import SkipTest from nxdrive.client import LocalClient from nxdrive.tests.common import OS_STAT_MTIME_RESOLUTION from nxdrive.client.common import LOCALLY_EDITED_FOLDER_NAME from nxdrive.tests.common_unit_test import UnitTestCase DRIVE_EDIT_XATTR_NAMES = ['ndrive', 'nxdriv...
def tearDownApp(self): self.drive_edit.stop() super(TestDriveEdit, self).tearDownApp() de
f test_filename_encoding(self): filename = u'Mode op\xe9ratoire.txt' doc_id = self.remote.make_file('/', filename, 'Some content.') # Linux / Win + Chrome: quoted utf-8 encoded browser_filename = 'Mode%20op%C3%A9ratoire.txt' self._drive_edit_update(doc_id, filename, browser_file...
lostinplace/filtered-intervaltree
setup.py
Python
mit
1,509
0.000663
from setuptools import setup, find_packages from codecs import open from os import path import os here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'readme.md'), encoding='utf-8') as f: long_description = f.read() with open(path.join(here, '.library-version'), encoding='utf-8') as f: exis...
ail
='cmwhee@gmail.com', license='MIT', # See https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Topic :: Software Development :: Libraries', 'License :: OSI Approved :: MIT License', ...
LPM-HMS/COSMOS2
examples/local_gpus.py
Python
gpl-3.0
895
0.002235
import os from cosmos.api import Cosmos, py_call from cosmos.util.helpers import environment_variables def use_cuda_device(some_arg, num_gpus): assert "CUDA_VISIBLE_DEVICES" in os.environ print(("some_arg", some_arg)) print(("CUDA_VISIBLE_DEVICES", os.environ["CUDA_VISIBLE_DEVICES"])) assert len(os.e...
num_gpus def main(): cosmos = Cosmos().initdb() workflow = cosmos.start("gpu", skip_confirm=True) for i, num_gpus in enumerate([1, 1, 2, 2, 3]): task = workflow.add_task( use_cuda_d
evice, dict(some_arg=i, num_gpus=num_gpus), gpu_req=num_gpus, uid=str(i), ) workflow.run( max_gpus=len(os.environ["COSMOS_LOCAL_GPU_DEVICES"].split(",")), cmd_wrapper=py_call, ) if __name__ == "__main__": with environment_variables(COSMOS_LOCAL_GPU_DEVICES="0,1,3"): main()
jrjhealey/bioinfo-tools
fastafetcher.py
Python
gpl-3.0
4,793
0.002712
#!/usr/bin/env python # Extract fasta files by their descriptors stored in a separate file. # Requires biopython # TODO: # - Create more sophisticated logic for matching IDs/Descriptions/Partial matches etc. # - Create a mode variable to encapsulate invert/partial/description/id etc? from Bio import SeqIO import s...
s to search the multifasta for. Must be one per line.", ) parser.add_argument( "-s"
, "--string", action="store", help="Provide a string to look for directly, instead of a file (can accept a comma separated list of strings).", ) parser.add_argument( "-o", "--outfile", action="store", default=None, ...
extesla/dice-python
tests/dice/tokens/test_term.py
Python
mit
1,315
0
# The MIT License (MIT) # # Copyright (c) 2016 Sean Quinn # # 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...
r sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditio
ns: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PU...
meshulam/chicago-justice
cjp/cjpusers/views.py
Python
gpl-3.0
4,777
0.009629
from cjp.settings.base import CJP_ROOT # TODO: don't rely on this from django.shortcuts import render_to_response, redirect from django.template import RequestContext from django.contrib.auth.models import User from django import forms class UserForm(forms.Form): firstName = forms.CharField(label="First Name"...
name, 'email' : managedUser.emai
l, 'inactive' : not managedUser.is_active }) except Exception as e: managedUser = None data = {'managedUser' : managedUser, 'userForm': userForm, 'updateSuccess': updateSuccess} return render_to_response('registration/userUpdate.html', data, ...
jlafon/PynamoDB
pynamodb/connection/table.py
Python
mit
12,792
0.000235
""" PynamoDB Connection classes ~~~~~~~~~~~~~~~~~~~~~~~~~~~ """ from typing import Any, Dict, Mapping, Optional, Sequence from pynamodb.connection.base import Connection, MetaTable, OperationSettings from pynamodb.constants import DEFAULT_BILLING_MODE, KEY from pynamodb.expressions.condition import Condition from pyn...
connect_timeout_seconds=connect_timeout_seconds, read_timeout_seconds=read_timeout_seconds, max_retry_attempts=max_retry_attempts, base_backoff_ms=base_backoff_ms, m...
x_pool_connections=max_pool_connections, extra_headers=extra_headers) if aws_access_key_id and aws_secret_access_key: self.connection.session.set_credentials(aws_access_key_id, aws_secret_access_key, ...
bodylabs/blmath
blmath/geometry/__init__.py
Python
bsd-2-clause
155
0
fr
om blmath.geometry.primitives.box import Box from blmath.geometry.primitives.plane import Plane from blmath.geometry.primitives.polyline im
port Polyline
sfu-fas/coursys
marking/migrations/0001_initial.py
Python
gpl-3.0
10,263
0.0038
# -*- coding: utf-8 -*- from django.db import models, migrations import autoslug.fields import django.core.files.storage import marking.models class Migration(migrations.Migration): dependencies = [ ('grades', '0001_initial'), ('groups', '0001_initial'), ] operations = [ migrat...
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('overall_comment', models.TextField(max_length=1000, null=True, blank=True)), ('created_by', models.CharField(help_text=b'Userid who gi
ves the mark', max_length=8)), ('created_at', models.DateTimeField(auto_now_add=True)), ('mark', models.CharField(max_length=2, choices=[(b'A+', b'A+ (Excellent performance)'), (b'A', b'A (Excellent performance)'), (b'A-', b'A- (Excellent performance)'), (b'B+', b'B+ (Good performance)')...
ibamacsr/imagery
imagery/migrations/0019_auto_20151103_1028.py
Python
agpl-3.0
686
0.001458
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import imagery.models class Migration(migrations.Migration): dependencies = [ ('imagery', '0018_auto_20151026_1404'), ] operations = [ migrations.AlterField( model_name='...
ield=models.CharField(unique=True, max_length=21), ), migrations.AlterField( model_name='scenerequest', name='scene_name',
field=models.CharField(validators=[imagery.models.validate_scene_name], unique=True, max_length=21, verbose_name='Scene name'), ), ]
normanjaeckel/WLANSimulationGame
wlan_simulation_game/game/templatetags/wlan_simulation_game_extras.py
Python
mit
866
0
from constance import config from django import template from django.core.urlresolvers import reverse register = template.Library() @register.simple_tag(takes_context=True) def url_href_class_current(context, url_name): """ This custom template tag checks whether the requested path starts with the given ...
html_tag_attributes = 'href="%s"' % url if (context['request'].path.startswith(url) and (context['request'].path == '/' or not url == '/')): html_tag_attributes += ' class="current"' return html_tag_attributes @
register.filter def rest_interceptions(count): """ Returns the differenc between the maximum number of interceptions the the given value. """ return config.number_of_interceptions - count
robsontpm/hiruotso
src/hiruotso/settings/common.py
Python
mit
2,916
0.000343
# coding: utf-8 """ Those are common settings overwritten for more specific tasks You should use either settings.development or settings.production """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os # One level up from this file (dirname(dirname()) == ../) BASE_DIR = os.path.dirna...
oject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } }
# Internationalization # https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.8/howto/static-files/ STATIC_URL = '/static/'
schmit/intro-python-course
lectures/code/list_mult.py
Python
mit
131
0.007634
myList = ['hello',
'world'] myLis
t * 2 # ['hello', 'world', 'hello', 'world'] 2 * myList # ['hello', 'world', 'hello', 'world']
elizabethgoldman/emerging_hotspots
test.py
Python
apache-2.0
277
0.018051
import fiona meta = fiona.open(r'U:\egoldman\hs_2015_update\footprint.shp').meta with fiona.open(r'U:\egoldman\hs_2015_update\merge.shp', 'w', **meta) as output: for features in fi
ona.open(r'U:\egoldman\hs_2015_update\footprint.shp'): output.wri
te(features) output.close()
pmav99/interpolation
tests/__init__.py
Python
bsd-3-clause
370
0
#!/usr/bin/env python # -*- coding: utf-8 -*- """ author: Panagiotis Mavrogiorgos email : gmail, pmav99 """ from __future__ import di
vision from __future__ import print_function from __future__ import unicode_literals from __future__ import absolute_import import sys if sys.version_info.major < 3: from future_builtins import map, zip, hex, oct,
filter, ascii
le717/LR-Track-Selector
setup.py
Python
mit
1,317
0
#! /usr/bin/python3.4-32 # -*- coding: utf-8 -*- # <pep8-80 compliant> """LEGO Racers Track Selector Created 2013-2014 Triangle717 <http://le717.github.io/> Licensed under The MIT License <http://opensource.org/licenses/MIT/> """ import os import sys from cx_Freeze import setup, Executable import constants as cons...
it binaries are not frozen. Please freeze using 32-bit Python 3.3 or greater.""") raise SystemExit(0) # Mac OS X elif sys.platform == "darwin": destfolder = os.path.join("bin", "Mac OS X") # Linux else: destfolder = os.path.join("bin", "Linux") # Create the freeze path if it doesn't exist if not os.p...
e_options = {"build_exe": destfolder, "include_files": ["LICENSE"]} setup( name=const.appName, version="{0}{1}".format(const.majVer, const.minVer), author=const.creator, description="", options={"build_exe": build_exe_options}, executables=[Executable("LRTrackSelector.pyw", tar...
Bozhidariv/statisticum
statisticum/profiles/models.py
Python
gpl-2.0
1,019
0.000981
import os import hashlib import datetime from django.db import models from django.conf import settings from django.contrib.auth.models import User from django.db import connection from django.db.models.signals import post_save def set_user_password(user, password): if user and password: password = passwor...
r_password class UserProfile(models.Model): GENDER_MALE = 1 GERNDER_FEMALE = 2 GENDERS = ( (GENDER_MALE, 'male'), (GERNDER_FEMALE, 'famale') ) DEFAULT_PROFILE_IMAGE = "profile/avatar.gif" user = models.ForeignKey(User) gender = models.I
ntegerField(choices=GENDERS, blank=True, null=True) class Meta: db_table = 'profiles' def create_user_profile(sender, instance, created, **kwargs): if created: profile, created = UserProfile.objects.get_or_create(user=instance) post_save.connect(create_user_profile, sender=User)
adityaduggal/erpnext
erpnext/regional/united_arab_emirates/setup.py
Python
gpl-3.0
4,165
0.026891
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe, os, json from frappe.custom.doctype.custom_field.custom_field import create_custom_fields from erpnext.setup.setup_wizard.operations.tax...
, 'Purchase Receipt Item': invoice_item_fields, 'Supplier Quotati
on Item': invoice_item_fields, } create_custom_fields(custom_fields) def add_print_formats(): frappe.reload_doc("regional", "print_format", "detailed_tax_invoice") frappe.reload_doc("regional", "print_format", "simplified_tax_invoice") frappe.reload_doc("regional", "print_format", "tax_invoice") frappe.db.sql(...
vevurka/pbc
image_detector/utils.py
Python
gpl-3.0
157
0.006369
import m
atplotlib.pyplot as plt # Aux functions for trainer. def display_image(image): plt.ion() plt.imshow(image, cmap='Greys_r') plt.draw(
)
DoWhatILove/turtle
programming/python/web/learning_log/learning_logs/migrations/0001_initial.py
Python
mit
623
0.001605
# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2017-07-10 01:36 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Topic'...
bose_name='ID')),
('text', models.CharField(max_length=200)), ('date_added', models.DateTimeField(auto_now_add=True)), ], ), ]
atareao/national-geographic-wallpaper
src/autostart.py
Python
gpl-3.0
3,791
0
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # This file is part of daily-wallpaper # # Copyright (c) 2017 Lorenzo Carbonell Cerezo <a.k.a. atareao> # # 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 t...
'X-MATE-Autostart-enabled'] = \ str(autostart).lower() with open(self.autostart_file,
'w') as configfile: config.write(configfile) def get_autostart(self): if not os.path.exists(self.autostart_file): self.create(False) return False config = configparser.ConfigParser() config.read(self.autostart_file) if config['Desktop Entry'][...
andymckay/zamboni
mkt/api/tests/test_paginator.py
Python
bsd-3-clause
4,864
0
from urlparse import urlparse from django.core.paginator import Paginator from django.http import QueryDict from nose.tools import eq_ from test_utils import RequestFactory from amo.tests import ESTestCase, TestCase from mkt.api.paginator import MetaSerializer, ESPaginator from mkt.webapps.indexers import WebappInd...
lized['total_count'], len(data)) eq_(serialized['limit'], per_page) prev = urlparse(serialized['previous']) eq_(prev.path, self.url) eq_(QueryDict(prev.query), QueryDict('limit=2&offset=4')) eq_(serialized['next'], None) def test_with
out_request_path(self): data = ['a', 'b', 'c', 'd', 'e'] per_page = 2 page = Paginator(data, per_page).page(2) serialized = MetaSerializer(page).data eq_(serialized['offset'], 2) eq_(serialized['total_count'], len(data)) eq_(serialized['limit'], per_page) ...
true7/srt
src/srt/urls.py
Python
mit
1,086
0.001842
"""srt URL Configuration The `u
rlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: fro...
to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf import settings from django.conf.urls.static import static from d...
rplevka/robottelo
robottelo/cli/virt_who_config.py
Python
gpl-3.0
1,569
0.000637
""" Usage: hammer virt-who-conf
ig [OPTIONS] SUBCOMMAND [ARG] ... Parameters:: SUBCOMMAND subcommand [ARG] ... subcommand arguments Subcommands:: create Create a virt-who configuration delete Delete a virt-who configuration deploy ...
y script for the specified virt-who configuration info Show a virt-who configuration list List of virt-who configurations update Update a virt-who configuration """ from robottelo.cli.base import Base ...
libvirt/autotest
client/tools/cd_hash.py
Python
gpl-2.0
1,765
0.001133
#!/usr/bin/python """ Program that calculates several hashes for a given CD image. @copyright: Red Hat 2008-2009 """ import os, sys, optparse, logging tr
y: import autotest.common as common except ImportError: import common from autotest_lib.client.common_lib import logging_manager from autotest_lib.client.bin import utils from autotest_lib.client.virt import virt_utils if __name__ == "__main__": parser = optparse.OptionParser("usage: %prog [options] [file...
else: parser.print_help() sys.exit(1) for filename in filenames: filename = os.path.abspath(filename) file_exists = os.path.isfile(filename) can_read_file = os.access(filename, os.R_OK) if not file_exists: logging.critical("File %s does not exist!", ...
ADMIcloud/www
docs/source/conf.py
Python
apache-2.0
14,197
0.006058
# -*- coding: utf-8 -*- # # ADMICloud documentation build configuration file, created by # sphinx-quickstart on Wed May 18 09:56:03 2016. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # #...
th()] #html_theme_path = ["../_themes",] # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each th
eme, see the # documentation. html_theme_options ={} # html_theme_options = { # # Navigation bar title. (Default: ``project`` value) # 'navbar_title': "ADMICloud", # # # Tab name for entire site. (Default: "Site") # #'navbar_site_name': "Site", # # # A list of tuples containing pages or urls to link...
OpenUniversity/ovirt-engine
packaging/setup/plugins/ovirt-engine-setup/ovirt-engine/pki/ssh.py
Python
apache-2.0
4,675
0
# # ovirt-engine-setup -- ovirt engine setup # Copyright (C) 2013-2015 Red Hat, 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 # # Unl...
licKey(self, key): rc, stdout, stderr = self.execute( ( self.command.get('ssh-keygen'), '-i', '-m', 'PKCS
8', '-f', '/proc/self/fd/0', ), stdin=key.split('\n'), ) return stdout[0] def _getSSHPublicKeyFingerprint(self, key): # until openssh-7.1 -l does not support pipe with tempfile.NamedTemporaryFile() as f: f.write(key) f....
ninapavlich/django-unsaved-changes
setup.py
Python
mit
782
0
from setuptools import setup, find_packages setup( name='django-unsaved-changes', version='1.1.0', author='Nina Pavlich', author_email='nina@ninalp.com',
url='https://github.com/ninapavlich/django-unsaved-changes', license="MIT", description='UX improvements for admin', keywords=['libraries', 'web development'], include_package_data=True, packages=['django_unsaved_changes'], classifiers=[ 'Development Status :: 4 - Beta', 'Env...
nse', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python' ] )
jamtwister/vncdotool
vncdotool/api.py
Python
mit
3,674
0.000272
""" Helpers to allow vncdotool to be intergrated into other applications. This feature is under developemental, you're help testing and debugging is appreciated. """ import threading try: import queue except ImportError: import Queue as queue import logging from twisted.internet import reactor from twisted.i...
nd.parse_host(server) client = ThreadedVNCClientProxy(factory) client.connect(host, port) return client def shutdown(): if not reactor.running: return reactor.callFro
mThread(reactor.stop) _THREAD.join() class ThreadedVNCClientProxy(object): def __init__(self, factory): self.factory = factory self.queue = queue.Queue() def connect(self, host, port=5900): reactor.callWhenRunning(reactor.connectTCP, host, port, self.factory) def disconnect(...
jrahlf/3D-Non-Contact-Laser-Profilometer
xpcc/scons/site_tools/hosted.py
Python
mit
2,890
0.023529
#!/usr/bin/env python # # Copyright (c) 2009, Roboterclub Aachen e.V. # 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 # ...
lt') env.Append(CXXFLAGS = "/EHsc") else: env.Append(ENV = {'PATH' : os.environ['PATH']}) env.Tool('gcc') env.Tool('g++') env.Tool('gnulink') env.Tool('ar') env.Tool('as') env['NM'] = "nm" env['SIZE'] = "du -s -h" # bu
ild messages if ARGUMENTS.get('verbose') != '1': env['CCCOMSTR'] = "Compiling C: $TARGET" env['CXXCOMSTR'] = "Compiling C++: $TARGET" env['ASCOMSTR'] = "Assembling: $TARGET" env['ASPPCOMSTR'] = "Assembling: $TARGET" env['LINKCOMSTR'] = "Linking: $TARGET" env['RANLIBCOMSTR'] = "Indexing: $TARGET" ...
maigimenez/cracking
chapter_01/src/answer_07.py
Python
apache-2.0
583
0.001715
def rotate_matrix(m): if not m: return [] rows = len(m) # cols = len(m[0]) # rotated_matrix = [[0]*cols for _ in range(rows)] # for i in range(rows): # for j in range(cols): # rotated_matrix[j][rows-i-1] = m[i][j] # return rotated_matrix # Inline for i in ra...
-i][rows-1-j] m[rows-1-i][rows-1-j] = m[j][rows-1-i] m[j][rows-1-i] = temp
return m
anhstudios/swganh
data/scripts/templates/object/ship/player/shared_player_hutt_heavy_s02.py
Python
mit
456
0.046053
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PL
EASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Ship() result.template = "object/ship/player/shared_player_hutt_heavy_s02.iff" result.attribute_template_id = -1 result.stfName("space_ship","player_hutt_heavy_s02") #### BEGIN MODIFICATIONS #### #### E...
OpenVZ/vcmmd
vcmmd/util/optparse.py
Python
lgpl-2.1
2,269
0.000441
# Copyright (c) 2016-2017, Parallels International GmbH # Copyright (c) 2017-2022, Virtuozzo International GmbH, All rights reserved # # This file is part of OpenVZ. OpenVZ 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 ...
e 59, 8200 # Schaffhausen, Switzerland. import copy import optparse # borrowed from chromium class OptionWithM
emsize(optparse.Option): @staticmethod def _CheckMemsize(option, opt, value): # Note: purposely no 'b' suffix, since that makes 0x12b ambiguous. multiplier_table = [ ('g', 1024 * 1024 * 1024), ('m', 1024 * 1024), ('k', 1024), ('', 1), ] ...
ppyordanov/HCI_4_Future_Cities
Server/src/virtualenv/Lib/site-packages/setuptools/command/bdist_egg.py
Python
mit
17,632
0.000567
"""setuptools.command.bdist_egg Build .egg distributions""" # This module should be kept compatible with Python 2.3 import sys import os import marshal import textwrap from setuptools import Command from distutils.dir_util import remove_tree, mkpath try: # Python 2.7 or >=3.2 from sysconfig import get_path, ...
ges = os.path.normcase(os.path.realpath(_get_purelib())) old, self.distribution.data_files = self.distribution.data_files, [] for item in old: if isinstance(item, tuple) and len(item) == 2: if os.path.isabs(item[0]): realpath = os.path.realpath(item[0]) ...
ages + os.sep ): item = realpath[len(site_packages) + 1:], item[1] # XXX else: raise ??? self.distribution.data_files.append(item) try: log.info("installing package data to %s" % self.bdist_dir) self.call_co...
centricular/meson
mesonbuild/mesonlib.py
Python
apache-2.0
11,768
0.007563
# Copyright 2012-2015 The Meson development team # 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 agree...
auto-detect this, so it must be set at build time return 'libexec' def default_prefix(): return 'c:/' if is_windows() else '/usr/local' def get_library_dirs(): if is_windows(): return ['C:/mingw/lib'] # Fixme if is_osx(): return ['/usr/lib'] # Fix me as well. # The following is pr...
tuff # installed by the sysadmin and is probably more up-to-date # than /usr/lib. If you feel that this search order is # problematic, please raise the issue on the mailing list. unixdirs = ['/usr/local/lib', '/usr/lib', '/lib'] plat = subprocess.check_output(['uname', '-m']).decode().strip() # ...
hswhite33/picturegame-bot
src/utils/RoundUtils.py
Python
mit
370
0.002703
def countWinStreak(rounds):
streak = 1 i = len(rounds) - 1 current = rounds[i] while i > 0: i -= 1 prev = rounds[i] if current - prev > 2: break streak += 1 current = prev return streak def roundsSinceLastWin(rounds): if len(rounds) > 1:
return rounds[-1] - rounds[-2] return -1
gwpy/gwpy.github.io
docs/latest/plotter/index-2.py
Python
gpl-3.0
265
0.003774
l1 = TimeSeries.fetch_open_data('L1', 1126259457, 1126259467) from gwpy.plotter import TimeSeriesPlot plot = TimeSeriesPlot() ax = plot.gca() ax.plot(h1, color='gwpy:ligo-hanford') ax.plot(l1, color='gwpy:ligo-livingston') ax.set_ylabel('Strain noise') plot.show
()
SchrodingersGat/InvenTree
InvenTree/InvenTree/management/commands/rebuild_thumbnails.py
Python
mit
1,950
0.000513
""" Custom management command to rebuild thumbnail images - May be required after importing a new dataset, for example """ import os import logging from PIL import UnidentifiedImageError from django.core.management.base import BaseCommand from django.conf import settings from django.db.utils import OperationalError...
gs): logger.setLevel(logging.INFO) logger.info("Rebuilding Part thumbnails")
for part in Part.objects.exclude(image=None): try: self.rebuild_thumbnail(part) except (OperationalError, ProgrammingError): logger.error("ERROR: Database read error.") break logger.info("Rebuilding Company thumbnails") ...
stemcellcommons/macs2
macs2_wrapper.py
Python
mit
9,144
0.044182
# macs2 python wrapper # based on http://toolshed.g2.bx.psu.edu/view/modencode-dcc/macs2 import sys, subprocess, tempfile, shutil, glob, os, os.path, gzip from galaxy import eggs import json CHUNK_SIZE = 1024 #========================================================================================== #functions #====...
unzip_cat_glob_path
( glob_path, target_filename, delete = False ): out = open( target_filename, 'wb' ) for filename in glob.glob( glob_path ): fh = gzip.open( filename, 'rb' ) while True: data = fh.read( CHUNK_SIZE ) if data: out.write( data ) else: ...
hryamzik/ansible
lib/ansible/modules/utilities/logic/import_tasks.py
Python
gpl-3.0
1,471
0.004079
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = { 'metadata_version': '1.1', 'status': ...
ion. version_added: "2.4" options: free-form: description:
- The name of the imported file is specified directly without any other option. - Most keywords, including loops and conditionals, only applied to the imported tasks, not to this statement itself. If you need any of those to apply, use M(include_tasks) instead. notes: - This is a core feature of A...
sheagcraig/python-jss
jss/distribution_point.py
Python
gpl-3.0
47,421
0.000949
#!/usr/bin/env python # Copyright (C) 2014-2018 Shea G Craig, 2018 Mosen # # 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 versio...
Raises: JSSError: If mandatory arguments are not supplied to the initializer. """ required_attrs = set() def __init__(self, **connection_args): """Store the connection information.""" if self.required_attrs.issubset(set(connection_args.keys())): self.connection =
connection_args self._build_url() else: missing_attrs = self.required_attrs.difference(set(connection_args.keys())) raise JSSError( "Missing REQUIRED argument(s) %s to %s distribution point." % (list(missing_attrs), self.__class__) ...
OCA/vertical-medical
medical_pharmacy/__manifest__.py
Python
gpl-3.0
1,966
0
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) LasLabs, Inc [https://laslabs.com]. All Rights Reserved # ############################################################################## # # Collaborators of this module: # Written By: Da...
rsion': '8.0.1.1.0', 'author': 'LasLabs, Odoo Medical Team, Odoo Community Association (OCA)', 'category': 'Medical', 'depends': [ 'medical', ], 'website': 'https://laslabs.com', 'license': 'GPL-3', 'data': [ 'views/medical_pharmacy_view.xml', 'security/ir.model.acces...
'auto_install': False, }
getsentry/zeus
zeus/factories/user.py
Python
apache-2.0
406
0
import factory
from zeus import models from zeus.utils import timezone from .base import ModelFactory from .types import GUIDFactory class UserFactory(ModelFactory): id = GUIDFactory() email = factory.Faker("email") date_created = factory.LazyAttribute(lambda o: timezone.now()) date_active = factory.LazyAttribute...
models.User
fake-name/ReadableWebProxy
WebMirror/management/rss_parser_funcs/feed_parse_extractRoontalesCom.py
Python
bsd-3-clause
539
0.03525
def extractRoontalesCom(item): ''' Parser for 'roontales.com' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None tagmap = [ ('PRC', 'PRC',
'translated'), ('Loiterous', 'Loiterous',
'oel'), ] for tagname, name, tl_type in tagmap: if tagname in item['tags']: return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type) return False
MobileCloudNetworking/maas
bundle/clients/nova.py
Python
apache-2.0
3,217
0.002487
from sm.so.service_orchestrator import LOG from novaclient import client from emm_exceptions.NotFoundException import NotFoundException from model.Entities import Key, Flavor, Image, Quotas __author__ = 'lto' class Client: def __init__(self, conf=None): if not conf: from util.SysUtil impor...
unit.floating_ips[k] = self.get_floating_ip(ip).ip LOG.debug(ip + " is a floating ip") except NotFoundException as e:
unit.ips[k] = ip LOG.debug(ip + " is a fixed ip") LOG.debug("ips: " + str(unit.ips)) LOG.debug("floating_ips: " + str(unit.floating_ips)) def get_images(self, object=True): images_repr = self.nova.images.list() images = [] for image_repr in images_rep...
readbeyond/lachesis
lachesis/nlpwrappers/pattern.py
Python
agpl-3.0
5,498
0.000364
#!/usr/bin/env python # coding=utf-8 # lachesis automates the segmentation of a transcript into closed captions # # Copyright (C) 2016-2017, Alberto Pettarin (www.albertopettarin.it) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License a...
en import split as func_split elif self.language == Language.ITALIAN: from pattern.it import parse as func_parse from pattern.it import split as func_split elif self.language == Language.SPANISH: from pattern.es import parse as func_parse from p
attern.es import split as func_split elif self.language == Language.FRENCH: from pattern.fr import parse as func_parse from pattern.fr import split as func_split elif self.language == Language.GERMAN: from pattern.de import parse as func_parse from pattern...
Kvoti/ditto
ditto/formbuilder/migrations/0006_auto_20150827_1019.py
Python
bsd-3-clause
918
0.002179
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration):
dependencies = [ ('formbuilder', '0005_auto_20150826_1600'), ] operations = [ migrations.RemoveField( model_name='choiceanswer', name='option', ), migrations.AddField( model_name='choiceanswer', name='choices', fie...
, ), migrations.AddField( model_name='choiceanswer', name='other', field=models.TextField(blank=True), ), migrations.AddField( model_name='choiceanswer', name='question', field=models.ForeignKey(related_name='answers...
NosajGithub/subreddit_profiler
non_shiny _code/03_analysis_code/mrjob/mrjobCommentWordCount.py
Python
mit
1,328
0.012801
"""Run MRJob to get the number of words per comment by subreddit.""" from mrjob.job import MRJob from math import sqrt import re class MRCommentWordCount(MRJob): def mapper(self, _, line): cline = re.sub("[~`*>#().!?,\[]","",line) cline2 = re.sub("(&gt;)|(&amp;)|(&lt;)|\]"," ",cline).lower() ...
rMeanVar.py N = 0.0 value_sum = 0.0 sumsq = 0.0 for x in num_words: N += 1 value_sum += x sumsq += x*x mean = value_sum/N sd = sqrt(sumsq/N - mean*mean) results = [round(mean,2)
,round(sd,2)] yield subreddit, results def steps(self): return [self.mr(mapper=self.mapper, reducer=self.reducer) ] if __name__ == '__main__': MRCommentWordCount.run()
DavisMiculis/Rasadron
GPS6MV.py
Python
mit
157
0.019108
#
!/usr/bin/python """ GPS Sensor - GY-GPS6MV2 (NEO-6M-0-001) THIS IS STILL IN DEVELOPMENT """ import math class GPS: def __init__(self): self.gps = 0
krbeverx/Firmware
src/lib/version/px_update_git_header.py
Python
bsd-3-clause
6,103
0.005899
#!/usr/bin/env python from __future__ import print_function import argparse import os import sys import subprocess import re parser = argparse.ArgumentParser(description="""Extract version info from git and generate a version header file. The working directory is expected to be the root of Firmware.""") parser.add_ar...
t("Examples:") print(" v1.9.0-rc3 (preferred)") print(" v1.9.0-beta1") print(" v1.9.0-1.0.0") print(" v1.9.0-1.0.0-alp
ha2") print("See also https://dev.px4.io/master/en/setup/building_px4.html#firmware_version") print("") sys.exit(1) git_version = subprocess.check_output('git rev-parse --verify HEAD'.split(), stderr=subprocess.STDOUT).decode('utf-8').strip() try: git_b...
rahulbohra/Python-Basic
7_first-string-operators.py
Python
mit
35
0
print '
abc' + '123'
print 'Hi' * 5
tholo/formhelpers2
formhelpers2/tests.py
Python
bsd-2-clause
406
0.002463
import unittest from pyramid imp
ort testing class ViewTests(unittest.TestCase): def setUp(self): self.config = testing.setUp() def tearDown(self): testing.tearDown() def test_my_view(self): from formhelpers2.views import comment request = testing.DummyRequest() info = comment(request) sel...
assertTrue(hasattr(info['forms'], 'comment_form'))
zenodo/invenio
invenio/modules/workflows/testsuite/test_workflows_delayed.py
Python
gpl-2.0
7,683
0.00039
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2014 CERN. # # Invenio 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...
ame="unit_tes
ts") self.assertEqual(40, test_objectb.get_data()) test_object = BibWorkflowObject() test_object.set_data(22) test_object.save() test_objectc = BibWorkflowObject() test_objectc.set_data(22) test_objectc.save() data = [test_object, test_objectc] for...
qilicun/python
python2/PyMOTW-1.132/PyMOTW/tarfile/tarfile_getmember.py
Python
gpl-3.0
463
0.006479
#!/usr/bin/env python # encoding: utf-8 # # Copyright (c) 2009 Doug Hellmann All rights reserved. # """ """ __version__ = "$Id$" #end_pymotw_header import tarfile import time t = tar
file.open('example.tar', 'r') for filename in [ 'README.txt', 'notthere.txt' ]: try
: info = t.getmember(filename) except KeyError: print 'ERROR: Did not find %s in tar archive' % filename else: print '%s is %d bytes' % (info.name, info.size)
edx/edx-search
search/filter_generator.py
Python
agpl-3.0
1,601
0.002498
""" overridable filter object to inject fields to auto-filter upon within searches """ from datetime import datetime from django.conf import settings from .utils import _load_class, DateRange class SearchFilterGenerator: """ Class to provide a set of filters for the search. Users of this search app wi...
ction
ary(**kwargs), generator.exclude_dictionary(**kwargs), )
lukas-hetzenecker/home-assistant
tests/components/wallbox/__init__.py
Python
apache-2.0
1,287
0.001554
"""Tests for the Wallbox integration.""" import json import requests_mock from homeassistant.components.wallbox.const import CONF_STATION, DOMAIN from homeassistant.const import CONF_PASSWORD, CONF_USERNAME from tests.common import MockConfigEntry test_response = json.loads( '{"charging_power": 0,"max_availabl...
async def setup_integration(hass): """Test wallbox sensor class setup.""" entry = MockConfigEntry( domain=DOMAIN, data={ CONF_USERNAME: "test_username", CONF_PASSWORD: "test_password", CONF_STATION: "12345", }, entry_id="testEntry", ) ...
t.get( "https://api.wall-box.com/auth/token/user", text='{"jwt":"fakekeyhere","user_id":12345,"ttl":145656758,"error":false,"status":200}', status_code=200, ) mock_request.get( "https://api.wall-box.com/chargers/status/12345", json=test_respons...
benjaminwilson/word2vec-norm-experiments
count_words.py
Python
apache-2.0
151
0
import sys fro
m functions import * word_counts = count_words(sys.stdin) for word, count in word_counts.iteritems(): print '%s,%i' % (
word, count)
toastedcornflakes/scikit-learn
sklearn/tests/test_calibration.py
Python
bsd-3-clause
12,016
0
# Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # License: BSD 3 clause import numpy as np from scipy import sparse from sklearn.utils.testing import (assert_array_almost_equal, assert_equal, assert_greater, assert_almost_equal, ...
RandomState(seed=42).uniform(size=y.size) X -= X.min() # MultinomialNB only allows positive X # split train and test X_train, y_train, sw_train = \ X[:n_sam
ples], y[:n_samples], sample_weight[:n_samples] X_test, y_test = X[n_samples:], y[n_samples:] # Naive-Bayes clf = MultinomialNB().fit(X_train, y_train, sample_weight=sw_train) prob_pos_clf = clf.predict_proba(X_test)[:, 1] pc_clf = CalibratedClassifierCV(clf, cv=y.size + 1) assert_raises(Value...
DGA-MI-SSI/YaCo
deps/swig-3.0.7/vms/genbuild.py
Python
gpl-3.0
4,052
0.001728
import os.path, string, posix, pyvms # # IDIR = ['swig_root:[source.swig]', 'swig_root:[source.doh.include]', 'swig_root:[source.include]', 'swig_root:[source.preprocessor]'] def new_file(fg, dirname): global IDIR fn = 'swig_root:[vms.scripts]compil_' + os.path.basename(dirname) + '.com' print >>...
-' print >> fc, line line = "\t" + cstr + fn print >> fc, line elif fn[-4:] == '.cxx': if first:
first = 0 fc = new_file(fg, dirname) cstr = "\"cxx ''cxxflags'\" " line = "$ call make swig_root:[vms.o_alpha]" line += fn[:-3] + 'obj -' print >> fc, line line = "\t" + cstr + fn print >> fc, line if first == 0: end_fi...
adamjmcgrath/glancydesign
src/django-nonrel/django/utils/encoding.py
Python
bsd-3-clause
7,321
0.001912
import types import urllib import locale import datetime import codecs from decimal import Decimal from django.utils.functional import Promise class DjangoUnicodeDecodeError(UnicodeDecodeError): def __init__(self, obj, *args): self.obj = obj UnicodeDecodeError.__init__(self, *args) def __str_...
pt
function for more details. Returns an ASCII string containing the encoded result. """ if path is None: return path # I know about `os.sep` and `os.altsep` but I want to leave # some flexibility for hardcoding separators. return urllib.quote(smart_str(path).replace("\\", "/"), safe="/~!*...
JioCloud/horizon
openstack_dashboard/dashboards/admin/info/views.py
Python
apache-2.0
1,536
0.000651
# Copyright 2012 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Copyright 2012 Nebula, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the...
as project_tabs class IndexView(tabs.TabbedTableView): tab_group_class = project_tabs.SystemInfoTabs template_name = constants.INFO_TEMPLATE_NAME def get_c
ontext_data(self, **kwargs): context = super(IndexView, self).get_context_data(**kwargs) try: context["version"] = version.version_info.version_string() except Exception: exceptions.handle(self.request, _('Unable to retrieve version information.')) ...
detrout/pykolab
pykolab/cli/cmd_user_info.py
Python
gpl-3.0
1,532
0.003264
# -
*- coding: utf-8 -*- # Copyright 2010-2012 Kolab Systems AG (http://www.kolabsys.com) # # Jeroen van Meeuwen (Kolab Systems) <vanmeeuwen a kolabsys.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 Fou...
hat it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU 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...
codelv/enaml-native
src/enamlnative/android/android_grid_layout.py
Python
mit
2,385
0
""" Copyright (c) 2017-2022, Jairus Martin. Distributed under the terms of the MIT License. The full license is in the file LICENSE, distributed with this software. Created on May 20, 2017 @author: jrm """ from atom.api import Typed from enamlnative.widgets.grid_layout import ProxyGridLayout from .android_view_grou...
ientation == "horizontal" else 1) def set_alignment_mode(self, mode): self.widget.setAlignmentMode(1 if mode == "margins" else 0) def set_columns(self, columns): self.widget.setColumnCount(columns) def set_column_order_preserved(self, preserved): self.widget.setColumnOrderPreserve...
ws): self.widget.setRowCount(rows) def set_row_order_preserved(self, preserved): self.widget.setRowOrderPreserved(preserved) def set_use_default_margins(self, use_default): self.widget.setUseDefaultMargins(use_default)
pculture/mirocommunity
localtv/management/commands/update_popularity.py
Python
agpl-3.0
921
0.001086
from datetime import datetime, timedelta from optparse import make_option from django.core.management.base import LabelCommand from localtv.management import site_
too_old from localtv.models import Video class Command(LabelCommand): option_list = ( make_option('--since', action='store', dest='since', default=11, type='int', help='The number of days in the past for which all watched videos shou
ld be reindexed.'), ) + LabelCommand.option_list def handle(self, **options): if site_too_old(): return since = options['since'] from localtv.tasks import haystack_batch_update haystack_batch_update.delay(Video._meta.app_label, V...
EachenKuang/PythonRepository
PublicOpinion/JSDistance.py
Python
apache-2.0
1,014
0.021231
# -*- coding: utf-8 -*- # ''' # Author: Eachen Kuang # Date: 2017.10.20 # Goal: 将文件转化为字典 # Other: # ''' import string from math import log import numpy as np def KLD(p,q): p,q=zip(*filter(lambda (x,y): x!=0 or y!=0, zip(p,q))) #去掉二者都是0的概率值 p=p+np.spacing(1) q=q+np.spacing(1) print p, q return su...
,2) for (_p,_q) in zip(p,q)]) # p=np.ones(5)/5.0 # q=[0,0,0.5,0.2,0.3] # print KLD(p,q) def JSD_core(p, q): p, q = zip(*filter(lambda[x,y]: x != 0 or y != 0, zip(p, q))) # 去掉二者都是0的概率值 M = [0.5 * (_p + _q) for _p, _q in zip(p, q)] p = p + np.spacing(1) q = q + np.spacing(1) M = M + np.spacing(1) ...
ercase] # 频数分布 rate = lambda y: [round(i * 1.0 / sum(reg(y)), 4) for i in reg(y)] # 概率分布 s1 = 'KuangYichen1raf' s2 = 'YichenKuang2' print JSD_core(rate(s1), rate(s2))
Alberto-Beralix/Beralix
i386-squashfs-root/usr/share/pyshared/gwibber/lib/__init__.py
Python
gpl-3.0
2,740
0.003285
import dbus from gwibber.microblog import util class GwibberPublic: """ GwibberPublic is the public python class which provides convience methods for using Gwibber. """ def __init__(self): self.bus = dbus.SessionBus() self.accounts = self.getbus("Accounts") self.service = ...
b): self.accounts.connect_to_signal("AccountCreated", cb) def MonitorAccountChanged(self, c
b): self.accounts.connect_to_signal("AccountChanged", cb) def MonitorAccountDeleted(self, cb): self.accounts.connect_to_signal("AccountDeleted", cb)
luc-demeyer/account-financial-reporting
account_financial_report_horizontal/__manifest__.py
Python
agpl-3.0
701
0
# -*- coding: utf-8 -*- # © 2012-2016 Therp BV <http://therp.nl> # © 2013 Agile Business Group sagl <http://www.agilebg.com> # <lorenzo.battistini@agilebg.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Accounting Financial Report Horizontal", "version": "10.0.1.0.0", "a...
', 'website': 'https://github.c
om/OCA/account-financial-reporting', 'license': 'AGPL-3', "depends": ["account"], 'data': [ "data/report_paperformat.xml", "data/ir_actions_report_xml.xml", "report/report_financial.xml", ], }
juancroldan/derinkuyu
generation/BSPTree.py
Python
mit
6,186
0.049305
from random import randint, seed, choice, random from numpy import zeros, uint8, cumsum, floor, ceil from math import sqrt, log from collections import namedtuple from PIL import Image from logging import info, getLogger class Tree: def __init__(self, leaf): self.leaf = leaf self.lchild = None self.rchild = Non...
= 0 MAP_HEIGHT = 0 N_ITERATIONS = 0 H
_RATIO = 0 W_RATIO = 0 MIN_ROOM_SIDE = 0 CENTER_HUB_HOLE = 0 CENTER_HUB_RADIO = 0 MAP_NAME = 0 def init(num_players): global MAP_WIDTH,MAP_HEIGHT,N_ITERATIONS,H_RATIO,W_RATIO,MIN_ROOM_SIDE,CENTER_HUB_HOLE,CENTER_HUB_RADIO,MAP_NAME MAP_WIDTH=int(500*sqrt(num_players)) MAP_HEIGHT=MAP_WIDTH N_ITERATIONS=log(MAP_WIDTH...
andyeff/skybot
plugins/seen.py
Python
unlicense
1,718
0
" seen.py: written by sklnd in about two beers July 2009" import time from util import hook, timesince def db_init(db): "check to see that our db has the the seen table and return a connection." db.execute("create table if not exists seen(name, time, quote, chan, " "primary key(name, chan))")...
, (input.nick.lower(), time.time(), input.msg, input.chan)) db.commit() @hook.command def seen(inp, nick='', chan='', db=None,
input=None): ".seen <nick> -- Tell when a nickname was last in active in irc" if input.conn.nick.lower() == inp.lower(): # user is looking for us, being a smartass return "You need to get your eyes checked." if inp.lower() == nick.lower(): return "Have you looked in a mirror latel...
SoftwareExperiment4/SungkyunWiki
wiki/tests/base.py
Python
gpl-3.0
2,591
0
from __future__ import unicode_literals from __future__ import absolute_import from django.core.urlresolvers import reverse from django.test import TestCase from django.test.client import Client from django.template import Context, Template try: from django.test import override_settings except ImportError: fro...
ase, self).setUp() response = self.c.post( reverse('wiki:root_create'), {'content': 'root article content', 'title': 'Root Article'}, follow=True ) self.assertEqual(response.status_code, 200) # sanity check self.root_article = URLPath.root().article...
'current_revision': '1', 'preview': '1', # 'save': '1', # probably not too important 'summary': 'why edited', 'title': 'wiki test' } def get_by_path(self, path): """ Get the article response for the path. Example: self.get_by...
rzzzwilson/pyQ1300ST
log.py
Python
mit
4,784
0.001254
#!/usr/bin/env python """ A simple logger. TODO: Use python logging, etc. """ import os import sys import datetime import traceback # maximum length of filename (enforced) MaxNameLength = 15 ################################################################################ # A simple logger. # # Simple usage: # ...
um_to_name[level] fname = fname[:MaxNameLength] self.logfd.write('%02d:%02d:%02d.%06d|%8s|%*s:%-4d|%s\
n' % (hr, min, sec, msec, loglevel, MaxNameLength, fname, lnum, msg)) self.logfd.flush() def critical(self, msg): """Log a message at CRITICAL level.""" self(msg, Log.CRITICAL) def error(self, msg): """Log a message at ERROR...
zaqwes8811/my-courses
stanford1/py/shortest_path.py
Python
apache-2.0
533
0.003752
# coding: utf-8 # C++ # http://www.e-olimp.com/articles/21 # http://hardfire.ru/Dij_sparse # Weak 5 # TODO: hear lession + lession about heap """ NAIVE: Initialize: - X = [S] [vert. processed so far] - A[S] = 0 [computed shortest path distances
] [- B[S] = []] [path - help only] - while X != V: - among all edges (v, w) in E, with v in X, w not in X - pick the one that minimize A[v]
+ l_vw [call it (v*, w*)] - add w* to X - set A[w*] := A[v*] + l_v*w* [- set B[w*] := B[v*] or (v*, w*)] WITH HEAP: """