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 |
|---|---|---|---|---|---|---|---|---|
tysonholub/twilio-python | tests/integration/fax/v1/fax/test_fax_media.py | Python | mit | 4,434 | 0.003834 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from tests import IntegrationTestCase
from tests.holodeck import Request
from twilio.base.exceptions import TwilioException
from twilio.http.response import Response
class FaxMediaTestCase(Integrat... | aaaa/Media?PageSize=50&Page=0",
"key": "media",
"next_page_url": null,
"page": 0,
"page_size": 50,
"previous_page_url": null,
| "url": "https://fax.twilio.com/v1/Faxes/FXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Media?PageSize=50&Page=0"
}
}
'''
))
actual = self.client.fax.v1.faxes(sid="FXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
.media.list()
self.a... |
popazerty/beyonwiz-sh4 | lib/python/Screens/UserInterfacePositioner.py | Python | gpl-2.0 | 10,293 | 0.025163 | from Screens.Screen import Screen
from Components.ActionMap import ActionMap
from Components.config import config, configfile, getConfigListEntry
from Components.ConfigList import ConfigListScreen
from Components.SystemInfo import SystemInfo
from Components.Sources.StaticText import StaticText
from Components.Pixmap im... | nt 'Setting OSD position: %s %s %s %s' % (config.osd.dst_left.value, config.osd.dst_width.value, config.osd.dst_top.value, config.osd.dst_height.value)
def saveAll(self):
for x in self["config"].list:
x[1].save()
configfile.save()
# keySave and keyCancel are just provided in case you need them.
# you have t... | ice(self):
try:
self.session.nav.playService(self.oldref)
except:
pass
def keySave(self):
self.saveAll()
self.playOldService()
self.close()
def cancelConfirm(self, result):
if not result:
return
for x in self["config"].list:
x[1].cancel()
self.playOldService()
self.close()
def keyCa... |
ZeitOnline/zeit.calendar | src/zeit/calendar/generation/install.py | Python | bsd-3-clause | 331 | 0 | import zeit.cms.generation
import zeit.cms.generation.install
import zeit.calendar.calendar
import zeit.calendar.interfaces
@zeit.cms.gen | eration.get_root
def evolve(root):
zeit.cms.generation.install.installLocalUti | lity(
root, zeit.calendar.calendar.Calendar,
'calendar', zeit.calendar.interfaces.ICalendar)
|
Undeterminant/math-modeling | mathmodeling/misc.py | Python | cc0-1.0 | 983 | 0.034588 | from calendar import monthrange as monrange
from datetime import datetime, date
__ | all__ = ['tocsv', 'fromcsv', 'date_to_float']
def tocsv(data, header, fname):
"""Converts a table into a CSV file."""
with open(fname, 'w') as f:
| print(','.join(header), file = f)
for row in data:
print(row, file = f)
def fromcsv(fname, cons):
"""Converts a CSV file into a table."""
with open(fname) as f:
f.readline()
return [cons(line.strip().split(",")) for line in f if line.strip()]
def date_to_float(D):
"""
Converts a date to a float in yea... |
rowinggolfer/openmolar2 | src/lib_openmolar/client/qt4/dialogs/save_discard_cancel_dialog.py | Python | gpl-3.0 | 3,474 | 0.007772 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
## ##
## Copyright 2010-2012, Neil Wallace <neil@openmolar.com> ##
## ... | ##
###############################################################################
from PyQt4 import QtCore, QtGui
from lib_openmolar.common.qt4.dialogs import ExtendableDialog
class SaveDiscardCancelDialog(ExtendableDialog):
def __init__(self, me... | |
mhils/mitmproxy | mitmproxy/proxy/layers/tls.py | Python | mit | 18,080 | 0.002685 | import struct
import time
from dataclasses import dataclass
from typing import Iterator, Literal, Optional, Tuple
from OpenSSL import SSL
from mitmproxy import certs, connection
from mitmproxy.net import tls as net_tls
from mitmproxy.proxy import commands, events, layer, tunnel
from mitmproxy.proxy import context
from... | == tls_start.context.client:
yield TlsStartClientHook(tls_start)
else:
yield TlsStartServerHook(tls_sta | rt)
if not tls_start.ssl_conn:
yield commands.Log("No TLS context was provided, failing connection.", "error")
yield commands.CloseConnection(self.conn)
assert tls_start.ssl_conn
self.tls = tls_start.ssl_conn
def tls_interact(self) -> layer.CommandGenerator[None]:
... |
abhishekgahlot/cockroach-python | cockroach/proto/log_pb2.py | Python | apache-2.0 | 8,487 | 0.003181 | # Generated by the protocol buffer compiler. DO NOT EDIT!
# source: cockroach/proto/log.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflecti... | RegisterFileDescriptor(DESCRIPTOR)
_LOGENTRY_ARG = _descriptor.Descriptor(
name='Arg',
full_name='cockroach.proto.LogEntry.Arg',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='type', full_name='cockroach.proto.LogEntry.Arg.type', index=0,
... | type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='str', full_name='cockroach.proto.LogEntry.Ar... |
sidorov-si/TADStates | call_borders.py | Python | gpl-2.0 | 6,153 | 0.006176 | #!/usr/bin/env python
"""
Generate BED files with TAD borders of particular width.
TAD border of width 2r between two TADs is defined as a region consisting of
r bp to the left and r bp to the right of the point separating the two TADs.
Usage:
call_borders.py (-f <TADs_filename> | -d <input_directory>) -w <border_w... | = arguments["-d"].rstrip('/')
if not exists(input_directory):
print "Error: Can't find input directory: no such directory '" | + \
input_directory + "'. Exit.\n"
sys.exit(1)
if not isdir(input_directory):
print "Error: Input directory must be a directory:). Something else given. Exit.\n"
sys.exit(1)
try:
border_width = int(arguments["-w"])
except ValueError:
... |
aio-libs/aiozmq | examples/stream_monitor.py | Python | bsd-2-clause | 919 | 0.001088 | import asyncio
import aiozmq
import zmq
async def monitor_stream(stream):
try:
while True:
event = await stream.read_event()
print(event)
except aiozmq.ZmqStreamClosed:
pass
async def go():
router = await aiozmq.create_zmq_stream(zmq.ROUTER, bind="tcp://127.0.0.1:... | msg = (b"data", b"ask", str(i).encode("utf-8"))
dealer.write(msg)
data = await router.read()
router.write(data)
answer = await dealer.read()
print(answer)
router.close()
dealer.close()
def main():
asyncio.run(go())
print("DONE")
if __name__ == "__ma | in__":
main()
|
ser/topitup | siema.py | Python | agpl-3.0 | 8,241 | 0.000971 | # Flask modules
from flask import (
Blueprint,
render_template,
redirect,
url_for,
request,
flash,
current_app,
g,
)
# FLask Login
from flask_login import (
current_user,
)
# WTForms
from flask_wtf import Form
from wtforms import (
SubmitField,
BooleanField,
DecimalFiel... | ate(page, 50)
return render_template('invoices.html',
invoices | =sql_query,
)
else:
flash('You are not admin and you can see your own invoices only!',
|
nezhar/updatable | test/test_update_license.py | Python | mit | 2,049 | 0 | #!/usr/bin/env python
import unittest
import os
import json
from updatable import utils as updatable_utils
PATH = os.path.dirname(os.path.realpath(__file__))
def get_pypi_package_data_monkey(package_name, v | ersion=None):
if version:
json_file = 'pypi-%s-%s.json' % (package_name, version)
else:
json_file = 'pypi-%s.json' % package_name
with open(os.path.join(PATH, 'fixtures', json_file)) | as data_file:
return json.load(data_file)
class TestUpdateLicense(unittest.TestCase):
"""
Tests package updatability
"""
def setUp(self):
self.get_pypi_package_data_orig = updatable_utils.get_pypi_package_data
updatable_utils.get_pypi_package_data = get_pypi_package_data_monke... |
dennisobrien/bokeh | bokeh/command/subcommands/sampledata.py | Python | bsd-3-clause | 2,480 | 0.008065 | #-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2018, Anaconda, Inc. All rights reserved.
#
# Powered by the Bokeh Development Team.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#---------------------------------------------------... | -------------------------------------------------
class Sampledata(Subcommand):
''' Subcommand to download bokeh sample data sets.
'''
#: name for this subcommand
name = "sampledata"
help = "Download the bokeh sample data sets"
args = (
)
def invoke(self, ar | gs):
'''
'''
sampledata.download()
#-----------------------------------------------------------------------------
# Dev API
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Private A... |
Foxugly/MyTaxAccountant | companies/migrations/0003_auto_20160413_1433.py | Python | agpl-3.0 | 1,551 | 0.003224 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('companies', '0002_auto_20160317_2216'),
]
operations = [
migrations.AddField(
model_name='company',
... | (
model_name='company',
name='number_employees',
field=models.IntegerField(default=1, verbose_name='Number of employees', choices=[(1, '1'), (2, 'Between 1 and 10'), (3, 'Between 10 and 50'), (4, 'More than 50')]),
),
migrations.AddField(
model_name='compa... | euros'), (2, 'Between 50.000 euros and 250.000 euros'), (3, 'Between 250.000 euros and 700.000 euros'), (4, 'Between 700.000 euros and 4.500.000 euros'), (5, 'More than 4.500.000 euros')]),
),
migrations.AddField(
model_name='company',
name='website',
field=models.URL... |
ericzolf/ansible | lib/ansible/modules/service.py | Python | gpl-3.0 | 63,886 | 0.002317 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2012, Michael DeHaan <michael.dehaan@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
DOCUMENTATION = r'''
---
modul... | placed by subclass).
def get_service_tools(self):
self.module.fail_json(msg="get_service_tools not implemented on target platform")
def service_enable(self):
self.module.fail_json(msg="service_enable not implemented on target platform")
def get_service_status(self):
self.module.fa... | ervice_status not implemented on target platform")
def service_control(self):
self.module.fail_json(msg="service_control not implemented on target platform")
# ===========================================
# Generic methods that should be used on all platforms.
def execute_command(self, cmd, da... |
invinst/ResponseBot | responsebot/utils/log_utils.py | Python | apache-2.0 | 626 | 0 | import logging
import logging.config
# TODO: add rotate file log
DEFAULT_CONFIG = {
'version': 1,
'formatters': {
'standard': {
'format': '[%(levelname)s] %(asctime)s %(message)s',
'datefmt': '%Y-%m-%d %H:%M:%S'
}
},
'handlers': {
' | console': {
'level': 'DEBUG',
'formatter': 'standard',
'class': 'logging.StreamHandler'
}
},
'loggers': {
'': {
'handlers': ['console'],
| 'level': 'INFO'
}
}
}
def configure_logging():
logging.config.dictConfig(DEFAULT_CONFIG)
|
luzi82/owatube | game/migrations/0001_initial.py | Python | gpl-3.0 | 11,684 | 0.007446 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Game'
db.create_table('game_game', (
('id', self.gf('django.db.models.fields.Aut... | , self.gf('django.db.models.fields.IntegerField')()),
('lenda', self.gf('django.db.models.fields.IntegerField')()),
))
db.send_create_signal('game', ['ScoreReport'])
# Adding model 'ScoreReportBest'
db.create_table('game_scorereportbest', (
('id', self.gf('django... | ields.AutoField')(primary_key=True)),
('report', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['game.ScoreReport'])),
))
db.send_create_signal('game', ['ScoreReportBest'])
def backwards(self, orm):
# Deleting model 'Game'
db.delete_table('game_game')
... |
SublimeText/PowershellUtils | sublimepath.py | Python | mit | 232 | 0.00431 | # Path management utilities for Sublim | e plugin dev.
# TODO: This will eventually be moved to a separate package.
import sublime
impor | t os
def rootAtPackagesDir(*leaf):
return os.path.join(sublime.packages_path(), *leaf)
|
jpetto/olympia | src/olympia/addons/management/commands/unsign_addons.py | Python | bsd-3-clause | 916 | 0 | # -*- coding: utf-8 -* | -
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from olympia.lib.crypto.tasks import unsign_addons
class Command(BaseCommand):
args = '<addon_id addon_id ...>'
help = 'Unsign a list of addons.'
option_list = BaseCommand.option_list + (
make_op... | def handle(self, *args, **options):
if len(args) == 0: # Unsign all the addons?
raise CommandError(
'Please provide at least one addon id to unsign. If you want '
'to unsign them all, use the '
'"process_addons --task unsign_addons" management comma... |
HEPData/hepdata_submission | scripts/check.py | Python | mpl-2.0 | 6,439 | 0.002951 | #!/usr/bin/env python
"""
Offline validation of submission.yaml and YAML data files.
Call this script from the directory containing these files:
./check.py
Or specify the directory as an additional argument:
./check.py directory
Or specify a single YAML file to validate:
./check.py single_yaml_file
"""
import s... | is_valid_data_file = data_file_validator.validate(file_path=data_file_path, data=contents)
if not is_valid_data_file:
print('%s is invalid HEPData YAML.' % data_file_path)
data_file_validator.print_errors(dat | a_file_path)
else:
# Check that the length of the 'values' list is consistent for
# each of the independent_variables and dependent_variables.
indep_count = [len(indep['values']) for indep in contents['independent_variables']]
... |
realms-team/basestation-fw | libs/smartmeshsdk-REL-1.3.0.1/external_libs/cryptopy/crypto/hash/sha1Hash_test.py | Python | bsd-3-clause | 2,119 | 0.012742 | #!/usr/bin/env python
""" sha1Hash_test.py
Unit tests for sha1.py
"""
from crypto.hash.sha1Hash import SHA1
import unittest
import struct
assert struct.calcsize('!IIIII') == 20, '5 integers should be 20 bytes'
class SHA1_FIPS180_TestCases(unittest.TestCase):
""" SHA-1 tests from FIPS180-1 Appendix A, B and ... | endix A test Failed'
def testFIPS180_1_Appendix_B(self):
""" APPENDIX B. A SECOND SAMPLE MESSAGE AND ITS MESSAGE DIGEST """
hashAlg = SHA1()
message = 'abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq'
message_digest = 0x84983E44L, 0x1C3BD26EL, 0xBAAE4AA1L, 0xF95129E5... | assert( hashAlg(message) == md_string ), 'FIPS180 Appendix B test Failed'
def testFIPS180_1_Appendix_C(self):
""" APPENDIX C. A THIRD SAMPLE MESSAGE AND ITS MESSAGE DIGEST
Let the message be the binary-coded form of the ASCII string which consists
of 1,000,000 repetitions of "a". """
... |
BadSingleton/pyside2 | tests/QtCore/bug_931.py | Python | lgpl-2.1 | 648 | 0.00463 | import unittest
from PySide2.QtCore import QObject, Signal
o = QObject()
class MyObject(QObject):
s = Signal(int)
class CheckSignalType(unittest.TestCase):
def testSignal(self):
self.assertTrue(isinstance(QObject.destroyed, Signal))
self.assertEqual(type(QObject.destroyed), Signal)
se... | self.assertTrue(isinstance(o.d | estroyed, Signal))
self.assertTrue(isinstance(MyObject.s, Signal))
self.assertFalse(isinstance(int, Signal))
if __name__ == '__main__':
unittest.main()
|
lefred/MyUndelete | MyUndelete.py | Python | gpl-2.0 | 11,156 | 0.025099 | #!/usr/bin/python
#
# MyUndelete.py - MySQL undelete from ROW base binary logs
#
# Author : Frederic -lefred- Descamps <lefred@lefred.be>
# Version: 0.3
# Date : 2018-01-05
#
# Use with care
#
# License: GPLv2 (c) Frederic Descamps
import os
import base64
import sys, getopt
import subprocess
import tempfile
import... | t()
p4.wait()
print "Done... I hope it worked ;)"
sys.exit(0)
else:
print "Bye...bye... my data"
if found_update:
print "We got an update!!"
# let's consider that the PK is always on one binlog line
# check that we have current... | he right binlog line
if base64.b64decode(binlog_event[0])[31] != "\xff":
print "ERROR: problem parsing binary log header"
sys.exit(5)
# find the "marker" and the PK
to_find = base64.b64decode(binlog_event[0])[32]
# let's concatenate to create the full binlog
bin... |
pfalcon/micropython | tools/codeformat.py | Python | mit | 6,422 | 0.00218 | #!/usr/bin/env python3
#
# This file is part of the MicroPython project, http://micropython.org/
#
# The MIT License (MIT)
#
# Copyright (c) 2020 Damien P. George
# Copyright (c) 2020 Jim Mussared
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated document... | f format_c:
command = ["uncrustify", "-c", UNCRUSTIFY_CFG, "-lC", "--no-backup"]
if not args.v:
command.append("-q")
batch(command, lang_files(C_EXTS))
for file in lang_files(C_EXTS):
fixup_c(file)
# | Format Python files with black.
if format_py:
command = ["black", "--fast", "--line-length=99"]
if args.v:
command.append("-v")
else:
command.append("-q")
batch(command, lang_files(PY_EXTS))
if __name__ == "__main__":
main()
|
jugonzalez/topology_lib_scapy | doc/conf.py | Python | apache-2.0 | 10,608 | 0.000189 | # -*- coding: utf-8 -*-
#
# scapy Communication Library for Topology documentation build configuration file.
#
# 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 configuration values hav... | lts to
# "<project> v<release> documentation".
# html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
# html_shor | t_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
# html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
# html_favicon = N... |
kuri-kustar/haptic_interface-project | manipulation/mitsubishi_arm_hardware_interface/scripts/writeJointRos.py | Python | gpl-3.0 | 1,782 | 0.030303 | #!/usr/bin/env python
import roslib;
import rospy
import serial
import time
#COM.baudrate=115200
#!/usr/bin/env python
import rospy
from sensor_msgs.msg import JointState
global COM
def callback(data):
rospy.loginfo(rospy.get_caller_id()+"I heard %s",data.position)
global COM
buffer=[]
j =[0.7,0.5,... | print COM
buffer = []
#r=rospy.Rate(10) # 10 hz
COM.write("1\r\n") # tells slave to init
r=rospy.Rate(10) # 10 hz
while rospy.is_shutdown()==False:
| r.sleep()
# spin() simply keeps python from exiting until this node is stopped
#rospy.spinOnce()
if __name__ == '__main__':
listener()
if __name__=="__main__":
rospy.init_node('cyber_glove_teleop')
init_pos=[0.5,0.5,0.0,0.2,-0.4,1.5]
|
bigfatpanda-training/pandas-practical-python-primer | training/level-2-command-line-interfaces/bfp-reference/exercise_09/file_ops.py | Python | artistic-2.0 | 612 | 0 | """
This modules provides various functions for operating on files.
Functions:
copy_files: Copy file(s) to a specified location.
"""
imp | ort subprocess
def copy_files(files: list, destination: str):
"""
Copy files to a given destination.
Args:
files: A list of files to copy.
destination: A str specifying the destination for copied
files.
"""
for file in files:
operation_result = subprocess.chec... | 'cp', '-vp', file, destination],
stderr=subprocess.STDOUT)
print(operation_result.decode().rstrip())
|
bow/fsnviz | fsnviz/fusioncatcher.py | Python | bsd-3-clause | 2,336 | 0 | # -*- coding: utf-8 -*-
"""
fsnviz.fusioncatcher
~~~~~~~~~~~~~~~~~~~~
FusionCatcher output plotting.
:copyright: (c) 2016 Wibowo Arindrarto <bow@bow.web.id>
:license: BSD
"""
from crimson.fusioncatcher import parse
from .models import CircosEntry, CircosLabel, CircosLink, FusionToolResults
from ... | nsf)
sfB = CircosLabel(rchrom, right["position"], right["position"] + 1,
nsf)
return CircosEntry(link, [gene | A, geneB], [jrA, jrB], [sfA, sfB])
@property
def circos_entries(self):
if not hasattr(self, "_circos_entries"):
entries = [self._make_circos_entry(x) for x in self.payload]
self._circos_entries = list(filter(None, entries))
return self._circos_entries
|
redhat-openstack/manila | manila/share/driver.py | Python | apache-2.0 | 45,808 | 0 | # Copyright 2012 NetApp
# Copyright 2015 Mirantis inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#... | "to look for network config options."
"If not set, the share backend's config group will be used."
"If an option is not found within provided group, then"
"'DEFAULT' | group will be used for search of option."),
cfg.BoolOpt(
'driver_handles_share_servers',
help="There are two possible approaches for share drivers in Manila. "
"First is when share driver is able to handle share-servers and "
"second when not. Drivers can support either bot... |
JConwayAWT/PGSS14CC | lib/python/multimetallics/ase/cluster/cubic.py | Python | gpl-2.0 | 1,732 | 0.005196 | """
Function-like objects that creates cubic clusters.
"""
import numpy as np
from ase.data import reference_states as _refstate
from ase.cluster.factory import ClusterFactory
class SimpleCubicFactory(ClusterFactory):
spacegroup = 221
xtal_name = 'sc'
def get_lattice_constant(self):
"Get the la... | "structure %s." % (symmetry,))
return _refstate[self.atomic_numbers[0]]['a']
def set_basis(self):
a = self.lattice_constant
if not isinstance(a, (int, float)):
raise ValueError("Improper lattice constant for %s crystal." % (self.xtal_name | ,))
self.lattice_basis = np.array([[a, 0., 0.],
[0., a, 0.],
[0., 0., a]])
self.resiproc_basis = self.get_resiproc_basis(self.lattice_basis)
SimpleCubic = SimpleCubicFactory()
class BodyCenteredCubicFactory(SimpleCubicFact... |
vegarang/devilry-django | devilry/apps/core/models/deliverytypes.py | Python | bsd-3-clause | 187 | 0.005348 | ELECTRON | IC = 0
NON_ELECTRONIC = 1
ALIAS = 2
def as_choices_tuple():
return ((ELECTRONIC, 'Electronic'),
(NON_ELECTRONIC, 'Non electronic'),
(ALIAS, 'Alias'))
| |
guigeek208/clickdial | ui_mainwindow.py | Python | gpl-3.0 | 4,125 | 0.034909 | # -*- coding: latin-1 -*-
from PyQt4 import QtCore, QtGui
import platform, shutil
import os
from ui_vboxlogin import Ui_VBoxLogIn
from ui_parambox import Ui_ParamBox
class Ui_MainWindow(QtGui.QMainWindow):
def __init__(self, debug, parent=None):
#super(Ui_clickdial, self).__init__()
self.debug = debug
if (self.... | _CONTACTS == 1):
self.vbox_main.load_directoryoutlook()
for i in range(len(self.vbox_main.click.OUTLOOK_CONTACTS_SHARED)):
self.vbox_main.loa | d_directoryoutlookSharedContacts(self.vbox_main.treeList_directoryoutlookcontactsshared[i], self.vbox_main.click.OUTLOOK_CONTACTS_SHARED[i])
# self.vbox_main.click.OUTLOOK = 0
# else:
# self.vbox_main.click.OUTLOOK = 1
if (val == 100):
self.vbox_main.load_history()
self.vbox_main.displayDirectoryEnts... |
levinas/assembly | lib/assembly/arastd.py | Python | mit | 4,544 | 0.003301 | #! /usr/bin/env python
"""
Arast Daemon
The Arast daemon runs on the control node.
"""
import argparse
import sys
import signal
import daemon
import logging
import lockfile
import multiprocessing
import os
import pymongo
import pika
import router
from ConfigParser import SafeConfigParser
import shock
import cloud
#... | ment("--mongo-host", help="specify the mongodb url",
action="store")
parser.add_argument("--mongo-port", help="specify the mongodb port",
action="store")
| parser.add_argument("--rabbit-host", help="specify the rabbitmq url",
action="store")
parser.add_argument("--rabbit-port", help="specify the rabbitmq port",
action="store")
parser.add_argument("--logfile", help="specify the logfile",
action="store")
parser.add... |
zhimin711/nova | nova/tests/unit/cells/test_cells_weights.py | Python | apache-2.0 | 9,003 | 0.000111 | # Copyright (c) 2012 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless ... | self.assertTrue(len(weighers) >= 2)
class_names = [cls.__name__ for cls in weighers]
self.assertIn('WeightOffsetWeigher', class_names)
self.assertIn('RamByInstanceTypeWeigher', class_names)
class _WeigherTestClass(test.NoDBTestCase):
"""Base cla | ss for testing individual weigher plugins."""
weigher_cls_name = None
def setUp(self):
super(_WeigherTestClass, self).setUp()
self.weight_handler = weights.CellWeightHandler()
weigher_classes = self.weight_handler.get_matching_classes(
[self.weigher_cls_name])
se... |
SUSE/azure-sdk-for-python | azure-mgmt-datalake-analytics/azure/mgmt/datalake/analytics/catalog/models/usql_view_paged.py | Python | mit | 874 | 0 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | s
# regenerated.
# --------------------------------------------------------------------------
from msrest.paging import Paged
class USqlViewPaged(Paged):
"""
A paging container for iterating over a list of USqlView object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'}... | __(*args, **kwargs)
|
PaulWay/insights-core | insights/parsers/dumpe2fs_h.py | Python | apache-2.0 | 2,755 | 0.001089 | """
DumpE2FS - Command ``dumpe2fs -h``
==================================
This parser handles ``dumpe2fs`` output.
The object provides access to this data using a dictionary. Particular keys
are stored as lists:
* Filesystem features
* Filesystem flags
* Default mount options
Other keys are stored as strings. The... | UID: | 1b332c5d-2410-4934-9118-466f8a14841f
Filesystem magic number: 0xEF53
Filesystem revision #: 1 (dynamic)
Filesystem features: has_journal ext_attr resize_inode dir_index filetype needs_recovery extent flex_bg sparse_super large_file huge_file uninit_bg dir_nlink extra_isize
Filesystem f... |
tomviner/pytest-django | pytest_django/fixtures.py | Python | bsd-3-clause | 12,082 | 0 | """All pytest-django fixtures"""
from __f | uture__ import with_statement
import os
import warnings
import pytest
from . import live_server_helper
from .db_reuse import (monkey_patch_creation_for_db_reuse,
monkey_patch_creation_for_db_suffix)
from .django_compat import is_django_unittest
from .lazy_django import get_django_version, skip... | ll__ = ['_django_db_setup', 'db', 'transactional_db', 'admin_user',
'django_user_model', 'django_username_field',
'client', 'admin_client', 'rf', 'settings', 'live_server',
'_live_server_helper']
# ############### Internal Fixtures ################
@pytest.fixture(scope='session')
de... |
sebrandon1/neutron | neutron/tests/unit/services/trunk/drivers/linuxbridge/agent/test_driver.py | Python | apache-2.0 | 11,541 | 0 | #
# Licensed under the Apache L | icense, 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
# distr | ibuted 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 mock
import oslo_messaging
from oslo_utils import uuidutils
import test... |
yaybu/touchdown | touchdown/provisioner/output.py | Python | apache-2.0 | 2,488 | 0.000804 | # Copyright 2015 Isotoma Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may | not use this file e | xcept 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, eit... |
adieyal/ghwa_profiles | server/server.py | Python | apache-2.0 | 2,916 | 0.00583 | import sys
import json
import flask
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.cors import origin
from parse import ProfileParser, IHMEParser
from flask import render_template
from flask import Response
from werkzeug.contrib.fixers import ProxyFix
app = Flask(__name__)
app.confi... | sion.add(d)
db.session.commit()
@app.route("/api/profiles", methods=["GET", "POST"])
@origin('*')
def api_profiles():
country = flask.request.values["country"]
values = dict([
(v.code, v.value) for v in Value.query.filter_by(country=country) if v.code
])
return Response(
response=j... | es, indent=4), status=200, mimetype="application/json"
)
@app.route("/api/daly", methods=["GET", "POST"])
@origin('*')
def api_daly():
country = flask.request.values["country"]
values = [
{
"rank" : v.rank, "text" : v.cause,
"value" : v.perc, "color" : v.color
} for... |
shengwen1994/calvin-base | calvin/runtime/south/plugins/transports/transport_base.py | Python | apache-2.0 | 1,349 | 0 | # -*- coding: utf-8 -*-
# Copyright (c) 2015 Ericsson AB
#
# 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 ... | buted 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.
class TransportServerBase(object):
def __init__(self, *args, **kwargs):
... | client_callback is a function taking a TransportBase
when a client is connecting.
"""
pass
def stop(self):
"""
Stops server.
"""
pass
class TransportBase(object):
def __init__(self, *args, **kwargs):
pass
def disconnect(self)... |
jkyeung/XlsxWriter | xlsxwriter/test/comparison/test_comment08.py | Python | bsd-2-clause | 1,363 | 0 | ###############################################################################
#
# Tests for XlsxWriter.
#
# Copyright (c), 2013-2016, John McNamara, jmcnamara@cpan.org
#
from ..excel_comparsion_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompareXLSXFiles(ExcelComparisonTest):
"""... | rksheet()
worksheet.write_comment('A1', 'Some text')
worksheet.write_comment('A2', 'Some text')
worksheet.write_comment('A3', 'Some text', {'visible': False})
| worksheet.write_comment('A4', 'Some text', {'visible': True})
worksheet.write_comment('A5', 'Some text')
worksheet.show_comments()
worksheet.set_comments_author('John')
workbook.close()
self.assertExcelEqual()
|
ruthfranklin/hande | tools/pyblock/pyblock/pd_utils.py | Python | lgpl-2.1 | 7,847 | 0.001912 | '''Pandas-based wrapper around :mod:`pyblock.blocking`.'''
# copyright: (c) 2014 James Spencer
# license: modified BSD license; see LICENSE for further details.
import numpy
import pandas as pd
import pyblock.blocking
def reblock(data, axis=0, weights=None):
'''Blocking analysis of correlated data.
Parameters
-... | taFrame.
# 'optimal block' is in the innermost level.
level = block_sub_info.columns.nlevels - 1
opt_cols = [col == 'optimal block'
for col in block_sub_info.columns.get_level_values(level)]
if not any(opt_cols):
raise ValueError('No optimal block data')
... | or:
col_opt = col[col != ''].index
if len(col_opt) == 0:
opt = float('inf')
elif len(col_opt) == 1:
opt = max(col_opt[0], opt)
else:
raise ValueError('Multiple entries listed as optimal.')
return opt
def reblock_summary(block_sub_info):
'''Ge... |
tiankangkan/paper_plane | treasure/admin.py | Python | gpl-3.0 | 155 | 0.006452 | # | -*- coding: utf-8 -*-
from django.contrib import admin
from models import FileMapping
# Register your models here.
admi | n.site.register(FileMapping)
|
ljnissen/shop_engine | mingw/lib/gcc/mingw32/4.5.2/libstdc++.dll.a-gdb.py | Python | mit | 2,316 | 0.006908 | # -*- python -*-
# Copyright (C) 2009 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
... | os.path.dirname (prefix) + '/'
# Strip off the prefix.
pythondir = pythondir[len (prefix):]
libdir = libdir[len (prefix):]
# Compute the ".."s needed to get from libdir to the prefix.
dotdots = ('..' + os.sep) * | len (libdir.split (os.sep))
objfile = gdb.current_objfile ().filename
dir = os.path.join (os.path.dirname (objfile), dotdots, pythondir)
if not dir in sys.path:
sys.path.insert(0, dir)
# Load the pretty-printers.
from libstdcxx.v6.printers import register_libstdcxx_printers
register_libstdcxx_pri... |
mschex1/pokedex | pokedex/db/load.py | Python | mit | 15,992 | 0.001251 | """CSV to database or vice versa."""
from __future__ import print_function
import csv
import fnmatch
import io
import os.path
import sys
import six
import sqlalchemy.sql.util
import sqlalchemy.types
import pokedex
from pokedex.db import metadata, tables, translations
from pokedex.defaults import get_default_csv_dir
... | pattern))
else:
table_names = metadata.tables.keys()
return list(table_names)
def _get_verbose_prints(verbose):
"""If `verbose` is true, returns three functions: one for printing a
starting message, one for printing an interim status update, and one for
printing a success or failure messag... | op functions.
"""
if not verbose:
# Return dummies
def dummy(*args, **kwargs):
pass
return dummy, dummy, dummy
### Okay, verbose == True; print stuff
def print_start(thing):
# Truncate to 66 characters, leaving 10 characters for a success
# or fail... |
lab2112/pretix | src/pretix/base/settings.py | Python | apache-2.0 | 7,483 | 0.000802 | import decimal
import json
from datetime import date, datetime, time
import dateutil.parser
from django.conf import settings
from django.db.models import Model
from versions.models import Versionable
DEFAULTS = {
'user_mail_required': {
'default': 'False',
'type': bool
},
'max_items_per_or... | date': {
'default': None,
'type': datetime
},
'contact_mail': {
'default': None,
'type': str
},
'imprint_url': {
' | default': None,
'type': str
},
'mail_prefix': {
'default': None,
'type': str
},
'mail_from': {
'default': settings.MAIL_FROM,
'type': str
}
}
class SettingsProxy:
"""
This objects allows convenient access to settings stored in the
EventSettings/O... |
pwcazenave/PyFVCOM | tests/preproc.py | Python | mit | 9,048 | 0.004752 | import os
import tempfile
import numpy.testing as test
import numpy as np
from unittest import TestCase
from datetime import datetime
from dateutil.relativedelta import relativedelta
from PyFVCOM.preproc import Model
from PyFVCOM.grid import write_sms_mesh
from PyFVCOM.utilities.time import date_range
class PrePro... | 547376,
-0.334109785567378, -0.665890214432622, -0.887849998452624, -0.969179683481321,
-0.992057763815731, -0.997988573338161, -0.999492857348489, - | 0.999872278839825,
-0.999967844396741, -0.999991906106309, -0.999997963875049, -0.999999488942708,
-0.99999987288245, -0.999999969540139, -0.999999993873919, -1])
sigma_levels = self.model.sigma_generalized(30, 10, 10, self.model.grid.h[50], 5)... |
Onager/plaso | tests/parsers/setupapi.py | Python | apache-2.0 | 4,841 | 0.001239 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Tests for the Windows Setupapi log parser."""
import unittest
from plaso.parsers import setupapi
from tests.parsers import test_lib
class SetupapiLogUnitTest(test_lib.ParserTestCase):
"""Tests for the Windows Setupapi log parser.
Since Setupapi logs record in ... | ': '2016-10-05 11:16:16.471000'}
self.CheckEventValues(storage_writer, events[4], expected_event_values)
expected_event_values = {
| 'data_type': 'setupapi:log:line',
'entry_type': (
'Device Install (DiInstallDriver) - C:\\Windows\\System32'
'\\DriverStore\\FileRepository\\prnms003.inf_x86_8f17aac186c70ea6'
'\\prnms003.inf'),
'exit_status': 'SUCCESS',
'timestamp': '2016-10-12 03:36:30... |
Azure/azure-sdk-for-python | sdk/cognitiveservices/azure-cognitiveservices-language-luis/azure/cognitiveservices/language/luis/runtime/models/_models.py | Python | mit | 11,988 | 0.000334 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | :type request_lists:
list[~azure.cognitiveservices.language.luis.runtime.models.RequestList]
"""
_validation = {
'list_entity_name': {'required': True},
'request_lists': {'required': True},
}
_attribute_map = {
'list_entity_name': {'key': 'listEntityName', 'type': 'str'... | **kwargs):
super(DynamicList, self).__init__(**kwargs)
self.list_entity_name = kwargs.get('list_entity_name', None)
self.request_lists = kwargs.get('request_lists', None)
class Error(Model):
"""Represents the error that occurred.
All required parameters must be populated in order to s... |
duke605/RunePy | commands/stats.py | Python | mit | 3,080 | 0.001948 | from util.runescape_util import get_users_stats, get_level_at_exp
from util.ascii_table import Table, Column
from util.image_util import text_to_image
from discord.ext import commands
from util.arguments import Arguments
from shlex import split
class Stats:
def __init__(self, bot):
self.bot = bot
@c... | ='store_true',
help='Displays the table as an image. (Useful for mobile)')
await self.bot.send_typing(ctx.message.channel)
try:
args = parser.parse_args(split(msg))
except Syste | mExit:
await self.bot.say('```%s```' % parser.format_help())
return
except Exception as e:
await self.bot.say('```%s```' % str(e))
return
args.name = ' '.join(args.name)
await self.execute(args)
async def execute(self, args):
stats =... |
nextml/NEXT | next/broker/celery_app/__init__.py | Python | apache-2.0 | 28 | 0 | from | celery_broker imp | ort *
|
TimeWz667/Kamanian | example/OOP/O2.4 SS, Single agent model.py | Python | mit | 446 | 0 | import complexism as | cx
import complexism.agentbased.statespace as ss
import epidag as dag
d | bp = cx.read_dbp_script(cx.load_txt('../scripts/SIR_BN.txt'))
pc = dag.quick_build_parameter_core(cx.load_txt('../scripts/pSIR.txt'))
dc = dbp.generate_model('M1', **pc.get_samplers())
ag = ss.StSpAgent('Helen', dc['Sus'], pc)
model = cx.SingleIndividualABM('M1', ag)
model.add_observing_attribute('State')
print(cx.s... |
richpolis/siveinpy | SiveinPy/apps/autores/models.py | Python | mit | 282 | 0.028369 | from django.db import models
class Aut | or(models.Model):
nombre = models.CharField(max_length=50)
pais = models.CharField(max_length=50)
descripcion = models.TextField(max_length=200)
foto = models.ImageField(upload_to='foto_au | tor')
def __unicode__(self):
return self.nombre |
glasnt/voc | tests/builtins/test_chr.py | Python | bsd-3-clause | 340 | 0 | from .. utils import TranspileTestCase, BuiltinFunctionTestCase
class ChrTests(TranspileTestCase):
pass
class BuiltinChrFunctionTests(BuiltinFunctionTe | stCase, TranspileTestCase):
functions = ["chr"]
not_implemented = [
'test_bytearray',
| 'test_class',
'test_complex',
'test_frozenset',
]
|
avedaee/DIRAC | RequestManagementSystem/DB/RequestDB.py | Python | gpl-3.0 | 26,378 | 0.031617 | ########################################################################
# $HeadURL $
# File: RequestDB.py
# Author: Krzysztof.Ciba@NOSPAMgmail.com
# Date: 2012/12/04 08:06:30
########################################################################
""" :mod: RequestDB
=======================
.. module: Request... | tionID == 0:
operation.OperationID = lastrowid
filesToSQL = [ opFile.toSQL()["Value"] for opFile in operation ]
if filesToSQL:
putFiles = self._transaction( filesToSQL )
if not putFiles["OK"]:
self.log.error( "putRequest: unable to put files for operation %d: %s" % ( reques... | s["Message"] ) )
if isNew:
deleteRequest = self.deleteRequest( request.requestName )
if not deleteRequest["OK"]:
self.log.error( "putRequest: unable to delete request '%s': %s"\
% ( request.RequestName, deleteRequest["Message"] ) )
... |
jrgdiz/cardwalker | grammar/constants/zones/decl.py | Python | mit | 143 | 0.006993 | from pyparsing import *
TOP = Forward()
BOTT | OM = Forward()
HAND = Forward()
GRAVEYARD = Forward()
LIBRARY = Forward()
BATTLEFIELD = Forward() | |
agiliq/Dinette | dinette/migrations/0005_unique_profiles.py | Python | bsd-3-clause | 9,643 | 0.009644 |
from south.db import db
from django.db import models
from dinette.models import *
class Migration:
def forwards(self, orm):
# Creating unique_together for [user] on DinetteUserProfile.
db.create_unique('dinette_dinetteuserprofile', ['user_id'])
def backwards(se... | ey': 'True'}),
'name': ('django. | db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'fi... |
bbengfort/flashcube | flashcube/console/color/__init__.py | Python | apache-2.0 | 1,580 | 0.005696 | # flashcube.console.color
# Sets up a terminal color scheme-- learned from Django.
#
# | Author: Benjamin Bengfort <benjamin@bengfort.com>
# Created: Fri Oct 16 20:55:26 2015 -0400
#
# Copyright (C) 2015 Bengfort.com
# For license informatio | n, see LICENSE.txt
#
# ID: __init__.py [] benjamin@bengfort.com $
"""
Sets up a terminal color scheme-- learned from Django.
"""
##########################################################################
## Imports
##########################################################################
import os
import sys
import... |
inklesspen/montague | src/montague/exceptions.py | Python | mit | 191 | 0 | from __future__ import absolute_import
class ConfigNotFound(LookupError):
"""Raise | this exception to signal th | at a requested config item
was not found in the config."""
pass
|
hassanibi/erpnext | erpnext/accounts/doctype/depreciation_schedule/depreciation_schedule.py | Python | gpl-3.0 | 286 | 0.006993 | # -*- | coding: utf-8 -*-
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
class D | epreciationSchedule(Document):
pass
|
sgmap/openfisca-web-api | openfisca_web_api/controllers/reforms.py | Python | agpl-3.0 | 2,088 | 0.021073 | # -*- coding: utf-8 -*-
"""Reforms controller"""
import collections
from .. import contexts, conv, model, wsgihelpers
@wsgihelpers.wsgify
def api1_reforms(req):
ctx = contexts.Ctx(req)
headers = wsgihelpers.handle_cross_origin_resource_sharing(ctx)
assert req.method == 'GET', req.method
params =... | method = req.script_name,
params = inputs,
url = req.url.decode('utf-8'),
).iteritems())),
headers = headers,
)
build_reform_function_by_key = model.build_reform_function_by_key
declared_reforms_key = build_reform_function_by_key.key... | eform_key, reform in model.reform_by_full_key.iteritems()
}.iteritems())) if declared_reforms_key is not None else None
return wsgihelpers.respond_json(ctx,
collections.OrderedDict(sorted(dict(
apiVersion = 1,
context = data['context'],
method = req.script_name,
... |
davidwtbuxton/captain-pasty | pasty/tests/test_models.py | Python | mit | 4,489 | 0 | import datetime
import unittest
from django.http import Http404
from . import AppEngineTestCase
from pasty.models import LexerConfig, Paste, PastyFile, make_relative_path
class PasteTestCase(AppEngineTestCase):
def test_unicode(self):
obj = Paste(author='alice@example.com', filename='example.txt')
... | mas = datetime.datetime(2016, 12, 25)
orig_key = Paste(id=1234, created=xmas).put()
fork = Paste(id=5678, created=xmas, fork=orig_key)
fork.put()
result = fork.to_dict()
self.assertEqual(
result,
{
u'author': None,
u'creat... | u'filename': 'untitled.txt',
u'files': [],
u'fork': 1234,
u'id': 5678,
u'num_files': 0,
u'num_lines': 0,
u'preview': None,
u'url': u'/5678/',
},
)
def test_highlight_conte... |
rohitranjan1991/home-assistant | tests/components/analytics/test_init.py | Python | mit | 1,428 | 0.002101 | """The tests for the analytics ."""
from unittest.mock import patch
from homeassistant.components.analytics.const import ANALYTICS_ENDPOINT_URL, DOMAIN
from homeassistant.setup import async_setup_component
MOCK_VERSION = "1970.1.0"
async def test_setup(hass):
"""Test setup of the integration."""
assert awai... | nse["success"]
with patch("homeassistant.components.analytics.analytics.HA_VERSION" | , MOCK_VERSION):
await ws_client.send_json(
{"id": 2, "type": "analytics/preferences", "preferences": {"base": True}}
)
response = await ws_client.receive_json()
assert len(aioclient_mock.mock_calls) == 1
assert response["result"]["preferences"]["base"]
await ws_client.s... |
yast/yast-python-bindings | examples/AutoShortcut1.py | Python | gpl-2.0 | 1,568 | 0.012117 | #!/usr/bin/env python
# encoding: utf-8
from yast import import_module
import_module('UI')
from yast import | *
class AutoShortcut1Client:
def main(self):
# (Minimalistic) Demo for automatically generated shortcuts.
#
# See 'AutoShortcut2.ycp' for a more realistic example.
#
# Please note this is _not_ how this option is meant to be used:
# It is intended for automatically generated da... | dgets.
# If you know your widget label at this point, manually add a keyboard
# shortcut; this will almost always be much better than anything what can
# be automatically generated.
#
#
# There shouldn't be any complaints about shortcuts in the log file when this is started.
U... |
tokyo-jesus/aniracetam | example/polls/wsgi.py | Python | apache-2.0 | 96 | 0 | # -*- codi | ng: utf-8 -*-
from aniracetam import Application
app = Application('poll.settings')
| |
leapp-to/snactor | examples/scripts/output_processors.py | Python | apache-2.0 | 493 | 0 | """ Sample script to test output processors """
from generic_runner import run, pprint, get_actor
def test_output_processors():
""" Execute iplist actor to test output processors """
data = {}
print("Before execution")
print("=" * 70)
pprint( | data)
print("=" * 70)
print("Execution result:",
get_actor('iplist').execute(data))
print("=" * 70)
print("After execution")
pprint(data)
if __name__ == '__main__':
run(test_o | utput_processors)
|
hackoregon/team-budget | budget_proj/budget_app/views.py | Python | mit | 5,220 | 0.007854 | # include for aggregation
from django.db.models import Case, IntegerField, Sum, Value, When
from django.db.models import CharField
# ------------------------------------------
# imports needed for the functional view
from rest_framework.response import Response
# ------------------------------------------
# ----------... | -------------------------
LA_Bureaus = ['MF']
EO_Bureaus = ['MY', 'PA', 'PS', 'PW', 'PU', 'AU']
class ListOcrb(generics.ListAPIView):
"""
Operating and Capital Requirements by Bureau (OCRB).
Note: Parameter values are compared case-insensitive.
"""
| serializer_class = serializers.OcrbSerializer
filter_class = filters.OcrbFilter
def get_queryset(self):
return models.OCRB.objects.order_by('-fiscal_year', 'budget_type', 'service_area', 'bureau', 'budget_category')
class OcrbSummary(generics.ListAPIView):
"""
Summarize Budget for Operati... |
Nablaquabla/csi-analysis | hcdataCalculateSpectra.py | Python | gpl-3.0 | 5,369 | 0.006333 | #!/usr/bin/env python
import os
import time as tm
# Main function handling all internals
# -----------------------------------------------------------------------------
def main():
mainDir = '/data2/coherent/data/csi/bjs-analysis/Processed/'
outDir = '/data2/coherent/data/csi/bjs-analysis/Processed/Analyzed/'
... | 'Run-16-08-30-11-37-42','Run-16-09-06-15-23-15',
'Run-16-09-15-15-23-58','Run-16-09-26-15-34-10' | ,
'Run-16-10-04-16-48-32','Run-16-10-07-15-32-53',
'Run-16-10-18-14-36-17','Run-16-11-02-18-39-29',
'Run-16-11-04-11-08-14','Run-17-02-02-15-26-34',
'Run-17-02-02-17-28-46','Run-17-02-08-16-39-02',
'Run-17-02-08-21-55-48','Run-17-02-21-12-39-17'... |
Arvin-X/swarm | lib/utils/banner.py | Python | gpl-3.0 | 334 | 0.020958 | #!/usr/bin/env python
# | -*- coding: utf-8 -*-
import time
timeformat='% | H:%M:%S'
def begin_banner():
print ''
print '[*] swarm starting at '+time.strftime(timeformat,time.localtime())
print ''
def end_banner():
print ''
print '[*] swarm shutting down at '+time.strftime(timeformat,time.localtime())
print '' |
Nakrez/RePy | tests/parser/good/file.py | Python | mit | 229 | 0 | my_file = open("/tmp/my_file", "w")
my_file.write("Test string")
my_file.close()
my_file = open("/tmp/my_fil | e", "r")
content = my_file.read()
my_file.close()
if (content == "Test string"):
print("OK")
else:
print("KO") | |
cloudtools/awacs | awacs/app_integrations.py | Python | bsd-2-clause | 1,748 | 0.000572 | # Copyright (c) 2012-2021, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from .aws import Action as BaseAction
from .aws import BaseARN
service_name = "Amazon AppIntegrations"
prefix = " | app-integrations"
class Action(BaseAction):
def __init__(self, action: str = None) -> None:
super().__init__(prefix, action)
class ARN(BaseARN):
def __init__(self, resource: str = "", region: str = "", account: str = "") -> None:
super().__init__(
service=prefix, resource=resourc... | )
CreateDataIntegration = Action("CreateDataIntegration")
CreateDataIntegrationAssociation = Action("CreateDataIntegrationAssociation")
CreateEventIntegration = Action("CreateEventIntegration")
CreateEventIntegrationAssociation = Action("CreateEventIntegrationAssociation")
DeleteDataIntegration = Action("Delet... |
YoApp/yo-water-tracker | server.py | Python | mit | 1,851 | 0.001082 | # -*- coding: utf-8 -*-
"""
"""
from datetime import datetime, timedelta
import os
from flask import request
from flask import Flask
import pytz
impo | rt db
from utils import get_remote_addr, get_location_data
app = Flask(__name__)
@app.route('/yo-water/', methods=['POST', 'GET'])
def yowater():
payload = request.args if request.args else request.get_json(force=True)
username = payload.get('username')
reminder = db.reminders.find_one({'username': us... | = get_remote_addr(request)
data = get_location_data(address)
if not data:
return 'Timezone needed'
user_data = {'created': datetime.now(pytz.utc),
'username': username}
if data.get('time_zone'):
user_data.update({... |
SteveDiamond/cvxpy | cvxpy/reductions/eliminate_pwl/atom_canonicalizers/cumsum_canon.py | Python | gpl-3.0 | 983 | 0 | """
Copyright 2013 Steven Diamond
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... | ied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from cvxpy.expressions.variable import Variable
def cumsum_canon(expr, args):
"""Cumulative sum.
"""
X = args[0]
axis = expr.axis
# Implicit O(n) definition:
# X = Y[1:,:] - Y[:-1, :]
... | else:
constr = [X[:, 1:] == Y[:, 1:] - Y[:, :-1], Y[:, 0] == X[:, 0]]
return (Y, constr)
|
pthierry38/openscap-daemon | openscap_daemon/cve_scanner/scanner_error.py | Python | lgpl-2.1 | 913 | 0 | # Copyright (C) 2015 Brent Baude <bbaude@redhat.com>
# Copyright (C) 2015 Red Hat Inc., Durham, North Carolina.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Less | er General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library 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 PART... | c License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with openscap-daemon. If not, see <http://www.gnu.org/licenses/>.
import dbus
class ImageScannerClientError(dbus.DBusException):
"""ImageScanner error"""
dbus_error_name = 'org.atomic.Exception'... |
MengGuo/P_MAS_TG | Intro/Examples/NAO_example.py | Python | gpl-2.0 | 2,441 | 0.03687 | # -*- coding: utf-8 -*-
from ts import MotionFts, ActionModel, MotActModel
from planner import ltl_planner
import time
###############################
################# initialize NAO_motion
colormap = {'ball':'red', 'obs':'black','basket':'yellow'}
symbols = colormap.keys()
WIDTH = 2400 # mm
HEIGHT = 2100 # mm
N =... | _motion.set_initial(init_pose)
edge_list = [ # 1st column
((WIDTH*RATE,HEIGHT*RATE), (WIDTH*RATE,HEIGHT*3*RATE)),
((WIDTH*RATE,HEIGHT*3*RATE), (WIDTH*RATE,HEIGHT*5*RATE)),
# 2nd row
((WIDTH*RATE,HEIGHT*3*RATE), (WIDTH*3*RATE,HEIGHT*3*RATE)),
((WIDTH*3*RATE | ,HEIGHT*3*RATE), (WIDTH*5*RATE,HEIGHT*3*RATE)),
# 2nd column
((WIDTH*3*RATE,HEIGHT*RATE), (WIDTH*3*RATE,HEIGHT*3*RATE)),
((WIDTH*3*RATE,HEIGHT*3*RATE), (WIDTH*3*RATE,HEIGHT*5*RATE)),
# 3rd column
((WIDTH*5*RATE,HEIGHT*RATE), (WIDTH*5*RATE,HEIGHT*3*RATE)),
((WIDTH*5*RATE,HEIGHT*3*RATE), (WIDTH*5*... |
Azure/azure-sdk-for-python | sdk/remoterendering/azure-mixedreality-remoterendering/azure/mixedreality/remoterendering/_shared/aio/mixedreality_account_key_credential.py | Python | mit | 2,073 | 0.001447 | # --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
from typi... | ken
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from typing import Any
from azure.core.credentials import AzureKeyCredential
ACCOUNT_KEY_VALID_YEARS = 10
class MixedRealityAccountKey | Credential(object):
""" Represents an object used for Mixed Reality account key authentication.
:param str account_id: The Mixed Reality service account identifier.
:param AzureKeyCredential account_key: The Mixed Reality service account primary or secondary key credential.
"""
def __init__(self, ... |
jawilson/Flexget | flexget/tests/test_utils.py | Python | mit | 3,596 | 0.000556 | from __future__ import unicode_literals, division, absolute_import
from builtins import * # noqa pylint: disable=unused-import, redefined-builtin
from datetime import datetime
import math
import pytest
from flexget.utils import json
from flexget.utils.tools import parse_filesize, split_title_year
def compare_floa... | date_obj = {'date': dt}
encoded_dt = json.dumps(date_obj, encode_datetime=True)
assert encoded_dt == '{"date": "%s"}' % date_str
def test_json_decode_dt(self):
date_str = '"2016-03-11T17:12:17Z"'
dt = datetime.strptime(date_str, '"%Y-%m-%dT%H:%M:%SZ"')
decoded_dt = json.loa... | (self):
date_str = '"2016-03-11T17:12:17Z"'
date_obj_str = '{"date": %s}' % date_str
decoded_dt = json.loads(date_obj_str, decode_datetime=True)
dt = datetime.strptime(date_str, '"%Y-%m-%dT%H:%M:%SZ"')
assert decoded_dt == {'date': dt}
class TestParseFilesize(object):
def ... |
bsmithyman/inversion-container | dsworks.py | Python | mit | 5,527 | 0.012846 | import h5py
import numpy as np
import os
class LeafNode(object):
def __init__(self, arr, attrs={}):
if isinstance(arr, h5py.Dataset):
self._dataset = arr
self.arr = arr
self.attrs = arr.attrs
else:
self.arr = arr
... | e an InternalNode without a backing group!')
self.attrs = {key: self._group.attrs[key] for key in self._group.attrs}
self.items = {key: Node(self._group[key]) for key in self._group}
| for key in self.items:
self.items[key].inflate()
def deflate(self):
if getattr(self, '_group', None) is None:
raise Exception('Cannot deflate an InternalNode without a backing group!')
if self.items is not getattr(self, '_group', None):
... |
faroit/loudness | python/tests/test_DoubleRoexBank.py | Python | gpl-3.0 | 5,063 | 0.000198 | import numpy as np
import matplotlib.pyplot as plt
import loudness as ln
class DoubleRoexBank():
def __init__(self, camLo=1.5, camHi=40.2, camStep=0.1):
self.camLo = camLo
self.camHi = camHi
self.camStep = camStep
self.binauralLoudnessFactor = 1.53e-8 * 2 * camStep
self.in... | 2
plt.plot(levels, gain)
plt.xlabel('Passive output level, dB')
plt.ylabel('Active gain, dB')
def plotPassiveFilters(self, colour='k'):
if self.initialized:
| plt.semilogx(self.freqs, 10 *
np.log10(self.wPassive + 1e-10), colour)
plt.xlabel('Frequency, Hz')
plt.ylabel('Response, dB')
plt.show()
def plotActiveFilters(self, colour='r'):
if self.initialized:
plt.semilogx(self.freqs,... |
jamiebull1/eppy | eppy/tests/test_iddgaps.py | Python | mit | 1,138 | 0.002636 | # Copyright (c) 2012 Santosh Philip
# =======================================================================
# Distributed under the MIT License.
# (See accompanying file LICENSE or copy at
# http://opensource.org/licenses/MIT)
# =======================================================================
"""pytest for... | ank Name'],
'Field': ['Water Supply Storage Tank Name'],
'object-list': ['WaterStorageTankNames'],
'type': ['object-list']
},
{
'field': ['Water Supply Storage Tank Name'],
'object-list': ['WaterStorageTankNames'],
'type': ['object-... | esult = iddgaps.cleaniddfield(field)
assert result == newfield
|
NeonWizard/Florchestra | master/python/midiplayer3.py | Python | mit | 1,901 | 0.028406 | import sys
import mido
mido.set_backend("mido.backends.pygame")
# import serialcomm as comm
import enginecomm as comm
import playertools
class Handler:
def __init__(self):
self.frives = [0, 0, 0, 0, 0, 0]
self.resetFrives()
def resetFrives(self):
for i in range(len(self.frives)):
comm.sendNote(0, i)
s... | sys.argv) == 3 else "1", "0")
h = Handler( | )
print("Ready to begin.")
for message in songfile.play():
h.parseNote(message, songdata)
comm.exit()
|
ua-snap/downscale | snap_scripts/downscaling_v2/wrap_downscaler_cmip5_slurm_minmax.py | Python | mit | 2,344 | 0.053328 | # # # # #
# wrap downscaler for running on slurm
# # # # #
def run_model( fn, base_dir, variable, mean_variable, model, scenario, units, metric, level=None, level_nam | e=None ):
import os, subprocess
head = '#!/bin/sh\n' + \
'#SBATCH --ntasks=32\n' + \
'#SBATCH --nodes=1\n' + \
'#SBATCH --ntasks-per-node=32\n' + \
'#SBATCH --account=snap\n' + \
'#SBATCH --mail-type=FAIL\n' + \
'#S | BATCH --mail-user=malindgren@alaska.edu\n' + \
'#SBATCH -p main\n'
script_path = '/workspace/UA/malindgren/repos/downscale/snap_scripts/downscaling_v2/downscale_cmip5_minmax.py'
with open( fn, 'w' ) as f:
if level != None:
command = ' '.join([ 'ipython', script_path,\
'--', '-b', base_dir, '-m', mo... |
tachijuan/python | myscripts/timeandtweet.py | Python | mit | 3,145 | 0.027981 | from twitter import *
import simplejson
import serial
import datetime
import time
import threading
QUIT = 0
prevtweet = ""
def centerstring(string,width):
""" Pad a string to a specific width """
return " "*((width-len(string))/2)+string
def padstring(string,width):
"""pad a string to a maximum length"""
if... | dth:
result = string[0:width]
else:
result = str | ing + " "*(width-len(string))
return result
def runtime():
rangthebell = 0
while QUIT == 0:
# dates = centerstring(datetime.datetime.now().strftime("%B %d, %Y"),20)
# times = centerstring(datetime.datetime.now().strftime("%I:%M:%S %p"),20)
#
# p.write("\x80")
# p.write("%s\r%s" % (dates,times))
... |
matthewjwoodruff/moeasensitivity | statistics/statistics.py | Python | lgpl-3.0 | 6,225 | 0.008193 | """
Copyright (C) 2013 Matthew Woodruff
This script is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This script is distributed in th... | "file. "
)
parser.add_argument("-d", "--deltas",
help="If group is specified, "\
"deltas may be used to impose "\
"grid boxes on the summary "\
"rather than using point "\
... | default="/gpfs/scratch/mjw5407/"
"task1/stats/"
)
return parser.parse_args()
def compute(data, stat):
if stat == "mean":
return data.mean()
if stat == "variance":
return data.var()
if is_quantile(stat):
quant... |
guilatrova/customercontrol-api | customers/tests.py | Python | mit | 1,951 | 0.0041 | import django
django.setup()
from django.test import TestCase
from rest_framework import status
from rest_framework.test import APITestCase
from rest_framework.test import APIClient
from customers.models import Customer, Email
class CustomersTest(APITestCase, TestCase):
def test_api_should_accept_multiple_emails... | EST)
def test_api_should_not_accept_equal_e | mails(self):
customer = self.get_default_customer()
customer['emails'].append({
"address": "jhondoe@stackoverflow.com",
"description": "Professional"
})
customer['emails'].append({
"address": "jhondoe@stackoverflow.com",
... |
fiete201/qutebrowser | qutebrowser/browser/hints.py | Python | gpl-3.0 | 44,206 | 0.000045 | # vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:
# Copyright 2014-2021 Florian Bruhin (The Compiler) <mail@qutebrowser.org>
#
# This file is part of qutebrowser.
#
# qutebrowser is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free S... | et.normal,
Target.tab_fg: usertypes.ClickTarget.tab,
Ta | rget.tab_bg: usertypes.ClickTarget.tab_bg,
Target.window: usertypes.ClickTarget.window,
}
if config.val.tabs.background:
target_mapping[Target.tab] = usertypes.ClickTarget.tab_bg
else:
target_mapping[Target.tab] = usertypes.ClickTarget.tab
if context.... |
cl4u2/chininux | tests/test_record.py | Python | gpl-3.0 | 720 | 0.004167 | from chininux import Record
r = Record("section", [
"label1",
"lab | el2",
"label3",
"label4",
"label5",
"label6",
"label7",
])
r.label1 = "prova"
r.label2 = "10.0.1.0/24"
r.label3 = "10.0.2.0/30 (GR)"
r.label4 = "10.3.0.0/16 - 10.4.0.0/16"
r.label5 = "10.5. | 0.0/16 10.6.0.0/16"
r.label6 = "10.7.3.1 (GR)"
r.label7 = "10.7.3.2"
print "-" * 12
print r
print "-" * 12
assert r.search("10.0.1.1") > 0
assert r.search("10.0.2.1") > 0
assert r.search("10.3.3.1") > 0
assert r.search("10.4.3.1") > 0
assert r.search("10.5.3.1") > 0
assert r.search("10.6.3.1") > 0
assert r.sear... |
agry/NGECore2 | scripts/mobiles/endor/mature_hanadak_rock_smasher.py | Python | lgpl-3.0 | 1,652 | 0.026634 | import sys
from services.spawn import MobileTemplate
from services.spawn import WeaponTemplate
from resources.datatables import WeaponType
from resources.datatables import Difficulty
from resources.datatables import Options
from java.util import Vector
def addTemplate(core):
mobileTemplate = MobileTemplate... | sistRange(12)
mobileTemplate.setStalker(False)
mobileTemplate.setOptionsBitmask(Options.AGGRESSIVE | Options.ATTACKABLE)
templates = Vector()
templates.add('object/mobile/shared_hanadak.iff')
mobileTemplate.setTemplates(templates)
weaponTemplates = Vector()
weapontemplate = WeaponTemplate('object/we... | bileTemplate.setWeaponTemplateVector(weaponTemplates)
attacks = Vector()
attacks.add('bm_dampen_pain_4')
attacks.add('bm_shaken_2')
attacks.add('bm_stomp_4')
mobileTemplate.setDefaultAttack('creatureMeleeAttack')
mobileTemplate.setAttacks(attacks)
core.spawnService.addMobileTemplate('mature_hanadak_... |
lukaszb/cq | examples/djangoapp/urls.py | Python | mit | 159 | 0 | from django.conf.urls | import include
f | rom django.conf.urls import url
import accounts.urls
urlpatterns = [
url(r'^api/auth/', include(accounts.urls)),
]
|
dimtion/jml | outputFiles/statistics/archives/ourIA/improved_closest_v2.py/0.6/10/player1.py | Python | mit | 11,253 | 0.007465 | # | !/usr/bin/env python3
# -*- coding: utf-8 -*-
####################################################################################################################################### | #############################################################################################
######################################################################################################## PRE-DEFINED IMPORTS #####################################################################################################... |
HunterUSF/Quandles | cohomology_calculation/rowreducing.py | Python | gpl-3.0 | 1,083 | 0.028624 | ##############
# Row-reducing
##############
def ToReducedRowEchelonForm( M):
if not M: return
lead = 0
rowCount = len(M)
columnCount = | len(M[0])
for r in range(rowCount):
if lead >= columnCount:
return
i = r
while M[i][lead] == 0:
i += 1
if i == rowCount:
i = r
lead += 1
if columnCount == lead:
return
M[i],M[r] =... | lv = M[i][lead]
M[i] = [ iv - lv*rv for rv,iv in zip(M[r],M[i])]
lead += 1
mtx = [[ 0, 1, -1, -1, 0, 0, 0, 0, 0],
[ 0, 1, -1, 0, 0, 0, 1, 0, 0],
[ 0, 0, 0, 1, 0, -1, 0, 1, 0],
[ 0,-1, 0, 1, 0, -1, 0, 0, 0],
[ 0, 0, 0, 0, 0, 1,... |
stryder199/RyarkAssignments | Assignment2/web2py/gluon/http.py | Python | mit | 3,669 | 0.001635 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This file is part of the web2py Web Framework
Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu>
License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)
"""
__all__ = ['HTTP', 'redirect']
defined_status = {
200: 'OK',
201: 'CREATED',
202: 'ACCEPTE... | + ' '
if not 'Content-Type' in self.headers:
self.headers['Content-Type'] = 'text/html; charset=UTF-8'
body = self.body
if status[:1] == '4':
if not body:
body = status
if isinstance(body, str):
if len(body)<512 and self.header... | dy)
headers = []
for (k, v) in self.headers.items():
if isinstance(v, list):
for item in v:
headers.append((k, str(item)))
else:
headers.append((k, str(v)))
responder(status, headers)
if hasattr(body, '__iter__')... |
ctriegg/governor | helpers/ha.py | Python | mit | 4,529 | 0.004195 | imp | ort sys, time, re, urllib2, json, psycopg2
import logging
from base64 import b64decode
import helpers.errors
import inspect
logger = logging.getLogger(__name__)
def lineno():
"""Returns the current line number in our program."""
return inspect.currentframe().f_back.f_lineno
class Ha:
def __init__(self... | _handler.name)
def update_lock(self):
return self.etcd.update_leader(self.state_handler)
def update_last_leader_operation(self):
return self.etcd.update_last_leader_operation(self.state_handler.last_operation)
def is_unlocked(self):
return self.etcd.leader_unlocked()
def has_... |
bovee/planknn | scripts/check_nn.py | Python | mit | 969 | 0.00516 | ## this may crash due | to memory demands (training too many features at once)
#from pyplanknn.network import Network
#from pyplanknn.submit import check_model
#
#check_model(Network)
import random
import numpy as np
from sklearn.metrics import classification_report
from pyplanknn.preprocess import read_train, read_meta
from pyplanknn.netwo... | ain()
y = np.zeros((x_class.shape[0], 121))
for i, c in enumerate(x_class):
y[i, c] = 1.
classes, _ = read_meta()
s = random.sample(range(len(x_class)), 1000)
x_train = (x[s] - 127.5).reshape(-1, 62500) / 127.5
x_guess = model(x_train)
print(multiclass_log_loss(x_class[s], x_guess... |
iarroyof/define-semantic-annotation | define/controllers/particular.py | Python | gpl-2.0 | 21,463 | 0.009271 | # -*- coding: utf-8 -*-
from __future__ import division
from nltk.corpus import wordnet as wn #Importamos el lector del corpus de wordnet
import random
import operator
#########################################################################
## La función inicio crea la vista inicial que tendrá el usuario si no tiene... | repite
"""
def noEnLista(idDefinicion, muestra):
flag = True
for definicion in muestra:
if definicion['id'] == idDefinicion:
flag = False
return flag
#########################################################################
## La función registraLista crea el registro temporal en la ... | #######################
"""
Nombre de la función: registraLista
Descripción: Registra la lista aleatoria en la base de datos
Versión: 1.0
Autor: Antonio Nuñez
Parametros: muestra - La lista de definiciones
"""
def registraLista(muestra):
for definicion in muestra:
db.temporal.insert(usuario_id=auth.user.... |
Scorched-Moon/server | server/miniboa/__init__.py | Python | gpl-3.0 | 32 | 0.03125 | fro | m .async import Tel | netServer
|
ironfroggy/django-better-cache | bettercache/views.py | Python | mit | 1,519 | 0.00395 | from bettercache.utils import CachingMixin, strip_wsgi
from bettercache.proxy import proxy
import logging
logger = logging.getLogger(__name__)
class BetterView(CachingMixin):
"""Accepts any path and attempts to serve it from the cache. If it cannot
find the response in the cache, it will use ``bettercache.pro... | k for %s" % request.build_absolute_uri())
self.send_task(request, response)
elif response:
logger.debug("not sending task for %s" % request.build_absolute_uri())
else:
logger.info("MISS for: %s" % request.build | _absolute_uri())
# if response is still none we have to proxy
if response is None:
logger.debug('PROXY from: %s' % request.build_absolute_uri())
response = proxy(request)
response['X-Bettercache-Proxy'] = 'true'
else:
response['X-Bettercache-Proxy... |
guardicore/monkey | envs/monkey_zoo/blackbox/tests/performance/telem_sample_parsing/sample_file_parser.py | Python | gpl-3.0 | 1,855 | 0.002695 | i | mport json
import lo | gging
from os import listdir, path
from typing import Dict, List
from tqdm import tqdm
TELEM_DIR_PATH = "../envs/monkey_zoo/blackbox/tests/performance/telemetry_sample"
MAX_SAME_TYPE_TELEM_FILES = 10000
LOGGER = logging.getLogger(__name__)
class SampleFileParser:
@staticmethod
def save_teletries_to_files(te... |
afimb/gtfslib-python | test/test_prettyprint.py | Python | gpl-3.0 | 3,131 | 0.01246 | # -*- coding: utf-8 -*-
# This file is part of Gtfslib-python.
#
# Gtfslib-python 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.
#
# Gtfslib-python 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... | <laurent.gregoire@mecatran.com>
"""
import math
import sys
import unittest
import six
from gtfsplugins.prettycsv import PrettyCsv
class TestPrettyPrinter(unittest.TestCase):
def test_prettyprinter(self):
# Capture standard output
saved_stdout = sys.stdout
try:
out = six.String... |
Carpetsmoker/qutebrowser | qutebrowser/browser/webkit/webkithistory.py | Python | gpl-3.0 | 2,126 | 0 | # vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:
# Copyright 2015-2017 Florian Bruhin (The Compiler) <mail@qutebrowser.org>
#
# This file is part of qutebrowser.
#
# qutebrowser is free software: you can redistribute it and/or modify
# | it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# qutebrowser is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABI... | lic License for more details.
#
# You should have received a copy of the GNU General Public License
# along with qutebrowser. If not, see <http://www.gnu.org/licenses/>.
"""QtWebKit specific part of history."""
import functools
from PyQt5.QtWebKit import QWebHistoryInterface
from qutebrowser.utils import debug
c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.