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
eliksir/mailmojo-python-sdk
test/test_page_api.py
Python
apache-2.0
1,093
0
# coding: utf-8 """ MailMojo API v1 of the MailMojo API # noqa: E501 OpenAPI spec version: 1.1.0 Contact: [email protected] Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import unittest import mailmojo_sdk from mailmojo_sdk.api.pa...
age_api.PageApi
() # noqa: E501 def tearDown(self): pass def test_get_page_by_id(self): """Test case for get_page_by_id Retrieve a landing page. # noqa: E501 """ pass def test_get_pages(self): """Test case for get_pages Retrieve all landing pages. # noqa: E501...
chhantyal/exchange
uhura/exchange/utils.py
Python
bsd-3-clause
183
0.010929
""" Utilities and helper functions """ def get_object_or_none(model, **kwargs): try:
return model.objects.get(**kwargs) except model.DoesNotExist
: return None
MikeLing/shogun
examples/undocumented/python/classifier_gmnpsvm.py
Python
gpl-3.0
912
0.046053
#!/usr/bin/env python traindat = '../data/fm_train_real.dat' testdat = '../data/fm_test_real.dat' label_traindat = '../data/label_train_multiclass.dat' parameter_list = [[t
raindat,testdat,label_traindat,2.1,1,1e-5],[traindat,testdat,label_traindat,2.2,1,1e-5]] def classifier_gmnpsvm (train_fname=traindat,test_fname=testdat,label_fname=label_traindat,width=2.1,C=1,epsilon=1e-5): from shogun import RealFeatures, MulticlassLabels from shogun import GaussianKernel, GMNPSVM, CSVFile feat...
rain_fname)) feats_test=RealFeatures(CSVFile(test_fname)) labels=MulticlassLabels(CSVFile(label_fname)) kernel=GaussianKernel(feats_train, feats_train, width) svm=GMNPSVM(C, kernel, labels) svm.set_epsilon(epsilon) svm.train(feats_train) out=svm.apply(feats_test).get_labels() return out,kernel if __name__=='...
dhuang/incubator-airflow
airflow/example_dags/test_utils.py
Python
apache-2.0
1,172
0
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
ense. """Used for unit tests""" from airflow import DAG from airflow.operators.bash import BashOperator
from airflow.utils.dates import days_ago with DAG(dag_id='test_utils', schedule_interval=None, tags=['example']) as dag: task = BashOperator( task_id='sleeps_forever', bash_command="sleep 10000000000", start_date=days_ago(2), owner='airflow', )
Akylas/CouchPotatoServer
couchpotato/core/notifications/history/main.py
Python
gpl-3.0
732
0.01776
from couchpotato import get_session from couchpotato.core.helpers.encoding import toUnicode from couchpotato.core.logger import CPLog from couchpotato.core.notifications.base import Notification from couchpotato.core.settings.model import History as Hist import time log = CPLog(__name__) class History(Notification):...
notify(self, message = '', data = {}, listener = None): db = get_session() history = Hist( added = int(time.time()), message = toUnicode(message), release_id = data.g
et('id', 0) ) db.add(history) db.commit() #db.close() return True
Xion/recursely
recursely/__init__.py
Python
bsd-2-clause
1,663
0
""" recursely """ __version__ = "0.1" __description__ = "Recursive importer for Python submodules" __author__ = "Karol Kuczmarski" __license__ = "Simplified BSD" import sys from recursely._compat import IS_PY3 from recursely.importer import Recurs
iveImporter from recursely.utils import SentinelList __all__ = ['install'] def install(retroactive=True): """Install the recursive import hook in ``sys.meta_path``, enabling the use of ``__recursive__`` directive. :param retroactive: Whether the hook should be retroactively applied
to module's that have been imported before it was installed. """ if RecursiveImporter.is_installed(): return importer = RecursiveImporter() # because the hook is a catch-all one, we ensure that it's always # at the very end of ``sys.meta_path``, so that it...
ESSS/err
errbot/repo_manager.py
Python
gpl-3.0
9,791
0.001634
import logging import os import shutil import subprocess from collections import namedtuple from datetime import timedelta, datetime from os import path import tarfile from urllib.error import HTTPError, URLError from urllib.request import urlopen from urllib.parse import urlparse import json import re from errbot.p...
"" def __init__(self, storage_plugin, plugin_dir, plugin_indexes): """ Make a repo manager. :param storage_plugin: where the manager store its state. :param plugin_dir: where on disk it will git clone the repos. :param plugin_indexes: a list of URL / path to get the json repo...
__init__() self.plugin_indexes = plugin_indexes self.storage_plugin = storage_plugin self.plugin_dir = plugin_dir self.open_storage(storage_plugin, 'repomgr') def shutdown(self): self.close_storage() def check_for_index_update(self): if REPO_INDEX not in self: ...
lkouame/cs3240-labdemo
new.py
Python
mit
71
0.014085
#include h
eader def new_method(msg): greeting(msg) print(
msg)
platsch/OctoPNP
octoprint_OctoPNP/ImageProcessingCaller.py
Python
agpl-3.0
974
0.004107
# -*- coding: utf-8 -*- """ This file is part of OctoPNP This is a test script to execute the imageprocessing-steps independent from the main software and particularly without a running printer. Main author: Florens Wasserfall <[email protected]> """ import time import Ima
geProcessing im = ImageProcessing.ImageProcessing(15.0, 120, 120) start_time = time.time() im.SetInteractive(True) # im.locatePartInBox("../utils/testimages/head_atmega_SO8.png", False) # im.locatePartInBox("../utils/testimages/head_atmega_SO8_2.png", False) # print im.getPartOrientation("../utils/testimages/bed_at...
/testimages/orientation_bed_atmega_SO8_green.png", 55.65) # im.getPartPosition("../utils/testimages/orientation_bed_atmega_SO8_green.png", 55.65) # im.getPartOrientation("../utils/testimages/bed_resistor_1206.png", 55.65) end_time = time.time() print("--- %s seconds ---" % (time.time() - start_time))
gauravmm/gauravmanek.com
generators/bkggen.py
Python
mit
3,912
0.025562
#!/usr/bin/python3 import random import svgwrite from svgwrite import rgb def bkggen_square(name): # image size img_draw_sz = "6cm" img_cell_count = 24 img_cell_sz = 5 img_gutter_sz = 1 colors = [rgb(col, col, col) for col in [246, 248, 250, 252, 255]] dwg = svgwrite.Drawing(name, (img_draw_sz, img_draw_sz...
+ img_gutter_sz/2 color_band = [random.choice(colors) fo
r _Cx in range(img_cell_count)] if color_band_first is None: color_band_first = color_band elif _Cy == -1: color_band = color_band_first for _Cx, _fill in enumerate(color_band): _x = _Cx * (img_cell_sz + img_gutter_sz / 2) if _fill is not None: if (_Cx + _Cy) % 2 == 0: dwg.add(dwg.polygon(...
chris-clm09/bzflag
bzagents/pfAgent.py
Python
gpl-3.0
14,123
0.004178
#!/usr/bin/python -tt import sys import math import time from myPrint import * from bzrc import BZRC, Command ###########################Potential Field Fun############################################ #################################################################### # Distance between two points. ##############...
d) * dx, b * (s + r - d) * dy) elif d > s+r: temp = (0, 0) return temp #################################################################### # Calculate repulsive fields on a given location. #################################################################### def generate_repulsive_field(x, y, obs...
or o in obstacles: temp = generate_a_repulsive_field(x, y, o) total[0] += temp[0] total[1] += temp[1] return total #################################################################### # Generate a single attractive vector. ##########################################################...
LiqunHu/MVPN
complineProj.py
Python
gpl-3.0
143
0.006993
# -*- coding: utf-8 -*- """ Created on Thu Jul 21
16:48:46 2016 @author: huliqun """ import compileal
l compileall.compile_dir('..')
mpiplani/Online-Pharmacy
online_pharmacy/online_pharmacy/urls.py
Python
apache-2.0
542
0.01476
from django.conf.urls import url,include from django.contrib import admin urlpatterns = [ url(r'^
',include('Register_and_login.urls')), url(r'^homepage/',include('MainPage.urls')), url(r'^username/cart/',include('cart.urls')), url(r'^username/',include('customer.urls')), url(r'^pharmacy_name/',include('pharmacy.ur
ls')), url(r'^pharmacy_name/inventory',include('inventory.urls')), url(r'^search/all_search=pcm',include('items.urls')), url(r'^', include('order.urls')), url(r'^admin/', admin.site.urls) ]
mjuenema/nomit
setup.py
Python
bsd-2-clause
902
0.02439
with open('README.txt') as f: long_description = f.read() from distutils.core import setup setup( name
= "nomit", packages = ["nomit"], version = "1.0", description = "Process Monit HTTP/XML", author = "Markus Juenemann", author_email = "[email protected]", url = "https://github.com/mjuenema/nomit", download_url = "https://github.com/mjuenema/nomit/tarball/1.0", keywords = ["xml", "Mo...
- Beta", "Environment :: Other Environment", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Operating System :: OS Independent", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: System :: Monitoring", ], ...
pi19404/mbed
workspace_tools/export/gccarm.py
Python
apache-2.0
3,520
0
""" mbed SDK Copyright (c) 2011-2013 ARM 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 agreed to in wr...
152RC', 'EFM32WG_STK3800', 'EFM32LG_STK3600', 'EFM32GG_STK3700', 'EFM32ZG_STK3200', 'EFM32HG_STK3400', 'NZ32SC151',
'SAMR21G18A', 'TEENSY3_1', ] DOT_IN_RELATIVE_PATH = True def generate(self): # "make" wants Unix paths self.resources.win_to_unix() to_be_compiled = [] for r_type in ['s_sources', 'c_sources', 'cpp_sources']: r = getattr(self.resources, r_type) ...
ktok07b6/polyphony
tests/if/if28.py
Python
mit
922
0
from polyphony import testbench def g(x):
if x == 0: return 0 return 1 def h(x): if x == 0: pass def f(v, i, j, k): if i == 0: return v elif i == 1: return v elif i == 2: h(g(j) + g(k)) return v elif i == 3: for m in range(j): v += 2 return v else: ...
v += 1 return v def if28(code, r1, r2, r3, r4): if code == 0: return f(r1, r2, r3, r4) return 0 @testbench def test(): assert 1 == if28(0, 1, 1, 0, 0) assert 2 == if28(0, 2, 0, 0, 0) assert 3 == if28(0, 3, 1, 0, 0) assert 4 == if28(0, 4, 2, 0, 0) assert 5 == if28(0,...
botswana-harvard/edc-dashboard
edc_dashboard/middleware.py
Python
gpl-2.0
1,322
0.007564
from django.conf import settings from edc_constants.constants import MALE, FEMALE, OTHER, YES, NO, NOT_APPLICABLE from edc_constants.constants import NEW, OPEN, CLOSED class DashboardMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(sel
f, request): try: request.url_name_data except AttributeError: request.url_name_data = {} try: request.template_data except AttributeError: request.template_data = {} response = self.get_response(request) return response ...
esponse(self, request, response): try: reviewer_site_id = settings.REVIEWER_SITE_ID except AttributeError: reviewer_site_id = None options = {'OPEN':OPEN, 'CLOSED':CLOSED, 'FEMALE':FEMALE, 'NEW':NEW, ...
opennode/nodeconductor-assembly-waldur
src/waldur_auth_valimo/client.py
Python
mit
9,636
0.002283
import logging from urllib.parse import urljoin import lxml.etree # noqa: S410 import requests from django.conf import settings as django_settings from django.utils import timezone logger = logging.getLogger(__name__) class ClientError(Exception): pass class ResponseParseError(ClientError): pass class ...
MSS_Format> </MSS_SignatureReq> </MSS_Signature> </soapenv:Body> </soapenv:Envelope> ""
" response_class = SignatureResponse @classmethod def execute(cls, transaction_id, phone, message): kwargs = { 'MessagingMode': 'asynchClientServer', 'AP_TransID': cls._format_transaction_id(transaction_id), 'MSISDN': phone, 'DataToBeSigned': '%s %s' ...
EdisonAlgorithms/HackerRank
practice/data-structures/heap/find-median-1/find-median-1.py
Python
mit
1,239
0.008071
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author: Zeyuan Shang # @Date: 2015-12-01 01:05:22 # @Last Modified by: Zeyuan Shang # @Last Modified time: 2015-12-01 01:05:37 import heapq class MedianFinder: def __init__(self): """ Initialize your data structure here. """ self....
m(self, num): """ Adds a num into the data structure. :type num: int :rtype: void """ if len(self.smallHeap) == len(self.largeHeap): heapq.heappush(self.largeHeap, -heapq.heappushpop(self.smallHeap, -num)) else:
heapq.heappush(self.smallHeap, -heapq.heappushpop(self.largeHeap, num)) def findMedian(self): """ Returns the median of current data stream :rtype: float """ if len(self.smallHeap) == len(self.largeHeap): return float(self.largeHeap[0] - self.small...
KuraudoTama/jenkins-events-handlers
event_handler.py
Python
apache-2.0
371
0.013477
import threading import log
ging import json class EventHandler(threading.Thread): log = logging.getLogger("events.EventHandler") def __init__(self,event): self.event=event.split(None)[0] self.data = json.loads(event.lstrip(self.event).lstrip()) threading.Thread.__init__(self
, name="EventHandler for event: <%s>" % event)
stackforge/networking-bagpipe-l2
networking_bagpipe/tests/unit/agent/sfc/test_agent_extension.py
Python
apache-2.0
54,420
0
# Copyright (c) 2017 Orange. # 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 a...
stLinuxBridgeAgentExtension): agent_extension_class = bagpipe_agt_ext.BagpipeSfcAgentExtension def setUp(self): super(TestSfcAgentExtension, self).setUp()
self.mocked_bulk_rpc = mock.patch.object( self.agent_ext._pull_rpc, 'bulk_pull').start() @mock.patch.object(registry, 'register') @mock.patch.object(resources_rpc, 'ResourcesPushRpcCallback') def test_initialize_rpcs(self, rpc_mock, subscribe_mock): self.agent_ext.initialize(self...
lcgong/sqlblock
sqlblock/setup.py
Python
mit
372
0.002688
import sys from sqlblock.postgres.connection import AsyncPostgresSQL def aiohttp_set
up_sqlblock(app, conn: AsyncPostgresSQL): async def startup(app): await conn.__aenter__() async def shutdown(app): await conn.__aexit__(*sys.exc_info()) print('closed sqlblock') app.on_startup.append(startup) app.on_cleanup.append(shutdown)
xzturn/caffe2
caffe2/python/toy_regression_test.py
Python
apache-2.0
2,822
0
import numpy as np import unittest from caffe2.python import core, workspace, test_util class TestToyRegression(test_util.TestCase): def testToyRegression(self): """Tests a toy regression end to end. The test code carries a simple toy regression in the form y = 2.0 x1 + 1.5 x2 + 0.5 ...
Fill([], "B_gt", shape=[1], values=[0.5]) LR = init_net.ConstantFill([], "LR", shape=[1], value=-0.1) ONE = init_net.ConstantFill([], "ONE", shape=[1], value=1.) ITER = init_net.ConstantFill([], "ITER", shape=[1], value=0, dtype=core.DataType.INT32) ...
nFill([], "X", shape=[64, 2], mean=0.0, std=1.0) Y_gt = X.FC([W_gt, B_gt], "Y_gt") Y_pred = X.FC([W, B], "Y_pred") dist = train_net.SquaredL2Distance([Y_gt, Y_pred], "dist") loss = dist.AveragedLoss([], ["loss"]) # Get gradients for all the computations above. Note that in fact w...
bcb/qutebrowser
tests/integration/features/test_tabs.py
Python
gpl-3.0
1,049
0
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: # Copyright 2015-2016 Florian Bruhin (The Compiler) <[email protected]> # # This file is part of qutebrowser. # # qutebrowser 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 S...
have received a copy of the GNU General Public License # along with qutebrowser. If not, see <http://www.gnu.org/licenses/>. import pytest_bdd as bdd bdd.scenarios('tabs.feature') @bdd.given("I clean up open tabs") def clean_open_tabs(quteproc): quteproc.set_setting('tabs', 'last-close', 'blank') quteproc.s...
cmd(':tab-only') quteproc.send_cmd(':tab-close')
BogdanWDK/ajaxbot
src/files/isup.py
Python
gpl-2.0
433
0.013857
#!/usr/bin/env python import re import sys fr
om urllib import urlopen def isup(domain): resp = urlopen("http://www.isup.me/%s" % domain).read() return "%s
" % ("UP" if re.search("It's just you.", resp, re.DOTALL) else "DOWN") if __name__ == '__main__': if len(sys.argv) > 1: print "\n".join(isup(d) for d in sys.argv[1:]) else: print "usage: %s domain1 [domain2 .. domainN]" % sys.argv[0]
abstract-open-solutions/l10n-italy
l10n_it_ateco/__openerp__.py
Python
agpl-3.0
1,563
0
# -*- encoding: utf-8 -*- ############################################################################## # # Copyright (C) 2014 Ab
stract # (<http://abstract.it>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This pro...
FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ###############################################################...
benguillet/wmr-frontend
lib/thrift/Thrift.py
Python
apache-2.0
3,530
0.027479
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
lif fid == 2:
if ftype == TType.I32: self.type = iprot.readI32(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): oprot.writeStructBegin('TApplicationException') if self.message != None: opro...
MSLNZ/msl-qt
msl/examples/qt/show_standard_icons.py
Python
mit
5,135
0.000584
""" Display all the icons available in :obj:`QtWidgets.QStyle.StandardPixmap` and in the *standard* Windows DLL/EXE files. """ from msl.qt import ( QtWidgets, QtCore, application, convert ) try: # check if pythonnet is installed import clr has_clr = True except ImportError: has_clr = Fa...
setIcon(ico) button.clicked.c
onnect(lambda *args, ic=ico, n=i: self.zoom(ic, n)) layout.addWidget(button, count // num_cols, count % num_cols) count += 1 self.num_icons += 1 tab.setLayout(layout) self.file_index += 1 self.progress_bar.setValue(self.file_index) def add_windows_tab(...
awalls-cx18/gnuradio
gr-uhd/examples/python/freq_hopping.py
Python
gpl-3.0
9,480
0.001793
#!/usr/bin/env python # # Copyright 2014,2019 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your optio...
class FrequencyHopperSrc(gr.hier_block2): """ Provides tags for frequency hopping """ def __init__( self, n_bursts, n_channels, freq_delta, base_freq, dsp_tuning,
burst_length, base_time, hop_time, post_tuning=False, tx_gain=0, verbose=False ): gr.hier_block2.__init__( self, "FrequencyHopperSrc", gr.io_signature(1, 1, gr.sizeof_gr_complex), gr.io_signature(1, 1, gr.sizeof_gr_complex), ...
alfasin/st2
st2actions/st2actions/utils/param_utils.py
Python
apache-2.0
14,817
0.002767
# Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use th...
e): continue if param_name in actionexec_action_parameters and param_name not in runner_parameters: resolved_params[param_name] = actionexec_action_parameters[param_name] return resolved_params
def get_resolved_params(runnertype_parameter_info, action_parameter_info, actionexec_parameters): ''' Looks at the parameter values from runner, action and action execution to fully resolve the values. Resolution is the process of determinig the value of a parameter by taking into consideration defaul...
argriffing/cvxpy
cvxpy/atoms/norm1.py
Python
gpl-3.0
735
0
""" Copyright 2013 Steven Diamond This file is part of CVXPY. CVXPY is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. CVXPY is distributed i...
ill 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 cop
y of the GNU General Public License along with CVXPY. If not, see <http://www.gnu.org/licenses/>. """ from cvxpy.atoms.pnorm import pnorm def norm1(x): return pnorm(x, 1)
hainm/pythran
pythran/analyses/imported_ids.py
Python
bsd-3-clause
2,844
0
""" ImportedIds gathers identifiers imported by a node. """ from pythran.analyses.globals_analysis import Globals from pythran.analyses.locals_analysis import Locals from pythran.passmanager import NodeAnalysis import pythran.metadata as md import ast class ImportedIds(NodeAnalysis): """Gather ids referenced b...
opy() self.current_locals.update(arg.id for arg in node.args.args) map(self.visit, node.body) self.current_locals = current_locals def visit_AnyComp(self, node): current_locals = self.current_loca
ls.copy() map(self.visit, node.generators) self.visit(node.elt) self.current_locals = current_locals visit_ListComp = visit_AnyComp visit_SetComp = visit_AnyComp visit_DictComp = visit_AnyComp visit_GeneratorExp = visit_AnyComp def visit_Assign(self, node): # order ...
mobiusklein/brainpy
brainpy/__init__.py
Python
apache-2.0
1,839
0.005982
''' A Python Implementation of the Baffling Recursive Algorithm for Isotopic cluster distributioN ''' import os from .brainpy import (isotopic_variants, IsotopicDistribution, periodic_table, max_variants, calculate_mass, neutral_mass, mass_charge_ratio, PROTON, _has_c, Peak)...
s` versions of the existing classes. As this implementation still spends a substantial amount of time in Python-space, it is slower than the option below, but is more straight-forward to manipu
late from Python. The `_c` module is a complete rewrite of the algorithm directly in C, using Python only to load mass configuration information and is fully usable. It exports an entrypoint function to Python which replaces the :func:`isotopic_variants` function when available. Because almost all of the ...
davidfoerster/schema-matching
src/schema_matching/collector/probability.py
Python
mit
748
0.032086
from .base import ItemCollector class BaseProbabilityCollector(ItemCollector): # result_dependencies = (*CountCollector, *FrequencyCollector) def __init__(self, previous_collector_set): super().__init__(previous_collector_set) self.__cached_result = None def get_result(self, collector_set): if self.
__cached_result is None: self.__cached_result = \ collector_set[self.result_dependencies[1]].get_result(collector_set) \ .normalize(collector_set[self.result_dependencies[0]] \ .get_result(collector_set)) return
self.__cached_result def as_str(self, collector_set, number_fmt=''): return format(self.get_result(collector_set), number_fmt) @staticmethod def result_norm(a, b): return a.distance_to(b)
darksteelcode/authorship
features/base.py
Python
gpl-3.0
1,482
0.006748
import numpy as np #numpy is used for later classifiers #Note: this is just a template with all required methods #text is the text represented as a string #textName is optional, indicate sthe name of the text, used for debug #args are aditional arguments for the feature calculator #debug indicates wheter to display deb...
e(): def __init__(self, text, textName="", args=[], debug=True): self.text = text.lower() self.args = args self.debug = debug self.textName = textName #Features, not yet
calculated self.f = np.array([]) def debugStart(self): if self.debug: print "--BaseFeatures--" def beginCalc(self): if self.debug: print "Feature calculation begining on " + self.textName print "------" def endCalc(self): if self.debug:...
GoogleCloudPlatform/solutions-google-compute-engine-cluster-for-hadoop
sample/shortest-to-longest-reducer.py
Python
apache-2.0
2,023
0.007909
#!/usr/bin/env python # Copyright 2013 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 ...
input line. Args: line: Input line. """ # Split input to key and value. key = line.split('\t', 1)[0] # Split key to word-length and word. word = key.split(':', 1)[1] if not self.current_word: self.current_word = Word(word) elif self.current_word.word != word: self.cu...
testToLongestReducer() for line in input_lines: reducer.ProcessLine(line) reducer.PrintCurrentWord() if __name__ == '__main__': main(sys.stdin)
mishravikas/geonode-cas
geonode/contrib/groups/tests.py
Python
gpl-3.0
15,540
0.00251
import json from django.contrib.auth import get_backends from django.contrib.auth.models import User, AnonymousUser from django.core.urlresolvers import reverse from django.test import TestCase from django.test.client import Client from geonode.contrib.groups.models import Group, GroupInvitation from geonode.documents....
Layer) self.assertTrue(layer.id in read_perms) self.assertTrue(layer.id not in write_perms) # Make sure Norman is not in the bar group. self.assertFalse(self.bar.user_is_member(self.norman)) # Add norman to the bar group. self.bar.join(self.norman) # Ensure No...
er(self.norman)) # Test that the bar group has default permissions on the layer bar_read_perms = backend.objects_with_perm(self.bar, 'layers.view_layer', Layer) bar_write_perms = backend.objects_with_perm(self.bar, 'layers.change_layer', Layer) self.assertTrue(layer.id in bar_read_perms...
JazzeYoung/VeryDeepAutoEncoder
pylearn2/pylearn2/datasets/hdf5_deprecated.py
Python
bsd-3-clause
13,414
0
""" Objects for datasets serialized in HDF5 format (.h5). """ __author__ = "Steven Kearnes" __copyright__ = "Copyright 2014, Stanford University" __license__ = "3-clause BSD" try: import h5py except ImportError: h5py = None import numpy as np from theano.compat.six.moves import xrange import warnings from py...
cept: * HDF5ViewConverter is used instead of DefaultViewConverter * Data specs are derived f
rom topo_view, not X * NaN checks have been moved to HDF5DatasetIterator.next Note that y may be loaded into memory for reshaping if y.ndim != 2. Parameters ---------- V : ndarray Topological view. axes : tuple, optional (default ('b', 0, 1, 'c')) ...
google-research/understanding-curricula
third_party/__init__.py
Python
apache-2.0
616
0.001623
# Copyright 2021 Google LLC
# # Licensed under the Apache License, Version 2.0 (the "License"); # you may no
t use this file except in compliance with the License. # You may obtain a copy of the License at # # https://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 CONDITI...
cstipkovic/spidermonkey-research
js/src/devtools/rootAnalysis/analyze.py
Python
mpl-2.0
10,455
0.003922
#!/usr/bin/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/. """ Runs the static rooting analysis """ from subprocess import Popen import subprocess import os ...
le, 'w') if config['verbose']: print_command(command, outfile=outfile, env=env(config)) jobs.append((command, Popen(command, stdout=output, env=env(config)))) final_status = 0 while jobs: pid, status = os.wait() jobs = [ job f
or job in jobs if job[1].pid != pid ] final_status = final_status or status if final_status: raise subprocess.CalledProcessError(final_status, 'analyzeRoots.js') with open(outfilename, 'w') as output: command = ['cat'] + [ 'rootingHazards.%s' % (i+1,) for i in range(int(config['jobs'])...
whiplash01/Hyperloop
docs/xdsm/hyperloop_xdsm.py
Python
apache-2.0
1,244
0.006431
from XDSM import XDSM opt = 'Optimization' dat = 'DataInter' mda = 'MDA' anl = 'Analysis' x = XDSM() #x.addComp('driver', mda, 'Solver') x.addComp('assembly inputs', anl, 'assembly inputs') x.addComp('compress', anl, 'compress') x.addComp('mission', anl, 'mission') x.addComp('pod', anl, 'pod') x.addComp('flow_limit',...
all\_temp') x.addDep('mission', 'compress', dat, '', stack=True) x.addDep('pod', 'compress', dat, '', stack=True) x.addDep('pod', 'mission', dat, '', stack=True) x.addDep('flow_limit', 'pod', dat, '', stack=True) x.addDep('tube_wall_temp', 'compress', dat
, '', stack=True) #reverse couplings x.addDep('compress', 'flow_limit', dat, '', stack=True) x.addDep('compress', 'tube_wall_temp', dat, '', stack=True) x.addDep('compress', 'pod', dat, '', stack=True) #assembly inputs x.addDep('compress', 'assembly inputs', dat, '', stack=True) x.addDep('mission', 'assembly inputs',...
shawndaniel/evernote-exporter
evernote_exporter.py
Python
gpl-3.0
10,506
0.001523
from fnmatch import fnmatch import os from sys import exit import html2text import re import urllib import shutil import logging import sqlite3 from sys import stdout logging.basicConfig(filename='error_log.log', filemode='a') class BackupEvernote(object): def __init__(self, evernote_dir, db_dir='', output_dir...
te3.connect(self.db_dir) notebooks = con.execute("SELECT * FROM notebook_attr;").fetchall() folder_chars = self.forbidden del folder_chars[2] for ind, i in enumerate(notebooks): nb_id, notebook, stack = i[0], i[1], i[2] stack = self._remove_chars(stack, folder_c...
chars) nb_notes = con.execute('SELECT * FROM note_attr WHERE note_attr.notebook_uid = %s;' % nb_id) notes_set = {i[1] for i in nb_notes} s_dir = '' if notebook and not stack: notebook_dir = self.output_dir + '/' + notebook if not os.path....
Nvizible/shotgunEvents
src/daemonizer.py
Python
mit
5,101
0.006077
#!/usr/bin/env python # Taken and modified from: # http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/ import atexit import os import signal import sys import time if (hasattr(os, "devnull")): DEVNULL = os.devnull else: DEVNULL = "/dev/null" class Daemon(object): """ A gene...
idfile) sys.exit(1) # Start the daemon if daemonize: self._daemonize() # Cleanup handling def termHandler(signum, frame): self._delpid() signal.signal(signal.SIGTERM, termHandl
er) atexit.register(self._delpid) # Run the daemon self._run() def stop(self): """ Stop the daemon """ # Get the pid from the pidfile try: pf = file(self._pidfile,'r') pid = int(pf.read().strip()) pf.cl...
xuru/pyvisdk
pyvisdk/do/extended_element_description.py
Python
mit
1,021
0.008815
import logging
from pyvisdk.exceptions import InvalidArgumentError ######################################## # Automatically generated, do not edit. ######################################## log = logging.getLogger(__name__) def ExtendedElementDescription(vim, *args, **kwargs):
'''''' obj = vim.client.factory.create('ns0:ExtendedElementDescription') # do some validation checking... if (len(args) + len(kwargs)) < 4: raise IndexError('Expected at least 5 arguments got: %d' % len(args)) required = [ 'messageCatalogKeyPrefix', 'key', 'label', 'summary' ] option...
aurelo/lphw
source/ex9.py
Python
mit
413
0
days = "Mon Tue Wed Thu Fri Sat Sun" months = "Jan\nFeb\nMar\nApr\n...\nSpe\nNov\nDec" print "Here are the days:",
days print "Here are the months:", months print "Months: %r" % months # raw printing retains special characters print ''' There's something going on here with the three double quotes We'll be able
to type as much as we like Even 4 lines if we want, or 5, or 6 ''' print """ this works too """
nth10sd/lithium
src/lithium/interestingness/timed_run.py
Python
mpl-2.0
5,962
0.000335
# coding=utf-8 # # 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 https://mozilla.org/MPL/2.0/. """Run a subprocess with timeout """ import argparse import collections import platform import signal ...
elapsedtime, killed, out, err, pid", ) class ArgumentParser(argparse.ArgumentParser): """Argument parser with `timeout` and `cmd_with_args`""" def __init__(self, *args, **kwds) -> None: # type: ignore super().__init__(
*args, **kwds) self.add_argument( "-t", "--timeout", default=120, dest="timeout", type=int, help="Set the timeout. Defaults to '%(default)s' seconds.", ) self.add_argument("cmd_with_flags", nargs=argparse.REMAINDER) def ge...
doismellburning/django
tests/contenttypes_tests/tests.py
Python
bsd-3-clause
16,513
0.001635
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.apps.registry import Apps, apps from django.contrib.contenttypes.fields import ( GenericForeignKey, GenericRelation ) from django.contrib.contenttypes import management from django.contrib.contenttypes.models import ContentType from django...
tp://...", "https://..." and "//..." """ for obj in SchemeIncludedURL.objects.all(): short_url = '/shortcut/%s/%s/' % (ContentType.objects.get_for_model(SchemeIncludedURL).id, obj.pk)
response = self.client.get(short_url) self.assertRedirects(response, obj.get_absolute_url(), status_code=302, fetch_redirect_response=False) def test_shortcut_no_absolute_url(self): "Shortcuts for an object that has no ...
171121130/SWI
venv/Lib/site-packages/openpyxl/reader/__init__.py
Python
mit
35
0
# Copyright (c) 2010
-2017 ope
npyxl
paulsmith/geodjango
tests/regressiontests/cache/tests.py
Python
bsd-3-clause
5,938
0.007943
# -*- coding: utf-8 -*- # Unit tests for cache framework # Uses whatever cache backend is set in the test settings file. import time import unittest from django.core.cache import cache from django.utils.cache import patch_vary_headers from django.http import HttpResponse # functions/classes for complex data type tes...
assertEqual(cache.has_key("goodbye1"), False) def test_in(self): cache.set("hello2", "goodbye2") self.assertEqual("hello2" in cache, True) self.assertEqual("goodbye2" in cache, False) def test_data_types(self): stuff = { 'string' : 'this is a string', ...
: [1, 2, 3, 4], 'tuple' : (1, 2, 3, 4), 'dict' : {'A': 1, 'B' : 2}, 'function' : f, 'class' : C, } cache.set("stuff", stuff) self.assertEqual(cache.get("stuff"), stuff) def test_expiration(self): cache.set('expire1', 'ver...
golaizola/pelisalacarta-xbmc
core/scrapertools.py
Python
gpl-3.0
52,267
0.011898
#------------------------------------------------------------ # -*- coding: utf-8 -*- #------------------------------------------------------------ # Download Tools # Based on the code from VideoMonkey XBMC Plugin #------------------------------------------------------------ # pelisalacarta # http://blog.tvalacarta.in...
ene los handlers del fichero en la cache cachedFile, newFile = getCacheFileNames(url) # Si no hay ninguno, descarga if cachedFile == "": logger.debug("[scrapertools.py] No está en cache") # Lo descarga data = downloadpage(url,post,headers) ...
logger.info("[scrapertools.py] Grabado a " + newFile) # Si sólo hay uno comprueba el timestamp (hace una petición if-modified-since) else: # Extrae el timestamp antiguo del nombre del fichero oldtimestamp = time.mktime( time.strptime(cachedFile[-20:-6], "%Y%m%d%H%M%S") ) ...
conan-io/conan-package-tools
cpt/test/integration/base.py
Python
mit
1,994
0.001003
import os import unittest from conans.util.files import mkdir_tmp from conans import __version__ as client_version from conans import tools from conans.client.conan_api import ConanAPIV1 from cpt.test.utils.tools import TestBufferConanOutput CONAN_UPLOAD_URL = os.getenv("CONAN_UPLOAD_URL", ...
ut = TestBufferConanOutput() self.api, _, _ = ConanAPIV1.factory() self.api.create_app() self.client_cache = self.api.app.cache def tearDown(self): os.chdir(self.old_folder) os.environ.clear() os.environ.update(self.old_env) def save_conanfile(self, conanfile): ...
tools.save(os.path.join(self.tmp_folder, "conanfile.py"), conanfile) def create_project(self): with tools.chdir(self.tmp_folder): if tools.Version(client_version) >= "1.32.0": self.api.new("hello/0.1.0", pure_c=True, exports_sources=True) else: ...
SirRujak/SirBot
dev/TOPSECRET/SirBot/SirBot.py
Python
mit
1,743
0.018933
# -*- coding: utf-8 -*- #main sirbot script ON = 1 SPLASH = 1 ##try: import lib.sirbot.initialize as initialize if(SPLASH == 1): #display splash splash = initialize.splashing() root = splash.root() #import configurations f
rom lib.sirbot.configloader import configloader config = configloader() #import main runtime classes from lib.sirbot.application i
mport application if(config['GUI'] == 1): from lib.sirbot.interfaceDEV import interface from lib.sirbot.assetloader import assetloader #import shutdown module from lib.sirbot.shutdown import shutdown #import tools from multiprocessing import Queue from time import sleep if __name__ == '__main__': #ini...
GeoscienceAustralia/eo-datasets
eodatasets3/model.py
Python
apache-2.0
3,589
0.001115
from pathlib import Path from typing import Tuple, Dict, Optional, List, Union from uuid import UUID import affine import attr from ruamel.yaml.comments import CommentedMap from shapely.geometry.base import BaseGeometry from eodatasets3.properties import Eo3Dict, Eo3Interface DEA_URI_PREFIX = "https://collections.de...
for metadata access:: >>> p = DatasetDoc() >>> p.platform = 'LANDSAT_8' >>> p.processed = '2018-04-03' >>> p.properties['odc:processing_datetime'] datetime.da
tetime(2018, 4, 3, 0, 0, tzinfo=datetime.timezone.utc) """ #: Dataset UUID id: UUID = None #: Human-readable identifier for the dataset label: str = None #: The product name (local) and/or url (global) product: ProductDoc = None #: Location(s) where this dataset is stored. #: #...
boriel/zxbasic
src/arch/z80/backend/runtime/datarestore.py
Python
gpl-3.0
274
0
# Run
time labels from .namespace import NAMESPACE class DataRestoreLabels: READ = f"{NAMESPACE}.__READ" RESTORE = f"{NAMESPACE}.__RESTORE" REQUIRED_MODULES = { DataRestoreLabels.
READ: "read_restore.asm", DataRestoreLabels.RESTORE: "read_restore.asm", }
nijel/weblate
weblate/utils/requests.py
Python
gpl-3.0
2,265
0
# # Copyright © 2012–2022 Michal Čihař <[email protected]> # # This file is part of Weblate <https://weblate.org/> # # 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 Found
ation, 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 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...
hello-base/web
apps/history/models.py
Python
apache-2.0
1,311
0.001526
from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models from model_utils import Choices from model_utils.models import TimeStampedModel class History(TimeStampedModel): RESOLUTIONS = Choices('second', 'minute', 'hour...
sNotExist: pass else: self.del
ta = self.sum - previous.sum super(History, self).save(*args, **kwargs)
SMALLplayer/smallplayer-image-creator
storage/.xbmc/addons/script.module.urlresolver/lib/urlresolver/plugins/vidhog.py
Python
gpl-2.0
4,269
0.008433
''' Vidhog urlresolver plugin Copyright (C) 2013 Vinnydude This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is dis...
time.sleep(3) kb = xbmc.Keyboard('', 'Type the letters in the image', False) kb.doModal()
capcode = kb.getText() if (kb.isConfirmed()): userInput = kb.getText() if userInput != '': capcode = kb.getText() elif userInput == '': raise Exception ('Yo...
vijaykumar0690/security_monkey
security_monkey/watchers/security_group.py
Python
apache-2.0
8,192
0.001831
# Copyright 2014 Netflix, 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...
"name": sg.name, "description": sg.description, "vpc_id": sg.vpc_id, "owner_id": sg.owner_id, "region": sg.region.name, "rules": [], "a
ssigned_to": None } for rule in sg.rules: for grant in rule.grants: rule_config = { "ip_protocol": rule.ip_protocol, "from_port": rule.from_port, ...
feng-zhe/ZheQuant-brain-python
zq_calc/inc_pct.py
Python
apache-2.0
2,959
0.005069
''' This module contains calculator to calculate the increased percentage ''' import json import datetime import pytz import zq_gen.str as zq_str import zq_db.mongodb as zq_mgdb key_err_msg = 'Missing parameter in command string' val_err_msg = 'Error in parsing the command string' no_rcrd_msg = 'No records in specifi...
except ValueError: return val_err_msg begin_value =
0 end_value = 0 for code, num in compo.items(): begin_doc = zq_mgdb.get_single_stock_data(code, begin) end_doc = zq_mgdb.get_single_stock_data(code, end) if not begin_doc or not end_doc: return no_rcrd_msg begin_value += begin_doc['close'] * num end_value += ...
3liz/QgisQuickOSMPlugin
QuickOSM/definitions/format.py
Python
gpl-2.0
657
0.001522
"""Definitions for ou
tput formats.""" import collections from enum imp
ort Enum, unique __copyright__ = 'Copyright 2021, 3Liz' __license__ = 'GPL version 3' __email__ = '[email protected]' format_output = collections.namedtuple('format', ['label', 'driver_name', 'extension']) @unique class Format(Enum): """ Name of output formats.""" GeoJSON = format_output('GeoJSON', 'GeoJSON', ...
paralab/Dendro4
slurm/slurm_pbs.py
Python
gpl-2.0
2,491
0.028904
# @author: Milinda Fernando # School of Computing, University of Utah. # generate all the slurm jobs for the sc16 poster, energy measurements, import argparse if __name__ == "__main__": parser = argparse.ArgumentParser(prog='slurm_pbs') parser.add_argument('-n','--npes', help=' number of mpi tasks') parser.add_ar...
rgs.SFC+'_'+str(tol)+'.pbs' pbs_file=open(fileName,'w') pbs_file.write('#!/bin/bash\n') pbs_file.write('#SBATCH --ntasks='+args.npes+'\n') pbs_file.write('#SBATCH --cpus-per-task='+args.N+'\n') pbs_file.write('#SBATCH -o /exp-share/dendro/build/sc16-poster-final-jobs/%J.out\n') pbs_file.wr...
le.write('n='+args.N+'\n') pbs_file.write('inputFile=ip\n') pbs_file.write('numPts='+args.grainSz+'\n') pbs_file.write('dim=3\n') pbs_file.write('maxDepth=30\n') pbs_file.write('solvU=0\n') pbs_file.write('writeB=0\n') pbs_file.write('k=1\n') pbs_file.write('inCorner=1\n') p...
CodeNameGhost/shiva
thirdparty/scapy/layers/tls/automaton_srv.py
Python
mit
30,139
0.001161
## This file is part of Scapy ## Copyright (C) 2007, 2008, 2009 Arnaud Ebalard ## 2015, 2016, 2017 Maxence Tury ## This program is published under a GPLv2 license """ TLS server automaton. This makes for a primitive TLS stack. Obviously you need rights for network access. We support versions SSLv2 to TL...
% (self.local_ip, self.local_port) s += "Remote end : %s:%d\n" % (self.remote_ip, self.remote_port) v
= _tls_version[self.cur_session.tls_version] s += "Version : %s\n" % v cs = self.cur_session.wcs.ciphersuite.name s += "Cipher suite : %s\n" % cs ms = self.cur_session.master_secret s += "Master secret : %s\n" % repr_hex(ms) body = "<html><body><pre>%s</pre></body>...
lazlolazlolazlo/onionshare
onionshare/settings.py
Python
gpl-3.0
4,545
0.00176
# -*- coding: utf-8 -*- """ OnionShare | https://onionshare.org/ Copyright (C) 2017 Micah Lee <[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 version 3 of the License, o...
RCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. """ import json import os import platform from . import strings, common cl...
ect to Tor. If it can't find the settings file, it uses the default, which is to attempt to connect automatically using default Tor Browser settings. """ def __init__(self, config=False): common.log('Settings', '__init__') # Default config self.filename = self.build_filename() ...
willthames/ansible-lint
test/TestMetaChangeFromDefault.py
Python
mit
1,169
0.000855
# pylint: disable=preferred-module # FIXME: remove once migrated per GH-725 import unittest from a
nsiblelint.rules import RulesCollection from ansiblelint.rules.MetaChangeFromDefaultRule import MetaChangeFromDefaultRule from ansiblelint.testing import RunFromText DEFAULT_GALAXY_INFO = ''' galaxy_info: author: your name description: your description company: your company (optional) license: license (GPLv2, ...
angeFromDefaultRule()) def setUp(self): self.runner = RunFromText(self.collection) def test_default_galaxy_info(self): results = self.runner.run_role_meta_main(DEFAULT_GALAXY_INFO) self.assertIn("Should change default metadata: author", str(results)) self....
nlgcoin/guldencoin-official
test/functional/feature_maxuploadtarget.py
Python
mit
6,606
0.001968
#!/usr/bin/env python3 # Copyright (c) 2015-2018 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test behavior of -maxuploadtarget. * Verify that getdata requests for old blocks (>1week) are dropped ...
g_old_block, 16) # Advance to two days ago self.nodes[0].setmocktime(int(time.time()) - 2*60*60*24) #
Mine one more block, so that the prior block looks old mine_large_block(self.nodes[0], self.utxo_cache) # We'll be requesting this new block too big_new_block = self.nodes[0].getbestblockhash() big_new_block = int(big_new_block, 16) # p2p_conns[0] will test what happens if we j...
zalando/turnstile
tests/test_discovery.py
Python
apache-2.0
636
0.003145
#!/usr/bin/env python # -*- coding: utf-8 -*- from turnstile.checks import get_checks from turnstile.manager import get_commands CORE_COMMIT_MSG_CHECKS = ['branch_pattern', 'branch_release', 'branch_type
', 'protect_master', 'specification'] CORE_SUBCOMMANDS = ['config', 'install', 'remove', 'specification', 'upgrade', 'version'] def test_checks(): checks = dict(get_checks('commit_msg')) for check_name in CORE_COMMIT_MSG_CHECKS: as
sert check_name in checks def test_subcommands(): subcommands = dict(get_commands()) for subcommand_name in CORE_SUBCOMMANDS: assert subcommand_name in subcommands
chromium/chromium
third_party/blink/tools/blinkpy/web_tests/controllers/manager_unittest.py
Python
bsd-3-clause
10,253
0.001073
# Copyright (C) 2010 Google Inc. All rights reserved. # Copyright (C) 2010 Gabor Rapcsanyi ([email protected]), University of Szeged # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of so...
op_servers() self.assertEqual(self.http_stopped, True) self.assertEqual(self.websocket_stopped, True) self.http_started = self.http_stopped = self.websocket_started = self.websocket_stopped = False manager._start_servers(['fast/html/foo.html']) self.assertEqual(self.http_started...
self.assertEqual(self.http_stopped, False) self.assertEqual(self.websocket_stopped, False) def test_look_for_new_crash_logs(self): def get_manager(): host = MockHost() port = host.port_factory.get('test-mac-mac10.10') manager = Manager( port, ...
rastermanden/metadata_example
meta/metadata/admin.py
Python
mit
1,394
0.017279
# -*- coding: utf-8 -*- from django.contrib import admin from metadata.models import Metadata from django.http import HttpResponseRedirect class MetadataAdmin(admin.ModelAdmin): def response_change(self, request, obj): return HttpResponseRedirect("/") ## redirect til frontpage efter add def respon...
sses': ('collapse',),'fields': [('created','updated', 'beginposition','endposition')]}), ('søgestreng ', {'classes': ('collapse',),'fields': ['search_string']}), ] list_display = ('title', 'purpose') prepopulated_fields = {'search_string': ('title','abstract',), 'slug':('title',),} search_field...
etadataAdmin)
frank-cq/Toys
searchBook.py
Python
apache-2.0
1,673
0.039624
# sudo apt install python-lxml,python-requests from lxml import html import requests urlPrefix = 'https://book.douban.com/subject/' candidateBookNums = [] candidateBookNums.append('3633461') selectedBooks = {} # i = 1 while candidateBookNums: bookNum = candidateBookNums.pop(0) bookUrl = urlPrefix + str(bookNum) ...
星评价比例 stars5 = stars[0] # 4星评价比例 stars4 = stars[1] # 3
星评价比例 stars3 = stars[2] # 2星评价比例 stars2 = stars[3] # 1星评价比例 stars1 = stars[4] # 豆瓣读书中指向其他书的链接 links = tree.xpath('//div[@class="content clearfix"]/dl/dd/a/@href') # 去掉空白符,如回车、换行、空格、缩进 bookName = bookName[0].strip() # 整理豆瓣上书籍的评分信息 book = { 'name':bookName, 'score':rating_num, 'rating_people':rating_pe...
andrebellafronte/stoq
stoqlib/domain/transfer.py
Python
gpl-2.0
15,361
0.001172
# -*- coding: utf-8 -*- # vi:si:et:sw=4:sts=4:ts=4 ## ## Copyright (C) 2007 Async Open Source <http://www.async.com.br> ## All rights reserved ## ## This program 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 F...
RANSFER_TO, self.id, batch=self.batch) ProductHistory.add_transfered_item(self.store, self.transfer_order.source_branch, self) def receive(self): """Receives this item, increasi...
oduct = self.sellable.product if product.manage_stock: storable = product.storable storable.increase_stock(self.quantity, self.transfer_order.destination_branch, StockTransactionHistory.TYPE_TRANSFER_FROM, ...
samsu/neutron
plugins/mlnx/common/constants.py
Python
apache-2.0
784
0
# Copyright 2013 Mellanox Technologies, Ltd # # Lice
nsed 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 ...
kostyakudinov/Prog
usr/share/vim/vim74/tools/demoserver.py
Python
gpl-2.0
3,102
0.000967
#!/usr/bin/python # # Server that will accept connections from a Vim channel. # Run this server and then in Vim you can open the channel: # :let handle = ch_open('localhost:8765') # # Then Vim can send requests to the server: # :let response = ch_sendexpr(handle, 'hello!') # # And you can control Vim by typing a JSON...
t("=== socket closed ===") break if data == '': print("=== socket closed ===") break print("received: {}".format(data)) try: decoded = json.loads(data) except ValueError: print("json decoding ...
nses. if decoded[0] >= 0: if decoded[1] == 'hello!': response = "got it" else: response = "what?" encoded = json.dumps([decoded[0], response]) print("sending {}".format(encoded)) self.requ...
Glottotopia/aagd
moin/local/moin/build/lib.linux-x86_64-2.6/MoinMoin/support/passlib/handlers/sun_md5_crypt.py
Python
mit
14,328
0.006421
"""passlib.handlers.sun_md5_crypt - Sun's Md5 Crypt, used on Solaris .. warning:: This implementation may not reproduce the original Solaris behavior in some border cases. See documentation for details. """ #============================================================================= # imports...
==========================
======== # core from hashlib import md5 import re import logging; log = logging.getLogger(__name__) from warnings import warn # site # pkg from passlib.utils import h64, to_unicode from passlib.utils.compat import b, bytes, byte_elem_value, irange, u, \ uascii_to_str, unicode,...
plumgrid/plumgrid-nova
nova/tests/api/openstack/compute/plugins/v3/test_instance_actions.py
Python
apache-2.0
12,710
0.000393
# Copyright 2013 Rackspace Hosting # 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 require...
ct_id}) self.stubs.Set(db, 'instance_get_by_uuid', fake_instance_get_by_uuid) req = fakes.HTTPRequestV3.blank(
'/servers/12/os-instance-actions/1') self.assertRaises(exception.NotAuthorized, self.controller.show, req, str(uuid.uuid4()), '1') class InstanceActionsTest(test.TestCase): def setUp(self): super(InstanceActionsTest, self).setUp() ...
jswope00/GAI
lms/djangoapps/dashboard/sysadmin.py
Python
agpl-3.0
27,630
0.00076
""" This module creates a sysadmin dashboard for managing and viewing courses. """ import csv import json import logging import os import subprocess import time import StringIO from django.conf import settings from django.contrib.auth import authenticate from django.contrib.auth.decorators import login_required from d...
row(row) csv_data = read_and_flush() yield csv_data response = HttpResponse(csv_data(), mimetype='text/csv') response['Content-Disposition'] = 'attachment; filename={0}'.format( filename) return response class Users(SysadminDashboardView): """ The st...
def fix_external_auth_map_passwords(self): """ This corrects any passwords that have drifted from eamap to internal django auth. Needs to be removed when fixed in external_auth """ msg = '' for eamap in ExternalAuthMap.objects.all(): euser = eamap.user ...
run2fail/locker
locker/network.py
Python
gpl-3.0
16,640
0.001563
''' Network related functionality like bridge and netfilter setup ''' import itertools import logging import re import time import iptc import locker import netaddr import pyroute2 from locker.util import regex_ip class BridgeUnavailable(Exception): ''' Bridge device does not exist Raised if the project sp...
f __init__(self, project): ''' Calls start() to setup n
etfilter rules and bridge ''' self.project = project self._bridge = self._get_existing_bridge() @property def project(self): ''' Get locker project instance ''' return self._project @project.setter def project(self, value): ''' Set locker project instanc...
Passtechsoft/TPEAlpGen
blender/doc/blender_file_format/BlendFileDnaExporter_25.py
Python
gpl-3.0
15,484
0.01001
#!/usr/bin/env python3 # ***** BEGIN GPL LICENSE BLOCK ***** # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This...
structureIndex = 0 for structure in self.
Catalog.Structs: structs_list += list_item.format(structureIndex, structure.Type.Name) structureIndex+=1 # ${structs_content} log.debug("Creating structs content") structs_content = '' for structure in self.Catalog.Structs: log.debug(structure.Type.Na...
mediawiki-utilities/python-mwreverts
mwreverts/tests/test_detector.py
Python
mit
849
0
from nose.tools import eq_ from ..detector import Detector def test_detector(): detector = Detector(2) eq_(detector.process("a", {'id': 1}), None) # Check noop eq_(detector.process("a", {'id': 2}), None) # Short revert
eq_(detector.process("b", {'id': 3}), None) eq_( detector.process("a", {'id': 4}), ({'id': 4}, [{'id': 3}], {'id': 2}) ) # Medium revert eq_(detector.process("c", {'id': 5}), None) eq_(detector.process("d", {'id': 6}), None) eq_( detector.process("a", {'id': 7}),
({'id': 7}, [{'id': 6}, {'id': 5}], {'id': 4}) ) # Long (undetected) revert eq_(detector.process("e", {'id': 8}), None) eq_(detector.process("f", {'id': 9}), None) eq_(detector.process("g", {'id': 10}), None) eq_(detector.process("a", {'id': 11}), None)
electric-cloud/metakit
python/metakit.py
Python
mit
2,471
0.017402
""" metakit.py -- Utility code for the Python interface to Metakit $Id: metakit.py 1669 2007-06-16 00:23:25Z jcw $ This is part of Metakit, see http://www.equi4.com/metakit.html This wraps the raw Mk4py compiled extension interface. To use Metakit through this interface, simply do: import metakit After that, things ...
or c in range(len(props)): print '', justs[c](cols[c][r], widths[c]), print print " Total: %d rows" % len(view) if _oldname == '__main__': db = storage() f = db.getas('frequents[drinker,bar,perweek:I]') s = db.getas('serves[bar,beer,quantity:I]') f.append(drinker='adam', bar='lolas', perweek=1) ...
rweek=5) f.append(drinker='sam', bar='cheers', perweek=5) f.append(drinker='lola', bar='lolas', perweek=6) s.append(bar='cheers', beer='bud', quantity=500) s.append(bar='cheers', beer='samaddams', quantity=255) s.append(bar='lolas', beer='mickies', quantity=1515) dump(f, 'frequents:') dump(s, 'serves:')...
jwren/intellij-community
python/testData/inspections/PyUnresolvedReferencesInspection/UnusedImportsInPackage/p1/__init__.py
Python
apache-2.0
178
0.02809
f
rom .m1 import f from p1.m1 import f from m1 import f from a import g <warning descr="Unused import statement '
from a import h'">from a import h</warning> __all__ = ['f', 'g']
rorytrent/the-duke
duke/game.py
Python
gpl-3.0
499
0
import random from .tiles import base INITIAL_TILES = [ base.ASSASSIN, base.BOWMAN, base.CHAMPION, base.DRAGOON, base.FOOTMAN, base.GENERAL, base.KNIGHT, base.LONGBOWMAN, base.MARSHALL, b
ase.PIKEMAN, base.PIKEMAN, base.PRIEST, base.RANGER, base.SEER, base.WIZARD, ] class Game(object): def __init__(self, initial_tiles=INITIAL_TILES): self.board = {} self.bags = (initial
_tiles[:], initial_tiles[:]) for bag in self.bags: random.shuffle(bag)
fpagyu/glory
pi/client.py
Python
mit
500
0.006
# coding: utf-8 from websocket impor
t create_connection def ws_handler(): ws = create_connection("ws://localhost:8000/echo") try: # ws.send("Hello, world") while 1: result = ws.recv() print(result) except: pass finally: ws.close() # with create_connection("ws://localhost:8000/e...
n__": ws_handler()
UPCnet/genweb.serveistic
genweb/serveistic/tests/test_ws_client_problems.py
Python
gpl-3.0
10,661
0.000188
# -*- coding: utf-8 -*- """Unit tests for the Web Service client.""" import base64 import datetime import json import unittest from mock import patch, MagicMock from requests.exceptions import ConnectionError from genweb.serveistic.ws_client.problems import ( Client, ClientException, Problem) class TestWSClie...
e = json.loads(''' { "resultat": "ERROR", "resultatMissatge": "This is the message" }''') try: self.client._parse_response_result(response) self.fail("ClientException should have been raised") except ClientException as cexce
ption: self.assertEqual( "Error code UNDEFINED: This is the message", cexception.message) response = json.loads(''' { "resultat": "ERROR", "codiError": "5" }''') try: self.client._parse_respo...
tectronics/evennia
src/utils/idmapper/base.py
Python
bsd-3-clause
19,327
0.00564
""" Django ID mapper Modified for Evennia by making sure that no model references leave caching unexpectedly (no use if WeakRefs). Also adds cache_size() for monitoring the size of the cache. """ import os, threading #from twisted.internet import reactor #from twisted.internet.threads import blockingCallFromThread f...
name,_GA(cls,fieldname) return _GA(cls, fieldname) def _get_foreign(cls, fname): "Wrapper for returing foreignkey fields" value = _GA(cls, fieldname) #print "_get_foreign:value:", value try: retu
rn _GA(value, "typeclass") except: return value def _set_nonedit(cls, fname, value): "Wrapper for blocking editing of field" raise FieldError("Field %s cannot be edited." % fname) def _set(cls, fname, value): "Wr...
futurice/vdsm
vdsm/kaxmlrpclib.py
Python
gpl-2.0
5,941
0.000842
# # Copyright 2008-2011 Red Hat, Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed ...
t(sslutils.VerifyingSa
feTransport): def make_connection(self, host): chost, self._extra_headers, x509 = self.get_host_info(host) if hasattr(xmlrpclib.SafeTransport, "single_request"): # Python 2.7 return TcpkeepHTTPSConnection( chost, None, key_file=self.key_file, strict=None, ...
Xarxa6/hackathon
src/config.py
Python
mit
1,937
0.009809
import json import os, sys, traceback script_dir = os.path.dirname(__file__) config_file = os.path.join(script_dir, './config/application.json') defaults = os.path.join(script_dir, './config/reference.json') def loadConfig(f): print "[INFO] Loading configuration from " + f + "..." with open(f, 'r') as opened:...
ig # If dev is passed to init.py, this s
cript loads the db linked via docker/fig in /etc/hosts if len(sys.argv) > 1 and sys.argv[1].upper() == 'DEV': print "Booting API using /etc/hosts file..." logConfig = { "level" : "DEBUG", "file" : "" } bootConfig = { "host" : "0.0.0.0", ...
Zarthus/CloudBotRefresh
plugins/test/test_fishbans.py
Python
gpl-3.0
3,502
0.001428
import json import pytest from plugins.fishbans import fishbans, bancount from cloudbot import http test_user = "notch" test_api = """ {"success":true,"stats":{"username":"notch","uuid":"069a79f444e94726a5befca90e38aaf5","totalbans":11,"service":{"mcbans":0,"mcbouncer":11,"mcblockit":0,"minebans":0,"glizer":0}}} """...
user) == bans_reply def tes
t_bans_single(monkeypatch): """ tests fishbans with a successful API response having a single ban """ def fake_http(url): assert url == "http://api.fishbans.com/stats/notch/" return json.loads(test_api_single) monkeypatch.setattr(http, "get_json", fake_http) assert fishbans(test_u...
rivalrockets/rivalrockets-api
app/api_1_0/app.py
Python
mit
3,161
0.000633
from flask_restful import Api from . import api_blueprint from ..api_1_0.resources.users import UserAPI, UserListAPI from ..api_1_0.resources.authentication import (TokenRefresh, UserLogin, UserLogoutAccess, UserLogoutRefresh) from ..api_1_0.resources.machines import MachineAPI, MachineListAPI, \ UserMachineLis...
/<int:id>', endpoint='cinebenchr15result') api.add_resource(RevisionCinebenchR15ResultListAPI, '/revisions/<int:id>/cinebenchr15results', endpoint='rev
ision_cinebenchr15results') api.add_resource(Futuremark3DMark06ResultListAPI, '/futuremark3dmark06results', endpoint='futuremark3dmark06results') api.add_resource(Futuremark3DMark06ResultAPI, '/futuremark3dmark06results/<int:id>', endpoint='futuremark3dmark06result') a...
hoaibang07/Webscrap
transcripture/sources/crawler_chuongthieu.py
Python
gpl-2.0
7,017
0.007981
# -*- encoding: utf-8 -*- import io from bs4 import BeautifulSoup from bs4 import SoupStrainer import urllib2 import urlparse from selenium import webdriver from selenium.webdriver.common.keys import Keys import time from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expecte...
http://www.transcripture.com/vietnamese-chinese-revelation-3.html'
# print urlchuong # # create request # req = urllib2.Request(urlchuong, headers=hdrs) # # get response # response = urllib2.urlopen(req) # soup = BeautifulSoup(response.read()) # Load a page driver.get(...
python-zk/kazoo
kazoo/tests/test_queue.py
Python
apache-2.0
6,221
0
import uuid import pytest from kazoo.testing import KazooTestCase from kazoo.tests.util import CI_ZK_VERSION class KazooQueueTests(KazooTestCase): def _makeOne(self): path = "/" + uuid.uuid4().hex return self.client.Queue(path) def test_queue_validation(self): queue = self._makeOne(...
assert queue.get() == b"one" assert queue.get() == b"two" assert queue.get() == b"three" assert len(queue) == 0 def test_priority(self): queue = self._makeOne() queue.put(b"four", priority=101) queue.put(b"one", priority=0) queue.put(b"two", priorit...
e.get() == b"two" assert queue.get() == b"three" assert queue.get() == b"four" class KazooLockingQueueTests(KazooTestCase): def setUp(self): KazooTestCase.setUp(self) skip = False if CI_ZK_VERSION and CI_ZK_VERSION < (3, 4): skip = True elif CI_ZK_VERSIO...
jameswatt2008/jameswatt2008.github.io
python/Python基础/截图和代码/面对对象-2/10-多继承.py
Python
gpl-2.0
259
0.015444
class Base(object): def test(self): print("----Base") class A(Base): def test1(self): print("---
--test1") class B(Base): def
test2(self): print("-----test2") class C(A,B): pass c = C() c.test1() c.test2() c.test()
kubevirt/client-python
kubevirt/models/k8s_io_apimachinery_pkg_apis_meta_v1_root_paths.py
Python
apache-2.0
3,286
0.000609
# coding: utf-8 """ KubeVirt API This is KubeVirt API an add-on for Kubernetes. OpenAPI spec version: 1.0.0 Contact: [email protected] Generated by: https://github.com/swagger-api/swagger-codegen.git """ from pprint import pformat from six import iteritems import re class K8sIoApi...
me and the value is attribute type. attribute_map (dict)
: The key is attribute name and the value is json key in definition. """ swagger_types = { 'paths': 'list[str]' } attribute_map = { 'paths': 'paths' } def __init__(self, paths=None): """ K8sIoApimachineryPkgApisMetaV1RootPaths - a mod...
sutartmelson/girder
tests/cases/routetable_test.py
Python
apache-2.0
6,390
0.002034
#
!/usr/bin/env python # -*- coding: utf-
8 -*- ############################################################################### # Copyright 2016 Kitware 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.ap...
petricm/DIRAC
WorkloadManagementSystem/Agent/OptimizerModule.py
Python
gpl-3.0
11,859
0.007589
######################################################################## # File : Optimizer.py # Author : Stuart Paterson ######################################################################## """ The Optimizer base class is an agent that polls for jobs with a sp
ecific status and minor status pair. The checkJob method is overridden for all optimizer instances and associated actions are performed there. """ __RCSID__ = "$Id$" from DIRAC import S_OK, S_ERROR, exit as dExit from DIRAC.Core.Base.AgentModule import AgentModule from DIRAC.Core.Utilities.ClassAd.ClassAdLight ...
from DIRAC.AccountingSystem.Client.Types.Job import Job as AccountingJob from DIRAC.WorkloadManagementSystem.DB.JobDB import JobDB from DIRAC.WorkloadManagementSystem.DB.JobLoggingDB import JobLoggingDB class OptimizerModule(AgentModule): """ The specific agents must provide the following methods: * ...
maligulzar/Rstudio-instrumented
logserver/server.py
Python
agpl-3.0
793
0.020177
#!/usr/bin/env python2.4 # # Copyright 2007 Google Inc. All Rights Reserved. import BaseHTTPServer import SimpleHTTPServer import urllib import random import sys import datetime class MyHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): def do_GET(self): form = {} now = datetime.datetime.now() lognam...
'): if queryParam.spli
t('=')[0] == "data": f = open(logname, 'a') f.write(urllib.unquote_plus(queryParam[5:] + ",\n")) f.close() self.wfile.flush() self.connection.shutdown(1) print sys.argv[1] bhs = BaseHTTPServer.HTTPServer(('', int(sys.argv[1])), MyHandler) bhs.serve_forever()
MicroPyramid/Django-CRM
tasks/migrations/0005_task_company.py
Python
mit
607
0
# Generated by Django 2.2.10 on 2020-04-27 12:23 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration):
dependencies = [ ("common", "0021_document_company"), ("tasks", "0004_task_teams"), ] operations = [ migrations.AddField( model_name="task", name="company", field=models.ForeignKey( blank=True, null=True, ...
models.deletion.SET_NULL, to="common.Company", ), ), ]
ptroja/spark2014
testsuite/gnatprove/tests/riposte__usergroup_examples/test.py
Python
gpl-3.0
41
0.02439
from test_sup
port import * prove_all ()
leapp-to/prototype
tests/data/actor-api-tests/topics/apitest.py
Python
lgpl-2.1
82
0
f
rom leapp.topics import Topic class ApiTestTopic(Topic): name = 'api_tes
t'
deepmind/dm_robotics
py/agentflow/subtasks/integration_test.py
Python
apache-2.0
12,432
0.002252
# Copyright 2020 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 ag...
self._parent_spec, step_type=dm_env.StepType.LAST, discount=self._default_discount) # TCP doesn't have to be in-bounds for subtask to provide terminal # reward, so just to verify we set back to out-of-bounds. random_last_timestep.observation[self._tcp_pos_obs] = event_tcp_obs ...
call[0][0].reward for call in mock_policy.step.call_args_list ] actual_discounts = [ call[0][0].discount for call in mock_policy.step.call_args_list ] self.assertEqual(expected_rewards, actual_rewards) self.assertEqual(expected_discounts, actual_discounts) @parameterized.parameters...
anneline/Bika-LIMS
bika/lims/browser/widgets/querywidget.py
Python
agpl-3.0
5,599
0.000714
from AccessControl import ClassSecurityInfo from archetypes.querywidget.views import WidgetTraverse as _WidgetTraverse from archetypes.querywidget.widget import QueryWidget as _QueryWidget from bika.lims.querystring.querybuilder import QueryBuilder from bika.lims.querystring.querybuilder import RegistryConfiguration fr...
registryreader.parseRegistry() # Then combine our fields registryreader = IQuerystringRegistryReader(registry) registryreader.prefix = "bika.lims.bika_catalog_query" config = registryreader.parseRegistry() config = registryreader.getVocabularyValues(config) config.update(...
fig) config = { 'indexes': config.get('bika.lims.bika_catalog_query.field'), 'sortable_indexes': config.get('sortable'), } # Group indices by "group", order alphabetically groupedIndexes = {} for indexName in config['indexes']: index = config['...