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 |
|---|---|---|---|---|---|---|---|---|
guibargar/stt-api | train_traffic_app/views.py | Python | mit | 1,323 | 0.005291 |
from rest_framework import generics
from rest_framework import permissions
from django.contrib.auth.models import User
from train_traffic_app.models import TrainTrafficRequest
from train_traffic_app.serializers import TrainTrafficRequestSerializer
from train_traffic_app.serializers import UserSerializer
from train_tr... | rics.RetrieveUpdateDestroyAPIView):
"""
Retrieve, update or delete a train_traffic_request.
"""
queryset = TrainTrafficRequest.objects.all()
serializer_class = TrainTrafficRequestSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly,IsOwnerOrReadOnly,)
class UserList(generics.... | erDetail(generics.RetrieveAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer |
seejay/feedIO | feedio/rilPlugin.py | Python | gpl-3.0 | 1,738 | 0.004028 | #!/usr/bin/python
"""
Read It Later (RIL) module for feedIO.
"""
__ve | rsion__ = "0.0.5"
__license__ = """
Copyright (C) 2011 Sri Lanka Institute of Information Technology.
feedIO 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
... | HOUT 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 feedIO. If not, see <http://www.gnu.org/licenses/>.
"""
__aut... |
catapult-project/catapult-csm | third_party/google-endpoints/apitools/base/py/testing/mock.py | Python | bsd-3-clause | 12,590 | 0 | #
# Copyright 2015 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... |
)).format(
key=expected_key,
expected_request=expected_ | repr,
received_request=received_repr,
diff=diff)
super(UnexpectedRequestException, self).__init__(msg)
class ExpectedRequestsException(Error):
def __init__(self, expected_calls):
msg = 'expected:\n'
for (key, request) in expected_calls:
msg ... |
knuu/competitive-programming | atcoder/corp/codethanksfes2017_f.py | Python | mit | 421 | 0 | N, | K = map(int, input().split())
A = [int(input()) for _ in range(N)]
A.sort()
dp = [[0] * int(2e5) for _ in range(2)]
dp[0][0] = 1
limit = 0
MOD = 10 ** 9 + 7
for i in range(N):
prev, now = i % 2, (i + 1) % 2
for j in range(limit + 1):
dp[now][j] = dp[prev][j]
for j in range(limit + 1):
dp[now... | 2][K])
|
miguelinux/vbox | src/VBox/Devices/EFI/Firmware/BaseTools/Source/Python/GenFds/Fv.py | Python | gpl-2.0 | 16,415 | 0.011636 | ## @file
# process FV generation
#
# Copyright (c) 2007 - 2014, 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 license may be ... | fsList :
FileName = FfsFile.GenFfs(MacroDict, FvParentAddr=BaseAddress)
FfsFileList.append(FileName)
self.FvInfFile.writelines("EFI_FILE_NAME = " + \
FileName + \
| T_CHAR_LF)
SaveFileOnChange(self.InfFileName, self.FvInfFile.getvalue(), False)
self.FvInfFile.close()
#
# Call GenFv tool
#
FvOutputFile = os.path.join(GenFdsGlobalVariable.FvDir, self.UiFvName)
FvOutputFile = FvOutputFile +... |
miguelgrinberg/flasky | config.py | Python | mit | 3,883 | 0 | import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config:
SECRET_KEY = os.environ.get('SECRET_KEY') or 'hard to guess string'
MAIL_SERVER = os.environ.get('MAIL_SERVER', 'smtp.googlemail.com')
MAIL_PORT = int(os.environ.get('MAIL_PORT', '587'))
MAIL_USE_TLS = os.environ.get('MAIL_US... | r(file_handler)
class UnixConfig(ProductionConfig):
@classmethod
def init_app(cls, app):
ProductionConfig.init_app(app)
# log to syslog
import logging
from logging.handlers import SysLogHandler
syslog_handler = SysLogHandler()
syslog_handler.setLevel(logging.IN... | nfig,
'docker': DockerConfig,
'unix': UnixConfig,
'default': DevelopmentConfig
}
|
mackst/glm | glm/detail/func_geometric.py | Python | mit | 3,822 | 0.00314 | # -*- coding: utf-8 -*-
# The MIT License (MIT)
#
# Copyright (c) 2014-2018 Shi Chi(Mack Stone)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limit... | urn -1.0 if x < 0.0 else 1.0
#elif isinstance(x, Vec2):
| #sqr = x.x * x.x + x.y * x.y
#return x * inversesqrt(sqr)
elif isinstance(x, Vec3):
sqr = x.x * x.x + x.y * x.y + x.z * x.z
return x * inversesqrt(sqr)
elif isinstance(x, Vec4):
sqr = x.x * x.x + x.y * x.y + x.z * x.z + x.w * x.w
return x * inversesqrt(sqr)
|
TimDettmers/spodernet | examples/snli_verbose.py | Python | mit | 10,703 | 0.004298 | '''This models is an example for training a classifier on SNLI'''
from __future__ import print_function
from os.path import join
import nltk
import numpy as np
import os
import urllib
import zipfile
import sys
from spodernet.hooks import AccuracyHook, LossHook, ETAHook
from spodernet.preprocessing.pipeline import Pip... | if data['gold_label'] == '-':
continue
premise = data['sentence1']
hypothe | sis = data['sentence2']
target = data['gold_label']
datafile.write(
json.dumps([premise, hypothesis, target]) + '\n')
return [names, [join(snli_dir, new_name) for new_name in new_files]]
def preprocess_SNLI(delete_data=False):
# load data
#na... |
Shakajiub/RoboJiub | src/irc.py | Python | gpl-3.0 | 6,161 | 0.004545 | import re
import sys
import socket
from src.config import *
class IRC:
def __init__(self, queue):
self.queue = queue
def end_connection(self):
"""Send a goodbye message through irc and close the socket."""
try:
self.send_custom_message('goodbye')
channel = get_... | dd relevant data to custom bot messages."""
if message == "cheer" and len(data) == 2:
text = text. | format(user=data[0], bits=data[1])
elif message == "sub" and len(data) == 5:
text = text.format(user=data[0], streak=data[1], tier=data[2], plan=data[3], count=data[4])
elif message == "raid" and len(data) == 2:
text = text.format(user=data[0], raiders=data[1])
return tex... |
alexlo03/ansible | lib/ansible/plugins/action/voss_config.py | Python | gpl-3.0 | 4,227 | 0.00071 | #
# (c) 2018 Extreme Networks Inc.
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ans... | result = super(ActionModule, self).run(tmp, task_vars)
del tmp # tmp no longer has any effect
if self._task.args.get('backup') and result.get('__backup__'):
# User requested backup and no error occurred in module | .
# NOTE: If there is a parameter error, _backup key may not be in results.
filepath = self._write_backup(task_vars['inventory_hostname'],
result['__backup__'])
result['backup_path'] = filepath
# strip out any keys that have two lea... |
monitoringartist/zenoss-searcher | scripts/gen-source-wiki.py | Python | gpl-2.0 | 649 | 0.006163 | #!/usr/bin/env python
from pyquery import PyQuery as pq
from lxml import etree
import | urllib, json, ziconizing, collections
arr = {}
d = pq(url='http://wiki.zenoss.org/All_ZenPacks')
for a in d('.smw-column li a'):
name = a.text.strip() + ' ZenPack'
if name.startswith('ZenPack.'):
continue
url = 'http://wiki.zenoss.org' + a.get('href')
arr[name.replace(' ','-')] = {
'name... | , name.lower().split(' '))
}
oarr = collections.OrderedDict(sorted(arr.items()))
print json.dumps(oarr)
|
vi4m/django-dedal | dedal/__init__.py | Python | bsd-3-clause | 71 | 0 | _ | _version__ = '0.1.0'
from dedal.site import site
__all__ = ['site' | ]
|
pombreda/httpplus | httpplus/tests/test_bogus_responses.py | Python | bsd-3-clause | 2,832 | 0.000353 | # Copyright 2010, 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 f... | T
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# pylint: disable=protected-access,missing-docstring,too-few-public-methods,invalid-name,too-many-public-methods
"""Tests against malformed responses.
Server implementation... | of CRLF have
been observed. Checking against ones that use only CR is a hedge
against that potential insanit.y
"""
import unittest
import httpplus
# relative import to ease embedding the library
import util
class SimpleHttpTest(util.HttpTestBase, unittest.TestCase):
def bogusEOL(self, eol):
con = httpp... |
apache/incubator-airflow | airflow/api_connexion/schemas/provider_schema.py | Python | apache-2.0 | 1,452 | 0 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | 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.
... |
glue-viz/echo | echo/qt/tests/test_connect_combo_selection.py | Python | mit | 3,424 | 0.000584 | import pytest
import numpy as np
from qtpy import QtWidgets
from echo.core import CallbackProperty
from echo.selection import SelectionCallbackProperty, ChoiceSeparator
from echo.qt.connect import connect_combo_selection
class Example(object):
a = SelectionCallbackProperty(default_index=1)
b = CallbackPrope... | ssert combo.currentIndex() == 0
with pytest.raises(ValueError) as exc:
t.a = 2
assert exc.value.args[0] == 'value 2 is not in valid choices: [4, 3.5]'
t.a = None
assert combo.currentInde | x() == -1
# Changing choices should change Qt combo box. Let's first try with a case
# in which there is a matching data value in the new combo box
t.a = 3.5
assert combo.currentIndex() == 1
a_prop.set_choices(t, (4, 5, 3.5))
assert combo.count() == 3
assert t.a == 3.5
assert combo.c... |
eschleicher/flask_shopping_list | venv/lib/python3.4/site-packages/argh/compat.py | Python | mit | 2,834 | 0.000706 | # originally inspired by "six" by Benjamin Peterson
import inspect
import sys
if sys.version_info < (3,0):
text_type = unicode
binary_type = str
import StringIO
StringIO = BytesIO = StringIO.StringIO
else:
text_type = str
binary_type = bytes
import io
StringIO = io.StringIO
Byte... | en calling `argh.dispatch_command(cythonCompiledFunc)`. However,
the CyFunctions do have | perfectly usable `.func_code` and
`.func_defaults` which is all `inspect.getargspec` needs.
This function just copies `inspect.getargspec()` from the standard
library but relaxes the test to a more duck-typing one of having
both `.func_code` and `.func_defaults` attributes.
"""
... |
fsalamero/pilas | pilasengine/ejemplos/ejemplos_a_revisar/deslizador.py | Python | lgpl-3.0 | 842 | 0.003563 | import pilasengine
# Permite que este ejemplo funcion incluso si no has instalado pilas.
import sys
sys.path.insert(0, "..")
pila | s = pilasengine.iniciar()
mono = pilas.actores.Mono(y=-100)
def cuando_cambia_escala(valor):
mono.escala = valor * 2
deslizador_escala = pilas.interfaz.Deslizador(y=50 | )
deslizador_escala.conectar(cuando_cambia_escala)
def cuando_cambia_rotacion(valor):
mono.rotacion = valor * 360
deslizador_rotacion = pilas.interfaz.Deslizador(y=100)
deslizador_rotacion.conectar(cuando_cambia_rotacion)
def cuando_cambia_posicion(valor):
# Obtiene valores entre -200 y 400
mono.x = -2... |
e-koch/FilFinder | fil_finder/tests/setup_package.py | Python | mit | 202 | 0 | def get_package_data():
return {
_ASTROPY_PACKAGE_NAME_ + '.tests': | ['data/*.fits',
| 'data/*.hdf5',
]}
|
brysonreece/Stream | resources/site-packages/stream/socks.py | Python | gpl-3.0 | 27,176 | 0.003422 | """
SocksiPy - Python SOCKS module.
Version 1.5.0
Copyright 2006 Dan-Haim. 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
... | None, timeout=None):
"""create_connection(dest_pair, *[, timeout], **proxy_args) -> socket object
Like socket.create_connection(), but connects to proxy
before returning the socket object.
dest_pair - 2-tuple of (IP/hostname, port).
**proxy_a | rgs - Same args passed to socksocket.set_proxy().
timeout - Optional socket timeout value, in seconds.
"""
sock = socksocket()
if isinstance(timeout, (int, float)):
sock.settimeout(timeout)
sock.set_proxy(proxy_type, proxy_addr, proxy_port,
proxy_username, proxy_password)
... |
1flow/1flow | oneflow/core/admin/processor.py | Python | agpl-3.0 | 5,116 | 0 | # -*- coding: utf-8 -*-
u"""
Copyright 2015 Olivier Cortès <[email protected]>.
This file is part of the 1flow project.
1flow is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of
the License, or ... | ),
'accept_code': CodeMirrorTextarea(
mode='python',
addon_js=settings.CODEMIRROR_ADDONS_JS,
addon_css=settings.CODEMIRROR_ADDONS_CSS,
keymap=settings.CODEMIRROR_KEYMAP,
| ),
'process_code': CodeMirrorTextarea(
mode='python',
addon_js=settings.CODEMIRROR_ADDONS_JS,
addon_css=settings.CODEMIRROR_ADDONS_CSS,
keymap=settings.CODEMIRROR_KEYMAP,
),
}
class ProcessorAdmin(admin.ModelAdmin):
... |
cpcloud/numba | numba/experimental/jitclass/base.py | Python | bsd-2-clause | 20,859 | 0.000192 | import inspect
import operator
import types as pytypes
import typing as pt
from collections import O | rderedDi | ct
from collections.abc import Sequence
from llvmlite import ir as llvmir
from numba import njit
from numba.core import cgutils, errors, imputils, types, utils
from numba.core.datamodel import default_manager, models
from numba.core.registry import cpu_target
from numba.core.typing import templates
from numba.core.typ... |
M4rtinK/pyside-android | tests/QtGui/qmenuadd_test.py | Python | lgpl-2.1 | 518 | 0.003861 | # -*- coding: utf-8 -*-
''' Test the QMenu.addAction() method'''
import unittest
import sys
from PySide import QtGui
from helper import UsesQApplication
class QMenuAddAction(UsesQApplication):
def openFile(self, *args):
self.arg = args
def testQMenuAddAction(self):
fileMen | u = QtGui.QMenu("&File")
addNewAction = fileMenu.addAction("&Open...", self.openFile)
addNewAction.trigger()
self.assertEqual | s(self.arg, ())
if __name__ == '__main__':
unittest.main()
|
PnCevennes/projet_suivi | docs/conf.py | Python | gpl-3.0 | 8,065 | 0.006324 | # -*- coding: utf-8 -*-
#
# test documentation build configuration file, created by
# sphinx-quickstart on Wed Sep 2 11:29:03 2015.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All ... | ngs as "system message" paragraphs in the built documents.
#keep_warnings = False
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'default'
# Theme options are theme-speci... | available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter t... |
longnow/panlex-tools | libpython/ben/icu_tools.py | Python | mit | 2,046 | 0.00782 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import icu
def all_glyphs(prop):
return [c.encode('utf-16', 'surrogatepass').decode('utf-16') for c in icu.UnicodeSetIterator(icu.UnicodeSet(r'[:{}:]'.format(prop)))]
def all_cps(prop):
return list(map(glyph_cp, all_glyphs(prop)))
def glyph_name(glyph, default=... | TypeError('glyph must be a string with length of 1')
elif len(glyph) == 0:
return default
else:
return icu.Char.charName(glyph)
def cp_glyph(cp, default=''):
try:
return chr(int(cp, 16))
except ValueError:
return default
def cp_name(cp, de | fault=''):
return glyph_name(cp_glyph(cp), default)
def glyph_cp(glyph):
return hex(ord(glyph))[2:]
class Rbnf:
def __init__(self, tag="spellout", locale="", rules=""):
if rules:
self._rbnf = icu.RuleBasedNumberFormat(rules)
else:
if tag.lower() not in {"spellout", ... |
asgeir/old-school-projects | python/verkefni2/cpattern.py | Python | mit | 1,006 | 0.000994 | # https://graphics.stanford.edu/~seander/bithacks.html#NextBitPermutation
def selector(values, setBits):
maxBits = len(values)
def select(v):
out = []
for i in range(maxBits):
if (v & (1 << i)):
out.append(values[i])
return out
v = (2 ** setBits) - 1
... | turn [ref.index(x) for x in perm]
def contains_pattern(perm, patt):
if len(patt) > len(perm):
return False
for p in selector(perm, len(patt)):
if normalize(p) == patt:
return True
return Fa | lse
if __name__ == '__main__':
print(contains_pattern(
[14, 12, 6, 10, 0, 9, 1, 11, 13, 16, 17, 3, 7, 5, 15, 2, 4, 8],
[3, 0, 1, 2]))
print(True)
|
xxd3vin/spp-sdk | opt/Python27/Lib/site-packages/numpy/distutils/__config__.py | Python | mit | 912 | 0.025219 | # This file is generated by Z:\Users\rgommers\Code\numpy\setup.py
# It contains system_info results at the time of building this package.
__all__ = ["get_info","show"]
blas_info={}
lapack_info={}
atlas_threads_info={}
blas_src_info={}
blas_opt_info={}
lapack_src_info={}
atlas_b | las_threads_info={}
lapack_opt_info={}
atlas_info={}
lapack_mkl_info={}
blas_mkl_info={}
atlas_blas_info={}
mkl_info={}
def get_info(name):
g = globals()
return g.get(name, g.get(name + "_info", {}))
def show():
for name,info_dict in globals().items():
if name[0] == "_" or type(info_dict) is not t... | int(name + ":")
if not info_dict:
print(" NOT AVAILABLE")
for k,v in info_dict.items():
v = str(v)
if k == "sources" and len(v) > 200:
v = v[:60] + " ...\n... " + v[-60:]
print(" %s = %s" % (k,v))
|
JavaRabbit/CS496_capstone | bigquery/rest/labels_test.py | Python | apache-2.0 | 1,254 | 0 | # Copyright 2016, Google, Inc.
# Licensed under the Apache License, Versi | on 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" BASI... | ense for the specific language governing permissions and
# limitations under the License.
import os
from labels import label_dataset, label_table
PROJECT = os.environ['GCLOUD_PROJECT']
def test_label_dataset(capsys):
label_dataset(
'test_dataset',
'environment',
'test',
project_... |
nanuxbe/microbit-files | button_motor_control.py | Python | mit | 571 | 0 | from microbit import *
while True:
if button_a.is_pressed():
pin1.write_digital(1)
pin2.write_d | igital(1)
pin0.write_digital(0)
pin8.write_digital(0)
display.show(Image.ARROW_N)
elif button_b.is_pressed():
pin0.write_digital(1)
pin8.write_digital(1)
pin1.write_digital(0)
pin2.write_digital(0)
display.show(Image.ARROW_S)
else:
pin | 0.write_digital(0)
pin8.write_digital(0)
pin1.write_digital(0)
pin2.write_digital(0)
display.show(Image.NO)
|
PureStorage-OpenConnect/purestorage-flocker-driver | tests/utils/__init__.py | Python | apache-2.0 | 66 | 0.015152 | # Copyright 2016 Pure Storage Inc.
# Se | e LIC | ENSE file for details. |
ali-salman/Aspose.Slides-for-Java | Plugins/Aspose-Slides-Java-for-Jython/asposeslides/WorkingWithSlidesInPresentation/Thumbnail.py | Python | mit | 4,221 | 0.005923 | from asposeslides import Settings
from com.aspose.slides import Presentation
from com.aspose.slides import SaveFormat
from javax import ImageIO
from java.io import File
class Thumbnail:
def __init__(self):
# Generating a Thumbnail from a Slide
self.create_thumbnail()
... | # Getting the image of desired window inside generated slide thumnbnail
# BufferedImage window = image.getSubimage(windowX, windowY, windowsWidth, windowHe | ight)
window_image = image.getSubimage(100, 100, 200, 200)
# Save the image to disk in JPEG format
imageIO = ImageIO()
imageIO.write(image, "jpeg", File(dataDir + "ContentBG_tnail.jpg"))
print "Created thumbnail of user defined window, please check the output file." . PH... |
iwm911/plaso | plaso/parsers/winreg_plugins/mountpoints_test.py | Python | apache-2.0 | 2,420 | 0.001653 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2014 The Plaso Project Authors.
# Please see the AUTHORS file for details on individual authors.
#
# 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 L... | gin."""
imp | ort unittest
# pylint: disable=unused-import
from plaso.formatters import winreg as winreg_formatter
from plaso.lib import timelib_test
from plaso.parsers import winreg
from plaso.parsers.winreg_plugins import mountpoints
from plaso.parsers.winreg_plugins import test_lib
class MountPoints2PluginTest(test_lib.Registr... |
deeplearning4j/deeplearning4j | libnd4j/include/graph/generated/nd4j/graph/UIAddName.py | Python | apache-2.0 | 1,253 | 0.00399 | # automatically generated by the FlatBuffers compiler, do not modify
# namespace: graph
import flatbuffers
class UIAddName(object):
__slots__ = ['_tab']
@classmethod
def GetRootAsUIAddName(cls, buf, offset):
n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset)
x = UIAddNam... | , pos)
# UIAddName
def NameIdx(self):
o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4))
if o != 0:
return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos)
return 0
# UIAddName
def Name(self):
o = flatbuffers.number_... | None
def UIAddNameStart(builder): builder.StartObject(2)
def UIAddNameAddNameIdx(builder, nameIdx): builder.PrependInt32Slot(0, nameIdx, 0)
def UIAddNameAddName(builder, name): builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(name), 0)
def UIAddNameEnd(builder): return builder.EndO... |
darren-wang/ks3 | keystone/resource/routers.py | Python | apache-2.0 | 1,239 | 0 | # Copyright 2013 Metacloud, Inc.
# Copyright 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 ... | re
# 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.
"""WSGI Routers for the Resource service."""
from keystone.common imp... | (self, mapper, routers):
routers.append(
router.Router(controllers.Domain(),
'domains', 'domain',
resource_descriptions=self.v3_resources))
routers.append(
router.Router(controllers.Project(),
'project... |
jtyr/ansible-modules-core | cloud/openstack/os_object.py | Python | gpl-3.0 | 4,163 | 0.001681 | #!/usr/bin/python
# Copyright (c) 2015 Hewlett-Packard Development Company, L.P.
# Copyright (c) 2013, Benno Joy <[email protected]>
#
# This module 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 vers... | )
changed = process_object(cloud, **module | .params)
module.exit_json(changed=changed)
except shade.OpenStackCloudException as e:
module.fail_json(msg=str(e))
# this is magic, see lib/ansible/module_common.py
from ansible.module_utils.basic import *
from ansible.module_utils.openstack import *
if __name__ == "__main__":
main()
|
jitka/weblate | weblate/trans/checks/data.py | Python | gpl-3.0 | 14,817 | 0 | # -*- coding: utf-8 -*-
#
# Copyright © 2012 - 2016 Michal Čihař <[email protected]>
#
# This file is part of Weblate <https://weblate.org/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, eith... | 'author',
'auto',
'autostart',
'authentication',
'avatar',
'backend',
'backspace',
'backup',
'badge',
'balance',
'baltic',
'bank',
'bar',
'baseball',
'battery',
'beg | in',
'bios',
'bit',
'bitcoin',
'bitcoins',
'bitmap',
'bitmaps',
'bitrate',
'block',
'blog',
'bluetooth',
'bool',
'boolean',
'boot',
'bootloader',
'branch',
'broadcast',
'browser',
'buffer',
'byte',
'bytes',
'bzip',
'bzip2',
'cab... |
purushothamc/myibitsolutions | stacks_queus/sliding_window_maximum.py | Python | gpl-3.0 | 670 | 0.002985 | def slidingMaximum(A, B):
from collections import deque
window = deque()
result | = list()
if not A or B <= 1:
return A
for i in xrange(B):
while window and A[window[-1]] <= A[i]:
window.pop()
window.append(i)
for j in xrange(i+1, len(A)):
print window, j
result.append(A[window[0]])
while window and window[0] <= (j - B):
... | <= A[j]:
window.pop()
window.append(j)
result.append(window[0])
return result
A = [1, 3, -1, -3, 5, 3, 6, 7]
A = [10, 9, 8, 7, 6, 5, 4]
B = 2
print slidingMaximum(A, B) |
dnguyen0304/clare | clare/clare/application/room_list_watcher/factories.py | Python | mit | 6,716 | 0.000596 | # -*- coding: utf-8 -*-
import collections
import logging
import sys
import selenium.webdriver
from selenium.webdriver.support.ui import WebDriverWait
from . import exceptions
from . import filters
from . import flush_strategies
from . import producers
from . import record_factories
from . import scrapers
from . imp... | ogging(sender=self._sender, logger=logger)
dependencies['sender'] = sender
# Construct the filters.
dependen | cies['filters'] = list()
# Construct the no duplicate filter.
countdown_timer = utilities.timers.CountdownTimer(
duration=self._properties['filter']['flush_strategy']['duration'])
after_duration = flush_strategies.AfterDuration(
countdown_timer=countdown_timer)
n... |
dennereed/paleoanthro | dissertations/tests.py | Python | gpl-3.0 | 632 | 0.001582 | from django.test import TestCase
from models import Dissertation
class DisertationModelTests(TestCase):
def test_dissertation_instance_creation(self):
dissertation_starting_count = Dissertation.objects.count()
# Test object creation with required fields only
Dissertation.objects.create(
| author_last_name="Test",
author_given_names="Ima",
contact_email="[email protected]",
titl | e="I Founda Cool Fossil And Said Somthing About It",
year=2014,
)
self.assertEqual(Dissertation.objects.count(), dissertation_starting_count+1)
|
gngrwzrd/gity | python/__old/tags.py | Python | gpl-3.0 | 1,125 | 0.026667 | # Copyright Aaron Smith 2009
#
# This file is part of Gity.
#
# Gity 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 Fo | undation, eith | er version 3 of the License, or
# (at your option) any later version.
#
# Gity 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 shou... |
mdrobisch/roseguarden | server/app/serializers.py | Python | gpl-3.0 | 5,422 | 0.011435 | __author__ = 'drobisch'
from models import User, Action
from marshmallow import Schema, fields, post_load, post_dump
import datetime
class UserListForSupervisorsSerializer(Schema):
class Meta:
fields = ("id", "email", "firstName", "lastName", "phone", "role", "licenseMask", "keyMask", "lastBudgetUpdateDa... | ss UserSyncSerializer(Schema):
class Meta:
fields = ("id", "email", "firstName", "lastName", "phone", "role", "licenseMask", "keyMask", "lastAccessDateTime",
"association", "registerDateTime", "lastLoginDateTime", "lastSyncDateTime", "lastAccessDaysUpdateDate",
"accessDat... | yclicBudget",
"accessTimeStart", "accessTimeEnd", "accessType", "accessDaysMask", "accessDayCounter",
"budget", "cardID", "password", "syncMaster", "active", "cardAuthBlock", "cardAuthSector",
"cardID", "cardSecret", "cardAuthKeyA", "cardAuthKeyB")
@post_load
... |
gimli-org/gimli | doc/examples/3_dc_and_ip/plot_04_ert_2_5d_potential.py | Python | apache-2.0 | 7,952 | 0.004276 | #!/usr/bin/env python
# encoding: utf-8
r"""
Geoelectrics in 2.5D
--------------------
This example shows geoelectrical (DC resistivity) forward modelling in 2.5 D, i.e.
a 2D conductivity distribution and 3D point sources, to illustrate the modeling level.
For ready-made ERT forward simulations in practice, please re... | a={'sourcePos': sourcePosB, 'k': k, 's':sigma},
verbose=True)
# The solution is shown by calling |
ax = pg.show(mesh, data=u, cMap="RdBu_r", cMin=-1, cMax=1,
orientation='horizontal', label='Potential $u$',
nCols=16, nLevs=9, showMesh=True)[0]
# Additionally to the image of the potential we want to see the current flow.
# The current flows along the gradient of our solution and can be pl... |
sassoftware/mint | mint/django_rest/rbuilder/platforms/image_type_descriptors/rawFsImage.py | Python | apache-2.0 | 3,614 | 0.000277 | #
# Copyright (c) SAS Institute 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 w... | d>
<name>options.autoResolve</name>
<descriptions>
<desc>Autoinstall Dependencies</desc>
</descriptions>
<help href="@Help_resolve_dependencies@"/>
<type>bool</type>
<default>false</default>
<required>false</required>
... | scriptions>
<desc>Generate in OVF 1.0?</desc>
</descriptions>
<help href="@Help_build_ovf_1_0@"/>
<type>bool</type>
<default>false</default>
<required>false</required>
</field>
</dataFields>
</descriptor>"""
|
imuntil/Python | L/game/game_stats.py | Python | mit | 311 | 0 | class GameStats():
def __init__(self, ai_settings):
| self.ai_settings = ai_settings
self.game_active = False
self.high_score = 0
self.reset_stats()
def reset_stats(self):
self.ships_left = self.ai_settings.ship_limit
self.score = 0
| self.level = 1
|
wonderpush/wonderpush-ios-sdk | official-translations.py | Python | apache-2.0 | 5,820 | 0.005326 | #!/usr/bin/python
# vim: set ts=4 sts=4 sw=4 et:
import sys
import subprocess
import re
try:
import biplist
except ImportError:
print 'Please install the `biplist` module:'
print ' sudo easy_install biplist'
sys.exit(1)
try:
import argparse
except:
print 'Cannot find library "argparse"!'
... | tripFilenameIfNeeded(fn)
fnPrinted = True
print '\t%s =\t%s' % (k, v)
def parseArgs(argv = None, **kwargs):
parser = argparse.ArgumentParser(
formatter_class=argpars | e.RawDescriptionHelpFormatter,
conflict_handler='resolve',
description='iOS translations extractor utility',
epilog='''\
Finds and extracts translations for the iOS SDK.''')
parser.add_argument('command', type=str, choices=['values', 'keys', 'key', 'languages', 'translations'], h... |
StardustGogeta/Physics-2.0 | Physics 2.0.py | Python | mit | 7,824 | 0.008819 | from functools import reduce
from operator import add
from pygame.math import Vector2 as V2
import pygame as pg, os
from src.display.tkinter_windows import create_menu
from src.core import constants
def init_display():
pg.init()
info = pg.display.Info()
dims = (int(info.current_w * 0.6), int(info.current_... | len(bodies)-1, b, -1):
if collision and bodies[o].test_collision(body):
if not COR: # Only remove second body if collision is perfectly inela | stic
bodies[o].merge(bodies[b], settings_window.properties_windows)
bodies.pop(b)
break
bodies[o].collide(bodies[b], COR)
if gravity:
force = body.force_of(bodies[o], G) # This is a misnomer; `force` is actually acce... |
NiloFreitas/Deep-Reinforcement-Learning | reinforcement/players/player_reinforce_rnn_2.py | Python | mit | 4,361 | 0.036918 | from players.player import player
from auxiliar.aux_plot import *
import random
from collections import deque
import sys
sys.path.append('..')
import tensorblock as tb
import numpy as np
import tensorflow as tf
# PLAYER REINFORCE RNN
class player_reinforce_rnn_2(player):
# __INIT__
def __init__(self):
... | self.brain.addSummaryScalar( input = 'Cost' )
self.brain.addSummaryHistogram( input = 'Target' )
self.brain.addWriter( name = 'Writer' , dir = './' )
self.brain.addSummary( name = 'Summary' )
self. | brain.initialize()
# TRAIN NETWORK
def train(self, prev_state, curr_state, actn, rewd, done, episode):
# Store New Experience Until Done
self.experiences.append((prev_state, curr_state, actn, rewd, done))
batchsize = len( self.experiences ) - self.NUM_FRAMES + 1
# Check for ... |
CRImier/pybatchinstall | lists/make_json.py | Python | mit | 1,028 | 0.013619 | import json
import sys
import os
import shlex
import | subprocess
def execute(*args):
try:
output = subprocess.check_output(args, stderr=subprocess.STDOUT, shell=True)
result = [0, output]
except subprocess.CalledProcessError as e:
result = [int(e.returncode), e.output]
return result
def transform(filename):
output = filename+".jso... | line().strip("\n")
#pre_install = shlex.split(f.readline().strip("\n"))
#post_install = shlex.split(f.readline().strip("\n"))
json_dict = {"name":name, "description":description, "packages":[package for package in packages.split(" ") if package], "pre-install":[], "post-install":[]}
json.dump(json_dict,... |
nandhp/youtube-dl | youtube_dl/extractor/vimeo.py | Python | unlicense | 33,081 | 0.002542 | # encoding: utf-8
from __future__ import unicode_literals
import json
import re
import itertools
from .common import InfoExtractor
from ..compat import (
compat_HTTPError,
compat_urlparse,
)
from ..utils import (
determine_ext,
ExtractorError,
InAdvancePagedList,
int_or_none,
RegexNotFound... | 'uploader_id': 'user7108434',
'uploader': 'Filippo Valsorda',
'duration': 10,
| },
},
{
'url': 'http://vimeopro.com/openstreetmapus/state-of-the-map-us-2013/video/68093876',
'md5': '3b5ca6aa22b60dfeeadf50b72e44ed82',
'note': 'Vimeo Pro video (#1197)',
'info_dict': {
'id': '68093876',
'ext': 'mp4'... |
foursquare/commons-old | src/python/twitter/pants/tasks/filedeps.py | Python | apache-2.0 | 1,488 | 0.00336 | # ==================================================================================================
# Copyright 2012 Twitter, Inc.
# ------------------------- | -------------------------------------------------------------------------
# Licensed under the Apache License, Version 2.0 (the "Licen | se");
# you may not use this work except in compliance with the License.
# You may obtain a copy of the License in the LICENSE file, or 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"... |
valexandersaulys/airbnb_kaggle_contest | venv/lib/python3.4/site-packages/sklearn/cluster/dbscan_.py | Python | gpl-2.0 | 12,482 | 0 | # -*- coding: utf-8 -*-
"""
DBSCAN: Density-Based Spatial Clustering of Applications with Noise
"""
# Author: Robert Layton <[email protected]>
# Joel Nothman <[email protected]>
# Lars Buitinck
#
# License: BSD 3 clause
import warnings
import numpy as np
from scipy import sparse
from ..ba... | p : float, optional
The power of the Minkowski metric to be used to calculate distance
between points.
sample_weight : array, shape (n_samples,), optional
Weigh | t of each sample, such that a sample with a weight of at least
``min_samples`` is by itself a core sample; a sample with negative
weight may inhibit its eps-neighbor from being core.
Note that weights are absolute, and default to 1.
random_state: numpy.RandomState, optional
Deprecat... |
Ohjel/wood-process | jump/animation.py | Python | mit | 750 | 0.004 | import pygame
class Animation:
def __init__(self, sheet, seq):
#Attributes
self.sheet = sheet
self.length = seq[0]
self.delay = seq[1]
self.x = seq[2]
self.y = seq[3]
sel | f.w = seq[4]
self.h = seq[5]
self.step = 0
self.tick = 0
self.curX = self.x
def draw(self, screen, dest):
screen.blit(self.sheet | , dest, pygame.Rect(self.curX, self.y, self.w, self.h))
if self.tick == self.delay:
self.tick = 0
self.step += 1
if self.step < self.length:
self.curX += self.w
else:
self.step = 0
self.curX = self.x
else:
... |
Featuretools/featuretools | featuretools/feature_base/features_deserializer.py | Python | bsd-3-clause | 5,124 | 0.001561 | import json
import boto3
from featuretools.entityset.deserialize import \
description_to_entityset as deserialize_es
from | featuretools.feature_base.feature_base import (
AggregationFeature,
DirectFeature,
Feature,
FeatureBase,
FeatureOutputSlice,
GroupByTransformFeature,
IdentityFeature,
TransformFeature
)
from featuretools.primitives.utils import PrimitivesDeserializer
from featuretools.utils.gen_utils imp... |
"""Loads the features from a filepath, S3 path, URL, an open file, or a JSON formatted string.
Args:
features (str or :class:`.FileObject`): The location of where features has
been saved which this must include the name of the file, or a JSON formatted
string, or a readable file handle... |
condereis/realtime-stock | docs/conf.py | Python | mit | 8,475 | 0.00531 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# rtstock documentation build configuration file, created by
# sphinx-quickstart on Tue Jul 9 22:26:36 2013.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# aut... | how page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Document | s to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output ------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual secti... |
QudevETH/PycQED_py3 | pycqed/measurement/detector_functions.py | Python | mit | 79,958 | 0.000638 | """
Module containing a collection of detector functions used by the
Measurement Control.
"""
import traceback
import numpy as np
from copy import deepcopy
import time
from string import ascii_uppercase
from pycqed.analysis import analysis_toolbox as a_tools
from pycqed.utilities.timer import Timer
from qcodes.instrume... | = 'Multi_detector'
self.value_names = []
self.value_units = []
for i, detector in enumerate(detectors):
for detector_value_name in detector.value_names:
if det_idx_suffix:
detector_value_name += '_det{}'.format(i)
self.value_names.a... | lf.value_units.append(detector_value_unit)
self.detector_control = self.detectors[0].detector_control
for d in self.detectors:
if d.detector_control != self.detector_control:
raise ValueError('All detectors should be of the same type')
def prepare(self, **kw):
f... |
benosment/daily-exercises | hr-exception.py | Python | gpl-2.0 | 104 | 0 | #!/bin/python3
S = input().stri | p()
try:
print(int(S))
except ValueError:
print("Bad Strin | g")
|
yahoo/bossmashup | templates/__init__.py | Python | bsd-3-clause | 278 | 0.014388 | #Copyright (c) 2011 Yahoo | ! Inc. All rights reserved. Licensed under t | he BSD License.
# See accompanying LICENSE file or http://www.opensource.org/licenses/BSD-3-Clause for the specific language governing permissions and limitations under the License.
__all__ = ["publisher"]
|
cripplet/practice | codeforces/489/attempt/a_sort.py | Python | mit | 1,271 | 0.050354 | import fileinput
def str_to_int(s):
return([ int(x) for x in s.split() ])
# args = [ 'line 1', 'line 2', ... ]
def proc_input(args):
return str_to_int(args[1] | )
def find(ints, offset):
min = float('inf')
min_index = -1
for k, v in enumerate(ints[offset:]):
if v < min:
min = v
min_index = k + offset
return(min_index)
def swap(l, a, b):
t = l[a]
l[a] = l[b]
l[b] = t
def solve(args, verbose=False, debug=False):
ints = proc_input(args)
if debug:
from copy i... | e(len(ints)):
min_index = find(ints, i)
if min_index != i:
results.append((min_index, i))
swap(ints, min_index, i)
if debug:
d.sort()
assert(ints == d)
assert(len(results) <= len(ints))
if verbose:
print len(results)
for (src, tgt) in results:
print src, tgt
return (len(results), results)
def... |
WritingTechForJarrod/app | src/wtfj/connectors_local.py | Python | gpl-3.0 | 2,202 | 0.052225 | import time
from threading import Thread
import threading
from wtfj_ids import *
from wtfj_utils import *
class Printer:
''' Opens a new output window and prints messages sent to it '''
def __init__(self,header=''):
self._header = header
def send(self,string):
print(self._header+string)
class Console:
''' Al... | x += 1
return [msg]
except IndexError:
return []
def subscribe(self,*uids):
for uid in uids:
if uid is not None:
if uid[0] is '@': assert uid[1:] in get_attr(Uid)
else: assert uid in get_attr(Uid)
return self
def load(self,msg_array):
self._msgs += msg_array
return self
def set_period(s... | (self.poll()) > 0: pass
def run_async(self):
Thread(target=self.run).start()
if __name__ == '__main__':
Printer('A simple printer: ').send('Just printing a msg to current_thread')
script = [
'@other_uid topic data',
'@other_uid topic',
'uid topic data',
'uid topic'
]
async = ['async topic '+str(n)... |
jgrizou/robot_omniwheel | catkin_ws/src/roslego/scripts/publisher.py | Python | gpl-3.0 | 541 | 0.001848 | import ros | py
import time
from collections import deque
class Publisher(object):
def __init__(self):
self.publishers = {}
self.queue = deque()
def add_publi | sher(self, alias, publisher):
self.publishers[alias] = publisher
def publish(self):
while len(self.queue) > 0:
alias, msg = self.queue.popleft()
print "publishing " + alias + ":" + str(msg)
self.publishers[alias].publish(msg)
def append(self, alias, msg):
... |
dkopecek/amplify | third-party/quex-0.65.2/quex/engine/analyzer/mega_state/template/gain_entry.py | Python | gpl-2.0 | 865 | 0.001156 |
def do(A, B):
"""Computes 'gain' with respect to entry actions, if two states are
combined.
"""
# Every different command list requires a separate door.
# => Entry cost is proportional to number of unique command lists.
# => Gain = number of unique command lists of A an B each
# ... | ue_cl_set = set(ta.command_list for ta in A.action_db.itervalues())
B_unique_cl_set = set(ta.command_list for ta in B.action_db.itervalues())
# (1) Compute sizes BEFORE setting Combined_cl_set = A_unique_cl_set
A_size = len(A_unique_cl_set)
B_size = len(B_unique_cl_set)
# (2) Compute combined cost
... | t = A_unique_cl_set # reuse 'A_unique_cl_set'
Combined_cl_set.update(B_unique_cl_set)
return A_size + B_size - len(Combined_cl_set)
|
threemeninaboat3247/raipy | raipy/Example.py | Python | mit | 3,116 | 0.022844 | # -*- coding: utf-8 -*-
"""
Created on Sat May 13 21:48:22 2017
@author: Yuki
"""
from PyQt5.QtWidgets import QVBoxLayout,QWidget,QHBoxLayout,QTabWidget,QStatusBar,QTextEdit,QApplication,QPushButton,QMenu,QAction
fro | m PyQt5.QtCore import pyqtSignal
EXAMPLE='Examples' #the folder exists in the same folder with __init__.py and contains samples
class MyAction(QAction):
actionName=pyqtSignal(str)
def __init__(self,*args):
super().__init__(*a | rgs)
self.triggered.connect(self.myEmit)
def myEmit(self):
self.actionName.emit(self.text())
class ExampleMenu(QMenu):
'''show example programs in Example folder'''
def __init__(self,*args):
super().__init__(*args)
import raipy
import os
folder=os.pa... |
virtool/virtool | virtool/references/tasks.py | Python | mit | 19,832 | 0.001412 | import asyncio
import json
import os
import shutil
from datetime import timedelta
from pathlib import Path
import aiohttp
import arrow
from semver import VersionInfo
import virtool.errors
import virtool.otus.db
import virtool.tasks.pg
from virtool.api.json import CustomEncoder
from virtool.github import create_update... | return await self.error(errors)
await virtool.tasks.pg.update(
self.pg, self.id, progress=tracker.step_completed, step="validate"
)
async def import_otus(self):
created_at = self.context["created_at"]
ref_id = self.context["ref_id"]
user_id = self.context["us... | ))
inserted_otu_ids = list()
for otu in otus:
otu_id = await insert_joined_otu(self.db, otu, created_at, ref_id, user_id)
inserted_otu_ids.append(otu_id)
await tracker.add(1)
await self.update_context({"inserted_otu_ids": inserted_otu_ids})
await v... |
jjhuo/btier2 | tools/show_block_details.py | Python | gpl-2.0 | 7,532 | 0.028943 | #!/usr/bin/python
#############################################
# show_block_details.py #
# #
# A simple python program that retrieves #
# btier block placement metadata #
# And optionally stores the data in sqlite #
# EXAMPLE CODE ... | "/"+str(newdev)
fp.write(command)
fp.close()
except IOError as e:
if e.errno == errno.EAGAIN:
return errno.EAGAIN
print "Failed to migrate block %d to device %d" % (blocknr, newdev)
exit(RET_MIGERR)
else:
return 0
def migrate_up(cur,blocknr,device):
if de... | xecute("SELECT blocknr FROM meta where blocknr = ? \
AND device = ? AND writecount > ? \
* (SELECT AVG(writecount) from meta \
where device = ?)", (blocknr,device, THRESHOLD_UP, device))
record = cur.fetchone()
if record == None:
return -1
blocknr=i... |
simudream/polyglot | polyglot/mapping/expansion.py | Python | gpl-3.0 | 3,238 | 0.011736 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from .base import OrderedVocabulary
from collections import defaultdict
from six import iteritems
import re
import logging
logger = logging.getLogger(__name__)
class VocabExpander(OrderedVocabulary):
def __init__(self, vocabulary, formatters, strategy):
super(Vocab... | .format(u" ".join(words_added)))
class CaseExpander(VocabExpander):
def __init__(self, vocabulary, | strategy='most_frequent'):
formatters = [lambda x: x.lower(),
lambda x: x.title(),
lambda x: x.upper()]
super(CaseExpander, self).__init__(vocabulary=vocabulary, formatters=formatters, strategy=strategy)
class DigitExpander(VocabExpander):
def __init__(self, vocabula... |
ExCiteS/geokey-wegovnow | geokey_wegovnow/templatetags/wegovnow.py | Python | mit | 470 | 0 | """Custom WeGovNow template tags."""
from django import template
register = temp | late.Library()
@register.filter()
def exclude_uwum_app(apps):
"""Exclude UWUM app."""
apps_without_uwum = []
| for app in apps:
if app.provider.id != 'uwum':
apps_without_uwum.append(app)
return apps_without_uwum
@register.filter()
def exclude_uwum_accounts(accounts):
"""Exclude UWUM accounts."""
return accounts.exclude(provider='uwum')
|
phlax/translate | translate/storage/jsonl10n.py | Python | gpl-2.0 | 10,135 | 0.000493 | # -*- coding: utf-8 -*-
#
# Copyright 2007,2009-2011 Zuza Software Foundation
#
# This file is part of the Translate Toolkit.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 o... | 8')
try:
self._file = json.loads(input, object_pairs_hook=OrderedDict)
except ValueError as e:
raise base.ParseError(e.message)
for k, data, ref, item in self._extract_translatables(self._file,
stop=self._filt... | ef serialize(self, out):
def nested_set(target, path, value):
if len(path) > 1:
if path[0] not in target:
target[path[0]] = OrderedDict()
nested_set(target[path[0]], path[1:], value)
else:
target[path[0]] = value
... |
schiz21c/CDListPy | setup_py2exe.py | Python | mit | 1,169 | 0.017964 | from distutils.core import setup
import py2exe, sys
sys.argv.append('py2exe')
MANIFEST = """
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<dependency>
<dependentAssembly>
<assemblyIdentity
type=... | age="*"
/>
</dependentAssembly>
</dependency>
</assembly>
"""
|
setup(
options = {'py2exe': {'packages': ['encodings', 'wx'],
'bundle_files': 1,
'compressed': 1,
'optimize': 2,
'dll_excludes': ['mswsock.dll', 'powrprof.dll']
}},
windows = [{'script': 'CDListPy.py',... |
thomashuang/Lilac | lilac/controller/user.py | Python | lgpl-3.0 | 6,114 | 0.009323 | #!/usr/bin/env python
import re
from lilac.controller import ADMIN, LOGGER
from lilac.orm import Backend
from lilac.tool import access, set_secure_cookie
from lilac.model import User
from solo.template import render_template
from solo.web.util import jsonify
from solo.web import ctx
from webob import exc
from lilac.... | return {'status' : 'error', 'msg' : 'user name:%s is used' %(username)}
user = User(username, email, real_name, password, status, role)
Backend('user').save(user)
return {'status' : 'info', 'msg' : 'saved'}
@access()
def edit_page(self, uid):
uid = int(uid)
... | , user=user)
@jsonify
@access()
def edit(self, uid, email, real_name, password, newpass1, newpass2, status, role='user'):
real_name, newpass1, newpass2 = real_name.strip(), newpass1.strip(), newpass2.strip()
uid = int(uid)
user = Backend('user').find(uid)
if not user:
... |
somebody1234/Charcoal | interpreterprocessor.py | Python | mit | 34,121 | 0.000645 | # TODO: direction list operator?
from direction import Direction, Pivot
from charcoaltoken import CharcoalToken as CT
from unicodegrammars import UnicodeGrammars
from wolfram import (
String, Rule, DelayedRule, Span, Repeated, RepeatedNull, PatternTest,
Number, Expression
)
import re
from math import floor, ce... | ])
return sum(
float(c) if "." in c else int(c)
for c in re.findall("\d+\.?\d*|\.\d+", item)
)
if hasattr(item, "__iter__") and item:
if isinstance(item[0], Expression):
item = iter_apply(item, lambda o: o.run())
| if isinstance(item[0], str):
return "".join(item)
if isinstance(item[0], String):
return "".join(map(str, item))
if isinstance(item[0], list):
return sum(item, [])
return sum(item)
def Product(item):
if isinstance(item, float):
item = int(ite... |
dandygithub/kodi | addons/context.dandy.kinopoisk.sc/resources/lib/sc_czxto.py | Python | gpl-3.0 | 1,100 | 0.01184 | import sys
import urllib, urllib2
import xbmc
import xbmcgui
import XbmcHelpers
common = XbmcHelpers
from videohosts import tools
URL = "http://czx.to"
HEADERS = {
"Ho | st": "czx.to",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36"
}
VALUES = {
}
_kp_id_ = ''
def get_content():
vh_title = "czx.to"
list_li = []
response = tools.get_response(URL + '/' + str(_kp_id_) + '/', HEAD | ERS, VALUES, 'GET')
if response:
iframe = common.parseDOM(response, "iframe", ret="src")[0]
title_ = "*T*"
title = "[COLOR=orange][{0}][/COLOR] {1}".format(vh_title, tools.encode(title_))
uri = sys.argv[0] + "?mode=show&url={0}".format(urllib.quote_plus(iframe))
item... |
overdrive3000/skytools | python/pgq/__init__.py | Python | isc | 980 | 0.002041 | """PgQ framework for Python."""
__pychecker__ = 'no | -miximport'
import pgq.event
import pgq.consumer
import pgq.remoteconsumer
import pgq.producer
import pgq.status
import pgq.cascade
import pgq.cascade.nodeinfo
import pgq.cascade.admin
import pgq.cascade.consumer
import pgq.cascade.worker
from pgq.event import *
from pgq.consumer import *
from pgq.coopcon | sumer import *
from pgq.remoteconsumer import *
from pgq.localconsumer import *
from pgq.producer import *
from pgq.status import *
from pgq.cascade.nodeinfo import *
from pgq.cascade.admin import *
from pgq.cascade.consumer import *
from pgq.cascade.worker import *
__all__ = (
pgq.event.__all__ +
pgq.consum... |
0rpc/zerorpc-crosstests | python/server.py | Python | mit | 1,678 | 0.002982 | # -*- coding: utf-8 -*-
# Open Source Initiative OSI - The MIT License (MIT):Licensing
#
# The MIT License (MIT)
# Copyright (c) 2016 François-Xavier Bourlet ([email protected])
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files... | 1]
class TestServer(zerorpc.Se | rver):
def echo(self, v):
print("echo {0} <{1}>".format(type(v), v))
return v
def quit(self):
print("exiting...")
self.stop()
server = TestServer()
server.bind(endpoint)
print('Server started', endpoint)
server.run()
|
cuteredcat/aukro | aukro/parser.py | Python | mit | 2,291 | 0.004822 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from datetime import datetime
from lxml.html import fromstring, make_links_absolute, tostring
from urlparse import parse_qs, urlparse
import cookielib, json, importlib, re, urllib, urllib2
RE_URL = re.compile(r"""(?i)\b((?:[a-z][\w-]+:(?:/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[... | ?«»“”‘’]))""")
class HTTPRedirectHandler(urllib2.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
newreq = urllib2.HTTPRedirectHandler.redirect_request(self, req, fp, code, msg, headers, newurl)
if newreq is not None: self.redirections.append(newreq.get_full_ur... | ie = cookielib.CookieJar()
self.headers = [('User-agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.93 Safari/537.36'),
('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8')]
def link(self, link):... |
technoarch-softwares/facebook-auth | setup.py | Python | bsd-2-clause | 1,410 | 0.002128 | import os
from setuptools import find_packages, setup
wi | th open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
install_requires = [
'requests==2.8.1'
]
setup(
name='facebook-auth',
version='0.1',
... | ckages=find_packages(),
include_package_data=True,
license='BSD License', # example license
description='A simple Django app for facebook authentcation.',
long_description=README,
url='https://github.com/technoarch-softwares/facebook-auth',
author='Pankul Mittal',
author_email='mittal.panku... |
murarugeorgec/USB-checking | USB/USB_DBus/usb_dbus_system.py | Python | gpl-3.0 | 1,795 | 0.016713 | #! /usr/bin/env python
# DBus to turn USB on or off (by unbinding the driver)
# The System D-bus
import dbus
import dbus.service
from gi.repository import GLib
from dbus.mainloop.glib import DBusGMainLoop
from usb_inhibit import USB_inhibit
class USB_Se | rvice_Blocker(dbus.service.Object):
inhibitor_work = False
def __init__(self):
self.usb_monitor = USB_inhibit(True)
bus_name = dbus.service.BusName('org.gnome.USBBlocker', bus=dbus.SystemBus())
dbus.service.Object.__init__(self, bus_name, '/org/gnome/USBBlocker')
@dbus.service.method(dbus_interf... | ')
def get_status(self):
return self.inhibitor_work
@dbus.service.method(dbus_interface='org.gnome.USBBlocker.inhibit')
def start(self):
print("Start monitoring Dbus system message")
if not self.inhibitor_work:
self.usb_monitor.start()
self.inhibitor_work = True
... |
suutari/shoop | shuup_tests/front/test_product.py | Python | agpl-3.0 | 1,368 | 0.002193 | # -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2016, Shoop Commerce Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
import pytest
from django.core.urlre | solvers import reverse
from shuup.testing.factories import create_product, get_default_product, get_default_shop
@pytest.mark.django_db
def test_product_page(client):
get_default_shop()
product = get_default_product()
res | ponse = client.get(
reverse('shuup:product', kwargs={
'pk': product.pk,
'slug': product.slug
}
)
)
assert b'no such element' not in response.content, 'All items are not rendered correctly'
# TODO test purchase_multiple and sales_unit.allow_fractions
@py... |
mattaw/SoCFoundationFlow | admin/waf/waf-extensions/SFFerrors.py | Python | apache-2.0 | 77 | 0 |
class Error(Exception):
| def | __init__(self, msg):
self.msg = msg
|
eelanagaraj/IST_project | LSTM_ISTapps.py | Python | mit | 5,130 | 0.020663 | #! /usr/bin/env python
""" time to run LSTM on this bad boy! """
from __future__ import absolute_import
from __future__ import print_function
import numpy as np
import cPickle as pkl
from keras.optimizers import SGD, RMSprop, Adagrad
from keras.utils import np_utils
from keras.mod | els import Sequential
from keras.layers.core import Dense, Dropout, Activation
from keras.layers.embeddings import Embedding
from keras.layers.recurrent import LSTM, GRU
from text_processing.ISTapps import load_ISTapps
#from ISTapps import load_ISTapps
from sklearn import cross_validation
# different structures to tes... | lting at a certain point
sgd = SGD(lr=0.1, decay=1e-6, momentum=0.9, nesterov=True)
optimizers = ['adam', sgd, 'adagrad', 'adadelta', 'rmsprop']
LSTM_ins = [128, 256, 512]
LSTM_outs = [128, 256]
activations = ['sigmoid', 'relu', 'softmax', 'tanh']
loss_functions = ['binary_crossentropy', 'mean_squared_error']
# trial ... |
jsvine/pdfplumber | pdfplumber/utils.py | Python | mit | 20,406 | 0.000441 | import itertools
from operator import itemgetter
from pdfminer.pdftypes import PDFObjRef
from pdfminer.psparser import PSLiteral
from pdfminer.utils import PDFDocEncoding
DEFAULT_X_TOLERANCE = 3
DEFAULT_Y_TOLERANCE = 3
DEFAULT_X_DENSITY = 7.25
DEFAULT_Y_DENSITY = 13
def cluster_list(xs, tolerance=0):
if toleran... | ordered_chars):
x0, top, x1, bottom = object | s_to_bbox(ordered_chars)
doctop_adj = ordered_chars[0]["doctop"] - ordered_chars[0]["top"]
upright = ordered_chars[0]["upright"]
direction = 1 if (self.horizontal_ltr if upright else self.vertical_ttb) else -1
word = {
"text": "".join(map(itemgetter("text"), ordered_chars))... |
sheagcraig/sal | inventory/migrations/0010_auto_20180911_1154.py | Python | apache-2.0 | 937 | 0 | # Generated by Django 1.10 on 2018-09-11 18:54
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('inventory', '0009_inventory_inventory_str'),
]
operations = [
migrations.AlterField(
model_name='application',
name=... | migrations.AlterField(
model_name='inventoryitem',
name='path',
field | =models.TextField(blank=True, null=True),
),
]
|
glaunay/pyproteins | src/pyproteins/alignment/scoringMatrix.py | Python | gpl-3.0 | 3,051 | 0.016716 | import numpy as np
class SubstitutionMatrix():
def __init__(self):
pass
def __getitem__(self, tup):
y, x = tup
return self.matrix[self.alphabet.index(y)][self.alphabet.index(x)]
class Blosum62(SubstitutionMatrix):
def __init__(self):
SubstitutionMatrix.__init__(self)
... | -2, 1, 4, -1, -4],
[0, -2, 0, -1, -3, -2, -2, 6, -2, -4, -4, -2, -3, -3, -2, 0, -2, -2, -3, -3, -1, -2, -1, -4],
[2, 0, 1, -1, -3, 0, 0, -2, 8, -3, -3, -1, -2, -1, -2, -1, -2, -2, 2, -3, 0, 0, -1, -4],
[1, -3, -3, | -3, -1, -3, -3, -4, -3, 4, 2, -3, 1, 0, -3, -2, -1, -3, -1, 3, -3, -3, -1, -4],
[1, -2, -3, -4, -1, -2, -3, -4, -3, 2, 4, -2, 2, 0, -3, -2, -1, -2, -1, 1, -4, -3, -1, -4],
[1, 2, 0, -1, -3, 1, 1, -2, -1, -3, -2, 5, -1, -3, -1, 0, -1, -3, -2, -2, 0, 1, -1, -4],
[1, -1, -2, -3, -1, 0, -2, -3, -2, ... |
PythonScanClient/PyScanClient | doc/make_version.py | Python | epl-1.0 | 355 | 0.008451 |
print """
Version Info
============
To obtain version info::
from scan.version import __version__, version_his | tory
print __version__
print version_history
"""
import sys
sys.path.append("..")
f | rom scan.version import __version__, version_history
print "Version history::"
for line in version_history.splitlines():
print (" " + line)
|
catapult-project/catapult | third_party/gsutil/gslib/tests/test_acl.py | Python | bsd-3-clause | 33,748 | 0.003793 | # -*- coding: utf-8 -*-
# Copyright 2013 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requir... | derr=True,
expected_status=1)
self.assertIn('CommandEx | ception', stderr)
self.assertIn('Invalid canned ACL', stderr)
def test_set_valid_def_acl_bucket(self):
"""Ensures that valid default canned and XML ACLs works with get/set."""
bucket_uri = self.CreateBucket()
# Default ACL is project private.
obj_uri1 = suri(self.CreateObject(bucket_uri=bucket_u... |
Miserlou/Emo | emo/code.py | Python | mit | 46,810 | 0.000192 | #
# This file is based on emoji (https://github.com/kyokomi/emoji).
#
# The MIT License (MIT)
#
# Copyright (c) 2014 kyokomi
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restr... | 0001f501",
":ru:": u"\U0001f1f7\U0001f1fa",
":new_moon:": u"\U0001f311",
":church:": u"\U000026ea",
":date:": | u"\U0001f4c5",
":earth_americas:": u"\U0001f30e",
":footprints:": u"\U0001f463",
":libra:": u"\U0000264e",
":mountain_cableway:": u"\U0001f6a0",
":small_red_triangle_down:": u"\U0001f53b",
":top:": u"... |
eayunstack/neutron | neutron/db/securitygroups_db.py | Python | apache-2.0 | 39,022 | 0.000179 | # Copyright 2012 VMware, Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by a... | direction='egress', ethertype=ethertype)
egress_rule.create()
sg.rules.append(egress_rule)
sg.obj_reset_changes(['rules'])
# fetch sg from db to load the sg rules with sg model.
# NOTE(yamamoto): Adding rules above bumps the revision
... | ect doesn't
# use the instance.
context.session.expunge(model_query.get_by_id(
context, sg_models.SecurityGroup, sg.id))
sg = sg_obj.SecurityGroup.get_object(context, id=sg.id)
secgroup_dict = self._make_security_group_dict(sg)
kwargs['security... |
FFMG/myoddweb.piger | monitor/api/python/Python-3.7.2/Lib/distutils/tests/test_bdist_dumb.py | Python | gpl-2.0 | 2,905 | 0.000688 | """Tests for distutils.command.bdist_dumb."""
import os
import sys
import zipfile
import unittest
from test.support import run_unittest
from distutils.core import Distribution
from distutils.command.bdist_dumb import bdist_dumb
from distutils.tests import support
SETUP_PY = """\
from distutils.core import setup
impo... | elf):
os.chdir(self.old_location)
| sys.argv = self.old_sys_argv[0]
sys.argv[:] = self.old_sys_argv[1]
super(BuildDumbTestCase, self).tearDown()
@unittest.skipUnless(ZLIB_SUPPORT, 'Need zlib support to run')
def test_simple_built(self):
# let's create a simple package
tmp_dir = self.mkdtemp()
pkg_dir... |
cmexiatyp/open_academy | model/wizard.py | Python | apache-2.0 | 611 | 0.006547 | # -*- encoding: utf-8 -*-
from openerp import models | , fields, api
class Wizard(models.TransientModel):
_name = 'openacademy.wizard'
def _default_sessions(self):
return self.env | ['openacademy.session'].browse(self._context.get('active_ids'))
session_ids = fields.Many2many('openacademy.session',
string="Sessions", required=True, default=_default_sessions)
attendee_ids = fields.Many2many('res.partner', string="Attendees")
@api.multi
def subscribe(self):
for sess... |
maurossi/deqp | scripts/opengl/gen_es31_wrapper.py | Python | apache-2.0 | 1,342 | 0.022355 | # -*- coding: utf-8 -*-
#-------------------------------------------------------------------------
# drawElements Quality Program utilities
# --------------------------------------
#
# Copyright 2015 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use t... | 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,
# WIT | HOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
#-------------------------------------------------------------------------
from src_util import *
def commandES31InitStatement (command):
memb... |
rmacqueen/CS274 | p3/md_macqueen.py | Python | gpl-2.0 | 10,475 | 0.025776 | import argparse
from math import sqrt
import sys
NUM_DIMENSIONS = 3
# Gets the distance between two points
def get_distance(pointA, pointB):
if not len(pointA) == len(pointB):
print "Trying to compare points of different dimension. Cannot do that"
sys.exit()
total_sum = 0.0
# Computes Euclidean distance by get... | et_new_velocity(self.delta_t)
def set_new_acceleration | s(self):
for atom in self.atoms:
atom.set_new_acceleration()
def calculate_potential_energy(self):
bond_potential_energy = 0.0
non_bond_potential_energy = 0.0
for interaction in self.bonds:
atom1 = self.atoms[interaction.atom1_id]
atom2 = self.atoms[interaction.atom2_id]
distance = get_distance(at... |
vprnet/timeline | app/_config.py | Python | mit | 840 | 0.002381 | import os
import inspect
# Frozen Flask
FREEZER_DEFAULT_MIMETYPE = 'text/html'
FREEZER_IGNORE_MIMETYPE_WARNINGS = True
# Amazon S3 Settings
AWS_KEY = ''
AWS_SECRET_KEY = ''
AWS_BUCKET = 'www.vpr.net'
AWS_DIRECTORY = 'sandbox/timeline'
# Cache Settings (units in seconds)
STATIC_EXPIRES = 60 * 24 * 3600
HTML_EXPIRES =... | yc', '.py', '.rb', '.md']
# Always | AWS_DIRECTORY for VPR projects
if AWS_DIRECTORY:
BASE_URL = 'http://' + AWS_BUCKET + '/' + AWS_DIRECTORY
FREEZER_BASE_URL = BASE_URL
else:
BASE_URL = 'http://' + AWS_BUCKET
ABSOLUTE_PATH = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) + '/'
|
antoinecarme/pyaf | tests/artificial/transf_Fisher/trend_LinearTrend/cycle_30/ar_12/test_artificial_128_Fisher_LinearTrend_30_12_20.py | Python | bsd-3-clause | 265 | 0.086792 | import pyaf.Bench.TS_datasets as tsds
import tests.artificial.process_artificial_dataset as art
art.process_dataset(N = 128 , FREQ = 'D', seed = 0, trendtype = "LinearTrend", cycle_length = | 30, transform = "Fisher", si | gma = 0.0, exog_count = 20, ar_order = 12); |
ychen820/microblog | y/google-cloud-sdk/platform/google_appengine/lib/cherrypy/cherrypy/tutorial/tut05_derived_objects.py | Python | bsd-3-clause | 2,291 | 0.003492 | """
Tutorial - Object inheritance
You are free to derive your request handler classes from any base
class you wish. In most real-world applications, you will probably
want to create a central base class used for all your pages, which takes
care of things like printing a common page header and footer.
"""
import cherr... | dy>
</html>
'''
# Note that header and footer don't get their exposed attributes
# set to True. This isn't necessary since the user isn't supposed
# t | o call header or footer directly; instead, we'll call them from
# within the actually exposed handler methods defined in this
# class' subclasses.
class HomePage(Page):
# Different title for this page
title = 'Tutorial 5'
def __init__(self):
# create a subpage
self.another = A... |
qateam123/eq | tests/integration/questionnaire/test_questionnaire_question_guidance.py | Python | mit | 4,682 | 0.002563 | from tests.integration.create_token import create_token
from tests.integration.integration_test_case import IntegrationTestCase
class TestQuestionnaireQuestionGuidance(IntegrationTestCase):
def test_question_guidance(self):
# Given I launch a questionnaire with various guidance
token = create_tok... | e)
# When we navigate to the block with all guidance features enabled
resp_url, resp = self.postRedirectGet(resp.location, {'action[start_questionnaire]': ''})
# Then we are presented with the question guidance with all features enabled
self.assertIn('block-test-guidance-all', resp_url... | self.assertIn('>Item Include 2<', content)
self.assertIn('>Item Include 3<', content)
self.assertIn('>Item Include 4<', content)
self.assertIn('>Exclude<', content)
self.assertIn('>Item Exclude 1<', content)
self.assertIn('>Item Exclude 2<', content)
self.assertIn('... |
Sriee/epi | data_structures/search/bsearch.py | Python | gpl-3.0 | 7,820 | 0.003197 | from collections import Counter
def bsearch(nums, target):
"""
Binary Search with duplicates.
:param nums: Given array
:param target: The element to find in the array
:return: first index of the element found
"""
idx, l, r = -1, 0, len(nums) - 1
while l <= r:
mid = l + (r - l... | , Counter(''.join(i for i in license_plate if i.isalpha()).lower())
for word in words:
flag = True
for k, v in lp.items():
if k not in word and v > word.count(k):
flag = False
break
if flag:
if not res:
res = word
... | :
"""
Leet code. Solution -> Accepted
Run Time:
Find minimum element in a rotated sorted array. The array does not contains
duplicates. If the array has duplicates, optical time
:param nums: Given array
:return: minimum element in an array
"""
low, high = 0, len(nums) - 1
whi... |
guillaume-havard/com_elements_gui | src/interface.py | Python | mit | 182 | 0.005495 | #!/usr/bin/ | python3
"""
Copyright (c) 2014 Guillaume Havard - BVS
"""
import tkinter as tk
from appli | cation import *
root = tk.Tk()
app = Application(master=root)
app.mainloop()
|
setsulla/stir | project/magnolia/script/kancolle.old/exercises.py | Python | mit | 1,442 | 0.006241 | import os
import sys
import time
from magnolia.utility import *
from magnolia.utility import LOG as L
from magnolia.script.kancolle import testcase_normal
class TestCase(testcase_normal.TestCase_Normal):
def __init__(self, *args, **kwargs):
super(TestCase, self).__init__(*args, **kwargs)
@classmethod... | et("args.deploy")), "Can't Login & Check Start.")
while self.expedition_result(): time.sleep(1)
self.slack_message(self.get("bot.exercises"))
self.assertTrue(self.exercises(), "Can't Exercises.")
while self.expedition_result(): time.sleep(1)
self.assertTrue(se... | ())
while self.expedition_result(): time.sleep(1)
self.minicap_finish(); time.sleep(2)
except Exception as e:
L.warning(type(e).__name__ + ": " + str(e))
self.minicap_finish(); time.sleep(2)
self.minicap_create_video()
self.fail("Error Ocur... |
yunojuno/django-perimeter | tests/test_middleware.py | Python | mit | 5,555 | 0.00036 | from unittest import mock
from urllib.parse import urlparse
from django.contrib.auth.models import AnonymousUser, User
from django.core.exceptions import ImproperlyConfigured, MiddlewareNotUsed
from django.test import RequestFactory, TestCase, override_settings
from django.urls import resolve, reverse
from perimeter.... | uld raise AssertionError."""
self.assertEqual(check_middleware(lambda r: r)(self.request), self.request)
del self.request.session
with self.assertRaises(ImproperlyConfigured):
| check_middleware(lambda r: r)(self.request)
def test_missing_session(self):
"""Missing request.session should raise AssertionError."""
del self.request.session
self.assertRaises(
ImproperlyConfigured, self.middleware.process_request, self.request
)
def test_... |
fake-name/ReadableWebProxy | WebMirror/management/rss_parser_funcs/feed_parse_extractQuillofkarnikaWordpressCom.py | Python | bsd-3-clause | 708 | 0.026836 | def extractQuillofkarnikaWordpressCom(item):
'''
Parser for 'quillofkarnika.wordpress.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp | or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('Top Giants: Rebirth of the Black-Bellied Wife', 'Top Giants: Rebirth of the Black-Bellied Wife', 'translated'),
('PRC', 'PRC', 'translated'),
('Loiterous', 'Loiterous', ... | ithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
return False |
CoachCoen/games | test/test_all.py | Python | mit | 467 | 0 | import unittest
from test.test_game_state import | TestAvailableActionSets
from test.test_ga | me_state import TestTurnComplete
from test.test_vector import TestVector
from test.test_buttons import TestButtonCollection
from test.test_ai_simple import TestAISimple
from test.test_drawing_surface import TestDrawingSurface
from test.test_game_actions import TestGameActions
from test.test_game_objects import TestGame... |
dstufft/warehouse | warehouse/migrations/versions/bf73e785eed9_add_notify_column_to_adminflag.py | Python | apache-2.0 | 1,034 | 0.000967 | # 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 L | icense for the specific language governing permissions and
# limitations under the License.
"""
Add notify column to AdminFlag
Revision ID: bf73e785eed9
Revises: 5dda74213989
Create Date: 2018-03-23 21:20:05.834821
"""
from alembic import op
import sqlalchemy as sa
revision = "bf73e785eed9"
down_revision = "5dda7421... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.