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
Hellowlol/plexpy
plexpy/datafactory.py
Python
gpl-3.0
57,912
0.003954
# This file is part of PlexPy. # # PlexPy 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. # # PlexPy is distributed in the hope t...
see <http://www.gnu.org/licenses/>. from plexpy import logger, datatables, common, database, helpers import datetime class DataFactory(object): """ Retrieve and process data from the monitor database """ def __init__(self): pass def get
_datatables_history(self, kwargs=None, custom_where=None, grouping=0, watched_percent=85): data_tables = datatables.DataTables() group_by = ['session_history.reference_id'] if grouping else ['session_history.id'] columns = ['session_history.reference_id', 'session_history.id...
stewartsmith/bzr
bzrlib/smart/packrepository.py
Python
gpl-2.0
1,623
0.000616
# Copyright (C) 2008 Canonical Ltd # # 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 ...
from bzrlib.smart.request import ( FailedSmartServerResponse, SuccessfulSmartServerResponse, ) from bzrlib.smart.repository import ( SmartServerRepositoryRequest, ) class SmartServerPackRepositoryAutopack(SmartServerRepositoryRequest): def do_repository_request(self, repository): pa...
his is a not a pack repo, so asking for an autopack is just a # no-op. return SuccessfulSmartServerResponse(('ok',)) repository.lock_write() try: repository._pack_collection.autopack() finally: repository.unlock() return SuccessfulSmartServ...
luozhaoyu/deepdive
crawler.py
Python
apache-2.0
6,748
0.001778
#!/usr/bin/python # -*- coding: utf-8 -*- """ crawler.py ~~~~~~~~~~~~~~ A brief description goes here. """ import csv import urllib2 import urllib import re import os import urlparse import threading import logging import logging.handlers import time import random import bs4 MINIMUM_PDF_SIZE = 4506 TASKS...
ror # http://en.wikipedia.org/wiki/Exponential_backoff if e.code / 100 == 5: sleep_time = random.randint(0, 2 ** i - 1) except urllib2.URLError as e: log.warn("%s\tURLError\t%s\tRetry:%i&Sleep:%.2f\t%s" % (sbid, url, i, ...
bid is not unique, so use sbid+pdfname as new name pdf_name = url.split('/')[-1].split('.')[0] _urlfetch(url, sbid, os.path.join(output_folder, "%s.%s.pdf" % (sbid, pdf_name))) else: page = _urlfetch(url, sbid) soup = bs4.BeautifulSoup(page) anchors = soup.findAll('a', attrs=...
frankvdp/django
django/db/models/functions/__init__.py
Python
bsd-3-clause
1,872
0
from .comparison import Cast, Coalesce, Greatest, Least from .datetime import ( Extract, ExtractDay, ExtractHour, ExtractIsoYear, ExtractMinute, ExtractMonth, ExtractQuarter, ExtractSecond, ExtractWeek, ExtractWeekDay, ExtractYear, Now, Trunc, TruncDate, TruncDay, TruncHour, TruncMinute, TruncMonth, Tru...
, Lead, NthValue, Ntile, PercentRank, Rank, RowNumber, ) __all__ = [ # comparison and conversion 'Cast', 'Coalesce', 'Greatest', 'Least', # datetime 'Extract', 'ExtractDay', 'ExtractHour', 'ExtractMinute', 'ExtractMonth', 'ExtractQuarter', 'ExtractSecond', 'ExtractWeek', 'ExtractWeekDay', '...
ExtractYear', 'Now', 'Trunc', 'TruncDate', 'TruncDay', 'TruncHour', 'TruncMinute', 'TruncMonth', 'TruncQuarter', 'TruncSecond', 'TruncMinute', 'TruncMonth', 'TruncQuarter', 'TruncSecond', 'TruncTime', 'TruncWeek', 'TruncYear', # math 'Abs', 'ACos', 'ASin', 'ATan', 'ATan2', 'Ceil', 'Cos', 'Cot', 'Deg...
jsfenfen/senate_disbursements
114_sdoc4/read_pages.py
Python
bsd-2-clause
11,865
0.024189
import re, csv header_end = re.compile("\s+START\s+END\s+") ## p. 1172 is missing a space between the final date and the description. Can't understand why the layout option does this; a space is clearly visible. I dunno. five_data_re = re.compile("\s*([\w\d]+)\s+(\d\d\/\d\d\/\d\d\d\d)\s+(.*?)\s+(\d\d\/\d\d\/\d\d\d\d...
top_matter_end_re.match(whole_line): break if blank_line_re.match(line): continue return None def process_top_matter(page_num, top_matter): #top_matter_top_left_column_delimiter = compute_break_position(top_matter) top_matter_top_left_column_delimiter = 48 #return ...
ole_line in top_matter: if top_matter_end_re.match(whole_line): break line = whole_line[:top_matter_top_left_column_delimiter] if blank_line_re.match(line): continue result = funding_year_re.match(line) line_stripped = line.strip() if ...
citrix-openstack/build-ryu
ryu/tests/unit/packet/test_bgp.py
Python
apache-2.0
4,299
0
# Copyright (C) 2013 Nippon Telegraph and Telephone Corporation. # Copyright (C) 2013 YAMAMOTO Takashi <yamamoto at valinux co jp> # # 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:...
n_routes, path_attributes=path_attributes, nlri=nlri) binmsg = msg.serialize() msg2, rest = bgp.BGPMessage.parser(binmsg) eq_(str(msg), str(msg2)) ok_(len(msg) > 23) eq_(rest, '') def test_keepalive(self): msg =...
msg), 19) eq_(rest, '') def test_notification(self): data = "hoge" msg = bgp.BGPNotification(error_code=1, error_subcode=2, data=data) binmsg = msg.serialize() msg2, rest = bgp.BGPMessage.parser(binmsg) eq_(str(msg), str(msg2)) eq_(len(msg), 21 + len(data)) ...
kobotoolbox/formpack
tests/fixtures/select_one_from_previous_answers/__init__.py
Python
gpl-3.0
336
0
# coding: utf-8 ''' select_one_from_previous_answers ''' from ..load_fixture_json import lo
ad_fixture_json DATA = { 'title': 'Household survey with select_one from previous answers', 'id_string': 'select_one
_from_previous_answers', 'versions': [ load_fixture_json('select_one_from_previous_answers/v1'), ], }
ajaniv/equitymaster
tests/regexp_tests.py
Python
gpl-2.0
3,514
0.013944
#/usr/bin/env python # -#- coding: utf-8 -#- # # parser/test/tests.py - parsing unit test module # # standard copy right text # # Initial version: 2011-03-08 # Author: Amnon Janiv """ .. module:: tests/regexp_tests :synopsis: regex_scripting test suite module Test suite designed to test regex_scripting featur...
.compile(tmpl) #exp = re.compile(r"^[a-zA-Z]{3,5}$") self.assertTrue(exp) matched = exp.match("aAbBc") self.assertTrue(matched) print self.displaymatch(matched) def test_numeric(self): min = 5 max = 5
sz = "{{{:d},{:d}}}".format(min,max) tmpl = r"^[0-9]"+sz+"$" exp = re.compile(tmpl) self.assertTrue(exp) matched = exp.match("12345") self.assertTrue(matched) print self.displaymatch(matched) exp = regexp.NumericRegExp(min_width=5, max_width=5) ...
stackforge/osprofiler
osprofiler/tests/unit/test_profiler.py
Python
apache-2.0
21,196
0.000047
# Copyright 2014 Mirantis 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...
self.assertEqual(hmac, prof.hmac_key) class WithTraceTestCase(test.TestCase):
@mock.patch("osprofiler.profiler.stop") @mock.patch("osprofiler.profiler.start") def test_with_trace(self, mock_start, mock_stop): with profiler.Trace("a", info="a1"): mock_start.assert_called_once_with("a", info="a1") mock_start.reset_mock() with profiler.Trace("b"...
swenger/glitter
examples/qt.py
Python
mit
9,648
0.001555
#!/usr/bin/env python # vim: set fileencoding=utf-8 : #! This file is a literate Python program. You can compile the documentation #! using mylit (http://pypi.python.org/pypi/mylit/). ## title = "glitter Example: Qt" ## stylesheet = "pygments_style.css" # <h1><i>glitter</i> Example: Qt</h1> # <h2>Summary</h2> # Thi...
event.pos()) # <h4>OpenGL interaction</h4> # Whenever the canvas is resized (also on creation), we set the viewport # (which is actually a <i>glitter</i> <code>Context</code> property) to the # full window and change the projection matrix such that it encompasses the # whole range from -1 to +1: ...
he <code>paintGL()</code> method is called by Qt whenever the canvas # needs to be redrawn: def paintGL(self): # First, we clear the canvas using <code>Context.clear()</code>. self.clear() # Then, if a mesh pipeline has been loaded, we draw it with the # <code>modelview_matrix</...
hanjihun/Car
compreseguros_com/compreseguros_com/spiders/compreseguros_com_spider.py
Python
mit
8,164
0.033684
# -*- coding: utf-8 -*- import scrapy from scrapy.exceptions import CloseSpider from scrapy import Request, FormRequest, Selector from datetime import date from collections import OrderedDict from json import loads from random import randint import json, re, collections import datetime, time import logging # Remove...
times = response.meta['t
imes'] ctime = int(time.time()) print "#", index,"th combination elasped ", ctime-stime,"s by ", times,"trying." # Log Section param = response.meta['param'] data = loads(response.body) bFinalized = data['finalizado'] if bFinalized == False: if times > 20: yield Request(self.start_urls[0], self.pa...
openSUSE/dbxincluder
tests/conftest.py
Python
gpl-3.0
1,148
0.000871
# # Copyright (c) 2016 SUSE Linux GmbH # # This file is part of dbxincluder. # # dbxincluder is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Fre
e Software Foundation, either version 3 of the License, or # (at your option) any later version. # # dbxincluder is distributed in the hope
that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with dbxincluder. If not, see <http://www....
Cinemair/cinemair-server
cinemair/users/connectors/google.py
Python
mit
4,872
0.008826
import requests import json from collections import namedtuple from urllib.parse import urljoin from django.conf import settings from django.utils.translation import ugettext_lazy as _ from cinemair.common.exceptions import BaseException class GoogleApiError(BaseException): status_code = 400 default_detail...
n") params={"code": access_code, "client_id": client_id, "client_secret": client_secret, "grant_type": "authorization_code", "redirect_uri": redirect_uri} data = _post(url, params=params, headers=headers) return
AuthInfo(access_token=data.get("access_token", None)) def get_user_profile(headers:dict=HEADERS): """ Get authenticated user info. (See https://developer.google.com/v3/users/#get-the-authenticated-user). """ url = _build_url("user", "profile") data = _get(url, headers=headers) id = data.g...
power12317/Biligrab
danmaku2ass2.py
Python
mit
38,418
0.002629
#!/usr/bin/env python2 # -*- coding: utf-8 -*- # The original author of this program, Danmaku2ASS, is StarBrilliant. # This file is released under General Public License version 3. # You should have received a copy of General Public License text alongside with # this program. If not, you can obtain it at http://gnu.or...
mp == '?': tmp = f.read(38) if tmp == 'xml version="1.0" encoding="UTF-8"?><p': return 'Niconico' elif tmp == 'xml version="1.0" encoding="UTF-8"?><i': return 'Bilibili' elif tmp == 'xml version="1.0" encoding="utf-8"?><i': ...
elif tmp == 'xml version="1.0" encoding="Utf-8"?>\n<': return 'Bilibili' # Komica, with the same file format as Bilibili elif tmp == 'xml version="1.0" encoding="UTF-8"?>\n<': return 'MioMio' elif tmp == 'p': return 'Niconico' # Himawari Dou...
adfernandes/pcp
qa/statsd/src/cases/01.py
Python
lgpl-2.1
500
0.01
#!/usr/bin/env pmpython # -*- co
ding: utf-8 -*- # Exercises installation and removal of pmdastatsd import sys import glob import os utils_path = os.path.abspath(os.path.join("utils")) sys.path.append(utils_path) import pmdastatsd_test_utils as utils utils.print_test_file_separator() print(os.path.basename(__file__)) def run_test(): install...
int(install_output) remove_output = utils.pmdastatsd_remove() print(remove_output) run_test()
TimothyZhang/structer
structerui/log.py
Python
gpl-3.0
937
0.002134
# Copyright 2014 Timothy Zhang(zt@live.cn). # # This file is part of Structer. # # Structer 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. # # Structer 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...
<http://www.gnu.org/licenses/>. import wx from structer.log import * def alert(*args, **kwargs): record = error(*args, **kwargs) msg = record.format() if record.exception: msg += '\n%s' % record.exception wx.MessageBox(msg)
jkleint/blamethrower
blamethrower/analyzers/findbugs.py
Python
mit
2,302
0.001738
# Copyright 2012 John Kleint # This is free software, licensed under the MIT License; see LICENSE.txt. """ Parse FindBugs -xml:withMessages output. FindBugs XML output is pretty straightforward: a sequence of <BugInstance> tags, with type and rank (severity) attributes. Each has one or more <SourceLine> tags; if mor...
t sourcelines, "No SourceLine for bug: {}".format(bug.attrib) for sourceline in sourcelines: filename = prefix + sourceline.get('sourcepath') linenum = sourceline.get('start')
yield Analyne(filename, int(linenum), bugtype, severity, None) bug.clear()
Acehaidrey/incubator-airflow
airflow/providers/google/cloud/example_dags/example_tasks.py
Python
apache-2.0
5,840
0.001027
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional infor
mation # regarding copyright ownership. The ASF licenses this file # to you 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, W...
Ledoux/ShareYourSystem
Pythonlogy/build/lib/ShareYourSystem/Standards/Itemizers/Conditioner/11_ExampleDoc.py
Python
mit
288
0.069444
#ImportModules import ShareYourSystem as SYS #Define MyConditioner=SY
S.ConditionerClass( ).get( 'MyList' ).set( 'MyList.append', { '#value':4, '#if':[ (type,SYS.operator.eq,SYS.ConditionerClass) ] } ) #print print('MyC
onditioner is') SYS._print(MyConditioner)
bixuehujin/mdeditor
mdeditor/application.py
Python
bsd-3-clause
472
0.008475
''' Created on 2013-7-21 @author: hujin ''' i
mport sys from PySide.QtGui import QApplication from mdeditor.ui.window import MainWindow class Application(QApplication): def __init__(self): ''' Constructor ''' super(Application, self).__init__(sys.argv) def run(self): ''' Run the application. ...
'' frame = MainWindow() frame.show() self.exec_() sys.exit()
hansegucker/bibliowork
depracted/guis/window.py
Python
gpl-3.0
3,434
0.000583
from PyQt5.QtWidgets import (QWidget, QDesktopWidget, QMainWindow, QHBoxLayout, QVBoxLayout, QGridLayout,
QLineEdit, QPushButton, QLabel, QTextEdit, QMessageBox, QComboBox, QAction, QSizePolicy, QToolTip, QApplication) from PyQt5.QtGui import QIcon, QFont, QPixmap from PyQt5.QtCore import * class Window(QMainWindow): def __init__(...
parent) self.Labels = {} self.Buttons = {} self.Layouts = {} self.Icons = {} self.OtherWidgets = {} self.Edits = {} self.widget = QWidget() self.setCentralWidget(self.widget) self.Menus = {} self.MenuActions = {} # Define colors ...
simongibbons/numpy
numpy/typing/tests/data/reveal/testing.py
Python
bsd-3-clause
8,824
0.0068
from __future__ import annotations import re import sys from typing import Any, Callable, TypeVar from pathlib import Path import numpy as np import numpy.typing as npt AR_f8: npt.NDArray[np.float64] AR_i8: npt.NDArray[np.int64] bool_obj: bool suppress_obj: np.testing.suppress_warnings FT = TypeVar("FT", bound=Call...
nd_catch_warnings.modules) # E: set[types.ModuleType] with np.testing.clear_and_catch_warnings(True) as c1: reveal_type(c1) # E: builtins.list[warnings.WarningMessage] with np.testing.clear_and_catch_warnings() as c2: reveal_type(c2) # E: None reveal_type(np.testing.suppress_warnings("once")) # E: suppres...
# E: def () -> builtins.int reveal_type(suppress_obj.filter(RuntimeWarning)) # E: None reveal_type(suppress_obj.record(RuntimeWarning)) # E: list[warnings.WarningMessage] with suppress_obj as c3: reveal_type(c3) # E: suppress_warnings reveal_type(np.testing.verbose) # E: int reveal_type(np.testing.IS_PYPY) ...
runefriborg/pycsp
pycsp/__init__.py
Python
mit
664
0.003012
""" PyCSP implementation of the CSP Core functionality (Channels, Processes, PAR, ALT). Copyright (c) 2009 John Markus Bjoerndalen <jmb@cs.uit.no>, Brian Vinter <vinter@nbi.dk>, Rune M. Friborg
<rune.m.friborg@gmail.com>. See LICENSE.txt for licensing details (MIT License). Ve
rsions available: parallel, greenlets Channels can not be used to communicate between versions. Modules available > import pycsp.parallel > import pycsp.greenlets > import pycsp.common.trace > import pycsp.common.plugNplay > import pycsp.common.toolkit """ # Import parallel by default to enable "import pycsp" if not...
zuBux/drydock
utils/confparse.py
Python
gpl-2.0
356
0.02809
import yaml import sys import logging class ConfParse: def load_conf(self,conf): """ Loads and parses an audit category from a configuration file
""" try: with open(conf)
as conf: profile = yaml.load(conf) except IOError: logging.error("Invalid file specified: %s" %(conf)) sys.exit(0) return profile
mzdaniel/oh-mainline
vendor/packages/python-openid/examples/djopenid/server/views.py
Python
agpl-3.0
9,294
0.001614
""" This module implements an example server for the OpenID library. Some functionality has been omitted intentionally; this code is intended to be instructive on the use of this library. This server does not perform actual user authentication and serves up only one OpenID URL, with the exception of IDP-generated id...
ple Registration information, if any, to send in the response. """ # If the request was an IDP-driven identifier selection request # (i.e., the IDP URL was entered at the RP)
, then return the # default identity URL for this server. In a full-featured # provider, there could be interaction with the user to determine # what URL should be sent. if not openid_request.idSelect(): id_url = getViewURL(request, idPage) # Confirm that this server can actually vouch...
clumsy/intellij-community
python/testData/inspections/PyUnusedLocalVariableInspection3K/test.py
Python
apache-2.0
132
0.007576
d
ef func1(): var = 1 def func2(): nonlocal var var = 2 print(var) func2() print(va
r) func1()
diegocortassa/TACTIC
src/tactic_sites/default/modules/index_wdg.py
Python
epl-1.0
16,459
0.006197
############################################################# # # Copyright (c) 2005, Southpaw Technology # All Rights Reserved # # PROPRIETARY INFORMATION. This software is proprietary to # Southpaw Technology, and is not to be reproduced, transmitted, # or disclosed in any way with...
ius: 10px") div.add_style("width: %s" % width) #div.set_dimensions( width_str='%spx' % width, content_height_str='50px' ) div.add_border() div.add_style("overflow: hidden") div.set_box_shadow() div.add_sty
le("margin-left: auto") div.add_style("margin-right: auto") div.add_style("width: %spx" % width) table = Table() table.set_max_width() table.add_style("margin-left: auto") table.add_style("margin-right: auto") table.add_style("background-color: %s" % bg_color) ...
laurent-george/protolab_sound_recognition
sound_classification/evaluate_classification.py
Python
mit
5,875
0.009362
__author__ = 'lgeorge' #import seaborn as sns import pylab import classification_service import numpy as np import sound_classification.confusion_matrix from sklearn.metrics import confusion_matrix def plot_distribution_true_false(prediction_df): """ :param prediction_df: :return: """ mask_well_c...
=False, keep_first_slice_only=False): """ Tool function to report classification accuracy for our classification tools """ predicted=[] expected=[] filenames = [] fold_num = 0 for train_set, test_set in stratified_fold: train_files = df.iloc[train_set].filename sound_cla...
assification_service.SoundClassification(train_files.tolist(), clf=clf, window_block_learning=window_block_learning , calibrate_score=calibrate_score) sound_classification_obj.learn() labels = sound_classification_obj.clf.classes_ for index in test_set: val = df.iloc[index] ...
Vagab0nd/SiCKRAGE
lib3/sqlalchemy/ext/baked.py
Python
gpl-3.0
21,989
0.000227
# sqlalchemy/ext/baked.py # Copyright (C) 2005-2020 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """Baked query extension. Provides a creational pattern for the :class:`.que...
lf.cls(self.cache, initial_fn, args) class BakedQuery(object): """A builder object for :class:`.query.Query` objects.""" __slots__ = "steps", "_bakery", "_cache_key", "_spoiled" def __init__(self, bakery, initial_fn, args=
()): self._cache_key = () self._update_cache_key(initial_fn, args) self.steps = [initial_fn] self._spoiled = False self._bakery = bakery @classmethod def bakery(cls, size=200, _size_alert=None): """Construct a new bakery. :return: an instance of :class:`...
cpennington/edx-platform
lms/djangoapps/grades/migrations/0013_persistentsubsectiongradeoverride.py
Python
agpl-3.0
1,154
0.006932
# -*- coding: utf-8 -*- from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('grades', '0012_computegradessetting'), ] operations = [ migrations.CreateModel( name='PersistentSubsectionGradeOverride', fields=[ ...
ed', models.DateTimeField(auto_now=True, db_index=T
rue)), ('earned_all_override', models.FloatField(null=True, blank=True)), ('possible_all_override', models.FloatField(null=True, blank=True)), ('earned_graded_override', models.FloatField(null=True, blank=True)), ('possible_graded_override', models.FloatFi...
cakesmith/Firefly
toolkit.py
Python
gpl-3.0
2,945
0.010866
from re import compile from itertools import count from collections import namedtuple, Iterable class LabelGenerator: def __init__(self, name, joinchar="."): self.labels = {None:self._makeiterator(name, joinchar)} self.name = name self.joinchar = joinchar def _makeiterator(sel...
n L such that L(loc) will yield the line number N in text. >>> L = loctoline("foo\\nbar") >>> L(0) 1 >>> L(3) 1 >>> L(4) 2 >
>> L(7) """ line = [] num = 1 for char in text: line.append(num) if char == "\n": num += 1 def lookup(location): try: return line[location] except IndexError: return None # return a closure to generate the data struc...
mahabs/nitro
nssrc/com/citrix/netscaler/nitro/resource/stat/ns/nspbr_stats.py
Python
apache-2.0
5,513
0.043715
# # 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...
n DENY . """ try : return self._pbrtotpktsdenied except Exception as e: raise e @property def pbrpktsallowedrate(self) : """Rate (/s) counter for pbrtotpktsallowed. """ try : return self._pbrpktsallowedrate except Exception as e: raise e def _get
_nitro_response(self, service, response) : """ converts nitro response into object and returns the object array in case of get request. """ try : result = service.payload_formatter.string_to_resource(nspbr_response, response, self.__class__.__name__.replace('_stats','')) if(result.errorcode != 0) : if (...
Nekroze/partpy
docs/conf.py
Python
mit
9,097
0.007585
# -*- coding: utf-8 -*- # # partpy documentation build configuration file, created by # sphinx-quickstart on Sat Feb 16 18:56:06 2013. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All ...
target name, title, author, # dir menu entry,
description, category) texinfo_documents = [ ('index', 'partpy', u'partpy Documentation', u'Taylor "Nekroze" Lawson', 'partpy', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texi...
sysadminmatmoz/odoo-clearcorp
account_name_extended/account_name_extended.py
Python
agpl-3.0
17,555
0.012646
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Addons modules by CLEARCORP S.A. # Copyright (C) 2009-TODAY CLEARCORP S.A. (<http://clearcorp.co.cr>). # # This program is free software: you can redistribute...
else: #If this is not addressed then the prefix digit search_domains.append({'company_ids':company_ids}) search_domains.append({'code':piece_1}) e...
e prefix is not a number #If something is typed after the prefix if piece_2: piece_2_b = piece_2.partition(' ')[0] piece_3 = piece_2.partition(' ')[2] #If it is a numbe...
bronikkk/tirpan
tests/accept_mir17.py
Python
gpl-3.0
1,313
0.007616
#!/usr/bin/env python """ Created on 28.10.2014 @author: evg-zhabotinsky """ from test_mir_common import * mir = tirpan_get_mir('test_mir17.py') n = find_mir_nodes(mir, x_call = func_checker('x'), y_call = func_checker('y'), z_call = func_checker('z'), ...
rNode)) find_node_down_mir_nojoin(mir, same_node_checker(n.x_call)) find_node_down_mir_nojoin(n.x_if.true, same_node_checker(n.y_call)) find_node_down_mir_nojoin(n.x_if.false, same_node_checker(n.z_call)) find_node_down_mir_nojoin(n.y_if.true, same_node_checker(n.z_call)) find_node_down_mir_nojoin(n.y_if.false, same_n...
down_mir_nojoin(n.b_call, same_node_checker(n.join)) find_node_down_mir_nojoin(n.join, same_node_checker(None))
TheTimmy/spack
var/spack/repos/builtin/packages/py-coverage/package.py
Python
lgpl-2.1
1,639
0.00122
############################################################################## # Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
c') depends_on('py-setuptools', type='bu
ild')
rakanalh/django-youtuber
example_project/urls.py
Python
mit
765
0
"""django_youtuber URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import:...
g import urls as blog_urls 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls)) """ from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', include(admin.site.urls)), ]
RaumZeit/gdesklets-core
shell2/shell.py
Python
gpl-2.0
113
0.00885
import SlickShe
ll import control.Assembly impo
rt gtk if __name__ == "__main__": s = SlickShell.SlickShell()
ljinshuan/LearningPython
base/Chapter6.py
Python
apache-2.0
1,591
0.003992
# coding:utf-8 # 函数式编程 def add(a, b): return a + b def fprintf(fmt, *args): """args is tuple""" print fmt % args print "{0:s}".format("ljinshuan") fprintf("%s,%d,%s", "xxx", 1, "gerg") def fprintf(fmt, **args): """args is map""" print args fprintf("{name} ,{age}", name="ljinshuan", age=10) ...
le_click = temp(handle_click) # 生成器 def countdown(n): print "Begin Counting" while n > 0: yield n n -= 1 c = countdown(10) for x in c: print x, # 协程 def receiver(): print "Begin receiv
er" while True: n = (yield) print "Got %d" % n r = receiver() r.next() r.send(1) r.close() # 接收的同时返回一个值 def line_splitter(delimter=None): print "Ready to split" result = None while True: line = (yield result) result = line.split(delimter) s = line_splitter(",") s.next(...
ibrahimGhailani/TodoFlask
app/models.py
Python
mit
2,952
0
from app import db import datetime from passlib.apps import custom_app_context as pwd_context from itsdangerous import (TimedJSONWebSignatureSerializer as Serializer, BadSignature, SignatureExpired) class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Colu...
eturn pwd_context.verify(password, self.password_hash) de
f generate_auth_token(self, expiration=6000): s = Serializer('SECRET_KEY', expires_in=expiration) return s.dumps({'id': self.id}) @staticmethod def verify_auth_token(token): s = Serializer('SECRET_KEY') try: data = s.loads(token) except SignatureExpired: ...
korovkin/WNNotifier
notifier/gen_notifier.py
Python
apache-2.0
23,166
0.011267
#!/usr/bin/python import json import time import parcon import operator import pprint import os import sys import getopt import re import optparse import string import hashlib import parse_objc as parser import sign #### tool version: VERSION = parser.VERSION VERSION_STR = sign.source_file_signature(__file__, VERSION...
notifier_name}Subcription *)subscription { [_baseImplementation removeSubscription:subscription]; } ${enumerator_implementation} ${protocol_implementation} @end """.strip() #### enu
merator_implementation_template = """ -(void)enumerateSubscriptionsUsingBlock:(${notifier_name}Visitor)visitor { if (!visitor) { return; } [_baseImplementation enumerateSubscriptionsUsingBlock:^bool(${notifier_name}Subcription * subscription) { visitor(subscription); return ((id<${listener_name}>)subs...
daniellustig/pipecheck
parse_litmus_test_results.py
Python
lgpl-2.1
3,270
0.022324
#!/usr/bin/env python ################################################################################ ## PipeCheck: Specifying and Verifying Microarchitectural ## ## Enforcement of Memory Consistency Models ## ## ...
iden = idens[proc][test] if expected == "Forb" and result == "Perm": sys.stdout.write("(bug?) \t") elif expected == "Perm" and result == "Forb": sys.stdout.write("(strict)\t") elif expected <> result: sys.stdout.write("?? \t") else: sys.stdout.write("...
sys.stdout.write("%s: %s: %s (test %s) (expected: %s)\n" % (proc, test, result, iden, expected)) except: print s
jordanemedlock/psychtruths
temboo/core/Library/Utilities/Email/__init__.py
Python
apache-2.0
134
0.007463
from temboo
.Library.Utilities.Email.SendEmail import SendEmail, SendEmailInputSet, SendEmailResultSet, SendEmailCho
reographyExecution
saltstack/salt
salt/states/netconfig.py
Python
apache-2.0
34,222
0.001519
""" Network Config ============== Manage the configuration on a network device given a specific static config or template. :codeauthor: Mircea Ulinic <ping@mirceaulinic.net> & Jerome Fleury <jf@cloudflare.com> :maturity: new :depends: napalm :platform: unix Dependencies ------------ - :mod:`NAPALM proxy minio...
the moment this only calls the ``net.load_template`` function from the :mod:`Network-related basic features execution module <salt.modules.napalm_network>`, but this may change in time. """ return __salt__["net.load_template"]( template_name, template_source=template_source, templa...
e_group, template_mode=template_mode, template_attrs=template_attrs, saltenv=saltenv, template_engine=template_engine, skip_verify=skip_verify, defaults=defaults, test=test, commit=commit, debug=debug, replace=replace, **template_va...
klusta-team/klustaviewa
klustaviewa/gui/tests/test_recluster.py
Python
bsd-3-clause
2,906
0.008259
"""Experiment tests.""" # ----------------------------------------------------------------------------- # Imports # ----------------------------------------------------------------------------- import os import shutil import tempfile import numpy as np impor
t pandas as pd import
tables as tb from nose import with_setup from klustaviewa.gui.recluster import run_klustakwik from kwiklib.dataio.kwik import (add_recording, create_files, open_files, close_files, add_event_type, add_cluster_group, get_filenames, add_cluster, add_spikes) from kwiklib.dataio.experiment import (Experiment, _re...
wileeam/airflow
airflow/providers/http/sensors/http.py
Python
apache-2.0
4,531
0.000662
# # 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...
re key is string and value depends on the option that's being modified. """ template_fields = ('endpoint', 'request_params') @apply_defaults def __init__(self, endpoint: str, http_conn_id: str = 'http_default', method: str = 'GET', ...
al[Dict] = None, headers: Optional[Dict] = None, response_check: Optional[Callable] = None, extra_options: Optional[Dict] = None, *args, **kwargs): super().__init__(*args, **kwargs) self.endpoint = endpoint self.http_conn_id = http_conn_id ...
bryanph/OIPA
OIPA/indicator_unesco/admin.py
Python
agpl-3.0
6,035
0.006462
import xml.etree.cElementTree as etree from django.contrib import admin from django.shortcuts import get_object_or_404 from multiupload.admin import MultiUploadAdmin from indicator.upload_indicators_helper import find_country, fi
nd_city, get_countries, get_citi
es, get_value, save_log, save_city_data, save_country_data from indicator_unesco.models import UnescoIndicatorData, UnescoIndicator from translation_model.models import TranslationModel class UnescoIndicatorDataUploadAdmin(MultiUploadAdmin): list_display = ['unesco_indicator','country', 'value'] search_fields...
edoburu/django-fluent-contents
fluent_contents/plugins/gist/migrations/0001_initial.py
Python
apache-2.0
1,780
0.001124
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [("fluent_contents", "0001_initial")] operations = [ migrations.CreateModel( name="GistItem", fields=[ ...
eave the filename empty to display all files in the Gist.", max_length=128, verbose_name="Gist filename", blank=True, ), ), ], options={ "db_table": "contentitem_gist_gisti...
}, bases=("fluent_contents.contentitem",), ) ]
tarunbod/dotfiles
scripts/todo.py
Python
mit
1,774
0.002825
#!/usr/bin/env python3 import os.pat
h, sys, json from collections import OrderedDict todo_list = OrderedDict() file_path = os.path.expanduser('~/.todo_list.json') if os.path.isfile(file_path): with open(file_path, 'r') as todo_list_file: todo_list.update(json.load(todo_list_file)) args = sys.argv[1:] def usage(): usage = """Usage: t...
<task number> todo.py done <task number>""" print(usage) sys.exit(0) if len(args) < 1: args = ["list"] task_count = len(todo_list) if args[0] == "add": if len(args) != 2: usage() name = args[1] todo_list[str(task_count + 1)] = { "name": name, "completed": False ...
thomashaw/SecGen
modules/utilities/unix/ctf/metactf/files/repository/src_angr/solutions/14_angr_shared_library/scaffold14.py
Python
gpl-3.0
2,337
0.021395
# The shared library has the function validate, which takes a string and returns # either true (1) or false (0). The binary calls this function. If it returns # true, the program prints "Good Job." otherwise, it prints "Try again." import angr import claripy import sys def main(argv): path_to_binary = ??? # The ...
program places the return v
alue, and constrain it so # that it is true. Then, solve for the solution and print it. # (!) solution = ??? print solution else: raise Exception('Could not find the solution') if __name__ == '__main__': main(sys.argv)
axbaretto/beam
sdks/python/.tox/py27gcp/lib/python2.7/site-packages/hamcrest/core/helpers/wrap_matcher.py
Python
apache-2.0
880
0.002273
import six from hamcrest.core.base_matcher import Matcher from hamcrest.core.core.isequal import equal_to __author__ = "Jon Reid" __
copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" import types def wrap_matcher(x): """Wraps argument in a matcher, if necessary. :returns: the argument as-is if it is already a matcher, otherwise wrapped in an :py:func:`~hamcrest.core.core.iseq
ual.equal_to` matcher. """ if isinstance(x, Matcher): return x else: return equal_to(x) def is_matchable_type(expected_type): if isinstance(expected_type, type): return True if isinstance(expected_type, six.class_types): return True if isinstance(expected_type...
fdev/bc125csv
bc125csv/__init__.py
Python
mit
548
0.001825
""" bc125csv - Channel import and expor
t tool for the Uniden BC125AT, UBC125XLT and UBC126AT. Copyright (c) 2020, fdev.nl. All rights reserved. Released under the MIT license. Uniden and Bearcat are registered trademarks of Uniden America Corporation. This application and its author are not affiliated with or endorsed by Uniden in any way. """ __author_...
le_scripts from bc125csv.handler import main
lancezlin/ml_template_py
lib/python2.7/site-packages/jupyter_console/_version.py
Python
mit
353
0.002833
""" For beta/alpha/rc releases, the version number for a beta is X.Y.ZbN **without dots between the last 'micro' number and b**. N is the number of the beta rel
eased i.e. 1, 2, 3 ... See PEP 440 https://www.python.org/dev/peps/pep-0440/ """ version_info = (5, 0, 0, '') __version__ = '.'.join(map(str, version_info[:3])) + '
'.join(version_info[3:])
Deepakkothandan/ansible
test/runner/lib/cloud/vcenter.py
Python
gpl-3.0
4,919
0.002236
"""VMware vCenter plugin for integration tests.""" from __future__ import absolute_import, print_function import os from lib.cloud import ( CloudProvider, CloudEnvironment, ) from lib.util import ( find_executable, display, ) from lib.docker_util import ( docker_run, docker_rm, docker_in...
display.info('Found vCenter simulator container address: %s'
% vcenter_host, verbosity=1) else: vcenter_host = 'localhost' self._set_cloud_config('vcenter_host', vcenter_host) def _get_simulator_address(self): results = docker_inspect(self.args, self.container_name) ipaddress = results[0]['NetworkSettings']['IPAddress'] ...
MSMBA/msmba-workflow
msmba-workflow/srclib/wax/examples/core-getapp.py
Python
gpl-2.0
233
0.012876
# core-getapp.py from wax import * c
lass MainFrame(Frame): def Body(self): app = core.GetApp() print app assert isinstance(app, Application) app
= Application(MainFrame, title="core-getapp") app.Run()
susurrant-audio/scdown
scdown/__init__.py
Python
mit
9
0
#
scdo
wn
Schevo/schevo
schevo/signal.py
Python
mit
304
0
"""PyDispatcher signals."""
# Copyright (c) 2001-2009 ElevenCraft Inc. # See LICENSE for details. from schevo.constant import _GLOBAL class Transact
ionExecuted(object): """Signal sent using PyDispatcher to indicate that a transaction was successfully executed.""" __metaclass__ = _GLOBAL
ritashugisha/ASUEvents
ASUEvents/managers/migrations/0010_auto_20150422_2018.py
Python
mit
581
0.001721
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import
models, migrations class Migration(migrations.Migration): dependencies = [ ('managers', '0009_managerprofile_description'), ] operations = [ migrations.AlterField( model_name='managerprofile', name='picture', field=models.ImageField(default=b'/static/...
), ]
ArcticCore/arcticcoin
qa/rpc-tests/keypool-hd.py
Python
mit
4,165
0.003361
#!/usr/bin/env python2 # Copyright (c) 2014-2015 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # Exercise the wallet keypool, and interaction with wallet encryption/locking # Add python-bitcoinrpc to...
rypt wallet and wait to terminate nodes[0].encryptwallet('test') bitcoind_processes[0].wait() # Restart node 0 node
s[0] = start_node(0, self.options.tmpdir, ['-usehd=1']) # Keep creating keys addr = nodes[0].getnewaddress() addr_data = nodes[0].validateaddress(addr) wallet_info = nodes[0].getwalletinfo() assert(addr_before_encrypting_data['hdchainid'] == wallet_info['hdchainid']) asse...
andersk/zulip
zerver/tests/test_realm_domains.py
Python
apache-2.0
7,224
0.002215
import orjson from django.core.exceptions import ValidationError from django.db.utils import IntegrityError from zerver.lib.actions import ( do_change_realm_domain, do_change_user_role, do_create_realm, do_remove_realm_domain, do_set_realm_property, ) from zerver.lib.domains import validate_domain ...
t_not_realm_admin(self) -> None: self.login("hamlet") result = self.client_post("/json/realm/domains")
self.assert_json_error(result, "Must be an organization administrator") result = self.client_patch("/json/realm/domains/15") self.assert_json_error(result, "Must be an organization administrator") result = self.client_delete("/json/realm/domains/15") self.assert_json_error(result,...
hiperwalk/hpwalk
Archive/neblina.py
Python
gpl-2.0
22,919
0.014442
# -*- coding: utf-8 -*- """ Created on Mon Jun 23 04:56:43 2014 @author: aaron """ import os import subprocess import numpy as np import config as cfg def runCore_DTQW1D(): if cfg.TEST_MODE: os.system("neblina -id %d HIPERWALK_TEMP_DTQW1D.nbl %d %d %d %d %d %d %d >> /dev/null "%(cfg.HARDWAREID,cfg.S...
)\n") # output.write(" <<< PROBABILITY_VECTOR\n") output.write(" print( f, PROBABILITY_VECTOR )\n") # output.write(" >>> PROBABILITY_VECTOR\n") output.write(" end\n") output.write("\n")
output.write(" tmp = vec_prod( DISTANCES_SQUARE, PROBABILITY_VECTOR )\n") output.write("\n") output.write(" s1 = vec_sum( tmp ) \n") output.write(" tmp = vec_prod( DISTANCES, PROBABILITY_VECTOR )\n") output.write(" mean = vec_sum( tmp )\n") output.write(" stddev = sqrt(abs(s1-mean...
unioslo/cerebrum
Cerebrum/rest/server.py
Python
gpl-2.0
2,520
0
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2016-2019 University of Oslo, Norway # # This file is part of Cerebrum. # # Cerebrum 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. # # Cerebrum is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even ...
the GNU General Public License # along with Cerebrum; if not, write to the Free Software Foundation, # Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. from Cerebrum.rest.api import create_app app = create_app('restconfig') def main(inargs=None): import argparse import Cerebrum.logutils imp...
kartikeys98/coala
coalib/core/Bear.py
Python
agpl-3.0
15,542
0
from collections import defaultdict from functools import partial import inspect import logging from os import makedirs from os.path import join, abspath, exists from appdirs import user_data_dir from coala_utils.decorators import (enforce_signature, classproperty, get_public_membe...
Returns the directory this bear is inside. >>> class SomeBear(Bear): pass >>> SomeBear.source_location '...Bear.py' """ return inspect.getfile(cls) @classproperty def maintainers(cls):
""" :return: A set containing ``MAINTAINERS`` if specified, else takes ``AUTHORS`` by default. """ return cls.AUTHORS if cls.MAINTAINERS == set() else cls.MAINTAINERS @classproperty def maintainers_emails(cls): """ :return: A set ...
bladebo/1flow
oneflow/settings/snippets/000_nobother.py
Python
agpl-3.0
1,544
0.001944
# -*- coding: utf-8 -*- """ Copyright 2013 Olivier Cortès <oc@1flow.io> This file is part of the 1flow project. 1flow 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 o...
on) any later version. 1flow 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 Affero General Public License for more details. You should have received a copy of the GN...
rnings.catch_warnings(): # These warnings are produced by external packages # that we use in 1flow. We have no time to fix them # ourselves, and their developers didn't update their # own code. BUMMER! warnings.filterwarnings("ignore", category=DeprecationWarning) import django.conf.urls.defaul...
csdms/coupling
pymt/mappers/__init__.py
Python
mit
285
0
from .
mapper import find_mapper, IncompatibleGridError from .celltopoint import CellToPoint from .pointtopoint import NearestVal from .pointtocell import PointToCell __all__ = [ "find_mapper", "IncompatibleGridError", "CellToPoint", "NearestVal", "PointToCell",
]
michailbrynard/django-skeleton
src/config/settings/extensions/guardian.py
Python
mit
180
0.005556
AUTHENTICATION_BACKENDS = ( 'django.contrib.a
uth.backends.ModelBackend', # default 'guardian.backends.ObjectPermissionBackend', ) # DJANGO GUARDIAN ANONYMOUS_USER_ID = -1
snowball-one/cid
cid/cursor.py
Python
bsd-3-clause
1,697
0.000589
from django.conf import settings from .locals import get_cid DEFAULT_CID_SQL_COMMENT_TEMPLATE = 'cid: {cid}' class CidCursorWrapper: """ A cursor wrapper that attempts to add a cid comment to each query """ def __init__(self, cursor): self.cursor = cursor def __getattr__(self, attr): ...
te(sql, params)
def executemany(self, sql, param_list): sql = self.add_comment(sql) return self.cursor.executemany(sql, param_list)
EvolutionClip/pyload
module/gui/CoreConfigParser.py
Python
gpl-3.0
5,711
0.014358
# -*- coding: utf-8 -*- from __future__ import with_statement from os.path import exists from os.path import join CONF_VERSION = 1 ######################################################################## class ConfigParser: #---------------------------------------------------------------------- def __init_...
False value = value[:-1] else: listmode = True value = [self.cast(typ, x.strip()) for x in value[1:].split(",") if x] else: ...
value = self.cast(typ, value) if not listmode: conf[section][option] = { "desc" : desc, "type" : typ, "value" : value} ...
zhuyue1314/claripy
claripy/vsa/valueset.py
Python
bsd-2-clause
9,471
0.002428
import functools import itertools from ..backend_object import BackendObject def normalize_types(f): @functools.wraps(f) def normalizer(self, region, o): ''' Convert any object to an object that we can process. ''' if isinstance(o, IfProxy): return NotImplemented ...
return new_vs def __eq__(self,
other): if isinstance(other, ValueSet): same = False different = False for region, si in other.regions.items(): if region in self.regions: comp_ret = self.regions[region] == si if BoolResult.has_true(comp_ret): ...
Azure/azure-sdk-for-python
sdk/agfood/azure-mgmt-agfood/azure/mgmt/agfood/aio/_configuration.py
Python
mit
3,236
0.004017
# 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 ...
on_id: str """ def __init__( self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any ) -> None: if credential is None: raise ValueError("Parameter 'credential' must not
be None.") if subscription_id is None: raise ValueError("Parameter 'subscription_id' must not be None.") super(AzureAgFoodPlatformRPServiceConfiguration, self).__init__(**kwargs) self.credential = credential self.subscription_id = subscription_id self.api_version = "...
Neurochain/neurowrk
src/processor.py
Python
mit
1,697
0.004125
from ipfs_
connector import IPFSConnector, IPFSConfig from nn_loader import NNListener, NNLoader class ProcessorCallback: pass class Processor(NNListener): def __init_
_(self, callback: ProcessorCallback, ipfs_config: IPFSConfig): print("Connecting to IPFS server %s:%d..." % (ipfs_config.server, ipfs_config.port)) try: self.ipfs_connector = IPFSConnector(ipfs_config) except: raise IPFSError("Can't connect IPFS server") print("IP...
Valtis/YATCP
tests/programs/test_programs/generated_arithmetic_expression_tests_integers/_generate_tests.py
Python
gpl-2.0
26,983
0.000815
INT_MAX = 2**31-1 INT_MIN = -INT_MAX-1 """ Tuples of: * Test file name without extension * Initialization expression(s) (e.g. variable declarations) * Expression for return statement * Expected answer """ test_tuples = [ # constant ("positive_constant...
f"let a: int = {INT_MAX};", "a*2", -2), ("negative_multiplication_result_can_overflow", f"let a: int = {INT_MIN};", "a*(-1)", INT_MIN, ), # division ("constant_constant_division_works_when_result_is_positive", "", "7/2", ...
_rhs_operand_is_negated", "", "5/(-2)", -2), ("variable_constant_division_works", "let a: int = 20;", "a/5", 4), ("variable_constant_self_assignment_division_works", """ let a: int = 20; a = a / 5; """, "a", ...
lnielsen/invenio
invenio/utils/remote_debugger/wsgi_reload.py
Python
gpl-2.0
3,968
0.006552
## This file is part of Invenio. ## Copyright (C) 2011 CERN. ## ## Invenio is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either version 2 of the ## License, or (at your option) any later version. ## ## Inv...
ion times on all files in sys.modules. for module in sys.modules.values(): if not hasattr(module, '__file__'): continue
path = getattr(module, '__file__') if not path: continue if os.path.splitext(path)[1] in ['.pyc', '.pyo', '.pyd']: path = path[:-1] if _modified(path): return _restart(path) # Check modification times on files which have...
facebookresearch/ParlAI
parlai/agents/examples/seq2seq.py
Python
mit
7,495
0.001734
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. r""" Example TorchGeneratorAgent model. This demonstrates the minimal structure of a building a generative model, consi...
ces): """ Reorder the decoder states to select only the given batch indices. This method can be a stub which always returns None; this will result in the decoder doing a complete forward pass for every sing
le token, making generation O(n^2). However, if any state can be cached, then this method should be implemented to reduce the generation complexity to O(n). """ h, c = incr_state return h[:, indices, :], c[:, indices, :] class Seq2seqAgent(tga.TorchGeneratorAgent): """ ...
crmccreary/openerp_server
openerp/addons/point_of_sale/account_bank_statement.py
Python
agpl-3.0
3,115
0.004173
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2008 PC Solutions (<http://pcsol.be>). All Rights Reserved # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free...
nt of sales."), } _defaults = { 'check_dtls': False, 'auto_cash': True, } account_journal() class account_cash_statement(osv.osv): _inherit = 'account.bank.statement' def _equal_balance(self, cr, uid, cash_id, context=None): statement = self.browse(cr, uid, cash_id, contex...
ournal_id.check_dtls: return True if statement.journal_id.check_dtls and (statement.balance_end != statement.balance_end_cash): return False else: return True def _get_cash_open_box_lines(self, cr, uid, context=None): res = super(account_cash_statement,se...
mvaled/sentry
src/sentry/utils/pytest/sentry.py
Python
bsd-3-clause
8,427
0.001187
from __future__ import absolute_import import mock import os from django.conf import settings from sentry_sdk import Hub TEST_ROOT = os.path.normpath( os.path.join(os.path.dirname(__file__), os.pardir, os.pardir, os.pardir, os.pardir, "test
s") ) def pytest_configure(config): # HACK: Only needed for testing! os.environ.setdefault("_SENTRY_SKIP_CONFIGURATION", "1") os.environ.setdefault("DJANGO_SETTINGS_MODULE", "sentry.conf.server") # override docs which are typically synchronized from an upstream server # to ensure tests are consi...
"fixtures", "integration-docs") ) from sentry.utils import integrationdocs integrationdocs.DOC_FOLDER = os.environ["INTEGRATION_DOC_FOLDER"] if not settings.configured: # only configure the db if its not already done test_db = os.environ.get("DB", "postgres") if test_db == "pos...
jungla/ICOM-fluidity-toolbox
2D/U/plot_vKE_mli.py
Python
gpl-2.0
1,416
0.010593
import os, sys import vtktools import fluidity_tools import numpy as np import matplotlib as mpl mpl.use('ps') import matplotlib.pyplot as plt label0 = 'm_25_3b' label1 = 'm_25_3b' basename1 = 'mli_checkpoint' basename0 = 'mli' path0 = '/tamay2/mensa/fluidity/'+label0+'/' path1 = '/tamay2/mensa/fluidity/'+label1+'/'...
filepath0 = path0+file0 stat0 = fluidity_tools.stat_parser(filepath0) file1 = basename1+'.stat' filepath1 = path1+file1 stat1 = fluidity_to
ols.stat_parser(filepath1) time0 = stat0["ElapsedTime"]["value"]/86400.0 time1 = stat1["ElapsedTime"]["value"]/86400.0 KE0 = (stat0["BoussinesqFluid"]["Velocity%3"]["l2norm"])/np.sqrt((2000*2000*50)) KE1 = (stat1["BoussinesqFluid"]["Velocity%3"]["l2norm"])/np.sqrt((2000*2000*50)) #time1[time1 > 1] = np.nan #KE1[time...
kilon/sverchok
utils/sv_viewer_utils.py
Python
gpl-3.0
2,130
0.003286
import re import random import bpy import mathutils from mathutils import Vector, Matrix def matrix_sanitizer(matrix): # reduces all values below threshold (+ or -) to 0.0, to avoid meaningless # wandering floats. coord_strip = lambda c: 0.0 if (-1.6e-5 <= c <= 1.6e-5) else c san = lambda v: Vector...
t_names, key=extended_sort) last = natural_sort[-1] num = extended_sort(last) return num+1 def get_random_init(): objects = bpy.data.objects greek_alphabet = [ 'Alpha', 'Beta', 'Gamma', 'Delta', 'Epsilon', 'Zeta
', 'Eta', 'Theta', 'Iota', 'Kappa', 'Lamda', 'Mu', 'Nu', 'Xi', 'Omicron', 'Pi', 'Rho', 'Sigma', 'Tau', 'Upsilon', 'Phi', 'Chi', 'Psi', 'Omega'] with_underscore = lambda obj: '_' in obj.name and obj.type == 'MESH' names_with_underscores = list(filter(with_underscore, objects)) ...
OVERLOADROBOTICA/OVERLOADROBOTICA.github.io
mail/formspree-master/formspree/static_pages/views.py
Python
mit
788
0
from flask import request, render_template, g, \ redirect, url_for from jinja2 import TemplateNotFound def default(template='index'): template = template if template.endswith('.html') else template+'.html' try: return render_template('static_pages/' + template, ...
return render_template('static_pages/404.html'), 404 def internal_error(e): import traceback g.log.error(traceback.format_exc()) return render_template('static_pages/500.html'), 500 def favicon(): return redirect(url_for('static', filename='img/favicon.ico')) def formspree_verify(
): return redirect(url_for('static', filename='formspree-verify.txt'))
arcticfoxnv/slackminion
slackminion/utils/test_helpers/bot.py
Python
mit
366
0
from slackminion.bot import Bot from slackminion.webserver import Webserver class DummyBot(Bot): def __init__(self, *args, **kwargs): super(DummyBot, s
elf).__init__(None, *args, **kwargs) setattr(self, 'start', lambda: None) setattr(self, 'send_message', lambda x, y, z, a: None) se
lf.webserver = Webserver('127.0.0.1', '9999')
thequbit/Velociwrapper
velociwrapper/querybuilder.py
Python
bsd-3-clause
6,429
0.043086
import copy from . import qdsl class QueryBody(object): def __init__(self): self._filter = { 'must':[], 'should':[], 'must_not':[], 'and':[], 'not':[], 'or':[] } self._query = { 'must':[], 'should':[], 'must_not':[] } self._bool = 'must' self._last_part = '_query' self._explicit = None def chain( self, ne...
ondition = True if q_type_count > 1: query_is_multi_condition = True query_needs_bool = True _output_query = {} if is_query: if query_needs_bool: _output_query = { 'bool': _query } else: _output_query = _query[q_type] _output_query = { 'query': _output_query } else: _output_query = ...
_output_filter = {} if filter_needs_bool: _output_filter = { 'bool': _filter } #elif len(_filter[f_type]) == 1: # _output_filter = _filter[f_type][0] elif filter_is_multi_condition or isinstance( _filter[f_type], list): _output_filter = _filter # explicit queries else: _output_filter = _fil...
tldavies/RackHD
test/stream-monitor/setup.py
Python
apache-2.0
552
0.018116
""" todo: add """ try: import ez_setup ez_setup.use_setuptools() except ImportError: pass from setuptools import setup setup( name='stream monitors', version='0.1', author='Stuart Stanley', author_email = 'stuart.stanley@dell.com', description = 'Stream-monitors and test-log-groupers',...
points = { 'nose.plugins.0.10': [ 'stream_monitor = sm_plugin:Stre
amMonitorPlugin' ] } )
awurster/jira
jira/version.py
Python
bsd-2-clause
232
0
# -*- coding: utf-8 -*- # Store the version here so: # 1) we don
't load dependencies by storing it in __init__.py # 2) we can import it in setup.py f
or the same reason # 3) we can import it into the jira module __version__ = '0.48'
florian-dacosta/chronopost
chronopost_api/chronopost.py
Python
agpl-3.0
11,111
0.00387
#!/usr/bin/env python # -*- coding: utf-8 -*- """ In order to use this lib, you have to call the method 'get_shipping_label' with the right arguments. To know which keys to send to this method read these lists : - req
uired fields - fields """ from datetime import datetime import re from suds.client import Client, WebFault from .label_helper import AbstractLabel from .exception_helper import ( InvalidSequence, Inv
alidWeight, InvalidSize, InvalidType, InvalidMissingField, InvalidZipCode, InvalidCountry, InvalidDate, InvalidCode, InvalidValue, InvalidValueNotInList, ) WEBSERVICE_URL = 'https://ws.chronopost.fr/shipping-cxf/ShippingServiceWS?wsdl' ESD_MODEL = { "retrievalDateTime": ...
projectcalico/calico
calicoctl/tests/st/utils/utils.py
Python
apache-2.0
20,521
0.001998
# Copyright (c) 2015-2016 Tigera, 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 applicabl...
the output from running a calicoctl command using the calicoctl function below. This class contains the command, output and error code (if it failed) along with YAML/JSON decoded output if the output could be decoded. """ def __init__(self, command, outp
ut, error=None): self.command = command self.output = output self.error = error # Attempt to decode the output and store the output format. self.decoded, self.decoded_format = decode_json_yaml(self.output) def assert_data(self, data, format="yaml", text=None): """ ...
opensciencegrid/myosg
bin/sample/xpah.py
Python
apache-2.0
1,855
0.007547
#!/usr/bin/python import urllib import libxml2 #download VO activation XML url = urllib.urlopen("http://myosg.grid.iu.edu/voactivation/xml?datasource=activation&start_type=7daysago&start_date=10%2F09%2F2009&end_type=now&end_date=10%2F09%2F2009&all_vos=on&active_value=1") vo_activation = url.read() url.close() #downlo...
t "\tReporting Group: " + name fqans = group.xpathEval("FQANs/F
QAN") print "\t\tFQANs:" for fqan in fqans: print "\t\t\t" + fqan.content contacts = group.xpathEval("Contacts/Contact/Name") print "\t\tContacts:" for contact in contacts: print "\t\t\t" + contact.content
bsipocz/astropy
astropy/tests/runner.py
Python
bsd-3-clause
22,579
0.000709
"""Implements the Astropy TestRunner which is a thin wrapper around py.test.""" import inspect import os import glob import copy import shlex import sys import tempfile import warnings import importlib from collections import OrderedDict from importlib.util import find_spec from functools import wraps from astropy.co...
# comprised of the docstrings for the ``keyword`` methods. # To add a keyword argument to the ``run_tests`` method, define a new # method decorated with ``@keyword`` and with the ``self, name, kwargs`` # signature. # Get all 'function' members as the wrapped
methods are functions functions = inspect.getmembers(cls, predicate=inspect.isfunction) # Filter out anything that's not got the name 'keyword' keywords = filter(lambda func: func[1].__name__ == 'keyword', functions) # Sort all keywords based on the priority flag. sorted_keywor...
lkundrak/scraperwiki
web/global_settings.py
Python
agpl-3.0
8,733
0.004122
""" Global settings file. Everything in here is imported *before* everything in settings.py. This means that this file is used for default, fixed and global varibles, and then settings.py is used to overwrite anything here as well as adding settings particular to the install. Note that there are no tuples h...
text_processors.i18n', 'django.core.context_processors.media', 'django.core.context_proces
sors.request', 'django.contrib.messages.context_processors.messages', 'django_notify.context_processors.notifications', 'frontend.context_processors.site', 'frontend.context_processors.template_settings', 'frontend.context_processors.vault_info', # 'frontend.context_processors.site_messages', # disa...
matteoredaelli/scrapy_tyres
bin/csv2json.py
Python
gpl-3.0
755
0.007947
## -*- coding: utf-8 -*- import sys import csv import os, datetime import datetime import logging, json filei
n = sys.argv[1] fileout = sys.argv[2] source = sys.argv[3] #today = datetime.datetime.strptime(sys.argv[4], "%Y-%m-%d") today=sys.argv[4] sep = sys.argv[5] if len(sys.argv) == 6 else "\n" if sep == "\\t": sep = "\t" #with open(filein, newline='', encoding='utf-8') as csvfile: with open(filein, newline='', encodi...
reader: row = dict(row) row["source"] = source row["crawled"] = today json.dump(row, f, ensure_ascii=False) f.write("\n")
mitodl/lore
xanalytics/tests/test_api.py
Python
agpl-3.0
2,673
0
""" Tests for hitting the xanalytics API. """ import json import logging from unittest import TestCase from django.conf import settings import responses from xanalytics import send_request, get_result, _call log = logging.getLogger(__name__) class TestAPI(TestCase): """ Tests using mocks to avoid actual H...
RL = "http://example.com" def tearDown(self): """Restore original setting.""" super(TestBadData, self).tearDown() settings.
XANALYTICS_URL = self.original_url @responses.activate def test_server_down(self): """Endpoint unavailable.""" resp = _call(settings.XANALYTICS_URL, {}) self.assertEqual(resp, {}) @responses.activate def test_binary(self): """ Binary data received. This also imp...
c4fcm/CivilServant
app/time_on_page_script.py
Python
mit
3,564
0.006453
import os import simplejson as json import datetime from utils.common import PageType, DbEngine from app.models import Base, SubredditPage, FrontPage def construct_rank_vectors(pages): rank_vectors = {} # {pid: {time: rank}} for page in pages: posts = json.loads(page.page_data) for i,post ...
n, end_time=datetime.datetime.max): values = { "total_time": 0, "gap_size": None, "num_gaps": 0, "sum_gaps": 0 } # connect to database. assuming this file is in a folder like a
pp. so you have to do "../config" to get to config BASE_DIR = os.path.join(os.path.dirname(os.path.realpath(__file__)), "../") ENV = os.environ['CS_ENV'] db_session = DbEngine(os.path.join(BASE_DIR, "config") + "/{env}.json".format(env=ENV)).new_session() pages = [] if not subreddit_id: # t...
thehub/hubplus
apps/plus_groups/forms.py
Python
gpl-3.0
5,946
0.012782
from datetime import datetime, timedelta from django.contrib.contenttypes.models import ContentType from django import forms from django.conf import settings from django.template.loader import render_to_string from django.utils.hashcompat import sha_constructor from django.utils.translation import ugettext_lazy as _, u...
n(self): self.cleaned_data['name']
= title_to_name(self.cleaned_data['title']) if not self.cleaned_data['name'] : self._errors['title']=_('Title must include alphabetic and / or numeric characters.') if self._errors: return self.cleaned_data self.cleaned_data['type_string'] = self.cleaned_data['create_i...
reedstrm/Pyrseas
pyrseas/testutils.py
Python
bsd-3-clause
19,886
0.000201
# -*- coding: utf-8 -*- """Utility functions and classes for testing Pyrseas""" import sys import os import getpass import tempfile from unittest import TestCase import yaml from pyrseas.config import Config from pyrseas.database import Database from pyrseas.augmentdb import AugmentDatabase from pyrseas.lib.dbconn i...
t() # Conversions curs = pgexecute( self.conn, """SELECT conname FROM pg_conversion c JOIN pg_namespace n ON (connamespace = n.oid) WHERE nspname NOT IN ('pg_catalog', 'information_schema')""") convs = curs.fetchall() curs.clo...
self.version >= 90100: curs = pgexecute( self.conn, """SELECT collname FROM pg_collation c JOIN pg_namespace n ON (collnamespace = n.oid) WHERE nspname NOT IN ( 'pg_catalog', 'information_schema')""") ...
CIRCL/AIL-framework
var/www/Flask_server.py
Python
agpl-3.0
8,669
0.005076
#!/usr/bin/env python3 # -*-coding:UTF-8 -* import os import sys import ssl import json import time import uuid import redis import random import logging import logging.handlers from flask import Flask, render_template, jsonify, request, Request, Response, session, redirect, url_for from flask_login import LoginMana...
blueprint(ail_2_ail_sync, url_prefix=baseUrl) # ========= =========# # ========= Cookie name ======== app.config.update
(SESSION_COOKIE_NAME='ail_framework_{}'.format(uuid.uuid4().int)) # ========= session ======== app.secret_key = str(random.getrandbits(256)) login_manager = LoginManager() login_manager.login_view = 'root.login' login_manager.init_app(app) print() # ========= LOGIN MANAGER ======== @login_manager.user_loader def lo...
Mesitis/community
sample-code/Python/25 Cashflows/get_cashflow_earnings.py
Python
mit
2,695
0.015213
''' - login and get token - process 2FA if 2FA is setup for this account - Get cashflow earnings for a given user ''' import requests import json get_token_url = "https://api.canopy.cloud:443/api/v1/sessions/" validate_otp_url = "https://api.canopy.cloud:443/api/v1/sessions/otp/validate.json" #calling the productio...
nse.json()['users']: partner_users.append(parent_user['id']) #print partner_users #take the first users in the list as the switch_user_id switch
_user_id = partner_users[0] #in case the user is a partner_admin then switch_user_id is any one of the users it has access to (here we take the first one from the list) #set per page value per_page = "20" querystring = {"page":"1","per_page":per_page} headers = { 'authorization': token, 'content-type': "app...
hulingfeng211/weixin
wechat/__init__.py
Python
apache-2.0
2,996
0.01843
# -*- coding:utf-8 -*- import json import logging import os from tornado import gen from tornado.gen import coroutine, Task from tornado.httpclient import AsyncHTTPClient from tornado.ioloop import IOLoop from tornado.web import RequestHandler from core import settings import constant __author__ = 'george' @corout...
access_token) except Exception, e:
raise gen.Return(access_token) def generate_media_message(users,content,agentid,type,safe=0): """生成图片、声音、文件三类消息""" body = { "touser": users if isinstance(users,unicode) or isinstance(users,str) else reduce(lambda x,y:x+'|'+y,users), "toparty": "", "totag": "", "msgtype"...
filipp/Servo
servo/forms/product.py
Python
bsd-2-clause
7,202
0.003055
# -*- coding: utf-8 -*- # Copyright (c) 2013, First Party Software # All rights reserved. # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright notice, # t...
aseModelForm): class Meta: model = ProductCategory exclude = [] class PurchaseOrderSearchForm(forms.Form): state = forms
.ChoiceField( required=False, label=_('State is'), choices=( ('', _('Any')), ('open', _('Open')), ('submitted', _('Submitted')), ('received', _('Received')), ), widget=forms.Select(attrs={'class': 'input-small'}) ) created_b...
ahmad88me/tada
tadacode/tadaa/ppool.py
Python
mit
1,341
0.000746
from multiprocessing import Process class Pool(object): def __init__(self, max_num_of_processes, func, params_list): self.max_num_of_processes = max_num_of_processes self.func = func self.params_list = params_list self.processes = [] self.active_processes = [] def run(...
x_num_of_processes - num_of_active_processes): if len(self.processes) > 0: p = self.processes.pop(0) p.start() print "spawn!" print "active processes: %d" % n
um_of_active_processes self.active_processes.append(p) [p.join() for p in self.active_processes]
chop-dbhi/varify-data-warehouse
vdw/samples/migrations/0038_auto__del_samplerun.py
Python
bsd-2-clause
24,516
0.008525
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Deleting model 'SampleRun' db.delete_table('sample_run') def backwards(self, orm): # Adding ...
abel': ('django.db.models.fields.CharField', [], {'max_length': '20'}), 'order': ('
django.db.models.fields.IntegerField', [], {'default': '0'}), 'value': ('django.db.models.fields.CharField', [], {'max_length': '3'}) }, 'literature.pubmed': { 'Meta': {'object_name': 'PubMed', 'db_table': "'pubmed'"}, 'pmid': ('django.db.models.fields.IntegerField', ...
mapycz/mapnik
scons/scons-local-3.0.1/SCons/Tool/xgettext.py
Python
lgpl-2.1
13,879
0.001297
""" xgettext tool Tool specific initialization of `xgettext` tool. """ # Copyright (c) 2001 - 2017 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction...
########################### ############################################################################# from SCons.Builder import BuilderBase ############################################################################# class _POTBuilder(B
uilderBase): def _execute(self, env, target, source, *args): if not target: if 'POTDOMAIN' in env and env['POTDOMAIN']: domain = env['POTDOMAIN'] else: domain = 'messages' target = [domain] return BuilderBase._execute(self, env, tar...