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 |
|---|---|---|---|---|---|---|---|---|
SummitKwan/python-neo | neo/io/axonio.py | Python | bsd-3-clause | 33,046 | 0.000424 | # -*- coding: utf-8 -*-
"""
Class for reading data from pCLAMP and AxoScope
files (.abf version 1 and 2), developed by Molecular device/Axon technologies.
- abf = Axon binary file
- atf is a text file based format from axon that could be
read by AsciiIO (but this file is less efficient.)
This code is a... | OCKSIZE + header[
'nNumPointsIgnored'] * dt.itemsize
totalsize = header['lActualAcqLength']
elif version >= 2.:
nbchannel = header['sections']['ADCSection']['llNumEntries']
head_offset = header['sections']['DataSection'][
'uBlockIndex'] *... | totalsize = header['sections']['DataSection']['llNumEntries']
data = np.memmap(self.filename, dt, 'r',
shape=(totalsize,), offset=head_offset)
# 3 possible modes
if version < 2.:
mode = header['nOperationMode']
elif version >= 2.:
... |
veloutin/tilde | tilde/tests/test_example_config.py | Python | gpl-3.0 | 1,068 | 0.003745 | from __future__ import unicode_literals
import os
from twisted.trial import unittest
example_file_path = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
os.path.pardir,
os.path.pardir,
"share",
"example-tilde.ini",
)
from tilde.loader import load_config
from tilde.commands import ubun... | srv["bar"]
self.assertEquals("foo.domain", foo.hostname)
self.assertEquals("/backup/homes", foo.archive_root)
self.assertEquals("bar", bar.hostname, "Should default to name")
self.assertEquals("/data/homes", bar.root)
self.assertIs(foo.commands, ubuntu)
self.assertIsN... | assertIn("custom", cmds)
|
sargo/exif-compare | src/exif_compare/utils.py | Python | mit | 446 | 0 | # -*- coding: utf-8 -*-
"""
Helper functions used in views.
"""
from json import dumps
from functools import wra | ps
from flask import Response
def jsonify(function):
"""
Creates a response with the JSON representation of wrapped function result.
"""
@wraps(functio | n)
def inner(*args, **kwargs):
return Response(dumps(function(*args, **kwargs)),
mimetype='application/json')
return inner
|
gabrielgmendonca/torrentcrawler | test.py | Python | gpl-3.0 | 1,757 | 0.015936 | import unittest
import os
from crawler import Crawler
domain = "http://www.legittorrents.info/"
URL = "http://www.legittorrents.info/index.php?page=torrents&search=&category=1&active=1"
line = '<td align="center" width="20" class="lista" style="text-align: center;"><a href="download.php?id=0819ccee9ebe25d7a02fe14496d5... | ual(crawler.get_Torrent_URL(line),url)
def test_get_torrents(self):
crawler = Crawler(URL,domain)
self.assertEqual(len(crawler.get_Torrents_List()),18)
def test_get_filename(self):
crawler = Crawler(URL,domain)
self.assertEqual(fi | lename,crawler.get_Filename(domain+url))
def test_download_file(self):
crawler = Crawler(URL,domain)
self.assertEqual(crawler.download_File(domain+url),filename)
self.assertTrue(os.path.isfile(filename))
def test_page_files(self):
crawler = Crawler(URL,domain)
target_... |
geminy/aidear | oss/qt/qt-everywhere-opensource-src-5.9.0/qtwebengine/src/3rdparty/chromium/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/port/browser_test.py | Python | gpl-3.0 | 4,089 | 0.000978 | # Copyright (C) 2014 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 ... | on't want to actually
check for system dependencies.
"""
return test_run_results.OK_EXIT_STATUS
def driver_name(self):
return 'browser_tests'
def default_timeout_ms(self):
timeout_ms = 10 * 1000
if self.get_option('configur | ation') == 'Debug': # pylint: disable=E1101
# Debug is usually 2x-3x slower than Release.
return 3 * timeout_ms
return timeout_ms
def virtual_test_suites(self):
return []
class BrowserTestLinuxPort(BrowserTestPortOverrides, linux.LinuxPort):
pass
class BrowserTestMa... |
mrknow/filmkodi | plugin.video.wizjatv/resources/lib/lib/client.py | Python | apache-2.0 | 22,250 | 0.009618 | # -*- coding: utf-8 -*-
'''
Specto Add-on
Copyright (C) 2015 lambda
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 l... | = 'gzip'
if redirect == False:
class NoRedirection(u | rllib2.HTTPErrorProcessor):
def http_response(self, request, response): return response
opener = urllib2.build_opener(NoRedirection)
opener = urllib2.install_opener(opener)
try: del headers['Referer']
except: pass
if isinstance(post, dict):
... |
heromod/migrid | mig/cgi-bin/logout.py | Python | gpl-2.0 | 1,078 | 0.002783 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# --- BEGIN_HEADER --- |
#
# logout - force-expire active login session
# Copyright (C) 2003-2014 The MiG Project lead by Brian Vinter
#
# This file is part of MiG.
# |
# MiG is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# MiG is distributed in the hope that it will be useful,
# but WITHOUT ANY WAR... |
superphy/insilico-subtyping | phylotyper/data/download/download_wzx_genes.py | Python | apache-2.0 | 1,774 | 0.009019 | #!/usr/bin/env python
"""Download Wzx gene sequences from Genbank
Example:
$ python download_wzx_genes.py .
"""
import argparse
import logging
import re
from utils import DownloadUtils, SubtypeParser, GeneFilter
__author__ = "Matthew Whiteside"
__copyright__ = "Copyright Government of Canada 2012-2015. F... | ?)(?:\b|\:)"
parser = SubtypeParser([re.compile(opattern, flags=re.IGNORECASE)],
source_fields=['organism','strain','serotype','serovar','note'],
annotation_fields=['source','serotype','organism','serovar'])
# Initialize Download object
dutil = DownloadUtils(args.output_directory, 'Escheri... | ad
dutil.download_by_accession(args.acc_file)
# Parse genbank files for known intimin types
dutil.parse()
|
huyphan/pyyawhois | test/record/parser/test_response_whois_nic_fr_tf_status_available.py | Python | mit | 1,779 | 0.003935 |
# This file is autogenerated. Do not edit it manually.
# If you want change the content of this file, edit
#
# spec/fixtures/responses/whois.nic.fr/tf/status_available
#
# and regenerate the tests with the following script
#
# $ scripts/generate_tests.py
#
from nose.tools import *
from dateutil.parser import pars... | path = "spec/fixtures/responses/whois.nic.fr/tf/status_available.txt"
host = "whois.nic.fr"
part = yawhois.record.Part(open(fixture_path, "r").read(), host)
self.record = yawhois.record.Record(None, [par | t])
def test_status(self):
eq_(self.record.status, 'available')
def test_available(self):
eq_(self.record.available, True)
def test_nameservers(self):
eq_(self.record.nameservers.__class__.__name__, 'list')
eq_(self.record.nameservers, [])
def test_admin_contacts(self... |
tacksoo/excel2pdf | flask_app.py | Python | mit | 4,839 | 0.010126 | # Started based on this sample:
# http://stackoverflow.com/questions/27628053/uploading-and-downloading-files-with-flask
from flask import Flask, request, redirect, url_for, Response, session
import openpyxl # using version 1.6.1
import docx # using python-docx 0.8.4
import os
import zipstream
import zipfile
import tim... | n.font.bold = True
cell2 = table.cell(0,1)
# add date
ce | ll2.text = u'Date: ' + time.strftime("%m/%d/%Y")
run2 = cell2.paragraphs[0].runs[0]
run2.font.bold = True
document.save('aca_form_' + firstname + '_' + lastname + '.docx')
@app.route('/')
def form():
return """
<html>
<body>
<h2>ACA documents generator</h2>
... |
sibis-platform/ncanda-data-integration | scripts/redcap/comments_search.py | Python | bsd-3-clause | 2,070 | 0.010628 | #!/usr/bin/env python
#!/usr/bin/env python
##
## See COPYING file distributed along with the ncanda-data-integration package
## for the copyright and license terms
#### $Revision: 2110 $
## $LastChangedBy: nicholsn $
## $LastChangedDate: 2015-08-07 09:10:29 -0700 (Fri, 07 Aug 2015) $
##
"""
Scan Report Comment S... | i", y1_y2['Year1_notes'][i].lower()) != None:
year1_noscan.append(y1_y2['study_id'][i])
if type(y1_y2['Year2_notes'][i]) == type('str'):
if re.match(".*no mri", y1_y2['Year2_notes'][i].lower()) != None:
year2_noscan.append( | y1_y2['study_id'][i])
i += 1
#write files to name
f = open("./Year1_ignore.txt", "w")
f.write("\n".join([str(x) for x in year1_ignore]))
f.close()
f = open("./Year2_ignore.txt", "w")
f.write("\n".join([str(x) for x in year2_ignore]))
f.close()
f = open("./Year1_NoScan.txt", "w")
f.write("\n".join([str(x) for x ... |
ProjetPP/PPP-datamodel-Python | ppp_datamodel/nodes/missing.py | Python | agpl-3.0 | 366 | 0.005587 | # coding: | utf8
"""Contains the class representing a “missing” leaf."""
from .abstractnode import register, AbstractNode
@register
class Missing(AbstractNode):
"""Represents a “missing” node.
https://github.com/ProjetPP/Documentation/blob/master/data-model.md#missing
"""
__slots__ = ()
_typ | e = 'missing'
_possible_attributes = ()
|
DecisionSystemsGroup/DSGos | airootfs/usr/share/DSGos-Installer/DSGos_Installer/hardware/catalyst_legacy.py | Python | mit | 7,766 | 0.001803 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# catalyst-legacy.py
#
# Copyright © 2013-2015 DSGos
#
# This file is part of DSGos_Installer.
# Based on code by Wayne Hartmann
#
# DSGos_Installer is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as pub... | ", "0x9580", "0x9588",
"0x9589", "0x9590", "0x9598", "0x9599", "0x9596", "0x9597", "0x9500",
"0x9515", "0x9505", "0x9501", "0x9507", "0x9519", "0x9517", "0x9540",
"0x9541", "0x9542", "0x954e", "0x954f" | , "0x9487", "0x948f", "0x9498",
"0x9490", "0x9495", "0x94b5", "0x94b3", "0x94b1", "0x94b4", "0x944c",
"0x9450", "0x9452", "0x9442", "0x9440", "0x944e", "0x9460", "0x9462",
"0x6838", "0x6839", "0x683b", "0x683d", "0x683f", "0x6858", "0x6859",
"0x6849", "0x6850", "0x6818", "0x6819", "0x6798", "0x679a", "0... |
go-lab/appcomposer | alembic/versions/16f121110a0f_add_same_tool_and_tool_id.py | Python | bsd-2-clause | 1,266 | 0.009479 | """Add same_tool and tool_id
Revision ID: 16f121110a0f
Revises: 2c58f1b857f1
Create Date: 2015-11-09 12:28:43.019410
"""
# revision identifiers, used by Alembic.
revision = '16f121110a0f'
down_revision = '2c58f1b857f1'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated b... | ble=True))
op.add_column('ActiveTranslationMessages', sa.Column('tool_id', sa.Unicode(length=255), nullable=True))
op.create_index(u | 'ix_ActiveTranslationMessages_same_tool', 'ActiveTranslationMessages', ['same_tool'], unique=False)
op.create_index(u'ix_ActiveTranslationMessages_tool_id', 'ActiveTranslationMessages', ['tool_id'], unique=False)
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please... |
fabian4/trove | trove/extensions/common/views.py | Python | apache-2.0 | 1,343 | 0 | # Copyright [2015] Hewlett-Packard Development Company, L.P.
# 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... | ,
"databases": self.user.databases
}
return {"user": user_dict}
class RootCreatedView(UserView):
def data(self):
user_dict = {
"name": self.user.name,
"password": self.user.password
}
return {"user": user_dict}
class RootEnabledView | (object):
def __init__(self, is_root_enabled):
self.is_root_enabled = is_root_enabled
def data(self):
return {'rootEnabled': self.is_root_enabled}
|
yousseb/django_pytds | django_pytds/patches.py | Python | mit | 485 | 0.006186 | from __future__ import unicode_literals
import sys
if sys.version_info >= (2, 7):
# Django Ticket #17671 - Allow using a cursor as a ContextManager
# in Python 2.7
from django.db.backends.util import CursorWrapper
if not hasattr(CursorWrapper, '__enter__'):
enter = lambda self: self
| exit = lambda self, type, value, traceback: self.cursor.__exit__(type, value, traceback)
CursorWr | apper.__enter__ = enter
CursorWrapper.__exit__ = exit
|
PXke/invenio | invenio/modules/redirector/redirect_methods/goto_plugin_cern_hr_documents.py | Python | gpl-2.0 | 7,113 | 0.005624 | # -*- coding: utf-8 -*-
##
## This file is part of Invenio.
## Copyright (C) 2012 CERN.
##
## Invenio is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
## published by the Free Software Foundation; either version 2 of the
## License, or (at your option) a... | 'lang': lang,
'edition': edition,
'modif': modif
}
else:
return "CERN_SSR_%(lang)s_ed%(edition)02d" % {
'lang': lang,
'edition': edition,
}
_RE_REVISION = re.compile(r"rev(\d\d)")
def _get_revision(docname):
"""
Return the revisio... | Circ_Op_en_02_rev01_Implementation measures.pdf -> 1
CERN_Circ_Op_en_02_rev02_Implementation measures.PDF -> 2
"""
g = _RE_REVISION.search(docname)
if g:
return int(g.group(1))
return 0
def _register_document(documents, docname, key):
"""
Register in the documents mapping the docnam... |
Demon-Hunter/tbag | tbag/core/web.py | Python | mit | 6,329 | 0.000526 | # -*- coding:utf-8 -*-
"""
web基类
Author: huangtao
Date: 2017/8/8
Update: 2017/12/12 1. 增加do_prepare/do_complete函数;
2017/12/17 1. 增加中间件;
2017/12/18 1. 修改错误返回类型;
2. 增加 query_params 及 data 属性方法;
3. 删除 do_http_error 方法;
2018/01/17 1. 跨域增加设置 Access-Contr... | """
body = self.request.body
if not body:
return None
if parse_json:
try:
body = json.loads(body.decode('utf8'))
except:
exceptions.ValidationError(msg='请求body数据格式错误')
return body
def do_success(self, data={}, msg... | ta': self._to_representation(data)
}
self.do_finish(result)
def do_failed(self, code=400, msg='error', data={}):
""" API失败返回
"""
result = {
'code': code,
'msg': msg,
'data': self._to_representation(data)
}
self.set_status(2... |
Elandril/SickRage | sickbeard/providers/tntvillage.py | Python | gpl-3.0 | 20,653 | 0.006779 | # Author: Giovanni Borri
# Modified by gborri, https://github.com/gborri for TNTVillage
#
# This file is part of SickRage.
#
# SickRage 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 L... | sBacklog = True
self.public = False
self.enabled = False
self._uid = None
self._hash = None
self.username = None
self.password = None
self.ratio = None
self.cat = None
self.page = 10
self.subtitle = None
| self.minseed = None
self.minleech = None
self.hdtext = [
' - Versione 720p',
' Versione 720p',
' V 720p',
' V 720',
' V HEVC',
' V HEVC',
... |
spierepf/mpf | tests/test_SmartVirtualPlatform.py | Python | mit | 3,495 | 0.004864 | from MpfTestCase import MpfTestCase
from mock import MagicMock
class TestSmartVirtualPlatform(MpfTestCase):
def getConfigFile(self):
return 'test_smart_virtual.yaml'
def getMachinePath(self):
return '../tests/machine_files/platform/'
def get_platform(self):
return 'smart_virtual... | witch_controller.process_switch('device1_s1', 1)
# have to stop() it since the ball is unexpected and it will eject it
# otherwise.
self.machine.ball_devices.device1.stop()
self.advance_time_and_run(.6)
self.assertEqual(1, self.machine.ball_devices.device1.balls)
self.a... | self.machine.switch_controller.is_active('device2_s1'))
self.assertEqual(False,
self.machine.switch_controller.is_active('device2_s2'))
self.assertEqual(True,
self.machine.switch_controller.is_active('device1_s1'))
self.assertEqual(False,
self.machine.swit... |
reuteras/sr_nyheter_m | news.py | Python | gpl-3.0 | 3,138 | 0.003829 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2012 Peter Reuterås
#
# 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.
#
# This program is distributed in the hope that i... |
rahulunair/nova | nova/api/wsgi.py | Python | apache-2.0 | 8,715 | 0 | # 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
# d... | arg passing it shouldn't be necessary.
"""
def _factory(app):
return cls(app, **local_config)
return _factory
def __init__(self, applicati | on):
self.application = application
def process_request(self, req):
"""Called on each request.
If this returns None, the next application down the stack will be
executed. If it returns a response then that response will be returned
and execution will stop here.
"""... |
tensorflow/tfx | tfx/utils/name_utils.py | Python | apache-2.0 | 2,836 | 0.010931 | # Copyright 2022 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | ributeError as e:
# Dynamically created classes is not importable and should not be accessed
# by the full_name.
raise ValueError(f'{value} is not importable.') from e
return f'{value.__module__}.{name}'
def resolve_full_name(full_name: str) -> Any:
"""Resolves reference (class, function, value,... | gments = full_name.split('.')
errors = []
for i in range(len(segments) - 1, 0, -1):
module_name = '.'.join(segments[:i])
try:
mod = importlib.import_module(module_name)
result = _get_nested_attr(mod, segments[i:])
break
except (ImportError, AttributeError) as e:
errors.append(e)
... |
phobson/statsmodels | statsmodels/tsa/statespace/dynamic_factor.py | Python | bsd-3-clause | 57,954 | 0.000155 | """
Dynamic factor model
Author: Chad Fulton
License: Simplified-BSD
"""
from __future__ import division, absolute_import, print_function
from warnings import warn
from statsmodels.compat.collections import OrderedDict
import numpy as np
import pandas as pd
from .kalman_filter import KalmanFilter, FilterResults
from... | ipy.linalg import solve_discrete_lyapunov
from statsmodels.multivariate.pca import PCA
from statsmodels.regression.linear_model import OLS
from statsmodels.tsa.vector_ar.var_model import VAR
from statsmodels.tools.tools import Bunch
from statsmodels.tools.data import _is | _using_pandas
from statsmodels.tsa.tsatools import lagmat
from statsmodels.tools.decorators import cache_readonly
from statsmodels.tools.sm_exceptions import ValueWarning
import statsmodels.base.wrapper as wrap
class DynamicFactor(MLEModel):
r"""
Dynamic factor model
Parameters
----------
endog :... |
stephanehenry27/Sickbeard-anime | sickbeard/encodingKludge.py | Python | gpl-3.0 | 2,060 | 0.003398 | # Author: Nic Wolfe <nic@wolfeden.ca>
# URL: http://code.google.com/p/sickbeard/
#
# This file is part of Sick Beard.
#
# Sick Beard 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 Lice... | f type(x) in (str, unicode) els | e x for x in args])
if type(result) == list:
return fixListEncodings(result)
elif type(result) == str:
return fixStupidEncodings(result)
else:
return result
|
bdh1011/wau | venv/lib/python2.7/site-packages/twisted/conch/scripts/ckeygen.py | Python | mit | 7,540 | 0.003714 | # -*- test-case-name: twisted.conch.test.test_ckeygen -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Implementation module for the `ckeygen` command.
"""
import sys, os, getpass, socket
if getpass.getpass == getpass.unix_getpass:
try:
import termios # hack around broken te... | ass.getpass(
'Enter new passphrase (empty for no passphrase): ')
p2 = getpass.getpass('Enter same passphrase again: ')
if p1 == p2:
break
print 'Passphrases do not match. Try again.'
options['newpass'] = p1
try:
newkeydata = keys.... | extra=options['newpass'])
except Exception as e:
sys.exit('Could not change passphrase: %s' % (e,))
try:
keys.Key.fromString(newkeydata, passphrase=options['newpass'])
except (keys.EncryptedKeyError, keys.BadKeyError) as e:
sys.exit('Could not change passphras... |
lowRISC/ibex | vendor/google_riscv-dv/pygen/experimental/riscv_instr_base.py | Python | apache-2.0 | 20,190 | 0.005002 | """Copyright 2020 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
dis... | m())
elif format == "S_FORMAT" or format == "B_FORMAT":
if category == "STORE":
asm += " {}, {}({})".format(src2, self.get_imm(), src1)
else:
asm += " {}, {}, {}".format(src1, src2, self.get_imm())
elif format == "R_FORMAT":
if category == "CSR":
| asm += " {}, {}, {}".format(destination, hex(csr), src1)
else:
asm += " {}, {}, {}".format(destination, src1, src2)
else:
if name == "BREAK":
asm = ".option norvc;ebreak;.option rvc;"
if self.comment != "":
asm += " # {}".format(self.comment)
return asm.lower()
# In... |
raiabril/arduino_logger | dist/arduino_logger.app/Contents/Resources/__boot__.py | Python | gpl-2.0 | 11,884 | 0.00589 | def _reset_sys_path():
# Clear generic sys.path[0]
import sys, os
resources = os.environ['RESOURCEPATH']
while sys.path[0] == resources:
del sys.path[0]
_reset_sys_path()
def _site_packages():
import site, sys, os
paths = []
prefixes = [sys.prefix]
if sys.exec_prefix != sys.pre... | ctypes.POINTER(ctypes.c_long) ]
carbon.AEGetNthDesc.restype = ctypes.c_int
carbon.AEGetNthDesc.argtypes = [
ctypes.c_void_p, ctyp | es.c_long, ctypes.c_int,
ctypes.c_void_p, ctypes.c_void_p ]
carbon.AEGetDescDataSize.restype = ctypes.c_int
carbon.AEGetDescDataSize.argtypes = [ ctypes.POINTER(AEDesc) ]
carbon.AEGetDescData.restype = ctypes.c_int
carbon.AEGetDescData.argtypes = [
ctypes.POINTER(AEDesc),
... |
shichao-an/momo | momo/plugins/flask/functions.py | Python | bsd-2-clause | 1,505 | 0 | # template global functions
# make sure not to conflict with built-ins:
# http://jinja.pocoo.org/docs/2.9/templates/#list-of-global-functions
from flask.helpers import url_for as _url_for
from flask_paginate import Pagination
def paginate(page, total, per_page, config):
record_name = config['MOMO_PAGINATION_RECO... | ', default=1, type=int)
def toggle_arg(endpoint, request, arg, value, **kwargs):
"""Toggle request arguments.
:param endpoint: endpoint name.
:param request: request object.
:param a | rg: request argument name to toggle.
:param value: intial value for the toggled argument.
:param kwargs: keyword arguments to preserve.
"""
args = request.args.to_dict()
if arg in args:
args.pop(arg)
else:
args[arg] = value
args.update(request.view_args)
args.update(kwarg... |
OpenPathView/batchPanoMaker | tests/unit/services/test_ressource_manager.py | Python | gpl-3.0 | 8,795 | 0.00307 | # coding: utf-8
# Copyright (C) 2017 Open Path View, Maison Du Libre
# 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.
# ... | pv_api_client import ressources
from unittest.mock import patch, call, MagicMock
from path import Path
from typing import List
ID_MALETTE = 1
def cam_img(p, ts):
c = CameraImage(path=Path(p))
c._ts = ts
return c
class TestRessourceManager(object):
@patch("opv_directorymanagerclient.DirectoryManage... | test_make_campaign(self, mock_dbrest_client, mock_dm_client):
mock_make = MagicMock()
mock_campaign_create = MagicMock()
mock_dbrest_client.make = mock_make
generated_campaign = MagicMock(ressources.Campaign)
generated_campaign.id_campaign = 42
generated_campaign.create ... |
BlackPole/bp-dvbapp | lib/python/Screens/LanguageSelection.py | Python | gpl-2.0 | 2,862 | 0.038784 | from Screen import Screen
from Components.ActionMap import ActionMap
from Components.Language import language
from Components.config import config
from Components.Sources.List import List
from Components.Label import Label
from Components.Pixmap import Pixmap
from Components.language_cache import LANG_TEXT
def _cache... | None:
png = LoadPixmap(resolveFilename(SCOPE_CURRENT_SKIN, "countries/missing.png"))
res = (index, name, png)
ret | urn res
class LanguageSelection(Screen):
def __init__(self, session):
Screen.__init__(self, session)
self.oldActiveLanguage = language.getActiveLanguage()
self.list = []
self["languages"] = List(self.list)
self["languages"].onSelectionChanged.append(self.changed)
self.updateList()
self.onLayoutFinish... |
maximumG/exscript | Exscript/interpreter/__init__.py | Python | mit | 1,329 | 0 | #
# Copyright (C) 2010-2017 Samuel Abels
# The MIT License (MIT)
#
# 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 limitation the rights to use, copy,... | OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR I... | CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
from __future__ import absolute_import
from .parser import Parser
import inspect
__all__ = [name for name, obj in list(locals().items())
if not (name.startswith('_') or inspect.ismodule(obj))]
|
Talvalin/server-client-python | tableauserverclient/server/endpoint/views_endpoint.py | Python | mit | 1,391 | 0.002157 | from .endpoint import Endpoint
from .exceptions import MissingRequiredFieldError
from .. import ViewItem, PaginationItem
import logging
logger = logging.getLogger('tableau.endpoint.views')
c | lass Views(Endpoint):
@property
def baseurl(self):
return "{0}/s | ites/{1}".format(self.parent_srv.baseurl, self.parent_srv.site_id)
def get(self, req_options=None):
logger.info('Querying all views on site')
url = "{0}/views".format(self.baseurl)
server_response = self.get_request(url, req_options)
pagination_item = PaginationItem.from_response(se... |
sgzsh269/django | tests/schema/tests.py | Python | bsd-3-clause | 97,864 | 0.001196 | import datetime
import itertools
import unittest
from copy import copy
from django.db import (
DatabaseError, IntegrityError, OperationalError, connection,
)
from django.db.models import Model
from django.db.models.deletion import CASCADE, PROTECT
from django.db.models.fields import (
AutoField, BigIntegerFiel... | tetime.datetime.now(),
)
# Repoint the FK constrain | t
old_field = Book._meta.get_field("author")
new_field = ForeignKey(Tag, CASCADE)
new_field.set_attributes_from_name("author")
with connection.schema_editor() as editor:
editor.alter_field(Book, old_field, new_field, strict=True)
# Make sure the new FK constraint is p... |
django/djangoproject.com | docs/migrations/0003_auto_20171107_1513.py | Python | bsd-3-clause | 1,072 | 0.001866 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2017-11-07 15:13
from __future__ import unicode_literals
import django.co | ntrib.postgres.fields.jsonb
import django.contrib.postgres.indexes
import django.contrib.postgres.search
from django.contrib.postgres.operations import TrigramExtension
from django.db import migrations
class Migration(migrations.Migration):
d | ependencies = [
('docs', '0002_extend_lang_field'),
]
operations = [
migrations.AddField(
model_name='document',
name='metadata',
field=django.contrib.postgres.fields.jsonb.JSONField(default=dict),
),
migrations.AddField(
model_nam... |
Jian-Zhan/customarrayformatter | openpyxl/writer/dump_worksheet.py | Python | mit | 10,418 | 0.003744 | # file openpyxl/writer/straight_worksheet.py
# Copyright (c) 2010-2011 openpyxl
#
# 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 limitation the rights... | f._fileobj_name = None
def write_header(self):
fobj = self.get_temporary_file(filename=self._fileobj_header_name)
doc = XMLGenerator(fobj, 'utf-8')
start_tag(doc, 'worksheet',
{'xml:space': 'preserve',
| 'xmlns': 'http://schemas.openxmlformats.org/spreadsheetml/2006/main',
'xmlns:r': 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'})
start_tag(doc, 'sheetPr')
tag(doc, 'outlinePr',
{'summaryBelow': '1',
'summaryRight': '1... |
tfroehlich82/erpnext | erpnext/stock/doctype/item/test_item.py | Python | gpl-3.0 | 10,134 | 0.025952 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import unittest
import frappe
from frappe.test_runner import make_test_objects
from erpnext.controllers.item_variant import (create_variant, ItemVarian... | item_code)
return item
def | test_get_item_details(self):
# delete modified item price record and make as per test_records
frappe.db.sql("""delete from `tabItem Price`""")
to_check = {
"item_code": "_Test Item",
"item_name": "_Test Item",
"description": "_Test Item 1",
"warehouse": "_Test Warehouse - _TC",
"income_account": ... |
davidwaroquiers/abiflows | abiflows/fireworks/utils/databases.py | Python | gpl-2.0 | 10,111 | 0.00267 | # coding: utf-8
"""
Utilities for database insertion
"""
import gridfs
import json
import pymongo
import paramiko
import os
import stat
import shutil
from monty.json import MSONable
class MongoDatabase(MSONable):
"""
MongoDB database class for access, insertion, update, ... in a MongoDB database
"""
... | n entry:
backup_current_entry_value = '{}_backup_{:d}'.format(entry_value, backup_number)
backup_number += 1
continue
entry[backup_current_entry_value] = entry[entry_value]
break
... | file_obj = self.gridfs.put(dict_str, encoding='utf-8')
entry[entry_value] = file_obj
self.collection.save(entry)
def as_dict(self):
"""
Json-serializable dict representation of a MongoDatabase
"""
dd = {"@module": self.__class__.__module__,
... |
michaelnetbiz/mistt-solution | app/controllers/interviews.py | Python | mit | 2,627 | 0.003426 | from app import db
| from app.models.interviews import InterviewSevenDays, InterviewNinetyDays
from flask import Blueprint, make_response, jsonify
from flask_cors import cross_origin
from flask_login import login_required
# instantiate the module's blueprint
interviews = Blueprint('interviews', __name__, template_folder='interviews', url_... | ds=['GET', 'POST'])
@login_required
def get_interviews_7_days():
return make_response(jsonify([service_plan for service_plan in db.InterviewSevenDays.find()]), 200)
@cross_origin()
@interviews.route('/seven/descriptives/', methods=['GET', 'POST'])
@login_required
def get_interviews_7_days_descriptives():
retu... |
Mariaanisimova/pythonintask | PMIa/2015/Velyan_A_S/task_5_6.py | Python | apache-2.0 | 503 | 0.015015 | # Задача 5. Вариант 6.
# Напишите программу, которая бы при запуске случайным образом отображала назв | ание одного из двух спутников Марса.
# Velyan A. S.
# 27.05.2016
print("\nназвание одного из двух спутников Марса:")
import random
satellite=["Фобос", "Деймос"]
s=random.choice(satellite)
print( | s)
input("Нажмите Enter для выхода") |
triump0870/mysana | src/mysana/settings/production.py | Python | mit | 1,793 | 0.000558 | # In production set the environment variable like this:
# DJANGO_SETTINGS_MODULE=mysana.settings.production
from .base import * # NOQA
import logging.config
# For security and performance reasons, DEBUG is turned off
DEBUG = False
TEMPLATE_DEBUG = False
# Must mention ALLOWED_HOSTS in production!
# ALL... | C_ROOT for the collectstatic command
STATIC_ROOT = join(BASE_DIR, '..', 'site', 'static')
# Log everything to the logs directory at the top
LOGFILE_ROOT = join(dirname(BASE_DIR), 'logs')
# Reset logging
LOGGING_CONFIG = None
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
... | %(levelname)s [%(pathname)s:%(lineno)s] %(message)s",
'datefmt': "%d/%b/%Y %H:%M:%S"
},
'simple': {
'format': '%(levelname)s %(message)s'
},
},
'handlers': {
'proj_log_file': {
'level': 'DEBUG',
'class': 'logging.FileHandler',
... |
varnion/genial | genial/utils.py | Python | bsd-3-clause | 6,193 | 0.009527 | from sys import intern
import os
import numpy as np
import pandas as pd
import re
from .exceptions import UnsupportedFile
def sort_intervals(starts, ends):
intervals = [(s, e) for s, e in zip(starts, ends)]
sorted_by_lower_bound = sorted(intervals, key=lambda tup: tup[0])
starts, ends = zip(*sorted_by_lo... | #10
| 'cds' #11
'phase' #12
'coords_array' #13
'ORF_coords' #14
"""
columns = ['organism', # 0
'assembly_version', # 1
'coords', # 2
'strand', # 3
'biotype', # 4
... |
rspavel/spack | var/spack/repos/builtin/packages/xrefresh/package.py | Python | lgpl-2.1 | 696 | 0.001437 | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Xrefresh(AutotoolsPackage, | XorgPackage):
"""xrefresh - refresh all or part of an X screen."""
homepage = "http://cgit.freedesktop.org/xorg/app/xrefresh"
xorg_mirror_path = "app/xrefresh-1.0.5.tar.gz"
version('1.0.5', sha256='b373cc1ecd37c3d787e7074ce89a8a06ea173 | d7ba9e73fa48de973c759fbcf38')
depends_on('libx11')
depends_on('xproto@7.0.17:', type='build')
depends_on('pkgconfig', type='build')
depends_on('util-macros', type='build')
|
jhseu/tensorflow | tensorflow/python/platform/test.py | Python | apache-2.0 | 3,771 | 0.005834 | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | """
return _googletest.GetTempDir()
@tf_export(v1=['test.test_src_dir_path'])
def test_src_dir_path(relative_path):
"""Creates an absolute test srcdir path given a relative path.
Args:
relative_path: a path relative to tensorflow root.
e.g. "core/platform".
Returns:
An absolute path to the l... | in runfiles.
"""
return _googletest.test_src_dir_path(relative_path)
@tf_export('test.is_built_with_cuda')
def is_built_with_cuda():
"""Returns whether TensorFlow was built with CUDA (GPU) support."""
return _test_util.IsGoogleCudaEnabled()
@tf_export('test.is_built_with_rocm')
def is_built_with_rocm():
"... |
astrand/webkom | set_version.py | Python | gpl-2.0 | 1,081 | 0.004625 | #!/usr/bin/env python2
# -*- coding: iso-8859-1 -*-
# WebKOM - a web based LysKOM client
#
# Copyright (C) 2000 by Peter Åstrand
#
# This program is free software; you can redistribute it and/or
# modi | fy it under the terms of the GNU General Publ | ic License
# as published by the Free Software Foundation; version 2
# of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for mo... |
wjbeksi/rgbd-covariance-descriptors | utilities/generate_random_paths.py | Python | bsd-2-clause | 932 | 0.006438 | #!/usr/bin/env python
#
# Generate test and training lists of absolute paths to files within
# subdirectories for a given top level directory. Each test path is randomly
# selected for a given input directory. The test and training paths are written
# out to separate files.
#
import os
import sys
import random
i... | ile_path + '\n')
else:
train_paths.write(file_path + '\n' | )
i = i + 1
train_paths.close()
test_paths.close()
|
laurentb/weboob | modules/avendrealouer/pages.py | Python | lgpl-3.0 | 6,825 | 0.0022 | # -*- coding: utf-8 -*-
# Copyright(C) 2017 ZeHiro
#
# This file is part of a weboob module.
#
# This weboob module 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,... | ("mainh1")]'), r',(.+)$'))
obj_text = CleanText('//div[has-class("property-description-main")]')
obj_date = Date(
Regexp(
CleanText('//div[has-class("property-description-main")]'),
r'Mise à jour le ([\d\\]+)', default=datetime.today()
)
)
... | SliderContainer"]//ul//li//img'):
url = Attr('.', 'src')(photo)
if url[0] != '/':
photos.append(HousingPhoto(url))
return photos
def obj_details(self):
return {
'GES': CleanText('//span[@id="gassymbol"]', '')(self),
... |
googleapis/python-automl | samples/beta/list_models.py | Python | apache-2.0 | 1,782 | 0 | # Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, so... | n response:
# Display the model information.
if (
model.deployment_state
== automl.Model.DeploymentState.DEPLOYED
):
deployment_state = "deployed"
else:
deployment_state = "undeployed"
print("Model name: {}".format(model.name))
... | .format(model.display_name))
print("Model create time: {}".format(model.create_time))
print("Model deployment state: {}".format(deployment_state))
# [END automl_list_models_beta]
|
databricks/spark-sklearn | python/spark_sklearn/random_search.py | Python | apache-2.0 | 10,095 | 0.000396 | """
Class for parallelizing RandomizedSearchCV jobs in scikit-learn
"""
from sklearn.model_selection import ParameterSampler
from spark_sklearn.base_search import SparkBaseSearchCV
class RandomizedSearchCV(SparkBaseSearchCV):
"""Randomized search on hyper parameters.
RandomizedSearchCV implements a "fit" an... | lection.StratifiedKFold` is used. In all
other cases, :class:`sklearn.model_selection.KFold` is used.
re | fit : boolean, default=True
Refit the best estimator with the entire dataset.
If "False", it is impossible to make predictions using
this RandomizedSearchCV instance after fitting.
verbose : integer
Controls the verbosity: the higher, the more messages.
random_state : int, Rand... |
egtaonline/GameAnalysis | profile/display.py | Python | apache-2.0 | 4,344 | 0 | """Aggregate profiling data and generate an rst file"""
import itertools
import tabulate
def update(means, new, count, num=1):
"""Recursively update mean dictionary"""
for key, val in new.items():
if isinstance(val, dict):
update(means.setdefault(key, {}), val, count)
else:
... | fact that
certain games may be more difficult than others. It also provides an easy
comparison metric to for baseline timing.
""")
fil.write(
'Comparisons Between Methods\n'
'----------------------------------\n\n')
fil.write(tabulate.tabulate(
sorted(([m.title(), v['card | '], v['weight'], v['speed'],
v['norm_speed']]
for m, v in agg_results.items()),
key=lambda x: x[1], reverse=True),
headers=['Method', 'Fraction of Eqa', 'Weighted Fraction',
'Time (sec)', 'Normalized Time'],
tablefmt='rst'))
fil.write(... |
globus/globus-release-tools | share/python/repo/advisories.py | Python | apache-2.0 | 3,857 | 0.001296 | #! /usr/bin/python
import json
import os
import re
import datetime
class Advisories(object):
today = datetime.datetime.now().strftime("%Y-%m-%d")
def __init__(self, initial_advisories_path=None, format="txt"):
self.advisories = []
self.added_packages = {}
if initial_advisories_path ... | f, desc = line.split(";", 4)
pkgs = p.split(",")
flags = f.split(" ")
desc = desc.replace("\"", "\\\"")
obj = {
"date": d,
"packages": pkgs,
"toolkit_version": v,
"flags": flags,
"description": desc,
}
self.advis... | ackages and \
".src.rpm" in p.path:
pfd = os.popen('rpm -q -p "%s" --changelog' % p.path)
pfd.readline() # Date line
changelog = ""
for l in pfd:
if l.startswith("*"):
break
... |
jclgoodwin/bustimes.org.uk | fares/migrations/0004_alter_tariff_access_zones.py | Python | mpl-2.0 | 414 | 0 | # Generated by Django 3.2.5 on 2021-08-17 19:45
from django. | db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('fares', '0003_auto_20210602_1534'),
]
operations = [
migrations.AlterField(
model_name='tariff',
name='access_zones',
field=models.Many | ToManyField(blank=True, to='fares.FareZone'),
),
]
|
haticeerturk/Github-Repositories | Github-Repositories.py | Python | gpl-3.0 | 957 | 0.036573 | import urllib2 , re
name = raw_input("Enter GitHub Account: ")
project_name = raw_input("Enter the project name: ")
url = "https://github.com/" + name + "? | tab=repositories"
searching = urllib2.urlopen(url)
reading = searching.read()
string = '<a href="/' + name + '/(.*?)" class="css-truncate css-truncate-target">'
project = re.findall(string, reading)
for i in range(len(project)) :
if project[i] == projec | t_name :
print "Project Name: ",project[i]
#Get Description...
_url = "https://github.com/" + name + "/" + project_name
_searching = urllib2.urlopen(_url)
_reading = _searching.read()
description = re.findall('<div class="repository-description">\n <p>(.*?)</p>', _reading)
if description :
p... |
kjs73/pele | pele/potentials/test_functions/__init__.py | Python | gpl-3.0 | 75 | 0.013333 | from _beale imp | ort Beale, Be | aleSystem
from _booth import Booth, BoothSystem |
skywalkerytx/oracle | src/main/python/xgbpredict.py | Python | mit | 138 | 0.014493 | import tensorflow as tf
im | port numpy as np
#import allguess as al
|
from datetime import datetime
a = str(datetime.now())[11:19]
print(a) |
OpenSourceHelpCommunity/OpenSourceHelpCommunity.github.io | oshc/oshc/settings/dev.py | Python | mit | 71 | 0 | # dev set | tings
from .base import *
DEBUG = os.getenv("DEBUG" | , False)
|
wakalixes/sqldataplot | plugins/pluginTransformI2B2a.py | Python | gpl-2.0 | 2,418 | 0.016956 | #--------------------------------------------------
# Revision = $Rev: 20 $
# Date = $Date: 2011-08-05 20:42:24 +0200 (Fri, 05 Aug 2011) $
# Author = $Author: stefan $
#--------------------------------------------------
from pluginInterfaces import PluginTransform
import numpy as np
import csv
import os,sys
class ... | return ["A0", "Coil-Conversion", "Feshbach-resonance center"]
def getTransformModelStr(self):
return "x-axis to a/a0"
def requieredInputParameters(self):
return None
def getInfoStr(self):
return "This plugin uses the equation B = (I-'A0')*'Coil-Conversion'" \
"+'Fre... | current in a coil" \
" to magnetic-field-strength B. The conversion will touch whatever " \
"x-axis is selected and will leave all other axes untouched"
|
xiangrufan/astro-NLP | hobby2vec/gensim_test.py | Python | gpl-3.0 | 558 | 0.005618 | import gensim
import numpy as np
from gensim.models import word2vec
import jieba
from TextSta_v2 import TextSta
from gensim.corpora.dictionary impor | t Dictionary
path = u"C:\\Users\\xiangrufan\\Desktop\\NLP\\Astro_NLP\\resource\\复旦分类语料\\answer\\C3-Art\\C3-Art0002.txt"
text = TextSta(path,encoding="GBK")
sentense_file = text.sen(all_return=True)
word_li | st = jieba.lcut(sentense_file)
tmp_dic = Dictionary()
tmp_dic(word_list)
# sentences = word2vec.Text8Corpus() # 加载语料
# model = word2vec.Word2Vec(sentences, size=10) # 默认window=5 |
jawilson/home-assistant | homeassistant/components/ebusd/__init__.py | Python | apache-2.0 | 3,733 | 0.000804 | """Support for Ebusd daemon for communication with eBUS heating systems."""
import logging
import socket
import ebusdpy
import voluptuous as vol
from homeassistant.const import (
CONF_HOST,
CONF_MONITORED_CONDITIONS,
CONF_NAME,
CONF_PORT,
)
import homeassistant.helpers.config_validation as cv
from hom... | write(self, call):
"""Call write methon on ebusd."""
name = call.data.get("name")
value = call.data.get("value")
try:
_LOGGER.debug("Opening socket to ebusd %s", name)
command_result = ebusdpy.write(self._address, self._circuit, n | ame, value)
if command_result is not None and "done" not in command_result:
_LOGGER.warning("Write command failed: %s", name)
except RuntimeError as err:
_LOGGER.error(err)
|
kittiu/sale-workflow | sale_order_margin_percent/__manifest__.py | Python | agpl-3.0 | 647 | 0 | # -*- coding: utf-8 -*-
# Copyright 2017 PESOL (http://pesol.es)
# Luis Adan Jimenez | Hernandez (luis.jimenez@pesol.es)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Sale Order Margin Percent",
"summary": "Show Percent in sale order",
"version": "10.0.1.0.0",
"category": "Sales",
"website": "http://www.pesol.es",
"author": "PESOL, Odoo Community Asso... | 'sale_margin'
],
"data": [
'views/sale_order_margin_percent_view.xml',
]
}
|
fantopop/post-production-scripts | Session info to table/modules/html.py | Python | mit | 1,144 | 0.011364 | #!/usr/bin/python
tab = ' '
class Tag():
def __init__(self, name, HTML):
self.name = name
self.HTML = HTML
def __enter__(self):
self.HTML.content += tab * self.HTML.indent + '<' + self.name + '>\n'
self.HTML.indent += 1
def __exit__(self, exc_type, exc_value, traceback):... | e + '>\n'
class HTML():
def __init__(self):
self.indent = 0
| self.content = '<!DOCTYPE html>\n'
def __str__(self):
return self.content
def add(self, text):
for line in text.split('\n'):
self.content += tab * self.indent + line + '\n'
def html(self):
return Tag('html', self)
def body(self):
return Tag('body', self)
... |
alivecor/tensorflow | tensorflow/python/framework/function_test.py | Python | apache-2.0 | 48,059 | 0.011049 | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | tions(
optimizer_options=config_pb2.OptimizerOptions(
opt_level=config_pb2.OptimizerOptions.L0,
do_common_subexpress | ion_elimination=cse,
do_function_inlining=inline,
do_constant_folding=cfold)))
class FunctionTestMethods(object):
"""Test methods for verifying Function support.
These test methods are used as mix-ins in two test cases: with
and without C API support.
"""
def testIdentity(s... |
davelab6/pyfontaine | fontaine/charsets/noto_glyphs/notosansdevanagari_regular.py | Python | gpl-3.0 | 38,139 | 0.02365 | # -*- coding: utf-8 -*-
class Charset(object):
common_name = 'NotoSansDevanagari-Regular'
native_name = ''
def glyphs(self):
glyphs = []
glyphs.append(0x0065) #uni0961
glyphs.append(0x0178) #glyph00376
glyphs.append(0x02D8) #glyph00728
glyphs.append(0x0179) #gl... | yphs.append(0x0148) #glyph00328
glyphs.append(0x0224) #glyph00548
glyphs.append(0x02BB) #glyph00699
glyphs.append(0x02BA) #glyph00698
glyphs.append(0x027E) #glyph00638
glyphs.append(0x031F) #uniA8E3
glyphs.append(0x02B3) # | glyph00691
glyphs.append(0x02B2) #glyph00690
glyphs.append(0 |
tethysplatform/tethys_dataset_services | tethys_dataset_services/tests/e2e_tests/ckan_engine_e2e_tests.py | Python | bsd-2-clause | 10,844 | 0.001752 | import os
import random
import string
import unittest
import requests
from tethys_dataset_services.engines import CkanDatasetEngine
try:
from tethys_dataset_services.tests.test_config import TEST_CKAN_DATASET_SERVICE
except ImportError:
print('ERROR: To perform tests, you must create a file in the "tests" pac... | lete_dataset
# Execute
result = self | .engine.delete_dataset(data |
cheesyc/2014KStateProgrammingCompetitionAnswers | 2011/1A.py | Python | mit | 386 | 0.007772 | num = input("What is the numerator")
dem = input("What is the denominator")
counta = 2
countb = 2
def math (num,dem):
| remainsa = 1
remainsb = 1
remains = remainsa - remainsb
while r | emains > 0:
a = num / counta
b = dem / countb
remainsa = num % counta
remainsb = num % countb
remains = remainsa - remainsb
if remains =
|
erkanay/django | tests/migrations/test_operations.py | Python | bsd-3-clause | 70,029 | 0.002956 | from __future__ import unicode_literals
import unittest
try:
import sqlparse
except ImportError:
sqlparse = None
from django import test
from django.test import override_settings
from django.db import connection, migrations, models, router
from django.db.migrations.migration import Migration
from django.db.m... | _editor() as editor:
return migration.apply(project_state, editor)
def unapply_operations(self, app_label, project_state, operations):
migration = Migration('name', app_label)
migration.operations = operations
with connection.schema_editor() as editor:
return migrati | on.unapply(project_state, editor)
def make_test_state(self, app_label, operation, **kwargs):
"""
Makes a test state using set_up_test_model and returns the
original state and the state after the migration is applied.
"""
project_state = self.set_up_test_model(app_label, **kw... |
rogeriofalcone/treeio | events/hmodule.py | Python | mit | 444 | 0.002252 | # encoding: utf-8
# Copyright 2011 Tree.io Limited
| # This file is part of Treeio.
# License www.tree.io/license
"""
Events: Hardtree module definition
"""
PROPERTIES = {
'title': 'Calendar',
'details': 'Manage events and calendars',
'url': '/calendar/',
'system': True,
'type': 'minor',
... | calendar/',
]
|
dryan/django-session-activity | session_activity/urls.py | Python | mit | 397 | 0 | # -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from django.conf.urls import patterns, url
from .views import session_list_view, sign_out_other_view
urlpatterns = [
url(r"^$", session_li | st_view, name="session_activity_list"), |
url(r"^sign-out-other/", sign_out_other_view, name="session_sign_out"),
]
|
jacobmarks/QTop | src/tests/test_DSP.py | Python | gpl-3.0 | 976 | 0.033811 | #
# QTop
#
# Copyright (c) 2016 Jacob Marks (jacob.marks@yale.edu)
#
# This file is part of QTop.
#
# QTop 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.
import sys
sys.path.append('../')
from src import color_codes, error_models, visualization
sys.path.append('decoders/')
from dsp import *
import networkx as nx
import numpy as np
import ... | ##########
L, d, p = 13, 2, 0.08
code = color_codes.Color_6_6_6(L,d)
model = error_models.PhaseError()
code = code.CodeCycle(model, p)
visualization.PlotPlaquette(code, "Before Decoding", 1)
decoder = DSP_decoder()
code = decoder(code)
if code.hasLogicalError():
print "ERROR"
else:
print "GOOD JOB!"
visualization... |
Nocturnal42/runmyrobot | test/gpio_test.py | Python | apache-2.0 | 566 | 0.014134 | import time
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
#GPIO.setup(4, GPIO.IN, pull_up_down=GPI | O.PUD_DOWN)
#GPIO.setup(25, GPIO.OUT, initial=GPIO.LOW)
#GPIO.add_event_detect(4, GPIO.BOTH)
#def my_callback():
# GPIO.output(25, GPIO.input(4))
#GPIO.add_event_callback(4, my_callback)
def call( | x):
print "something happened:", x
#for i in range(0, 26):
for i in range(17, 18):
# print i
GPIO.setup(i, GPIO.IN)
# #GPIO.add_event_detect(i, GPIO.BOTH)
# GPIO.add_event_callback(i, call)
while True:
print GPIO.input(17)
time.sleep(1)
|
freyes/juju | acceptancetests/jujucharm.py | Python | agpl-3.0 | 6,215 | 0 | """Helpers to create and manage local juju charms."""
from contextlib import contextmanager
import logging
import os
import re
import subprocess
import pexpect
import yaml
from utility import (
ensure_deleted,
JujuAssertionError,
)
__metaclass__ = type
log = logging.getLogger("jujucharm")
class Char... | if storage is not None:
self.metadata["storage"] = storage
self._hook_scripts = {}
def to_dir(self, directory):
"""Serialize charm into a new directory."""
with open(os.path.join(directory, "metadata.yaml"), "w") as f:
| yaml.safe_dump(self.metadata, f, default_flow_style=False)
if self._hook_scripts:
hookdir = os.path.join(directory, "hooks")
os.mkdir(hookdir)
for hookname in self._hook_scripts:
with open(os.path.join(hookdir, hookname), "w") as f:
os.... |
amurzeau/streamlink-debian | src/streamlink/plugins/app17.py | Python | bsd-2-clause | 1,952 | 0.001025 | import logging
import re
from streamlink.plugin import Plugin, pluginmatcher
from streamlink.plugin.api import validate
from streamlink.stream.hls import HLSStream
from streamlink.stream.http import HTTPStream
log = logging.getLogger(__name__)
@pluginmatcher(re.compile(
r"https?://17\.live/.+/live/(?P<channel>[... | "live-hdl", "live-hls").replace(".flv", ".m3u8")
s = HLSStream.parse_variant_playlist(self.session, hls_url)
if not s:
yield "live", HLSStream(self.session, hls_url)
else:
if | len(s) == 1:
for _n, _s in s.items():
yield "live", _s
else:
yield from s.items()
__plugin__ = App17
|
codecakes/cloudroutes-service | src/web/reactions.py | Python | agpl-3.0 | 5,105 | 0 | ######################################################################
# Cloud Routes Web Application
# -------------------------------------------------------------------
# Reaction Class
######################################################################
import rethinkdb as r
class Reaction(object):
def __... | else:
return "edit failed"
def deleteReaction(self, uid, rid, rdb):
''' This will delete a specified reaction '''
reaction = r.table('reactions').get(rid).run(rdb)
if reaction['uid'] == uid:
delete = r.table('reactions').get(rid).delete().run(rdb)
i... | a['item'] = reaction
qdata['action'] = 'delete'
qdata['type'] = 'reaction'
qdata['item']['rid'] = rid
q1 = r.table('dc1queue').insert(qdata).run(rdb)
q2 = r.table('dc2queue').insert(qdata).run(rdb)
return True
el... |
BoxeePlay/svtplay3 | tv.boxeeplay.svtplay3/async_task.py | Python | mit | 995 | 0.003015 | import threading
from logger import BPLog, Level
class AsyncTask(threading.Thread):
def __init__(self, target, args=(), kwargs={}):
threading.Thread.__init__(self)
self.target = target
self.args = args
self.kwargs = kwargs
self.setDaemon(True)
self.returned = None
... | f.isAlive():
raise RuntimeError("Not finished yet")
if self.exc_info:
raise self.exc_info[1], None, self.exc_info[2]
return self.returned
class AsyncError(Exception):
def __init__(self, message, e):
Exception.__init__(self, message)
self.log(message, e)
... | |
Pekkoo/OhSiHAPP | ohsiha/urls.py | Python | mit | 568 | 0.001761 | from django.conf.urls import url, include
from django.contrib impor | t admin
import ohsihapp.views
import django.contrib.auth.views
import comment.urls
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^login/$', django.contrib.auth.views.login, {'template_name': 'ohsihapp/login.html'}),
url(r'^register/$', ohsihapp.views.register),
url(r'^soundcloud/$', ohsihapp.... | t/$', django.contrib.auth.views.logout, {'next_page': '/'}),
url(r'^$', ohsihapp.views.index),
url(r'^comment/', include(comment.urls))
]
|
tomjmul/wemo | wemo/examples/Randomize.py | Python | bsd-3-clause | 1,078 | 0.008349 |
import random
import datetime
import time
import wemo
from wemo.environment import Environment
# http://pydoc.net/Python/wemo/0.7.3/wemo.examples.watch/
if __name__ == "__main__":
print("")
print("WeMo Randomizer")
print("---------------")
env = Environment()
# TODO: run from 10am to 10pm
try:... | t()
env.discover(100)
print(env.list_switches())
print(env.list_motions())
print("---------------")
while True:
# http://stackoverflow.com/questions/306400/how-do-i-randomly-select-an-item-from-a-list-using-python
switchRND = env.get_switch( random.choice(... | print("---------------")
print("Goodbye!")
print("---------------")
# Turn off all switches
for switch in ( env.list_switches() ):
print("Turning Off: " + switch)
env.get_switch( switch ).off()
|
TrevorLowing/PyGames | pysollib/tk/selectcardset.py | Python | gpl-2.0 | 15,583 | 0.003915 | #!/usr/bin/env python
# -*- mode: python; coding: utf-8; -*-
##---------------------------------------------------------------------------##
##
## Copyright (C) 1998-2003 Markus Franz Xaver Johannes Oberhumer
## Copyright (C) 2003 Mt. Hood Playing Card Co.
## Copyright (C) 2005-2009 Skomoroh
##
## This program is free ... | ne
| items = CSI.STYLE.items()
items.sort(lambda a, b: cmp(a[1], b[1]))
nodes = []
for key, name in items:
if manager.registered_styles.get(key):
nodes.append(SelectCardsetNode(None, name, lambda cs, key=key: key in cs.si.styles))
if nodes:
node... |
SAP/lumira-extension-da-linkedin | source/LinkedinExtractor.py | Python | apache-2.0 | 6,132 | 0.012231 | # -*- coding: utf-8 -*-
#imports
from linkedin import linkedin
import easygui
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
import requests
def enum(*sequential, **named):
enums = dict(zip(sequential, range(len(sequential))), **named)
return type('Enum', (), enums)
Mode = enum('PREVIEW', 'EDIT', ... | try:
print ''.join([c['firstName'].replace(',', ''), ',']),
except:
print ''.join(['None', ', ']),
try:
print ''.join([c['lastName'].replace(',', ''), ',']),
except:
| print ''.join(['None', ', ']),
try:
print ''.join([c['location']['name'].replace(',', '')])
except:
print ''.join(['None'])
print "endData"
else:
print "beginDSInfo"
print "endDSInfo"
print "beginData"
pr... |
emilybache/KataMedicineClash | Python/medicine.py | Python | mit | 228 | 0.017544 |
class Medicine(object):
def __init__(self, name):
self.name = name
self.prescriptions = []
def add_prescription(self, prescription):
self.prescriptions.append(prescription)
| ||
timonweb/djow | project_name/apps/custom_comments/models.py | Python | mit | 138 | 0.014493 | from django.db import | models
from django_comments.models import Comment
# Create your models here.
class CustomComment(Comment):
| pass |
noslenfa/tdjangorest | uw/lib/python2.7/site-packages/IPython/core/tests/test_run.py | Python | apache-2.0 | 13,433 | 0.001489 | # encoding: utf-8
"""Tests for code execution (%run and related), which is particularly tricky.
Because of how %run manages namespaces, and the fact that we are trying here to
verify subtle object deletion and reference counting issues, the %run tests
will be kept in this separate file. This makes it easier to aggreg... | _ip = get_ipython()
# Test that the id of __builtins__ is not modified by %run
bid1 = id(_ip.user_ns['__builtins__'])
self.run_tmpfile()
bid2 = id(_ip.user_ns['__builtins__'])
n | t.assert_equal(bid1, bid2)
def test_builtins_type(self):
"""Check that the type of __builtins__ doesn't change with %run.
However, the above could pass if __builtins__ was already modified to
be a dict (it should be a module) by a previous use of %run. So we
also check explicitly ... |
cloudcopy/seahub | tests/api/test_auth.py | Python | apache-2.0 | 2,115 | 0.002364 | #coding: UTF-8
"""
Test auth related api, such as login/logout.
"""
import random
import re
from urllib import urlencode, quote
from tests.common.common import USERNAME, PASSWORD, SEAFILE_BASE_URL
from tests.common.utils import randstring, urljoin
from tests.api.urls import (
AUTH_PING_URL, TOKEN_URL, DOWNLOAD_RE... |
'device_name': 'fake-device-name',
'client_version': '4.1.0',
'platform_version': '',
}
return self.post(TOKEN_URL, data=data, use_token=False).json()['token']
def _do_auth_ping(self, token, **kwargs):
return self.get(AUTH_PING_URL, token=token, **kwargs... | en=token).json()['token']
def _get_repo_info(self, sync_token, repo_id, **kwargs):
headers = {
'Seafile-Repo-Token': sync_token
}
url = urljoin(SEAFILE_BASE_URL,
'repo/%s/permission-check/?op=upload' % repo_id)
self.get(url, use_token=False, headers... |
alexcasgarcia/CCI | TreesAndGraphs/DFS.py | Python | mit | 2,154 | 0.021356 | class Queue:
def __init__(self,values):
self.values = values
def __str__(self):
return str(self.values)
def add(self,value):
self.values = self.values + [value]
def remove(self):
beginningOfQueue = self.values[0]
self.values = self.values[1:]
return be... | sited(self):
return self.visited
def depthfirstsearch(self):
if | (self == None):
return
self.visit()
children = self.getChildren()
for x in xrange(len(children)):
if (children[x].wasVisited() == False):
children[x].depthfirstsearch()
def breadthfirstsearch(self):
q = Queue([])
self.mark()
q.... |
recap/pumpkin | examples/tracula/injector.py | Python | mit | 2,720 | 0.013235 | __author__ = 'reggie'
###START-CONF
##{
##"object_name": "injector",
##"object_poi": "injector-9192",
##"auto-load": true,
##"remoting" : true,
##"parameters": [
## {
## "name": "inject",
## "type": "Composite",
## "state" : "ALL_RAW",
## ... | ry later")
if os.path.isfile(outputDir):
self.logger.info("Found outputDir file")
else:
found = False
self.logger.warn("Input file "+outputDir+" not found yet...retry later")
if os.path.isfile(lic):
self.logger | .info("Found license file")
else:
found = False
self.logger.warn("Input file "+lic+" not found yet...retry later")
#mri_input = mri_file+"|,|"+subjectID+"|,|"+outputDir+"|,|"+lic
mri_input = data[0]+"|,|"+data[2]+"|,|"+data[3]+"|,|"+data[4]
#dti_input = dti_file
... |
iarspider/pyscm | main.py | Python | gpl-3.0 | 834 | 0.003597 | #!python | 3
import argparse
import scmFile
if __name__ == "__main__":
parser = argparse.ArgumentParser()
g = parser.add_mutually_exclusive_group(required=True)
g.add_argument('-r', '--read', action="store_const", dest="mode", const="read",
help="Convert | SCM to one or more CSV")
g.add_argument('-w', '--write', action="store_const", dest="mode", const="write",
help="Convert CSV files back to SCM")
parser.add_argument('-f', '--format', action="store", choices=['F', 'f', 'C', 'c'], required=True)
parser.add_argument('file')
args = parse... |
Seldaiendil/meyeOS | devtools/qooxdoo-1.5-sdk/tool/pylib/generator/code/clazz/MClassResources.py | Python | agpl-3.0 | 5,779 | 0.006056 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
################################################################################
#
# qooxdoo - the new era of web development
#
# http://qooxdoo.org
#
# Copyright:
# 2006-2011 1&1 Internet AG, Germany, http://www.1und1.de
#
# License:
# LGPL: http://www.gnu.org/li... | s
if hint.regex.match(res.id):
| hint.seen = True
hint.clazz.resources.add(res)
# add matches of embedded images
if isinstance(res, CombinedImage):
for embed in res.embeds:
if hint.regex.match(embed.id):
hint.seen = True
... |
nuobit/odoo-addons | account_asset_invoice_line_link/models/account_move.py | Python | agpl-3.0 | 659 | 0 | # Copyright NuoBiT Solutions, S.L. (<https://www.nuobit.com>)
# Eric Antones <eantones@nuobit.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl)
from odoo import fields, models
class AccountMove(models.Model):
_inher | it = "account.move"
def _prepare_asset_vals(self, aml):
vals = super()._prepare_asset_vals(aml)
vals["move_id"] = aml.move_id
vals["move_line_id"] = aml
return vals
class AccountInvoiceLine(models.Model):
_inherit = "account.move.line"
asset_ids = fields.One2many(
... | ssets",
)
|
thjwhite/personal_website | personal_website/recipes/admin.py | Python | mit | 700 | 0.001429 | from django.contrib import admin
from .models import Recipe, IngredientRequirement, Ingredient
admin.site.site_header = 'TJ White\'s website admin panel'
admin.site.site_title = 'TJ White\'s personal website'
admin.site.index_title = 'Administration'
class IngredientRequirementInline(admin.TabularInline):
model ... | min(admin.ModelAdmin):
fieldsets = [
('General Information', {'fields': ['name', 'title']}),
('Publishing Information', {'fields': ['date_published']})
]
inlines =[IngredientRequirementInline]
search_fields = ['title']
admin.site.register(Recipe, RecipeAdmin | )
admin.site.register(Ingredient)
|
mochrul/zorp | tests/zorpctl/test_szig.py | Python | gpl-2.0 | 3,271 | 0.006726 | #!/usr/bin/env python2.7
############################################################################
##
## Copyright (c) 2000-2015 BalaBit IT Ltd, Budapest, Hungary
## Copyright (c) 2015-2018 BalaSys IT Ltd, Budapest, Hungary
##
##
## This program is free software; you can redistribute it and/or modify
## it under th... | one)
self.assertEquals(self.szig.get_value("info.policy.file"), "/etc/zorp/policy.py")
self.assertEquals(self.szig.get_value("stats.thread_number"), 5)
self.assertEquals(self.szig.get_value("service.service_http_transparent.sessions_running"), 0)
def test_get_sibling(self):
self.ass... | .thread_rate_max")
self.assertEquals(self.szig.get_sibling("stats.thread_rate_max"), "stats.audit_number")
self.assertEquals(self.szig.get_sibling("stats.thread_number"), None)
def test_get_child(self):
self.assertEquals(self.szig.get_child(""), "conns")
self.assertEquals(self.szig.... |
mumuwoyou/vnpy-dev | vn.trader/ctaStrategy/strategy/strategyTmm3.py | Python | mit | 19,435 | 0.006349 | # encoding: UTF-8
from ctaBase import *
from ctaTemplate import CtaTemplate
import talib
import numpy as np
import math
import copy
from datetime import datetime
########################################################################
class Tmm3Strategy(CtaTemplate):
className = 'Tmm3Strategy'
author = ... | --------------------------------------------------------------
def onTick(self, tick):
"""收到行情TICK推送(必须由用户继承实现)"""
| # 计算K线
#super(Tmm3Strategy, self).onTick(tick)
tickMinute = tick.datetime.minute
if tickMinute != self.barMinute:
if self.bar:
self.bar.datetime = tick.datetime.replace(second=0, microsecond=0)
self.bar.date = tick.date
self.b... |
Azure/azure-sdk-for-python | sdk/synapse/azure-mgmt-synapse/azure/mgmt/synapse/operations/_integration_runtime_nodes_operations.py | Python | mit | 15,893 | 0.004216 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | lizer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
@distributed_trace
def get(
self,
resource_group_name: str,
workspace_name: str,
integration_runtime_name: str,
... |
) -> "_models.SelfHostedIntegrationRuntimeNode":
"""Get integration runtime node.
Get an integration runtime node.
:param resource_group_name: The name of the resource group. The name is case insensitive.
:type resource_group_name: str
:param workspace_name: The name of th... |
closeio/tasktiger | tasktiger/redis_semaphore.py | Python | mit | 3,150 | 0.000317 | """Redis Semaphore lock."""
import os
import time
SYSTEM_LOCK_ID = 'SYSTEM_LOCK'
class Semaphore(object):
"""Semaphore lock using Redis ZSET."""
def __init__(self, redis, name, lock_id, timeout, max_locks=1):
"""
Semaphore lock.
Semaphore logic is implemented in the lua/semaphore.l... | eout plus buffer for troubleshooting
pipeline.execute()
def release(self):
"""Release semaphore."""
self.redis.zrem(self.name, self.lock_id)
def acquire(self):
"""
Obtain a semaphore lock.
Returns: Tuple that contains True/False if the lock was acquired and nu... |
locks in semaphore.
"""
acquired, locks = self._semaphore(
keys=[self.name],
args=[self.lock_id, self.max_locks, self.timeout, time.time()],
)
# Convert Lua boolean returns to Python booleans
acquired = True if acquired == 1 else False
... |
dhamaniasad/mythbox | resources/lib/twisted/twisted/internet/endpoints.py | Python | gpl-2.0 | 15,010 | 0.001666 | # -*- test-case-name: twisted.internet.test.test_endpoints -*-
# Copyright (c) 2007-2010 Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Implementations of L{IStreamServerEndpoint} and L{IStreamClientEndpoint} that
wrap the L{IReactorTCP}, L{IReactorSSL}, and L{IReactorUNIX} interfaces.
@since: 10.1
"""
f... | ct the C{self._wrappedProtocol} to our C{self.transport} and
callback C{self._ | connectedDeferred} with the C{self._wrappedProtocol}
"""
self._wrappedProtocol.makeConnection(self.transport)
self._connectedDeferred.callback(self._wrappedProtocol)
def dataReceived(self, data):
"""
Proxy C{dataReceived} calls to our C{self._wrappedProtocol}
"""
... |
hmdc/outagenotifier | scripts/outages.py | Python | gpl-2.0 | 2,381 | 0.00882 | #!/usr/bin/env python
"""
Script for printing outage information to the console.
"""
from bs4 import BeautifulSoup
import argparse
import ConfigParser
import hmdclogger
import os
__author__ = "Harvard-MIT Data Center DevOps"
__copyright__ = "Copyright 2015, HMDC"
__credits__ = ["Bradley Frank"]
__license__ = "GPLv2"... | ngFiles', 'working_directory'),
}
return settings
def set_logger(debug_level):
"""Creates an instance of HMDCLogger with appropriate handlers."""
hmdclog = hmdclogger.HMDCLogger("outages", debug_level)
hmdclog.log_to_console()
return hmdclog
def parse_xml(source, hmdclog):
"""Reads in messages from... | with open(source, "r") as file:
xml_file = BeautifulSoup(file, "xml")
file.close()
hmdclog.log('debug', "Read in file: " + source)
else:
raise Exception("Notifications file not found!")
counter = 0
outages = []
messages = xml_file.find_all("message")
for message in messages:
counter +=... |
AbstractGeek/rusmalai-ncbs | packages/examples/test_data.py | Python | mit | 768 | 0.018229 | import ANN
import matplotlib.pyplot as plt
from sklearn.datasets import load_digits
data = load_digits()
input = data.data
target = data.target
numLayers = 5
iterations = 20000
#input = [[0,0],[0,1],[1,0],[1,1]]
#target = [0,1,1,0]
nn1 = ANN.FNN(numLayers, input, target, eta=0.05 )
e = nn1.train(iterations)
achi... | e.app | end(nn1.iterate())
#print "Output is {}".format(nn1.output_layer.output)
#print nn1.output_layer.neurons[0].w, nn1.output_layer.prev_layer.neurons[0].output, nn1.output_layer.prev_layer.neurons[1].output, nn1.output_layer.prev_layer.neurons[2].output
plt.plot(e)
plt.show()
#plt.scatter(input.T[0], input.T[1], c... |
googleads/google-ads-python | google/ads/googleads/v10/enums/types/user_list_combined_rule_operator.py | Python | apache-2.0 | 1,169 | 0.000855 | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | AND_NOT = 3
__all__ = | tuple(sorted(__protobuf__.manifest))
|
lorien/grab | grab/spider/__init__.py | Python | mit | 158 | 0 | from grab.spider.base import Spider # noqa
from grab.spid | er.task import Task # noqa
from grab.spider.error import * # noqa py | lint: disable=wildcard-import
|
tensorflow/tensorflow | tensorflow/python/kernel_tests/nn_ops/embedding_ops_test.py | Python | apache-2.0 | 47,859 | 0.009486 | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | num_shards,
vocab_size,
partition_strategy="mod",
weight_vals=None):
if weight_vals is None:
weight_vals = np.copy(id_vals)
weight_vals.fill(1)
values = []
weights = []
weights_squared = []
for ids, wts in zip(id_vals, weight_... | s]
for i, weight_value in zip(ids, wts):
if partition_strategy == "mod":
val = np.copy(params[_PName(i % num_shards) + ":0"][
i // num_shards, :]) * weight_value
elif partition_strategy == "div":
ids_per_partition, extras = divmod(vocab_size, num_shards)
threshold = e... |
cloudera/hue | desktop/core/src/desktop/api_public_urls.py | Python | apache-2.0 | 7,696 | 0.007147 | #!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you ma... | .conf.urls import url as re_path
# "New" query API (i.e. connector based, lean arguments).
# e.g. https://demo.gethue.com/api/query/execute/ | hive
urlpatterns = [
re_path(r'^query/create_notebook/?$', api_public.create_notebook, name='query_create_notebook'),
re_path(r'^query/autocomplete/?$', api_public.autocomplete, name='query_autocomplete_databases'),
]
# Compatibility with "old" private API.
# e.g. https://demo.gethue.com/notebook/api/execute/hive
... |
subramani95/neutron | neutron/tests/unit/vmware/nsxlib/test_router.py | Python | apache-2.0 | 45,472 | 0.000044 | # Copyright (c) 2014 VMware, 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 writi... | gins.vmware.api_client import exception as api_exc
from neutron.plugins.vmware.api_client import version as version_module
from neutron.plugins.vmware.common import exceptions as nsx_exc
from neutron.plugins.vmware.common import utils
from neutron.plugins.vmware import nsxlib
from neutron.plugins.vmware.nsxlib import r... | vmware.nsxlib import base
_uuid = test_api_v2._uuid
class TestNatRules(base.NsxlibTestCase):
def _test_create_lrouter_dnat_rule(self, version):
with mock.patch.object(self.fake_cluster.api_client,
'get_version',
new=lambda: version_module.Ver... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.