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
openstates/openstates
openstates/ks/ksapi.py
Python
gpl-3.0
8,104
0.000123
ksleg = "http://www.kslegislature.org/li" url = "%s/api/v11/rev-1/" % ksleg # These actions are from the KLISS API documentation, # and are in the same order as that table # The PDF is linked from this webpage, and changes name # based on the most recent API version: # http://www.kslegislature.org/klois/Pages/RESTianA...
w_jcow_203": None, "ccac_cc_377": None, # conf committee changed member "ee_enrb_226": None, # Enrolled # more COW actions "cow_jcow_681": None, "cow_jcow_682": None, "cow_jcow_683": None, "cow_jcow_688": None, "cow_jcow_689": None, # veto overrides "gov_avm_88
5": "veto-override-failure", "gov_avm_887": "veto-override-passage", "ref_rsc_312": "referral-committee", # more COW actions "cow_jcow_903": None, "cow_jcow_902": None, "cow_jcow_901": None, "cow_jcow_905": None, # no motion to veto override (count as failure?) "gov_avm_128": "veto-o...
bitmazk/django-event-rsvp
event_rsvp/tests/forms_tests.py
Python
mit
3,796
0
"""Tests for the forms of the ``event_rsvp`` app.""" from django.test import TestCase from django.utils import timezone from django_libs.tests.factories import UserFactory from event_rsvp.forms import EventForm, GuestForm from event_rsvp.models import Event, Guest from event_rsvp.tests.factories import EventFactory ...
plate=True) self.assertTrue(form.is_valid()) instance = form.save() self.assertEqual(Event.objects.all().count(), 2) # Test saving a template data.update({'template_name': 'Foo'}) form = EventForm(data=data, created_by=self.user) self.assertTrue(form.is_valid()) ...
data.update({'street': 'Barstreet'}) instance = Event.objects.get(template_name='Foo') form = EventForm(data=data, instance=instance, created_by=self.user) self.assertTrue(form.is_valid()) instance = form.save() self.assertEqual(instance.street, 'Barstreet') class Guest...
google/gazoo-device
gazoo_device/tests/unit_tests/nrf_matter_device_test.py
Python
apache-2.0
4,549
0.005056
# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
PERSISTENT_PROPERTIES) def test_flash_build_capability(self): """Verifies the initialization of flash_build capability.""" self.assertTrue(self.uut.flash_build) def test_matter_endpoints_capability(self): """Verifies the initialization of matter_endpoints capability.""" self.assertIsNotNone(self.u...
_power_capability(self): """Verifies the initialization of device_power capability.""" self.assertIsNotNone(self.uut.device_power) @mock.patch.object( device_power_default.DevicePowerDefault, "cycle", autospec=True) def test_device_reboot_hard(self, reboot_fn): self.uut.reboot(method="hard") ...
networkdynamics/zenlib
src/zen/tests/gml_interpreter.py
Python
bsd-3-clause
2,727
0.041437
from zen import * import unittest import os import os.path as path import tempfile class GMLTokenizerCase(unittest.TestCase): tok = gml_tokenizer.GMLTokenizer() codec = gml_codec.BasicGMLCodec() interp = gml_interpreter.GMLInterpreter(codec, tok) def test_basic_correct(self): tokens = [ ('keyOne', 0, 1),...
ef test_incorrect_eof_when_expecting_value(self): tokens = [ ('keyOne', 0, 1), ('"one"', 1, 1), ('keyTwo', 0, 1) ] self.assertRaises(ZenException, self.interp.interpret, tokens) def test_incorrect_eolist_when_expecting_value(self): tokens = [ ('keyOne', 0, 1), ('[', 2, 1), ('subKeyOne', 0, 2),...
yTwo', 0, 3), (']', 3, 6), ('keyTwo', 0, 8), ('"two"', 1, 8) ] self.assertRaises(ZenException, self.interp.interpret, tokens) if __name__ == '__main__': unittest.main()
x2Ident/x2Ident_test
mitmproxy/mitmproxy/addons.py
Python
gpl-3.0
2,173
0
from __future__ import absolute_import, print_function, division from mitmproxy import exceptions import pprint def _get
_name(itm): return getattr(itm, "name", itm.__class__.__name__) class Addons(object): def __init__(self, master): self.chain = [] self.master = master master.options.changed.connect(self.options_update) def options_update(self, options, updated): for i in self.c...
ValueError("No addons specified.") self.chain.extend(addons) for i in addons: self.invoke_with_context(i, "start") self.invoke_with_context( i, "configure", self.master.options, self.master.options.keys() ...
openstack/zaqar
zaqar/storage/configuration.py
Python
apache-2.0
1,625
0
# Copyright (c) 2016 HuaWei, 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 writi...
CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. from oslo_config import cfg class Configuration(object): def __init__(self, conf): """Initialize configuration.""" self.local_conf = conf ...
me_opts, group=None): self.local_conf.register_opts(volume_opts, group=group) def set_override(self, name, override, group=None): self.local_conf.set_override(name, override, group=group) def safe_get(self, value): try: return self.__getattr__(value) except cfg.NoSu...
peterbe/configman
configman/tests/test_option.py
Python
bsd-3-clause
12,084
0.000248
# ***** BEGIN LICENSE BLOCK ***** # Version: MPL 1.1/GPL 2.0/LGPL 2.1 # # The contents of this file are subject to the Mozilla Public License Version # 1.1 (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.mozilla.org/MPL/ # # Softwa...
Developer are Copyright (C) 2011 # the Initial Developer. All Rights Reserved. # # Contributor(s): # K Lars Lohn, lars@mozilla.com # Peter Bengtsson, peterbe@mozilla.com # # Alternatively, the contents of this file may be used under the terms of # either the GNU General Public License Version 2 or later (the "GPL...
# of those above. If you wish to allow use of your version of this file only # under the terms of either the GPL or the LGPL, and not to allow others to # use your version of this file under the terms of the MPL, indicate your # decision by deleting the provisions above and replace them with the notice # and other pro...
jepio/JKalFilter
test/test_track.py
Python
gpl-2.0
673
0.001486
""" Test of tracking and detector response. """ # pylint:
disable=C0103 from ..detector import LayeredDetector from ..track import gen_straight_tracks from matplotlib import pyplot as plt def main(): """ Test if construction of detector works and propagate tracks through detector. """ A = LayeredDet
ector(1, 0, 0.5, 8, 10, 25) tracks = gen_straight_tracks(20) x_coords = [0.1 * i for i in xrange(100)] A.propagate_tracks(tracks) for track in tracks: y = [track.get_yintercept(x) for x in x_coords] plt.plot(x_coords, y) plt.xlim(0, 10) plt.ylim(-0.5, 0.5) A.draw() if __na...
danbob123/gplearn
gplearn/skutils/tests/test_testing.py
Python
bsd-3-clause
3,785
0.000264
import warnings import unittest import sys from nose.tools import assert_raises from gplearn.skutils.testing import ( _assert_less, _assert_greater, assert_less_equal, assert_greater_equal, assert_warns, assert_no_warnings, assert_equal, set_random_state, assert_raise_message) fro...
_warns is not i
mpacted by externally set # filters and is reset internally. # This is because `clean_warning_registry()` is called internally by # assert_warns and clears all previous filters. warnings.simplefilter("ignore", UserWarning) assert_equal(assert_warns(UserWarning, f), 3) # ...
Danielweber7624/pybuilder
src/main/python/pybuilder/plugins/python/pep8_plugin.py
Python
apache-2.0
1,506
0.000664
# -*- coding: utf-8 -*- # # This file is part of PyBuilder # # Copyright 2011-2015 PyBuilder 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/l...
ogger.warn("Found %d warning%s p
roduced by pep8", len(reports), "" if len(reports) == 1 else "s")
wallnerryan/quantum_migrate
quantumclient/quantum/v2_0/nvp_qos_queue.py
Python
apache-2.0
2,899
0
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2013 Nicira Inc. # All Rights Reserved # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/lice...
parsed_args.qos_marking: params['qos_marking'] = parsed_args.qos_marking if parsed_args.dscp: params['dscp'] = parsed_args.dscp if parsed_args.tenant_id: params['ten
ant_id'] = parsed_args.tenant_id return {'qos_queue': params} class DeleteQoSQueue(quantumv20.DeleteCommand): """Delete a given queue.""" log = logging.getLogger(__name__ + '.DeleteQoSQueue') resource = 'qos_queue' allow_names = True
Azure/azure-sdk-for-python
sdk/network/azure-mgmt-network/azure/mgmt/network/v2019_07_01/aio/operations/_express_route_circuit_peerings_operations.py
Python
mit
21,838
0.00522
# 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 ...
/expressRouteCircuits/{circuitName}/peerings/{peeringName}'} # type: ignore async def begin_delete( self, resource_group_name: str, circuit_name: str, peering_name: str, **kwargs: Any ) -> As
yncLROPoller[None]: """Deletes the specified peering from the specified express route circuit. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param circuit_name: The name of the express route circuit. :type circuit_name: str :...
Danko90/cifpy3
lib/cif/types/observables/ipv6.py
Python
gpl-3.0
836
0.001196
__author__ = 'James DeVincentis <james.d@hexhost.net>' from .ipaddress import Ipaddress class Ipv6(Ipaddress): def __
init__(self, *args, **kwargs): self._mask = None super(Ipv6, self).__init__(self, args, **kwargs) @property def mask(self): return self._mask @mask.setter def mask(self, value): if self._validation and value is not None: if not isinstance(value, int): ...
or("Mask must be an integer") from e if value > 128: raise TypeError("Mask cannot be greater than 128 bits for IPv6") if value < 0: raise TypeError("Mask cannot be less than 0 bits") self._mask = value
jkloo/BatchY
batchy/cli.py
Python
mit
2,138
0.003274
#!/usr/bin/python import argparse from . import CLI from .utils import _list_files from .find import batchy_find from .update import batchy_update from .view import batchy_view def _batchy_find(args): return batchy_find(args.pattern, args.keys, args.replace, args.files) def _batchy_update(args): return ba...
iles = _list_files(args.files, args.dirs) return args
def main(args=None): args = _generate_args(args) return args.func(args)
santiago-salas-v/walas
basic_constants_from_the_properties_of_gases_and_liquids.py
Python
mit
10,361
0.002124
import os import re import locale locale.setlocale(locale.LC_ALL, '') # decimals according to locale out_file_name = './logs/output_basic_constants.csv' sep_char_for_csv = '|' out_file = open(out_file_name, mode='w') out_file_full_path = os.path.abspath(out_file_name) def str_list_to_np_array_str(param): retur...
[10] is not None else 0.0 for item in matches] # Debye table_indexes_of_comp_nos = [ no.index(comp_no) for comp_no in sel_component_numbers ] out_file.write('# ======================') out_file.write('\n') props = ['no', 'formula', 'name', 'cas_no', 'delHf0', 'delGf0', 'delHb', 'de...
prop in props: is_numeric_prop = not isinstance((globals()[prop])[0], str) out_file.write(prop) if is_numeric_prop: for comp_no in table_indexes_of_comp_nos: out_file.write(' | ' + locale.str((globals()[prop])[comp_no]) ) else: ...
153/wbs
admin.py
Python
cc0-1.0
4,183
0.005259
#/usr/bin/env python3 import webtools as wt import os, crypt, cgitb cgitb.enable() modes = {"0": "no mode", "1": "lock", "2": "sticky", "3": "stickylock", "4": "permasage" } settings = "./settings.txt" b_conf = [] cd = {} with open(settings, "r") as settings: setting...
{} t["ti"] = [] for th in t_list: th = th.split(" >< ") t["ti"].append(th[0]) t[th[0]] = th[1:] return t def load_thread(thr='0'): # print(b_conf[5] + thr) with open(b_conf[5] + thr, 'r') as thr: thr = thr.read().splitlines() for n, th in enumerate(thr): t...
None table = ["<table>"] table.append("<tr><td><td>Name<td>Date<td>Comment") print("<tr><th colspan='4'>", thr.pop(0)[0]) for n, t in enumerate(thr): t.pop(2) t = f"<tr><td>{n+1}.<td>" + "<td>".join(t) table.append(t) print("\n".join(table), "</table>") def tripcode(pw): ...
bijanebrahimi/pystatus
pystatus/libs/__init__.py
Python
gpl-3.0
331
0.003021
# from cryptography import * from salmon import MagicSig from crypt impo
rt strip_whitespaces, b64_to_num, b64_to_str, b64encode, b64decode, generate_rsa_key, export_rsa_key from activitystreams import salmon, salmon1, salmon2, salm
on3 from webfinger import WebfingerClient from convert import str_to_datetime, datetime_to_rfc3339
makerdao/keeper
pymaker/numeric.py
Python
agpl-3.0
14,935
0.003348
# This file is part of Maker Keeper Framework. # # Copyright (C) 2017-2018 reverendus # Copyright (C) 2018 bargst # # 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...
hmeticError def __abs__(self): return Wad(abs(self.value)) def __eq__(self, other): if isinstance(other, Wad): return self.value =
= other.value else: raise ArithmeticError def __hash__(self): return hash(self.value) def __lt__(self, other): if isinstance(other, Wad): return self.value < other.value else: raise ArithmeticError def __int__(self): return int(s...
joelthe1/web-scraping
scrape-website-example-1.py
Python
mit
3,431
0.01195
#!/usr/bin/python '''Scrape a website using urllib2 (A library for pinging URLs) and BeautifulSoup (A library for parsing HTML)''' from bs4 import BeautifulSoup import urllib2 import time import sys import socket start_time = time.time() #Open files rfile = open("input.csv","r").read().splitlines() wfile = open("tran...
) req.add_header("Host", "filesdownloader.com") # req.add_header("If-Modified-Since", "Thu, 30 Jan 2014 17:24:29 GMT") # req.add_header("Cache-Control", "max-age=0") # req.add_header("If-Modified-Since", "Fri, 31 Jan 2014 21:52:35 GMT") req.add_header("Cookie", "...
4faibrkcp5bm85; __unam=7639673-143e40de47e-4218148d-4; __utma=127728666.207454719.1391100551.1391208734.1391434591.6; __utmb=127728666.2.10.1391434591; __utmc=127728666; __utmz=127728666.1391197253.2.2.utmcsr=prx.centrump2p.com|utmccn=(referral)|utmcmd=referral|utmcct=/english/") page = urllib2.urlopen(req,...
w1ll1am23/home-assistant
homeassistant/components/modbus/cover.py
Python
apache-2.0
7,501
0.000533
"""Support for Modbus covers.""" from __future__ import annotations from datetime import timedelta from typing import Any from pymodbus.exceptions import ConnectionException, ModbusException from pymodbus.pdu import ExceptionResponse from homeassistant.components.cover import SUPPORT_CLOSE, SUPPORT_OPEN, CoverEntity...
rite_coil(self, value): """Write coil using the Modbus hub slave.""" try: self._hub.write_coil(self._slave,
self._coil, value) except ConnectionException: self._available = False return self._available = True
google-research/google-research
basisnet/personalization/centralized_emnist/data_processing.py
Python
apache-2.0
4,786
0.006686
# coding=utf-8 # Copyright 2022 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
t_dataset(dataset): cnt = 0 for _ in iter(dataset): cnt = cnt + 1 return int(cnt) def get_local_y_dist(client_dataset): dist =
np.zeros((1, NUM_EMNIST_CLASSES)) for x in client_dataset: y = x['label'].numpy() dist[y] += 1 return np.array(dist).reshape((1, -1)) / np.sum(dist) def parse_data(emnist_train, emnist_test, client_ids, cliend_encodings, with_dist=False): """P...
dapengchen123/code_v1
reid/loss/oim.py
Python
mit
1,727
0.000579
from __future__ import absolute_import import torch import torch.nn.functional as F from torch import nn, autograd class OIM(autograd.Function): def __init__(self, lut, momentum=0.5): super(OIM, self).__init__() self.lut = lut self.momentum = momentum def forward(self, inputs, target...
argets = self.saved_tensors grad_inputs = None if self.needs_input_grad[0]: grad_inputs = grad_outputs.mm(self.lut) for x, y in zip(inputs, targets): self.lut[y] = self.momentum * self.lut[y] + (1. - self.momentum) * x self.lut[y] /= self.lut[y].norm() ...
Module): def __init__(self, num_features, num_classes, scalar=1.0, momentum=0.5, weight=None, size_average=True): super(OIMLoss, self).__init__() self.num_features = num_features self.num_classes = num_classes self.momentum = momentum self.scalar = scalar ...
LungNoodle/lungsim
tests/pFUnit-3.2.9/bin/pFUnitParser.py
Python
apache-2.0
34,426
0.011735
#!/usr/bin/env python # For python 2.6-2.7 from __future__ import print_function from os.path import * import re # from parseBrackets import parseBrackets from parseDirectiveArgs import parseDirectiveArguments class MyError(Exception): def __init__(self, value): self.value = value def __str__(self)...
return m def action(self, m, line): options = re.match('\s*'+self.keyword+'\s*\\((.*)\\)\s*$', line, re.IGNORECASE) method = {} if options: npesOption = re.search('npes\s*=\s*\\[([0-9,\s]+)\\]', options.groups()[0], re.IGNORECASE) if npesOption: n...
lit(',')) method['npRequests'] = npes #ifdef is optional matchIfdef = re.match('.*ifdef\s*=\s*(\w+)', options.groups()[0], re.IGNORECASE) if matchIfdef: ifdef = matchIfdef.groups()[0] method['ifdef'] = ifdef matchIfndef =...
stwunsch/gnuradio
grc/core/Platform.py
Python
gpl-3.0
11,876
0.001347
""" Copyright 2008-2016 Free Software Foundation, Inc. This file is part of GNU Radio GNU Radio 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) any l...
self.connection_templates.clear() ParseXML.xml_failures.clear() # Try to parse and load blocks for xml_file in
self.iter_xml_files(): try: if xml_file.endswith("block_tree.xml"): self.load_category_tree_xml(xml_file) elif xml_file.endswith('domain.xml'): self.load_domain_xml(xml_file) else: self.load_block_xm...
chipsecintel/chipsec
source/tool/chipsec/cfg/__init__.py
Python
gpl-2.0
894
0.020134
#CHIPSEC: Platform Security Assessment Framework #Copyright (c) 2010-2016, Intel Corporation # #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; Version 2. # #This program is d
istributed 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 no...
information: #chipsec@intel.com # ## \defgroup config Platform Configuration # chipsec/cfg/\<platform\>.py - configuration for a specific \<platform\>
ArcherSys/ArcherSys
Lib/distutils/tests/test_archive_util.py
Python
mit
35,333
0.002723
<<<<<<< HEAD <<<<<<< HEAD # -*- coding: utf-8 -*- """Tests for distutils.archive_util.""" import unittest import os import sys import tarfile from os.path import splitdrive import warnings from distutils import archive_util from distutils.archive_util import (check_archive_formats, make_tarball, ...
# trying an uncompressed one base_name = os.path.join(tmpdir2, target_n
ame) old_dir = os.getcwd() os.chdir(tmpdir) try: make_tarball(splitdrive(base_name)[1], '.', compress=None) finally: os.chdir(old_dir) tarball = base_name + '.tar' self.assertTrue(os.path.exists(tarball)) def _tarinfo(self, path): tar ...
unibet/unbound-ec2
tests/unit/test_server.py
Python
isc
6,080
0.002138
from tests import unittest from tests import mock from unbound_ec2 import server from tests import attrs class TestServer(server.Server): HANDLE_FORWARD_RESULT = 'dummy_handle_forward' HANDLE_PASS_RESULT = True DNSMSG = mock.MagicMock() def handle_request(self, _id, event, qstate, qdata, request_type...
rate_event_new(self): id = 'bogus_id' event = attrs['MODULE_EVENT_NEW'] qstate = mock.MagicMock() qdata = mock.Mag
icMock() qstate.qinfo.qname_str = "fqdn.not-bogus.tld" self.assertTrue(self.srv.operate(id, event, qstate, qdata)) qstate.ext_state.__setitem__.assert_called_with(id, attrs['MODULE_WAIT_MODULE']) def test_operate_event_pass(self): id = 'bogus_id' event = attrs['MODULE_EVENT_...
waddedMeat/asteroids-ish
Asteroids/MovingObject.py
Python
mit
242
0
__aut
hor__ = 'jmoran' from Asteroids import Object class MovingObject(Object): def __init__(self, window, game, init_point, slope): Object.__init__(self, window, game)
self.point = init_point self.slope = slope
last-one/tools
caffe/result/celeba_multilabel_acc.py
Python
bsd-2-clause
857
0.002334
import os import numpy as np import sys label_file = open('/home/hypan/data/celebA/test.txt', 'r') lines = label_file.readlines() label_file.close() acc = np.zeros(40) cou = 0 for line in lines: info = li
ne.strip('\r\n').split() name = info[0].split('.')[0] gt_labels = info[1: ] feat_path = '/home/hypan/data/celebA/result/' + sys.argv[1] + '/test_feature/' + name + '.npy' if not os.path.exists(feat_path): print '{} has not predict feature.'.format(name) pd_labels = np.load(feat_path) cnt...
pd_label = 1 else: pd_label = -1 if gt_label == pd_label: acc[i] += 1 cou += 1 for i in range(40): print i, acc[i] * 1.0 / cou
beeftornado/sentry
src/sentry/models/projectkey.py
Python
bsd-3-clause
8,014
0.001497
from __future__ import absolute_import, print_function import petname import six import re from bitfield import BitField from uuid import uuid4 from django.conf import settings from django.core.urlresolvers import reverse from django.db import models from django.utils import timezone from django.utils.translation im...
elf.project.organization @property def dsn_private(self): return self.get_dsn(public=False) @property def dsn_public(self): return self.get_dsn(public=True) @property def csp_endpoint(sel
f): endpoint = self.get_endpoint() return "%s/api/%s/csp-report/?sentry_key=%s" % (endpoint, self.project_id, self.public_key) @property def security_endpoint(self): endpoint = self.get_endpoint() return "%s/api/%s/security/?sentry_key=%s" % (endpoint, self.project_id, self.pu...
eveliotc/gradleplease-workflow
common.py
Python
apache-2.0
1,475
0.013559
# -*- coding: utf-8 -*-
__author__ = 'eveliotc' __license__ = 'See LICENSE' import alfred from alfred import Item import sys from subprocess import Popen, PIPE def json_
to_obj(x): if isinstance(x, dict): return type('X', (), {k: json_to_obj(v) for k, v in x.iteritems()}) else: return x def join_query(dic): return ' '.join(dic) def le_result(r, exit = True): alfred.write(r) if exit: sys.exit() def xml_result(r, exit = True): if len(r) ...
Qwaz/solved-hacking-problem
SharifCTF/2016/RSA-Keygen/generate-key.py
Python
gpl-2.0
2,346
0.020887
from random import randrange import fractions def get_primes(n): numbers = set(range(n, 1, -1)) primes = [] while numbers: p = numbers.pop() primes.append(p) numbers.difference_update(set(range(p*2, n+1, p))) return primes def egcd(a, b): if a == 0: return (b, 0, 1) else: g, y, x =...
rimes = get_primes(443) primes.sort() del primes[0] #print primes pi = 1; for x in primes: pi *= x print "pi=%X" % pi while True: kp = randrange(1, 2**12) + 2**12 + 2**13 + 2**14 + \ 2**15 + 2**16 + 2**17 +
2**18 + 2**19 print "kp=%X" % kp tp = 0 while fractions.gcd(tp, pi) != 1: print "trying..." tp = randrange(1, 2**399); print "tp=%X" % tp p = kp * pi * 2**400 + tp print "p=%X" % p print "bitlength(p)=", len(bin(p))-2 if miller_rabin(p, 40) == True: break while True: kq = randrange(1, 2**12) + 2**12 ...
Crystal-SDS/dashboard
crystal_dashboard/dashboards/crystal/controllers/panel.py
Python
gpl-3.0
271
0
from django.utils.translation import
ugettext_lazy as _ from crystal_dashboard.dashboards.crystal import dashboard import horizon class Controllers(horizon.Panel): name = _("Controllers") slug = 'controllers' dashboard.CrystalController.regis
ter(Controllers)
XKNX/xknx
xknx/io/transport/ip_transport.py
Python
mit
3,449
0.00087
""" Abstract base for a specific IP transports (TCP or UDP). * It starts and stops a socket * It handles callbacks for incoming frame service types """ from __future__ import annotations from abc import ABC, abstractmethod import asyncio import logging from typing import Callable, cast from xknx.exceptions import Co...
class Callback: """Callback class for handling callbacks for different 'KNX service types' of received packets.""" def __init__( self, callback: TransportCallbackType, service_types: list[KNXIPServiceType] | None = None, ): """Initialize Call...
ce_type: KNXIPServiceType) -> bool: """Test if callback is listening for given service type.""" return not self.service_types or service_type in self.service_types def register_callback( self, callback: TransportCallbackType, service_types: list[KNXIPServiceType] | N...
meltwater/proxymatic
src/proxymatic/services.py
Python
mit
5,559
0.002159
import re from copy import copy from random import randint class Server(object): def __init__(self, ip, port, hostname): self.ip = ip self.port = port self.hostname = hostname self.weight = 500 self.maxconn = None def __cmp__(self, other): if not isinstance(othe...
hen they're added for i in range(len(self.slots)): if not self.slots[i]: self.slots[i] = server return # Not present in list, just insert randomly self.slots.insert(randint(0, len(self.slots)), server) def _remove(self, server): self.serv...
for i in range(len(self.slots)): if self.slots[i] == server: del self.slots[i] return raise KeyError(str(server))
domchoi/fluentPython
dataModel/vector.py
Python
gpl-3.0
743
0.014805
''' Created on Mar 28, 2017 @author: J001684 ''' from math import hypot class Vector: ''' classdocs ''' def __init__(self, x=0, y=0): ''' Constructor ''' self.x = x self.y = y def _repr_(self): return 'Vector({x}, {y...
return Vector(self.x * scalar, self.y * sc
alar) v1 = Vector(2, 4) print v1
serbyy/MozDef
alerts/unauth_ssh_pyes.py
Python
mpl-2.0
2,867
0.002093
#!/usr/bin/env python # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # Copyright (c) 2015 Mozilla Corporation # # Contributors: # Aaron Meihm <ameihm@mozilla.com> fro...
egexp> # user username # skiphosts 1.2.3.4 2.3.4.5 class AlertUnauthSSH(AlertTask): def main(self): date_timedelta = dict(minutes=30) self.config_file = './unauth_ssh_pyes.conf' self.config = None self.initConfiguration() must = [ pyes.TermFilter('_type', 'eve...
TermFilter('details.program', 'sshd'), pyes.QueryFilter(pyes.QueryStringQuery('details.hostname: /{}/'.format(self.config.hostfilter))), pyes.QueryFilter(pyes.MatchQuery('summary', 'Accepted publickey {}'.format(self.config.user), operator='and')) ] must_not = [] for x in...
tcpcloud/contrail-controller
src/nodemgr/analytics_nodemgr/analytics_event_manager.py
Python
apache-2.0
2,984
0.008378
# # Copyright (c) 2015 Juniper Networks, Inc. All rights reserved. # from gevent import monkey monkey.patch_all() import os import sys import socket import subprocess import json import time import datetime import platform import gevent import ConfigParser from nodemgr.common.event_manager import EventManager from p...
alytics.rules" json_file = open(self.rule_file) self.rules_data = json.load(json_file) def send_process_state_db(self, group_names): self.send_process_state_db_base( group_names, ProcessInfo) def send_nodemgr_process_status(self): self.send_nodemgr_process_status_b
ase( ProcessStateNames, ProcessState, ProcessStatus) def get_node_third_party_process_dict(self): return self.third_party_process_dict def get_process_state(self, fail_status_bits): return self.get_process_state_base( fail_status_bits, ProcessStateNames, ProcessState)
ktan2020/legacy-automation
win/Lib/distutils/command/build_clib.py
Python
mit
8,340
0.001439
"""distutils.command.build_clib Implements the Distutils 'build_clib' command, to build a C/C++ library that is included in the module distribution and needed by an extension module.""" __revision__ = "$Id$" # XXX this module has *lots* of code ripped-off quite transparently from # build_ext.py -- not sur...
"a list of source filenames") % lib_name sources = list(sources) log.info("building '%s' library", lib_name) # First, compile the source code to object files in the library # directory. (This should probably change to putting object # files i...
d_info.get('include_dirs') objects = self.compiler.compile(sources, output_dir=self.build_temp, macros=macros, include_dirs=include_dirs, ...
pandastream/panda_client_python
panda/models.py
Python
mit
5,728
0.005237
import json import logging from functools import wraps logger = logging.getLogger(__name__) class PandaError(Exception): pass def error_check(func): @wraps(func) def check(*args, **kwargs): try: res = func(*args, **kwargs) if "error" in res: logger.error(re...
Cloud(UpdatablePandaModel): path = "/clouds" class Encoding(PandaModel): path = "/encodings" def video(self): return SingleRetriever(self.panda, Video, "/videos/{0}".format(self["video_id"])).get() def profile(self): key = self["profile_name"] or self["profile_id"] return Sing...
gs/{0}/cancel.json".format(self["id"])).post() def retry(self): return SingleRetriever(self.panda, PandaDict, "/encodings/{0}/retry.json".format(self["id"])).post() class Profile(UpdatablePandaModel): path = "/profiles" class Notifications(UpdatablePandaModel): path = "/notifications" @error...
caseyrollins/osf.io
addons/wiki/migrations/0010_migrate_node_wiki_pages.py
Python
apache-2.0
23,077
0.003467
# -*- coding: utf-8 -*- # Generated by Django 1.11.9 on 2018-02-22 20:39 from __future__ import unicode_literals import time import logging import progressbar from django.db import connection, migrations from django.db.models import Q from django.contrib.contenttypes.models import ContentType from bulk_update.helper i...
schema): """ Reverses NodeWikiPage migration. Repoints guids back to each NodeWikiPage, repoints comment_targets, comments_viewed_timestamps, and deletes all WikiVersions and WikiPages """ NodeWikiPage = state.get_model('addons_wiki', 'nodewikipage') Abs
tractNode = state.get_model('osf', 'AbstractNode') nwp_content_type_id = ContentType.objects.get_for_model(NodeWikiPage).id nodes = AbstractNode.objects.exclude(wiki_pages_versions={}) progress_bar = progressbar.ProgressBar(maxval=nodes.count() or 100).start() for i, node in enumerate(nodes, 1): ...
eli261/jumpserver
apps/audits/urls/api_urls.py
Python
gpl-2.0
319
0
# ~*~ coding: utf-8 ~*~ from __future__ import unicode_literals from django.conf.urls import url from rest_framework.routers import DefaultRouter from .. import api
app_name = "audits" router = DefaultRouter()
router.register(r'ftp-log', api.FTPLogViewSet, 'ftp-log') urlpatterns = [ ] urlpatterns += router.urls
keithhackbarth/clowder_python_client
tests.py
Python
gpl-2.0
6,224
0
# -*- coding: utf-8 -*- import datetime import unittest import clowder import mock # import psutil class BaseClowderTestCase(unittest.TestCase): """Base class for all clowder test cases.""" def assert_send_contains_data(self, send_mock, key, value): """Assert that the given send mock was called wit...
rt_called_once() kwargs = post.call_args[1] self.assertIn('data', kwargs) self.assertEqual(kwargs['data'], self.fixture) def test_should_raise_error_if_invalid_data_given(self): self.assertRaisesRegexp( Va
lueError, "Invalid data keys 'herp'", clowder._send, {'name': 'Test', 'herp': 123} ) def test_should_raise_error_if_missing_keys(self): self.assertRaisesRegexp( ValueError, "Missing keys 'name'", clowder._send, {'va...
jctoledo/ligandneighbours
ligandneighbours.py
Python
mit
10,769
0.023865
# Copyright (c) 2013 Jose Cruz-Toledo # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, dis...
r = flags.output_file radius = flags.radius #fetch a list of all the pdb files in the input directory filepaths = fetchPdbFilePaths(loca
l_dir) #fetch the ligand list ligands = fetchLigandList(pdb_to_ligand_list_url) for fp in filepaths: #get the file name and extension of the pdb file fn, fe = os.path.splitext(fp) pdbId = fn.rsplit('/')[-1] # dict of ligands (PDB.Residue) to residues (PDB.Residue) ln = findNeighbours(fp, ligands, radius)...
cigroup-ol/metaopt
metaopt/plugin/visualization/best_fitness.py
Python
bsd-3-clause
1,969
0
# -*- coding: utf-8 -*- # Future from __future__ import absolute_import, division, print_function, \ unicode_literals, with_statement # Standard Library from datetime import datetime # Third Party import matplotlib.pyplot as plt from matplotlib import cm from mpl_toolkits.mplot3d import Axes3D # Load 3d plots ca...
ax.set_ylabel(self.get_y_label()) ax.plot(self.best_fitnesses) plt.show() def show_fitness_time_plot(self): """Show a fitness--time plot""" fig = plt.figure() ax = fig.add_subplot(111) ax.set_xlabel("Time") ax.set_ylabel(self.get_y_la
bel()) ax.plot(self.timestamps, self.best_fitnesses) plt.show() def get_y_label(self): return self.return_spec.return_values[0]["name"]
st3f4n/latex-sanitizer
sanitize.py
Python
gpl-3.0
1,706
0
#!/usr/bin/env python3 import fileinput import string import sys DELETE = '' REPLACE = {'“': '``', '”': '\'\'', '’': '\'', '\\': '\\textbackslash ', '*': '\\textasteriskcentered ', '_': '\\_', '#': '\\#', '$': '\\$', '%': '\\%', ...
'}': '\\}', '&': '\\&', '…': '\\dots ', '~': '\\~{}', '^': '\\^{}'} def main(): all_deleted, all_replaced, all_specials = set(), set(), set() for line in fileinput.input(): line, deleted = delete(line, DELETE) all_deleted.update(deleted) line...
sys.stdout.write(line) print('Deleted characters: {}'.format(' '.join(sorted(all_deleted))), file=sys.stderr) print('Replaced characters: {}'.format(' '.join(sorted(all_replaced))), file=sys.stderr) prtxt = 'Remaining special characters: {}' print(prtxt.format(' '.join(sorted(all_...
MOOCworkbench/MOOCworkbench
marketplace/migrations/0013_auto_20170605_1359.py
Python
mit
601
0.001664
# -*- coding: utf-8 -*- # Generated by Django 1.11.2 on 2017-06-05 13:59 f
rom __future__ import unicode_literals import django.core.validators from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('marketplace', '0012_auto_20170604_1335'), ] operations = [ migrations.AlterField( model_name='package', ...
rue, validators=[django.core.validators.RegexValidator('^[a-z]*$', 'Only lowercase letters are allowed.')]), ), ]
vegastrike/Assets-Production
modules/XGUI.py
Python
gpl-2.0
2,379
0.008407
import Base import VS import GUI import XGUITypes import XGUIDebug XGUIRootSingleton = None XGUIPythonScriptAPISingleton = None """----------------------------------------------------------------""" """ """ """ XGUIRoot - root management interface for th...
context) return context """----------------------------------------------------------------""" """ """ """ XGUIPythonScriptAPI - through this class, all PythonScript """ """ API calls are routed. """ ""...
-----------------------------------------""" class XGUIPythonScriptAPI: def __init__(self,layout,room): self.layout = layout self.room = room """----------------------------------------------------------------""" """ """ """ XGUI gl...
HBPNeurorobotics/nest-simulator
pynest/nest/tests/test_quantal_stp_synapse.py
Python
gpl-2.0
4,353
0
# -*- coding: utf-8 -*- # # test_quantal_stp_synapse.py # # This file is part of NEST. # # Copyright (C) 2004 The NEST Initiative # # NEST 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 th...
TestCase): """Compare quantal_stp_synapse with its deterministic equivalent.""" def test_QuantalST
PSynapse(self): """Compare quantal_stp_synapse with its deterministic equivalent""" nest.ResetKernel() nest.set_verbosity(100) n_syn = 12 # number of synapses in a connection n_trials = 50 # number of measurement trials # parameter set for facilitation fac_para...
andydandy74/ClockworkForDynamo
nodes/2.x/python/FamilyInstance.FlipFromToRoom.py
Python
mit
612
0.011438
import clr clr.AddReference('RevitAPI') from Autodesk.Revit.DB
import * clr.AddReference("RevitServices") import RevitServices from RevitServices.Persistence import DocumentManager from RevitServices.Transactions import TransactionManager doc = DocumentManager.Instance.CurrentDBDocument faminstances = UnwrapElement(IN[0]) booleans = [] TransactionManager.Instance.EnsureInTrans...
actionManager.Instance.TransactionTaskDone() OUT = (faminstances,booleans)
antoinecarme/pyaf
tests/periodicities/Minute/Cycle_Minute_1600_T_7.py
Python
bsd-3-clause
82
0.04878
import tests.perio
dicities.p
eriod_test as per per.buildModel((7 , 'T' , 1600));
LBenzahia/cltk
cltk/lemmatize/french/french.py
Python
mit
2,931
0.006188
import re """Rules are based on Brunot & Bruneau (1949). """ estre_replace = [('^sereient$|^fussions$|^fussiens$|^sereies$|^sereiet$|^serïens$|^seriiez$|^fussiez$|^fussent$|^ierent$|^fustes$|^furent$|^ierent$|^sereie$|^seroie$|^sereit$|^seiens$|^seient$|^fusses$|^fussez$|^estant$|^seiens$|^somes$|^estes$|^ieres$|^ier...
|^avreie$
|' '^avrïez$|^eüsses$|^eüssez$|^avons$|^eümes$|^orent$|^avrai$|' '^avras$|^avrez$|^aiens$|^ayons$|^aient$|^eüsse$|^avez$|^avra$|' '^arai$|^aies$|^aiet$|^aiez$|^ayez$|^eüst$|^ont$|^eüs$|' '^oüs$|^óut$|^oiz$|^aie$|^ait$|^ai$|^as$|^at$|^oi$|' '^ot$|^oü$|^eü$|^a$', 'avoir')] a...
hgdeoro/GarnishMyPic
gmp/dnd.py
Python
gpl-3.0
4,062
0.003693
# -*- coding: utf-8 -*- #=======================
======================================================== # # Copyright 2013 Horacio Guillermo de Oro <hgdeoro@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either vers
ion 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details...
OpusVL/odoo
addons/account/wizard/account_change_currency.py
Python
agpl-3.0
3,683
0.003801
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the G...
currency_id.id != new_currency: old_rate =
invoice.currency_id.rate if old_rate <= 0: raise osv.except_osv(_('Error!'), _('Current currency is not configured properly.')) new_price = (line.price_unit / old_rate ) * rate obj_inv_line.write(cr, uid, [line.id], {'price_unit': new_price}) obj_...
teddywing/pubnub-python
python-tornado/examples/here-now.py
Python
mit
1,031
0.007759
## www.pubnub.com - PubNub Real-time push service in the cloud. # coding=utf8 ## PubNub Real-time Push APIs and Notifications Framework ## Copyright (c) 2010 Stephen Blum ## http://www.pubnub.com/ import sys from pubnub import PubnubTornado as Pubnub publish_key = len(sys.argv) > 1 and sys.argv[1] or 'demo' subscri...
_on = len(sys.argv) > 5 and bo
ol(sys.argv[5]) or False ## ----------------------------------------------------------------------- ## Initiate Pubnub State ## ----------------------------------------------------------------------- pubnub = Pubnub(publish_key=publish_key, subscribe_key=subscribe_key, secret_key=secret_key, cipher_key...
metabrainz/acousticbrainz-server
webserver/utils.py
Python
gpl-2.0
860
0.002326
import string import random import webserver.views.api.exceptions def generate_strin
g(length): """Generates random s
tring with a specified length.""" return ''.join([random.SystemRandom().choice( string.ascii_letters + string.digits ) for _ in range(length)]) def reformat_date(value, fmt="%b %d, %Y"): return value.strftime(fmt) def reformat_datetime(value, fmt="%b %d, %Y, %H:%M %Z"): return value.strftime...
rsignell-usgs/notebook
HOPS/hops_velocity.py
Python
mit
830
0.03253
# coding: utf-8 # ## Plot velocity from non-CF HOPS dataset # In[5]: get_ipython().magic(u'matplotlib inline') import netCDF4 import matplotlib.pyplot as plt # In[6]: url='http://geoport.whoi.edu/thredds/dodsC/usgs/data2/
rsignell/gdrive/nsf-alpha/Data/MIT_MSEAS/MSEAS_Tides_20160317/mseas_tides_2015071612_2015081612_01h.nc' # In[8]: nc = netCDF4.Dataset(url) # In[9]: ncv = nc.variables # In[ ]: # extract lon,lat variables from vgrid2 variable lon = ncv['vgrid2'][:,:,0] lat = ncv['vgrid2'][:,:,1] # In[20]: # extract u,v varia...
vbaro'][itime,:,:,0] v = ncv['vbaro'][itime,:,:,1] # In[30]: n=10 fig = plt.figure(figsize=(12,8)) plt.quiver(lon[::n,::n],lat[::n,::n],u[::n,::n],v[::n,::n]) #plt.axis([-70.6,-70.4,41.2,41.4]) # In[ ]: # In[ ]: # In[ ]:
npapier/sbf
src/sbfDoxygen.py
Python
gpl-3.0
6,169
0.041984
# SConsBuildFramework - Copyright (C) 2013, Nicolas Papier. # Distributed under the terms of the GNU General Public License (GPL) # as published by the Free Software Foundation. # Author Nicolas Papier import os from src.sbfRsync import createRsyncAction from src.SConsBuildFramework import stringFormatter ...
x_build' ) # target dox env.
Alias( 'dox', 'dox_install' ) if env['publishOn'] : rsyncAction = createRsyncAction( env, 'doc_%s_%s' % (sbf.myProject, sbf.myVersion), Dir(os.path.join(doxBuildPath, 'html')), 'dox' ) env.Depends( rsyncAction, 'dox_install' ) # target dox_clean env.Alias( 'dox_clean', 'dox' ) env.Clean( 'dox_clea...
jrmi/pypeman
pypeman/msgstore.py
Python
apache-2.0
9,722
0.00288
import os import re import asyncio import logging from collections import OrderedDict from pypeman.message import Message from pypeman.errors import PypemanConfigError logger = logging.getLogger("pypeman.store") DATE_FORMAT = '%Y%m%d_%H%M' class MessageStoreFactory(): """ Message store factory class can gener...
if path is None: raise PypemanConfigError('file message store requires a path') self.base_path = path def get_store(se
lf, store_id): return FileMessageStore(self.base_path, store_id) class FileMessageStore(MessageStore): """ Store a file in `<base_path>/<store_id>/<month>/<day>/` hierachy.""" # TODO file access should be done in another thread. Waiting for file backend. def __init__(self, path, store_id): ...
payet-s/pyrser
pyrser/type_system/val.py
Python
gpl-3.0
1,017
0
# val for type checking (literal or ENUM style) from pyrser import fmt from pyrser.type_system.signature import * from pyrser.type_system.type_name import * class Val(Signature): """ Describe a value signature for the language """ nvalues = 0 valuniq = dict() def __init__(self, value, tret: s...
idx = Val.valuniq[k] super().__init__('$' + str(idx)) def internal_name(self): """ Return the unique internal name """ unq = super().internal
_name() if self.tret is not None: unq += "_" + self.tret return unq
aqfaridi/Code-Online-Judge
web/env/Main1145/Main1145.py
Python
mit
90
0.011111
while(
True):
n = input() if(n == 42): break else: print n
imh/gnss-analysis
gnss_analysis/mk_sdiffs.py
Python
lgpl-3.0
4,406
0.006809
import pandas as pd import numpy as np from swiftnav.ephemeris import * from swiftnav.single_diff import SingleDiff from swiftnav.gpstime import * def construct_pyobj_eph(eph): return Ephemeris( eph.tgd, eph.crs, eph.crc, eph.cuc, eph.cus, eph.cic, eph.cis, eph.dn, ep...
p] if earlier_ephs.shape[0] >= 1: eph = earlier_ephs.ix[-1].ephemeris else: eph = fst_eph gpstime = datetime2gpst(timestamp) p
os, vel, clock_err, clock_rate_err = calc_sat_pos(eph, gpstime) return pd.Series([c1, l1, np.nan, pos[0], pos[1], pos[2], vel[0], vel[1], vel[2], snr, int(sat[1:])], index=['C1', 'L1', 'D1', 'sat_pos_x', 'sat_pos_y', 'sat_pos_z', 'sat_vel_x', ...
snsokolov/contests
codeforces/556A_zeroes.py
Python
unlicense
2,674
0.000748
#!/usr/bin/env python3 # 556A_zeroes.py - Codeforces.com/problemset/problem/556/A Zeroes quiz by Sergey 2015 # Standard modules import unittest import sys import re # Additional modules ############################################################################### # Zeroes Class ###################################...
apper """ if it: return next(it) else: return input() # Getting string inputs num = int(uinput()) ints = [int(n) for n in uinput()] return ints def calculate(test_inputs=None): """ Base class calculate method wrapper """ return Zeroes(get_inputs(test_i...
##### # Unit Tests ############################################################################### class unitTests(unittest.TestCase): def test_sample_tests(self): """ Quiz sample tests. Add \n to separate lines """ self.assertEqual(calculate("4\n1100"), "0") self.assertEqual(calculate("5...
sqaxomonophonen/worldmapsvg
svg/path/path.py
Python
cc0-1.0
15,350
0.001303
from __future__ import division from math import sqrt, cos, sin, acos, degrees, radians, log from collections import MutableSequence # This file contains classes for the different types of SVG path segments as # well as a Path object that contains a sequence of path segments. MIN_DEPTH = 5 ERROR = 1e-12 def segmen...
rol1 = control1 self.control2 = control2 self.end = end def __repr__(self): return 'CubicBezier(start=%s, control1=%s, control2=%s, end=%s)' % ( self.start, self.control1, self.control2, self.end) def __eq__(self, other): if not isinstance(other, CubicBezier): ...
trol1 and self.control2 == other.control2 def __ne__(self, other): if not isinstance(other, CubicBezier): return NotImplemented return not self == other def is_smooth_from(self, previous): """Checks if this segment would be a smooth segment following the previous""" ...
kk6/onedraw
onedraw/tags/models.py
Python
mit
345
0
# -*- coding: utf-8 -*- from django.db import m
odels from tweets.models import Tweet class Tag(models.Model): name = models.CharField(max_length=255, unique=True, db_index=True) is_hash
tag = models.BooleanField(default=False) tweets = models.ManyToManyField(Tweet, related_name='tags') class Meta: db_table = 'tags'
shravan97/WordHunter
ImageSearch/image_searcher.py
Python
mit
775
0.023226
""" A simple module to get the links of first 10 images d
isplayed on google image search """ from googleapiclient.discovery import build class GoogleImageSearch: def __init__(self,api_key,cse_id): self.
my_api_key = api_key self.my_cse_id= cse_id def search(self,search_term,**kwargs): google_service = build("customsearch", "v1", developerKey=self.my_api_key) result = google_service.cse().list(q=search_term, cx=self.my_cse_id, **kwargs).execute() ...
urashima9616/Leetcode_Python
Leet201_BitwiswAndRange.py
Python
gpl-3.0
1,001
0.006993
""" Given a range [m, n] where 0 <= m <= n <= 2147483647, re
turn the bitwise AND of all numbers in this range, inclusive. For example, given the range [5, 7], you should return 4. Credits: Special thanks to @amrsaqr for adding this problem and creating all test cases. """ class Solution(object): def rangeBitwiseAnd(self, m, n): """ :type m: int :...
min_i = m bits = [0 for _ in xrange(32)] for i in xrange(32): #take the i-th pos of max and min a = max_i & 1 b = min_i & 1 max_i >>= 1 min_i >>= 1 if a == 0 or b == 0: bits[i] = 0 else: ...
henriquesouza/toply
src/objects/GetText.py
Python
gpl-3.0
6,417
0.009512
# -*- coding: utf-8 -*- class GetText(): _file_path = None _body_list = None _target = None def __init__(self, file_path): #self._file_path = open(file_path, "r+").read().replace("<br","\n<br") self._file_path = file_path.replace("<br />", "<br />\n") #self._file_path = (se...
d("<br") > -1 and since_last_br[i+3].find("<br") > -1 and self.br_check(since_last_br[i]) == False and self.br_check(since_last_br[i+1]) == False and self.br_check(since_last_br[i+2]) == False and self.br_check(since_last_br[i+3]) == False ...
se: i = i +1 if (since_last_br[i].find("<br") > -1 and i+3< len(since_last_br) and self.br_check(since_last_br[i+3]) == False): #print("i + 1 contains <br>") #print(since_last_br[i]) del since_last_br[0:i] # print (since_last_b...
munkireport/munkireport-php
public/assets/client_installer/payload/usr/local/munkireport/munkilib/reportcommon.py
Python
mit
17,507
0.000914
#!/usr/local/munkireport/munkireport-python2 # encoding: utf-8 from . import display from . import prefs from . import constants from . import FoundationPlist from munkilib.purl import Purl from munkilib.phpserialize import * import subprocess import pwd import sys import hashlib import platform from urllib import ur...
sctl", "-n", "kern.boottime"] proc = subproces
s.Popen( cmd, shell=False, bufsize=-1, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) (output, unused_error) = proc.communicate() sec = int(re.sub(".*sec = (\d+),.*", "\\1", output)) up = int(time.time() - sec) return up if up...
Lisergishnu/LTXKit
uStripDesign.py
Python
gpl-2.0
5,581
0.03064
# -*- coding: utf-8 -*- # @Author: Marco Benzi <marco.benzi@alumnos.usm.cl> # @Date: 2015-06-07 19:44:12 # @Last Modified 2015-06-09 # @Last Modified time: 2015-06-09 16:07:05 # ========================================================================== # This program is free software: you can redistribute it and/or...
HANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Pub
lic 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/>. # ========================================================================== import math """ Speed of light constant """ c = 3E8 """ Vacuu...
clbarnes/hiveplotter
test/simple_tests.py
Python
bsd-3-clause
882
0
from hiveplotter import HivePlot
from networkx import nx import random from unittest import TestCase SEED = 1 NTYPES = ['A', 'B', 'C'] class SimpleCase(TestCase): def make_graph(self): G = nx.fast_gnp_random_graph(30, 0.2, seed=SEED) for node, data in G.nodes_iter(data=True): data['ntype'] = random.choice(NTYPES) ...
r(data=True): data['weight'] = random.random() return G def test_simple(self): G = self.make_graph() H = HivePlot(G, node_class_attribute='ntype') H.draw() H.save_plot('./output/main.pdf') def test_dump_cfg(self): G = self.make_graph() H = H...
macarthur-lab/xbrowse
xbrowse_server/base/views/account_views.py
Python
agpl-3.0
4,556
0.004829
import json import logging from django.contrib.auth.models import User from django.contrib.auth import login, authenticate, logout from django.contrib.auth.decorators import login_required from django.shortcuts import render, redirect, get_object_or_404 from django.http import HttpResponse from django.core.mail import...
r('xbrowse JS error', extra={'request': request}) return HttpResponse(json.dumps({'success': True})) @log_request('home') def home(request): if request.user.is_anonymous(): return landing_page(request)
projects = get_projects_for_user(request.user) return render(request, 'home.html', { 'user': request.user, 'projects': projects, 'new_page_url': '/dashboard', }) @log_request('login') def login_view(request): logout(request) next = request.GET.get('next') if reques...
loehnertz/rattlesnake
rattlesnake.py
Python
mit
15,227
0.001773
import sys import math import wave import struct import curses import pyaudio import numpy as np import matplotlib.pyplot as plt # 'curses' configuration stdscr = curses.initscr() stdscr.nodelay(True) curses.noecho() curses.cbreak() # PyAudio object variable pa = pyaudio.PyAudio() # The mode the user chose with a sc...
# Read in a chunk of live audio on each iteration original = stream.read(CHUNK) # Invert the original audio
inverted = invert(original) # Play back the inverted audio stream.write(inverted, CHUNK) # On every nth iteration append the difference between the level of the source audio and the inverted one if i % NTH_ITERATION == 0: # Clear the terminal before...
ddurieux/alignak
alignak/sorteddict.py
Python
agpl-3.0
6,690
0.000149
#!/usr/bin/env python # -*- coding: utf-8 -*- # # sorteddict.py # Sorted dictionary (implementation for Python 2.x) # # Copyright (c) 2010 Jan Kaliszewski (zuo) # # The MIT License: # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (th...
ict's one, but: * methods: __repr__(), __str__(), __iter__(), iterkeys(), itervalues(), iteritems(), keys(), values(), items() and popitem() -- return results taking into consideration sorted keys order;
* new methods: largest_key(), largest_item(), smallest_key(), smallest_item() added. ''' def __init__(self, *args, **kwargs): '''Like with the ordinary dict: from a mapping, from an iterable of (key, value) pairs, or from keyword arguments.''' dict.__init__(self, *args, **kwar...
cliftonmcintosh/openstates
openstates/nh/__init__.py
Python
gpl-3.0
3,210
0.005296
import lxml.html from .bills import NHBillScraper from .legislators import NHLegislatorScraper from .committees import NHCommitteeScraper metadata = { 'abbreviation': 'nh', 'name': 'New Hampshire', 'capitol_timezone': 'America/New_York', 'legislature_name': 'New Hampshire General Court', 'legislatu...
start_year': 2017, 'end_year': 2018} ], 'session_details': { '2011': {'display_name': '2011 Regular Session', 'zip_url': 'http://gencourt.state.nh.us/downloads/2011%20Session%20Bill%20Status%20Tables.zip', '_scraped_name': '2011 Sessio
n', }, '2012': {'display_name': '2012 Regular Session', 'zip_url': 'http://gencourt.state.nh.us/downloads/2012%20Session%20Bill%20Status%20Tables.zip', '_scraped_name': '2012 Session', }, '2013': {'display_name': '2013 Regular Session', ...
radiasoft/radtrack
radtrack/plot/contourf_demo.py
Python
apache-2.0
3,308
0.009069
#!/usr/bin/env python import numpy as np import matplotlib.pyplot as plt origin = 'lower' #origin = 'upper' delta = 0.025 x = y = np.arange(-3.0, 3.01, delta) X, Y = np.meshgrid(x, y) Z1 = plt.mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) Z2 = plt.mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1) Z = 10 * (Z1 - Z2) nr,...
filled contours. Alternatively, # We could pass in additional levels to provide extra resolution, # or leave out the l
evels kwarg to use all of the original levels. CS2 = plt.contour(CS, levels=CS.levels[::2], colors = 'r', origin=origin, hold='on') plt.title('Nonsense (3 masked regions)') plt.xlabel('word length anomaly') plt.ylabel('sentence length anomaly') ...
bkolli/swift
test/unit/proxy/test_sysmeta.py
Python
apache-2.0
16,039
0
# Copyright (c) 2010-2012 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except
in compliance with the Licen
se. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See t...
Tayamarn/socorro
socorro/cron/jobs/ftpscraper.py
Python
mpl-2.0
19,943
0.000301
from __future__ import print_function import datetime import sys import re import os import json import urlparse import fnmatch import functools import mock import lxml.html import requests from requests.adapters import HTTPAdapter from configman import Namespace from configman.converters import class_converter, str...
plit('.en-US.') elif '.multi.' in url: pv, platform = re.sub('\.json$', '', basename).split('.multi.') else: continue version = pv.split('-')[-1
] repository = [] for field in dirname.split('-'): # Skip until something is not a digit and once we've # appended at least one, keep adding. if not field.isdigit() or repository: repository.append(field) repository...
nttks/edx-platform
biz/djangoapps/gx_org_group/tests/test_views.py
Python
agpl-3.0
34,785
0.003823
import json from mock import patch from django.core.urlresolvers import reverse from django.core.files.uploadedfile import SimpleUploadedFile from student.tests.factories import UserFactory from biz.djangoapps.ga_invitation.tests.test_views import BizContractTestBase from biz.djangoapps.ga_manager.tests.factori...
ManagerFactory from biz.djangoapps.gx_org_group.models import Group, Right, Parent, Child from biz.djangoapps.gx_org
_group.tests.factories import GroupUtil, GroupFactory from biz.djangoapps.gx_member.tests.factories import MemberFactory from biz.djangoapps.gx_member.models import Member class OrgGroupListViewTest(BizContractTestBase): """ Test Class for gx_org_group """ def setUp(self): super(BizCon...
Debaq/Triada
CP_Marcha/TUG.py
Python
gpl-3.0
8,883
0.014643
#!/usr/bin/env python # -*- coding: utf-8 -*- import serial import time import serial.tools.list_ports #import json import matplotlib.pyplot as plt import matplotlib.animation as animation from matplotlib import style from matplotlib.gridspec import GridSpec #from mpl_toolkits.mplot3d import Axes3D #import threading i...
= 'green' resIMC = 'Peso Normal' elif IMC >=25 and IMC <=29.9: colorIMC = 'yellow' resIMC = 'Sobrepeso' elif IMC >=30 and IMC <=34.9: colorIMC
= 'magenta' resIMC = 'Obesidad tipo I' elif IMC >=35 and IMC <=39.9: colorIMC = 'red' resIMC = 'Obesidad tipo II' elif IMC >40: colorIMC = 'red' resIMC = 'Obesidad tipo II' print(("IMC = ",colored(IMC,colorIMC,attrs=['bold']), '-', colored(resIMC,colorIMC,attrs=['bol...
thisisshi/cloud-custodian
tools/c7n_azure/tests_azure/tests_resources/test_iot_hub.py
Python
apache-2.0
921
0
# Copyright The Cloud Custodian Authors. # SPDX-License-Identifier: Apache-2.0 from ..azure_common import BaseTest, arm_template class IoTHubTest(BaseTest): def setUp(self): super(IoTHubTest, self).setUp() def test_iot_hub_schema_validate(self): with self.
sign_out_patch(): p = self.load_policy({ 'name': 'test-iot-hub-compliance', 'resource': 'azure.iothub' }, validate=True) self.assertTrue(p) @arm_template('iothub.json
') def test_find_by_name(self): p = self.load_policy({ 'name': 'test-azure-iothub', 'resource': 'azure.iothub', 'filters': [ {'type': 'value', 'key': 'name', 'op': 'glob', 'value': 'cctest-iothub*'}], ...
kavasoglu/ocl_web
ocl_web/libs/ocl/concept_class.py
Python
mpl-2.0
229
0
# from ..ocl import
ApiResource # class ConceptClass(ApiResource): # def __init__(self): # super(ConceptClass, self).__init__() # self.names = [] # self.descriptions = [] # se
lf.sources = []
bleepbloop/Pivy
scons/scons-local-1.2.0.d20090919/SCons/Platform/hpux.py
Python
isc
1,763
0.002836
"""engine.SCons.Platform.hpux Platform-specific initialization for HP-UX systems. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Platform.Platform() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 200...
opies 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 PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS B
E # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Platform/hpux.py 4369 2009/09/19 15:58:29 scons" import posix def gen...
codenote/chromium-test
tools/telemetry/telemetry/page/page_test_runner.py
Python
bsd-3-clause
2,691
0.010777
# Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import logging import os import sys from telemetry.core import browser_finder from telemetry.core import browser_options from telemetry.page import page_...
ssible_browser, test, results) print '%i pages succeed\n' % len(results.page_successes) if len(results.page_failures): logging.warning('Failed pages: %s', '\n'.join( [failure['page'].url for failure in results.page_failures])) if len(
results.skipped_pages): logging.warning('Skipped pages: %s', '\n'.join( [skipped['page'].url for skipped in results.skipped_pages])) return min(255, len(results.page_failures))
privateip/ansible
lib/ansible/plugins/doc_fragments/shell_windows.py
Python
gpl-3.0
1,460
0.002055
# Copyright (c) 2019 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 class ModuleDocFragment(object): # Windows shell documentation fragment # FIXME: set_module...
- name: ansible_a
sync_dir version_added: '2.8' remote_tmp: description: - Temporary directory to use on targets when copying files to the host. default: '%TEMP%' ini: - section: powershell key: remote_tmp vars: - name: ansible_remote_tmp set_module_language: description: - Controls if w...
deepmind/open_spiel
open_spiel/python/algorithms/psro_v2/meta_strategies.py
Python
apache-2.0
5,344
0.008046
# Copyright 2019 DeepMind Technologies Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agr...
return_joint: If true, only returns marginals. Otherwise marginals as well as joint probabilities. Returns: PRD-computed strategies. """ meta_games = solver.get_meta_game() if not isinstance(meta_games, lis
t): meta_games = [meta_games, -meta_games] kwargs = solver.get_kwargs() result = projected_replicator_dynamics.projected_replicator_dynamics( meta_games, **kwargs) if not return_joint: return result else: joint_strategies = get_joint_strategy_from_marginals(result) return result, joint_str...
LLNL/spack
var/spack/repos/builtin/packages/py-nistats/package.py
Python
lgpl-2.1
1,272
0.002358
# Copyri
ght 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Projec
t Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class PyNistats(PythonPackage): """Modeling and Statistical analysis of fMRI data in Python.""" homepage = "https://github.com/nilearn/nistats" pypi = "nistats/nistats-0.0...
hirofumi0810/tensorflow_end2end_speech_recognition
models/encoders/core/student_cnn_xe.py
Python
mit
4,732
0.000634
#! /usr/bin/env python # -*- coding: utf-8 -*- """Student CNN encoder for XE training.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow as tf from models.encoders.core.cnn_util import conv_layer, max_pool, batch_norm...
='relu') inputs = batch_normalization(inputs, is_training=is_training) inputs = max_pool(inputs, pooling_size=[1, 1], stride=[1, 1], name='max_pool') # Reshape to 2D tensor `[B, new_h * new_w * C_o...
ape=[batch_size, np.prod(inputs.shape.as_list()[-3:])]) for i in range(1, 5, 1): with tf.variable_scope('fc%d' % (i)) as scope: outputs = tf.contrib.layers.fully_connected( inputs=outputs, num_outputs=2048, activation_fn=tf...
carpedm20/fbchat
tests/threads/test_page.py
Python
bsd-3-clause
669
0.001495
import fbchat from fbchat import PageData def test_page_from_graphql(session): data = { "id": "123456", "name": "Some school", "profile_picture": {"uri": "https://scontent-arn2-1.xx.fbcdn.net/v/..."},
"url": "https://www.facebook.com/some-school/", "category_type": "SCHOOL", "city": None, } assert PageData( session=session, id="123456", photo=fbchat.Image
(url="https://scontent-arn2-1.xx.fbcdn.net/v/..."), name="Some school", url="https://www.facebook.com/some-school/", city=None, category="SCHOOL", ) == PageData._from_graphql(session, data)
Atom1c/home
board/board/wsgi.py
Python
unlicense
385
0.002597
""" WSGI config for board project. It exposes the WSGI callable as a module-level var
iable named ``application``.
For more information on this file, see https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/ """ import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "board.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application()
networks-lab/tidyextractors
tidyextractors/tidymbox/mbox_to_pandas.py
Python
gpl-3.0
6,462
0.002787
# ********************************************************************************************* # Copyright (C) 2017 Joel Becker, Jillian Anderson, Steve McColl and Dr. John McLevey # # This file is part of the tidyextractors package developed for Dr John McLevey's Networks Lab # at the University of Waterloo. For mor...
os.walk(mbox_path) for f in files if f.endswith('mbox')] mail_table = [] f_pbar = tqdm.tqdm(range(0,len(mbox_files))) f_pbar.set_description('Extracting mbox files...') for mbox_file in mbox_files: write_table(mbox_fi
le, mail_table) f_pbar.update(1) df_out = pd.DataFrame(mail_table) df_out.columns = ['From', 'To', 'Cc', 'Date', 'Subject', 'Body'] df_out['NumTo'] = df_out['To'].map(lambda i: len(i)) df_out['NumCC'] = df_out['Cc'].map(lambda i: len(i)) return df_out
missionpinball/mpf
mpf/tests/test_DropTargets.py
Python
mit
18,577
0.001453
from mpf.tests.MpfFakeGameTestCase import MpfFakeGameTestCase from unittest.mock import MagicMock, patch from mpf.tests.MpfTestCase import MpfTestCase class TestDropTargets(MpfTestCase): def get_config_file(self): return 'test_drop_targets.yaml' def get_machine_path(self): return 'tests/mac...
ine.coils["coil1"].pulse.called self.hit_switch_and_run("switch3", .5) self.assertTrue(self.machine.drop_targets["left1"].complete) self.assertTrue(self.machine.drop_targets["left2"].complete) self.assertTrue(self.machine.drop_targets["left3"].complete) self.assertTrue(self.mach...
me_and_run(.5) self.machine.coils["coil1"].pulse.assert_called_once_with(max_wait_ms=100) # after another 100ms the switches releases self.release_switch_and_run("switch1", 0) self.release_switch_and_run("switch2", 0) self.release_switch_and_run("switch3", 1) self.asser...
wasit7/PythonDay
django/mysite6/mysite6/wsgi.py
Python
bsd-3-clause
391
0
""" WSGI config for mysite6 project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on t
his file, see https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite6.settings"
) application = get_wsgi_application()
rosenvladimirov/addons
product_barcodes_bg/__init__.py
Python
agpl-3.0
992
0.001008
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # # Copyright (c) 2015 ERP|O
PEN (www.erpopen.nl). # # This program is free software: you can redistribute it and/or modify # it u
nder the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty ...
chalbersma/persist_transaction
archive.py
Python
gpl-3.0
3,154
0.045656
#!/usr/bin/env python3 from configparser import ConfigParser from colorama import Fore, Back, Style import time import argparse import ast import pymysql if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("-c", "--config", help="JSON Config File with our Storage Info", required=True...
er"], passwd=config_items
["db"]["dbpassword"], \ db=config_items["db"]["dbname"], autocommit=True ) except Exception as e : # Error print("Error Connecting to Datbase with error: ", str(e) ) do_archive = False if do_archive == True : # Set Archive Time ARCHIVE_TIME = int(time.time()) if VERBOSE: print("...
shaunwbell/FOCI_Analysis
temp/griddata.py
Python
mit
3,221
0.005899
# griddata.py - 2010-07-11 ccampo import numpy as np def griddata(x, y, z, binsize=0.01, retbin=True, retloc=True): """ Place unevenly spaced 2D data on a grid by 2D binning (nearest neighbor interpolation). Parameters ---------- x : ndarray (1D) The idependent data x-axis of the g...
rid the same shape as `grid`, except the value of each cell is the n
umber of points in that bin. Returns only if `retbin` is set to True. wherebin : list (2D) A 2D list the same shape as `grid` and `bins` where each cell contains the indicies of `z` which contain the values stored in the particular bin. Revisions --------- 2010-07-11 c...
reflectometry/direfl
direfl/gui/simulation_page.py
Python
mit
41,666
0.002328
# Copyright (C) 2006-2011, University of Maryland # # 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,...
from .input_list import InputListPanel from .instrument_params import InstrumentParameters from .wx_utils import (popup_error_message, popup_warning_message, StatusBarInfo, ExecuteInThread, WorkInProgress) # Text strings for use in file selection dialog boxes. DATA_FILES = "Data files (*.dat)|...
_DESC = "demo_model_1.dat" DEMO_MODEL2_DESC = "demo_model_2.dat" DEMO_MODEL3_DESC = "demo_model_3.dat" # Custom colors. WINDOW_BKGD_COLOUR = "#ECE9D8" PALE_YELLOW = "#FFFFB0" # Other constants NEWLINE = "\n" NEWLINES_2 = "\n\n" DATA_ENTRY_ERRMSG = """\ Please correct any highlighted field in error, then retry the op...
coreycb/horizon
openstack_dashboard/dashboards/project/images/utils.py
Python
apache-2.0
3,845
0
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under t...
) tuples
. :param request: django http request object :param include_empty_option: flag to include a empty tuple in the front of the list :return: list of (id, name) tuples """ try: images = get_available_images(request, request.user.project_id) except Exception: exceptions.han...
tensorflow/tpu
models/official/efficientnet/eval_ckpt_main.py
Python
apache-2.0
4,717
0.003604
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
one, 'Imagenet eval label file path, ' 'such as /imagenet/ILSVRC2012_validation_ground_truth.txt') flags.DEFINE_string('ckpt_dir', '/tmp/ckpt/', 'Checkpoint folders') flags.DEFINE_boolean('enable_ema', True, 'Enable exponential moving average.') flags.DEFINE_string('export_ckpt', None, 'Exported ckpt for eval graph...
flags.DEFINE_string('labels_map_file', '/tmp/labels_map.txt', 'Labels map from label id to its meaning.') flags.DEFINE_bool('include_background_label', False, 'Whether to include background as label #0') flags.DEFINE_bool('advprop_preprocessing', False, 'Whether ...
12019/cyberflex-shell
cards/cardos_card.py
Python
gpl-2.0
4,862
0.005965
import utils, TLV_utils from iso_7816_4_card import * import building_blocks class CardOS_Card(ISO_7816_4_Card,building_blocks.Card_with_ls): DRIVER_NAME = ["CardOS"] ATRS = [ ("3bf2180002c10a31fe58c80874", None), ] APDU_LIFECYCLE = C_APDU("\x00\xCA\x01\x83\x00") APDU_PHASE_CO...
ecause of checksum error (prop.)", "6F82": "Not enough memory available in XRAM", "6F83": "Transaction error (i.e. command must not be used in transaction)", "6F84": "General protection fault (prop.)", "6F85": "Internal failure of PK-API (e.g. wrong CCMS format)", "6F86": "Key Ob...
ng error", "6FFF": "Internal assertion (invalid internal error)\n + This error is no runtime error, but an internal error which can occur because of a programming error only.", "9000": "Command executed correctly", "9001": "Command exectued correctly; EEPROM weakness detected (EEPROM written wit...