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 |
|---|---|---|---|---|---|---|---|---|
sidnarayanan/PandaProd | Producer/python/utils/puppi_cff.py | Python | mit | 1,650 | 0.025455 | import FWCore.ParameterSet.Config as cms
# Copied from PhysicsTools.PatAlgos.slimming.puppiForMET_cff import makePuppiesFromMiniAOD
from CommonTools.PileupAlgos.Puppi_cff import puppi
puppi.candName = 'packedPFCandidates'
puppi.vertexName = 'offlineSlimmedPrimaryVertices'
#puppi.useExistingWeights = False # I still d... | d = cms.EDProducer("CandViewMerger",
src = cms.VInputTag('puppiNoLep', 'pfLeptonsPUPPET')
)
import PandaProd.Producer.utils.egmidconf as egmidconf
from CommonTools.PileupAlgos.PhotonPuppi_cff import puppiPhoton
puppiFor | MET = puppiPhoton.clone(
candName = 'packedPFCandidates',
photonName = 'slimmedPhotons',
runOnMiniAOD = True,
puppiCandName = 'puppiMerged',
useRefs = False, # need to perform dR matching because of "an issue in refs in PackedCandidates"
photonId = egmidconf.photonLooseId
)
puppiMETSequence = ... |
elzaggo/pydoop | examples/avro/py/check_results.py | Python | apache-2.0 | 1,677 | 0.001193 | # BEGIN_COPYRIGHT
#
# Copyright 2009-2018 CRS4.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may | obtain a copy
# of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See th | e
# License for the specific language governing permissions and limitations
# under the License.
#
# END_COPYRIGHT
import sys
import os
import errno
from collections import Counter
from pydoop.utils.py3compat import iteritems
def iter_lines(path):
try:
contents = os.listdir(path)
except OSError as e... |
ubiqx-org/Carnaval | carnaval/smb/SMB_Core.py | Python | agpl-3.0 | 6,873 | 0.008148 | # -*- coding: utf-8 -*-
# ============================================================================ #
# SMB_Core.py
#
# Copyright:
# Copyright (C) 2014 by Christopher R. Hertel
#
# $Id: SMB_Core.py; 2019-04-14 16:25:33 -0500; Christopher R. Hertel$
#
# -----------------------------... | microsecond, or 10^-7 seconds).
There is no "official" prefix for 10^-7, so use of | the term
"bozosecond" is on your own recognizance.
FILETIME values are 64-bit unsigned integers, supporting a date range
from the Windows Epoch to 28-May-60056.
"""
# References:
# Implementing CIFS: The Common Internet File System
# Section 2.6.3.1 under "SystemTimeLow and SystemTimeHigh"
# ... |
home-assistant/home-assistant | homeassistant/components/recollect_waste/__init__.py | Python | apache-2.0 | 2,425 | 0.001649 | """The ReCollect Waste integration."""
from __future__ import annotations
from datetime import date, timedelta
from aiorecollect.client import Client, PickupEvent
from aiorecollect.errors import RecollectError
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import Platform
from homeassi... | ry.data[CONF_SERVICE_ID], session=session
)
async def async_get_pickup_events() -> list[PickupEvent]:
"""Get the next pickup."""
try:
return await client.async_get_pickup_events(
start_date=date.today(), end_date=date.today() + timedelta(weeks=4)
)
... | r:
raise UpdateFailed(
f"Error while requesting data from ReCollect: {err}"
) from err
coordinator = DataUpdateCoordinator(
hass,
LOGGER,
name=f"Place {entry.data[CONF_PLACE_ID]}, Service {entry.data[CONF_SERVICE_ID]}",
update_interval=DEFAULT... |
erdinc-me/Defter3 | sub/remote/gmail/gmailApiWorkers.py | Python | gpl-3.0 | 14,818 | 0.00189 | # -*- coding: utf-8 -*-
__project_name__ = 'Defter3'
__author__ = 'Erdinç Yılmaz'
__date__ = '7/20/15'
from PyQt5.QtCore import QObject, pyqtSignal, pyqtSlot, QModelIndex
import base64
import email
# import quopri
# from googleapiclient.http import BatchHttpRequest
import httplib2
from apiclient import errors
# fro... | #################################################################
class GmailAPIWorkerSearch(QObject):
# ## in
sThreadConnectToServer = pyqtSignal(object)
sThreadCancelFetch = pyqtSignal()
sThreadDisconnectFromServer = pyqtSignal()
sThreadUploadFile = pyqtSignal(str, str, str, str, QModelIndex)
... | ToTrash = pyqtSignal(bool, str, QModelIndex, str)
sThreadCreateFolder = pyqtSignal(str, str, QModelIndex)
# ## out ###
stConnectedToServer = pyqtSignal(str)
stMessageIdListsRetrieved = pyqtSignal(dict)
# stFilesRetrieved = pyqtSignal(dict)
stDisconnectedFromServer = pyqtSignal()
stSetConnec... |
sysadminmatmoz/odoo-clearcorp | TODO-8.0/hr_payroll_pay_commission/hr_payroll_pay_commission.py | Python | agpl-3.0 | 2,121 | 0.004715 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Original Module by SIESA (<http://www.siesacr.com>)
# Refactored by CLEARCORP S.A. (<http://clearcorp.co.cr>)
#
# This program is free software: you can redis... | 'invoice_id': fields.related('commission_id', 'invoice_id', type='many2one',
obj='account.invoice', string='Invoice', readonly=True),
'input_id': fields.many2one('hr.payslip.input', ondelete='restrict', string='Input'),
'slip_id':fields.related('input_id', 'payslip_id', type='many2one',
... | ds.float('Amount Paid', digits=(16,2)),
}
_constraints = [(_check_amount_paid, 'Value must be greater or equal than 0.', ['amount_paid'])] |
DirectXMan12/nova-hacking | nova/api/openstack/compute/contrib/coverage_ext.py | Python | apache-2.0 | 11,724 | 0.000938 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 IBM Corp.
#
# 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
#
# ... | rom nova.openstack.common import log as logging
from nova.openstack.common.rpc import common as rpc_common
LOG = | logging.getLogger(__name__)
authorize = extensions.extension_authorizer('compute', 'coverage_ext')
CONF = cfg.CONF
class CoverageController(object):
"""The Coverage report API controller for the OpenStack API."""
def __init__(self):
self.data_path = None
self.services = []
self.combine... |
rabimba/p2pScrapper | BitTorrent-5.2.2/BitTorrent/GUI_wx/LanguageSettings.py | Python | mit | 5,226 | 0.006123 | # The contents of this file are subject to the BitTorrent Open Source License
# Version 1.1 (the License). You may not copy or use this file, in either
# source code or executable form, except in compliance with the License. You
# may obtain a copy of the License at http://www.bittorrent.com/license/.
#
# Software di... | _sizer.Add(self.choice, flag=wx.GROW|wx.ALL, border=SPACING)
self.box_sizer.Add(restart, flag= | wx.BOTTOM|wx.LEFT|wx.RIGHT, border=SPACING)
self.box_sizer.Add(self.bottom_error, flag=wx.BOTTOM|wx.LEFT|wx.RIGHT, border=SPACING)
# clear out bottom error
self.clear_error()
self.sizer.AddFirst(self.box_sizer, flag=wx.GROW)
self.sizer.Fit(self)
def set_language(self, *a)... |
svn2github/vbox | src/VBox/ValidationKit/testmanager/webui/wuifailurecategory.py | Python | gpl-2.0 | 4,643 | 0.012061 | # -*- coding: utf-8 -*-
# $Id$
"""
Test Manager WUI - Failure Categories Web content generator.
"""
__copyright__ = \
"""
Copyright (C) 2012-2014 Oracle Corporation
This file is part of VirtualBox Open Source Edition (OSE), as
available from http://www.virtualbox.org. This file is free software;
you can redistribute... | ActionFailureCategoryShowEdit,
FailureCategoryData.ksParam_idFailureCategory: oEntry.idFailureCategory }),
WuiTmLink('Remove', WuiAdmin.ksScriptName,
{ WuiAdmin.ksParamAction: WuiAdmin.ksActionFailureCategoryDel,
... | want to remove failure cateogry #%d?' % (oEntry.idFailureCategory,)),
] ];
|
vvw/linearAlgebra-coursera | assignment 5/perspective_lab/perspective_lab.py | Python | mit | 4,055 | 0.015536 | from image_mat_util import *
from mat import Mat
from vec import Vec
import matutil
from solver import solve
## Task 1
def move2board(v):
'''
Input:
- v: a vector with domain {'y1','y2','y3'}, the coordinate representation of a point q.
Output:
- A {'y1','y2','y3'}-vector z, the coordina... | erspective_lab.make_equations(592, 157, 1, 0)[0]
# row_dict[5] = perspective_lab.make_equations(592, 157, 1, 0)[1]
# row_dict[6] = perspective_lab.make_equations(580, 483, 1, 1)[0]
# row_dict[7] = pers | pective_lab.make_equations(580, 483, 1, 1)[1]
# foo = perspective_lab.make_equations(0, 0, 0, 0)[0]
# foo[('y1', 'x1')] = 1
# foo[('y1', 'x3')] = 0
# row_dict[8] = foo
# M = matutil.rowdict2mat(row_dict)
# print(M)
# solve(M, vecutil.list2vec([0, 0, 0, 0, 0, 0, 0, 0, 1]))
# Y_in = Mat(({'y1', 'y2', 'y3'}, {0,1,2,3}),
#... |
lmazuel/azure-sdk-for-python | azure-mgmt-containerinstance/azure/mgmt/containerinstance/models/usage_name.py | Python | mit | 1,236 | 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 may cause inco... | e code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.serialization import Model
class UsageName(Model):
"""The name object of the resource.
Variables are only populated by the server, and will be ignored when
sending a request.
:ivar valu... |
elfnor/sverchok | nodes/generators_extended/hilbert3d.py | Python | gpl-3.0 | 3,123 | 0.001281 | # ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distrib... | y = step * .5 * np.array([.5+xo, .5+zo, .5+zo, .5+yo, -.5+yo, -.5-zo, -.5-zo, -.5-xo])
z = step * .5 * np.array([.5+yo, -.5+xo, -.5+xo, .5-zo, .5-zo, -.5+xo, -.5+xo, .5-yo])
return [x, y, z]
vx, vy, vz = hilbert3(n)
vx = vx.flatten().tolist()
vy = vy.flatten().tolist()
vz = vz.fl... | ''' Hilbert3d line '''
bl_idname = 'Hilbert3dNode'
bl_label = 'Hilbert3d'
bl_icon = 'OUTLINER_OB_EMPTY'
level_ = IntProperty(
name='level', description='Level',
default=2, min=1, max=5,
options={'ANIMATABLE'}, update=updateNode)
size_ = FloatProperty(
name='size', d... |
SohKai/ChronoLogger | web/flask/lib/python2.7/site-packages/sqlalchemy/dialects/sqlite/base.py | Python | mit | 32,174 | 0.002797 | # sqlite/base.py
# Copyright (C) 2005-2012 the SQLAlchemy authors and contributors <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""Support for the SQLite database.
For information on connecting using a specific dri... | hemy's default mode of usage with the ORM is known
as "autocommit=False", which means the moment the :class:`.Session` begins to be
used, a transaction is begun. As the :class:`.Session` is used, the autoflush
featur | e, also on by default, will flush out pending changes to the database
before each query. The effect of this is that a :class:`.Session` used in its
default mode will often emit DML early on, long before the transaction is actually
committed. This again will have the effect of serializing access to the SQLite
database... |
francisrod01/wrangling_mongodb | lesson 2/nytimes.py | Python | mit | 3,355 | 0.00149 | #!~/envs/python3/udacity_python_mongodb
import json
import codecs
import requests
import os
URL_MAIN = "http://api.nytimes.com/svc/"
URL_POPULAR = URL_MAIN + "mostpopular/v2/"
API_KEY = {
"popular": "",
"article": ""
}
DATA_DIR = "datasets"
POPULAR_FILE = "popular-{0}-{1}.json"
MOST_FILE = "most{0}/{1}/{2}.j... | for mm in m["media-metadata"]:
if mm["format"] == "Standard Thumbnail":
urls.append(mm["url"])
return titles, urls
def query_site(url, target, offset):
# This will set up the query with the API key and offset
# Web services often use offset para... | he offset parameter.
if API_KEY["popular"] == "" or API_KEY["article"] == "":
print("You need to register for NYTimes Developer account to run this program.")
print("See Instructor notes for more information.")
return False
params = {
"api-key": API_KEY[target],
"offset"... |
tickbox-smc-ltd/xfero | src/xfero/db/manage_cots_pattern.py | Python | agpl-3.0 | 15,606 | 0.002371 | #!/usr/bin/env python
'''
**Purpose**
Module contains functions to manage the database table XFERO_COTS_Pattern
**Unit Test Module:** test_crud_XFERO_COTS_Pattern.py
**Process Flow**
.. figure:: ../process_flow/manage_cots_patterns.png
:align: center
Process Flow: Manage COTS Pattern
*External dependenci... | -------------+---------------------------------------------------+
'''
import sqlite3 as lite
from /xfero/ import get_conf as get_conf
import logging.config
def create_XFERO_COTS_Pattern(cotspattern_product, co | tspattern_pattern_name,
cotspattern_prototype, xfero_token=False):
'''
**Purpose:**
The function ```create_XFERO_COTS_Pattern``` is a script to insert a row into
the XFERO_COTS_Pattern table.
It performs the following SQL statement:
```'INSERT INTO XFERO_COTS_Patte... |
dblenkus/rolca | src/rolca/core/views.py | Python | apache-2.0 | 3,758 | 0.000532 | """.. Ignore pydocstyle D400.
==========
Core views
==========
.. autofunction:: rolca.core.views.upload
"""
import io
import json
import logging
import os
import zipfile
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.http import (
HttpResponse,
HttpRe... | )
max_image_resolution = settings.MAX_IMAGE_RESOLUTION
if max(file_.file.width, file_.file.height) > max_image_resolution:
logger.warning("Too big file.")
return HttpResponseBadRequest(
"File can't excede size of {}px".format(settings.MAX_IMAGE_RESOLUTION)
)
file_.s... | basename(file_.file.name),
"size": file_.file.size,
"url": file_.file.url,
"thumbnail": file_.thumbnail.url,
"delete_url": '',
"delete_type": "POST",
}
)
response_data = json.dumps(result)
return HttpResponse(response_data, content_type='ap... |
stdweird/aquilon | tests/broker/test_usecase_hacluster.py | Python | apache-2.0 | 15,847 | 0.000694 | #!/usr/bin/env python2.6
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-
# ex: set expandtab softtabstop=4 shiftwidth=4:
#
# Copyright (C) 2012,2013 Contributor
#
# 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... | "service_address",
"hacl%dg1addr" % cl,
"config")
self.dsdb_expect_add("hacl%dg1.aqd-unittest.ms.com" % cl,
ips[cl - 1])
self.successtest(["add", "service | ", "address",
"--cluster", "hacl%d" % cl,
"--resourcegroup", "hacl%dg1" % cl,
"--service_address", "hacl%dg1.aqd-unittest.ms.com" % cl,
"--name", "hacl%dg1addr" % cl,
"--... |
koery/win-sublime | Data/Packages/Default/mark.py | Python | mit | 1,396 | 0.005014 | import sublime, sublime_plugin
class SetMarkCommand(sublime_plugin.TextCommand):
def run(self, edit):
mark = [s for s in self.view.sel()]
self.view.add_regions("mark", mark, "mark", "dot",
sublime.HIDDEN | sublime.PERSISTENT)
class SwapWithMarkCommand(sublime_plugin.TextCommand):
d... | for r in ol | d_mark:
self.view.sel().add(r)
class SelectToMarkCommand(sublime_plugin.TextCommand):
def run(self, edit):
mark = self.view.get_regions("mark")
num = min(len(mark), len(self.view.sel()))
regions = []
for i in range(num):
regions.append(self.view.sel()[i... |
willemw12/get_iplayer_downloader | src/get_iplayer_downloader/ui/log_dialog.py | Python | gpl-3.0 | 5,896 | 0.007463 | from gi.repository import Gtk, Pango
# Load application-wide definitions
import get_iplayer_downloader
#NOTE Import module, not symbol names inside a module, to avoid circular import
import get_iplayer_downloader.ui.main_window
from get_iplayer_downloader import command_util
from get_iplayer_downloader.tools import ... | #scrolled_window.grab_focus()
if button_id | == FULL_LOG_BUTTON_ID or button_id == SUMMARY_LOG_BUTTON_ID:
if button_id_prev != button_id:
# Log view changed (different log view type or log files removed)
# Scroll to top
label = self.dialog.get_scrolled_label()
adjustme... |
gmr/queries | queries/results.py | Python | bsd-3-clause | 3,382 | 0 | """
query or callproc Results
"""
import logging
import psycopg2
LOGGER = logging.getLogger | (__name__)
class Results(object):
"""The :py:class:`Results` class contains the results returned from
:py:meth:`Session.query <queries.Session.query>` and
:py:meth:`Session.callproc <queries. | Session.callproc>`. It is able to act
as an iterator and provides many different methods for accessing the
information about and results from a query.
:param psycopg2.extensions.cursor cursor: The cursor for the results
"""
def __init__(self, cursor):
self.cursor = cursor
def __getite... |
Enteee/pdml2flow | pdml2flow/flow.py | Python | apache-2.0 | 3,496 | 0.001144 | # vim: set fenc=utf8 ts=4 sw=4 et :
import json
import dict2xml
from .autovivification import AutoVivification
from .conf import Conf
from .utils import call_plugin
from .logging import *
class Flow():
# The overall frame time
newest_overall_frame_time = 0
@staticmethod
def get_flow_id(frame):
... | rame_time
@property
def newest_frame_time(self):
return self.__newest_frame_time
@property
def framecount(self):
return self.__framecount
def add_frame(self, frame):
# check if frame expands flow length
frame_time = frame[Conf.FRAME_TIME]
self.__first_frame... | frame_time)
self.__framecount += 1
# Extract data
if Conf.FRAMES_ARRAY:
self.__frames.append(
frame.clean_empty()
)
else:
self.__frames.merge(
frame.clean_empty()
)
if Conf.COMPRESS_DATA:
... |
robwebset/script.ebooks | resources/lib/mobi/__init__.py | Python | gpl-2.0 | 7,612 | 0.011167 | #!/usr/bin/env python
# encoding: utf-8
# https://github.com/kroo/mobi-python
"""
Mobi.py
Created by Elliot Kroo on 2009-12-25.
Copyright (c) 2009 Elliot Kroo. All rights reserved.
"""
import sys
from struct import *
from lz77 import uncompress_lz77
class Mobi:
def parse(self):
""" reads in the file, then pars... | unt",
"First DATP Record",
"DATP Record Count",
"EXTH flags",
"-36 u | nknown bytes, if Mobi is long enough",
"DRM Offset",
"DRM Count",
"DRM Size",
"DRM Flags",
"-Usually Zeros, unknown 8 bytes",
"-Unknown",
"Last Image Record",
"-Unknown",
"FCIS record",
"-Unknown",
"FLIS record",
"Unknown"
]
header = se... |
osiell/oerplib | oerplib/rpc/__init__.py | Python | lgpl-3.0 | 10,786 | 0.001669 | # -*- coding: UTF-8 -*-
##############################################################################
#
# OERPLib
# Copyright (C) 2011-2013 Sébastien Alix.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# ... | r, self.port)
setattr(self, service_name, srv)
ret | urn srv
class ConnectorJSONRPC(Connector):
"""Connector class using the `JSON-RPC` protocol.
>>> from oerplib import rpc
>>> cnt = rpc.ConnectorJSONRPC('localhost', port=8069)
Open a user session:
>>> cnt.proxy.web.session.authenticate(db='database', login='admin', password='admin')
{u'json... |
svanschalkwyk/datafari | windows/python/Lib/test/test_threadedtempfile.py | Python | apache-2.0 | 2,021 | 0.004948 | """
Create and delete FILES_PER_THREAD temp files (via tempfile.TemporaryFile)
in each of NUM_THREADS threads, recording the number of successes and
failures. A failure is a bug in tempfile, and may be due to:
+ Trying to create more than one tempfile with the same name.
+ Trying to delete a tempfile that doesn't sti... | a 2.0 failure under Linux.
"""
NUM_THREADS = 20
FILES_PER_THREAD = 50
import tempfile
from test.test_support import start_threads, run_unittest, import_module
threading = import_module('threading')
import unittest
import StringIO
from traceback import print_exc
startEvent = threading.Event()
class TempFileGreedy(... | THREAD):
try:
f = tempfile.TemporaryFile("w+b")
f.close()
except:
self.error_count += 1
print_exc(file=self.errors)
else:
self.ok_count += 1
class ThreadedTempFileTest(unittest.TestCase):
def test_m... |
pmandr/plant_carer | MyGarden/manage.py | Python | gpl-3.0 | 806 | 0 | #!/usr | /bin/env python
import os
import sys
if __name_ | _ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "MyGarden.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that the
# issue is really that Django is missing to a... |
earney/asetniop | src/machine/test_registry.py | Python | gpl-2.0 | 1,430 | 0.004895 | # Copyright (c) 2013 Hesky Fisher
# See LICENSE.txt for details.
"""Unit tests for registry.py."""
import unittest
from registry import Registry, machine_registry, NoSuchMachineException
class RegistryClassTestCase(unittest.TestCase):
def test_lookup(self):
registry = Registry()
registry.regis | ter('a', 1)
self.assertEqual(1, registry.get('a'))
def test_unknown_entry(self):
registry = Registry()
with self.assertRaises(NoSuchMachineException):
registry.get('b')
def test_alias(self):
registry = Registry()
registry.register('a', 1)
... | ', 'a')
self.assertEqual(registry.resolve_alias('b'), 'a')
self.assertEqual(1, registry.get('b'))
def test_all_names(self):
registry = Registry()
registry.register('a', 1)
registry.register('b', 5)
registry.add_alias('c', 'b')
self.assertEqual(['a... |
jawilson/home-assistant | homeassistant/components/aws/config_flow.py | Python | apache-2.0 | 507 | 0.001972 | """Config flow for AWS component."""
from homeassistant import config_entries
from .const import DOMAIN
class AWSFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
"""Handle a config flow."""
VERSION = 1
async def async_step_import(self, user_input):
"""Import a config entry."""
if... | ntries():
return self.async_abort(reason="single_instance_allowed")
| return self.async_create_entry(title="configuration.yaml", data=user_input)
|
shaun-h/pythonista-objc-utils | Audio Recording.py | Python | mit | 1,104 | 0.033514 | # this is based in the audio recording example provided by omz (Ole Zorn)
from objc_util import *
import os
def main():
AVAudioSession = ObjCClass('AVAudioSession')
NSURL = ObjCClass('NSURL')
AVAudioRecorder = ObjCClass('AVAudioRecorder')
shared_session = AVAudioSession.sharedInstance()
category_set = shared_sess... | Key'):ns(2)}
output_path = os.path.abspath('Recording.m4a')
out_url = NSURL.fileURLWithPath_(ns(output_path))
rec | order = AVAudioRecorder.alloc().initWithURL_settings_error_(out_url, settings, None)
started_recording = recorder.record()
if started_recording:
print('Recording started, press the "stop script" button to end recording...')
try:
while True:
pass
except KeyboardInterrupt:
print('Stopping...')
recorder.s... |
davidwboswell/documentation_autoresponse | lib/l10n_utils/gettext.py | Python | mpl-2.0 | 8,132 | 0 | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from __future__ import with_statement
import codecs
import os
import re
from os.path import join
from tokenize import g... |
return ext == '.html'
def is_python(path):
(base, ext) = os.path.splitext(path)
return ext == '.py'
def parse_python(path):
"""
Look though a python file and extract the specified `LANG_FILES` constant
value and return it.
`LANG_FILES` must be defined at the module level, and can be a ... | en(path, encoding='utf-8') as src_f:
tokens = generate_tokens(src_f.readline)
for token in tokens:
t_type, t_val, (t_row, t_col) = token[:3]
# find the start of the constant declaration
if t_type == NAME and t_col == 0 and t_val == 'LANG_FILES':
in_lan... |
pepsipepsi/nodebox_opengl_python3 | examples/05-path/05-spider.py | Python | bsd-3-clause | 1,901 | 0.023672 | import os, sys
sys.path.insert(0, os.path.join("..",".."))
from nodebox.graphics.shader import render
from nodebox.graphics.context import *
from nodebox.graphics import *
from nodebox.graphics.geometry import distance
def spider(string, x=0, y=0, radius=25, **kwargs):
""" A path filter that creates web thread... | index.php/Path_Filters
"""
# **kwargs represents any additional optional parameters.
# For example: spider("hello", 100, 100, font="Helvetica") =>
| # kwargs = {"font": "Helvetica"}
# We pass these on to the textpath() call in the function;
# so the spider() function takes the same parameters as textpath:
# x, y, font, fontsize, fontweight, ...
font(
kwargs.get("font", "Droid Sans"),
kwargs.get("fontsize", 100))
p = textpath... |
leighpauls/k2cro4 | third_party/WebKit/Tools/Scripts/webkitpy/tool/bot/sheriff_unittest.py | Python | bsd-3-clause | 3,776 | 0.001589 | # Copyright (C) 2010 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the f... | ing disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be | used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR... |
arvinddoraiswamy/mywebappscripts | BurpExtensions/FileUploadFuzz.py | Python | mit | 1,693 | 0.014767 | from burp import IBurpExtender
from burp import IContextMenuFactory
from javax.swing import JMenuItem
import sys
import os
import re
#Adding directory to the path where Python searches for modules
module_folder = os.path.dirname('/home/arvind/Documents/Me/My_Projects/Git/WebAppsec/BurpExtensions/modules/')
sys.path.in... | \2', request, re.DOTALL|re.MULTILINE)
# Add regex to substitute fileContent depending on request structure
def getListOfFiles(self):
| fileList= []
for filename in os.listdir(filePayloadDir):
fileList.append(filename)
return fileList
|
stephrdev/brigitte | brigitte/repositories/migrations/0012_auto__add_field_repository_last_commit_date.py | Python | bsd-3-clause | 5,432 | 0.008837 | # encoding: 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 field 'Repository.last_commit_date'
db.add_column('repositories_repository', 'last_commit_date', ... | ield', [], {'max_length': '80'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
},
'repositories.repositoryuser': {
'Meta': {'unique_together': "(('repo', 'user'),)", 'object_n | ame': 'RepositoryUser'},
'can_admin': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'can_read': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'can_write': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ... |
openhomity/homity-hub | runhub.py | Python | apache-2.0 | 1,615 | 0.002477 | """
Launcher for homity-hub
"""
from Hub import app
from Hub.api import hub_config
import cherrypy
from paste.translogger import TransLogger
if hub_config.get('ssl_enable'):
from OpenSSL import SSL
def run_cherrypy():
"""Start CherryPy server."""
#Enable WSGI access logging via Paste
app_logged = Tr... | host': '0.0.0.0'
}
if hub_config.get('ssl_enable'):
cherrypy_config['server.ssl_module'] = 'builtin'
cherrypy_config['server.ssl_private_key'] = hub_config.get(
'ssl_private_key')
cherrypy_config['server.ssl_certificate'] = hub_config.get(
'ssl_cert')
cherryp... | ne.block()
def run_werkzeug():
""" Werkzeug deprecated in favor of CherryPy. """
if hub_config.get('ssl_enable'):
context = SSL.Context(SSL.SSLv23_METHOD)
context.use_privatekey_file(hub_config.get('ssl_private_key'))
context.use_certificate_file(hub_config.get('ssl_cert'))
app.... |
staranjeet/fjord | vendor/packages/requests-2.7.0/requests/packages/chardet/euctwprober.py | Python | bsd-3-clause | 1,674 | 0.001792 | ######################## BEGIN LICENSE BLOCK ########################
# The Original Code is mozilla.org code.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 1998
# the Initial Developer. All Rights Reserved.
#
# Con... | ,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# Licen | se along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
# 02110-1301 USA
######################### END LICENSE BLOCK #########################
from .mbcharsetprober import MultiByteCharSetProber
from .codingstatemachine import CodingStateMachine
from ... |
junkoda/mockgallib | script/compute_corr_multipole.py | Python | gpl-3.0 | 3,670 | 0.006812 | """
This script computes correlation function multipoles from given files of
galalxy and random catalgues
python3 compute_corr_multipole.py
Args:
n: index of mock
Options:
--igalaxies=1:1
--irandoms=1:1
Input:
mocks/mock_<n>.txt
randoms/random_<n>.txt
File format is:
x y z
in ea... | axies[0])
i1 = int(igalaxies[1]) + 1
for i in range(i0, i1):
ii= i - i0
r = corr.r_i(ii)
xi0 = corr.xi0_i(ii)
xi2 = corr.xi2_i(ii)
nrow= | len(r)
filename = '%s/corr_multipole_%05d.txt' % (arg.o, i)
with open(filename, 'w') as f:
for irow in range(nrow):
f.write('%e %e %e\n' % (r[irow], xi0[irow], xi2[irow]))
print('%s written' % filename)
|
piMoll/SEILAPLAN | lib/reportlab/lib/fontfinder.py | Python | gpl-2.0 | 13,553 | 0.006862 | #Copyright ReportLab Europe Ltd. 2000-2019
#see license.txt for license details
__version__='3.4.22'
#modification of users/robin/ttflist.py.
__doc__="""This provides some general-purpose tools for finding fonts.
The FontFinder object can search for font files. It aims to build
a catalogue of fonts which our framewo... | parse hundreds of fonts,
it can use a cache to store a file w | ith all fonts found. The cache file name
For each font found, it creates a structure with
- the short font name
- the long font name
- the principal file (.pfb for type 1 fonts), and the metrics file if appropriate
- the time modified (unix time stamp)
- a type code ('ttf')
- the family name
- bold and italic attribut... |
kyleabeauchamp/HMCNotes | code/misc/benchmark_mts_july.py | Python | gpl-2.0 | 1,588 | 0.005038 | import time
import simtk.openmm.app as app
import simtk | .openmm as mm
from simtk import unit as u
from openmmtools import hmc_integrators, testsystems, integrators
testsystem = testsystems.DHFRExplicit(rigid_water=False, constraints=None)
system, topology, positions = testsystem.system, testsystem.topology, testsystem.positions
platform = mm.Platform.getPlatformByName('C... | ystem, nonbonded=0, others=0, fft=0)
#groups = [(0, 1)]
# new (65.32461094856262, 13.226255578932173, 76.54083089659821, 76.54083089659821)
# old (64.60578417778015, 13.373415569455394, 77.39245121212612, 77.39245121212612)
hmc_integrators.guess_force_groups(system, nonbonded=0, others=0, fft=0)
groups = [(0, 1), (1, ... |
lebauce/darling | tools/gdb_maloader.py | Python | gpl-3.0 | 2,497 | 0.0004 | # Copyright 2011 Shinichiro Hamaji. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions ... | RANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Shinichiro Hamaji OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, B | UT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
# OF THE USE OF THIS SOFTWARE, EVEN IF... |
EntPack/SilentDune-Client | silentdune_client/sdc_firewall.py | Python | lgpl-3.0 | 12,943 | 0.002627 | #
# Authors: Robert Abram <robert.abram@entpack.com>
#
# Copyright (C) 2015-2017 EntPack
# see file 'LICENSE' for use and warranty information
#
# 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, e... | or mod in mods:
mod.set_config(self._config) # Set the configuration information in the module.
# If the | module is enabled, add it to the active_mods list.
if mod.module_enabled():
active_mods.append(mod)
else:
_logger.debug('Service: module {0} is disabled.'.format(mod.get_name()))
pmanager = Manager()
mqueue = pmanager.Queue... |
annapowellsmith/openpresc | openprescribing/dmd2/gen_models/gen_models.py | Python | mit | 1,981 | 0.000505 | import csv
def model_name(table_name):
if table_name in [
'vtm',
'vpi',
'vmp',
'vmpp',
'amp',
'ampp',
'gtin',
]:
return table_name.upper()
else:
return ''.join(tok.title() for tok in table_name.split('_'))
def quote(s):
assert '... | l):')
print('# class Meta:')
| print('# verbose_name = "TODO"')
print()
if line['type'] == 'retired':
continue
options = []
if line['primary_key'] == 'True':
options.append(('primary_key', 'True'))
if line['db_column']:
options.append(('db_column', quote(line['db_column'])))
if li... |
Shaunwei/shua-shua-shua | G_farthest_BST_sum.py | Python | mit | 2,599 | 0.001924 | """
given a BST, find the two nodes that sums up to a value and are the farthest apart.
"""
class Tree:
def __init__(self, val):
self.val = val
self.left = self.right = None
def __repr__(self):
return '[ %d ]' % self.val
def get_tree():
def build_tree(vals):
if not vals:
... | mid+1:])
return root
return build_tree(range(1, 8))
def print_tree(r):
stac | k = []
while stack or r:
if r:
stack.append(r)
r = r.left
else:
r = stack.pop()
print(r)
r = r.right
class Solution:
def find_farthest_nodes(self, tree, sums):
values = self.in_order(tree)
distance = 0
nodes = ... |
kdmurray91/scikit-bio | skbio/metadata/_repr.py | Python | bsd-3-clause | 5,981 | 0 | # ----------------------------------------------------------------------------
# Copyright (c) 2013--, scikit-bio development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
# --------------------------------------------... | self._obj.positional_metadata.columns.values.tolist():
dtype = self._obj.positional_metadata[key].dtype
self._lines.add_lines(
self._format_positional_metadata_column(key, dtype))
def _format_positional_metadata_column(self, key, dtype):
key_fmt = self._f... | metadata key.
Includes initial indent and trailing colon and space:
<indent>'foo':<space>
"""
key_fmt = self._indent + repr(key)
supported_types = (str, bytes, numbers.Number, type(None))
if len(key_fmt) > (self._width / 2) or not isinstance(key,
... |
eth-cscs/production | easybuild/easyblocks/craytoolchain.py | Python | gpl-3.0 | 3,472 | 0.002592 | ##
# Copyright 2015-2021 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be),
# Flemish Research Foundation (F... | the terms of the GNU General Public License as published by
# the Free Software Foundation v2.
#
# EasyBuild 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 t | he
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with EasyBuild. If not, see <http://www.gnu.org/licenses/>.
##
"""
EasyBuild support for installing Cray toolchains, implemented as an easyblock
@author: Kenneth Hoste (Ghent University)
@au... |
devilry/trix2 | trix/project/develop/settings/develop.py | Python | bsd-3-clause | 57 | 0 | from .common impor | t * # noqa
LANGUAGE_CODE | = 'nb'
|
pereerro/schooly | school_base/school_groups.py | Python | agpl-3.0 | 1,792 | 0.00558 | # -*- coding: utf-8 -*-
##############################################################################
#
# School App for Odoo
# Copyright (C) 2015
# Pere Ramon Erro Mas <pereerro@tecnoba.com> All Rights Reserved.
#
# This file is a part of School App for Odoo
#
# School App for Odoo is free software:... | m datetime import datetime, date, timedelta
from openerp.tools.translate import _
class groups_part | icipation(osv.osv):
_name = 'groups.participation'
_inherit = 'groups.participation'
def name_get(self, cr, uid, ids, context = None):
res = []
for item in self.browse(cr, uid, ids):
session_name = item.session_id and item.session_id.name or ''
res.append((item['id']... |
KarlGong/ptest | ptest/config.py | Python | apache-2.0 | 12,010 | 0.005246 | import os
import platform
import re
from optparse import OptionParser, OptionGroup
from typing import List
from . import __version__
_properties = {}
_options = {}
def get_option(option: str) -> str:
try:
return _options[option]
except KeyError:
return None
def get_property(key: str, defa... | = re.compile(property_re | gex_str)
for line in file_object:
property_match = property_regex.search(line.strip())
if property_match:
_properties[property_match.group(1)] = property_match.group(2)
finally:
file_object.close()
def __load_args(args):
property_... |
eunchong/build | third_party/sqlalchemy_migrate_0_7_1/migrate/tests/versioning/test_genmodel.py | Python | bsd-3-clause | 7,057 | 0.008219 | # -*- coding: utf-8 -*-
import os
import sqlalchemy
from sqlalchemy import *
from nose.tools import eq_
from migrate.versioning import genmodel, schemadiff
from migrate.changeset import schema, SQLA_06
from migrate.tests import fixture
class TestSchemaDiff(fixture.DB):
table_name = 'tmp_schemadiff'
level ... | sertDiff(False, [], [], [])
if not self.engine.name == 'oracle':
# Make sure data is still present.
result = self.engine.execute(self.table.select(self. | table.c.id==dataId2))
rows = result.fetchall()
self.assertEquals(len(rows), 1)
self.assertEquals(rows[0].name, 'mydata2')
self.assertEquals(rows[0].data2, '123')
# Delete data, since we're about to make a required column.
# Not even us... |
aalto-speech/flatcat | flatcat/__init__.py | Python | bsd-2-clause | 1,193 | 0.006706 | #!/usr/bin/env python
"""
Morfessor 2.0 FlatCat - Python implementation of
the FlatCat variant of the Morfessor method
"""
import logging
__all__ = ['MorfessorException', 'ArgumentException', 'FlatcatIO',
'FlatcatModel', 'flatcat_main', 'get_flatcat_argparser',
'MorphUsageProperties', 'Heuristic... | author__ = 'Stig-Arne Gronroos'
__author_email__ = "morfessor@cis.hut.fi"
show_progress_bar = True
_logger = logging.getLogger(__name__)
def get_version(numeric=False):
if numeric:
return __version__
return 'FlatCat {}'.format(__version__)
# The public api import | s need to be at the end of the file,
# so that the package global names are available to the modules
# when they are imported.
from .flatcat import FlatcatModel, AbstractSegmenter
from .flatcat import FlatcatAnnotatedCorpusEncoding
from .categorizationscheme import MorphUsageProperties, HeuristicPostprocessor
from .ca... |
chromium/chromium | third_party/blink/tools/blinkpy/w3c/wpt_github_unittest.py | Python | bsd-3-clause | 15,485 | 0.000452 | # Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import base64
import json
import unittest
from blinkpy.common.host_mock import MockHost
from blinkpy.w3c.chromium_commit_mock import MockChromiumCommit
from... | elf):
self.wpt_github = WPTGitHub(
MockHost(), user='rutabaga', token='decafbad', pr_history_window=1)
self.wpt_github.host.web.responses = [
{
'status_code':
200,
'headers': {
'Link': ''
},
... | json.dumps({
'incomplete_results': False,
'items': [self.generate_pr_item(1)]
})
},
]
self.assertEqual(
len(self.wpt_github.recent_failing_chromium_exports()), 1)
def test_recent_failing_chromium_exports_all_pages... |
karstenw/nodebox-pyobjc | libs/pathmatics/pathmatics.py | Python | mit | 2,790 | 0.007527 | from math import sqrt, pow
def linepoint(t, x0, y0, x1, y1):
"""Returns coordinates for point at t on the line.
Calculates the coordinates of x and y for a point
at t on a straight line.
The t parameter is a number between 0.0 and 1.0,
x0 and y0 define the starting point of the line,
x1 and ... | bic bezier spline, and its control points,
based on the de Casteljau interpolation algorithm.
The t parameter is a number between 0.0 and 1.0,
x0 and y0 define the starting point of the spline,
x1 and y1 its control point,
x3 and y3 the e | nding point of the spline,
x2 and y2 its control point.
If the handles parameter is set,
returns not only the point at t,
but the modified control points of p0 and p3
should this point split the path as well.
"""
mint = 1 - t
x01 = x0 * mint + x1 * t
y01 = y0 * mint + ... |
gragas/simpletcp | examples/echoreverse/client.py | Python | apache-2.0 | 664 | 0 | from simpletcp.clientsocket import ClientSocket
s1 = ClientSocket("localhost", 5000)
response = s1.send | ("Hello, World!")
s2 = ClientSocket("localhost", 5000, single_use=False)
r1 = s2.send("Hello for the first time...")
r2 = s2.send("...and hello for the last!")
s2.close()
# Display the correspondence
print("s1 sent\t\tHello, World!")
print("s1 received\t\t{}".format( | response.decode("UTF-8")))
print("-------------------------------------------------")
print("s2 sent\t\tHello for the first time....")
print("s2 received\t\t{}".format(r1.decode("UTF-8")))
print("s2 sent\t\t...and hello for the last!.")
print("s2 received\t\t{}".format(r2.decode("UTF-8")))
|
wpoely86/easybuild-framework | easybuild/tools/repository/svnrepo.py | Python | gpl-2.0 | 6,109 | 0.002783 | # #
# Copyright 2009-2016 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be),
# Flemish Research Foundation (... | :
res = self.client.update(self.wc)
self.log.debug("Updated to revision %s in %s" % (res, self.wc))
except C | lientError:
raise EasyBuildError("Update in wc %s went wrong", self.wc)
if len(res) == 0:
raise EasyBuildError("Update returned empy list (working copy: %s)", self.wc)
if res[0].number == -1:
# revision number of update is -1
# means nothing has been che... |
MISP/MISP | tools/misp_retention.py | Python | agpl-3.0 | 3,874 | 0.003872 | #!/usr/bin/env python3
#
# This script requires the MISP retention taxonomy is installed and enabled
# See https://github.com/MISP/misp-taxonomies/tree/master/retention/retention
from pymisp import ExpandedPyMISP, MISPEvent
from datetime import datetime
from dateutil.relativedelta import relativedelta
import re
from k... | if tag["existing_tag"]["Tag"]["hide_tag"] is False:
| tag["existing_tag"]["Tag"]["hide_tag"] = True
self.misp.update_tag(tag["existing_tag"]["Tag"])
else:
raise Exception("Could not parse retention time/unit from tag: '{}'.".format(tag["tag"]))
if __name__ == "__main__":
misp = misphelper()
... |
apeng2012/apeng-kicad | tools/markcomp/markcomp.py | Python | mit | 4,277 | 0.002806 | # coding: utf-8
import argparse
from pyparsing import OneOrMore, nestedExpr
from progressbar import ProgressBar, Percentage, Bar
from time import time
from collections import defaultdict
import platform
last_val = -1
checked = False
mark_val = "0.1u"
class KiCAD_PCB:
def __init__(self, filename):
self.... | filename):
with open(filename) as f:
data = f.read()
start_time = time()
total_len = len(data)
bar = ProgressBar(widgets=['Parsing...', Percentage(), ' ', Bar('=', '|')], maxval=100).start()
def cb(locn, tokens):
global last_val, checked
val... | nabled
if not platform.python_implementation().startswith('PyPy'):
print "Parsing too slow? Consider using PyPy to accelerate the progress."
checked = True
bar.update(locn * 100 / total_len)
last_val = val
ast = One... |
SeungGiJeong/SK_FastIR | health/windows8_1StateMachine.py | Python | gpl-3.0 | 2,827 | 0.003184 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from statemachine import _Statemachine
class Windows8_1StateMachine(_Statemachine):
def __init__(self, params):
_Statemachine.__init__(self, params)
def _list_share(self):
return super(Windows8_1StateMachine, self)._list_share()
... | arp_table())
def csv_list_route_table(self):
super(Windows8_1StateMachine, self)._csv_list_route_table(self._list_route_table())
def csv_list_sockets | _networks(self):
super(Windows8_1StateMachine, self)._csv_list_sockets_network(self._list_sockets_network())
def csv_list_services(self):
super(Windows8_1StateMachine, self)._csv_list_services(self._list_services())
def csv_list_kb(self):
super(Windows8_1StateMachine, self)._csv_list_k... |
dongsenfo/pymatgen | pymatgen/electronic_structure/tests/test_bandstructure.py | Python | mit | 23,174 | 0.003884 | # coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
import unittest
import os
import json
from io import open
import warnings
from pymatgen.electronic_structure.bandstructure import Kpoint
from pymatgen import Lattice
from pymatgen.electronic_structure.core im... | dStructureSymmLine_test(PymatgenTest):
def setUp(self):
self.bs = loadfn(os.path.join(test_dir, " | Cu2O_361_bandstructure.json"))
self.bs2 = loadfn(os.path.join(test_dir, "CaO_2605_bandstructure.json"))
self.bs_spin = loadfn(os.path.join(test_dir, "NiO_19009_bandstructure.json"))
self.bs_cbm0 = loadfn(os.path.join(test_dir, "InN_22205_bandstructure.json"))
self.bs_cu = loadfn(os.path.... |
andrewpaulreeves/soapy | soapy/pyqtgraph/canvas/TransformGuiTemplate_pyqt5.py | Python | gpl-3.0 | 2,586 | 0.001547 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file './pyqtgraph/canvas/TransformGuiTemplate.ui'
#
# Created: Wed Mar 26 15:09:28 2014
# by: PyQt5 UI code generator 5.0.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Form(ob... | t(self.reflectImageBtn)
self.verticalLayout.addLayout(self.horizontalLayout)
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Form"))
... | ))
self.mirrorImageBtn.setText(_translate("Form", "Mirror"))
self.reflectImageBtn.setText(_translate("Form", "Reflect"))
|
shaneoc/atom | atom/http/headers.py | Python | mit | 7,250 | 0.010069 | from urlparse import urlparse, parse_qs
from datetime import datetime
from atom.logger import get_logger
from atom.http.exceptions import HTTPSyntaxError
log = get_logger(__name__)
status_codes = {
100: 'Continue',
200: 'OK',
302: 'Found',
400: 'Bad Request',
403: 'Forbidden',
404: 'Not Found... | )
@classmethod
def response(cls, code, message = None):
self = cls('response')
self.http_version = 'HTTP/1.1'
self.code = int(code)
self.message = message or status_codes[code]
return self
@classmethod
def request(cls, method, uri):
self = cls('r... | def raw(self):
if self.type == 'request':
ret = ['{} {} {}'.format(self.method, self.uri, self.http_version)]
else:
ret = ['{} {} {}'.format(self.http_version, self.code, self.message)]
ret.extend('{}:{}'.format(h[1], h[2]) for h in self._headers)
return '\r\n'.j... |
poldracklab/mriqcwebapi | dockereve-master/eve-app/settings.py | Python | apache-2.0 | 15,268 | 0.000131 | import os
from copy import deepcopy
bids_schema = {
# BIDS identification bits
'modality': {
'type': 'string',
'required': True
},
'subject_id': {
'type': 'string',
'required': True
},
'session_id': {'type': 'string'},
'run_id': {'type': 'string'},
'acq_i... | quired': True
},
'summary_fg_k': {
'type': 'float',
'required': True
},
'summary_fg_mean': {
'type': 'float',
'required': True
},
'summary_ | fg_median': {
'type': 'float',
'required': True
},
'summary_fg_mad': {
'type': 'float',
'required': True
},
'summary_fg_p05': {
'type': 'float',
'required': True
},
'summary_fg_p95': {
'type': 'float',
'required': True
},
's... |
jessicalucci/NovaOrc | nova/api/openstack/compute/contrib/used_limits.py | Python | apache-2.0 | 2,963 | 0 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-... | ed(req):
try:
return int(req.GET['reserved'])
except (ValueError, KeyError):
return False
@wsgi.extends
def index(self, req, resp_obj):
resp_obj.attach(xml=UsedLimitsTemplate())
context = req.environ['nova.context']
quotas = QUOTAS.get_project_quo... | res',
'totalInstancesUsed': 'instances',
'totalFloatingIpsUsed': 'floating_ips',
'totalSecurityGroupsUsed': 'security_groups',
}
used_limits = {}
for display_name, quota in quota_map.iteritems():
if quota in quotas:
reserved = (quot... |
Ivoz/pip | setup.py | Python | mit | 2,816 | 0.00071 | import codecs
import os
import re
import sys
from setuptools import setup, find_packages
from setuptools.command.test import test as TestCommand
here = os.path.abspath(os.path.dirname(__file__))
class PyTest(TestCommand):
def finalize_options(self):
TestCommand.finalize_options(self)
self.test... | ',
author='The pip developers',
author_email='python-virtualenv@groups.google.com',
url='http://www.pip-installer.org',
license='MIT',
packages=find_packages(exclude=["contrib", "docs", "tests*", "tasks"]),
package_data={
'pip._vendor.requests': ['*.pem'],
'pip._vendor.distlib._b... | , 'w64.exe'],
},
entry_points={
"console_scripts": [
"pip=pip:main",
"pip%s=pip:main" % sys.version[:1],
"pip%s=pip:main" % sys.version[:3],
],
},
tests_require=tests_require,
zip_safe=False,
extras_require={
'testing': tests_require,
... |
pokymobo/redomat | libredo/data/result_httpd.py | Python | mpl-2.0 | 4,908 | 0.00326 | #!/usr/bin/env python3
# coding:utf-8
from __future__ import print_function
'PackagesHTTPD - stream folder content as .tar over http'
__author__ = 'Mathias Gumz <mgumz@tpip.net>'
__license__ = 'MPL2'
__version__ = ''
import sys
import os, os.path
import zipfile, tarfile
from StringIO import StringIO
import cgi
try:... | .server import SimpleHTTPRequestHandler, HTTPServer
except Impor | tError: # assume py2
from BaseHTTPServer import HTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler
class PackagesHTTPD(SimpleHTTPRequestHandler):
'''
httpd-server to stream the contents of a given folder as
/packages.tar if /packages.tar is accessed. otherwise
it acts just like S... |
gutooliveira/progScript | tekton/backend/apps/emprestado_app/facade.py | Python | mit | 2,614 | 0.004208 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from gaegraph.business_base import NodeSearch, DeleteNode
from emprestado_app.commands import ListEmprestadoCommand, SaveEmprestadoCommand, UpdateEmprestadoCommand, \
EmprestadoPublicForm, EmprestadoDetailForm, EmprestadoShortForm, Sal... | ate Emprestado entity with id equals 'emprestado_id'
:param emprestado_properties: a dict of properties to update model
:return: a Command that update Emprestado, validating and localizing properties received as strings
"""
return UpdateEmprestadoCommand(emprestado_id, **emprestado_properties)
def lis... | o list Emprestado entities ordered by their creation dates
:return: a Command proceed the db operations when executed
"""
return ListEmprestadoCommand()
def emprestado_detail_form(**kwargs):
"""
Function to get Emprestado's detail form.
:param kwargs: form properties
:return: Form
"""
... |
ema/conpaas | conpaas-services/src/conpaas/services/webservers/manager/autoscaling/monitoring.py | Python | bsd-3-clause | 23,600 | 0.019068 |
"""
Monitoring Controller collects all the informantion extracted using Ganglia monitoring system.
@author: fernandez
"""
import sys
from subprocess import Popen, PIPE
import memcache
import socket
from time import time
from os import path, listdir
from conpaas.services.webservers.manager.autoscaling.performance imp... | except:
print >>sys.stderr, 'Failed to read configuration file'
sys.exit(1)
#initialize a memcache client
memcache_addr = config_parser.get('manager', 'MEMCACHE_ADDR')
if memcache_addr == '':
pr | int >>sys.stderr, 'Failed to find memcache address in the config file'
sys.exit(1)
self.memcache = memcache.Client([memcache_addr])
self.perf_info = ServicePerformance()
self._performance_info_set(self.perf_info)
self.monitoring_metrics_web = ['web_request_rate', 'web_res... |
jinglundong/GuessGame | service/indicator.py | Python | mit | 827 | 0.004837 | from collections import defaultdict
class Indicator():
def indicate( | self, guess, answer):
if(len(guess) != len(answer)):
raise InvalidInput("Length of answer and guess are different.")
aligned = 0;
not_aligned = 0;
chars_guess = defaultdict(int)
chars_answer = defaultdict(int)
for i in range(len(guess)):
char_gu... | char_answer = answer[i:i+1]
if char_guess == char_answer:
aligned += 1
else:
chars_guess[char_guess] += 1
chars_answer[char_answer] += 1
for key, value in chars_guess.iteritems():
if chars_answer.get(key):
... |
rdio/sentry | src/sentry/migrations/0094_auto__add_eventmapping__add_unique_eventmapping_project_event_id.py | Python | bsd-3-clause | 29,441 | 0.008356 | # -*- 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 'EventMapping'
db.create_table('sentry_eventmapping', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
... | .gf('django.db.models.fields.related.ForeignKey')(to=orm['sentry.Group'])),
('event_id', self.gf('django.db.models.fields.CharField')(max_length=32)),
('date_added', self.gf('django.db.models.fields.DateTimeField')(default=datetime.datetime.now)),
))
db.send_create_signal('sentry... |
dashpay/dash | test/functional/feature_bip68_sequence.py | Python | mit | 17,835 | 0.003869 | #!/usr/bin/env python3
# Copyright (c) 2014-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test BIP68 implementation."""
from test_framework.test_framework import BitcoinTestFramework
from test... | es, and leave 50 for the output
tx_size = len(ToHex(tx))//2 + 120*num_inputs + 50
tx.vout.append(CTxOut(int(value-self.relayfee*tx_size*COIN/1000), CScript([b'a'])))
rawtx = self.nodes[0].signrawtransactionwithwallet(ToHex(tx))["hex"]
if (using_sequence_locks a | nd not should_ |
andrewleech/script.module.pycurl | lib/pycurl/pycurl-7.19.5.1/tests/reset_test.py | Python | lgpl-2.1 | 2,691 | 0.003716 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# vi:ts=4:et
import pycurl
import unittest
import sys
try:
import urllib.parse as urllib_parse
except ImportError:
import urllib as urllib_parse
from . import appmanager
from . import util
setup_module, teardown_module = appmanager.setup(('app', 8380))
class Re... | break
count, good, bad = cm.info_read()
for h | , en, em in bad:
print("Transfer to %s failed with %d, %s\n" % \
(h.getinfo(pycurl.EFFECTIVE_URL), en, em))
raise RuntimeError
for h in good:
httpcode = h.getinfo(pycurl.RESPONSE_CODE)
if httpcode != 200:
... |
zake7749/Chatbot | Chatbot/QuestionAnswering/responsesEvaluate.py | Python | gpl-3.0 | 5,244 | 0.005353 | import logging
import os
import math
from collections import defaultdict
from gensim import corpora
# 引入斷詞與停用詞的配置
from .Matcher.matcher import Matcher
class Evaluator(Matcher):
"""
讀入一串推文串列,計算出當中可靠度最高的推文
"""
def __init__(self,segLib="Taiba"):
#FIXME 若「線上版本」受記憶體容量限制,需考慮更換為 jieba!
sup... | Words(path=self.path + "/data/stopwords/specialMarks.txt")
self.loadFilterdWord(path=self.path + "/data/stopwords/ptt_words.txt")
def cleanFormerResult(self):
"""
清空之前回應留下的紀錄
"""
self.responses = []
self.seg | Responses = []
self.totalWords = 0
def getBestResponse(self, responses, topk, debugMode=False):
"""
從 self.responses 中挑選出可靠度前 K 高的回應回傳
Return : List of (reply,grade)
"""
self.cleanFormerResult()
self.buildResponses(responses)
self.segmentResponse()
... |
IgniparousTempest/py-minutiae-viewer | pyminutiaeviewer/gui_editor.py | Python | mit | 5,203 | 0.002306 | import math
from pathlib import Path
from tkinter import W, N, E, StringVar, PhotoImage
from tkinter.ttk import Button, Label, LabelFrame
from overrides import overrides
from pyminutiaeviewer.gui_common import NotebookTabBase
from pyminutiaeviewer.minutia import Minutia, MinutiaType
class MinutiaeEditorFrame(Notebo... | 0
self.root.minutiae.appen | d(Minutia(round(px * scale_factor), round(py * scale_factor), angle, minutiae_type, 1.0))
self.current_minutiae = None
self.root.draw_minutiae()
self._update_minutiae_count()
class InfoFrame(LabelFrame):
def __init__(self, parent, title, minutiae_count):
super(self.__class__, self... |
popeye123/studip-sync | studip_sync/parsers.py | Python | unlicense | 8,325 | 0.002282 | import cgi
import json
import re
import urllib.parse
from bs4 import BeautifulSoup
class ParserError(Exception):
pass
def extract_files_flat_last_edit(html):
def extract_json(s):
form = s.find('form', id="files_table_form")
if not form:
raise ParserError("last_edit: files_table... | act_csrf_token(html):
soup = BeautifulSoup(html, 'lxml')
tokens = soup.find_all("input", attrs={"name": "security_token"})
if len(tokens) < 1:
raise ParserError("Could not find CSRF token")
return tokens.pop().attrs.get("value", "")
def extract_courses(html, only_recen | t_semester):
soup = BeautifulSoup(html, 'lxml')
div = soup.find("div", id="my_seminars")
tables = div.find_all("table")
for i in range(0, len(tables)):
if only_recent_semester and i > 0:
continue
j = len(tables) - i
table = tables[i]
semester = table.find... |
dsandersAzure/python_cowbull_server | Game/GameMode.py | Python | apache-2.0 | 9,034 | 0.00476 | from python_cowbull_server import error_handler
from flask_helpers.check_kwargs import check_kwargs
class GameMode(object):
"""
A representation of a game mode (complexity, number of digits, guesses allowed, etc.). The
mode contains the following information:
* mode <str> A text name fo... | : <int>
"""
return self._digit_type
@digit_type.setter
def digit_type(sel | f, value):
self._digit_type = self._property_setter(
keyword="digit_type", required=False, default=0, datatype=int, value=value
)
@property
def guesses_allowed(self):
"""
The number of guesses the mode is allowed; for example an easy mode might allow
20 guess... |
plotly/plotly.py | packages/python/plotly/plotly/validators/image/hoverlabel/font/_colorsrc.py | Python | mit | 424 | 0.002358 | impor | t _plotly_utils.basevalidators
class Co | lorsrcValidator(_plotly_utils.basevalidators.SrcValidator):
def __init__(
self, plotly_name="colorsrc", parent_name="image.hoverlabel.font", **kwargs
):
super(ColorsrcValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs... |
mrtommyb/AstroFuckOffs | bot/tests/test_bot.py | Python | mit | 1,600 | 0.005009 | import os
import json
import pytest
from .. import bot, PACKAGEDIR
EXAMPLE_TWEET = json.load(open(os.path.join(PACKAGEDIR, 'tests', 'examples', 'example-tweet.json'), 'r'))
EXAMPLE_RETWEET = json.load(open(os.path.join(PACKAGEDIR, 'tests', 'examples', 'retweeted-status.json'), 'r'))
EXAMPLE_NARCISSISTIC = json.load(... | responses) == 1
assert resp | onses[0] == "@exoplaneteer I'm sorry, Dan. I'm afraid I can't do that."
|
ept/windmill | windmill/server/https.py | Python | apache-2.0 | 17,211 | 0.003428 | # Copyright (c) 2009 Canonical Ltd.
# Copyright (c) 2009 Mikeal Rogers <mikeal.rogers@gmail.com>
# Copyright (c) 2009 Domen Kozar <domen@dev.si>
#
# 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 t... | self.send_error(404, msg)
| return False
return True
def do_CONNECT(self):
""" Handle CONNECT commands. Just set up SSL and restart. """
request = None
try:
try:
self.log_request(200)
self.wfile.write(self.protocol_version +
' 200 C... |
solintegra/addons | sale/wizard/sale_line_invoice.py | Python | agpl-3.0 | 6,126 | 0.002775 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... | ce(cr, uid, 'account', 'invoice_tree')
tree_id = tree_res | and tree_res[1] or False
return {
'name': _('Invoice'),
'view_type': 'form',
'view_mode': 'form,tree',
'res_model': 'account.invoice',
'res_id': invoice_ids,
'view_id': False,
'views': [(form_id, 'form'), (tree_id, 'tree')],
... |
OCA/social | mass_mailing_subscription_email/tests/test_unsubscribe_from_list.py | Python | agpl-3.0 | 1,590 | 0.001259 | # Copyright 2022 Camptocamp SA (https://www.camptocamp.com).
# @author Iván Todorovich <ivan.todorovich@camptocamp.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from lxml import etree
from odoo.tests import HttpCase, tagged
from odoo.addons.mail.tests.common import MockEmail
@tagged("-at_in... | mailing_list_data")
self.mailing_contact = self.env["mailing.contact"].create(
{
"name": "John Doe",
"email": "john.doe@example.com",
}
)
def test_subscription_email_unsubscribe_from_list(self):
# Create subscription
with self.... | ct.id,
"list_id": self.mailing_list.id,
}
)
body = self._new_mails._send_prepare_values()["body"]
root = etree.fromstring(body, etree.HTMLParser())
anchor = root.xpath("//a[@href]")[0]
unsubscribe_url = anchor.attrib["href"]
web_bas... |
m00dawg/holland | plugins/holland.backup.mysql_lvm/holland/backup/mysql_lvm/plugin/mysqldump/__init__.py | Python | bsd-3-clause | 38 | 0 | from pl | ugin impo | rt MysqlDumpLVMBackup
|
fossoult/odoo | openerp/addons/base/ir/ir_sequence.py | Python | agpl-3.0 | 14,812 | 0.005198 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-TODAY OpenERP S.A. <http://www.openerp.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms o... | GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import logging
import time
imp... | = 'ir.sequence.type'
_order = 'name'
_columns = {
'name': openerp.osv.fields.char('Name', required=True),
'code': openerp.osv.fields.char('Code', size=32, required=True),
}
_sql_constraints = [
('code_unique', 'unique(code)', '`code` must be unique.'),
]
def _code_get(self... |
yashdsaraf/scancode-toolkit | tests/extractcode/test_patch.py | Python | apache-2.0 | 72,541 | 0.007637 | #
# Copyright (c) 2017 nexB Inc. and others. All rights reserved.
# http://nexb.com and https://github.com/nexB/scancode-toolkit/
# The ScanCode software is licensed under the Apache License version 2.0.
# Data generated with ScanCode require an acknowledgment.
# ScanCode is a trademark of nexB Inc.
#
# You may not use... | = self.get_test_loc('patch/patches/dnsmasq_2.63-1.diff.expected')
check_patch(test_file, expected_file)
def test_patch_info_patch_patches_dropbear_2012_55_1_diff(self):
test_file = self.get_test_loc(u'patch/patches/d | ropbear_2012.55-1.diff')
expected_file = self.get_test_loc('patch/patches/dropbear_2012.55-1.diff.expected')
check_patch(test_file, expected_file)
def test_patch_info_patch_patches_electricfence_2_0_5_longjmp_patch(self):
test_file = self.get_test_loc(u'patch/patches/ElectricFence-2.0.5-lon... |
lo-windigo/fragdev | fragdev/settings.py | Python | agpl-3.0 | 5,073 | 0.000986 | # This file is part of the FragDev Website.
#
# the FragDev Website 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.
#
# the FragDev W... | sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'dj | ango.contrib.messages.middleware.MessageMiddleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'fragdev.urls'
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'fragdev.ws... |
stonebig/bokeh | scripts/issues.py | Python | bsd-3-clause | 12,422 | 0.002898 | #!/usr/bin/env python
from __future__ import print_function
import argparse
import datetime
import dateutil.parser
import dateutil.tz
import gzip
import json
import logging
import os
import pickle
import sys
from collections import OrderedDict
from functools import partial
from itertools import count, groupby
from s... | ction heading for the issue, or None if this issue should be ignored."""
labels = issue.get('labels', [])
for label in labels:
if not label['name'].startswith('type: '):
continue
if label['name'] in LOG_SECTION:
return LOG_SECTION[label['name']]
elif label['name'... | logging.warning('unknown issue type: "{}" for: {}'.format(label['name'], issue_line(issue)))
return None
def issue_tags(issue):
"""Returns list of tags for this issue."""
labels = issue.get('labels', [])
return [label['name'].replace('tag: ', '') for label in labels if label['name'].starts... |
yarikoptic/NiPy-OLD | examples/neurospin/need_data/block_matching.py | Python | bsd-3-clause | 1,238 | 0.016963 | #!/usr/bin/env python
from nipy.neurospin.register.iconic_matcher import IconicMatcher
from nipy.io.imageformats import load as load_image
from os.path import join
import numpy as np
"""
Example of running affine matching on the 'sulcal2000' database
"""
##rootpath = 'D:\\data\\sulcal2000'
rootpath = '/neurospin/l... | et_affine(), J.get_affine()) ## I: source, J: target
# Params
size = 5
nsimu = 1
depth = 10
import pylab as pl
# Simulations
for i in range(nsimu):
# Select random block
x0 = np.random.randint(I.array.shape[0]-size)
y0 = np.random.randint(I.array.shape[1]-size)
z0 = np.random.randint(I.array.shape... | ge(2*depth + 1)-depth)
s, p = matcher.explore(tx=tx)
# Display
pl.plot(p[:,0],(1-s)**(-.5*size**3))
pl.show()
|
bnaul/scikit-learn | sklearn/ensemble/tests/test_stacking.py | Python | bsd-3-clause | 19,101 | 0 | """Test the stacking classifier and regressor."""
# Authors: Guillaume Lemaitre <g.lemaitre58@gmail.com>
# License: BSD 3 clause
import pytest
import numpy as np
import scipy.sparse as sparse
from sklearn.base import BaseEstimator
from sklearn.base import ClassifierMixin
from sklearn.base import RegressorMixin
from ... | rk.parametrize(
"final_estimator", [None, RandomForestClassifier(random_state=42)]
)
@pytest.mark.parametrize("passthrough", [False, True])
def test_stacking_classifier_iris(cv, final_estimator, passthrough):
# prescale the data to avoid convergence warning without using a pipeline
# for later assert
X_... | ression()), ('svc', LinearSVC())]
clf = StackingClassifier(
estimators=estimators, final_estimator=final_estimator, cv=cv,
passthrough=passthrough
)
clf.fit(X_train, y_train)
clf.predict(X_test)
clf.predict_proba(X_test)
assert clf.score(X_test, y_test) > 0.8
X_trans = clf.t... |
vzhong/sent2rel | tests/test_adaptors.py | Python | mit | 10,128 | 0.005924 | __author__ = 'victor'
import unittest
from data.adaptors import *
import csv
import os
mydir = os.path.dirname(os.path.abspath(__file__))
class TestAdaptor(object):
def test_words(self):
ex = self.adaptor.to_example(self.raw)
self.assertEqual(ex.words, [w.lower() for w in self.words])
def t... | "of", "Denmark", "-LRB-", "0000", "-", "0000", "-RRB-", "was", "Queen",
"Consort", "to", "Edward", "VII", "of", "the", "United", "Kingdom", "and", "thus",
"Empress", "of", " | India", "during", "her", "husband", "\'s", "reign", "."
]
self.lemmas = [
"Alexandra", "of", "Denmark", "-lrb-", "0000", "-", "0000", "-rrb-", "be", "Queen",
"Consort", "to", "Edward", "VII", "of", "the", "United", "Kingdom", "and", "thus",
"empress", "of", "... |
denny820909/builder | lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/monkeypatches/sqlalchemy2189.py | Python | mit | 4,442 | 0.005853 | # This file is part of Buildbot. Buildbot 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, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without eve... | if args is not None:
args = re.findall(r'(\d+)', args)
| coltype = coltype(*[int(a) for a in args])
columns.append({
'name' : name,
'type' : coltype,
'nullable' : nullable,
'default' : default,
'primary_key': primary_key
})
return columns
@reflection.cache
def get_columns_07x_fixed(self, c... |
n4hy/gnuradio | gnuradio-core/src/python/gnuradio/blks2impl/fm_demod.py | Python | gpl-3.0 | 4,236 | 0.017469 | #
# Copyright 2006,2007 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio 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, or (at your option)
# any later versi... | h
from math import pi
class fm_demod_cf(gr.hier_block2):
"""
Generalized FM demodulation block with deemphasis and audio
filtering.
This block demodulates a band-limited, complex down-converted FM
channel into the the original baseband signal, optionally applying
deemphasis. Low pass filteri... | oduces an output float strem in the range of [-1.0, +1.0].
@param channel_rate: incoming sample rate of the FM baseband
@type sample_rate: integer
@param deviation: maximum FM deviation (default = 5000)
@type deviation: float
@param audio_decim: input to output decimation rate
@type audio_deci... |
oliverlee/pydy | pydy/viz/camera.py | Python | bsd-3-clause | 9,435 | 0.000212 | #!/usr/bin/env python
# standard lib
import warnings
# local
from ..utils import PyDyUserWarning
from .shapes import Shape
from .visualization_frame import VisualizationFrame
__all__ = ['PerspectiveCamera', 'OrthoGraphicCamera']
warnings.simplefilter('once', PyDyUserWarning)
class PerspectiveCamera(VisualizationF... | uper(PerspectiveCamera, self).generate_scene_dict(**kwargs)
scene_dict[id(self)]['type'] = self.__class__.__name__
scene_dict[id(self)]['fov'] = self.fov
scene_dict[id(self)]['near'] = self.near
scene_dict[id(self)]['far'] = self.far
return scene_dict
class OrthoGraphicCamera(... | ene. The camera is
inherited from ``VisualizationFrame``, and thus behaves similarly. It can
be attached to dynamics objects, hence we can get a moving camera. All the
transformation matrix generation methods are applicable to a
``OrthoGraphicCameraCamera``.
"""
def __init__(self, *args, **kw... |
moses1984/aafmt | LaTeXtoLaTeX-master/myoperations.py | Python | gpl-2.0 | 1,718 | 0.018044 |
import re
import utilities
import component
def setvariables(text):
component.chapter_abbrev = utilities.argument_of_macro(text,"chap",2)
####### | ############
def mytransform(text):
thetext = text
# get rid of extraneous spaces after \begin and \end
thetext = re.sub(r"\\begin\s+{",r"\\begin{",thetext)
thetext = re.sub(r"\\end\s+{",r"\end{",thetext)
# replace \begin{prop}{the_label} by
# \begin{prop}\label{proposition:chaptername:the_l... | lities.replacemacro(thetext,r"\begin{prop}",1,
r"\begin{prop}\label{proposition:"+component.chapter_abbrev+":#1}")
# and similarly for example and exercise (yes, this can be in a loop)
thetext = utilities.replacemacro(thetext,r"\begin{example}",1,
r"\begin{exam... |
minlexx/pyevemon | esi_client/models/put_fleets_fleet_id_members_member_id_unprocessable_entity.py | Python | gpl-3.0 | 3,138 | 0.002231 | # coding: utf-8
"""
EVE Swagger Interface
An OpenAPI for EVE Online
OpenAPI spec version: 0.4.6
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
class PutFleetsFleetIdMembersMemberIdUnprocessableEntity(object)... | result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dic... | ))
else:
result[attr] = value
return result
def to_str(self):
"""
Returns the string representation of the model
"""
return pformat(self.to_dict())
def __repr__(self):
"""
For `print` and `pprint`
"""
... |
materialsproject/custodian | custodian/vasp/handlers.py | Python | mit | 72,810 | 0.002857 | """
This module implements specific error handlers for VASP runs. These handlers
try to detect common errors in vasp runs and attempt to fix them on the fly
by modifying the input files.
"""
import datetime
import logging
import operator
import os
import re
import shutil
import time
import warnings
from collections im... | monty.os.path import zpath
from monty.serializatio | n import loadfn
from pymatgen.core.structure import Structure
from pymatgen.io.vasp.inputs import Incar, Kpoints, Poscar, VaspInput
from pymatgen.io.vasp.outputs import Oszicar, Outcar, Vasprun
from pymatgen.io.vasp.sets import MPScanRelaxSet
from pymatgen.transformations.standard_transformations import SupercellTransf... |
openstack/heat-translator | translator/hot/tosca/tosca_network_network.py | Python | apache-2.0 | 4,835 | 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
# distributed under the ... | csar_dir=csar_dir)
pass
def handle_properties(self):
| tosca_props = self.get_tosca_props()
net_props = {}
for key, value in tosca_props.items():
if key in self.NETWORK_PROPS:
if key == 'network_name':
# If CIDR is specified network_name should
# be used as the name for the new net... |
LePastis/pyload | module/plugins/hooks/DeleteFinished.py | Python | gpl-3.0 | 2,839 | 0.011272 | # -*- coding: utf-8 -*-
from module.database import style
from module.plugins.internal.Addon import Addon
class DeleteFinished(Addon):
__name__ = "DeleteFinished"
__type__ = "hook"
__version__ = "1.14"
__status__ = "testing"
__config__ = [("interval" , "int" , "Check interval in hours" ... | lter Purcaro", "vuolter@gmail.com")]
MIN_CHECK_INTERVAL = 1 * 60 * 60 #: 1 hour
## overwritten methods ##
def init | (self):
# self.event_map = {'pluginConfigChanged': "plugin_config_changed"}
self.interval = self.MIN_CHECK_INTERVAL
def periodical(self):
if not self.info['sleep']:
deloffline = self.get_config('deloffline')
mode = "0,1,4" if deloffline else "0,4"
msg = ... |
skibblenybbles/django-commando | commando/django/core/management/cleanup.py | Python | mit | 1,234 | 0.008914 | from commando import management
BaseCleanupCommand = management.get_command_class(
"cleanup", exclude_packages=("commando",))
if BaseCleanupCommand is not None:
base = BaseCleanupCommand()
class CleanupCommandOptions(management.CommandOptions):
"""
Cleanup command options.
... | return self.call_command("cleanup", *args, **options)
class CleanupCommand(CleanupCommandOptions, management. | StandardCommand):
"""
Cleanup command.
"""
option_list = management.StandardCommand.option_list
option_groups = \
CleanupCommandOptions.option_groups + \
management.StandardCommand.option_groups
else:
CleanupCommand = management.Stan... |
ronkitay/Rons-Tutorials | Python/APIs/tor_json_processing.py | Python | mit | 3,684 | 0.001357 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Python considers any map or collection as JSON elements. 'Serializing/DeSerializing' them is VERY easy
Read:
- json.load(data_file) --> Loads an object from a File
- json.loads(json_as_string) --> Loads an object from a string representing a JSON object
Write:
- json.d... | rom sets import Set
phase = 0
def load_json_from_file(input_file_name):
with | open(input_file_name) as data_file:
return json.load(data_file)
def save_json_to_file(output_file, json_object):
with open(output_file, 'w') as outfile:
json.dump(json_object, outfile)
def print_json_object(json_object):
print json.dumps(json_object, indent=True, sort_keys=True)
def print... |
mbayon/TFG-MachineLearning | venv/lib/python3.6/site-packages/scipy/interpolate/tests/test_regression.py | Python | mit | 484 | 0.002066 | fro | m __future__ import division, print_function, absolute_import
import numpy as np
import scipy.interpolate as interp
from numpy.testing import assert_almost_equal
class TestRegression(object):
def test_spalde_scalar_input(self):
"""Ticket #629"""
x = np.linspace(0,10)
y = x**3
tck ... | lmost_equal(res, des)
|
espadrine/opera | chromium/src/third_party/chromite/buildbot/portage_utilities.py | Python | bsd-3-clause | 30,932 | 0.007015 | # Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Routines and classes for working with Portage overlays and ebuilds."""
import collections
import filecmp
import fileinput
import glob
import loggi... | 'does not match expected format.' % filename)
super(EBuildVersionFormatException, self).__init__(message)
class EbuildFormatIncorrectException(Exception):
def __init__(self, filename, message):
message = | 'Ebuild %s has invalid format: %s ' % (filename, message)
super(EbuildFormatIncorrectException, self).__init__(message)
class EBuild(object):
"""Wrapper class for information about an ebuild."""
VERBOSE = False
_PACKAGE_VERSION_PATTERN = re.compile(
r'.*-(([0-9][0-9a-z_.]*)(-r[0-9]+)?)[.]ebuild')
_WO... |
forseti-security/forseti-security | tests/common/util/__init__.py | Python | apache-2.0 | 658 | 0 | # Copyright 2017 The Forseti Security 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 ap... | pecific language governing permissions and
# limitations under the Licen | se.
"""Common utilities usable by all tests."""
|
digidotcom/transport_examples | WR31/doormon.py | Python | mpl-2.0 | 3,979 | 0.000503 | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Copyright (c) 2016 Digi International Inc. All Rights Reserved.
"""
Monitor the WR31 door enclosure
"""
i... | :
"""
Send a command to the SarOS CLI and receive the response
:param cmd: str, Command to run
:return response: str, Response to cmd
"""
cli = sarcli.open()
cli.write(cmd)
response = cli.read()
cli.close()
return response
class SmsAlert(obje | ct):
"""
Send an SMS alert
"""
def __init__(self, destination, custom_text):
self.destination = destination
self.custom_text = custom_text
def send_alert(self, message):
"""
Send an SMS alert
:param message: str, Content of SMS message
:re... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.