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
hugobuddel/orange3
Orange/widgets/__init__.py
Python
gpl-3.0
791
0.002528
""" """ import os import sysconfig import pkg_resources import Orange # Entry point for main Orange categories/widgets discovery def widget_discovery(discovery): dist = pkg_resources.get_distribution("Orange") pkgs = [ "Orange.widgets.data", "Orange.widgets.visualize", "Orange.widge...
"Orange.widgets.evaluate", "Orange.widgets.unsupervised", ] for pkg in pkgs: discovery.process_category_package(pkg, distribution=dist) WIDGET_HELP_PATH = ( ("{DEVELOP_ROOT}/doc/build/htmlhelp/index.html", None),
# os.path.join(sysconfig.get_path("data"), # "share", "doc", "Orange-{}".format(Orange.__version__)), ("http://docs.orange.biolab.si/3/", "") )
shawon922/django-blog
posts/migrations/0001_initial.py
Python
mit
1,203
0.001663
# -*- coding: utf-8 -*- # Generated by Django 1.10.1 on 2016-11-12 17:04 from __future__ import unicode_literals from django.db import migrations, models import posts.models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( ...
(default=0)), ('width_field', models.IntegerField(default=0)), ('content', models.TextField()), ('updated', models.DateTimeFie
ld(auto_now=True)), ('timestamp', models.DateTimeField(auto_now_add=True)), ], options={ 'ordering': ['-timestamp', '-updated'], }, ), ]
bdol/bdol-ml
decision_trees/run_decision_tree.py
Python
lgpl-3.0
1,993
0.001505
""" An example that runs a single decision tree using MNIST. This single tree can achieve ~20% error rate on a random 70/30 train/test split on the original MNIST data (with a depth limit of 10). ============== Copyright Info ============== This program is free software: you can redistribute it and/or modify it under ...
should have received a copy of the GNU General Public License along with this p
rogram. If not, see <http://www.gnu.org/licenses/>. Copyright Brian Dolhansky 2014 [email protected] """ from decision_tree import DecisionTree from fast_decision_tree import FastDecisionTree from sklearn.datasets import fetch_mldata from data_utils import integral_to_indicator, split_train_test import numpy as np ...
mhaze4/jquery-textflow
django-textflow/textflow/templatetags/__init__.py
Python
mit
37
0
# coding: utf-8 __author__ = 'mh
aze
'
cliburn/flow
src/plugins/io/ReadFCS/memoized.py
Python
gpl-3.0
662
0.036254
class memoized(object): """Decorator that caches a function's return value each time it is called. If called later with the same arguments, the cached value is returned, and not re-evaluated. """ def __init__(self, func): self.func = func self.cache = {} def __call__(self, *args): try: return self.cache[...
.func(*args) return value except TypeError: # uncachable -- for instance, passing a list
as an argument. # Better to not cache than to blow up entirely. return self.func(*args) def __repr__(self): """Return the function's docstring.""" return self.func.__doc__
uw-it-aca/course-dashboards
coursedashboards/cache.py
Python
apache-2.0
815
0
from memcached_clients import RestclientPymemcacheClient import re ONE_MINUTE = 60 ONE_HOUR = 60 * 60 class RestClientsCache(RestclientPymemcacheClient): """ A custom cache implementation
for Course Dashboards """ def get_cache_expiration_time(self, service, url, status=200): if "sws" == service: if re.match(r"^/student/v\d/term/\d{4}", url): return ONE_HOUR * 10 if re.match(r"^/studen
t/v\d/(?:enrollment|registration)", url): return ONE_HOUR * 2 return ONE_HOUR if "pws" == service: return ONE_HOUR * 10 if "gws" == service: return ONE_MINUTE * 2 if "canvas" == service: if status == 200: return O...
thorsummoner/crowbar
crowbar/baseextension.py
Python
unlicense
2,406
0.002494
# # crowbar - a geometry manipulation program # Copyright (C) 2020 Dylan Scott Grafmyre # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the License, ...
ources_module = None pkg_resources_prefix = None main_glade_object_name = None def __init__(self): self.LOGGER = logging.getLogger(self.__class__.__name__) @property def glade_filename(self): raise NotImplementedError @property def main_gtk_widget(self): if self.bu...
r.add_from_file(%s)', self.glade_filename) self.builder.add_from_file(self.glade_filename) # builder.connect_signals(Handler()) self.LOGGER.info('Gtk.Builder.get_object(%s)', self.main_glade_object_name) widget = self.builder.get_object(self.main_glade_object_name) i...
rg3/youtube-dl
youtube_dl/extractor/bfmtv.py
Python
unlicense
4,216
0.002137
# coding: utf-8 from __future__ import unicode_literals import re from .common import InfoExtractor from ..utils import extract_attributes class BFMTVBaseIE(InfoExtractor): _VALID_URL_BASE = r'https?://(?:www\.)?bfmtv\.com/' _VALID_URL_TMPL = _VALID_URL_BASE + r'(?:[^/]+/)*[^/?&#]+_%s[A-Z]-(?P<id>\d{12})\.h...
AN-202101060275.html', 'only_matching': True, }] def _real_extract(self, url): bfmtv_id = self._match_id(url
) webpage = self._download_webpage(url, bfmtv_id) entries = [] for video_block_el in re.findall(self._VIDEO_BLOCK_REGEX, webpage): video_block = extract_attributes(video_block_el) video_id = video_block.get('videoid') if not video_id: continue...
cloudkick/libcloud
libcloud/base.py
Python
apache-2.0
1,286
0.000778
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use ...
License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either ex
press or implied. # See the License for the specific language governing permissions and # limitations under the License. from libcloud.common.base import RawResponse, Response, LoggingConnection from libcloud.common.base import LoggingHTTPSConnection, LoggingHTTPConnection from libcloud.common.base import ConnectionKe...
benediktschmitt/py-jsonapi
jsonapi/flask/api.py
Python
mit
4,513
0.001329
#!/usr/bin/env python3 # The MIT License (MIT) # # Copyright (c) 2016 Benedikt Schmitt # # 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...
to a flask response. """ if japi_response.is_file: flask_response = flask.send_file(japi_response.file) elif japi_response.has_body: flask_response = flask.Respons
e(japi_response.body) else: flask_response = flask.Response("") for key, value in japi_response.headers.items(): flask_response.headers[str(key)] = value flask_response.status_code = japi_response.status return flask_response class FlaskAPI(jsonapi.base.api.API): """ Implement...
hnakamur/saklient.python
saklient/cloud/resources/routerplan.py
Python
mit
4,491
0.01222
# -*- coding:utf-8 -*- from ..client import Client from .resource import Resource from ...util import Util import saklient # module saklient.cloud.resources.routerplan class RouterPlan(Resource): ## ルータ帯域プラン情報の1レコードに対応するクラス。 # (instance field) m_id # (instance field) m_name # (instance...
} self.is
_incomplete = False if Util.exists_path(r, "ID"): self.m_id = None if Util.get_by_path(r, "ID") is None else str(Util.get_by_path(r, "ID")) else: self.m_id = None self.is_incomplete = True self.n_id = False if Util.exists_path(r, "Name"): s...
NoXPhasma/sshplus
sshplus.py
Python
gpl-3.0
9,010
0.001665
#!/usr/bin/python3 # -*- coding: utf-8 -*- # # SSHplus # A remote connect utlity, sshmenu compatible clone, and application starter. # # (C) 2011 Anil Gulecha # Based on sshlist, incorporating changes by Benjamin Heil's simplestarter # # This program is free software: you can redistribute it and/or modify # it under th...
nu.append(menu_item) return menu_item def get_sshplusconfig(): if not os.path.exists(_SETTINGS_FILE): return [] app_list = [] f = open(_SETTINGS_FILE, "r") try: for line in f.readlines(): line = line.rstrip() if not line or line.startswith("#"): ...
line == "sep": app_list.append("sep") elif line.startswith("label:"): app_list.append({"name": "LABEL", "cmd": line[6:], "args": ""}) elif line.startswith("folder:"): app_list.append({"name": "FOLDER", "cmd": line[7:], "args": ""}) els...
databricks/spark-deep-learning
sparkdl/horovod/tensorflow/keras.py
Python
apache-2.0
903
0.001107
# Copyright 2018 Databricks, Inc. # # pylint: disable=too-few-public-methods # pylint: disable=too-many-instance-attributes # pylint: disable=logging-format-interpolation # pylint: disable=invalid-name import time from tensorflow import keras from sparkdl.horovod import log_to_driver __all__ = ["LogCallback"] clas...
ovodRunner log callback that streams event logs to notebook cell output. """ def __init__(self, per_batch_log=False
): """ :param per_batch_log: whether to output logs per batch, default: False. """ raise NotImplementedError() def on_epoch_begin(self, epoch, logs=None): raise NotImplementedError() def on_batch_end(self, batch, logs=None): raise NotImplementedError() def ...
orbitfp7/nova
nova/scheduler/filters/ram_filter.py
Python
apache-2.0
3,894
0.002054
# Copyright (c) 2011 OpenStack Foundation # Copyright (c) 2012 Cloudscaling # 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/l...
compute node to test
against: host_state.limits['memory_mb'] = memory_mb_limit return True class RamFilter(BaseRamFilter): """Ram Filter with over subscription flag.""" ram_allocation_ratio = CONF.ram_allocation_ratio def _get_ram_allocation_ratio(self, host_state, filter_properties): return self.ram...
kyoheiotsuka/Latent-Dirichlet-Allocation-Variational-Implementation-
sample.py
Python
mit
976
0.050205
# -*- coding: utf-8 -*- import numpy as np import cv2, os, lda if __name__ == "__main__": # set parameter for experiment nTopics = 8 # create folder for saving result if not os.path.exists("result"): os.mkdir("result") # create folder for showing fitting process if not os.path.exists("visualization"): os...
pic.max()*255 topic = topic.reshape((4,4)) cv2.imwrite("result/%d.bmp"%i,c
v2.resize(topic.astype(np.uint8),(200,200),interpolation=cv2.INTER_NEAREST))
fabianmg/Tareas-1-2014
JuegoOware.py
Python
gpl-2.0
12,611
0.043731
# -*- coding: utf-8 -*- ''' oware para windows :@ alternativa 1 (idea 1, con 2 listas para cada jugador) open(nombre del archivo,modo) ''' import os import random # 0 1 2 3 4 5 6 --> j2 = [4,4,4,4,4,4,0] # Esta sera la lista del jugador dos, j1 = [4,4,4,4,4,4,0] # jugador 1 # 0 1 2 3 4 5 6 --> en el ...
ue se repartieron todas (al contrario de) # de las agujas del reloj if mismoJugador(actual,j1,1):#si el jugador acutal es el uno (j1) puntos(lugar,j2,j1) #comprueba si gana puntos o no, llamando a la funcion putos else: # y se le asignaran al j1, si es que los gana puntos(lugar,j1,j2) ...
1 jugador[lugar] += 1 semillas -= 1 #print(semillas) return mover1(lugar,semillas,jugador,1,actual) elif mismoJugador(jugador,j1,1): return mover1(-1,semillas,j2,1,actual) else: return mover1(-1,semillas,j1,1,actual) def noHaySemillas(semillas,jugador,lugar) : #mapa($movidas) if semillas == 0...
bioinfo-center-pasteur-fr/python-course-1
source/_static/code/homolog.py
Python
cc0-1.0
1,585
0.003785
Class Gene: def __init__(self, name, system, loner, profile): self.name = name self.profile = profile self._system = system self._loner = loner @property def system(self): """ :return: the System that owns this Gene :rtype: :class:`macsypy.system.S...
aram gene: the query of the test :type gene: :class:`macsypy.gene.Gene` object. :rtype: boolean. """ return self.gene.name == gene.name def is_aligned(self): """ :return: True if this gene homolog is aligned to its
homolog, False otherwise. :rtype: boolean """ return self.aligned
switch-model/switch-hawaii-studies
models/dr/fuel_markets_expansion.py
Python
apache-2.0
4,206
0.011888
# For large systems, each fuel market tier is a category of capacity expansion, and # it can be built fractionally. For small systems, each fuel market tier is one # capacity-expansion project, and it must be fully built and/or activated each period. # To do this, we add binary variables and confine additions and acti...
ow delivery from activated tiers m.Enforce_RFM_Supply_Tier_Activated = Constraint(
m.RFM_SUPPLY_TIERS, rule=lambda m, r, p, st: m.FuelConsumptionByTier[r, p, st] <= m.RFMSupplyTierActivate[r, p, st] * m.rfm_supply_tier_limit[r, p, st]) # Eventually, when we add capital costs for capacity expansion, we will need a # variable showing how much ...
gajim/gajim
gajim/gajim_remote.py
Python
gpl-3.0
18,904
0.003967
#!/usr/bin/env python3 # Copyright (C) 2005-2006 Dimitur Kirov <dkirov AT gmail.com> # Nikos Kouremenos <kourem AT gmail.com> # Copyright (C) 2005-2014 Yann Leboulanger <asterix AT lagaule.org> # Copyright (C) 2006 Junglecow <junglecow AT gmail.com> # Travis Shirk <travis AT ...
al.signal(signal.SIGINT, signal.SIG_DFL) # ^C exits the application try: PREFERRED_ENCODING = locale.getpreferreden
coding() except Exception: PREFERRED_ENCODING = 'UTF-8' def send_error(error_message): '''Writes error message to stderr and exits''' print(error_message, file=sys.stderr) sys.exit(1) try: import dbus import dbus.service # import dbus.glib # test if dbus-x11 is installed bus = dbus....
Kefkius/scallop
gui/android.py
Python
gpl-3.0
31,779
0.008559
#!/usr/bin/env python # # Electrum - lightweight Bitcoin client # Copyright (C) 2011 thomasv@gitorious # # 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...
which') == 'positive' def edit_label(addr): v
= modal_input('Edit label', None, wallet.labels.get(addr)) if v is not None: wallet.set_label(addr, v) droid.fullSetProperty("labelTextView", "text", v) def select_from_contacts(): title = 'Contacts:' droid.dialogCreateAlert(title) l = contacts.keys() droid.dialogSetItems(l) dro...
googleapis/python-resource-manager
samples/generated_samples/cloudresourcemanager_v3_generated_folders_update_folder_sync.py
Python
apache-2.0
1,634
0.000612
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this fi
le except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIN...
either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Generated code. DO NOT EDIT! # # Snippet for UpdateFolder # NOTE: This snippet has been automatically generated for illustrative purposes only. # It may require modifications to work in ...
dag/genshi
genshi/template/base.py
Python
bsd-3-clause
22,687
0.002028
# -*- coding: utf-8 -*- # # Copyright (C) 2006-2010 Edgewall Software # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms # are also available at http://genshi.edgewall.org/wiki/License. # # This software consist...
%d)' % message.lineno, '') TemplateError.__init__(self, message, filename, lineno) class BadDirectiveError(TemplateSyntaxError): """Exception raised when an unknown directive is encountered when parsing a template. An unknown directive is any attribute using the namespace for directives, ...
n :param name: the name of the directive :param filename: the filename of the template :param lineno: the number of line in the template at which the error occurred """ TemplateSyntaxError.__init__(self, 'bad directive "%s"' % name, ...
tylertian/Openstack
openstack F/horizon/horizon/tests/api_tests/keystone_tests.py
Python
apache-2.0
3,893
0.000514
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # 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 # no...
ty', endpoint_type='internalURL') self.admin_url = api.base.url_for(self.request, 'identity', endpoint_type='adminURL') self.conn = FakeConnection() class RoleAPITests(test.AP...
self.roles.list() def test_remove_tenant_user(self): """ Tests api.keystone.remove_tenant_user Verifies that remove_tenant_user is called with the right arguments after iterating the user's roles. There are no assertions in this test because the checking is handled ...
gleb812/pch2csd
tests/test_utils.py
Python
mit
2,150
0.004186
from unittest import TestCase, skip from pch2csd.patch import ModuleParameters, Location, Module from pch2csd.resources import ProjectData from pch2csd.util import AttrEqMixin class TestAttrEqMixin(TestCase): class ThreeSlots(AttrEqMixin): def __init__(self, one, two, th
ree): self.one = one self.two = two self.three = three def test_different_args(self): o1 = self.ThreeSlots(1, [x for x
in 'test'], [x * 2 for x in range(10)]) o2 = self.ThreeSlots(1, [x for x in 'test'], [x * 2 for x in range(10)]) self.assertTrue(o1.attrs_equal(o2)) def test_overloaded_eq(self): o1 = ModuleParameters(1, 2, [(1, 32), (3, '43')]) o2 = ModuleParameters(1, 2, [x for x in [(1, 32), (3, ...
bretth/woven
woven/deployment.py
Python
bsd-3-clause
8,823
0.012581
#!/usr/bin/env python from functools import wraps from glob import glob from hashlib import sha1 import os, shutil, sys, tempfile from django.template.loader import render_to_string from fabric.state import env from fabric.operations import run, sudo, put from fabric.context_managers import cd, settings, hide from fa...
ee = root.replace(local_dir,'') if relative_tree: relative_tree = relative_tree[1:] if local_files: files = local_files.get(relative_tree,[]) for file in files: if relative_tre
e: filepath = os.path.join(relative_tree,file) if not os.path.exists(os.path.join(staging_dir,relative_tree)): os.mkdir(os.path.join(staging_dir,relative_tree)) else: filepath = file shutil.copy2(os.path.join(root,file),os.path.join(staging_dir...
pombredanne/anitya
anitya/tests/lib/backends/test_hackage.py
Python
gpl-2.0
3,310
0.000604
# -*- coding: utf-8 -*- # # Copyright © 2014 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions # of the GNU General Public License v.2, or (at your option) any later # version. This program is distributed in t...
self.assertRaises( AnityaPluginException, backend.HackageBackend.get_version, project ) if __name__ == '__main__': SUITE = unittest.TestLoader().loadTestsFromTestCase(
HackageBackendtests) unittest.TextTestRunner(verbosity=2).run(SUITE)
Stibbons/dopplerr
cfgtree/dictxpath.py
Python
mit
5,244
0.001716
# coding: utf-8 # Standard Libraries import logging import re # Third Party Libraries from cfgtree import LOGGER_NAME log = logging.getLogger(LOGGER_NAME) # tells flake8 to ignore complexity check for this file # flake8: noqa def get_node_by_xpath(mapping, xpath, default=None, ignore_errors=False, ...
en(items) <= index: if not ignore_errors: raise KeyError("Invalid '{}' selector: item index '{}' of '{}' is " "outside of the list boundaries. Length is: {}".format( xpath, index...
pping = items[index] continue elif not ignore_errors: raise KeyError("Invalid '{}' selector: '{}' doesn't match " "anything. Available keys: {!r}".format( xpath, segment, list(mapping.keys()))) ...
rebost/django
tests/modeltests/model_forms/models.py
Python
bsd-3-clause
8,153
0.005151
""" XX. Generating HTML forms from models This is mostly just a reworking of the ``form_for_model``/``form_for_instance`` tests to use ``ModelForm``. As such, the text may not make sense in all cases, and the examples are probably a poor fit for the ``ModelForm`` syntax. In other words, most of these tests should be r...
width_field='width', height_field='height', blank=True, null=True) width = models
.IntegerField(editable=False, null=True) height = models.IntegerField(editable=False, null=True) path = models.CharField(max_length=16, blank=True, default='') def __unicode__(self): return self.description except ImportError: test_images = False class CommaSeparatedInteger(mod...
MiiRaGe/pyreport
setup.py
Python
mit
108
0.027778
from setuptools import setup, find_packages setup( name='pyreport'
, ve
rsion='0.3', packages=['pyreport'] )
wimleers/fileconveyor
fileconveyor/arbitrator.py
Python
unlicense
59,744
0.004067
import logging import logging.handlers import Queue import os import stat import threading import time import sys import sqlite3 from UserList import UserList import os.path import signal FILE_CONVEYOR_PATH = os.path.abspath(os.path.dirname(__file__)) # HACK to make sure that Django-related libraries can be loaded:...
elf[0] def jump(self, item): self.insert(0, item) def put(self, item): self.append(item) def get(self): return self.pop(0) def qsize(self)
: return len(self) # Define exceptions. class ArbitratorError(Exception): pass class ArbitratorInitError(ArbitratorError): pass class ConfigError(ArbitratorInitError): pass class ProcessorAvailabilityTestError(ArbitratorInitError): pass class TransporterAvailabilityTestError(ArbitratorInitError): pass class S...
bengarrett/RetroTxt
ext/fonts/woff-to-woff2.py
Python
lgpl-3.0
558
0
#!/usr/bi
n/python3 # # On Windows or a current Linux distro. # pip3 install fontTools[woff] # import os from fontTools.ttLib import TTFont directory = '.' for name in os.listdir(directory): file = os.path.join(directory, name) if os.path.isfile(file) and name.endswith(".woff"): (b, ext) = os.path.splitext(name...
continue print(file, "=>", w2) f = TTFont(file) f.flavor = "woff2" f.save(woff2)
hotchemi/mvns
version.py
Python
apache-2.0
42
0
# -*-
coding:utf-8 -*- VERSION = "0.1.3
"
mkoura/dump2polarion
tests/test_requirement_exporter.py
Python
gpl-2.0
2,552
0.002351
# pylint: disable=missing-docstring,redefined-outer-name,no-self-use,protected-access import copy import os from collections import OrderedDict import pytest from dump2polarion.exceptions import Dump2PolarionException, NothingToDoException from dump2polarion.exporters.requirements_exporter import RequirementExport f...
as excinfo: req_exp.export() assert "Invalid value 'inv' for the 'lookup-method' property" in str(excinfo.value) def test_no_requirements(self, config_cloudtp): req_exp = RequirementExport([], config_cloudtp) with pytest.raises(NothingToDoException)
as excinfo: req_exp.export() assert "Nothing to export" in str(excinfo.value)
zouyapeng/horizon-newtouch
horizon/templatetags/horizon.py
Python
apache-2.0
6,643
0
# 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 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...
vigation entries.""" if 'request' not in context: return {} current_dashboard = context['request'].horizon.get('dashboard', None) dashboards = [] for dash in Horizon.get_dashboards(): if dash.can_access(context): if callable(dash.nav) and dash.nav(context): da...
dash.nav: dashboards.append(dash) return {'components': dashboards, 'user': context['request'].user, 'current': current_dashboard, 'request': context['request']} @register.inclusion_tag('horizon/_subnav_list.html', takes_context=True) def horizon_dashboard_nav(...
sgabe/Enumerator
enumerator/lib/nmap.py
Python
mit
3,708
0.003776
#!/usr/bin/env python """This module is the first step in gathering initial service enumeration data from a list of hosts. It initializes the scanning commands and parses the scan results. The scan results are then passed to the delegator module which determines what enumerator should do next. @author: Steve Coward (s...
(host)s-tcp-greppable.txt -oX %(output_dir)s/%(host)s-tcp.xml %(host)s', 'normal': '-T4 -p-', 'stealth': '-T2', }, { 'command': 'nmap -Pn %(scan_mode)s -sU -sV --open -oN %(output_dir)s/%(host)s-udp-standard.txt
-oG %(output_dir)s/%(host)s-udp-greppable.txt -oX %(output_dir)s/%(host)s-udp.xml %(host)s', 'normal': '-T4 --top-ports 100', 'stealth': '-T2 --top-ports 10', }] # Refined regex pattern for greppable nmap output. SERVICE_PATTERN = re.compile( '\s(\d+)\/([^/]+)?\/([^/]+)?\/([^/]+)?\/([^/]+)?\/([^/]+)?\/([^...
mrquim/mrquimrepo
script.module.exodus/lib/resources/lib/indexers/episodes.py
Python
gpl-2.0
67,539
0.011845
# -*- 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...
years = [str(year), str(int(year)+1), str(int(year)-1)] tvdb = client.request(url, timeout='10') tvdb = re.sub(r'[^\x00-\x7F]+', '', tvdb) tvdb = client.replaceHTMLCodes(tvdb) tvdb = client.parseDOM(tvdb, 'Series') tvdb = [(x, cl...
r x in tvdb] tvdb = [(x, x[1][0], x[2][0]) for x in tvdb if len(x[1]) > 0 and len(x[2]) > 0] tvdb = [x for x in tvdb if cleantitle.get(tvshowtitle) == cleantitle.get(x[1])] tvdb = [x[0][0] for x in tvdb if any(y in x[2] for y in years)][0] tvdb = client.pa...
Advance2/ADVANCE-2.0-Terminal
terminal.py
Python
gpl-2.0
690
0.010145
""" Advnace 2.0 Terminal system created by DatOneLefty DatOneLefty also develops ForceOS """ f = open("log.adv2", "w") def init(): pass def disp(text): """ use: to display text and to log what is displayed How to: disp(te
xt to display) """ f.write("DISPLAY: " + text) print text def askq(quest): """ use: to ask a question and log it How to: var_to_set = askq(question to ask) """ feedback = raw_input (quest) f.write("QUE
STION: " + quest + " With answer: " + feedback) def log(logid, logdisp): f.write (logid + ": " + logdisp) def stop(): import shutil shutil.rmtree("save") disp("The system will stop NOW")
ppolewicz/logfury
src/logfury/v0_1/__init__.py
Python
bsd-3-clause
400
0.0025
from .meta import AbstractTracePublicCallsMeta, DefaultTraceAbstractMeta, Default
TraceMeta, TraceAllPublicCallsMeta from .trace_call import trace_ca
ll from .tuning import limit_trace_arguments, disable_trace assert AbstractTracePublicCallsMeta assert DefaultTraceAbstractMeta assert DefaultTraceMeta assert TraceAllPublicCallsMeta assert disable_trace assert limit_trace_arguments assert trace_call
dslab-epfl/asap
utils/release/findRegressions-simple.py
Python
bsd-2-clause
4,045
0.020766
#!/usr/bin/env python import re, string, sys, os, time, math DEBUG = 0 (tp, exp) = ('compile', 'exec') def parse(file): f = open(file, 'r') d = f.read() # Cleanup weird stuff d = re.sub(r',\d+:\d', '', d) r = re.findall(r'TEST-(PASS|FAIL|RESULT.*?):\s+(.*?)\s+(.*?)\r*\n', d) test = {} fname = '' ...
ew[t].has_key(x): regressions[x] += t + "\n" elif not d_old[t].has_key(x): passes[x] += t + "\n" if math.isnan(d_old[t][x]) and math.isnan(d_new[t][x]): continue elif math.isnan(d_old[t][x]) and not math.isnan(d_new[t][x]): passes[x] += t + "\n" ...
x] > d_old[t][x] and d_old[t][x] > 0.0 and \ (d_new[t][x] - d_old[t][x]) / d_old[t][x] > .05: regressions[x] += t + ": " + "{0:.1f}".format(100 * (d_new[t][x] - d_old[t][x]) / d_old[t][x]) + "%\n" else : removed += t + "\n" if len(regressions['compile state']) != 0: print 'REGR...
telecombcn-dl/2017-cfis
sessions/dream.py
Python
mit
2,614
0.005738
from keras.preprocessing.image import load_img, img_to_array import numpy as np from scipy.optimize import fmin_l_bfgs_b from keras.applications import vgg16 from keras import backend as K from keras.layers import Input def preprocess_image(image_path,img_height,img_width): img = load_img(image_path, target_size=...
uts = f_outputs([x])
loss_value = outs[0] if len(outs[1:]) == 1: grad_values = outs[1].flatten().astype('float64') else: grad_values = np.array(outs[1:]).flatten().astype('float64') return loss_value, grad_values # this Evaluator class makes it possible # to compute loss and gradients in one pass # while ret...
minlexx/pyevemon
esi_client/models/get_markets_structures_structure_id_200_ok.py
Python
gpl-3.0
11,924
0.001593
# coding: utf-8 """ EVE Swagger Interface An OpenAPI for EVE Online OpenAPI spec version: 0.4.6 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from pprint import pformat from six import iteritems import re class GetMarketsStructuresStructureId200Ok(object): """ ...
cation_id integer :param location_id: The
location_id of this GetMarketsStructuresStructureId200Ok. :type: int """ if location_id is None: raise ValueError("Invalid value for `location_id`, must not be `None`") self._location_id = location_id @property def min_volume(self): """ Gets the min...
progrium/duplex
python/demo/demo.py
Python
mit
626
0.011182
import asyncio import websockets imp
ort duplex rpc = duplex.RPC("json") @asyncio.coroutine def echo(ch): obj, _ = yield from ch.recv() yield from ch.send(obj) rpc.register("echo", echo) @asyncio.coroutine def do_msgbox(ch): text, _ = yield from ch.recv() yield from ch.call("msgbox", text, async=True) rpc.register("doMsgbox", do_msgbox)...
erver, 'localhost', 8001) asyncio.get_event_loop().run_until_complete(start_server) asyncio.get_event_loop().run_forever()
praba230890/PYPOWER
pypower/_compat.py
Python
bsd-3-clause
103
0
""" Compatibility helpers for older Python versions. """ import sys PY2 = sys.versio
n_info[0]
== 2
Elico-Corp/odoo-addons
website_captcha_nogoogle_crm/__openerp__.py
Python
agpl-3.0
517
0
# -*- coding: utf-8 -*- # © 2015 Elico corp (www.elico-corp.com) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { 'nam
e': 'Contact Form CAPTCHA', 'version': '8.0.1.0.0', 'category': 'Website', 'depends': [ 'website_crm', 'website_captcha_nogoogle', ], 'author': 'Elico Corp', 'license': '
LGPL-3', 'website': 'https://www.elico-corp.com', 'data': [ 'views/website_crm.xml', ], 'installable': True, 'auto_install': False, }
tehamalab/dgs
goals/filters.py
Python
unlicense
4,056
0
from django import forms from django.contrib.postgres.forms import SimpleArrayField import django_filters from .models import (Plan, Goal, Theme, Sector, Target, Indicator, Component, Progress, Area, AreaType) class SimpleIntegerArrayField(SimpleArrayField): def __init__(self, base_field=for...
ter(name='target__goal'
, queryset=Goal.objects.all()) description = django_filters.CharFilter(lookup_expr='icontains') data_source = django_filters.CharFilter(lookup_expr='icontains') agency = django_filters.CharFilter(lookup_expr='iexact') progress_count = django_filters.NumberFilt...
harryfb/DST5
ArcPy Code/Topography.py
Python
apache-2.0
1,297
0.023901
# import system modules import arcpy from arcpy import env # Set environment settings env.workspace = "C:\Users\Ewan\Desktop\SFTPDST5\MapFiles" try: # Set the local variable in_Table = "Topography.csv" x_coords = "x" y_coords = "y" out_Layer = "Topography_Layer" saved_Layer = "c:\...
Save to a layer file arcpy.SaveToLayerFile_management(out_Layer, saved_Layer) except Exception as err: print(err.args[0]) # Set local variables inFeatures = "Topography.lyr" valField = "Topography" outRaster = "C:\Users\Ewan\Desktop\SFTPDST5\Mapfiles\TopographyR" assignmentType = "MOST_FREQUENT" ...
.000005 # Execute PointToRaster arcpy.PointToRaster_conversion(inFeatures, valField, outRaster, assignmentType, priorityField, cellSize) ##Assign colormap using clr file arcpy.AddColormap_management("c:\Users\Ewan\Desktop\SFTPDST5\Mapfiles\TopographyR", "#", "c:\Users\Ewan\Desktop\SFTPDST5\Mapfiles\colormap.c...
YACOWS/PyNFe
pynfe/entidades/emitente.py
Python
lgpl-3.0
1,321
0.000757
from base import Entidade from pynfe.utils.flags import CODIGO_BRASIL class Emitente(Entidade): # Dados do Emitente # - Nome/Razao Social (obrigatorio) razao_social = str() # - Nome Fantasia nome_fantasia = str() # - CNPJ (obrigatorio) cnpj = str() # - Inscricao Estadual (obrigatorio...
rio) endereco_numero = str() # - Complemento endereco_complemento = str() # - Bairro (obrigatorio) endereco_bairro = str() # - CEP endereco_cep = str() # - Pais (aceita somente Brasil) endereco_pais = CODIGO_BRASIL
# - UF (obrigatorio) endereco_uf = str() # - Municipio (obrigatorio) endereco_municipio = str() # - Codigo Municipio (opt) endereco_cod_municipio = str() # - Telefone endereco_telefone = str() # Logotipo logotipo = None def __str__(self): return self.cnpj
scode/pants
src/python/pants/backend/jvm/tasks/jvm_compile/scala/zinc_compile.py
Python
apache-2.0
12,212
0.007943
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os import tex...
, self).__init__(*args, **kwargs) # A directory independent of any other classpath which can contain per-target # plugin resource files. self._plugin_info_dir = os.path.join(self.workdir, 'sca
lac-plugin-info') self._lazy_plugin_args = None def create_analysis_tools(self): return AnalysisTools(DistributionLocator.cached().real_home, ZincAnalysisParser(), ZincAnalysis) def zinc_classpath(self): # Zinc takes advantage of tools.jar if it's presented in classpath. # For example com.sun.tool...
dalf/searx
searx/engines/sepiasearch.py
Python
agpl-3.0
2,928
0.000342
# SPDX-License-Identifier: AGPL-3.0-or-later """ SepiaSearch (Videos) """ from json import loads from dateutil import parser, relativedelta from urllib.parse import urlencode from datetime import datetime # about about = { "website": 'https://sepiasearch.org', "wikidata_id": None, "official_api_documenta...
lta.relativedelta(months=-1), 'year': re
lativedelta.relativedelta(years=-1) } embedded_url = '<iframe width="540" height="304" src="{url}" frameborder="0" allowfullscreen></iframe>' def minute_to_hm(minute): if isinstance(minute, int): return "%d:%02d" % (divmod(minute, 60)) return None def request(query, params): params['url'] = ba...
boisde/Greed_Island
business_logic/order_collector/transwarp/orm.py
Python
mit
11,968
0.003593
#!/usr/bin/env python # coding:utf-8 """ Database operation module. This module is independent with web module. """ import time, logging import db class Field(object): _count = 0 def __init__(self, **kw): self.name = kw.get('name', None) self.ddl = kw.get('ddl', '') self._default =...
if 'ddl' not in kw: kw['ddl'] = 'datetime' super(DateTimeField, self).__init__(**kw) class DateField(Field): def __init__(self, **kw): if 'ddl' not in kw: kw['ddl'] = 'date' super(DateField, self).__init__(**kw) class EnumField
(Field): def __init__(self, **kw): if 'ddl' not in kw: kw['ddl'] = 'enum' super(EnumField, self).__init__(**kw) _triggers = frozenset(['pre_insert', 'pre_update', 'pre_delete']) def _gen_sql(table_name, mappings): pk, unique_keys, keys = None, [], [] sql = ['-- generating SQL ...
abadger/mondegreen
mondegreen/config.py
Python
gpl-3.0
3,476
0.00374
# -*- coding: utf-8 -*- # # Copyright (c) 2014 Toshio Kuratomi # License: GPLv3+ # # This file is part of Mondegreen. # # Mondegreen 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 Lice...
ault=list())
self.add_argument('--version', action='version', version=__version__) self.add_argument('--idt-posting-team', dest='idt_posting_team') self.add_argument('--slack-posting-channel', dest='slack_posting_channel')
Csega/PythonCAD3
pythoncad_qt.py
Python
gpl-2.0
1,067
0.005623
#!/usr/bin/env python # # This is only needed for Python v2 but is harmless for Python v3. # import PyQt5.sip as sip sip.setapi('QString', 2) # from PyQt5 import QtCore, QtGui, QtWidgets # import sys import os import sqlite3 as sqlite # # this is needed for me to use unpickle objects # sys.path.append(os.path.join(os.g...
dow import CadWindowMdi def getPythonCAD(): app = QtWidgets.QApplication(sys.argv) # Splash screen splashPath = os.path.join(os.getcwd(), 'icons', 'splashScreen1.png') splash_pix = QtGui.QPixmap(splashPath) splash = QtWidgets.QSplashScreen(splash_pix, QtCore.Qt.W
indowStaysOnTopHint) splash.setMask(splash_pix.mask()) splash.show() w = CadWindowMdi() w.show() # End of splash screen splash.finish(w) return w, app if __name__ == '__main__': w, app = getPythonCAD() sys.exit(app.exec_())
masml/masmlblog
Pandas/pandas_masml.py
Python
mit
7,022
0.017374
# coding: utf-8 # In[1]: #Importing libraries import pandas as pd import numpy as np import matplotlib.pyplot as plt # In[2]: #Read csv file #data_frame = pd.read_csv('C:\\Users\\hp\\Desktop\\MAS ML\\datasets\\nyc_weather.csv') #Read excel file data_frame_1 = pd.read_excel('C:\\Users\\hp\\Desktop\\MAS ML\\dataset...
a list of keys #or to have a continuous indexing, just apply ignore_index=True concated_df # In[14]: cross_tab_df = pd.read_excel('C:\\Users\\hp\\Desktop\\MAS ML\\datasets\\survey.xls') pd.crosstab([cross_tab_df.Nationality,cross_tab_df.Sex],cross_tab_df.Handedness,margins
=False,normalize="index") #check the index parameter # In[15]: df= pd.read_csv('C:\\Users\\hp\\Desktop\\MAS ML\\datasets\\weather3.csv') print(df) #Make sure transform_df_1= df.pivot(index="date", columns="city") print(transform_df_1) transform_df_2= df.pivot_table(index="date", columns="city", margins=True, aggfunc...
code-dice/dice
dice/client/__init__.py
Python
gpl-2.0
12,056
0
from __future__ import print_function import argparse import collections import io import json import logging import os # pylint: disable=import-error import queue import random import re import requests import sys import traceback import threading import time from ..core import provider from ..utils import rnd from ...
x=100, method='exact'): self.key = key self.counter = 0 self.queue_max = queue_max self.method = method self.queue = collections.deque([], queue_max) def match(self, text): if self.method == 'exact': return text == self.key elif self.method == 're...
f append(self, result): self.counter += 1 self.queue.append(result) def extend(self, stat): for result in stat.queue: self.append(result) class DiceApp(object): """ Curses-based DICE client application. """ def __init__(self): self.parser = argparse.Arg...
frasern/ADL_LRS
oauth_provider/tests/xauth.py
Python
apache-2.0
2,360
0.002966
# -*- coding: utf-8 -*- import time import urllib from urlparse import parse_qs from oauth_provider.tests.auth import BaseOAuthTestCase, METHOD_URL_QUERY, METHOD_AUTHORIZATION_HEADER, METHOD_POST_REQUEST_BODY class XAuthTestCase(BaseOAuthTestCase): def setUp(self): super(XAuthTestCase, self).setUp() ...
h_consumer_key": self.CONSUMER_KEY, "oauth_consumer_secret": self.CONSUMER_SECRET, "oauth_nonce": "12981230918711", 'oauth_signature_method': 'PLAINTEXT', 'oauth_signature': "%s&%s" % (self.CONSUMER_SECRET, ""), 'oauth_timestamp': str(int(time.time())), ...
'x_auth_username': self.username, } if method==METHOD_AUTHORIZATION_HEADER: header = self._get_http_authorization_header(parameters) response = self.c.get("/oauth/access_token/", HTTP_AUTHORIZATION=header) elif method==METHOD_URL_QUERY: response = self...
brosner/django-sqlalchemy
tests/apps/inventory/models.py
Python
bsd-3-clause
250
0.012
from django.db import
models class Tag(models.Model): tag = models.CharField(max_length=10, primary_key=True) class Product(models.Model): name = models.CharField(max_length=18, primary_key=True) tags = models.ManyToManyFi
eld(Tag)
antmicro/distant-bes
distantbes/enums.py
Python
apache-2.0
1,058
0.006616
from enum import Enum EXIT_CODES = [ "SUCCESS", "BUILD_FAILURE", "PARSING_FAILURE", "COMMAND_LINE_ERROR", "TESTS_FAILED", "PARTIAL_ANALYSIS_FAILURE", "NO_TESTS_FOUND", "RUN_FAILURE", "ANALYSIS_FAILURE", "INTERRUPTED", "LOCK_HEL...
win = "darwin" freebsd = "freebsd" armeabi = "armeabi-v7a" arm = "arm" aarch64 = "aarch64" x64_windows = "x64_windows" x64_w
indows_msvc = "x64_windows_msvc" s390x = "s390x" ppc = "ppc" ppc64 = "ppc64" class CompilationMode(DistantEnum): fastbuild = "fastbuild" dbg = "dbg" opt = "opt"
obeattie/sqlalchemy
lib/sqlalchemy/test/testing.py
Python
mit
27,201
0.003787
"""TestCase and TestSuite artifacts and testing decorators.""" import itertools import operator import re import sys import types import warnings from cStringIO import StringIO from sqlalchemy.test import config, assertsql, util as testutil from sqlalchemy.util import function_named, py3k from engines import drop_all...
, config.db.name, config.db.driver, reason) print msg if carp: print >> sys.stderr, msg return True else: return fn(*args, **kw) return function_named(maybe, fn_name) return decorate def only_on(db, reason): ...
kw): if spec(config.db): return fn(*args, **kw) else: msg = "'%s' unsupported on DB implementation '%s+%s': %s" % ( fn_name, config.db.name, config.db.driver, reason) print msg if carp: print ...
oroulet/python-aravis
examples/save-frame.py
Python
gpl-3.0
538
0.005576
import sys import logging import numpy as np from aravis import Camera if __name__ == "__main__": #cam = ar.get_camera("Prosilica-02-2130A-06106") #cam = Camera("AT-Automation Technology GmbH-20805103") cam = Camera(loglevel=logging.DEBUG) if len(sys.argv) > 1: pa
th = sys.argv[1] else: path = "frame.npy" #cam.start_acquisition_trigger() cam.start_acquisition_continuous() frame = cam.pop_frame() print("Saving frame to ", path) np.save(p
ath, frame) cam.stop_acquisition()
stffer/yunshu
article/migrations/0003_auto_20170512_1614.py
Python
mit
645
0.00155
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-05-12 08:14 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('article', '0002_auto_20170512_1554'), ] operations =...
ns.RemoveField( model_name='talks', name='article', ), migrations.AddField( model_name='article', name='talks', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to=
'article.Talks'), ), ]
geronimo-iia/brume
tests/test_template.py
Python
mit
2,787
0.001435
import os import unittest import boto3 import pytest from moto import mock_s3 from brume.template import Template CONFIG = { 'region': 'eu-west-1', 'local_path': 'test_stack', 's3_bucket': 'dummy-bucket', } class TestTemplate(unittest.TestCase): """Test for brume.Template.""" def setUp(self): ...
ket=CONFIG['s3_bucket']) self.template.upload(copy=True) body = conn.Object(CONFIG['s3_bucket'], self.template.s3_key + '.copy').get()['Body'].read().decode("utf-8") with open(self.template_path, 'r') as f: assert body == f.read() def test_public_url(self): assert self.t...
sts/main.json' def test_s3_key(self): assert self.template.s3_key == 'tests/main.json' def test_public_url_with_s3_path(self): config = { 'region': 'eu-west-1', 'local_path': 'test_stack', 's3_bucket': 'dummy-bucket', 's3_path': 'cloudformation',...
certego/pcapoptikon
main/api.py
Python
gpl-2.0
2,785
0.006463
#!/usr/bin/env python # # api.py # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # 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 more details. # # You should have
received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA # # Author: Pietro Delsante <[email protected]> # www.certego.net # import os from django.contrib.auth.models imp...
andrei-karalionak/ggrc-core
test/integration/ggrc_basic_permissions/test_creator_audit.py
Python
apache-2.0
7,603
0.005261
# Copyright (C) 2016 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> """ Test Creator role with Audit scoped roles """ from ggrc import db from ggrc.models import all_models from integration.ggrc import TestCase from integration.ggrc.api_helper import Api from integration.gg...
"id": context_i
d, "href": "/api/contexts/{}".format(context_id) }}}) self.assertEqual(response.status_code, 201) def test_creator_audit_roles(self): """ Test creator role with all audit scoped roles """ # Check permissions based on test_cases: errors = [] for test_case in self.test_cas...
alexeyum/scikit-learn
sklearn/random_projection.py
Python
bsd-3-clause
22,132
0
# -*- coding: utf8 """Random Projection transformers Random Projections are a simple and computationally efficient way to reduce the dimensionality of the data by trading a controlled amount of accuracy (as additional variance) for faster processing times and smaller model sizes. The dimensions and distribution of Ra...
onents of the random matrix are drawn from N(0, 1.0 / n_components). Read more in the :ref:`User Guide <gaussian_random_matrix>`. Parameters ---------- n_components : int, Dimensionality of the target projection spac
e. n_features : int, Dimensionality of the original source space. random_state : int, RandomState instance or None (default=None) Control the pseudo random number generator used to generate the matrix at fit time. Returns ------- components : numpy array of shape [n_compon...
shanzi/myicons
iconcollections/migrations/0002_auto_20141027_1107.py
Python
bsd-2-clause
2,135
0.001405
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('iconcollections', '0001_initial'), ] operations = [ migrations.AlterField( mode...
), migrations.AlterField( model_name='
collectionicon', name='svg_d', field=models.TextField(default=b'', blank=True), preserve_default=True, ), migrations.AlterField( model_name='collectionicon', name='tagnames', field=models.TextField(default=b'', blank=True), ...
mbertrand/cga-worldmap
geonode/register/forms.py
Python
gpl-3.0
2,566
0.007405
# -*- coding: UTF-8 -*- from django import forms from django.conf import settings from django.contrib.auth.models import User from django.contrib.sites.models import Site from registration.forms import RegistrationFormUniqueEmail from django.utils.translation import ugettext_lazy as _ from geonode.maps.models import Co...
l = forms.EmailField(widget=fo
rms.TextInput(attrs=dict(attrs_dict, maxlength=75)), label=_(u'Email Address')) class UserRegistrationForm(RegistrationFormUniqueEmail): if (settings.USE_CUSTOM_ORG_AUTHORIZATION): is_org_member = forms.TypedChoiceField(coerce=lambda x: bool(int(x)), choices=((1, _(u'Yes...
BridgesLab/mousedb
mousedb/veterinary/__init__.py
Python
bsd-3-clause
730
0.006849
'''The veterinary app is for medical issues associated with animals. The primary functions of this app are to: * Store data about mice which have some medical problem * Describe the problem including its duration. * Store details about the treatment of that problem. As such there are three data structures in this ap...
ion. *
:class:`~mousedb.veterinary.MedicalTreatment, which describes the treatment response. The goal of this app is to more accurately systematize medical data, and to link that data back to differences in strains or mice.``'''
tkao1000/pinot
thirdeye/thirdeye-pinot/src/main/resources/scripts/detector_admin.py
Python
apache-2.0
19,104
0.005392
# fix desktop python path for argparse import sys sys.path.insert(1, '/usr/local/linkedin/lib/python2.6/site-packages') import argparse import cmd from datetime import date, datetime, timedelta import json from pprint import pprint import httplib import re import urllib client = None class ThirdEyeHttpClient(objec...
(func=show_email_report_ids) find_parser = email_reports_subparser.add_parser('find', help='find an email report') find_parser.add_argument('inps', type=int, nargs='+', help='email_report ids', metav
ar='ids') find_parser.set_defaults(func=find_email_report) create_parser = email_reports_subparser.add_parser('create', help='create a new email report. be sure to reset the scheduler afterwards!') create_parser.add_argument('inps', nargs='+', help='JSON files specifying email reports to be created', metav...
RohanNagar/lightning
scripts/tester.py
Python
mit
5,735
0.002267
import argparse import hashlib import json import requests from pprint import pprint class Colors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' class TestCase: def __in...
, authentication, params={'email': args.email}, headers={'password': password}), TestCase('GET', '/facebook/photos', authentication, params={'email': args.email}, headers={'password': password}), TestCase('GET', '/facebook/videos', auth...
password}), TestCase('GET', '/facebook/extendedToken', authentication, params={'email': args.email}, headers={'password': password}), TestCase('POST', '/facebook/publish', authentication, params={'email': args.email, 'type': 'photo', 'message': 'Lightn...
fernandog/Sick-Beard
sickbeard/postProcessor.py
Python
gpl-3.0
41,517
0.00737
# Author: Nic Wolfe <[email protected]> # URL: http://code.google.com/p/sickbeard/ # # This file is part of Sick Beard. # # Sick Beard 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 Lice...
sick
beard import encodingKludge as ek from sickbeard.exceptions import ex from sickbeard.name_parser.parser import NameParser, InvalidNameException from lib.tvdb_api import tvdb_api, tvdb_exceptions class PostProcessor(object): """ A class which will process a media file according to the post processing settings...
dotKom/onlineweb4
apps/slack/urls.py
Python
mit
191
0
from apps.api.utils import SharedAPIRootRouter from apps.slack import views urlpatterns = [] router = SharedA
PIRootRouter() router.register('slack',
views.InviteViewSet, base_name='slack')
wilsonkichoi/zipline
tests/test_panel_daily_bar_reader.py
Python
apache-2.0
2,906
0
# # Copyright 2016 Quantopian, 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 wr...
ng.fixtures import ( WithAssetFinder, WithNYSETradingDays, ZiplineTestCase, ) class TestPanelDailyBarReader(WithAssetFinder, WithNYSETradingDays, ZiplineTestCase): START_DATE = pd.Timestamp('2006-01-03', tz='utc') END_DATE = pd.Timestamp...
c') @classmethod def init_class_fixtures(cls): super(TestPanelDailyBarReader, cls).init_class_fixtures() finder = cls.asset_finder days = cls.trading_days items = finder.retrieve_all(finder.sids) major_axis = days minor_axis = ['open', 'high', 'low', 'close', '...
wenottingham/ansible
lib/ansible/plugins/connection/ssh.py
Python
gpl-3.0
32,355
0.00306
# (c) 2012, Michael DeHaan <[email protected]> # Copyright 2015 Abhijit Menon-Sen <[email protected]> # # This file is part of Ansible # # Ansible 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, eithe...
(%s)' % (explanation, ')('.join(to_text(a) for a in b_args)), host=self._play_context.remote_addr) b_command += b_args def _build_command(self, binary, *other_args): ''' Takes a binary (ssh, scp, sftp) and optional extra arguments and returns a command line as an
array that can be passed to subprocess.Popen. ''' b_command = [] # # First, the command to invoke # # If we want to use password authentication, we have to set up a pipe to # write the password to sshpass. if self._play_context.password: if...
alliance-genome/agr_prototype
indexer/src/files/comment_file.py
Python
mit
327
0
class CommentFile: def __init__
(self, f, commentstring="#"): self.f = f self.commentstring = commentstring def next(self): line = self.f.next() while line.startswith(self.commentstring): line = self.f.next() return l
ine def __iter__(self): return self
back-to/streamlink
src/streamlink/plugins/ard_mediathek.py
Python
bsd-2-clause
4,132
0.00121
import re from streamlink.plugin import Plugin from streamlink.plugin.api import validate from streamlink.stream import HDSStream, HLSStream, HTTPStream MEDIA_URL = "http://www.ardmediathek.de/play/media/{0}" SWF_URL = "http://www.ardmediathek.de/ard/static/player/base/flash/PluginFlash.swf" HDCORE_PARAMETER = "?hdco...
"288p", 0: "144p" } _url_re = re.compile(r"http(s)?://(?:(\w+\.)?ardmediathek.de/tv|mediathek.daserste.de/)") _media_id_re = re.compile(r"/play/(?:media|config)/(\d+)") _media_s
chema = validate.Schema({ "_mediaArray": [{ "_mediaStreamArray": [{ validate.optional("_server"): validate.text, "_stream": validate.any(validate.text, [validate.text]), "_quality": validate.any(int, validate.text) }] }] }) _smil_schema = validate.Schema( ...
SEA000/uw-empathica
empathica/gluon/contrib/login_methods/motp_auth.py
Python
mit
4,542
0.008587
#!/usr/bin/env python import time from hashlib import md5 from gluon.dal import DAL def motp_auth(db=DAL('sqlite://storage.sqlite'), time_offset=60): """ motp allows you to login with a one time password(OTP) generated on a motp client, motp clients are available for practica...
/login_methods/ folder first auth_user has to have 2 extra fields - motp_secret and motp_pin for that define auth like shown below: ## after auth = Auth(db) db.define_table( auth.settings.table_user_name, Field('first_name', length=128, d
efault=''), Field('last_name', length=128, default=''), Field('email', length=128, default='', unique=True), # required Field('password', 'password', length=512, # required readable=False, label='Password'), Field('motp_secret',length=512,default='', ...
Yarr/Yarr
localdb/lib/localdb-tools/modules/db_logging.py
Python
gpl-2.0
3,337
0.011387
#!/usr/bin/env python3 ################################# # Author: Arisa Kubota # Email: arisa.kubota at cern.ch # Date: July 2020 # Project: Local Database for YARR ################################# import os from copy import copy from logging import getLogger, getLoggerClass, Formatter, FileHandler, StreamHandler, a...
FO' : "[ info ]", # cyan 'WARNING' : "[warning ]", # yellow 'ERROR' : "[ error ]", # red 'CRITICAL': "[critical]", # white on red bg } LevelColors = { 'DEBUG' : 37, # white 'INFO' : 32, # green 'WARNING' : 33, # yellow 'ERROR' : 31, # red 'CRITICAL': 41, # white on red bg...
_init__(self, patern, datefmt="%H:%M:%S") def format(self, record): colored_record = copy(record) levelname = colored_record.levelname color = LevelColors.get(levelname, 37) name = LevelNames .get(levelname, "[unknown ]") colored_levelname = "\033[{0}m{1}[ Local DB ]:\0...
txomon/vdsm
vdsm/storage/hsm.py
Python
gpl-2.0
138,543
0.000079
# # Copyright 2009-2012 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 2 of the License, or # (at your option) any later version. # # This program is distributed ...
ns = config.get( 'irs', 'nfs_mount_options').replace(' ', '') if (frozenset(conf_options.split(',')) != frozenset(storageServer.NFSConnection.DEFAULT_OPTIONS)): logging.warning("Using deprecated nfs_mount_options from" " vds...
rageServer.PosixFsConnectionParameters( conDict.get('connection', None), 'nfs', conf_options) return None typeName = CON_TYPE_ID_2_CON_TYPE[conTypeId] if typeName == 'localfs': params = storageServer.LocaFsConnectionParameters( conDict.get('connection', None)) ...
wangshiphys/HamiltonianPy
HamiltonianPy/quantumoperator/factory.py
Python
gpl-3.0
15,843
0.000126
""" This module provides functions that generate commonly used Hamiltonian terms. """ __all__ = [ "Annihilator", "Creator", "CPFactory", "HoppingFactory", "PairingFactory", "HubbardFactory", "Coulo
mbFactory", "HeisenbergFactory", "IsingFactory", "TwoSpinTermFactory", ] from HamiltonianPy.quantumope
rator.constant import ANNIHILATION, CREATION, \ SPIN_DOWN, SPIN_UP from HamiltonianPy.quantumoperator.particlesystem import AoC, ParticleTerm from HamiltonianPy.quantumoperator.spinsystem import * def Creator(site, spin=0, orbit=0): """ Generate creation operator: $c_i^{\\dagger}$. Parameters ---...
timsnyder/bokeh
examples/custom/font-awesome/named_icon.py
Python
bsd-3-clause
7,263
0.008674
from bokeh.core.enums import enumeration NamedIcon = enumeration(*[ "adjust", "adn", "align-center", "align-justify", "align-left", "align-right", "ambulance", "anchor", "android", "angellist", "angle-double-down", "angle-double-left", "angle-double-right", "angle-double-up", "angle-down", "angle-left", "a...
tasks", "taxi", "tencent-weibo", "terminal", "text-height", "text-width", "th", "th-large", "th-list", "thumb-tack", "thum
bs-down", "thumbs-o-down", "thumbs-o-up", "thumbs-up", "ticket", "times", "times-circle", "times-circle-o", "tint", "toggle-down", "toggle-left", "toggle-off", "toggle-on", "toggle-right", "toggle-up", "trash", "trash-o", "tree", "trello", "trophy", "truck", "try", "tty", "tumblr", "tumblr-square", "turkish...
css-umsetzung/three.js
utils/exporters/blender/2.60/scripts/addons/io_mesh_threejs/__init__.py
Python
mit
15,481
0.018022
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distrib...
workers", default=False) def execute(self, context): import io_mesh_threejs.import_threejs return io_mesh_threejs.import_threejs.load(self, context, **self.properties) def draw(self, context): layout = self.layout row = layout.row() row.prop(self.properties, "option_f...
operties, "option_worker") # ################################################################ # Exporter - settings # ################################################################ SETTINGS_FILE_EXPORT = "threejs_settings_export.js" import os import json def file_exists(filename): """Return true if file exis...
MediaKraken/mkarchive
main_download.py
Python
gpl-2.0
3,059
0.002615
''' Copyright (C) 2017 Quinn D Granfor <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but ...
mmon_logging_elasticsearch.CommonElasticsearch('main_download') def on_message(channel, method_frame, header_frame, body): """ Process pika message """ if body
is not None: common_global.es_inst.com_elastic_index('info', {'msg body': body}) json_message = json.loads(body) if json_message['Type'] == 'youtube': dl_pid = subprocess.Popen(['youtube-dl', '-i', '--download-archive', '/mediakraken/archive.txt...
facebook/mcrouter
mcrouter/test/test_mcrouter_to_mcrouter_tko.py
Python
mit
1,294
0.002318
#!/usr/bin/env python3 # Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import re import time from mcrouter.test.McrouterTestCase import McrouterTestCase class TestMcrouterToMcrouterTko(M...
ats)) self.assertTrue(re.match("status:(tko|down)", list(stats.values())[0]
)) stats = mcr.stats("suspect_servers") self.assertEqual(0, len(stats))
diogo149/treeano
treeano/sandbox/nodes/interval_relu.py
Python
apache-2.0
1,043
0
""" relu where each channel has a different leak rate """ import numpy as np import theano import theano.tensor as T import treeano import treeano.nodes as tn fX = theano.config.floatX @treeano.register_node("interval_relu") class IntervalReLUNode(treeano.NodeImpl): hyperparameter_names = ("leak_min", ...
w.shape[1] alpha = np.linspace(leak_min, leak_max, num_channels).astype(fX) pattern = ["x" if i != 1 else 0 for i in range(in_vw.ndim)] alpha_var = T.constant(alpha).dimshuffle(*pattern) out_var = treeano.utils.rectify(in_vw.variable, negative_coef...
w.shape, tags={"output"}, )
movicha/dcos
packages/bootstrap/extra/dcos_internal_utils/utils/__init__.py
Python
apache-2.0
1,151
0
import fcntl import logging import os log = logging.getLogger(__name__) def read_file_line(filename): with open(filename, 'r') as f: return f.read().strip() class Directory: def __init__(self, path): self.path = path def __enter__(self): log.info('Opening {}'.format(self.path))...
log.info('Closing {} with fd {}'.format(self.path, self.fd)) os.close(self.fd) def lock(self): return Flock(self.fd, fcntl.LOCK_EX) class Flock: def
__init__(self, fd, op): (self.fd, self.op) = (fd, op) def __enter__(self): log.info('Locking fd {}'.format(self.fd)) # If the fcntl() fails, an IOError is raised. fcntl.flock(self.fd, self.op) log.info('Locked fd {}'.format(self.fd)) return self def __exit__(sel...
YuukanOO/beard
tests/test_pos.py
Python
mit
454
0.006608
from beard import pos import base_test import unittest class TestPosModule(base_test.RequireTokens): def test_create_from_tokens(self): data = pos.create_from_tokens(se
lf.tokens_01) w = data.get('words', {}) p = data.get('parts_of_speech', {}) self.assertTrue(w) self.assertT
rue(p) self.assertEqual(len(w), 14) self.assertEqual(len(p), 7) # Don't forget the None Pos (start of paragraph)
kamatama41/luigi-bigquery
luigi_bigquery/tests/test_helper.py
Python
apache-2.0
3,217
0.002176
from luigi_bigquery import ResultProxy import os import shutil import tempfile class MockClient(object): def __init__(self, datasets, tables, jobs): self._datasets = datasets self._tables = tables self._jobs = jobs def create_dataset(self, dataset_id, friendly_name=None, description=N...
return dataset_id in [ds['datasetReference']['datasetId'] for ds in self.get_datasets()] def get_table(self, dataset_id, table_id): for table in self._tables: ref = table['tableReference'] if ref['datasetId'] == dataset_id and ref['tableId'] == table_id: return ...
omplete', False), int(job.get('total_rows', 0))) def get_query_schema(self, job_id): job = self._job(job_id) return job['schema'] def get_query_rows(self, job_id): job = self._job(job_id) return job['rows'] def query(self, query): return (self._jobs[0]['job_id'], N...
skitzycat/beedraw
beesessionstate.py
Python
gpl-2.0
21,483
0.045012
# Beedraw/Hive network capable client and server allowing collaboration on a single image # Copyright (C) 2009 Thomas Becker # # 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; eith...
port * from beeeventstack import * from beelayer import BeeLayerState from beeutil import getTimeString from Queue import Queue import os from datetime import datetime class BeeSessionState: """ Represents the state of a current drawing with all layers and the current composition of them to be displayed on the scree...
# save passed values self.networkhistorysize=0 self.docwidth=width self.docheight=height self.type=type self.master=master self.remoteidlock=qtcore.QReadWriteLock() self.remoteid=0 self.historysize=20 self.nextfloatinglayerkey=-1 self.nextfloatinglayerkeylock=qtcore.QReadWriteLock() self.lay...
exaile/exaile
xl/migrations/database/from1to2.py
Python
gpl-2.0
2,024
0.000988
# Copyright (C) 2008-2010 Adam Olsen # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # # This program is distributed in the hope that...
. from gi.repository import Gio def migrate(db, pdata, oldversion, newversion): for k in (x for x in pdata.keys() if x.startswith("tracks-")):
p = pdata[k] tags = p[0] try: loc = tags['__loc'] except KeyError: continue if not loc or not loc.startswith("file://"): continue loc = loc[7:] gloc = Gio.File.new_for_uri(loc) uri = gloc.get_uri() tags['__loc'] = uri ...
ActiveState/code
recipes/Python/416087_Persistent_environment_variables/recipe-416087.py
Python
mit
1,724
0.012761
from _winreg import * import os, sys, win32gui, win32con def queryValue(key, name): value, type_id = QueryValueEx(key, name) return value def show(key): for i in range(1024): try: n,v,t = EnumValue(key, i) print '%s=%s' % (n...
lue enver will delete the <name> environment variable Note that the current command window will not be affected, only new command windows. """ argc = len(sys.argv) if argc > 2 or (argc == 2 and sys.argv[1].find('=') == -1): print usage
sys.exit() main()
KristianOellegaard/python-cloudfoundry
cloudfoundry/apps.py
Python
mit
1,241
0.003223
class CloudFoundryApp(object): environment_variables = [] instances = 0 meta = {} created = 0 debug = None version = 0 running_instances = 0 services = [] state = "" uris = [] def __init__(self, name, env=None, instanc
es=None, meta=None, created=None, debug=None, version=None, runningInstances=None, services=None, state=None, uris=None, staging=None, resources=None, interface=None): self._name = name self.environment_variables = env self.instances = instances self.met...
ices self.state = state self.uris = uris self.interface = interface @property def name(self): return self._name @staticmethod def from_dict(dict, interface=None): return CloudFoundryApp(interface=interface, **dict) def delete(self): if not self.inte...
Yellowen/Owrang
patches/may_2013/p02_update_valuation_rate.py
Python
agpl-3.0
1,359
0.031641
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import webnotes def execute(): from stock.stock_ledger import update_entries_after item_warehouse = [] # update valuation_rate in transaction doctypes = {"Purchas...
(dt, '%s', '%s'), tuple([item.valuation_rate, item.name])) if dt == "Purchase Receipt": webnotes.conn.sql("""update `tabStock Ledger Entry` set incoming_rate = %s wh
ere voucher_detail_no = %s""", (item.valuation_rate, item.name)) if [item.item_code, item.warehouse] not in item_warehouse: item_warehouse.append([item.item_code, item.warehouse]) for d in item_warehouse: try: update_entries_after({"item_code": d[0], "warehouse": d[1], "posting_date": "2013-01...
kfox1111/apps-catalog-ui
app_catalog/panel.py
Python
apache-2.0
734
0
# Copyright 2015 IBM Corp. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file
except in compliance with the License. # You ma
y obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for...
ianunruh/hvac
tests/unit_tests/api/secrets_engines/test_aws.py
Python
apache-2.0
3,608
0.000554
#!/usr/bin/env python # -*- coding: utf-8 -*- import logging from unittest import TestCase import requests_mock from parameterized import parameterized, param from hvac.adapters import JSONAdapter from hvac.api.secrets_engines import Aws from hvac.api.secrets_engines.aws import DEFAULT_MOUNT_POINT from hvac.exception...
JSONAdapter()) mock_url = "http://localhost:8200/v1/{mount_point}/config/
rotate-root".format( mount_point=mount_point, ) logging.debug("Mocking URL: %s" % mock_url) with requests_mock.mock() as requests_mocker: requests_mocker.register_uri( method="POST", url=mock_url, status_code=expected_status...
dev1972/Satellitecoin
qa/rpc-tests/util.py
Python
mit
12,392
0.008554
# Copyright (c) 2014 The Bitcoin Core developers # Copyright (c) 2014-2015 The Dash developers # Copyright (c) 2015-2017 The STLL developers # Distributed under the MIT/X11 software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # # Helpful routines for regression te...
rt: rv += ['-rpcport=' + rpcport] return rv def start_node(i, dirname, extra_args=None, rpchost=None): """ Start a stlld and return RPC c
onnection to it """ datadir = os.path.join(dirname, "node"+str(i)) args = [ os.getenv("BITCOIND", "stlld"), "-datadir="+datadir, "-keypool=1", "-discover=0", "-rest" ] if extra_args is not None: args.extend(extra_args) bitcoind_processes[i] = subprocess.Popen(args) devnull = open("/dev/null", "w...
ewbankkit/cloud-custodian
tools/c7n_azure/c7n_azure/resources/vm.py
Python
apache-2.0
6,309
0.00111
# Copyright 2018 Capital One Services, 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 agreed to in...
return super(InstanceViewFilter, self).__call__(i['instanceView']) @VirtualMachine.filter_registry.register('network-interface') class NetworkInterfaceFilter(RelatedResourceFilter): schema = type_schema('network-interface', rinherit=ValueFilter.sch
ema) RelatedResource = "c7n_azure.resources.network_interface.NetworkInterface" RelatedIdsExpression = "properties.networkProfile.networkInterfaces[0].id" @VirtualMachine.action_registry.register('poweroff') class VmPowerOffAction(AzureBaseAction): schema = type_schema('poweroff') def _prepare_proc...
ptpt/taoblog
taoblog/views/api.py
Python
mit
7,738
0.000258
from flask import (Blueprint, current_app as app, g, request, make_response, jsonify, session) from ..models import ModelError, Session from ..models.post import Post, Draft, PostOperator from .helpers import (require_int, JumpDirectly) api_bp = Blueprint('api', __name__) post_o...
'/posts/') def get_posts(): """ Get posts. * admin required * arguments: offset, limit, status, meta, sort, asc, tags, id """ offset = require_int(request.args.get('offset', 0), JumpDirectly(jsonify_error('invalid offset', 400))) limit = require_int( request...
us = request.args.get('status', 'public+private').lower() # admin may be required in this function status_code = get_status_code(status) meta = 'meta' in request.args sort = request.args.get('sort', 'created_at') # if asc argument is found, do asc sort asc = 'asc' in request.args tags = requ...
FaradayRF/Faraday-Software
faraday/deviceconfiguration.py
Python
gpl-3.0
26,804
0.003582
#------------------------------------------------------------------------------- # Name: /faraday/deviceconfiguration.py # Purpose: Configure the Faraday radio by manipulating relevant INI files # and providing a Flask server to kick off programming with via # proxy. # # Author: ...
Initialize Faraday radio configuration file from faraday_config.sample.ini :return: None, exits program ''' faradayHelper.initializeConfig(faradayTruthFile, faradayFile) sys.exit(0) def programFaraday(deviceConfigurationConfigPath): ''' Programs Faraday by generating a HTTP POST query that...
data to the CC430 FLASH memory. :param deviceConfigurationConfigPath: Path to deviceconfiguration.ini file :return: None ''' config = ConfigParser.RawConfigParser() config.read(deviceConfigPath) # Variables local_device_callsign = config.get("DEVICES", "CALLSIGN") local_device_node_i...
marrow/wsgi.objects
tests/test_adapters/test_content_adapters.py
Python
mit
2,463
0.007714
# encoding: utf-8 from __future__ import unicode_literals, division, print_function, absolute_import try: # This to handle Python 2.6 which is missing a lot. from unittest2 import TestCase except ImportError: from unittest import TestCase fr
om marrow.wsgi.objects.adapters.content import ContentType, ContentEncoding from helpers import MockObject class TestContentType(TestCase): class Mock(MockObject): mime = ContentType('CONTENT_TYPE', None) def setUp(self): self.inst = self.Mock() def test_empty(self): self...
inst = Mock() self.assertEquals(b"text/html", inst.mime) def test_assignment(self): self.assertEquals(None, self.inst.mime) __import__('pprint').pprint(self.inst) self.inst.mime = "text/html" self.assertEquals(b"text/html", self.inst.mime) def test_a...
scheib/chromium
third_party/blink/tools/blinkpy/web_tests/controllers/test_result_sink.py
Python
bsd-3-clause
10,076
0.000595
# Copyright 2020 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. """TestResultSink uploads test results and artifacts to ResultDB via ResultSink. ResultSink is a micro service that simplifies integration between ResultDB a...
name, paths in result.artifacts.artifacts.items(): for p in paths: art_id = name i = 1 while art_id in ret: art_id = '%s-%d' % (name, i) i += 1 ret[art_id] = { 'filePath': s
elf._port.host.filesystem.join(base_dir, p), } # Web tests generate the same artifact names for text-diff(s) # and image diff(s). # - {actual,expected}_text, {text,pretty_text}_diff # - {actual,expected}_image, {image,pretty_image}_diff ...