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
kmike/tornado-slacker
slacker/__init__.py
Python
mit
37
0
fro
m slacker.postpone impo
rt Slacker
InterSIS/django-rest-serializer-field-permissions
rest_framework_serializer_field_permissions/permissions.py
Python
gpl-3.0
1,438
0.002782
""" Permissions to use with the rest_framework_serializer_field_permissions.field classes: class PersonSerializer(FieldPermissionSerializerMixin, serializers.ModelSerializer): family_names = fields.CharField(permission_classes=(IsAuthenticated(), )) given_names = fields.CharField(permission_clas
ses=(IsAuthenticated(), )) nick_name = fields.CharField(permission_classes=(AllowAny(), )) """ class BaseFieldPermission(object): """ The permission from which all other field-permissions inherit. Create your own field-permissions by extending this object and overriding has_permission. ""...
permission(self, request): """ Return true if permission is granted, return false if permission is denied. """ return True class AllowAny(BaseFieldPermission): """ Permission which allows free-access to the given field. """ def has_permission(self, request): ...
eeue56/just-columns
just-columns/test.py
Python
bsd-3-clause
447
0.008949
from wrapper imp
ort get, run import logging import requests @get('/') def f(*args, **kwargs): return '<html><head></head><body><h1>Hello!</h1></body></html>' @get('/test', ['php']) def test_f(*args, **kwargs): arguments = kwargs['arguments'] php = arguments['php'][0] self = args[0] self.write("Head") retur...
= '__main__': test()
cmjatai/cmj
cmj/core/migrations/0009_auto_20180220_0941.py
Python
gpl-3.0
578
0.001757
# -*- coding: utf-8 -*- # Generated by Django 1.11.8 on 2018-02-20 12:41 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('core', '0008_notificacao_user_origin'), ] operations = [
migrations.AlterModelOptions(
name='notificacao', options={'permissions': (('popup_notificacao', 'Visualização das notificações em Popup no Avatar do Usuário'),), 'verbose_name': 'Notificação', 'verbose_name_plural': 'Notificações'}, ), ]
django-leonardo/django-leonardo
leonardo/fields/__init__.py
Python
bsd-3-clause
209
0
import warnings from leonardo.forms.fields import * warnings.
warn('leonardo.field
s is obsolete' ' location use leonardo.forms instead' 'This location is only in migrations now')
joshainglis/python-soundscape
soundscape.py
Python
mit
14,885
0.003225
# Python 3 program for soundscape generation. (C) P.B.L. Meijer 2015 # Direct port of the hificode.c C program # Last update: October 6, 2015; released under the Creative # Commons Attribution 4.0 International License (CC BY 4.0), # see http://www.seeingwithsound.com/im2sound.htm for details # # Beware that this progr...
ngly slowly under Python, # while the PyPy python JIT compiler does not (yet) support OpenCV import math import os import struct import sys import wave import cv2 as cv
import numpy as np file_name = 'hificode.wav' # User-defined parameters min_frequency = 500 # Lowest frequency (Hz) in soundscape max_frequency = 5000 # Highest frequency (Hz) sample_frequency = 44100 # Sample frequency (Hz) image_to_sound_conversion_time = 1.05 # Image to sound conversion time (s) use_exponent...
tombstone/models
research/object_detection/meta_architectures/context_rcnn_lib.py
Python
apache-2.0
8,672
0.005996
# Lint as: python3 # Copyright 2020 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 ...
reshape(projected_features, [batch_size, -1, projection_dimension]) if normalize: projected_features = tf.math.l2_normalize(projected_features, axis=-1) return projected_features def attent
ion_block(input_features, context_features, bottleneck_dimension, output_dimension, attention_temperature, valid_mask, is_training): """Generic attention block. Args: input_features: A float Tensor of shape [batch_size, input_size, num_input_features]. context_...
kingsdigitallab/pbw-django
pbw/models.py
Python
gpl-2.0
46,771
0.001048
import os from django.core import serializers from django.db import models from django.utils.functional import cached_property from wagtail.admin.edit_handlers import FieldPanel from wagtail.core.fields import RichTextField from wagtail.core.models import Page from .settings import DISPLAYED_FACTOID_TYPES, BASE_DIR ...
ntegerField(db_column="chronOrder", b
lank=True, null=True) lft = models.SmallIntegerField() rgt = models.SmallIntegerField() chrontreekey = models.SmallIntegerField( db_column="chronTreeKey", blank=True, null=True ) year = models.SmallIntegerField(blank=True, null=True) datingelement = models.CharField( db_column="d...
hrayr-artunyan/shuup
shuup/xtheme/views/extra.py
Python
agpl-3.0
1,769
0.000565
# -*- coding: utf-8 -*- # This file is part of Shuup. # # Copyright (c) 2012-2016, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from django.core.exceptions import ImproperlyConfigured from django.core.sig...
import get_current_theme _VIEW_CACHE = {} def clear_vie
w_cache(**kwargs): _VIEW_CACHE.clear() setting_changed.connect(clear_view_cache, dispatch_uid="shuup.xtheme.views.extra.clear_view_cache") def _get_view_by_name(theme, view_name): view = theme.get_view(view_name) if hasattr(view, "as_view"): # Handle CBVs view = view.as_view() if view and n...
ActiveState/code
recipes/Python/189745_Symmetric_datobfuscatiusing/recipe-189745.py
Python
mit
1,786
0.00112
class Obfuscator: """ A simple obfuscator class using repeated xor """ def __init__(self, data): self._string = data def obfuscate(self): """Obfuscate a string by using repeated xor""" out = "" data = self._string a0=ord(data[0]) a1=ord(data...
thon obfuscator" obfuscator = Obfuscator(testString) testStringObf = obfuscator.obfuscate() print testStringObf obfuscator = Obfuscator(tes
tStringObf) testString = obfuscator.unobfuscate() print testString if __name__=="__main__": main()
oomlout/oomlout-OOMP
old/OOMPpart_HEAD_I01_L_PI08_01.py
Python
cc0-1.0
242
0
import OOMP new
Part = OOMP.oompItem(8936) newPart.addTag("oompType", "HEAD") newPart.addTag("oompSize", "I01") newPart.addTag("oompColor", "L") newPart.addTag("oompDesc", "PI08"
) newPart.addTag("oompIndex", "01") OOMP.parts.append(newPart)
bowringchan/SDRRadio_Remote_Version
encoder.py
Python
gpl-3.0
3,025
0.01124
#coding=utf-8 import subprocess from time import sleep import os import signal import m3u8_generator import fifo_tool class Batch_Encoder: def __init__(self, fifo_tool_i): self.fifo_tool_i = fifo_tool_i self.output_list = [] self.output_counter = 1 self.EXTINF = 1 self.media...
enerator_i.generate(self.output_list, self.media_sequence) self.output_co
unter += 1 else: break self.fifo_tool_i.delfifo_file() subprocess.call("sudo sh clean.sh",shell = True)
yadudoc/cloud_kotta
command.py
Python
apache-2.0
6,801
0.010587
#!/usr/bin/env python import subprocess32 as subprocess import threading import os import time import dynamo_utils as dutils import config_manager as cm import shlex ############################################################################ # Default params ##########################################################...
subsequently everytime when # more than 60s has elapsed since t_last_update. if (t_last_update == 0) or ((delta - t_last_update)
> USAGE_UPDATE_TIME) : update_usage_stats(app, job_id) t_last_update = delta time.sleep(sleep_time) total_t = time.time() - start_t print "RunCommand Completed {0} in {1} s".format(cmd, total_t) return total_t #########################################...
MartinHjelmare/home-assistant
homeassistant/components/wemo/switch.py
Python
apache-2.0
8,674
0
"""Support for WeMo switches.""" import asyncio import logging from datetime import datetime, timedelta import requests import async_timeout from homeassistant.components.switch import SwitchDevice from homeassistant.exceptions import PlatformNotReady from homeassistant.util import convert from homeassistant.const im...
attributes of the device.""" attr = {} if self.maker_params: # Is the maker sensor on or off. if self.maker_params['hassensor']: # Note a state of 1 matches the WeMo app 'not triggered'! if self.maker_params['sensorstate']: att...
TATE] = STATE_ON # Is the maker switch configured as toggle(0) or momentary (1). if self.maker_params['switchmode']: attr[ATTR_SWITCH_MODE] = MAKER_SWITCH_MOMENTARY else: attr[ATTR_SWITCH_MODE] = MAKER_SWITCH_TOGGLE if self.insight_params or ...
mathemage/h2o-3
h2o-py/h2o/grid/metrics.py
Python
apache-2.0
34,611
0.007657
# -*- encoding: utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals #----------------------------------------------------------------------------------------------------------------------- # AutoEncoder Grid Search #-------------------------------------------------------------...
will be used. :param bool train: If train is True, then return the accuracy value for the training data. :param bool valid: If valid is True, then return the accu
racy value for the validation data. :param bool xval: If xval is True, then return the accuracy value for the cross validation data. :returns: The accuracy for this binomial model. """ return {model.model_id: model.accuracy(thresholds, train, valid, xval) for model in self.models} ...
sh1ng/imba
lgbm_submition.py
Python
agpl-3.0
14,927
0.005962
import gc import pandas as pd import numpy as np import os import arboretum import lightgbm as lgb import json import sklearn.metrics from sklearn.metrics import f1_score, roc_auc_score from sklearn.model_selection import train_test_split from scipy.sparse import dok_matrix, coo_matrix from sklearn.utils.multiclass imp...
6, 'add_to_cart_order': np.uint8, 'reordered': bool}) orders = pd.read_csv(os.path.join(path, "orders.csv"), dtype={'order_id': np.uint32, ...
'user_id': np.uint32, 'eval_set': 'category', 'order_number': np.uint8, ...
benfinke/ns_python
nssrc/com/citrix/netscaler/nitro/resource/config/authentication/authenticationsamlidppolicy_binding.py
Python
apache-2.0
4,203
0.031882
# # Copyright (c) 2008-2015 Citrix Systems, Inc. # # Licensed under the Apache License, Version 2.0 (the "License") # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable l...
rrorcode != 0) : if (result.errorcode == 444) : service.clear_session(self) if result.severity : if (result.severity == "ERROR") : raise nitro_exception(result.errorcode, str(result.message), str(result.severity)) else : raise nitro_exception(result.errorcode, str(result.message), str(r...
ect_name(self) : ur""" Returns the value of object identifier argument """ try : if self.name is not None : return str(self.name) return None except Exception as e : raise e @classmethod def get(self, service, name) : ur""" Use this API to fetch authenticationsamlidppolicy_binding resource. ...
jasonwee/asus-rt-n14uhp-mrtg
src/lesson_algorithms/itertools_zip.py
Python
apache-2.0
55
0
for i in zip
([1, 2, 3], [
'a', 'b', 'c']): print(i)
dreibh/planetlab-lxc-plcapi
PLC/Methods/AddSliceToNodesWhitelist.py
Python
bsd-3-clause
1,708
0.002927
from PLC.Faults import * from PLC.Method import Method from PLC.Parameter import Parameter, Mixed from PLC.Nodes import Node, Nodes from PLC.Slices import Slice, Slices from PLC.Auth import Auth class AddSliceToNodesWhitelist(Method): """ Adds the specified slice to the whitelist on the specified nodes. Nodes ...
accepts = [ Auth(), Mixed(Slice.fields['slice_id'],
Slice.fields['name']), [Mixed(Node.fields['node_id'], Node.fields['hostname'])] ] returns = Parameter(int, '1 if successful') def call(self, auth, slice_id_or_name, node_id_or_hostname_list): # Get slice information slices = Slices(self.api, [slice...
MontrealCorpusTools/Montreal-Forced-Aligner
montreal_forced_aligner/acoustic_modeling/sat.py
Python
mit
14,192
0.001973
"""Class definitions for Speaker Adapted Triphone trainer""" from __future__ import annotations import multiprocessing as mp import os import re import shutil import subprocess import time from queue import Empty from typing import Dict, List, NamedTuple import tqdm from montreal_forced_aligner.acoustic_modeling.tri...
s(speaker_independent=True) return [ AccStatsTwoFeatsArguments( os.path.join(self.working_log_directory, f"acc_stats_two_feats.{j.name}.log"), j.current_dictionary_names, j.construct_path_dictionary(self.working_directory, "ali", "ark"), ...
_feat_strings[j.name], ) for j in self.jobs ] def calc_fmllr(self) -> None: self.worker.calc_fmllr() def compute_calculated_properties(self) -> None: """Generate realignment iterations, initial gaussians, and fMLLR iterations based on configuration""" su...
apache/incubator-systemml
src/main/python/systemds/operator/algorithm/builtin/garch.py
Python
apache-2.0
3,230
0.002477
# ------------------------------------------------------------- # # 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 unde...
ents during fitting :return: 'OperationNode' containing simulated garch(1,1) process on fitted coefficients & variances of simulated fitted process & constant term of fitted process & 1-st arch-coefficient of fitted process & 1-st garch-coefficient of fitted process & drawbacks: slow convergence of optimization (so...
vicinity': start_vicinity, 'end_vicinity': end_vicinity, 'sim_seed': sim_seed, 'verbose': verbose} vX_0 = Matrix(X.sds_context, '') vX_1 = Matrix(X.sds_context, '') vX_2 = Scalar(X.sds_context, '') vX_3 = Scalar(X.sds_context, '') vX_4 = Scalar(X.sds_context, '') output_nodes = [vX_0, vX_1,...
sam-roth/Keypad
keypad/plugins/pymodel/syntax.py
Python
gpl-3.0
5,339
0.0118
import re import keyword import logging import builtins from keypad.api import BufferController, autoconnect from keypad.core.syntaxlib import SyntaxHighlighter, lazy _python_kwlist = frozenset(keyword.kwlist) - frozenset('from import None False True'.split()) _python_builtins = frozenset(x for x in dir(builtins) i...
contains=PythonLexers ) return Python @autoconnect(BufferController.buffer_needs_highlight, lambda tags: tags.get('syntax') == 'python') def python_syntax_high
lighting(controller): highlighter = SyntaxHighlighter('keypad.plugins.pycomplete.syntax', pylexer(), dict(lexcat=None)) highlighter.highlight_buffer(controller.buffer) def main(): from keypad.plugins.semantics.syntaxlib import Tokenizer from keypad.core import AttributedString from keypad.buffers ...
nachandr/cfme_tests
cfme/tests/cloud_infra_common/test_vm_ownership.py
Python
gpl-2.0
10,161
0.001279
import fauxfactory import pytest from cfme import test_requirements from cfme.base.credential import Credential from cfme.cloud.provider import CloudProvider from cfme.exceptions import ItemNotFound from cfme.infrastructure.provider import InfraProvider from cfme.infrastructure.provider.virtualcenter import VMwareProv...
ry.gen_alphanu
meric(25, start="group_only_user_owned_"), role=role_only_user_owned.name) yield group appliance.server.login_admin() group.delete() @pytest.fixture(scope="module") def role_user_or_group_owned(appliance): appliance.server.login_admin() role = appliance.collections.roles.create( na...
jiaphuan/models
research/tcn/utils/luatables.py
Python
apache-2.0
2,393
0.006686
# Copyright 2017 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 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 K...
nguage governing permissions and # limitations under the License. # ============================================================================== # pylint: disable=line-too-long,g-explicit-length-test """A convenience class replicating some lua table syntax with a python dict. In general, should behave like a dictio...
globocom/database-as-a-service
dbaas/admin/templatetags/config_tags.py
Python
bsd-3-clause
453
0
from django import template from system.models
import Configuration register = template.Library() @register.assignment_tag def get_config(conf_name=None): if conf_name is None: raise Exception("Invalid config name") c = Configuration.get_by_name_all_fields(conf_name)
if not c: return None return { "name": c.name, "value": c.value, "description": c.description, "hash": c.hash }
MiiRaGe/cryptanalysis-tools
vigenere/PyGenere.py
Python
gpl-2.0
13,863
0.012479
class Caesar(str): """An implementation of the Caesar cipher.""" def encipher(self, shift): """Encipher input (plaintext) using the Caesar cipher and return it (ciphertext).""" ciphertext = [] for p in self: if p.isalpha(): ciphertext.append(chr((...
ue used is based on the one desc
ribed in: http://www.stonehill.edu/compsci/Shai_papers/RSA.pdf (pages 9-10) Character frequencies taken from: http://www.csm.astate.edu/~rossa/datasec/frequency.html (English) http://www.characterfrequency.com/ (French, Italian, Portuguese, Spanish) http://www.santacruzpl.org/readyref/files/g-...
skhal/performance
python/utility/timer.py
Python
mit
901
0.00222
#!/usr/bin/env python ''' Created by Samvel Khalatyan, May 01, 2012 Copyright 2012, All rights reserved '
'' from __future__ import division import time class Timer(object): def __init__(self): self._calls
= 0 self._elapsed = 0 self._start = None def start(self): if not self._start: self._start = time.clock() def stop(self): if self._start: self._elapsed += time.clock() - self._start self._calls += 1 self._start = None def ca...
google/compare-codecs
lib/file_codec.py
Python
apache-2.0
7,774
0.007718
#!/usr/bin/python # Copyright 2014 Google. # # 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...
defined') def DecodeCommandLine(self, videofile, encodedfile, yuvfile): """This function returns the command line that should be executed in order to turn an en
coded file into an YUV file.""" # pylint: disable=W0613,R0201 raise encoder.Error('DecodeCommandLine not defined') def ResultData(self, encodedfile): """Returns additional fields that the codec may know how to generate.""" # pylint: disable=W0613,R0201 return {} def VerifyEncode(self, paramete...
pbfy0/visvis.dev
functions/colorbar.py
Python
bsd-3-clause
531
0.013183
# -*- coding: utf-8 -*- # Copyright (C) 2012, Almar Klein # # Visvis is distributed under the terms of the (new) BSD License. # The full license can be found in 'license.txt'. import visvis as vv def colorbar(axes=None): """ colorbar(axes=N
one) Attach a colorbar to the given axes (or the current axes if not given). The reference to the colorbar instance is returned. Also see the vv.ColormapEditor wibject. """ if axe
s is None: axes = vv.gca() return vv.Colorbar(axes)
tomspur/shedskin
examples/mwmatching.py
Python
gpl-3.0
32,668
0.003459
"""Weighted maximum matching in general graphs. The algorithm is taken from "Efficient Algorithms for Finding Maximum Matching in Graphs" by Zvi Galil, ACM Computing Surveys, 1986. It is based on the "blossom" method for finding augmenting paths and the "primal-dual" method for finding a matching of maximum weight, bo...
he edge through which v is # reachable from outside the blossom. labelend = (2 * nvertex) * [ -1 ] # I
f v is a vertex, # inblossom[v] is the top-level blossom to which v belongs. # If v is a top-level vertex, v is itself a blossom (a trivial blossom) # and inblossom[v] == v. # Initially all vertices are top-level trivial blossoms. inblossom = range(nvertex) # If b is a sub-blossom, # blossomparent[b] is its immediate ...
hyperNURb/ggrc-core
src/ggrc/models/response.py
Python
apache-2.0
5,096
0.009027
# Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: [email protected] # Maintained By: [email protected] from ggrc import db from ggrc.models.mixins import ( deferred, Noted, Describ...
ble=True), 'Response') sample_evidence_id = deferred( db.Column(db.Integer, db.ForeignKey('documents.id'), nullable=True), 'Response') population_worksheet = db.relationship( "Document", foreign_keys="PopulationSampleResponse.population_worksheet_id" ) sample_worksheet = db.relationship...
t_id" ) sample_evidence = db.relationship( "Document", foreign_keys="PopulationSampleResponse.sample_evidence_id" ) @staticmethod def _extra_table_args(cls): return ( db.Index('population_worksheet_document', 'population_worksheet_id'), db.Index('sample_evidence_document', 'sa...
daniele-athome/kontalk-legacy-xmppserver
kontalk/xmppserver/component/c2s/handlers.py
Python
gpl-3.0
16,001
0.004
# -*- coding: utf-8 -*- """c2s protocol handlers.""" """ Kontalk XMPP server Copyright (C) 2014 Kontalk Devteam <[email protected]> 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 ver...
itervalues(): presence = x._presence if presence and not presence.hasAttribute('type'): response = domish.Element((None, 'presence')) response['to'] = to response['from...
e = getattr(presence, child) if e: response.addChild(deepcopy(e)) self.send(response) num_avail += 1 except KeyError: pass ...
eLRuLL/scrapy
tests/test_utils_request.py
Python
bsd-3-clause
4,301
0.003953
import unittest from scrapy.http import Request from scrapy.utils.request import request_fingerprint, _fingerprint_cache, \ request_authenticate, request_httprepr class UtilsRequestTest(unittest.TestCase): def test_request_fingerprint(self): r1 = Request("http://www.example.com/query?id=111&cat=222")...
f.assertNotEqual(request_fingerprint(r1), request_fingerprint(r2)) # make sure caching is working self.assertEqual(request_fingerprint(r1), _fingerprint_cache[r1][(None, False)]) r1 = Request("http://www.example.com/members/offers.html") r2 = Request("http://www.example.com/members/off...
r2 = Request("http://www.example.com/") r2.headers['Accept-Language'] = b'en' r3 = Request("http://www.example.com/") r3.headers['Accept-Language'] = b'en' r3.headers['SESSIONID'] = b"somehash" self.assertEqual(request_fingerprint(r1), request_fingerprint(r2), request_fingerpri...
aroth-arsoft/arsoft-meta-packages
grp_dovecot.py
Python
gpl-3.0
1,242
0.045089
#!/usr/bin/python # -*- coding: utf-8 -*- # kate: space-indent on; indent-width 4; mixedindent off; indent-mode python; dovecot = [
{'name':'common', 'mainpackage':True, 'short
desc':'Installs the latest version of the Dovecot mail server', 'description':'', 'packages':['dovecot-core', 'dovecot-antispam', 'dovecot-imapd', 'dovecot-pop3d', 'dovecot-gssapi', 'dovecot-lmtpd', 'dovecot-managesieved', 'dovecot-solr' ] }, {'name':'mysql', 'shortdesc':'Installs t...
JhooClan/QLibCJ
qalg.py
Python
mit
9,431
0.023976
from qlibcj import * def DJAlg(size, U_f, **kwargs): # U_f es el oraculo, que debe tener x1..xn e y como qubits. Tras aplicarlo el qubit y debe valer f(x1..xn) XOR y. El argumento size es n + 1, donde n es el numero de bits de entrada de f. rnd.seed(kwargs.get('seed', None)) # Para asegurar la repetibilidad fijamos l...
Line(I(1), H(1), I(1)) qc.addLine(I(1), CNOT()) # Aqui es donde trabajamos con el qubit Q que queremos enviar posteriormente. Se le aplica la puerta pasada como parámetro qc.addLine(gate, I(2)) # Una vez terminado todo lo que queremos ha
cerle al QuBit, procedemos a preparar el envio qc.addLine(CNOT(), I(1)) # Se aplica una puerta C-NOT sobre Q (control) y B (objetivo). qc.addLine(H(1), I(2)) # Se aplica una puerta Hadamard sobre Q. c1 = Condition([None, 1, None], PauliX()) c2 = Condition([1, None, None], PauliZ()) m = Measure([1, 1, 0], conds=[...
scVENUS/PeekabooAV
peekaboo/server.py
Python
gpl-3.0
13,675
0.000219
############################################################################### # # # Peekaboo Extended Email Attachment Behavior Observation Owl # # # ...
t.content_type) # application/x-www-form-urlencoded is inefficient at transporting # binary data. Also it needs a separate field to transfer the filename. # Make clear here that we do not support that format (yet). if content_type != 'multipart/form-data': logger.error('Inva...
400) boundary = parameters["boundary"].encode("utf-8") form_parts = request.body.split(boundary) # split above leaves preamble in form_parts[0] and epilogue in # form_parts[2] num_fields = len(form_parts) - 2 if num_fields <= 0: logger.error('Invalid...
jiasir/playback
playback/cli/cli.py
Python
mit
2,192
0.006387
import sys import argparse import pkg_resources from playback import __version__ def get_parser(): parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter, description='OpenStack provisioning and orchestration library with command-line tools' ) parser.add...
_points('provision') ] entry_
points.sort( key=lambda (name, fn): getattr(fn, 'priority', 100), ) for (name, fn) in entry_points: p = provision_subparser.add_parser( name, description=fn.__doc__, help=fn.__doc__, ) fn(p) return parser def _main(): parser = ...
novafloss/django-formidable
formidable/utils.py
Python
mit
342
0
from importlib import import_module def import_object(object_path): """ Import class or function by path :param object_path: path to the obj
ect for import :return: imported object """ module_path, class_name = object_path.rsplit('.', 1) module = import_module(module_path) retur
n getattr(module, class_name)
ericdill/bokeh
bokeh/server/storage/backbone_storage.py
Python
bsd-3-clause
3,761
0.003988
#----------------------------------------------------------------------------- # Copyright (c) 2012 - 2015, Continuum Analytics, Inc. All rights reserved. # # Powered by the Bokeh Development Team. # # The full license is in the file LICENSE.txt, distributed with this software. #----------------------------------------...
ever use the temporary_docid # when we actually store the values # TODO: refactor this API in the future for better separation if temporary_docid is not None: storage_id = temporary_docid else: storage_id = doc.docid logger.debug("storing objects to %s", s...
models = doc._models.values() if dirty_only: models = [x for x in models if hasattr(x, '_dirty') and x._dirty] json_objs = doc.dump(*models) self.push(storage_id, *json_objs) for mod in models: mod._dirty = False return models def push(self, d...
nick-huang-cc/GraffitiSpaceTT
UnderstandStudyPython/TCP_stu2.py
Python
agpl-3.0
1,020
0.015588
#!/usr/bin/env python3 # -*- coding:UTF-8 -*- #Copyright (c) 1986 Nick Wong. #Copyright (c) 2016-2026 TP-NEW Corp. # License: TP-NEW (www.tp-new.com) __author__ = "Nick Wong" ''' TCP 客户端 ''' #导入socket库 import socket #创建一个socket AF_INET是定IPv4协议、AF_INET6为指定IPv6协议, SOCK_STREAM指定使用面向流的TCP协议 s = socket.socket(socket...
TREAM) #建立连接 如下参数tuple包含地址可端口号 s.connect(('www.wufazhuce.com', 80)) #建立TCP连接后就可以向连接发送请求, #发送数据 s.send(b'GET / HTTP/1.1\r\nHost:www.wufazhuce.com\r\nConnection: close\r\n\r\n') #接收数据 buffer = [] while True: #每次最多接收1k字节 d = s.recv(1024) if d: buffer.append(d) else: break data = b''.join
(buffer) #关闭连接 s.close() header, html = data.split(b'\r\n\r\n', 1) print(header.decode('utf-8')) #把接收的数据写入文件: with open('com.html', 'wb') as f: f.write(html)
dqnykamp/nykampweb
nykampweb/wsgi.py
Python
gpl-2.0
395
0
""" WSGI co
nfig for nykampweb project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODUL...
ion()
kingfisher1337/tns
qpotts_groundstate_1d/plot.py
Python
gpl-3.0
12,349
0.008017
import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt import os from hashlib import md5 from fractions import Fraction mpl.rcParams["text.usetex"] = True mpl.rcParams["text.latex.preamble"] = "\usepackage{bm}" def read_hash(path): if not os.path.isfile(path): return "" with open(...
get_pm_yticks(q,ymin,ymax): return get_yticks_for_fields(primFieldsPM[q],ymin,ymax) def get_fm_yticklabels(q,ymin,ymax): return get_yticklabels_for_fields(primFieldsFM[q],ymin,ymax) def get_pm_yticklabels(q,ymin,ymax): return get_yticklabels_for_
fields(primFieldsPM[q],ymin,ymax) for filename in sorted(os.listdir("output")): if filename.startswith("ctmrgsvals_detail_"): h_xi = dict() md = md5() with open("output/" + filename, "r") as f: chi = filter(lambda s: s.find("chi=") != -1, filename[:-4].split("_"))[0].split("=")[...
timrchavez/capomastro
jenkins/tests/test_models.py
Python
mit
1,239
0
from django.test import TestCase from httmock import HTTMock from jenkinsapi.jenkins import Jenkins from jenkins.models import Build, JobType from .helpers import mock_url from .factories import BuildFactory, JenkinsServerFactory class JenkinsServerTest(TestCase): def test_get_client(self): """ ...
lf): """Builds should be ordered in reverse build order by default.""" builds = BuildFactory.create_batch(5) build_numbers = sorted([x.number for x in builds], reverse=True) self.assertEqual( build_numbers, list(Build.objects.all().values
_list("number", flat=True))) class JobTypeTest(TestCase): def test_instantiation(self): """We can create JobTypes.""" JobType.objects.create( name="my-test", config_xml="testing xml")
konini-school/pibot26
module3.py
Python
gpl-2.0
541
0.003697
############################################## # File Name: module3.py # Version: 1.0 # Team No.: 26 # Team Name: # Date: 28 Oct 15 ############################################## import RPi.GPIO as GPIO import time imp
ort sys, tty, termios print '\nHi, I am PiBot, your very own learning robot..\n' GPIO.setmode(GPIO.BOARD) GPIO.setup(7, GPIO.OUT) ledOnTime = 5 # Turn on LED print 'Turn the LED on' GPIO.output(7, True) time.sleep(ledOnTime
) print 'Turn the LED off' GPIO.output(7, False) GPIO.cleanup() print "\nEnd of program"
mhl/gib
gitsetup.py
Python
lgpl-2.1
10,749
0.004279
from configparser import RawConfigParser import os import re from subprocess import call, check_call, Popen, PIPE, STDOUT import sys from errors import Errors from general import ( exists_and_is_directory, shellquote, print_stderr ) from githelpers import has_objects_and_refs class OptionFrom: '''enum-like va...
re subj
ect to shell interpretation.''' command = "git --git-dir="+shellquote(self.git_directory) command += " --work-tree="+shellquote(self.directory_to_backup) return command def git_initialized(self): '''Returns True if it seems as if the git directory has already been intialized...
thebjorn/dkcoverage
dkcoverage/rtestcover.py
Python
gpl-2.0
3,325
0.000902
# -*- coding: utf-8 -*- """Called from datakortet\dkcoverage.bat to record regression test coverage data in dashboard. """ import re import os # import sys # import time import glob # from datakortet.dkdash.status import send_status # from datakortet.utils import root from coverage import coverage, misc from cover...
kenv.DKROOT)) for p in cov.omit] _skipli
st = [] for pat in skippatterns: _skiplist += glob.glob(pat) return set(_skiplist) def abspath(fname): # cwd = os.getcwd() res = os.path.normcase( os.path.normpath( os.path.abspath(fname))) #.replace(cwd, root())))) return res def valid_file(fname, _skiplist=None): ...
kaltwang/latenttrees
latenttrees/test_lt_helper.py
Python
bsd-3-clause
880
0.003409
import unittest import numpy as np import latenttrees.lt_helper
as lth from scipy.stats import norm class TestLtHelper(unittest.TestCase): pass def test_norm_logpdf_generator(x, mu, std): def test(self): scipy_d = norm(mu, std) # scipy normal distribution logpdf_scipy = scipy_d.logpdf(x) logpdf = lth.norm_logpdf(x, mu, std) # se...
, False) np.testing.assert_allclose(logpdf, logpdf_scipy) return test if __name__ == '__main__': for i in range(10): test_name = 'test_norm_logpdf_{}'.format(i) d1 = 100 d2 = 1 mu = np.random.randn(d1, d2) std = np.random.rand(d1, d2) x = (np.r...
vanita5/TwittnukerGCMServer
app.py
Python
gpl-3.0
6,900
0.006667
import os, binascii from dateutil import parser as dateparser from bottle import run, get, post, delete, install, HTTPError, request from bottle_sqlite import SQLitePlugin from dbsetup import init_db from google_auth import gauth from app_conf import DBNAME, DEBUG from app_gcm import send_notification init_db(DBNAME) ...
else: prnt('NO CHANGES ON DB') return HTTPError(500, "Account id could not be added to the database.") if __name__ == '__main__': run(host = '0.0.0.0', port = 5050, re
loader = True, debug = True)
Instanssi/Instanssi.org
Instanssi/users/views.py
Python
mit
2,915
0.002058
# -*- coding: utf-8 -*- from Instanssi.common.auth import user_access_required from django.shortcuts import render from django.http import HttpResponseRedirect from django.contrib import auth from django.urls import reverse from Instanssi.users.forms import OpenIDLoginForm, DjangoLoginForm, ProfileForm from Instanssi....
c import get_url_local_path AUTH_METHODS = [ # Short name, social-auth, friendly name ('facebook', 'facebook', 'Facebook'), ('google', 'google-oauth2', 'Google'), ('twitter', 'twitter', 'Twitter'), ('github', 'github', 'Github'), ('battlenet', 'battlenet-oauth2', 'Battle.net'), ('steam', '...
.is_authenticated: return HttpResponseRedirect(reverse('users:profile')) # Get referer for redirect # Make sure that the referrer is a local path. if 'next' in request.GET: next_page = get_url_local_path(request.GET['next']) else: next_page = get_url_local_path(request.META....
tartavull/google-cloud-python
datastore/tests/unit/test_query.py
Python
apache-2.0
26,883
0
# Copyright 2014 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
(query.kind, _KIND_BEFORE) query.kind = _KIND_AFTER self.asser
tEqual(query.project, self._PROJECT) self.assertEqual(query.kind, _KIND_AFTER) def test_ancestor_setter_w_non_key(self): query = self._make_one(self._make_client()) def _assign(val): query.ancestor = val self.assertRaises(TypeError, _assign, object()) self.asse...
rsalmaso/django-babeljs
babeljs/execjs/__init__.py
Python
mit
8,122
0.001847
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright (C) 2007-2018, Raffaele Salmaso <[email protected]> # Copyright (c) 2012 Omoto Kenji # Copyright (c) 2011 Sam Stephenson # Copyright (c) 2011 Josh Peek # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and a...
t except ImportError:
from ordereddict import OrderedDict from .exceptions import Error, RuntimeError, ProgramError, RuntimeUnavailable from .runtime import Runtime, PyV8Runtime __all__ = [ "get", "register", "runtimes", "get_from_environment", "exec_", "eval", "compile", "Runtime", "Context", "Error", "RuntimeError", "Prog...
adazey/Muzez
libs/nltk/classify/__init__.py
Python
gpl-3.0
4,636
0.000647
# Natural Language Toolkit: Classifiers # # Copyright (C) 2001-2016 NLTK Project # Author: Edward Loper <[email protected]> # URL: <http://nltk.org/> # Fo
r license information, see LICENSE.TXT """ Classes and interfaces for labeling tokens with category labels (or "class labels"). Typically, labels are represented with strings (such as ``'health'`` or ``'sports'``). Classifiers can be used to perform a wide range of classification tasks. For example, classifi...
h word sense is intended - to classify acoustic signals by which phoneme they represent - to classify sentences by their author Features ======== In order to decide which category label is appropriate for a given token, classifiers examine one or more 'features' of the token. These "features" are typically ch...
ankanaan/chimera
src/chimera/util/output.py
Python
gpl-2.0
5,104
0.000392
# Copyright 1998-2004 Gentoo Foundation # Distributed under the terms of the GNU General Public License v2 # $Id: output.py,v 1.1 2006/03/06 18:13:31 henrique Exp $ import os import sys import re havecolor = 1 dotitles = 1 spinpos = 0 spinner = "/-\\|/-\\|/-\\|/-\\|\\-/|\\-/|\\-/|\\-/|" esc_seq = "\x1b[" g_attr =...
: return codes["fuchsia"] + text + codes["reset"] def purple(text): return codes["purple"] + text + codes["reset"] def blue(text): return codes["blue"] + text + codes["reset"] def darkblue(text): return codes["darkblue"] + text + codes["reset"] def green(text): return codes["green"] + text +...
t"] def brown(text): return codes["brown"] + text + codes["reset"] def darkyellow(text): return brown(text) def red(text): return codes["red"] + text + codes["reset"] def darkred(text): return codes["darkred"] + text + codes["reset"] def update_basic_spinner(): global spinner, spinpos ...
Crazepony/crazepony-gitbook
wiki/changelink.py
Python
apache-2.0
4,252
0.010335
#!/usr/bin/env python # -*- coding: utf-8 -*- # Filename: deleteline.py import os import sys reload(sys) #sys.setdefaultencoding('utf8') def ChangeLineInFile(infile,isOverwrite): isOverwrite = isOverwrite.upper() _dir = os.path.dirname(infile) oldbasename = os.path.basename(infile) newbasename = ol...
if title != None: line2 = line.replace("{{ page.title }}", title) outfp.writelines(line2) else: #print line outfp.writelines(line) infp.close() outfp.close() if isOverwrite == 'Y': #print 'remove',infile os.remo...
def ChangeLineInFolders(): string = u'请输入目标文件夹路径====>' inpath = raw_input(string.encode('utf8')) string = u'您输入是:' + inpath print string string = u'是否覆盖源文件(Y/N)' isOverwrite = raw_input(string.encode('utf8')) isOverwrite = isOverwrite.upper() string = u'您的选择是:' + isOverwrite p...
piyueh/SEM-Toolbox
utils/errors/__init__.py
Python
mit
330
0
#! /usr/bin/env
python3 # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2016 Pi-Yueh Chuang <[email protected]> # # Distributed under terms of the MIT license. """__init__.py""" from utils.errors.Error import Error from utils.errors.InfLoopError import InfLoopError __author__ = "Pi-Yueh Chuang" __version__
= "alpha"
davidvon/pipa-pay-server
admin/utils/__init__.py
Python
apache-2.0
28
0.035714
__
author__ = 'f
engguanhua'
galek/anki-3d-engine
docs/drafts/octree.py
Python
bsd-3-clause
246
0.03252
from math import * octree_node_size = 112 def recurse(depth): if depth == 0: retur
n 1 else: return pow(8, depth) + recurse(depth - 1) def octree_size(depth): return recurse(depth) * octree_node_size print("Size %d" % (octree_size(3)))
codypiersall/mlab
tests/test_mlab_on_unix.py
Python
mit
753
0.003984
import sys sys.path = ['../src/'] + sys.path import unittest from mlab.mlabwrap import Matlab
ReleaseNotFound class Test
MlabUnix(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_version_discovery(self): import mlab instances = mlab.releases.MatlabVersions(globals()) assert len(instances.pick_latest_release()) > 0 with self.assertRaises(MatlabReleas...
openelisglobal/openelisglobal-sandbox
liquibase/OE2.7/CILNSPMassive/scripts/dictionary.py
Python
mpl-2.0
1,212
0.005776
#!/usr/bin/env python # -*- coding: utf-8 -*- def get_comma_split_names( name ): split_name_list = [name] if ',' in name: split_name_list = name.split(",") elif ';' in name: split_name_list = name.split(";") for i in range(0, len(split_name_list)): split_name_lis...
n("dictionaryResult.sql",'w') for line in old_file: old.append(line.strip()) old_file.close() for line in new_file: if len(line) > 1: values = get_comma_split_names(line) for value in values: if value.strip() not in old: old.a
ppend(value.strip()) result.write("INSERT INTO clinlims.dictionary ( id, is_active, dict_entry, lastupdated, dictionary_category_id ) \n\t") result.write("VALUES ( nextval( 'dictionary_seq' ) , 'Y' , '" + value.strip() + "' , now(), ( select id from clinlims.dictionary_category where d...
manu0466/BookingBot
src/bot/handler/decorator/__init__.py
Python
gpl-2.0
67
0
from .
FilterableHandlerDecorator import FilterableHandlerDecorator
hugoallan9/programacionMatematica
skeleton/App/hilo.py
Python
gpl-3.0
352
0.014286
# -*- coding: utf-8 -*- """ Created on Mon Oct 10
06:32:29 2016 @author: hugo """ import threading def worker(count): for x in range(count): print "Programación matemática %s \n " % x return threads = list() t = threading.Thread(target=worker, args=(10,)) threads.app
end(t) t.start() print 'Hola mundo'
ray-project/ray
rllib/examples/models/rnn_model.py
Python
apache-2.0
5,133
0.000974
import numpy as np from ray.rllib.models.modelv2 import ModelV2 from ray.rllib.models.preprocessors import get_preprocessor from ray.rllib.models.tf.recurrent_net import RecurrentNetwork from ray.rllib.models.torch.recurrent_net import RecurrentNetwork as TorchRNN from ray.rllib.utils.annotations import override from ...
n_h, state_in_c], ) # Postprocess LSTM output with another hidden layer and compute values logits = tf.keras.layers.Dense( self.num_outputs,
activation=tf.keras.activations.linear, name="logits" )(lstm_out) values = tf.keras.layers.Dense(1, activation=None, name="values")(lstm_out) # Create the RNN model self.rnn_model = tf.keras.Model( inputs=[input_layer, seq_in, state_in_h, state_in_c], outputs=[lo...
bfalacerda/strands_executive
task_executor/tests/mdp_exec_test.py
Python
mit
2,319
0.004743
#!/usr/bin/env python import rospy from strands_executive_msgs import task_utils from strands_executive_msgs.msg import Task from strands_executive_msgs.srv import AddTasks, SetExecutionStatus from strands_navigation_msgs.msg import * import sys def get_services(): # get services necessary to do the job add_t...
exe_stat_srv_name) rospy.loginfo("Done") add_tasks_srv = rospy.ServiceProxy(add_tasks_srv_name, AddTasks) set_execution_status = rospy.ServiceProxy(set_exe_stat_srv_name, SetExecutionStatus) return add_tasks_srv, set
_execution_status def create_wait_task(node, secs=rospy.Duration(1), start_after=None, window_size=rospy.Duration(3600)): if start_after is None: start_after = rospy.get_rostime() wait_task = Task(action='wait_action',start_node_id=node, end_node_id=node, max_duration=secs) wait_task.start_after ...
centaurialpha/edis
src/ui/dialogs/file_properties.py
Python
gpl-3.0
3,225
0.000932
# -*- coding: utf-8 -*- # EDIS - a simple cross-platform IDE for C # # This file is part of Edis # Copyright 2014-2015 - Gabriel Acosta <acostadariogabriel at gmail> # License: GPLv3 (see http://www.gnu.org/licenses/gpl.html) import re import os from datetime import datetime from PyQt4.QtGui import ( QDialog, ...
utton(self.tr("Aceptar")) grid.addWidget(btn_aceptar, 8, 1, Qt.AlignRight) vLayout.addLayout(grid) b
tn_aceptar.clicked.connect(self.close) def get_type(self, filename): try: ext = filename.split('.')[-1] if ext == 'c': type_ = self.tr("Archivo fuente C") elif ext == 'h': type_ = self.tr("Archivo de Cabecera") elif ext == 's':...
AdamWill/bodhi
bodhi/tests/server/test_metadata.py
Python
gpl-2.0
16,797
0.001072
# 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 in the hope that it will be useful, # bu...
t ZopeTransactionExtension import createrepo_c from bodhi.server import log from bodhi.server.config import config from bodhi.server.util import mkmetad
atadir from bodhi.server.models import (Package, Update, Build, Base, UpdateRequest, UpdateStatus, UpdateType) from bodhi.server.buildsys import get_session, DevBuildsys from bodhi.server.metadata import ExtendedMetadata from bodhi.tests.server.functional.base import DB_PATH from bodhi.tests.server import popu...
rwl/openpowersystem
rdflib/util.py
Python
agpl-3.0
7,101
0.006337
from rdflib.URIRef import URIRef from rdflib.BNode import BNode from rdflib.Literal import Literal from rdflib.Variable import Variable from rdflib.Graph import Graph, QuotedGraph from rdflib.Statement import Statement from rdflib.exceptions import SubjectTypeError, PredicateTypeError, ObjectTypeError, ContextTypeErro...
instance(s, URIRef) or isinstance(s
, BNode)): raise SubjectTypeError(s) def check_predicate(p): """ Test that p is a valid predicate identifier.""" if not isinstance(p, URIRef): raise PredicateTypeError(p) def check_object(o): """ Test that o is a valid object identifier.""" if not (isinstance(o, URIRef) or \ ...
suyashphadtare/vestasi-erp-jan-end
erpnext/stock/doctype/material_request/material_request.py
Python
agpl-3.0
13,650
0.024469
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt # ERPNext - web based ERP (http://erpnext.com) # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe.utils import cstr, flt f...
nt_details')] def validate_qty_against_so(self): so_items = {} # Format --> {'SO/00001': {'Item/001': 120, 'Item/002': 24}} for d in self.get('indent_details'): if d.sales_order_no: if not so_items.has_key(d.sales_order_no): so_items[d.sales_order_no] = {d.item_code: flt(d.qty)} else:
if not so_items[d.sales_order_no].has_key(d.item_code): so_items[d.sales_order_no][d.item_code] = flt(d.qty) else: so_items[d.sales_order_no][d.item_code] += flt(d.qty) for so_no in so_items.keys(): for item in so_items[so_no].keys(): already_indented = frappe.db.sql("""select sum(ifnull(q...
mjames-upc/python-awips
dynamicserialize/dstypes/com/raytheon/uf/common/auth/user/User.py
Python
bsd-3-clause
673
0.002972
## ## # File auto-generated agains
t equivalent DynamicSerialize Java class from dynamicserialize.dstypes.com.raytheon.uf.common.auth.user import UserId class User(object): def __init__(self, userId=None): if userId is None: self.userId = UserId.UserId() else:
self.userId = userId self.authenticationData = None def getUserId(self): return self.userId def setUserId(self, userId): self.userId = userId def getAuthenticationData(self): return self.authenticationData def setAuthenticationData(self, authenticationData): ...
ava-project/AVA
ava/input/KeyManager.py
Python
mit
1,876
0.001066
import io import sys import threading import wave from pynput import keyboard from pynput.keyboard import Key, Controller from .RawInput import RawInput from ..components import _BaseComponent class KeyManager: def __init__(self, queues): self.activated = False self.listener = None self....
self.activated: self.activated = False self.input_listener.stop() print("Voice recognition stopped !") while self.input_listener.done == False: pass self.write_to_file(self.input_listener.record) def run(self): with keyboard.Liste...
ress=self.on_press, on_release=self.on_release) as self.listener: self.listener.join() def stop(self): print('Stopping {0}...'.format(self.__class__.__name__)) self.listener.stop()
openstack-dev/bashate
bashate/messages.py
Python
apache-2.0
7,248
0.000138
# 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 the...
property for quick access. return "%s: %s" % (self.msg_id, self.msg_str) _messages = { 'E001': { 'msg': 'Trailing Whitespace', 'long_msg': None, 'default': 'E' }, 'E002': { 'msg': 'Tab indents', 'long_msg': """
Spaces are preferred to tabs in source files. """, 'default': 'E' }, 'E003': { 'msg': 'Indent not multiple of 4', 'long_msg': """ Four spaces should be used to offset logical blocks. """, 'default': 'E' }, 'E004': { 'msg': 'Fil...
cheshirekow/codebase
third_party/lcm/test/python/bool_test.py
Python
gpl-3.0
1,778
0.001687
#!/usr/bin/python import unittest import lcmtest class TestBools(unittest.TestCase): def test
_bool(self): """Encode a bools_t message, then verify that it decodes correctly. Also check that the decoded fields are all of type bool. """ msg = lcmtest.bools_t() msg.one_bool = True msg.fixed_array = [False, True, False] msg.num_a = 3 msg.num_b = 2 ...
2)) msg.two_dim_array.append(inner_list) msg.one_dim_array.append(bool((a_index + 1) % 2)) data = msg.encode() decoded = lcmtest.bools_t.decode(data) self.assertEqual(msg.one_bool, decoded.one_bool) self.assertEqual(list(msg.fixed_array), list(decoded.fixed_arr...
portableant/open-context-py
opencontext_py/apps/edit/inputs/fieldgroups/models.py
Python
gpl-3.0
2,043
0.002447
import collections from jsonfield import JSONField from datetime import datetime from django.utils import timezone from django.db import models # Stores information about fields for a data entry form class InputFieldGroup(models.Model): GROUP_VIS = {'open': 'Show Field Group in an open panel', '...
make sure that for real_vis_key, value in self.GROUP_VIS.items(): visibility = real_vis_key break; return visibility def save(self, *args, **kwargs): """ saves the record with creation date """ self.visibility = self.validate_visi...
if self.obs_num is None: self.obs_num = 1 if self.created is None: self.created = datetime.now() super(InputFieldGroup, self).save(*args, **kwargs) class Meta: db_table = 'crt_fieldgroups' ordering = ['profile_uuid', 'sort', ...
uvacw/tcst
lnparse.py
Python
gpl-3.0
1,302
0.050691
#!/usr/bin/env python # -*- coding: utf-8 -*- import re bestandsnaam="De_Telegraaf2014-03-22_22-08.TXT" artikel=0 tekst={} datum={} s
ection={} length={} loaddate={} language={} pubtype={} journal={} with open(bestandsnaam,"r") as f: for line in f: line=line.replace("\r","") if line=="\n": continue matchObj=re.match(r"\s+(\d+) of (\d+) DOCUMENTS",line) if matchObj: # print matchObj.group(1), "of", matchObj.group(2) artikel= int(mat...
st[artikel]="" continue if line.startswith("SECTION"): section[artikel]=line.replace("SECTION: ","").rstrip("\n") elif line.startswith("LENGTH"): length[artikel]=line.replace("LENGTH: ","").rstrip("\n") elif line.startswith("LOAD-DATE"): loaddate[artikel]=line.replace("LOAD-DATE: ","").rstrip("\n") ...
OHRI-BioInfo/pyZPL
web.py
Python
bsd-2-clause
1,418
0.004937
from flask import * from pyZPL import * from printLabel import printLabel import xml.etree.ElementTree as ET import os app = Flask(__name__) dn = os.path.dirname(os.path.realpath(__file__))+"/" tree = ET.parse(dn+"pace.xml") customElements = tree.findall(".//*[@id]") customItems = [] for element in customElements: ...
newItem.type = element.tag if element.g
et("fixed"): newItem.fixed = "readonly" customItems.append(newItem) @app.route('/') def root(): return render_template("index.html",items=customItems) @app.route('/print', methods=['POST']) def print_(): customItemsModified = [] if request.method == 'POST': for key,value in request...
waseem18/oh-mainline
vendor/packages/docutils/test/test_parsers/test_rst/test_directives/test_sidebars.py
Python
agpl-3.0
1,905
0.005249
#! /usr/bin/env python # $Id: test_sidebars.py 7062 2011-06-30 22:14:29Z milde $ # Author: David Goodger <[email protected]> # Copyright: This module has been placed in the public domain. """ Tests for the "sidebar" directive. """ from __init__ import DocutilsTestSupport def suite(): s = DocutilsTestSupport.Pa...
<title> Outer <system_message level="3" line="3" source="test data" type="ERROR"> <paragraph> The "si
debar" directive may not be used within a sidebar element. <literal_block xml:space="preserve"> .. sidebar:: Nested \n\ Body. """], ["""\ .. sidebar:: Margin Notes :subtitle: with options :class: margin :name: note:Options Body. """, """\ <docu...
zephyrplugins/zephyr
zephyr.plugin.jython/jython2.5.2rc3/Lib/test/test_mhlib.py
Python
epl-1.0
11,388
0.003864
""" Tests for the mhlib module Nick Mathewson """ ### BUG: This suite doesn't currently test the mime functionality of ### mhlib. It should. import unittest from test.test_support import is_jython, run_unittest, TESTFN, TestSkipped import os, StringIO import sys import mhlib if (sys.platform.startswith("...
] f.putsequences({'cur': [5], 'lowprime': lowprimes, 'lowcompos': lowcompos}) seqs = readFile(os.path.join(_mhpath, 'wide', '.mh_sequences')) seqs = sortLines(seqs) eq(seqs, ["cur: 5", "lowcompos: 6 8-10 12 14-16 18 20-22...
17 19 23 29"]) seqeq('lowprime', lowprimes) seqeq('lowprime:1', [5]) seqeq('lowpri
akun/pycon2015
tests/test_file_rw.py
Python
mit
1,886
0
#!/usr/bin/env python # coding=utf-8 import os import unittest from mock import mock_open, patch from pycon2015.file_rw import read_dollar, write_rmb class FileTestCase(unittest.TestCase): test_dir = os.path.dirname(os.path.abspath(__file__)) class FileReadTestCase(FileTestCase): def test_read(self)
: file_path = os.path.join(self.test_dir, 'money.txt') money_list = read_dollar(file_path) self.assertEqual(money_list, ['1', '2', '3', '4']) self.assertItemsEqual(money_list, ['4', '1', '2', '3']) def test_read_big_file(self): test_list = [str(i) for i in range(12345)] ...
open(read_data=os.linesep.join(test_list)) fake_path = '/it/is/a/fake/path' money_list = [] with patch('__builtin__.open', fake_open): money_list = read_dollar(fake_path) self.assertEqual(money_list, test_list) fake_open.assert_called_once_with(fake_path) class Fi...
dwfreed/mitmproxy
mitmproxy/proxy/protocol/websocket.py
Python
mit
7,347
0.002314
import os import socket import struct from OpenSSL import SSL from mitmproxy import exceptions from mitmproxy import flow from mitmproxy.proxy.protocol import base from mitmproxy.net import tcp from mitmproxy.net import websockets from mitmproxy.websocket import WebSocketFlow, WebSocketBinaryMessage, WebSocketTextMess...
ot self.channel.should_exit.is_set(): r = tcp.ssl_rea
d_select(conns, 0.1) for conn in r: source_conn = self.client_conn if conn == client else self.server_conn other_conn = self.server_conn if conn == client else self.client_conn is_server = (conn == self.server_conn.connection) ...
ESOedX/edx-platform
openedx/core/djangoapps/schedules/tests/factories.py
Python
agpl-3.0
1,310
0.000763
""" Factories for schedules tests """ from __future__ import absolute_import import factory import pytz from openedx.core.djangoapps.schedules import models from openedx.core.djangoapps.site_configuration.tests.factories import SiteFactory from student.tests.factories import CourseEnrollmentFactory class ScheduleEx...
) upgrade_deadline = factory.Faker('future_datetime', tzinfo=pytz.UTC) enrollm
ent = factory.SubFactory(CourseEnrollmentFactory) experience = factory.RelatedFactory(ScheduleExperienceFactory, 'schedule') class ScheduleConfigFactory(factory.DjangoModelFactory): class Meta(object): model = models.ScheduleConfig site = factory.SubFactory(SiteFactory) create_schedules = Tru...
peerdrive/peerdrive
client/peerdrive/struct.py
Python
gpl-3.0
10,142
0.033429
# vim: set fileencoding=utf-8 : # # PeerDrive # Copyright (C) 2011 Jan Klötzke <jan DOT kloetzke AT freenet DOT de> # # 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 Lic...
f (isinstance(base, basestring) or isinstance(base, bool) or isinstance(base, connector.RevLink) or isins
tance(base, connector.DocLink) or isinstance(base, float) or isinstance(base, (int, long))): changes = [o for o in versions if o != base] count = len(set(changes)) if count > 1: # take the latest change return (changes[0], True) elif count == 1: return (changes[0], False) else: return (base,...
smiller171/ansible
lib/ansible/module_utils/facts.py
Python
gpl-3.0
132,404
0.004955
# (c) 2012, Michael DeHaan <[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, either version 3 of the License, or # (at your option) any lat...
ld subclass Facts. """ # i86pc is a Solaris and derivatives-ism _I386RE = re.compile(r'i([3456]86|86pc)') # For the most part, we assume that platform.dist() will tell the truth. # This is the fallback to handle unknowns or exceptions OSDIST_LIST = ( ('/etc/oracle-release', 'OracleLinux'), ...
e', 'RedHat'), ('/etc/vmware-release', 'VMwareESX'), ('/etc/openwrt_release', 'OpenWrt'), ('/etc/system-release', 'OtherLinux'), ('/etc/alpine-release', 'Alpine'), ('/etc/release', 'Solaris'), ('/etc/...
bkosawa/admin-recommendation
admin_recommendation/urls.py
Python
apache-2.0
879
0
"""recomendation URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Cla...
r_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url, include...
de('crawler.urls')) ]
pkimber/invoice
invoice/tests/test_invoice_print.py
Python
apache-2.0
1,817
0
# -*- encoding: utf-8 -*- from datetime import date from dj
ango.test import TestCase from contact.tests.factories import ContactFactory from crm.tests.factories import TicketFactory from finance.tests.factories import VatSettingsFactory from invoice.models import InvoiceError from invoice.service import ( InvoiceCreate, InvoicePrint, ) from invoice.tests.factories imp...
, InvoiceLineFactory, InvoiceSettingsFactory, TimeRecordFactory, ) from login.tests.factories import UserFactory class TestInvoicePrint(TestCase): def test_invoice_create_pdf(self): InvoiceSettingsFactory() VatSettingsFactory() contact = ContactFactory() InvoiceContact...
mytliulei/DCNRobotInstallPackages
windows/win32/paramiko-1.14.0/tests/test_auth.py
Python
apache-2.0
8,501
0.001412
# Copyright (C) 2008 Robey Pointer <[email protected]> # # This file is part of paramiko. # # Paramiko is free software; you can redistribute it and/or modify it under the # terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 2.1 of the License, or (at you...
assword works. """ self.start_server() self.tc.connect(hostkey=self.public_host_key) try: self.tc.auth_password(username='slowdive', password='error') self.assertTrue(False) except: etype, evalue, etb = sys.exc_info() self.assertTru...
est_3_multipart_auth(self): """ verify that multipart auth works. """ self.start_server() self.tc.connect(hostkey=self.public_host_key) remain = self.tc.auth_password(username='paranoid', password='paranoid') self.assertEqual(['publickey'], remain) key = D...
icoxfog417/kanaria
tests/core/test_service_db.py
Python
apache-2.0
987
0.001013
import unittest from datetime import datetime from kanaria.core.service.db import MongoDBService class ModelExample(object): def __init__(self, title="", description="", date=None): self.title = title self.description = description self.date = date if date else datetime.now() self...
m) dic = db.object_to_dict(m) self.assertTrue("model_example", name) self.assertTrue(m.title, dic["title"]) self.asse
rtTrue(m.date, dic["date"]) self.assertFalse("_private" in dic) self.assertFalse("method" in dic) def test_get_collection(self): db = MongoDBService() collection = db.get_collection(ModelExample) self.assertTrue(collection)
katrid/keops
keops/report_urls.py
Python
bsd-3-clause
457
0.002188
from django.conf import settings from django.conf.urls import url import django.views.static from keops.api impor
t site import keops.views.reports urlpatterns = [ url(r'^web/reports/', keops.views.reports.dashboard), url(r'
^web/reports/view/', keops.views.reports.report), url(r'^api/reports/choices/', keops.views.reports.choices), url(r'^reports/temp/(?P<path>.*)$', django.views.static.serve, {'document_root': settings.REPORT_ROOT}) ]
hankcs/HanLP
hanlp/common/transform.py
Python
apache-2.0
15,235
0.000788
# -*- coding:utf-8 -*- # Author: hankcs # Date: 2020-05-03 14:44 import logging import os from abc import ABC, abstractmethod from typing import Tuple, Union, List from hanlp_common.constant import EOS, PAD from hanlp_common.structure import SerializableDict from hanlp_common.configurable import Config
urable from hanlp.common.vocab import Vocab from hanlp.utils.io_util import get_resource from hanlp_common.io import load_json from hanlp_common.reflection import classpath_of, str_to_type from hanlp.utils.string_util import ispunct class ToIndex(ABC): def __init__(self, vocab: Vocab = None) -> None: sup...
f save_vocab(self, save_dir, filename='vocab.json'): vocab = SerializableDict() vocab.update(self.vocab.to_dict()) vocab.save_json(os.path.join(save_dir, filename)) def load_vocab(self, save_dir, filename='vocab.json'): save_dir = get_resource(save_dir) vocab = SerializableD...
dgellis90/nipype
nipype/interfaces/freesurfer/base.py
Python
bsd-3-clause
6,473
0.000154
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """The freesurfer module provides basic functions for interfacing with freesurfer tools. Currently these tools are supported: * Dicom2Nifti: using mri_convert * Resample: using mri_convert Exam...
generated by suffixing inputs.infile
Parameters ---------- basename : string (required) filename to base the new filename on fname : string if not None, just use this fname cwd : string prefix paths with cwd, otherwise os.getcwd() suffix : string default suffix ...
deathowl/huey
huey/consumer.py
Python
mit
11,130
0.00027
import datetime import logging import os import signal import threading import time from multiprocessing import Event as ProcessEvent from multiprocessing import Process try: import gevent from gevent import Greenlet from gevent.event import Event as GreenEvent except ImportError: Greenlet = GreenEven...
registry import registry class BaseProcess(object): def __init__(self, huey, utc): self.huey = huey self.utc = utc def get_now(self):
if self.utc: return datetime.datetime.utcnow() return datetime.datetime.now() def sleep_for_interval(self, start_ts, nseconds): delta = time.time() - start_ts if delta < nseconds: time.sleep(nseconds - (time.time() - start_ts)) def enqueue(self, task): ...
davide-ceretti/DEPRECATED-googleappengine-djangae-skeleton
application/application/urls.py
Python
mit
309
0
from django.conf.urls import patterns, include, url from django.contrib import admin from application.crud import views urlpatterns = patterns(
'', url(r'^admin/', include(admin.site.urls)), url(r'^_ah/', include('djangae.urls')), url(r'^$', views.ItemCr
eateView.as_view(), name='index'), )
antong/ldaptor
ldaptor/protocols/ldap/proxy.py
Python
lgpl-2.1
3,381
0.001775
"""LDAP protocol proxy server""" from twisted.internet import reactor, defer from ldaptor.protocols.ldap import ldapserver, ldapconnector, ldapclient from ldaptor.protocols import pureldap class Proxy(ldapserver.BaseLDAPServer): protocol = ldapclient.LDAPClient client = None waitingConnect = [] unbou...
if self.client is None: d = defer.Deferred() self.waitingConnect.append((d, fn, a, kw)) return d else: return defer.maybeDeferred(fn, *a, **kw) def _cbConnectionMade(self, proto): self.client = proto while self.waitingConnect: ...
d) def _clientQueue(self, request, controls, reply): # TODO controls if request.needs_answer: d = self.client.send_multiResponse(request, self._gotResponse, reply) # TODO handle d errbacks else: self.client.send_noResponse(request) def _gotResponse(s...
greyshell/Pen-Test
web/sqli/models/__init__.py
Python
mit
120
0
#!/usr/bin/env python3 # author: greyshell from .tblpost01 impor
t * from .tblpost02
import * from .tblpost03 import *
probcomp/cgpm
src/cgpm.py
Python
apache-2.0
7,812
0.00064
# -*- coding: utf-8 -*- # Copyright (c) 2015-2016 MIT Probabilistic Computing Project # 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 # Unles...
corresponding to a single sample. """ raise NotImplementedError def logpdf_score(self): """Return joint density of all observations and current latent state.""" raise NotImplementedError def transition(self, **kwargs): """Apply an inference operator transitioning ...
tions on the learning mechanism, which may be based on optimization (variational inference, maximum likelihood, EM, etc), Markov chain Monte Carlo sampling (SMC, MH, etc), arbitrary heuristics, or others. """ raise NotImplementedError def to_metadata(...
RyanWolfe/cloud-custodian
c7n/resources/apigw.py
Python
apache-2.0
781
0.00128
# Copyright 2016 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...
License for the specific language governing permissions and # limitations under the License. from c7n.manager import resources from c7n.query import QueryResourceManager @resources.register
('rest-api') class RestAPI(QueryResourceManager): resource_type = "aws.apigateway.restapis"
dwalton76/rubiks-cube-NxNxN-solver
rubikscubennnsolver/RubiksCube444Misc.py
Python
mit
105,442
0.000009
# standard libraries from typing import Dict, Set, Tuple # 12-23 are high edges, make these U (1) # 0-11 are low edges, make these D (6) # https://github.com/cs0x7f/TPR-4x4x4-Solver/blob/master/src/FullCube.java high_edges_444: Tuple[Tuple[int, int, int]] = ( (14, 2, 67), # Upper (13, 9, 19), (15, 8, 51),...
35), (21, 25, 76), # Left (20, 24, 37), (23, 57, 44), # Right (22, 56, 69), (18, 82, 46), # Down (17, 89, 30), (19, 88, 62), (16, 95, 78), ) low_edges_444: Tuple[Tuple[int, int, int]] = ( (2, 3, 66), # Upper (1, 5, 18), (3, 12, 50), (0, 14, 34), (9, 21, 72), #...
(7, 92, 63), (4, 94, 79), ) # These apply to 4x4x4 and 5x5x5 highlow_edge_mapping_combinations: Dict[int, Tuple[Set[Tuple[str]]]] = { 0: (set()), 2: ( set(("UB", "UL")), set(("UB", "UR")), set(("UB", "UF")), set(("UB", "LB")), set(("UB", "LF")), set(("UB...
flgiordano/netcash
+/google-cloud-sdk/lib/surface/bigquery/__init__.py
Python
bsd-3-clause
2,500
0.0016
# Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
nitialize context for bigquery commands. Args: context: The current context. args: The argparse name
space that was specified on the CLI or API. Returns: The updated context. """ resources.SetParamDefault( api='bigquery', collection=None, param='projectId', resolver=resolvers.FromProperty(properties.VALUES.core.project)) # TODO(user): remove command dependence on these. cont...
ajdawson/jabr
lib/parser.py
Python
mit
2,590
0.002703
"""Parse ISI journal abbreviations website.""" # Copyright (c) 2012 Andrew Dawson # # 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 righ...
ser(HTMLParser): """Parser for ISI Web of Knowledge journal abbreviation pages. **Note:** Due to the ISI pages containing malformed html
one must call the :py:meth:`ISIJournalParser.finalize` method once parsing is complete to ensure all entries are read correctly. """ def __init__(self): HTMLParser.__init__(self) self.journal_names = [] self.journal_abbreviations = [] self.parser_state = Non...
brodyberg/autorest
AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Url/autoresturltestservice/__init__.py
Python
mit
714
0.002801
# 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 cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from .auto_rest_url_test_service import AutoRestUrlTestService, Aut...
'AutoRestUrlTestService', 'AutoRestUrlTestServiceConfiguration' ] __version__ = VERSION
alerta/alerta-contrib
plugins/prometheus/setup.py
Python
mit
663
0
from setuptools import setup, find_packages version = '5.4.0' setup( name="alerta-prometheus", version=version, description='Alerta plugin for Prometheus Alertmanager', url='https://github.com/alerta/alerta-contrib', license='MIT', author='Nic
k Satterly', author_email='[email protected]', packages=find_packages(), py_modules=['alerta_prometheus'], install_requires=[ 'requests', 'alerta-server>=4.10.1' ], include_package_data=True, zip_safe=Tr
ue, entry_points={ 'alerta.plugins': [ 'prometheus = alerta_prometheus:AlertmanagerSilence' ] } )
halilozercan/halocoin
halocoin/service.py
Python
apache-2.0
11,707
0.001452
import queue import sys import threading import traceback from halocoin import tools from halocoin.ntwrk.message import Order class NoExceptionQueue(queue.Queue): """ In some cases, queue overflow is ignored. Necessary try, except blocks make the code less readable. This is a special queue class that ...
|STOPPED|TERMINATED) -> () """ Set the current state of the service. This should never be used outside of the service. Treat as private method. :param state: New state :return: None """ if state == Service.STOPPED or state == Service.TERMINATED: ...
for thread_name in self.__threads.keys(): self.__threads[thread_name]["running"] = False self.__state = state def close_threaded(self): """ Close current side-thread. :return: None """ thread_name = threading.current_thread().name ...