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
TribeMedia/synapse
synapse/server.py
Python
apache-2.0
11,005
0.000091
# -*- coding: utf-8 -*- # Copyright 2014-2016 OpenMarket Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
return AuthH
andler(self) def build_macaroon_generator(self): return MacaroonGeneartor(self) def build_device_handler(self): return DeviceHandler(self) def build_device_message_handler(self): return DeviceMessageHandler(self) def build_e2e_keys_handler(self): return E2eKeysHandler...
miloszz/DIRAC
DataManagementSystem/Client/FTSRequest.py
Python
gpl-3.0
37,261
0.02818
############################################################################# # $HeadURL$ ############################################################################# """ ..mod: FTSRequest ================= Helper class to perform FTS job submission and monitoring. """ # # imports import sys import re import...
se self.sourceToken = res['Value'] self.sourceValid = True return S_OK() def setTargetSE( self, se ): """ set target SE :param self: self reference :param str se: target
SE name """ if se == self.sourceSE: return S_ERROR( "TargetSE is SourceSE" ) self.targetSE = se self.oTargetSE = StorageElement( self.targetSE ) return self.__checkTargetSE() def setTargetToken( self, token ): """ target space token setter :param self: self reference :param st...
XiaosongWei/blink-crosswalk
Tools/Scripts/webkitpy/layout_tests/port/driver.py
Python
bsd-3-clause
23,508
0.003148
# Copyright (C) 2011 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the ...
self._crashed_process_name = "unknown process name" self._crashed_pid = 0 if stop_when_done or crashed or timed_out or leaked: # We call stop() even if we crashed or timed out in order to get any remaining stdo
ut/stderr output. # In the timeout case, we kill the hung process as well. out, err = self._server_process.stop(self._port.driver_stop_timeout() if stop_when_done else 0.0) if out: text += out if err: self.error_from_test += err ...
peoplepower/botlab
com.ppc.Microservices/intelligence/dashboard/tools/set_status.py
Python
apache-2.0
7,607
0.00723
#!/usr/bin/env python # encoding: utf-8 ''' Created on September 24, 2019 @author: David Moss ''' import time # Time conversions to ms ONE_SECOND_MS = 1000 ONE_MINUTE_MS = 60 * ONE_SECOND_MS ONE_HOUR_MS = ONE_MINUTE_MS * 60 ONE_DAY_MS = ONE_HOUR_MS * 24 ONE_WEEK_MS = ONE_DAY_MS * 7 ONE_MONTH_MS = ONE_DAY_MS * 30 ONE...
DRESS = "update_dashboard_content" # # Data Stream Content # DATASTREAM_CONTENT = { # "type": 0, # "title": "NOW", # "weight": 0, # "content": { # "status": 0, # "comment": "Left the house once today.", # "weight": 25, # "id": "leave", # "icon": "house-leave", #...
# # Data Stream Content # DATASTREAM_CONTENT = { # "type": 0, # "title": "NOW", # "weight": 0, # "content": { # "status": 0, # "comment": "81% sleep score.", # "weight": 20, # "id": "sleep", # "icon": "snooze", # "icon_font": "far", # "alarms": { #...
ktan2020/legacy-automation
win/Lib/test/test_shutil.py
Python
mit
30,473
0.001313
# Copyright (C) 2003 Python Software Foundation import unittest import shutil import tempfile import sys import stat import os import os.path from os.path import splitdrive from distutils.spawn import find_executable, spawn from shutil import (_make_tarball, _make_zipfile, make_archive, ...
te(data) f.close() def read_data(path): f = open(path) data = f.read() f.close() return data src_dir = tempfile.mkdtemp() dst_dir = os.path.join(tempfile.mkdtemp(), 'destination') write_data(os.path.join(src_dir, ...
ee(src_dir, dst_dir) self.assertTrue(os.path.isfile(os.path.join(dst_dir, 'test.txt'))) self.assertTrue(os.path.isdir(os.path.join(dst_dir, 'test_dir'))) self.assertTrue(os.path.isfile(os.path.join(dst_dir, 'test_dir', 'test...
vbelakov/h2o
py/testdir_single_jvm/test_parse_mnist_fvec.py
Python
apache-2.0
2,023
0.006426
import unittest import random, sys, time, re sys.path.extend(['.','..','../..','py']) import h2o, h2o_cmd, h2o_browse as h2b, h2o_import as h2i, h2o_glm, h2o_util, h2o_rf class Basic(unittest.TestCase): def tearDown(self): h2o.check_sandbox_for_errors() @classmethod def setUpClass(cls): # ...
f test_parse_mnist_B_t
esting(self): importFolderPath = "mnist" csvFilelist = [ ("mnist_testing.csv.gz", 600), ("mnist_testing.csv.gz", 600), ] trial = 0 allDelta = [] for (csvFilename, timeoutSecs) in csvFilelist: testKey2 = csvFilename + "_" + str(trial) +...
dtamayo/rebound
rebound/widget.py
Python
gpl-3.0
25,951
0.006127
shader_code = """ <script id="orbit_shader-vs" type="x-shader/x-vertex"> uniform vec3 focus; uniform vec3 aef; uniform vec3 omegaOmegainc; attribute float lintwopi; varying float lin; uniform mat4 mvp; const float M_PI = 3.14159265359; void main() { float a = aef.x; float e...
he shader source code. g
lr.shaderSource(shader, shaderSource); // Compile the shader glr.compileShader(shader); // Check if it compiled var success = glr.getShaderParameter(shader, glr.COMPILE_STATUS); if (!success) { // Something went wrong during compilation; get the error throw "could not compile shader:" + glr.getSha...
fmartingr/iosfu
setup.py
Python
mit
1,441
0
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup, find_packages import re import os import sys def get_version(package): """ Return package version as listed in `__version__` in `init.py`. """ init_py = open(os.path.join(package, '__init__.py')).read() return re.search( ...
git tag -a %(version)s -m 'version %(version)s'" % args) print(" git push --tags") sys.exit() setup( name='iosfu', version=version, url='http://github.com/fmartingr/iosfu', license='MIT', description='iOS Forensics Utility', author='Felipe Martin', author_email='[email protected]',...
uirements.txt').read().split('\n'), classifiers=[ 'Development Status :: 1 - Planning', 'Intended Audience :: Developers', 'Intended Audience :: Other Audience' 'Operating System :: OS Independent', 'Programming Language :: Python ;; 2.7', 'Programming Language :: Pyt...
tristan-hunt/UVaProblems
DataStructures/ac.py
Python
gpl-3.0
6,305
0.00571
# Least common ancestor Problem #http://www.ics.uci.edu/~eppstein/261/BenFar-LCA-00.pdf # http://code.activestate.com/recipes/498243-finding-eulerian-path-in-undirected-graph/ # http://codereview.stackexchange.com/questions/104074/eulerian-tour-in-python # Store Arrays: Parents: P[i] is the parent of i # ...
o the root self.E = list() # nodes visited on the Eulerian tour of the tree self.L = list() self.R = list() # First visit of i on the Eulerian tour self.RMQ = dict() self.depth = 0 self.graph = defaultdict(list) def addEdge(self, u, v): self.graph[u].append(...
= self.graph[current].pop() while(queue): if self.graph[current]: queue.append(current) current = self.graph[current].pop() else: current = queue.pop() self.E.append(current) #print(self.E) def findDepth(self,...
max-posedon/telepathy-python
examples/tubeconn.py
Python
lgpl-2.1
3,866
0.001035
# This should eventually land in telepathy-python, so has the same license: # Copyright (C) 2007 Collabora Ltd. <http://www.collabora.co.uk/> # # 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 Founda...
OPERTIES_IFACE from telepathy.interfaces import CHANNEL_TYPE_DBUS_TUBE logger = logging.getLogger('telepathy.tubeconn') class TubeConnection(Connection): def __new__(cls, conn, tube, address, group_iface=None, mainloop=None): self = super(TubeConnection, cls).__new__(cls, address, ...
= tube self.participants = {} self.bus_name_to_handle = {} self._mapping_watches = [] if group_iface is None: method = conn.GetSelfHandle else: method = group_iface.GetSelfHandle method(reply_handler=self._on_get_self_handle_reply, ...
ClimbsRocks/scikit-learn
sklearn/model_selection/_search.py
Python
bsd-3-clause
44,853
0.000067
""" The :mod:`sklearn.model_selection._search` includes utilities to fine-tune the parameters of an estimator. """ from __future__ import print_function from __future__ import division # Author: Alexandre Gramfort <[email protected]>, # Gael Varoquaux <[email protected]> # Andreas...
s.random import sample_without_replacement from ..utils.validation import indexable, check_is_fitted from ..utils.metaestimators import if_delegate_has_method from ..metrics.scorer import check_scoring __all__ = ['GridSearchCV', 'ParameterGrid', 'fit_grid_point', 'ParameterSampler', 'RandomizedSearchCV'] ...
t-in function iter. Read more in the :ref:`User Guide <search>`. Parameters ---------- param_grid : dict of string to sequence, or sequence of such The parameter grid to explore, as a dictionary mapping estimator parameters to sequences of allowed values. An empty dict signifi...
BenDoan/code_court
code_court/courthouse/views/admin/admin.py
Python
mit
497
0
from flask import current_app, Blueprint, render_template import util from database import db_uri admin = Blueprint("admin", __name__, template_folder="templates") @admin.route("/", methods=["GET"]) @util.login_required("operator") def index(): """ The index page for the admin interface, contains a lis...
e URI"
: db_uri, "Run Mode": current_app.config["RUNMODE"]} return render_template("admin_index.html", info=info)
hetajen/vnpy161
vn.trader/dataRecorder/drEngine.py
Python
mit
11,808
0.008268
# encoding: UTF-8 ''' 本文件中实现了行情数据记录引擎,用于汇总TICK数据,并生成K线插入数据库。 使用DR_setting.json来配置需要收集的合约,以及主力合约代码。 History <id> <author> <description> 2017050300 hetajen Bat[Auto-CTP连接][Auto-Symbol订阅][Auto-DB写入][Auto-CTA加载] 2017050301 hetajen DB[CtaTemplate增加日线bar数据获取接口][Mongo不保存Tick数据][新...
close=bar.close)) bar.vtSymbol = drTick.vtSymbol bar.symbol = drTick.symbol bar.exchange = drTick.exchange bar.open = drTick.lastPrice ...
lose = drTick.lastPrice '''2017051500 Add by hetajen begin''' bar.tradingDay = drTick.tradingDay bar.actionDay = drTick.actionDay '''2017051500 Add by hetajen end''' bar.date = drTick.date bar.time = drTick.time ...
ghoshabhi/Multi-User-Blog
utility/filters.py
Python
mit
230
0.008696
from models import Likes
def filterKey(key): return key.id() def showCount(post_key): like_obj = Likes.query(Likes.post == post_key).get() if like_obj: return like_obj.like_count else:
return "0"
Yukinoshita47/Yuki-Chan-The-Auto-Pentest
Module/Spaghetti/modules/discovery/AdminInterfaces.py
Python
mit
1,102
0.040835
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Spaghetti: Web Server Security Scanner # # @url: https://github.com/m4ll0k/Spaghetti # @author: Momo Outaadi (M4ll0k
) # @license: See the file 'doc/LICENSE' from lib.net import http from lib.utils import printer from lib.net import utils class AdminInte
rfaces(): def __init__(self,url,agent,proxy,redirect): self.url = url self.printer = printer.Printer() self.http = http.Http(agent=agent,proxy=proxy,redirect=redirect) self.check = utils.Checker() def Run(self): info = { 'name':'Common administration interfaces', 'author':'Momo Outaadi (M4ll0k)', 'd...
xiligey/xiligey.github.io
code/2.py
Python
apache-2.0
1,442
0.00208
"""This example follows the simple text document Pipeline illustrated in the figures
above. """ from pyspark.ml import Pipeline from pyspark.ml.classification import LogisticRegression from pyspark.ml.feature import HashingTF, Tokenizer # Prepare training documents from a list of (id, text, label) tuples. training = spark.createDataFrame([ (0, "a b c d e spark", 1.0), (1, "b d", 0.0), (2,...
= Tokenizer(inputCol="text", outputCol="words") hashingTF = HashingTF(inputCol=tokenizer.getOutputCol(), outputCol="features") lr = LogisticRegression(maxIter=10, regParam=0.001) pipeline = Pipeline(stages=[tokenizer, hashingTF, lr]) # Fit the pipeline to training documents. model = pipeline.fit(training) # Prepare ...
NetApp/manila
manila/share/utils.py
Python
apache-2.0
3,138
0
# Copyright (c) 2012 OpenStack Foundation # Copyright (c) 2015 Rushil Chugh # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/l...
st = 'HostA@BackendB#PoolC' ret = extract_host(host, 'host') # ret is 'HostA' ret = extract_host(host, 'backend') # ret is 'HostA@BackendB' ret = extract_host(host, 'pool') # ret is 'PoolC' ret = extract_host(host, 'backend_name') # ret is 'BackendB' ...
""" if level == 'host': # Make sure pool is not included hst = host.split('#')[0] return hst.split('@')[0] if level == 'backend_name': hst = host.split('#')[0] return hst.split('@')[1] elif level == 'backend': return host.split('#')[0] elif level == 'pool...
Stvad/anki
aqt/sync.py
Python
agpl-3.0
18,494
0.00173
# Copyright: Damien Elmes <[email protected]> # License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html import socket import time import traceback import gc from aqt.qt import * import aqt from anki import Collection from anki.sync import Syncer, RemoteServer, FullSyncer, MediaSyncer, \ RemoteMe...
le['syncMedia']) t.event.connect(self.onEvent) self.label = _("Connectin
g...") self.mw.progress.start(immediate=True, label=self.label) self.sentBytes = self.recvBytes = 0 self._updateLabel() self.thread.start() while not self.thread.isFinished(): self.mw.app.processEvents() self.thread.wait(100) self.mw.progress.finis...
osantana/quickstartup
tests/base.py
Python
mit
2,174
0
from pathlib import Path from django.test import SimpleTestCase TEST_ROOT_DIR = Path(__file__).parent TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True, 'DIRS': ( str(TEST_ROOT_DIR / "templates"), ), 'OPTIONS': { ...
test_case.assertTemplateUsed(response, template_name=template_name) return True def
check_contains(response, text): test_case = SimpleTestCase() test_case.assertContains(response, text=text) return True def check_in_html(needle, haystack): test_case = SimpleTestCase() test_case.assertInHTML(needle, haystack) return True
GoogleCloudPlatform/training-data-analyst
quests/data-science-on-gcp-edition1_tf2/07_sparkml_and_bqml/experiment.py
Python
apache-2.0
5,377
0.015622
from __future__ import print_function from pyspark.mllib.classification import LogisticRegressionWithLBFGS from pyspark.mllib.regression import LabeledPoint from pyspark.sql import SparkSession from pyspark import SparkContext import numpy as np sc = SparkContext('local', 'logistic') spark = SparkSession \ .builde...
option("header", "true") \ .csv('gs://{}/flights/trainday.csv'.format(BUCKET)) traindays.createOrReplaceTempView('traindays') from pyspark.sql.types import StringType, FloatType, StructType, StructField header = 'FL_DATE,UNIQUE_CARRIER,AIRLINE_ID,CARRIER,FL_NUM,ORIGIN_AIRPORT_ID,ORIGIN_AIRPORT_SEQ_ID,ORIGIN_CITY_...
EST,CRS_DEP_TIME,DEP_TIME,DEP_DELAY,TAXI_OUT,WHEELS_OFF,WHEELS_ON,TAXI_IN,CRS_ARR_TIME,ARR_TIME,ARR_DELAY,CANCELLED,CANCELLATION_CODE,DIVERTED,DISTANCE,DEP_AIRPORT_LAT,DEP_AIRPORT_LON,DEP_AIRPORT_TZOFFSET,ARR_AIRPORT_LAT,ARR_AIRPORT_LON,ARR_AIRPORT_TZOFFSET,EVENT,NOTIFY_TIME' def get_structfield(colname): if colnam...
playpauseandstop/aiohttp
tests/test_signals.py
Python
apache-2.0
3,612
0
import asyncio from unittest import mock import pytest from multidict import CIMultiDict from aiohttp.signals import Signal from aiohttp.test_utils import make_mocked_request from aiohttp.web import Application, Response @pytest.fixture def app(): return Application() @pytest.fixture def debug_app(): retu...
(1, a=2) pre.assert_called_once_with(1, 'aiohttp.signals:Signal', 1, a=2) post.assert_called_once_with(1, 'aiohttp.signals:Signal', 1, a=2) def test_setitem(app): signal = Signal(app) m1 = mock.Mock() signal.append(m1) assert signal[0] is m1 m2 = mock.Mock() signal[0] = m2 assert s...
m1 = mock.Mock() signal.append(m1) assert len(signal) == 1 del signal[0] assert len(signal) == 0 def test_cannot_append_to_frozen_signal(app): signal = Signal(app) m1 = mock.Mock() m2 = mock.Mock() signal.append(m1) signal.freeze() with pytest.raises(RuntimeError): si...
ooici/coi-services
ion/util/stored_values.py
Python
bsd-2-clause
1,331
0.004508
#!/usr/bin/env python ''' @author Luke C @date Mon Mar 25 09:57:59 EDT 2013 @file ion/util/stored_values.py ''' from pyon.core.ex
ception
import NotFound import gevent class StoredValueManager(object): def __init__(self, container): self.store = container.object_store def stored_value_cas(self, doc_key, document_updates): ''' Performs a check and set for a lookup_table in the object store for the given key '''...
wtsi-hgi/bam2cram-check
checks/stats_checks.py
Python
gpl-3.0
11,324
0.003621
import os import subprocess import logging import re from checks import utils import sys class RunSamtoolsCommands: @classmethod def _run_subprocess(cls, args_list): proc = subprocess.run(args_list, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) utils.log_error(args_l...
tokens = version_line.split() if len(tokens) < 2: raise ValueError("samtools --version output looks different than expected. Can't parse it.") return tokens[1] @classmethod def _extract_major_version_nr(cls, version): return version.split('.', 1)[0] @classmethod ...
', version, 1) if len(vers_tokens) < 2: raise ValueError("samtools version output looks different than expected.Can't parse it.") min_vs = re.split(r'[.-]', vers_tokens[1], 1)[0] return min_vs @classmethod def _check_major_version_nr(cls, major_vs_nr): if not major_v...
datsfosure/ansible
lib/ansible/plugins/strategies/__init__.py
Python
gpl-3.0
19,457
0.003443
# (c) 2012-2014, Michael DeHaan <[email protected]> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) an...
mechanism to set all of the attributes based on # the loaders created there class SharedPluginLoaderObj: ''' A simple object to make pass the various plugin loaders to the forked processes over the queue easier ''' def __init__(self): self.basedirs = _basedirs[:] self.fil...
trategy plugins, which contains some common code useful to all strategies like running handlers, cleanup actions, etc. ''' def __init__(self, tqm): self._tqm = tqm self._inventory = tqm.get_inventory() self._workers = tqm.get_workers() self._n...
quchunguang/test
testpy3/testdoctest.py
Python
mit
305
0.003279
""" Created on 2013-1-19 @author: Administrator """ import doctest def average(values): """Computes the arithmetic mean of a list of numbers. >>> print(average
([20, 30, 70])) 40.0 """ return sum(values) / len(values) doctest.testmod() # automatically validate the embe
dded tests
oddbird/gurtel
tests/test_session.py
Python
bsd-3-clause
1,572
0
import datetime from mock import patch from pretend import stub from gurtel import session def test_annotates_request(): """Annotates request with ``session`` proper
ty.""" request = stub( cookies={}, app=stub(secret_key='secret', is_ssl=True, config={}), ) session.session_middleware(request, lambda req: None) assert request.session.secret_key == 'secret' @patch.object(session.JSONSecureCookie, 'save_cookie') def test_sets_cookie_on_response(...
={}), ) response = stub() session.session_middleware(request, lambda req: response) mock_save_cookie.assert_called_once_with( response, httponly=True, secure=True) @patch.object(session.JSONSecureCookie, 'save_cookie') @patch.object(session.timezone, 'now') def test_can_set_expiry(mock_n...
awsdocs/aws-doc-sdk-examples
python/example_code/transcribe/transcribe_basics.py
Python
apache-2.0
17,119
0.002045
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Purpose Shows how to use the AWS SDK for Python (Boto3) with the Amazon Transcribe API to transcribe an audio file to a text file. Also shows how to define a custom vocabulary to improve the accuracy of the ...
transcribe_client: The Boto3 Transcribe client. :param vocabulary_name: The name of a custom vocabulary to use when transcribing the audio file. :return: Data about the job. """ try: job_args = { 'TranscriptionJobName': job_name, 'Media': {'Med...
ge_code} if vocabulary_name is not None: job_args['Settings'] = {'VocabularyName': vocabulary_name} response = transcribe_client.start_transcription_job(**job_args) job = response['TranscriptionJob'] logger.info("Started transcription job %s.", job_name) except ClientErro...
carlosb1/examples-python
ideas/mango-example/mango.py
Python
gpl-2.0
444
0.009009
import dryscrape dryscrape.start_xvfb() sess = dryscrape.Session(ba
se_url = 'http://shop.mango.com') sess.set_attribute('auto_load_images',False) sess.visit('/ES/m/hombre/prendas/todas/?m=coleccion') print sess.at_xpath("//*").children() print "--------------------------" print sess.at_xpath("//*[contains(@class,\"searchResultPrice\")]/text()") #for price in sess.at_xpath("//*[conta...
hResultPrice\")]"): # print price
sfu-rcg/ampush
amlib/file_map.py
Python
mit
6,519
0.00046
import os import re from amlib import conf, utils, log ''' Functions for parsing AD automount maps into a common dict format. Part of ampush. https://github.com/sfu-rcg/ampush Copyright (C) 2016 Research Computing Group, Simon Fraser University. ''' # ff = flat file automount map def get_names(): ''' Return a li...
er_dir = chunks[1].split(':')[1]
d_map[am_key] = {'server_hostname': server_hostname, 'server_dir': server_dir, 'options': None} return d_map def parse(map_name=None): ''' Read flat file automount maps ${ampush.conf/flat_file_map_dir} and pass map names to parser_master_map o...
kopchik/qtile
libqtile/widget/bitcoin_ticker.py
Python
mit
2,607
0
# Copyright (c) 2013 Jendrik Poloczek # Copyright (c) 2013 Tao Sauvage # Copyright (c) 2014 Aborilov Pavel # Copyright (c) 2014 Sean Vig # Copyright (c) 2014-2015 Tycho Andersen # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "S...
A bitcoin ticker widget, data provided by the btc-e.com API. Defaults to displaying currency in whatever the current locale is.
''' QUERY_URL = "https://btc-e.com/api/2/btc_%s/ticker" orientations = base.ORIENTATION_HORIZONTAL defaults = [ ('currency', locale.localeconv()['int_curr_symbol'].strip(), 'The currency the value of bitcoin is displayed in'), ('format', 'BTC Buy: {buy}, Sell: {sell}', ...
eubr-bigsea/tahiti
tahiti/workflow_permission_api.py
Python
apache-2.0
5,484
0
# -*- coding: utf-8 -*-} import logging import os import uuid import requests from flask import request, current_app, g from flask_babel import gettext from flask_restful import Resource from sqlalchemy import or_ from sqlalchemy.orm import joinedload from sqlalchemy.sql.elements import and_ from marshmallow.exceptio...
permission=form['permission'])
db.session.add(permission) db.session.commit() result, result_code = {'message': action_performed, 'status': 'OK'}, 200 else: result, result_code = dict( ...
rohitranjan1991/home-assistant
homeassistant/components/emoncms/sensor.py
Python
mit
8,487
0.000471
"""Support for monitoring emoncms feeds.""" from __future__ import annotations from datetime import timedelta from http import HTTPStatus import logging import requests import voluptuous as vol from homeassistant.components.sensor import ( PLATFORM_SCHEMA, SensorDeviceClass, SensorEntity, SensorState...
lue"]), DECIMALS) class EmonCmsDa
ta: """The class for handling the data retrieval.""" def __init__(self, hass, url, apikey, interval): """Initialize the data object.""" self._apikey = apikey self._url = f"{url}/feed/list.json" self._interval = interval self._hass = hass self.data = None @Th...
kingvuplus/nn-gui
mytest.py
Python
gpl-2.0
17,117
0.026757
import eConsoleImpl import eBaseImpl import enigma enigma.eTimer = eBaseImpl.eTimer enigma.eSocketNotifier = eBaseImpl.eSocketNotifier enigma.eConsoleAppContainer = eConsoleImpl.eConsoleAppContainer from Tools.Profile import profile, profile_final profile("PYTHON_START") from enigma import runMainloop, eDVBDB, eTime...
setEPGCachePat
h(configElement): eEPGCache.getInstance().setCacheFile("%s/epg.dat" % configElement.value) #demo code for use of standby enter leave callbacks #def leaveStandby(): # print "!!!!!!!!!!!!!!!!!leave standby" #def standbyCountChanged(configElement): # print "!!!!!!!!!!!!!!!!!enter standby num", configElement.value # fr...
GreenLightGo/django-mailer-2
django_mailer/management/commands/retry_deferred.py
Python
mit
1,161
0.001723
from django.core.management.base import NoArgsCommand from django_mailer import models from django_mailer.management.commands import create_handler from optparse import make_option import logging class Command(NoArgsCommand): help = 'Place deferred messages back in the queue.' option_list = NoArgsCommand.opti...
= models.QueuedMessage.objects.retry_deferred( max_retries=max_retries) if count: logger = logging.getLogger('django_mailer.commands.retry_deferred') logger.warning("%s defer
red message%s placed back in the queue" % (count, count != 1 and 's' or '')) logger.removeHandler(handler)
KonradBreitsprecher/espresso
src/python/espressomd/comfixed.py
Python
gpl-3.0
699
0.001431
from __future__ import print_function, absolute_import from .script_interface import ScriptInterfaceHelper, script_interface_register @script_interface_register class ComFixed(ScriptInterfaceHelper): """Fix the center of mass of specific types. Subtracts mass-weighted fraction of the total force action on...
each force calculation. This keeps the center of mass of the type fixed iff the total momentum of the type is zero. Parameters ---------- type
s : array_like List of types of which the center of mass should be fixed. """ _so_name = "ComFixed" _so_creation_policy = "GLOBAL"
tensorflow/tensorflow
tensorflow/compiler/mlir/tensorflow/tests/tf_saved_model/multi_arguments_results_v1.py
Python
apache-2.0
3,570
0.005882
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
x3xf32> {tf_saved_model.index_path = ["
x"]} # CHECK-SAME: tensor<3x3xf32> {tf_saved_model.index_path = ["t"]} # CHECK-SAME: tensor<5x5xf32> {tf_saved_model.index_path = ["s"]} # CHECK-SAME: attributes {{.*}} tf_saved_model.exported_names = ["key"] # CHECK-DAG: %[[MUL0:.*]] = "tf.MatMul"(%[[ARG1]], %[[ARG0]]) # CHECK-DAG: %[...
openwebinars-django/newspaper
newspaper/newspaper/news/admin.py
Python
apache-2.0
353
0.002833
from django.contrib import admin from newspaper.news.models import News, Event class NewsAdmin(admin.ModelA
dmin): list_display = ('title', 'publish_date') list_filter = ('publish_date',) search_fields = ('title',) class EventAdmin(admin.ModelAdmin): pass admin.site.register(News, NewsAdmin) admin.site.register(Event, Eve
ntAdmin)
slyphon/pants
src/python/pants/engine/exp/graph.py
Python
apache-2.0
7,197
0.009032
# coding=utf-8 # Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import collections ...
ath.append(address) obj = self._address_mapper.resolve(address) def parse_addr(a): return Address.parse(a, relative_to=address.spec_path) def resolve_item(item, addr=None): if Serializable.is_serializable(item): hydrated_args = {'address': addr} if addr else {} # Recurse on t...
osure in the inline case. for key, value in item._asdict().items(): is_addressable = AddressableDescriptor.is_addressable(item, key) def maybe_addr(x): return parse_addr(x) if is_addressable and isinstance(x, six.string_types) else x if isinstance(value, collections.M...
bringsvor/sponsor
wizards/add_sponsorship.py
Python
agpl-3.0
1,922
0.011967
__author__ = 'tbri' from openerp import models, fields, api, _ class add_sponsorship_wizard(models.TransientModel): _name = 'add_sponsorship_wizard' def _get_all_children(self)
: c = [] children = self.env['res.partner'].search([('sponsored_child', '=', 'True')]) for n in children: child_ref = '%s %s' % (n.child_ident, n.name) c.append( (n.id, child_ref) ) return c #sponsor_id = fields.Many2one('sponsor') # see partner.py.........
one('res.partner', _('Sub Sponsor'), domain=[('sub_sponsor','=',True)]) start_date = fields.Date(_('Start date')) end_date = fields.Date(_('End date')) @api.one def data_save(self): print "DATA_SAVE 1", self._context """ DATA_SAVAE! {'lang': 'en_US', 'search_disable_custom_filte...
arpitprogressive/arpittest
apps/analytics/models.py
Python
bsd-3-clause
14,238
0.000702
# -*- coding: utf-8 -*- """ analytics.models Models for Demand and Supply data :copyright: (c) 2013 by Openlabs Technologies & Consulting (P) Limited :license: see LICENSE for more details. """ import operator from django.db import models import django.contrib.admin from admin.models import Occupati...
me='Percent Male in Entry Level roles' ) male_middle = models.IntegerField( verbose_name='Percent Male in Middle Level roles' ) create_date = models.DateTimeField(auto_now_add=True) write_date = models.DateTimeField(auto_now=
True) @property def female_leadership(self): "Percent Females in leadership level roles" return 100 - self.male_leadership @property def female_entry(self): "Percent Females in entry level roles" return 100 - self.male_entry @property def female_middle(self): ...
cclauss/In-Harms-Way
server/run_django.py
Python
apache-2.0
727
0.016506
#!/usr/bin/env python import os, sys, webbrowser try: from subprocess import getstatusoutp
ut # Python3 except: from commands import getstatusoutput # Python2 def shell_command(command): # do the command and print the output cmdResults = getstatusoutput(command) if True: # not cmdResults[0]: for theLine in cmdResults[1].splitlines(): print(theLine.partition('==')[0]) if __nam...
0.0.0:' + port) else: # running locally webbrowser.open('http://127.0.0.1:8000') shell_command('python3 manage.py runserver')
yosukesuzuki/url-shortner
admin.py
Python
bsd-2-clause
1,232
0
# Copyright 2016 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations u
nder the License. # [START app] from flask import Flask, request from google.appengine.api import users from models import User from tasks import create_dataset, create_click_log_data app = Flask(__name__) @app.route('/_admin/createbq', methods=['GET']) def create_bq(): result = create_dataset() return resu...
pioneers/topgear
ipython-in-depth/examples/Embedding/internal_ipkernel.py
Python
apache-2.0
2,018
0.004955
#---------------------------------------
-------------------------------------- # Imports #----------------------------------------------------------------------------- import sys from IPython.lib.kernel import connect_qtconsole from IPython.kernel.zmq.kernelapp import IPKernelApp #---------------------------------------------------------------------------...
rnel(gui): """Launch and return an IPython kernel with matplotlib support for the desired gui """ kernel = IPKernelApp.instance() kernel.initialize(['python', '--matplotlib=%s' % gui, #'--log-level=10' ]) return kernel class InternalIPKernel(object): ...
wright-group/WrightTools
WrightTools/artists/_interact.py
Python
mit
20,114
0.00179
"""Interactive (widget based) artists.""" import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt from matplotlib.widgets import Slider, RadioButtons from types import SimpleNamespace from ._helpers import create_figure, plot_colorbar, add_sideplot from ._base import _order_for_imshow from ._color...
ex(self.focus_axis) if ax == "next": ind -= 1 elif ax == "previous": ind += 1 ax = self.axes[ind % len(self.axes)] if self.focus_axis == ax or ax not in self.axes: return else: # set new focus for spine i
n ["top", "bottom", "left", "right"]: self.focus_axis.spines[spine].set_linewidth(1) ax.spines[spine].set_linewidth(self.linewidth) self.focus_axis = ax def _at_dict(data, sliders, xaxis, yaxis): return { a.natural_name: (a[:].flat[int(sliders[a.natural_name].va...
pythonchelle/opencomparison
apps/core/tests/test_ga.py
Python
mit
1,060
0.00566
# -*- coding: utf-8 -*- from core.test_utils.context_managers import SettingsOverride from django import template from django.test.testcase
s import TestCase class PackaginatorTagsTests(TestCase): def test_fixed_ga(self): tpl = template.Template(""" {% load packaginator_tags %} {% fixed_ga %} """) context = template.Context() with SettingsOverride(URCHIN_ID='testid', DEBUG=False): ...
acker = _gat._getTracker("testid");' in output) with SettingsOverride(URCHIN_ID='testid', DEBUG=True): output = tpl.render(context) self.assertEqual(output.strip(), "") with SettingsOverride(URCHIN_ID=None, DEBUG=True): output = tpl.render(context) ...
libracore/erpnext
erpnext/stock/doctype/delivery_note/delivery_note.py
Python
gpl-3.0
23,654
0.003551
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe import frappe.defaults from erpnext.controllers.selling_controller import SellingController from erpnext.stock.doctype.batch.batch import...
ct", "="], ["currency", "="]] }, "Sales Invoice Item
": { "ref_dn_field": "si_detail", "compare_fields": [["item_code", "="], ["uom", "="], ["conversion_factor", "="]], "is_child_table": True, "allow_duplicate_prev_row_id": True }, }) if cint(frappe.db.get_single_value('Selling S...
jeremiahyan/odoo
addons/mass_mailing_crm/models/utm.py
Python
gpl-3.0
294
0.003401
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full co
pyright and licensing details. from o
doo import fields, models class UtmCampaign(models.Model): _inherit = 'utm.campaign' ab_testing_winner_selection = fields.Selection(selection_add=[('crm_lead_count', 'Leads')])
katakumpo/nicepy
nicepy/assertions/helpers.py
Python
mit
1,696
0.004717
# -*- coding: utf-8 *-* from collections import OrderedDict from nicepy.utils import ljust_all, pretty_rep
r def get_failed_msg(compare_method, values, expected_values, names=None, expected_names=None): failed_list = [] names = names or map(str,
range(len(values))) expected_names = expected_names or [''] * len(names) for value, expected_value, name, expected_name in zip(values, expected_values, names, expected_names): #print value, expected_value, name, expected_name if not comp...
isstiaung/Adimal
adimal/twitter_feed/migrations/0002_tweet_links.py
Python
mit
490
0
# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-06-12 23:00 from __future__ import unicode_literals from django.db import migrations, mode
ls class Migration(migrations.Migration): dependencies = [ ('twitter_feed', '0001_initial'), ]
operations = [ migrations.AddField( model_name='tweet', name='links', field=models.CharField(default=' ', max_length=200), preserve_default=False, ), ]
chemelnucfin/tensorflow
tensorflow/python/keras/metrics_confusion_matrix_test.py
Python
apache-2.0
51,243
0.002381
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
_op.constant(((0, 0,
1, 1, 0), (1, 1, 1, 1, 1), (0, 1, 0, 1, 0), (1, 1, 1, 1, 1))) sample_weight = constant_op.constant((1., 1.5, 2., 2.5)) result = fp_obj(y_true, y_pred, sample_weight=sample_weight) self.assertAllClose(14., self.evaluate(result)) def test_unweighted_with_thresholds(self)...
JianfengYao/thefuck
thefuck/logs.py
Python
mit
1,661
0.000602
import sys from traceback import format_exception import colorama def color(color_, settings): """Utility for ability to disabling colored output.""" if settings.no_colors: return '' else: return color_ def exception(title, exc_info, settings): sys.stderr.write( u'{warn}[WARN...
colorama.Back.RED + colorama.Fo
re.WHITE + colorama.Style.BRIGHT, settings), reset=color(colorama.Style.RESET_ALL, settings), title=title, trace=''.join(format_exception(*exc_info)))) def rule_failed(rule, exc_info, settings): exception('Rule {}'.format(rule.name), exc_info, settings) ...
sio2project/filetracker
filetracker/servers/storage.py
Python
gpl-3.0
17,784
0.00045
"""This module is responsible for storing files on disk. The storage strategy is as follows: - Files themselves are stored in a separate directory called 'blobs'. - Stored files are named by their SHA256 hashes (in hex). - Stored files are grouped into directories by their first byte (two hex characters), referred t...
_LOCK_RETRIES = 20 _LOCK_SLEEP_TIME_S = 1 logger = logging.getLogger(__name__) class FiletrackerFileNotFoundError(Exception): pass class ConcurrentModificationError(Exception): """Raised after acquiring lock failed multiple times.""" def __init__(self, lock_name): message = 'Failed to acquire...
storage.""" def __init__(self, base_dir): self.base_dir = base_dir self.blobs_dir = os.path.join(base_dir, 'blobs') self.links_dir = os.path.join(base_dir, 'links') self.locks_dir = os.path.join(base_dir, 'locks') self.db_dir = os.path.join(base_dir, 'db') _makedir...
srottem/indy-sdk
wrappers/python/tests/wallet/test_import_wallet.py
Python
apache-2.0
1,307
0.00153
import pytest from indy import IndyError from indy import did from indy import wallet from indy.error import ErrorCode @pytest.mark.asyncio @pytest.mark.parametrize("wallet_handle_cleanup", [
False]) async def test_import_wallet_works(wallet_handle, wallet_config, credentials, export_config): (_did, _verkey) = await did.create_and_store_my_did(wallet_handle, "{}") await did.set_did_metadata(wallet_handle, _did, "metadata") did_with_meta_before = await did.get_my_did_with_meta(wallet_handle, _di...
) await wallet.export_wallet(wallet_handle, export_config) await wallet.close_wallet(wallet_handle) await wallet.delete_wallet(wallet_config, credentials) await wallet.import_wallet(wallet_config, credentials, export_config) wallet_handle = await wallet.open_wallet(wallet_config, credentials) ...
kbase/narrative
src/biokbase/service/Client.py
Python
mit
7,649
0.000392
try: import json as _json except ImportError: import sys sys.path.append("simplejson-2.3.3") import simplejson as _json import requests as _requests import urllib.parse as _urlparse import random as _random import base64 as _base64 from configparser import ConfigParser as _ConfigParser import os as _o...
d to read in the
~/.kbase_config file if one is present authdata = None if _os.path.exists(file): try: config = _ConfigParser() config.read(file) # strip down whatever we read to only what is legit authdata = { x: config.get("authentication", x) ...
vlegoff/tsunami
src/secondaires/navigation/commandes/matelot/__init__.py
Python
bsd-3-clause
3,210
0.000312
# -*-coding:Utf-8 -* # Copyright (c) 2010-2017 LE GOFF Vincent # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # ...
the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # * Neither the name of the copyright holder nor the names of it
s contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERC...
wolfram74/numerical_methods_iserles_notes
venv/lib/python2.7/site-packages/sympy/integrals/tests/test_transforms.py
Python
mit
31,213
0.002531
from sympy.integrals.transforms import (mellin_transform, inverse_mellin_transform, laplace_transform, inverse_laplace_transform, fourier_transform, inverse_fourier_transform, sine_transform, inverse_sine_transform, cosine_transform, inverse_cosine_transform, hankel_transform, inverse_hankel_transfo...
a, sqrt(x)), x, s) == \ (2**a
*gamma(a/2 + s)*gamma(-2*s + S(1)/2)/( gamma(-a/2 - s + S(1)/2)*gamma(a - 2*s + 1)), ( -re(a)/2, S(1)/4), True) assert MT(besselj(a, sqrt(x))**2, x, s) == \ (gamma(a + s)*gamma(S(1)/2 - s) / (sqrt(pi)*gamma(1 - s)*gamma(1 + a - s)), (-re(a), S(1)/2), True) assert MT(...
e-koch/VLA_Lband
16B/pipeline4.7.1_custom/EVLA_pipe_fluxgains.py
Python
mit
6,065
0.019621
###################################################################### # # Copyright (C) 2013 # Associated Universities, Inc. Washington DC, USA, # # This library is free software; you can redistribute it and/or modify it # under the terms of the GNU Library General Public License as published by # the Free Software Fo...
librators.ms') positions = [] for ii in range(0,len(field_positions[0][0])): positions.append([field_positions[0][0][ii], field_position
s[1][0][ii]]) standard_source_names = [ '3C48', '3C138', '3C147', '3C286' ] standard_source_fields = find_standards(positions) ii=0 for fields in standard_source_fields: for myfield in fields: spws = field_spws[myfield] for myspw in spws: reference_frequency = center_frequencies[myspw]...
hardworkingcoder/dw_experiments
migrations/versions/059e2a9bfb4c_.py
Python
mit
1,851
0.010805
"""empty message Revision ID: 059e2a9bfb4c Revises: Create Date: 2017-07-10 21:50:44.380938 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql # revision identifiers, used by Alembic. revision = '059e2a9bfb4c' down_revision = None branch_labels = None depends_on = None d...
alse), sa.Column('user_uuid', postgresql.UUID(as_uuid=True), nullable=True), sa.Column('is_active', sa
.Boolean(), nullable=False), sa.ForeignKeyConstraint(['user_uuid'], ['users.user_uuid'], ), sa.PrimaryKeyConstraint('session_uuid') ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_table('sessions') op.drop_table('users...
fhfuih/MCEdit-Unified
pymclevel/setup_leveldb.py
Python
isc
11,800
0.003136
#!/usr/bin/python2.7 # # setup_leveldb.py # # Compiles and install Minecraft Pocket Edtition binary support. # __author__ = "D.C.-G. 2017" __version__ = "0.3.0" import sys import os import platform import fnmatch if sys.platform != "linux2": print "This script can't run on other platforms than Linux ones..." ...
e architecture could not be check with library internal data, rely on the folder name. if os.path.split(found)[0] in arch_paths: r = True v = found.rsplit('.so.', 1) if len(v) == 2: ver = v[1] os.chdir(cur_dir) return found, r
, ver def get_sources(name, url): print "Downloading sources for %s" % name print "URL: %s" % url os.system("%s %s.zip %s" % (wget_curl, name, url)) print "Unpacking %s" % name os.system("unzip -q %s.zip" % name) os.system("mv $(ls -d1 */ | egrep '{n}-') {n}".format(n=name)) print "Cleanin...
googleapis/python-grafeas
grafeas/grafeas_v1/services/grafeas/transports/__init__.py
Python
apache-2.0
1,131
0
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.
org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitati...
port GrafeasGrpcTransport from .grpc_asyncio import GrafeasGrpcAsyncIOTransport # Compile a registry of transports. _transport_registry = OrderedDict() # type: Dict[str, Type[GrafeasTransport]] _transport_registry["grpc"] = GrafeasGrpcTransport _transport_registry["grpc_asyncio"] = GrafeasGrpcAsyncIOTransport __all...
django-bmf/django-bmf
djangobmf/contrib/task/permissions.py
Python
bsd-3-clause
2,444
0.003682
#!/usr/bin/python # ex:set fileencoding=utf-8: from __future__ import unicode_literals from django.db.models import Q # from djangobmf.permissions import ModulePermission from djangobmf.utils import FilterQueryset class GoalFilter(FilterQueryset): def filter_queryset(self, qs, user): if user.has_perm(...
angobmf.team) return qs.filter(qs_filter) class TaskFilter(FilterQueryset):
def filter_queryset(self, qs, user): qs_filter = Q(project__isnull=True, goal__isnull=True) qs_filter |= Q(employee=user.djangobmf.employee or -1) qs_filter |= Q(in_charge=user.djangobmf.employee) if hasattr(qs.model, "goal"): # pragma: no branch goal = qs.model._meta.get_f...
chrys87/orca-beep
src/orca/scripts/apps/soffice/script_utilities.py
Python
lgpl-2.1
22,259
0.001483
# Orca # # Copyright 2010 Joanmarie Diggs. # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library i...
showing = cell.getState().contains(pya
tspi.STATE_SHOWING) except: continue if showing: cells.append(cell) return cells def getTableRowRange(self, obj): """If this is spread sheet cell, return the start and end indices of the spread sheet cells for the table that obj is in...
geosoco/reddit_coding
api/urls.py
Python
bsd-3-clause
1,309
0
from django.conf.urls import url, include from rest_framework import routers from api import views router = routers.DefaultRouter(trailing_slash=True) router.register( r'sysusers', views.DjangoUserViewSet, base_name="sysusers") router.register( r'sysgroups', views.DjangoGroupView
Set, base_name="sysgroups") router.register( r'comment', views.CommentViewSet, base_name="comment") router.register( r'submission', views.SubmissionViewSet, base_name="submission") router.r
egister( r'codescheme', views.CodeSchemeViewSet, base_name="codescheme") router.register( r'code', views.CodeViewSet, base_name="code") router.register( r'commentcodeinstance', views.CommentCodeInstanceViewSet, base_name="commentcodeinstance") router.register( r'assignment', views.AssignmentView...
bricaud/OCR-classif
pdf2txt.py
Python
apache-2.0
3,948
0.029889
#!/usr/bin/env python3 """ Program that convert a pdf to a text file using Tesseract OCR. The pdf file is first converted to a png file using ghostscript, then the png file if processed by Tesseract. """ import os import subprocess import glob import platform import argparse parser = argparse.ArgumentParser(descri...
dSAFER -dNOPAUSE -q -r300x300 -sDEVICE=pnggray -dBATCH -dLastPage=' + str(page_limit) + ' -sOutputFile=' + out_file + ' ' + pdf_file) else: cmd_pdf2png = ('gs -dSAFER -dNOPAUSE -q -r300x300 -sDEVICE=pnggray -dBATCH -dLastPage=' + str(page_limit) + ' -sOutputFile=' + out_file + ' ' + pdf_file) proc_results = s...
= 'logfile_png2txt.txt' # initiate log file to report errors with open(LOG_FILE1, 'a') as logfile: logfile.write('Logfile produced by pdf2txt.py\n') with open(LOG_FILE2, 'a') as logfile: logfile.write('Logfile produced by pdf2txt.py\n') # init paths png_path = os.path.join(PDF_PATH,'png') txt_path = os.pat...
sundream/shell
backup_db.py
Python
gpl-2.0
896
0.014509
#coding=utf-8 import sys import os import time from shutil import * def backup_db(dirname): assert os.path.isdir(dirname),"not dirname" for root,dirs,filenames in os.walk(dirname): #print root,dirs,filenames for filename in filenames: filename = os.path.join(root,filename) ...
backup_filename = "%s_%s.bak" % (filename,now) tmp_filename = backup_filename + ".tmp" copy2(filename,tmp_filename) # preserve attr copy2(tmp_filename,backup_filename) os.remove(tmp_filename) break if __name__ == "__main__": if...
exit(0) dirname = sys.argv[1] backup_db(dirname)
pymedusa/Medusa
ext/deluge_client/client.py
Python
gpl-3.0
12,558
0.00223
import logging import socket import ssl import struct import warnings import zlib import io import os import platform from functools import wraps from threading import local as thread_local from .rencode import dumps, loads DEFAULT_LINUX_CONFIG_DIR_PATH = '~/.config/deluge' RPC_RESPONSE = 1 RPC_ERROR = 2 RPC_EVENT = ...
data) except zlib.error: if not d: raise ConnectionLostException() continue break data = list(loads(data, decode_utf8=self.decode_utf8)) msg_type = data.pop(0) req
uest_id = data.pop(0) if msg_type == RPC_ERROR: if self.deluge_version == 2: exception_type, exception_msg, _, traceback = data # On deluge 2, exception arguments are sent as tuple if self.decode_utf8: exception_msg = ', '.join(exc...
flavoi/diventi
diventi/core/migrations/0002_auto_20190430_1520.py
Python
apache-2.0
446
0.002242
# Generated by Django 2.1.7 on 2019-04-30 13:20 from django.db import migrations, models import uuid class Migration(migrations.Migration): dependencies = [ ('core', '0001_initial'), ] operations = [ migrations.AlterField( model_name='publishablemodel', name='id'...
]
arunkgupta/gramps
gramps/gen/utils/alive.py
Python
gpl-2.0
26,674
0.005436
# # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2000-2007 Donald N. Allingham # Copyright (C) 2009 Gary Burton # Copyright (C) 2011 Tim G L Lyons # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published ...
if year != 0: # sibling birth date return (Date().copy_ymd(year - self.MAX_SIB_AGE_DIFF), Date().copy_ymd(year - self.MAX_SIB_AGE_DIFF + self.MAX_AGE_PROB_ALIVE), ...
dobj = ev.get_date_object() if dobj.get_start_date() != Date.EMPTY: # if sibling death date too far away, then not alive: year = dobj.get_year() if year != 0: # sibl
ljx0305/ice
python/test/Ice/adapterDeactivation/AllTests.py
Python
gpl-2.0
2,229
0.007627
# ********************************************************************** # # Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. # # This copy of Ice is licensed to you under
the terms described in the # ICE_LICENSE file included in this distribution. # # ********************************************************************** import sys, Ice, Test def test(b): if not b: raise RuntimeError('test assertion failed') def allTests(communicator): sys.stdout.write("testing string...
Proxy("test:default -p 12010") test(base) print("ok") sys.stdout.write("testing checked cast... ") sys.stdout.flush() obj = Test.TestIntfPrx.checkedCast(base) test(obj) test(obj == base) print("ok") sys.stdout.write("creating/destroying/recreating object adapter... ") sys.stdou...
PMR2/pmr2.oauth
pmr2/oauth/tests/test_form.py
Python
gpl-2.0
4,711
0
import unittest import zope.component from zExceptions import Unauthorized from Products.PloneTestCase import ptc from Products.PloneTestCase.ptc import default_user from pmr2.oauth.interfaces import ITokenManager, IConsumerManager from pmr2.oauth.interfaces import IScopeManager from pmr2.oauth.token import Token fr...
}) form = token.AuthorizeTokenForm(self.portal, request) form.update() result = form.render() self.assertTrue('_authenticator' in result) def test_0001_authform_post_authfail(self): request = TestRequest(form={ 'oauth_token': self.reqtoken.key, ...
token.AuthorizeTokenForm(self.portal, request) self.assertRaises(Unauthorized, form.update) def test_0002_authform_post_authgood(self): request = TestRequest(form={ 'oauth_token': self.reqtoken.key, 'form.buttons.approve': 1, }) form = token.AuthorizeTokenFor...
devolio/devolio
users/migrations/0002_auto_20170321_2209.py
Python
gpl-3.0
589
0.001698
# -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-03-21 22:09 from __fu
ture__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('users', '0001_initial'), ] operations = [ migrations.AlterField( model_name='skill', name='level', field=models.CharField...
, max_length=50, verbose_name="What's your level?"), ), ]
kalrey/swift
swift/common/constraints.py
Python
apache-2.0
10,266
0
# Copyright (c) 2010-2012 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agree...
CONSTRAINTS.items(): value = OVERRIDE_CONSTRAINTS.get(name, default) EFFECTIVE_CONSTRAINTS[name] = value # "globals"
in this context is module level globals, always. globals()[name.upper()] = value reload_constraints() # Maximum slo segments in buffer MAX_BUFFERED_SLO_SEGMENTS = 10000 #: Query string format= values to their corresponding content-type values FORMAT2CONTENT_TYPE = {'plain': 'text/plain', 'json': 'applica...
cts2/pyjxslt
pyjxslt-python/tests/testXMLtoJSON.py
Python
apache-2.0
3,904
0.003842
# -*- coding: utf-8 -*- # Copyright (c) 2015, Mayo Clinic # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # Redistributions of source code must retain the above copyright notice, this # list...
-8"?> <?xml-stylesheet type="text/xsl" href="./datadict_v2.xsl"?> <data_table id="pht003897.v1" study_id="phs000722.v1" participant_set="1"> </data_table>""" expected_pi = '{ "data_table": { "id": "pht003897.v1", "study_id": "phs000722.v1", "participant_set": "1" } }' expected_bad = 'ERROR: Transformer exception: or...
"</doc>".' class XMLToJsonTestCase(unittest.TestCase): # Just a quick test as the actual transform is tested elsewhere. Our job is just to make sure # that we get what we expect through the gateway gw = pyjxslt.Gateway() if not gw.gateway_connected(reconnect=False): print("Gateway must be ru...
FederatedAI/FATE
python/fate_arch/metastore/db_models.py
Python
apache-2.0
4,898
0.001429
# # Copyright 2019 The FATE Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
ense is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import inspect import os import sys from peewee import CharField, IntegerField, BigIntegerField...
del import DateTimeField from fate_arch.common import file_utils, log, EngineType, conf_utils from fate_arch.common.conf_utils import decrypt_database_config from fate_arch.metastore.base_model import JSONField, SerializedField, BaseModel LOGGER = log.getLogger() DATABASE = decrypt_database_config() is_standalone = ...
agile-geoscience/agilegeo
bruges/rockphysics/test/fluidsub_test.py
Python
apache-2.0
2,698
0
# -*- coding: utf-8 -*- """ Tests. """ import unittest from bruges.rockphysics import fluidsub # Inputs... GAS case vp_gas = 2429.0 vs_gas = 1462.4 rho_gas = 2080. # Expected outputs... BRINE case vp_brine = 2850.5 vs_brine = 1416.1 rho_brine = 2210.0 phi = 0.275 # Don't know this... reading from fig rhoh...
(unittest.TestCase): """ Tests fluid sub calculations against Smith et al 2003. htt
ps://dl.dropboxusercontent.com/u/14965965/Smith_etal_2003.pdf """ def test_avseth(self): # Base case: gas # Subbing with: brine sub = fluidsub.avseth_fluidsub(vp=vp_gas, vs=vs_gas, rho=rho_gas, ...
saullocastro/compmech
compmech/conecyl/modelDB.py
Python
bsd-3-clause
17,932
0.001617
r""" Used to configure the main parameters for each implemented model. .. currentmodule:: compmech.conecyl.modelDB """ import numpy as np from scipy.sparse import coo_matrix from clpt import * from fsdt import * db = { 'clpt_donnell_bc1': { 'linear static': True, 'linear...
': 3, 'num2': 8, }, 'clpt_sanders_bc1': { 'linear static': True, 'linear bucklin
g': True, 'non-linear static': True, 'commons': clpt_commons_bc1, 'linear': clpt_sanders_bc1_linear, 'non-linear': clpt_sanders_bc1_nonlinear, 'dofs': 3, 'e_num': 6, 'i0': 0, ...
vtbassmatt/django-expression-fields
src/expression_fields/expr.py
Python
mit
668
0.01497
from __future__ import division from math import * def calculate(expr_string): math_list = ['math', 'acos',
'asin', 'atan', 'atan2', 'ceil', 'cos', 'cosh', 'degrees', 'e', 'exp', 'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log', 'log10', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh'] builtins_list = [abs] local_ctx = dict([ (k, globals().get(k, None)) for k i...
_list ]) local_ctx.update(dict([ (b.__name__, b) for b in builtins_list ])) try: return eval(expr_string, { "__builtins__": None }, local_ctx) except (SyntaxError, TypeError, NameError): return None
StanfordBioinformatics/loom
server/loomengine_server/api/test/models/test_data_nodes.py
Python
agpl-3.0
10,494
0.019726
from django.core.exceptions import ValidationError from django.test import TestCase from api.test.models import _get_string_data_object from api.models.data_nodes import * class TestDataNode(TestCase): INPUT_DATA=( ([(0,3),(0,1)], 'i'), ([(1,3),(0,2)], 'a'), ([(1,3),(1,2)], 'm'), ...
rror): root.add_leaf(degree, data_object) with self.assertRaises(IndexOutOfRangeError): root.add_leaf(-1, data_object) def testDegreeMismatchError(self): data_object = _get_string_data_object('text') root = DataNode.objects.create(degree=2, type='string') roo...
) def testUnknownDegreeError(self): data_object = _get_string_data_object('text') root = DataNode.objects.create(type='string') with self.assertRaises(UnknownDegreeError): root.add_leaf(0, data_object) def testIsReady(self): some_of_the_data=( ([...
stlim0730/glide
api/views.py
Python
mit
35,037
0.013643
from rest_framework.decorators import api_view, parser_classes from rest_framework.parsers import JSONParser, FormParser, MultiPartParser from rest_framework.response import Response from .serializers import * import json from urllib.parse import urlencode from urllib.request import urlopen, Request from urllib.error i...
rror' }) @api_view(['POST']) def cdn(request, owner, repo): """ Responds with RawGit url for the specified file """ res = {} accessToken = request.session['accessToken'] file = request.dat
a['file'] # branch = request.data['branch'] commit = _getLatestCommit(accessToken, owner, repo) cdnUrl = 'https://cdn.rawgit.com/{}/{}/{}/{}' cdnUrl = cdnUrl.format(owner, repo, commit['sha'], file['path']) return Response({ 'cdnUrl': cdnUrl }) @api_view(['POST']) def parse(request): template = requ...
kernevil/samba
python/samba/netcmd/drs.py
Python
gpl-3.0
36,173
0.001603
# implement samba_tool drs commands # # Copyright Andrew Tridgell 2010 # Copyright Andrew Bartlett 2017 # # based on C implementation by Kamen Mazdrashki <[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 pub...
creds = credopts.get_
credentials(self.lp, fallback_machine=True) self.verbose = verbose output_function = { 'summary': self.summary_output, 'notify_summary': self.notify_summary_output, 'pull_summary': self.pull_summary_output, 'json': self.json_output, 'classic':...
michaelbratsch/bwb
populate.py
Python
gpl-3.0
1,775
0
#!/usr/bin/env python from datetime import timedelta import os import random from django.utils.dateparse import parse_date from faker import Faker test_email = '[email protected]' fake = Faker('de') fake.seed(1) random.seed(1) def get_random_date(): return parse_date('1983-03-31') + timedelta(days=random.r...
date_of_birth=get_random_date()) add_registration(candidate=candidate, bicycle_kind=random.randint(1, 4), email=fake.email()) def add_candidate(first_name, last_name, date_of_birth): return Ca
ndidate.objects.create(first_name=first_name, last_name=last_name, date_of_birth=date_of_birth) def add_registration(candidate, bicycle_kind, email): return UserRegistration.objects.create(candidate=candidate, ...
allenlavoie/tensorflow
tensorflow/contrib/distributions/python/ops/estimator.py
Python
apache-2.0
7,908
0.004299
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
enable_centered_bias=enable_centered_bias, head_name=head_name) class _DistributionRegressionHead(_RegressionHead): """Creates a _RegressionHead instance from an arbitrary `Distribution`.""" def __init__(self, make_distribution_fn, label_dimension, logits_dimen...
le_centered_bias=False, head_name=None): """`Head` for regression. Args: make_distribution_fn: Python `callable` which returns a `tf.Distribution` instance created using only logits. label_dimension: Number of regression labels per example. This is the size of the las...
unho/pootle
pootle/apps/pootle_app/management/commands/update_tmserver.py
Python
gpl-3.0
13,500
0.000963
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. import os from hashlib import md5 # This mu...
options.
external = parser.add_argument_group('External TM', 'Pootle External ' 'Translation Memory') external.add_argument( nargs='*', dest='files', help='Translation memory files', ) e
andreaso/ansible
lib/ansible/modules/packaging/os/homebrew_tap.py
Python
gpl-3.0
7,344
0.000681
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2013, Daniel Jaouen <[email protected]> # (c) 2016, Indrajit Raychaudhuri <[email protected]> # # Based on homebrew (Andrew Dunham <[email protected]>) # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the...
s/>. ANSIBLE_METADATA = {'metadata_version': '1.0', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: homebrew_tap author: - "Indrajit Raych
audhuri (@indrajitr)" - "Daniel Jaouen (@danieljaouen)" short_description: Tap a Homebrew repository. description: - Tap external Homebrew repositories. version_added: "1.6" options: name: description: - The GitHub user/organization repository to tap. required: true alias...
jackrzhang/zulip
zerver/data_import/import_util.py
Python
apache-2.0
21,272
0.003197
import random import requests import shutil import logging import os import traceback import ujson from typing import List, Dict, Any, Optional, Set, Callable, Iterable, Tuple, TypeVar from django.forms.models import model_to_dict from zerver.models import Realm, RealmEmoji, Subscription, Recipient, \ Attachment,...
full_name: str, id: int, is_active: bool, is_realm_admin: bool, is_guest: bool, is_mirror_dummy: bool, realm_id: int, short_name: str, ...
date_joined=date_joined, delivery_email=delivery_email, email=email, full_name=full_name, id=id, is_active=is_active, is_realm_admin=is_realm_admin, is_guest=is_guest, pointer=pointer, realm_id=realm_id, short_name=short_name, timez...
vedujoshi/tempest
tempest/api/network/test_floating_ips.py
Python
apache-2.0
10,882
0
# Copyright 2013 OpenStack Foundation # 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 requ...
ngip( floating_network_id=self.ext_net_id) created_floating_ip = body['floatingip'] self.addCleanup(self.floating_ips_client.delete_floatingip, created_floating_ip['id']) # Create a port port = self.ports_client.create_port(network_id=self.network['id'...
port_id=created_port['id']) # Delete port self.ports_client.delete_port(created_port['id']) # Verifies the details of the floating_ip floating_ip = self.floating_ips_client.show_floatingip( created_floating_ip['id']) shown_floating_ip = floating_ip['float...
missulmer/Pythonstudy
coursera_python_specialization/9_4.py
Python
cc0-1.0
1,246
0.005618
""" 9.4
Write a program to read through the mbox-short.txt and figure out who has the sent the greatest number of mail messages. The program
looks for 'From ' lines and takes the second word of those lines as the person who sent the mail. The program creates a Python dictionary that maps the sender's mail address to a count of the number of times they appear in the file. After the dictionary is produced, the program reads through the dictionary using a maxi...
yubinbai/python_practice
priorityqueue.py
Python
apache-2.0
1,718
0.005239
# use priority queue to implement stack and queue import heapq class stack: data = [] highestPriority = 0 lowestPriority = 0 def push(self, e): self.highestPriority -= 1 # smaller value means priority is higher heapq.heappush(self.data, (self.highestPriority, e)) def pop(self):...
self.isEmpty(): return None else: # increaste the highest priority (lowering it ) self.highestPriority += 1 return heapq.heappop(self.data)[1] def isEmpty(self): if self.highestPriority >= self.lowestPriority: self.highestPriority = 0 ...
sh(h, i) return [heapq.heappop(h) for x in range(len(iterable))] if __name__ == '__main__': import random data = [random.randint(1, 100) for x in range(15)] data.sort() ''' s = stack() for i in data: s.push(i) while not s.isEmpty(): print(s.pop()) ''' q = queue() for i in data: ...
eduNEXT/edunext-ecommerce
ecommerce/extensions/partner/migrations/0017_auto_20200305_1448.py
Python
agpl-3.0
887
0.003382
# -*- coding: utf-8 -*- # Generated by Django 1.11.29 on 2020-03-05
14:48 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('partner', '0016_auto_20191115_2151'), ] operations = [ migrations.AlterField(
model_name='historicalpartner', name='name', field=models.CharField(blank=True, db_index=True, max_length=128, verbose_name='Name'), ), migrations.AlterField( model_name='partner', name='name', field=models.CharField(blank=True, db_index=T...
willycs40/zoopla_pull
db.py
Python
bsd-2-clause
795
0.015094
import MySQLdb from parameters import Parameters import logging def run_sql(sql, db=None): db = MySQLdb.connect(host=Parameters.DB_HOST, user=Parameters.DB_USER, passwd=Parameters.DB_PASSWORD, db=Parameters.DB_SCH
EMA) cursor = db.cursor() logging.debug(sql) try: cursor.execute(sql) db.commit() data = cursor.fetchall() db.close() except Exception as e: logging.error(e) db.rollback() try: return data[0][0] except: return True ...
t: run_sql(sql) def initialise_db(): run_sql_multi(Parameters.SQL_INITIALISE) if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG) initialise_db()
atagar/ReviewBoard
reviewboard/notifications/email.py
Python
mit
13,727
0.000437
import logging from django.conf import settings from django.contrib.sites.models import Site from django.core.mail import EmailMultiAlternatives from django.core.urlresolvers import reverse from django.template.loader import render_to_string from django.utils import timezone from djblets.siteconfig.models import SiteC...
om list as-is. return g.mailing_list.split(',') else: return [get_email_address_for_user(u) for u in g.users.filter(is_active=True)] class SpiffyEmailMessage(EmailMultiAlternatives): """An EmailMessage subclass with improved header and message ID support. This also kno...
ed Message-ID header from the e-mail can be accessed through the :py:attr:`message_id` attribute after the e-mail is sent. """ def __init__(self, subject, text_body, html_body, from_email, sender, to, cc, in_reply_to, headers={}): headers = headers.copy() if sender: ...
pacoqueen/bbinn
informes/albaran_multipag.py
Python
gpl-2.0
26,260
0.01394
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### # Copyright (C) 2005-2008 Francisco José Rodríguez Bogado # # ([email protected]) # # ...
canvas, datos_de_la_empresa) # Cabecera de factura build_tabla_cabecera(canvas, datos_albaran, 22.5*cm) def dibujar_datos_empresa(canvas, datos_de_la_empresa): """ Dibuja los datos de la empresa en la parte superior. """ logo, empresa = build_logo_y_
empresa_por_separado(datos_de_la_empresa) logo.drawOn(canvas, 1*cm, PAGE_HEIGHT - 2.8 * cm) fuente = "Helvetica" tamanno = 16 for i in range(len(empresa)): if i == 1: tamanno -= 4 # Primera línea (nombre empresa) un poco más grande. linea = PAGE_HEIGHT - 1.5 * cm el_...
FredrikAugust/server-status
statuspagescript.py
Python
mit
2,247
0.015576
#!/usr/bin/python """A script to get inform
ation from MrTijn's new server so I (MrMadsenMalmo) can display it on a website """ __author__ = "MrMadsenMalmo - Fredrik A. Madsen-Malmo & Tijndagamer" import os import time import re import datetime def main(): dataList = [] dataList.append(os.popen("uptime").read() + "\n") dataList.append(os.popen("c...
d(os.popen("getup").read() + "\n") dataList.append("Memory stats:\n" + os.popen("free -h").read() + "\n") dataList.append("Drive stats: TOTAL | USED | FREE\n" + os.popen("df -h | grep '/dev/' && df -h --total | grep 'total'").read()) data = str(dataList) data = data.replace('[', '') data = data.re...
osasto-kuikka/KGE
tools/sqf_validator.py
Python
gpl-2.0
8,231
0.008018
#!/usr/bin/env python3 import fnmatch import os import re import ntpath import sys import argparse def validKeyWordAfterCode(content, index): keyWords = ["for", "do", "count", "each", "forEach", "else", "and", "not", "isEqualTo", "in", "call", "spawn", "execVM", "catch"]; for word in keyWords: try: ...
False): # This means we have encountered a /, so we are now checking if this is an inline comment or a comment block if (checkIfInComment): checkIfInComment = False if c == '*': # if the next character after / is a *, we are at the start of a com...
isInCommentBlock = True elif (c == '/'): # Otherwise, will check if we are in an line comment ignoreTillEndOfLine = True # and an line comment is a / followed by another / (//) We won't care about anything that comes after it if (isInComm...
QISKit/qiskit-sdk-py
qiskit/result/exceptions.py
Python
apache-2.0
1,290
0
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modif...
rd as it comes back from the API. The format is like:: error = {'status': 403, 'message': 'Your credits are not enough.', 'code': 'MAX_CREDITS_EXCEEDED'} """ def __init__(self, error): super().__init__(error['message']) ...
def __str__(self): return '{}: {}'.format(self.code, self.message)
mushtaqak/edx-platform
common/djangoapps/third_party_auth/tasks.py
Python
agpl-3.0
6,642
0.003917
# -*- coding: utf-8 -*- """ Code to manage fetching and storing the metadata of IdPs. """ #pylint: disable=no-member from celery.task import task # pylint: disable=import-error,no-name-in-module import datetime import dateutil.parser import logging from lxml import etree import requests from onelogin.saml2.utils impor...
except Exception as err: # pylint: disable=broad-except log.exception(err.message) num_failed += 1 return (num_changed, num_failed, len(url_map)) def _parse_metadata_xml(xml, entity_id): """ Given an XML do
cument containing SAML 2.0 metadata, parse it and return a tuple of (public_key, sso_url, expires_at) for the specified entityID. Raises MetadataParseError if anything is wrong. """ if xml.tag == etree.QName(SAML_XML_NS, 'EntityDescriptor'): entity_desc = xml else: if xml.tag != etr...
intel/ipmctl
BaseTools/Source/Python/AutoGen/GenPcdDb.py
Python
bsd-3-clause
75,819
0.007755
## @file # Routines for generating Pcd Database # # Copyright (c) 2013 - 2016, Intel Corporation. All rights reserved.<BR> # This program and the accompanying materials # are licensed and made available under the terms and conditions of the BSD License # which accompanies this distribution. The full text of the ...
VPD_HEAD ${VPD_HEAD_CNAME_DECL}_${VPD_HEAD_GUID_DECL}[${VPD_HEAD_NUMSKUS_DECL}]; ${END} DYNAMICEX_MAPPING ExMapTable[${PHASE}_EXMAPPING_TABLE_SIZE]; UINT32 LocalTokenNumberTable[${PHASE}_LOCAL_TOKEN_NUMBER_TABLE_SIZE]; GUID GuidTable[${PHASE}_GUID_TABLE_SIZE]; ${BEGIN} ...
BLE_HEAD ${VARIABLE_HEAD_CNAME_DECL}_${VARIABLE_HEAD_GUID_DECL}_Variable_Header[${VARIABLE_HEAD_NUMSKUS_DECL}]; ${END} ${BEGIN} SKU_HEAD SkuHead[${PHASE}_SKU_HEAD_SIZE]; ${END} ${BEGIN} UINT8 StringTable${STRING_TABLE_INDEX}[${STRING_TABLE_LENGTH}]; /* ${STRING_TABLE_CNAME}_${STRING_TA...
jlgoldman/writetogov
database/populate_rep_status_from_propublica.py
Python
bsd-3-clause
2,149
0.005119
import requests from config import constants from database import db from database import db_models from util import fips R = db_models.Rep HOUSE_MEMBERS_LEAVING_OFFICE_URL = 'https://api.propublica.org/congress/v1/114/house/members/leaving.json' SENATE_MEMBERS_LEAVING_OFFICE_URL = 'https://api.propublica.org/congre...
break db.session.commit() def populate_reps(): response = requests.get(HOUSE_MEMBERS_LEAVING_OFFICE_URL, headers={'X-API-Key
': constants.PROPUBLICA_API_KEY}) info_by_district_code = {} for member in response.json()['results'][0]['members']: if member['state'] in fips.ONE_DISTRICT_STATE_CODES: district_code = '%s00' % member['state'] else: district_code = '%s%02d' % (member['state'], int(member...
alex-eri/aiohttp-1
aiohttp/client_proto.py
Python
apache-2.0
6,070
0
import asyncio import asyncio.streams from .client_exceptions import (ClientOSError, ClientPayloadError, ClientResponseError, ServerDisconnectedError) from .http import HttpResponseParser, StreamWriter from .streams import EMPTY_PAYLOAD, DataQueue class ResponseHandler(DataQueue, asyn...
self._message = None self._payload = None self._payload_parser = None self._reading_paused = False super().connection_lost(exc) def eof_received(self): pass def pause_reading(self): if not self._re
ading_paused: try: self.transport.pause_reading() except (AttributeError, NotImplementedError, RuntimeError): pass self._reading_paused = True def resume_reading(self): if self._reading_paused: try: self.transpo...
getupcloud/openshift-nginx-python-2.7
app.py
Python
apache-2.0
1,287
0.018648
#!/usr/bin/env python import imp import os import sys PYCART_DIR = ''.join(['python-', '.'.join(map(str, sys.version_info[:2]))]) try: zvirtenv = os.path.join(os.environ['OPENSHIFT_HOMEDIR'], PYCART_DIR, 'virtenv', 'bin', 'activate_this.py') execfile(zvirtenv, dict(__file__ = zvirtenv...
import make_server make_server(ip, port, app).serve_forever() # # IMPORTANT: Put any additional includes below this line. If placed above this # line, it's possible required libraries won't be in your searchable path # # # main(): # if __name__ == '__main__': ip = os.environ['OPENSHIFT_PYTHON_IP'] po...
%s:%d ... ' % (ip, port) try: run_gevent_server(zapp.application, ip, port) except: print 'gevent probably not installed - using default simple server ...' run_simple_httpd_server(zapp.application, ip, port)