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 |
|---|---|---|---|---|---|---|---|---|
mscuthbert/abjad | abjad/tools/pitchtools/test/test_pitchtools_NamedIntervalClass_from_pitch_carriers.py | Python | gpl-3.0 | 3,312 | 0.000302 | # -*- encoding: utf-8 -*-
from abjad import *
def test_pitchtools_NamedIntervalClass_from_pitch_carriers_01():
r'''Ascending intervals greater than an octave.
'''
mcpi = pitchtools.NamedIntervalClass.from_pitch_carriers(
NamedPitch(-3), NamedPitch(12))
assert mcpi == pitchtools.NamedIntervalC... | inor', 3)
mcpi = pitchtools.NamedIntervalClass.from_pitch_carriers(
NamedPitch(-2), NamedPitch(12))
assert mcpi == pitchtools.NamedIntervalClass('major', 2)
mcpi = pitchtools.NamedIntervalClass.from_pitch_carriers(
NamedPitch(-1), NamedPitch(12))
assert mcp | i == pitchtools.NamedIntervalClass('minor', 2)
def test_pitchtools_NamedIntervalClass_from_pitch_carriers_02():
r'''Ascending octave.
'''
mcpi = pitchtools.NamedIntervalClass.from_pitch_carriers(
NamedPitch(0), NamedPitch(12))
assert mcpi == pitchtools.NamedIntervalClass('perfect', 8)
def t... |
blakegarretson/projecteuler | prob12.py | Python | gpl-2.0 | 452 | 0.024336 | t = 1 # triangle number order, e.g. t=7 is 7th triangle number or 1+2+3+4+5+6+7=28
divisors = []
while len(divisors) <= 500:
n = sum(range(1,t+1)) # Genera | te triangle number
step = 2 if n%2 else 1
divisors = reduce(list.__add__, ([i, n//i] for i in range(1, int((n**0.5))+1, step) if n % i == 0))
# divisors = set(reduce(list.__add__, ([i, n//i] for i in range(1, int((n**0.5))+1, s | tep) if n % i == 0)))
t += 1
print n |
karllessard/tensorflow | tensorflow/python/data/experimental/kernel_tests/serialization/flat_map_dataset_serialization_test.py | Python | apache-2.0 | 4,497 | 0.007116 | # 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... | ensor_slices([defun_fn(x)])
return dataset_ops.Dataset.range(100).flat_map(map_fn)
self.run_core_tests(build_ds, 100)
@combinations.generate(test_base.default_test_combinations())
def testDisallo | wVariableCapture(self):
def build_ds():
test_var = variable_scope.get_variable(
name="test_var", shape=(), use_resource=True)
return dataset_ops.Dataset.range(5).flat_map(
lambda _: dataset_ops.Dataset.from_tensor_slices([test_var]))
self.verify_error_on_save(build_ds, 5, error... |
barseghyanartur/django-extensions | django_extensions/management/commands/shell_plus.py | Python | mit | 15,982 | 0.002127 | import os
import sys
import time
import traceback
from optparse import make_option
import six
from django.conf import settings
from django.core.management.base import NoArgsCommand
from django_extensions.management.shells import import_objects
from django_extensions.management.utils import signalcommand
class Comma... | raw_sql = self.db.ops.last_executed_query(self.cursor, sql, params)
if sqlparse:
print(sqlparse.format(raw_sql, reindent=True))
else:
print(raw_sql)
print("")
... | PrintQueryWrapper
def get_kernel():
try:
from IPython import release
if release.version_info[0] < 2:
print(self.style.ERROR("--kernel requires at least IPython version 2.0"))
return
from IPython import embed_ker... |
avalentino/PyTables | bench/chunkshape-bench.py | Python | bsd-3-clause | 1,877 | 0.001598 | #!/usr/bin/env python
# Benchmark the e | ffect of chunkshapes in reading large datasets.
# You need at least PyTables 2.1 to run this!
# F. Alted
from time import perf_counter as clock
import numpy as np
import tables as tb
dim1, dim2 = 360, 6_109_666
rows_to_read = range(0, 360, 36)
print("=" * 32)
# Create the EArray
f = tb.open_file("/tmp/test.h5", "w")... | (), shape=(dim1, 0),
expectedrows=dim2)
print("Chunkshape for original array:", a.chunkshape)
# Fill the EArray
t1 = clock()
zeros = np.zeros((dim1, 1), dtype="float64")
for i in range(dim2):
a.append(zeros)
tcre = clock() - t1
thcre = dim1 * dim2 * 8 / (tcre * 1024 * 1024)
print(f"Time to appe... |
naphatkrit/easyci | easyci/exit_codes.py | Python | mit | 115 | 0 | SUCCESS = 0
FAILURE = 1 # NO | TE: | click.abort() uses this
# for when tests are already running
ALREADY_RUNNING = 2
|
vishnuprathish/constrained-data-generator | fingered_temp.py | Python | apache-2.0 | 10,459 | 0.061956 | #!/Users/vishnu/anaconda/bin/python
import random
import sys
"""class schema:
files=[]
def __init__(self):
pass
def addFile(self,file):
self.files.append(file)
def setForeignKey(self,primaryFile,theOtherOne):
pass"""
class JoinReq:
def __init__(self,R,S,m,n,fing):
self.cost=0
self.first_req=True... | ]==list1[i]:
#print "xx" + str(list2[j])
#counter+=1
#if counter>1:
list2[j]=(list2[j]+list2[j+1])/2
return list1+list2
pass
def FormData(s | elf):
""" for col in range(self.cols):
if col == self.keyCol:
#print "key" + str(col)
#print runs
for r in range(self.runs[col]):
temp=sorted(random.sample(range(self.max),size/runs[col]))
#print temp
self.data[str(col)]=self.replaceDupandSum(self.data.get(str(col),[]),temp)
#self.d... |
bewo001/temsc | setup.py | Python | gpl-2.0 | 272 | 0.022059 | #!/usr/bin/env/ python3
from distutils.core import setup
setup | (name="temsc",
description="message flow generator",
version="v1.1",
author="Wolfgang Beck",
author_email=" | beckw@telekom.de",
url="https://github.com/bewo001/temsc",
packages=["msc"])
|
qilicun/python | python2/PyMOTW-1.132/PyMOTW/multiprocessing/multiprocessing_names.py | Python | gpl-3.0 | 764 | 0.006545 | #!/usr/bin/env python
# encoding: utf-8
#
# Copyright (c) 2008 Doug Hellmann All righ | ts reserved.
#
"""Naming threads
"""
#end_pymotw_header
import multiprocessing
import time
def worker():
name = multiprocessing.current_process().name
print name, 'Starting'
time.sleep(2)
print name, 'Exiting'
def my_service():
name = multiprocessing.current_process().name
print name, 'Starti... | processing.Process(name='my_service', target=my_service)
worker_1 = multiprocessing.Process(name='worker 1', target=worker)
worker_2 = multiprocessing.Process(target=worker) # use default name
worker_1.start()
worker_2.start()
service.start()
|
Mikumiku747/Student-Planner-Online-GAE | source/useragent.py | Python | mit | 1,406 | 0.000711 | # UserAg | ent
# Lets me check if a user is using the site on mobile or on desktop.
# Also lets you check kind of precisely what device the user is
# Viewing the site on
def checkMobile(request):
"Lets you che | ck to see if the user is on a mobile device."
agent = request.headers["User-Agent"]
deviceInfo = agent[agent.find('(')+1:agent.find(')')]
if "Android" in deviceInfo:
if "U;" in deviceInfo:
return True
else:
return False
elif "iPhone OS" in deviceInfo:
retu... |
mluscon/dnf | dnf/cli/commands/upgrade.py | Python | gpl-2.0 | 4,033 | 0.000744 | # upgrade.py
# Upgrade CLI command.
#
# Copyright (C) 2014-2016 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is... | self.base.output.term.bold(pkg.location))
else:
done | = True
# Update packages.
for pkg_spec in self.opts.pkg_specs:
try:
self.base.upgrade(pkg_spec)
except dnf.exceptions.MarkingError as e:
logger.info(_('No match for argument: %s'),
self.bas... |
KennyCandy/HAR | HAR_v7.py | Python | mit | 15,245 | 0.002558 | # Thanks to Zhao Yu for converting the .ipynb notebook to
# this simplified Python script that I edited a little.
# Note that the dataset must be already downloaded for this script to work, do:
# $ cd data/
# $ python download_dataset.py
import tensorflow as tf
import numpy as np
import matplotlib
import mat... | eatures count is of | 9: three 3D sensors features over time
self.n_hidden = 16 # nb of neurons inside the neural network
self.n_classes = 6 # Final output classes
self.W = {
'hidden': tf.Variable(tf.random_normal([self.n_inputs, self.n_hidden])), # [9, 32]
'output': tf.... |
jckarter/swift | benchmark/scripts/test_compare_perf_tests.py | Python | apache-2.0 | 46,859 | 0.000814 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# ===--- test_compare_perf_tests.py --------------------------------------===//
#
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library... | le(1, 2, 3)
self.assertEqual(s.i, 1)
self.as | sertEqual(s.num_iters, 2)
self.assertEqual(s.runtime, 3)
def test_is_iterable(self):
s = Sample(1, 2, 3)
self.assertEqual(s[0], 1)
self.assertEqual(s[1], 2)
self.assertEqual(s[2], 3)
class TestPerformanceTestSamples(unittest.TestCase):
def setUp(self):
self.sam... |
googleapis/python-logging | google/cloud/logging_v2/handlers/_helpers.py | Python | apache-2.0 | 7,592 | 0.001712 | # Copyright 2016 Google LLC All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | ace_id, span_id and trace_sampled
for the request. All fields will be N | one if a django request isn't found.
"""
if flask is None or not flask.request:
return None, None, None, False
# build http_request
http_request = {
"requestMethod": flask.request.method,
"requestUrl": flask.request.url,
"userAgent": flask.request.user_agent.string,
... |
sup95/zulip | zerver/views/integrations.py | Python | apache-2.0 | 4,038 | 0.002724 | from __future__ import absolute_import
from typing import Optional, Any, Dict
from collections import OrderedDict
from django.views.generic import TemplateView
from django.conf import settings
from django.http import HttpRequest, HttpResponse
import ujson
from zerver.lib import bugdown
from zerver.lib.integrations im... | I_PATH)
else:
external_api_path_subdomain = settings.EXTERNAL_API_PATH
html_settings_links = True
external_api_uri_subdomain = '%s%s' % (settings.EXTERNAL_URI_SCHEME,
external_api_path_subdomain)
context['external_api_path_subdomain'] = external_a... | s
class ApiURLView(TemplateView):
def get_context_data(self, **kwargs):
# type: (Optional[Dict[str, Any]]) -> Dict[str, str]
context = super(ApiURLView, self).get_context_data(**kwargs)
add_api_uri_context(context, self.request)
return context
class APIView(ApiURLView):
templat... |
mmetak/streamlink | src/streamlink/plugins/ceskatelevize.py | Python | bsd-2-clause | 4,014 | 0.000249 | """
Plugin for Czech TV (Ceska televize).
Following channels are working:
* CT1 - http://www.ceskatelevize.cz/ct1/zive/
* CT2 - http://www.ceskatelevize.cz/ct2/zive/
* CT24 - http://www.ceskatelevize.cz/ct24/
* CT sport - http://www.ceskatelevize.cz/sport/zive-vysilani/
* CT Decko - http://decko.ce... | oup(0).replace('&', '&')
if 'hash' not in tmp_url:
# there's | no hash in the URL, try to find it
matches = _hash_re.search(response.text)
if matches:
url = tmp_url+'&hash='+matches.group(1)
else:
url = tmp_url
return 'http://ceskatelevize.cz/'+url
class Ceskatelevize(Plugin):
@classmethod
def can_handle_... |
GoogleCloudPlatform/mlops-on-gcp | immersion/guided_projects/guided_project_2_solution/models/keras/model_test.py | Python | apache-2.0 | 1,262 | 0.00317 | # Lint as: python2, python3
# Copyright 2020 Google LLC. 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 req... | import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
from models.keras import model
class ModelTest(tf.test.TestCase):
def testBuildKerasModel(self):
pass
built_model = model._build_keras_model(
hidden_units=[1, 1], learning_rate=0.1... | t: disable=protoected-access
self.assertEqual(len(built_model.layers), 10)
built_model = model._build_keras_model(hidden_units=[1], learning_rate=0.1) # pylint: disable=protected-access
self.assertEqual(len(built_model.layers), 9)
if __name__ == '__main__':
tf.test.main()
|
oche-jay/vEQ-benchmark | vEQ_benchmark.py | Python | gpl-2.0 | 13,919 | 0.01401 | '''
Created on 24 Feb 2015
@author: oche
'''
from __future__ import unicode_literals
from __future__ import division
import argparse
import os
import sys
import time
import re
import logging
import json
import numpy
from plotter import makeSubPlot
from os.path import expanduser
from util import validURLMatch, validYo... |
cpu = procmon.get_processor()
os_info = procmon.get_os()
gpu = procmon.get_gpu()
specs =procmon.get_specs()
values = [start_time,os_info,cpu, gpu,specs]
sys_info_index = vEQdb.insertIntoSysInfoTable(values)
if not validURLMatch(video) and not (os.access(video, os.R_OK)):
... | Error: %s file not readable' % video)
sys.exit(1)
try:
if not validURLMatch(video):
logging.debug("Found regular video - using MediaInfo to extract details")
video_url = video
video_info = MediaInfo.parse(video)
video_data = video_info.to_json... |
coala/coala-bears | tests/python/requirements/PinRequirementsBearTest.py | Python | agpl-3.0 | 857 | 0 | from bears.python.requirements.PinRequirementsBear import PinRequirementsBear
from coalib.testing.LocalBearTestHelper import verify_local_bear
majors_given = """
# So this file contains majors, minors and patch versions
coala==0
coala-bears==0.8
coala-utils==0.5.0
"""
minors_given = """
# So this file contains major... | s_given,),
invalid_files=(majors_given, minors_given),
settings={'require_patch | ': True})
|
tadfisher/rama | rama/actions.py | Python | mit | 166 | 0.012048 | from os import f | ork, execvp
def launch(cmd):
args = cmd.split()
def launcher():
if not fork():
execvp(args[0], args)
return launc | her
|
mswart/pyopenmensa | tests/feed/test_prices.py | Python | lgpl-3.0 | 6,634 | 0.00182 | # -*- coding: UTF-8 -*-
import pytest
import re
from pyopenmensa.feed import convertPrice, buildPrices
class TestPriceConverting():
def test_int2price_convert(self):
assert convertPrice(304) == 304
assert convertPrice(20) == 20
def test_str_dot2price_convert(self):
assert convertPri... | ldPrices(
'-',
default='student',
additional={'employee': '0.20€', 'others': 50}
) == {}
def test_addtional_charges_with_none_clearing2(self):
assert buildPrices(
364,
default='student',
additional={'employee': '-', 'others': 5... | es(
CustomStr('3.64€'),
default='student',
) == self.single_price_example
def test_build_from_custom_int_subtype(self):
class CustomInt(int): pass
assert buildPrices(
CustomInt(364),
default='student',
) == self.single_price_example
... |
susantoj/powerfactory_python | examples/create_time_characteristics.py | Python | gpl-2.0 | 2,293 | 0.007414 |
"""
#####################################
## create_time_characteristics.py
#####################################
- Open a CSV file of 30min daily load profiles using TKinter file dialog box (for example "load_file.csv")
- Read CSV file and build list of loads
- Loop through list of loads and create time | characteristics
Format of CSV file:
- Column 1: Name of load
- Column 2-49: Load demand (in kW) for each half ho | ur interval from 0:00 to 23:30
"""
import tkinter as tk
from tkinter import filedialog
import sys
import csv
import powerfactory as pf
# Load object class definition
class csv_load():
def __init__ (self, input):
self.name = input[0]
self.P = [float(i)/1000 for i in input[1:49]] # Convert loads f... |
kuke/models | fluid/PaddleNLP/text_classification/async_executor/data_generator/data_generator.py | Python | apache-2.0 | 22,716 | 0.001189 | # Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the | Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless | required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
i... |
ruter/WeChat-img-Search | app/__init__.py | Python | apache-2.0 | 418 | 0.002392 | # -*- coding: utf-8 -*-
import sys
import pymongo
from flask import Flask
# Fix messy code
reload(sys)
sys.setdefaultencoding('utf-8')
app = Flask(__name__, instance_relative_config=True)
app.config.from_object('config')
app.config.from_pyfile('config.py')
client = pymongo.MongoClient(a | pp.config['DB_URI'])
| db = client[app.config['DB_NAME']]
collection = db[app.config['DB_COLLECTION']]
from app import views
|
MengGuo/mix_initiative | hil_mix_control/src/ltl_tools/product.py | Python | gpl-2.0 | 9,442 | 0.02616 | # -*- coding: utf-8 -*-
from buchi import check_label_for_buchi_edge
from networkx.classes.digraph import DiGraph
class ProdAut(DiGraph):
def __init__(self, ts, buchi, beta=100):
DiGraph.__init__(self, ts=ts, buchi=buchi, beta=beta, initial=set(), accept=set(), type='ProdAut')
def build_full(self):
for f_ts_... |
t_prod_node = self.composition(t_ts_node, t_buchi_node)
#print 't_prod_node' , (t_ts_node, t_buchi_node)
label = self.graph['ts'].node[f_ts_node]['label']
cost = self.graph['ts'][f_ts_node][t_ts_node]['wei | ght']
truth, dist = check_label_for_buchi_edge(self.graph['buchi'], label, f_buchi_node, t_buchi_node)
#print 'label,truth,total_weight', label,truth,total_weight
if truth:
total_weight ... |
snapcore/snapcraft | snapcraft/internal/sources/_script.py | Python | gpl-3.0 | 1,454 | 0 | # -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# Copyright (C) 2016 Canonical Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the h... | )
def download(self, filepath: str = None) -> str:
filepath = super().download(filepath=filepath)
st = os.stat(self.file)
os.chmod(self.file, st.st_mod | e | stat.S_IEXEC)
return filepath
|
Bloomie/murano-repository | muranorepository/api/v1.py | Python | apache-2.0 | 4,731 | 0.000634 | # Copyright (c) 2013 Mirantis, 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 requi | red 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 limitations
# under the License.
import os
from fl... | ser
from muranorepository.utils.archiver import Archiver
from muranorepository.consts import DATA_TYPES, MANIFEST
from oslo.config import cfg
CONF = cfg.CONF
v1_api = Blueprint('v1', __name__)
@v1_api.route('/client/ui')
def get_ui_data():
parser = ManifestParser(CONF.manifests)
manifests = parser.parse()
... |
LunaAstro/rochelobe | rochelobe.py | Python | gpl-3.0 | 61 | 0 | #!/usr/bin/env python
from | sospex import __main__
__main_ | _()
|
kbarnes3/guidcoin | web/manage_prod.py | Python | bsd-2-clause | 256 | 0 | # | !/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "guidcoin.settings_prod")
from django.core.management import exec | ute_from_command_line
execute_from_command_line(sys.argv)
|
godaddy/Thespian | thespian/system/test/test_fmap.py | Python | mit | 2,297 | 0.037875 | from pytest import raises
from thespian.system.utilis import fmap
class plain_obj(object):
def __init__(self, sublist):
self._sublist = sublist
def vals(self): return self._sublist
class fmap_obj(plain_obj):
def fmap(self, f):
return fmap_obj(fmap(f, self._sublist))
class TestFMap(obje... | , range(3))))))
# Arg: realize all of the iterables, since python3 returns things like map objects and filter objects
# but comparing those to an actual list fails. That's what all the list(result...) stuff is below.
print(len(result))
| assert [[20, 22], [46, 48], [[62,64], [84,(110,132)]], [(0,6), (2,8), (4,10)]] == \
[list(result[0]),
list(result[1]),
[list(result[2][0]), list(result[2][1])],
list(result[3].vals())]
|
alon/polinax | libs/external_libs/Pygments-0.11.1/pygments/styles/default.py | Python | gpl-2.0 | 2,543 | 0.000786 | # -*- coding: utf-8 -*-
"""
pygments.styles.default
~~~~~~~~~~~~~~~~~~~~~~~
The default highlighting style.
:copyright: 2007 by Tiberius Teng.
:copyright: 2006 by Georg Brandl.
:license: BSD, see LICENSE for more details.
"""
from pygments.style import Style
from pygments.token import Keyword... | ,
Generic.Strong: "bold",
Generic.Prompt: "bold #000080",
Ge | neric.Output: "#888",
Generic.Traceback: "#04D",
Error: "border:#FF0000"
}
|
ArcherSys/ArcherSys | node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/input_test.py | Python | mit | 9,761 | 0.006762 | <<<<<<< HEAD
<<<<<<< HEAD
#!/usr/bin/env python
# Copyright 2013 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Unit tests for the input.py file."""
import gyp.input
import unittest
import sys
class TestFindCycles(unittest.T... | ], self.nodes['b'], self.nodes['a']) in cycles)
self.assertTrue(
(self.nodes['b'], self.nodes['c'], self.nodes['b']) in cycles)
self.assertEquals(2, len(cycles))
def test_big_cycle(self):
self._create_dependency(self.nodes['a'], self.nodes['b'])
self._create_dependency(self.nodes['b'], self.no... | f._create_dependency(self.nodes['c'], self.nodes['d'])
self._create_dependency(self.nodes['d'], self.nodes['e'])
self._create_dependency(self.nodes['e'], self.nodes['a'])
self.assertEquals([(self.nodes['a'],
self.nodes['b'],
self.nodes['c'],
... |
izadorozhna/tempest | tempest/api/identity/admin/v2/test_tenant_negative.py | Python | apache-2.0 | 6,865 | 0 | # Copyright 2013 Huawei Technologies Co.,LTD.
# 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
#
# Unl... | str(uuid.uuid4().hex))
@test.attr(type=['negative'])
@test.idempotent_id('af16f44b-a849-46cb-9f13-a751c388f739')
def test_tenant_create_duplicate(self):
# Tenant names should be unique
tenant_name = data_utils.rand_name(name='tenant')
body = self.client.create_t... | body.get('id')
self.addCleanup(self.client.delete_tenant, tenant1_id)
self.addCleanup(self.data.tenants.remove, tenant)
self.assertRaises(lib_exc.Conflict, self.client.create_tenant,
tenant_name)
@test.attr(type=['negative'])
@test.idempotent_id('d26b278a-638... |
pombredanne/rekall | rekall-core/rekall/plugins/linux/bash.py | Python | gpl-2.0 | 6,561 | 0.000457 | # Rekall Memory Forensics
#
# Copyright 2013 Google Inc. All Rights Reserved.
#
# Authors:
# Michael Cohen <scudette@users.sourceforge.net>
#
# 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; eith... | ash data structures."""
__abstract = True
# types come from bash's ./lib/readli | ne/history.h
bash_vtype_32 = {
"_hist_entry": [0xC, {
"line": [0, ["Pointer", dict(target="String")]],
"timestamp": [4, ["Pointer", dict(target="String")]],
"data": [8, ["Pointer", dict(target="String")]],
}],
}
def __init__(self, **kwargs):
... |
nvazquez/Turtlebots | pysamples/brain.py | Python | mit | 4,207 | 0 | # A Turtle Block based on the Speak Activity interface to AIML
# Copyright 2012 Walter Bender, Sugar Labs
#
# Copyright (C) 2008 Sebastian Silva Fundacion FuenteLibre
# sebastian@fuentelibre.org
#
# Style and structure taken from Speak.activity Copyright (C) Joshua Minor
#
# HablarConSara.activity is free software:... | default_voice = voice.defaultVoice()
if default_voice.friendlyname not in | BOTS:
return voice.allVoices()[_('English')]
else:
return default_voice
def brain_respond(kernel, text):
if kernel is not None:
text = kernel.respond(text)
if kernel is None or not text:
text = ''
tw.showlabel(
'sta... |
praekelt/ummeli | ummeli/providers/tests.py | Python | bsd-3-clause | 29 | 0.034483 | # | This is where the te | sts go.
|
davidlee1435/MusicWebs | app/routes/user.py | Python | mit | 448 | 0.03125 | from flask import Blueprint, render_template,request, redirect, url_for, jsonify
from flask.ext.login import login_required, current_user
from app.models.tracks import Track,Layer
from app import db
user = Blueprint('user', __name__, url_prefix='/user')
@user.route('/<username>')
def findUser(username): #better way ... | cks = Track.objects(creat | edBy = username)
return render_template("all.html", tracks = tracks, search = username)
|
dud225/incubator-airflow | airflow/operators/mssql_operator.py | Python | apache-2.0 | 1,087 | 0 | import logging
from airflow.hooks import MsSqlHook
from airflow.models import BaseOperator
from airflow.utils.decorators import apply_defaults
class MsSqlOperator(BaseOperator):
"""
Executes sql code in a specific Microsoft SQL database
:param mssql_conn_id: reference to a specific mssql database
:ty... | MsSqlHook(mssql_conn_id=self.mssql_conn_id)
hook.run(self.sql, parameters=self.para | meters)
|
gpailler/Android2Wp_SMSConverter | thirdparty/filetimes.py | Python | mit | 3,563 | 0 | # Copyright (c) 2009, David Buxton <david@gasmark6.com>
# 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 li... | 0000000
ZERO = timedelta(0)
HOUR = timedelta(hours=1)
class UTC(tzinfo):
"""UTC"""
def utcoffset(self, dt):
return ZERO
def tzname(self, dt):
return "UTC"
def dst(self, dt):
return ZERO
utc = UTC()
def dt_to_filetime(dt):
"""Converts a datetime to Microsoft filetime... | 000'
>>> "%.0f" % dt_to_filetime(datetime(1970, 1, 1, 0, 0, tzinfo=utc))
'116444736000000000'
>>> "%.0f" % dt_to_filetime(datetime(1970, 1, 1, 0, 0))
'116444736000000000'
>>> dt_to_filetime(datetime(2009, 7, 25, 23, 0, 0, 100))
128930364000001000
"""
if (dt.tzinfo is None) or (dt.tzin... |
anthgur/servo | tests/wpt/web-platform-tests/tools/wptserve/wptserve/stash.py | Python | mpl-2.0 | 5,785 | 0.003111 | import base64
import json
import os
import uuid
import threading
from multiprocessing.managers import AcquirerProxy, BaseManager, DictProxy
class ServerDictManager(BaseManager):
shared_data = {}
def _get_shared():
return ServerDictManager.shared_data
ServerDictManager.register("get_dict",
... | if Stash._proxy is None:
manager = ClientDictManager(address, authkey)
manager.connect()
Sta | sh._proxy = manager.get_dict()
Stash.lock = LockWrapper(manager.Lock())
def _wrap_key(self, key, path):
if path is None:
path = self.default_path
# This key format is required to support using the path. Since the data
# passed into the stash can be a DictProxy which ... |
harshilasu/GraphicMelon | y/google-cloud-sdk/platform/gsutil/third_party/oauth2client/tests/test_oauth2client.py | Python | gpl-3.0 | 41,466 | 0.005523 | #!/usr/bin/python2.4
#
# Copyright 2014 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless require... | nt.client import MemoryCache
from oauth2client.client import NonAsciiHeaderError
from oauth2client.client import OAuth2C | redentials
from oauth2client.client import OAuth2WebServerFlow
from oauth2client.client import OOB_CALLBACK_URN
from oauth2client.client import REFRESH_STATUS_CODES
from oauth2client.client import SERVICE_ACCOUNT
from oauth2client.client import Storage
from oauth2client.client import TokenRevokeError
from oauth2client.... |
materialsproject/pymatgen | pymatgen/apps/battery/tests/test_plotter.py | Python | mit | 2,269 | 0.002644 | # Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
import json
import os
import unittest
from monty.json import MontyDecoder
from pymatgen.apps.battery.conversion_battery import ConversionElectrode
from pymatgen.apps.battery.insertion_battery import Inser | tionElectrode
from pymatgen.apps.battery.plotter import VoltageProfilePlotter
from pymatgen.core.composition import Composition
from pymatgen.entries.computed_entries import ComputedEntry
from pymatgen.util.testing import PymatgenTest
class VoltageProfilePlotterTest(unittest.TestCase):
def se | tUp(self):
entry_Li = ComputedEntry("Li", -1.90753119)
with open(os.path.join(PymatgenTest.TEST_FILES_DIR, "LiTiO2_batt.json")) as f:
entries_LTO = json.load(f, cls=MontyDecoder)
self.ie_LTO = InsertionElectrode.from_entries(entries_LTO, entry_Li)
with open(os.path.join... |
Nemo112/brainf | bl2co.py | Python | gpl-2.0 | 11,003 | 0.000182 | #!/usr/bin/python3
import sys
from optparse import OptionParser
import os
import zlib
import math
class Unbuffered(object):
def __init__(self, stream):
self.stream = stream
def write(self, data):
self.stream.write(data)
self.stream.flush()
def __getattr__(self, attr):
re... | eft_pixel = current
upleft_pixel = up_pixel
| pixels.append(row)
return pixels
def isPng(inp):
header = b'\x89PNG\r\n\x1a\n'
if inp == header:
return 1
else:
return 0
parser = OptionParser(usage="usage: %prog [options] files",
version="%prog 0.1")
parser.add_option("-i",
"--FileInpu... |
plilja/project-euler | problem_25/fibonacci_with_digits.py | Python | apache-2.0 | 241 | 0 | def fibonacci_with_digi | ts(num_digits):
if num_digits == 1:
return 1
n = 3
fib = 2
(fa, fb) = (1, 2)
while len(str(fib)) < num_digits:
fib = fa + fb
| (fa, fb) = (fb, fib)
n += 1
return n
|
gnsiva/Amphitrite | gui/SpectralAveragingGui/EditableListCtrl.py | Python | gpl-2.0 | 1,537 | 0.011711 | """Super class for creating an list control (table), where
the cells can be edited by the user.
"""
__author__ = "Ganesh N. Sivalingam <g.n.sivalingam@gmail.com"
import wx
from wx.lib.mixins.listctrl import TextEditMixin, ListCtrlAutoWidthMixin
#class EditableListCtrl(wx.ListCtrl, TextEditMixin, ListCtrlAutoWidthMix... | int)
"""
self.columnToIgnore = col
def getColumnStrings(self,col):
"""Get a list of strings containing the data in each
| cell in a column.
:parameter col: Column index (int)
:returns: List of strings
"""
rows = self.GetItemCount()
strings = []
for i in xrange(rows):
strings.append(self.GetItem(i,col).GetText())
return strings
|
open-motivation/motivation-ide | ninja_ide/gui/dialogs/preferences.py | Python | gpl-3.0 | 87,573 | 0.002866 | # -*- coding: utf-8 -*-
#
# This file is part of NINJA-IDE (http://ninja-ide.org).
#
# NINJA-IDE 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
# any later version.
#
# NIN... | self.overlay.resize(event.size())
event.accept()
class GeneralTab(QWidget):
def __init__(self, parent):
QWidget.__init__(self)
vbox = QVBoxLayout(self)
self._tabs = QTabWidget()
self._generalConfigur | ation = GeneralConfiguration(parent)
self._generalExecution = GeneralExecution()
self._shortcutConfiguration = shortcut_manager.ShortcutConfiguration()
self._tabs.addTab(self._generalConfiguration, self.tr("General"))
self._tabs.addTab(self._generalExecution, self.tr("Execution"))
... |
4shadoww/usploit | core/colors.py | Python | mit | 222 | 0.004545 | # Copyright (C) 2015 – 2021 Noa-Emil Nissinen (4shadoww)
purple = '\033[95m'
blue = '\033[94m'
green = '\033[32m'
cy | an = '\033[36m'
yellow = '\033[93m'
red = '\033[91m'
end = '\033[0m'
bol | d = '\033[1m'
uline = '\033[4m' |
botswana-harvard/getresults-receive | getresults_receive/models/receive.py | Python | gpl-2.0 | 2,273 | 0.00132 | from django.db import models
from django.utils import timezone
from edc_base.model.models import BaseUuidModel
from simple_history.models import HistoricalRecords as AuditTrail
from getresults_patient.models import Patient
from .receive_identifier import ReceiveIdentifier
class ReceiveBaseFieldsMixin(models.Model):... | f.receive_datetime.strftime('%Y-%m-% | d %H:%M'))
def save(self, *args, **kwargs):
if not self.id and not self.receive_identifier:
self.receive_identifier = ReceiveIdentifier().identifier
if not self.specimen_reference:
self.specimen_reference = '{}-{}'.format(
self.collection_datetime.strftime('%... |
Maratyszcza/confu | confu/tools/toolchains/nacl.py | Python | mit | 5,484 | 0.0062 | from __future__ import absolute_import
from confu.platform import Platform
from confu.tools.toolchains import UnixToolchain
import confu.globals
import confu.platform
import os
class NaClToolchain(UnixToolchain):
def __init__(self, target, toolchain):
supe | r(NaClToolchain, self).__init__(target)
assert isinstance(target, Platform)
assert target in ["x86_64-nacl-gnu", "x86_64-nacl-newlib", "pnacl-nacl-newlib"]
assert isinstance(toolchain, str)
# Check if we are running in a supported environment
if confu.platform.host not in ["x86_... | -gnu", "x86_64-macos", "x86_64-windows"]:
raise EnvironmentError("Cross-compilation for {target} is not supported on {host}: "
"x86-64 Linux, Mac, or Windows system required"
.format(target=target, host=confu.platform.host))
# Lo... |
shutterfly/logtools | logtools/utils.py | Python | apache-2.0 | 1,266 | 0.028436 | #!/u | sr/bin/env python
#
# 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 writ... | CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
logtools.utils
A few programmatic utilities / methods.
These are not exposed as command-line tools
but can be used by other methods
"""
import os
import sy... |
MiracleWong/PythonBasic | mail/send_email_and_picture.py | Python | mit | 800 | 0.002646 | # -*- coding: utf-8 -*-
from smtplib import SMTP_SSL
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
from email.mime.text import MIMEText
client = SMTP_SSL("smtp.qq.com")
# 此处填写自己的邮箱账号和授权码,
client.login('shiyanlou@qq.com', 'shiyanlou')
# 打开图 | 片文件
with open("test_img.png", "rb") as f:
img = MIMEImage(f.read(), name="test_img.png")
img.add_header("Content-ID", "img_id")
msg = MIMEMultipart()
html = MIMEText("""
<p> there is a img </p>
<img src="cid:img_id">
""", "html", "utf-8")
msg.attach(img)
msg.attach(html)
msg['From'] = "shiyanlou@qq | .com"
msg['To'] = "shiyanlou@qq.com"
msg['Subject'] = "this is a subject"
client.sendmail("shiyanlou@qq.com", "shiyanlou@qq.com", msg.as_string())
client.quit() |
vangdfang/conspace-register | admin.py | Python | bsd-2-clause | 14,624 | 0.004034 | # Copyright (c) 2014-2015, Doug Kelly
# 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, this
# list of conditions and... | e documentation
# and/or other materials provided with the distribution.
#
# 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 MERCHA | NTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PRO... |
bouncer-app/bouncer | bouncer/test_bouncer/models.py | Python | mit | 547 | 0.001828 | class User(object):
def __init__(self, **kwargs):
self.i | d = kwargs.get('id', 1)
self.name = kwargs['name']
| self.admin = kwargs['admin']
pass
@property
def is_admin(self):
return self.admin
class Article(object):
def __init__(self, **kwargs):
self.author = kwargs['author']
class BlogPost(object):
def __init__(self, **kwargs):
self.author_id = kwargs['author_id']
... |
3dfxsoftware/cbss-addons | report_move_voucher/report/__init__.py | Python | gpl-2.0 | 1,449 | 0.001381 | #!/usr/bin/python
# -*- encoding: utf-8 -*-
###########################################################################
# Module Writen to OpenERP, Open Source Management Solution
# Copyright (C) OpenERP Venezuela (<http://openerp.com.ve>).
# All Rights Reserved
###############Credits##########################... | p://vauxoo.com
# Audited by: Humberto Arocha humberto@openerp.com.ve
#############################################################################
# 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... | the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# ... |
summea/dream-world-storehouse | dreamworld/app/views/character.py | Python | mit | 3,312 | 0.003019 | from bottle import post, route
from .. import dbengine
from ..app import authenticate, db_object_to_dict
from ..models import Character, Location
from ..view import render
class Characters:
def __init__(self):
pass
def all(self):
"""list all characters for editing"""
username = authen... | te.html', {'username': username, 'locations': locations}, 'admin.html')
def edit(self, id):
"""edit character"""
username = authenticate()
session = dbengine.connect()
character = session.query(Character).filter(Character.id==id | ).first()
locations = {}
for location in session.query(Location):
locations[location.id] = db_object_to_dict(location)
return render('characters/edit.html', {'username': username, 'character': character, 'locations': locations}, 'admin.html')
def index(self):
"""charact... |
moonbury/notebooks | github/Numpy/Chapter7/sortcomplex.py | Python | gpl-3.0 | 239 | 0 | from __future__ import print_function
import numpy as np
np.random.seed(42)
complex_numbe | rs = np.random.random(5) + 1j * np.random.random(5)
print("Complex numbers\n", complex_numbers)
print("Sorted\n", np.sor | t_complex(complex_numbers))
|
GbalsaC/bitnamiP | django-wiki/django_notify/urls.py | Python | agpl-3.0 | 864 | 0.016204 | # -*- coding: utf-8 -*-
from django.conf.urls.defau | lts import patterns, url
urlpatterns = patterns('',
url('^json/get/$', 'django_notify.views.get_notifications', name='json_get', kwargs={}),
url('^js | on/mark-read/$', 'django_notify.views.mark_read', name='json_mark_read_base', kwargs={}),
url('^json/mark-read/(\d+)/$', 'django_notify.views.mark_read', name='json_mark_read', kwargs={}),
url('^goto/(?P<notification_id>\d+)/$', 'django_notify.views.goto', name='goto', kwargs={}),
url('^goto/$', 'd... |
costincaraivan/hackerrank | algorithms/warmup/python3/simple_array_sum.py | Python | mit | 149 | 0 | #!/bin/python3
impor | t sys
n = int(input().strip())
arr = [int(arr_temp) for arr_temp in input().strip().split(' ')]
total = sum(arr)
print(to | tal)
|
alxgu/ansible | lib/ansible/modules/cloud/misc/virt_pool.py | Python | gpl-3.0 | 21,816 | 0.000779 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2015, Maciej Delmanowski <drybjed@gmail.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1... | l:
state: active
name: vms
# Ensure that a pool is inactive
- virt_pool:
state: inactive
name: vms
# Ensure that a given pool will be started at boot
- virt_pool:
autostart: yes
name: vms
# Disable autostart for a given pool
- virt_pool:
autostart: no
name: vms
'''
try:
import li... | HAS_VIRT = True
try:
from lxml import etree
except ImportError:
HAS_XML = False
else:
HAS_XML = True
from ansible.module_utils.basic import AnsibleModule
VIRT_FAILED = 1
VIRT_SUCCESS = 0
VIRT_UNAVAILABLE = 2
ALL_COMMANDS = []
ENTRY_COMMANDS = ['create', 'status', 'start', 'stop', 'build', 'delete',
... |
ifduyue/django | django/core/management/commands/showmigrations.py | Python | bsd-3-clause | 5,333 | 0.0015 | from django.core.management.base import BaseCommand, CommandError
from django.db import DEFAULT_DB_ALIAS, connections
from django.db.migrations.loader import MigrationLoader
class Command(BaseCommand):
help = "Shows all available migrations for the current project"
def add_arguments(self, parser):
pa... | (leaves).
for app_name in app_names:
self.stdout.write(app_name, self.style.MIGRATE_LABEL)
shown = set()
for node in graph.leaf_nodes(app_name):
for plan_node in graph.forwards_plan(node):
if plan_node not in shown and plan_node[0] == app_... | n_node].replaces:
title += " (%s squashed migrations)" % len(graph.nodes[plan_node].replaces)
# Mark it as applied/unapplied
if plan_node in loader.applied_migrations:
self.stdout.write(" [X] %s" % title)
... |
Semillas/semillas_platform | services/migrations/0007_auto_20161112_1406.py | Python | mit | 496 | 0.002016 | # -*- codi | ng: utf-8 -*-
# Generated by Django 1.9.7 on 2016-11-12 14:06
from __future__ import unicode_literals
from django.db import migrations, models
import uuid
class Migration(migrations.Migration):
dependencies = [
('services', '0006_auto_20161112_1406'),
]
operations = [
migrations.AlterFi... | alse, unique=True),
),
]
|
Sparkier/inviwo | data/scripts/savetransferfunction.py | Python | bsd-2-clause | 196 | 0.02551 | # Inviwo Python script
import inviwopy
tf = inviwopy.app.network.VolumeRaycaster. | transferFunction
tf.save( inviwopy.app.getPath( inviwopy.PathType.T | ransferFunctions) + "/transferfunction.itf" )
|
JonatanAntoni/CMSIS_5 | CMSIS/DSP/SDFTools/sdf/nodes/py/StereoToMono.py | Python | apache-2.0 | 1,632 | 0.015931 | ###########################################
# Project: CMSIS DSP Library
# Title: StereoToMono.py
# Description: Stereo to mono in Q15
#
# $Date: 06 August 2021
# $Revision: V1.10.0
#
# Target Processor: Cortex-M and Cortex-A cores
# -------------------------------------------------------------... | # See the License for the specific language governing permissions and
# limitations under the License.
############################################
from sdf.schedule.simu import *
import numpy as np
i | mport cmsisdsp as dsp
class StereoToMono(GenericNode):
def __init__(self,inputSize,outputSize,fifoin,fifoout):
GenericNode.__init__(self,inputSize,outputSize,fifoin,fifoout)
if fifoin.type == np.dtype(np.float32):
self._isFloat=True
else:
self._isFloat=False
d... |
parthz/buku | core/services/serializers.py | Python | mit | 1,760 | 0.016477 | from rest_framework import serializers
from .models import PublicCategories, PrivateCategories, FeedMapper, Feeds, UserSubscriptions, FeedStatus, UserSubscriptions
#Default Serializers
class FeedStatusSerializer(serializers.ModelSerializer):
class Meta:
model = FeedStatus
class UserSubscriptionsSerializer... | alizer):
class Meta:
model = FeedMapper
class FeedsSerializer(serializers.ModelSerializer):
class Meta:
model = Feeds
class UserSubscriptionsSerializ | er(serializers.ModelSerializer):
class Meta:
model = UserSubscriptions
#Create Serializer
class PrivateCategoriesCreateSerializer(serializers.ModelSerializer):
class Meta:
model = PrivateCategories
fields = ('name', 'description')
#List Serializer
class UserSubscriptionsListSerializer(... |
mkouhei/nenga | nenga/address/migrations/__init__.py | Python | gpl-3.0 | 40 | 0 | """ nenga.address.migrations modu | le """
| |
rbarlow/pulp_docker | extensions_admin/pulp_docker/extensions/admin/content.py | Python | gpl-2.0 | 7,183 | 0 | from gettext import gettext as _
from pulp.client.commands import options
from pulp.client.commands.criteria import DisplayUnitAssociationsCommand
from pulp.client.commands.unit import UnitCopyCommand, UnitRemoveCommand
from pulp_docker.common import constants
DESC_COPY_MANIFESTS = _('copies manifests from one repo... | tSearchCommand, self).__init__(
name='manifest',
description=DESC_SEARCH_MANIFESTS,
method=self.run)
self.context = context
self.prompt = context.prompt
def run(self, **kwargs):
"""
Print a list of all the manifests matching the search parameters.... | kwargs['type_ids'] = [constants.MANIFEST_TYPE_ID]
reply = self.context.server.repo_unit.search(repo_id, **kwargs)
manifests = reply.response_body
self.prompt.render_document_list(manifests)
class ManifestCopyCommand(UnitCopyCommand):
"""
Command used to copy manifest units betw... |
moden-py/aiohttp | aiohttp/helpers.py | Python | apache-2.0 | 21,217 | 0.000283 | """Various helper functions"""
import asyncio
import base64
import binascii
import cgi
import datetime
import functools
import io
import os
import re
import warnings
from collections import MutableSequence, namedtuple
from pathlib import Path
from time import gmtime, time
from urllib.parse import urlencode
from async... | FormData:
"""Helper class for multipart/form-data and
application/x-www-form-urlencoded body generation."""
def __init__(self, fields=()):
from . import multipart
self._writer = multipart.MultipartWriter('form-data')
self._fields = []
self._is_multipart = False
if i... | fields = list(fields.items())
elif not isinstance(fields, (list, tuple)):
fields = (fields,)
self.add_fields(*fields)
@property
def is_multipart(self):
return self._is_multipart
@property
def content_type(self):
if self._is_multipart:
return s... |
nesl/mercury | Services/Mapping/fixProgram/script.py | Python | gpl-2.0 | 1,925 | 0.004675 | #!/usr/bin/python
import os
import sys
import re
# file name unified by the following rule:
# 1. always save the osm under ../osmFiles directory
# 2. the result automatically generate to ../trajectorySets
# 3.1. change variable "osmName", or
# 3.2. use command argument to specify osm file name
# 4. this script genera... | l'
cmd = 'basex findWayTrajectory.xq > ' + xmlWayDetail
print('CMD: ' + cmd)
if os.path.isfile(xmlWayDetail):
print('File existed. S | kip.')
else:
os.system(cmd)
# the next step should be executing the python3 ../makeElevSegMap.py with the input
# parameter outFile, but because of the relative folder path issue, integrating
# makeElevSegMap.py into this code needs to make big changes. So at this stage,
# we still stay on manually executing that ... |
rlbabyuk/integration_tests | cfme/cloud/stack.py | Python | gpl-2.0 | 8,488 | 0.002356 | from functools import partial
from xml.sax.saxutils import quoteattr
from navmazing import NavigateToSibling, NavigateToAttribute
from selenium.common.exceptions import NoSuchElementException
import cfme.fixtures.pytest_selenium as sel
from cfme import web_ui as ui
from cfme.exceptions import DestinationNotFound, Sta... | ar():
try:
self.find_quadicon()
except StackNotFound:
return True
else:
return False
navigate_to(self, 'All' | )
wait_for(_wait_to_disappear, fail_condition=False, message="Wait stack to disappear",
num_sec=15 * 60, fail_func=self.refresh_view_and_provider, delay=30)
def wait_for_appear(self):
def _wait_to_appear():
try:
self.find_quadicon()
except St... |
hugovk/coveragepy | coverage/exceptions.py | Python | apache-2.0 | 1,237 | 0 | # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0
# For details: https://github.com/nedbat/coveragepy/blob/master/NOTICE.txt
"""Exceptions coverage.py can raise."""
class BaseCoverageException(Exception):
"""The base of all Coverage exceptions."""
pass
class CoverageException(... | pass
class NotPython(CoverageException):
"""A source file turned out not to be parsable Python."""
pass
class ExceptionDuringRun(CoverageException):
"""An exception happened while running customer code.
Construct it with three arguments, the values from `sys.exc_info`.
"""
pass
class St... | overageTest class converts these to SkipTest, so that when running
tests, raising this exception will automatically skip the test.
"""
pass
class CoverageWarning(Warning):
"""A warning from Coverage.py."""
pass
|
costincaraivan/hackerrank | regex/repetitions/python3/match_x_repetitions.py | Python | mit | 73 | 0.013699 | Regex_Patter | n = r'^[a-zA-Z02468]{40}[13579\s] | {5}$' # Do not delete 'r'.
|
StackVista/sts-agent-integrations-core | ssh_check/check.py | Python | bsd-3-clause | 4,172 | 0.003116 |
# stdlib
from collections import namedtuple
import time
# 3p
import paramiko
# project
from checks import AgentCheck
class CheckSSH(AgentCheck):
OPTIONS = [
('host', True, None, str),
('port', False, 22, int),
('username', True, None, str),
('password', False, None, str),
... | key_file)
else:
private_key = paramiko.RSAKey.from_private_key_file(conf.private_key_file)
except IOError:
self.warning("Unable to find private key file: {}".format(conf.private_key_file))
except paramiko.ssh_e | xception.PasswordRequiredException:
self.warning("Private key file is encrypted but no password was given")
except paramiko.ssh_exception.SSHException:
self.warning("Private key file is invalid")
client = paramiko.SSHClient()
if conf.add_missing_keys:
client.... |
zmetcalf/django-webdev | backbone_ajax/views.py | Python | gpl-3.0 | 112 | 0.008929 | from dj | ango.shortcuts import render
def index(request):
ret | urn render(request, 'backbone_ajax/index.html')
|
compstak/selenium | py/selenium/webdriver/__init__.py | Python | apache-2.0 | 1,282 | 0 | #!/usr/bin/python
#
# Copyright 2008-2013 Software Freedom Conservancy
#
# 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.apac | he.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
# limit... |
yugangw-msft/azure-cli | tools/automation/utilities/path.py | Python | mit | 6,263 | 0.003193 | # --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... | dules)
def fil | ter_user_selected_modules_with_tests(user_input_modules=None, profile=None):
import itertools
existing_modules = list(itertools.chain(get_core_modules_paths_with_tests(profile),
get_command_modules_paths_with_tests(profile)))
if user_input_modules is not None:
... |
globality-corp/microcosm | microcosm/errors.py | Python | apache-2.0 | 595 | 0 | """
Error types
"""
class AlreadyBoundError(Exception):
"""
Raised if a factory is already bound to a name.
"""
pass
class CyclicGraphError(Exception):
"""
Raised if a graph has a cycle.
"""
pass
class LockedGraphError(Exception):
"""
Raised when attempting to create a c... | ject graph.
"""
pass
class NotBoundError(Exception):
"""
Raised if not factory is bound to a name.
"""
pass
class ValidationError(Exception):
"""
Raised if a configuration value fails | validation.
"""
pass
|
jonlatorre/MatriculaEIDE | pagosonline/views.py | Python | mit | 6,782 | 0.008857 | # -*- coding: utf-8 -*-
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import ListView, CreateView, UpdateView, DeleteView
from django.http import HttpResponse
from django.shortcuts import get_object_or_404, render_to_response, redirect
from django.views.generic.detail import DetailVi... | ject
| site = Site.objects.get_current()
site_domain = site.domain
pago = self.object
merchant_parameters = {
"Ds_Merchant_Titular": 'John Doe',
"Ds_Merchant_MerchantData": 'man-%s' % pago.id, # id del Pedido o Carrito, para identificarlo en el mensaje de vuelta
"D... |
tu-darmstadt-ros-pkg/hector_flexbe_behavior | behaviors/behavior_detect_pipes/src/behavior_detect_pipes/detect_pipes_sm.py | Python | bsd-3-clause | 16,710 | 0.02322 | #!/usr/bin/env python
###########################################################
# WARNING: Generated code! #
# ************************** #
# Manual changes may get lost if file is generated again. #
# Only code inside the [MANUAL] tags will be kept. ... | ed pipe manipulation", severity=Logger.REPORT_HINT),
transitions={'done': 'Decide_Open_Gripper'},
autonomy={'done': Autonomy.High})
# x:215 y:511
OperatableStateMachine.add('Open_Gripper',
GripperState(action=GripperState.OPEN, duration=1.0),
transitions={'done': 'finished... | ow, 'failed': Autonomy.High})
# x:153 y:384, x:388 y:221
_sm_move_back_out_1 = OperatableStateMachine(outcomes=['finished', 'failed'], input_keys=['pipes_out_pose'])
with _sm_move_back_out_1:
# x:118 y:87
OperatableStateMachine.add('Get_Cartesian_Path_Back',
CalculateCartesianPathState(move_gro... |
codilime/contrail-controller | src/config/common/vnc_kombu.py | Python | apache-2.0 | 12,514 | 0.002637 | #
# Copyright (c) 2014 Juniper Networks, Inc. All rights reserved.
#
import re
from distutils.util import strtobool
import kombu
import gevent
import gevent.monkey
gevent.monkey.patch_all()
import time
import signal
from gevent.queue import Queue
try:
from gevent.lock import Semaphore
except ImportError:
# old... | f._conn.connection_errors + self._conn.channel_errors as e:
| self._reconnect()
except Exception as e:
log_str = "Error in rabbitmq publisher greenlet: %s" %(str(e))
self._logger(log_str, level=SandeshLevel.SYS_ERR)
# avoid 'reconnect()' here as that itself might cause exception
connected = False
... |
boxed/CMi | web_frontend/gdata/oauth/rsa.py | Python | mit | 4,676 | 0.004919 | #!/usr/bin/python
"""
requires tlslite - http://trevp.net/tlslite/
"""
import binascii
try:
from gdata.tlslite.utils import keyfactory
except ImportError:
from tlslite.tlslite.utils import keyfactory
try:
from | gdata.tlslite.utils import cryptomath
except ImportError:
from tlslite.tlslite.utils import cryptomath
# XXX andy: ugly local import due to module name, oauth.oauth
import gdata.oauth as oauth
class OAuthSignatureMethod_RSA_SHA1(oauth.OAuthSignatureMethod):
def get_name(self):
return "RSA-SHA1"
def _fetch... | consumer
# (2) fetch via http using a url provided by the requester
# (3) some sort of specific discovery code based on request
#
# either way should return a string representation of the certificate
raise NotImplementedError
def _fetch_private_cert(self, oauth_request):
# not implemented yet... |
sharoonthomas/nereid-project | tests/test_task.py | Python | gpl-3.0 | 38,238 | 0 | # -*- coding: utf-8 -*-
"""
test_task
TestTask
:copyright: (c) 2013-2015 by Openlabs Technologies & Consulting (P) Limited
:license: BSD, see LICENSE for more details.
"""
import unittest
import json
import smtplib
from minimock import Mock
from trytond.tests.test_tryton import POOL, DB_NAME, USER, C... | self.assertEqual(respo | nse.status_code, 201)
# Get Task
response = c.get(
'/projects/%d/tasks/' % self.project1.id,
)
self.assertEqual(response.status_code, 200)
task_data = json.loads(response.data)
self.assertEqual(task_dat... |
mayconbordin/boardhood | server_app/api/boardhood/tests/test_model_conversations.py | Python | mit | 8,541 | 0.002576 | import unittest
from config import app
from datetime import datetime
from boardhood.models.conversations import Conversation
from boardhood.helpers.validator import is_integer, is_array
class TestConversationModel(unittest.TestCase):
def setUp(self):
self.model = Conversation()
Conversation.db = ap... | Conversation))
self.assertTrue(obj.interest.id == interest_id)
def testFind | AllAround(self):
objs = Conversation.findAll(location=[-27.8727, -54.4951])
self.assertTrue(is_array(objs))
self.assertTrue(len(objs) > 0)
for obj in objs:
self.assertTrue(isinstance(obj, Conversation))
def testFindAllAroundRadius(self):
objs = Conversation.find... |
Zac-HD/3D-tools | src/geoply.py | Python | gpl-3.0 | 8,980 | 0.000891 | """
Tools to read and write georeferenced pointclouds such as output from Pix4D,
based on the plyfile module.
"""
import collections
import itertools
import json
import tempfile
import warnings
import numpy as np
import plyfile
UTM_COORD = collections.namedtuple(
'UTMCoord', ['easting', 'northing', 'zone', 'nor... | shape=self['vertex'].data.shape)
mmap[:] = self['vertex'].data[:]
self['vertex'].data = mmap
@staticmethod
def read(stream):
"""Reads vertices from ``stream``, with UTM offset and data cleaning.
stream may be a filename, or a file-like object.
... | omments in the file header, if the pointcloud was created
by this class.
- the corresponding '_ply_offset.xyz' file, if the pointcloud was
created by Pix4D. In this case, the Z-offset is added to vertex
coordinates.
Data cleaning consists of:
- discarding non-"ve... |
belokop/indico_bare | indico/core/storage/backend.py | Python | gpl-3.0 | 11,228 | 0.001069 | # This file is part of Indico.
# Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN).
#
# Indico 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 (a... | a = definition.split(':', 1)
try:
backend = get_storage_backends()[name]
except KeyError:
raise RuntimeError('Storage backend {} has i | nvalid type {}'.format(backend_name, name))
return backend(data)
def get_storage_backends():
return named_objects_from_signal(signals.get_storage_backends.send(), plugin_attr='plugin')
class StorageError(Exception):
"""Exception used when a storage operation fails for any reason"""
class Storage(objec... |
uclouvain/OSIS-Louvain | base/tests/models/test_session_exam_calendar.py | Python | agpl-3.0 | 14,621 | 0.004514 | ##############################################################################
#
# OSIS stands for Open Student Information System. It's an application
# designed to manage the core business of higher education institutions,
# such as universities, faculties, institutes and professional schools.
# The core ... | data_year=cls.current_academic_yr,
reference=AcademicCalendarTypes.SCORES_EXAM_SUBMISSION.name)
cls.academic_cale | ndar_4 = AcademicCalendarFactory(title="Deliberation session 1",
start_date=datetime.date(next_year, 1, 1),
end_date=datetime.date(next_year, 1, 2),
... |
achilleas-k/brian-scripts | thesis_stuff/test_in_out.py | Python | apache-2.0 | 2,076 | 0 | from __future__ import print_function, division
from brian import (Network, NeuronGroup, SpikeMonitor,
| PoissonGroup, Connection,
mV, ms, Hz)
import sys
import matplotlib.pyplot as plt
import numpy as np
import itertools as itt
fin = [f*Hz for f in range(10, 41, 5)]
w | in = [w*mV for w in np.arange(0.5, 2.1, 0.5)]
Nin = [n for n in range(100, 181, 20)]
tau = 10*ms
Vth = 15*mV
reset = 0*mV
configs = [c for c in itt.product(Nin, fin, win)]
Nsims = len(configs)
print("Number of configurations: {}".format(Nsims))
lifeq = "dV/dt = -V/tau : volt"
sim = Network()
nrn = NeuronGroup(Nsims, ... |
Tomcuzz/OctaHomeAutomation | Api/api.py | Python | mit | 2,221 | 0.029266 | from Lights.models import *
from django.http import Http | Response, HttpResponseNotFound
from SharedFunctions.deviceControl import *
class LightApi():
def webRequest(self, request):
command = request.GET.get('command', '')
if command == "getStatus":
pageContent = "["
isNotInFirstLoop = False
for alight in Lights.objects.all():
if isNotInFirstLoop:
page... | else:
isNotInFirstLoop = True
pageContent += "{"
pageContent += "\"id\":"
pageContent += "\"" + str(alight.id) + "\", "
pageContent += "\"Light\":"
pageContent += "\"" + alight.LightName.replace("_", " ") + "\", "
pageContent += "\"Room\":"
pageContent += "\"" + alight.Room.Name.replace... |
mdiscenza/gallery_hop_2 | make_photo_table.py | Python | mit | 728 | 0.017857 | import mysql.connector
import csv
# Make RDS table and add rows from CSV file
cnx = mysql.connector.connect(user='galleryhop', password='galleryhop', host='galleryhop2.crflf9m | u2uwj.us-east-1.rds.amazonaws.com',database='galleryhop2')
cursor = cnx.cursor()
t = """CREATE TABLE photos(
artist VARCHAR(50),
photo VARCHAR(5000))"""
cursor.execute(t)
cnx.commit()
urls = ['https://s3.amazonaws.com/galleryhop/copperwhite.jpg','https://s3.amazonaws.com/galleryhop/gitman.jpg','https://s3.amazonaws... | o) VALUES (%s,%s)"
cursor.execute(stmt,(artists[i],urls[i]))
cnx.commit()
|
tradej/pcs | pcs/test/test_rule.py | Python | gpl-2.0 | 67,998 | 0.001941 | from __future__ import absolute_import
import os
import sys
import shutil
import unittest
import xml.dom.minidom
parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, parentdir)
from pcs_test_functions import pcs,ac
import rule
empty_cib = "empty.xml"
temp_cib = "temp.xml"
class D... | o" % item,
rule.DateDurationValue
)
def testDateSpecValidation(self):
for item in rule.DateCommonValue.allowed_items:
value = 1
self.assertEquals(
str(value),
rule.DateSpecValue("%s=%s" % (item, value)).parts[item]
... | ).parts[item]
)
self.assertEquals(
"hours=9-16 weekdays=1-5",
str(rule.DateSpecValue("hours=9-16 weekdays=1-5"))
)
for item in rule.DateCommonValue.allowed_items:
self.assertSyntaxError(
"invalid %s '%s' in 'date-spec'" ... |
slabanja/ase | ase/utils/geometry.py | Python | gpl-2.0 | 16,615 | 0.002708 | # Copyright (C) 2010, Jesper Friis
# (see accompanying license files for details).
"""Utility tools for convenient creation of slabs and interfaces of
different orientations."""
import numpy as np
def gcd(seq):
"""Returns greatest common divisor of integers in *seq*."""
def _gcd(m, n):
while n:
... | plane, you can get all layers
parallel to this with miller=np.cross(a,b).
tolerance: float
The maximum distance in Angstrom along the plane normal for
counting two atoms as belonging to the same plane.
Returns:
tags: array of integres
Array of layer indices fo | r each atom.
levels: array of floats
Array of distances in Angstrom from each layer to origo.
Example:
>>> import numpy as np
>>> from ase.lattice.spacegroup import crystal
>>> atoms = crystal('Al', [(0,0,0)], spacegroup=225, cellpar=4.05)
>>> np.round(atoms.positions, decimals=5)
... |
madmax983/h2o-3 | h2o-py/tests/testdir_misc/pyunit_headers.py | Python | apache-2.0 | 641 | 0.017161 | import sys
sys.path.insert(1,"../../")
import h2o
from tests import pyunit_utils
def headers():
headers = h2o.import_file( | pyunit_utils.locate("smalldata/airlines/allyears2k_headers_only.csv"))
headers_and = h2o.import_file(pyunit_utils.locate("smalldata/airlines/allyears2k.zip"))
headers_and.set_names(headers.names)
print headers.names
print headers_and.names
assert headers.names == headers_and.names, "Expected the sam... | e:
headers()
|
stb-tester/stb-tester | tests/test_frameobject.py | Python | lgpl-2.1 | 11,807 | 0.000508 | import threading
import stbt_core as stbt
class TruthyFrameObject(stbt.FrameObject):
"""
The simplest possible FrameObject
>>> frame = _load_frame("with-dialog")
>>> bool(TruthyFrameObject(frame))
True
>>> TruthyFrameObject(frame)
TruthyFrameObject(is_visible=True)
"""
@property
... | nother called
11
>>> m._another
11
>>> m
FalseyPrintingFrameObject(is_visible=False)
"""
@property
def is_visible(self):
print("is_visible called")
ten = self.public
seven = self._private
return bool(ten < seven)
@property
def _private(self):
... | er(self):
print("another called")
return 10
@property
def _another(self):
print("_another called")
return 11
def test_that_is_visible_and_properties_arent_racy():
# Calling a public property on a falsey FrameObject must always return
# `None`, even if another thread is... |
ppiotr/Bibedit-some-refactoring | modules/webjournal/lib/webjournal_tests.py | Python | gpl-2.0 | 2,817 | 0.006035 | # -*- coding: utf-8 -*-
##
## This file is part of CDS Invenio.
## Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008 CERN.
##
## CDS 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 versio... | = '07/2009'
self.assertEqual(issue_is_later_than(issue1, issue2), False)
issue1 = '07/2009'
issue2 = '06/2009'
self.assertEqual(issue_is_later_than(issue1, issue2), True)
issue1 = '06/2009'
issue2 = '07/2009'
self.assertEqual(issue_is_later_than(issue1, issue2),... | = '07/2009'
issue2 = '07/2009'
self.assertEqual(issue_is_later_than(issue1, issue2), False)
TEST_SUITE = make_test_suite(TestCompareIssues)
if __name__ == "__main__":
run_test_suite(TEST_SUITE)
|
bbengfort/email-analysis | mailstat/utils/__init__.py | Python | mit | 513 | 0.001949 | # mailstat.utils
# Utilities and functions for the mailstat package
#
# Author: Benjamin Bengfort <benjamin@bengfort.com>
# Created: Sun Dec 29 17:27:38 2013 -0600
#
# Copyright (C) 2013 Bengfort.com
# For license information, see LICENSE.txt
#
# ID: __init__.py [] benjamin@bengfort.com $
"""
Utilities and function... | ########################################## | |
wolendranh/movie_radio | radio/views/track_info_sse.py | Python | apache-2.0 | 2,957 | 0.001353 | import logging
from concurrent.futures import CancelledError
import asyncio
from aiohttp import web
from aioredis import create_redis
from etc.ice_fetcher import get_current_song
from config.settings import STREAM_HOST, STREAM_PORT
server_logger = logging.getLogger('aiohttp.server')
async def push_current_track(r... | mat(e))
# going into loop to get updates fro redis
try:
try:
while True:
# check the channel queue size
if channel._queue.qsize() > 0:
for msg in range(channel._queue.qsize()):
message = await channel.get()
... | # so we check it. In other case Client will kill server with
# every 3 second request for new song.
stream.write(b'event: track_update\r\n')
stream.write(b'data: ' + message + b'\r\n\r\n')
else:
stre... |
j9ac9k/NavitronEve | crons/navitron_crons/navitron_system_stats.py | Python | mit | 5,545 | 0.001262 | """navitron_system_kills.py: cronjob for snapshotting /universe/system_kills/"""
from os import path
from datetime import datetime
import warnings
import pandas as pd
import retry
import navitron_crons.exceptions as exceptions
import navitron_crons.connections as connections
import navitron_crons._version as _version... | ls(
c | onfig=self.config,
logger=self.logger
)
except Exception: # pramga: no cover
self.logger.error(
'%s: Unable to fetch system_kills',
self.PROGNAME,
exc_info=True
)
raise
self.logger.info('Mer... |
smblott-github/podrecast | setup.py | Python | mit | 1,761 | 0.022714 | #!/usr/bin/env python
import sys, os, subprocess
from distutils.core import setup
from distutils.command.install import install as Install
# ####################################################################
# Custom installer...
class Installer(Install):
env = [ 'PODRE | CAST_CGI_BIN', 'CGI_BIN' ]
cgi = [ '/usr/lib/cgi-bin', '~/public_html/cgi-bin' ]
def run(self):
| Install.run(self)
for directory in [ os.environ[env] for env in self.env if env in os.environ ] + self.cgi:
if self.cgi_install(directory):
return
print
print 'Warning:'
print ' CGI bin not found.'
print ' CGI script (./podrecast) not installed; please install it by... |
thinkopensolutions/aeroolib | aeroolib/plugins/__init__.py | Python | gpl-3.0 | 2,201 | 0.000454 | ##############################################################################
#
# Copyright (c) 2010 Alistek Ltd. (http://www.alistek.com) All Rights
# Reserved.
# General contacts <info@alistek.com>
#
# DISCLAIMER: This module is licensed under GPLv3 or newer and
# is considered incompatible with ... | , or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty | of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, ... |
goozbach/ansible | lib/ansible/executor/process/result.py | Python | gpl-3.0 | 7,123 | 0.003931 | # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# 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... | ed.
# So, per the docs, we reassign the list so the proxy picks up and
# notifies all other threads
for notify in result_item['_ansible_not | ify']:
self._send_result(('notify_handler', result, notify))
if 'add_host' in result_item:
# this task added a new host (add_host module)
self._send_result(('add_host', result_item))
... |
igg/filedrop | filedrop/filedrop.py | Python | lgpl-2.1 | 5,365 | 0.0274 | from flask import Flask, render_template, request, redirect, Response, url_for, session, abort
import time, os, json, base64, hmac, urllib, random, string, datetime
from hashlib import sha1
from ConfigParser import SafeConfigParser
from logging import Formatter
import requests
import boto3
application = Flask(__name__... | onfig from: {}".format(config_file_path))
config.read ( config_file_path )
application.secret_key = config.get('flask','secret_key')
##
## Process Flask routes
@application.route("/reCAPTCHA", methods=['GET', 'POST'])
def reCAPTCHA():
application.logger.debug("in reCAPTCHA")
if request.method == 'POST':
applicat... | , "response":request.form['g-recaptcha-response']})
if 'success' in r.json() and r.json()['success']:
session['reCAPTCHA'] = True
session['s3_numsigs'] = 0
application.logger.debug("capcha successful.")
return redirect(url_for('index'))
if 'reCAPTCHA' not in session or not session['reCAPTCHA']:
applic... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.