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
redsolution/django-utilities
doc/source/conf.py
Python
gpl-3.0
6,330
0.006635
# -*- coding: utf-8 -*- # # django-utilities documentation build configuration file, created by # sphinx-quickstart on Wed Feb 1 19:53:28 2012. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file...
e # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. Major the...
ome with # Sphinx are currently 'default' and 'sphinxdoc'. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here,...
NKI-CCB/imfusion
tests/imfusion/external/test_ext_bowtie.py
Python
mit
579
0
# -*- coding: utf-8 -*- """Unit tests for functio
ns calling bowtie externally.""" from pathlib2 import Path import pytest from imfusion.external import bowtie class TestBowtieIndex(object): """Unit tests for the bowtie_index function.""" def test_call(self, mocker): """Tests example call with Path paths.""" mock_run = mocker.patch.objec...
, 'reference.fa', 'genome'], log_path=None)
romeoabulencia/booking_order
models/booking_setting.py
Python
gpl-3.0
888
0.007973
from odoo import api from odoo import fields from odoo import models class booking_settings(models.Model): _name="booking.settings" post_booking_time = fields.Integer('Post Booking Time') pre_booking_time = fields.Integer('Pre Booking Time') # Post Booking Time – Numeric field # Pre Booking Time ...
ample post booking is 30 <integer> minutes <static text> # That means when the system does the "check" for the booking of # stakeholders, it will check whether they have any event during that duration # + the post booking time and pre booking time # Employee A has an even
t 15 August 3pm – 4pm # There is a booking for 4.15 – 5:15pmpm, then it checks employee A. # while Employee A has a booking at 3pm – 4pm +30 minutes which overlaps # with 4.15, thus employee A is unavailable # Default Pre and Post booking time is 0 minutes.
crobby/sahara
sahara/tests/unit/service/validation/utils.py
Python
apache-2.0
14,870
0
# Copyright (c) 2013 Mirantis Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writ...
raise nova_ex.NotFound("") return 'OK' def _get_fl_ip_pool_list(): return [FakeNetwork("d9a3bebc-f788-4b81-9a93-aa048022c1ca")] def _get_availability_zone_list(detailed=True): return [FakeAvailabilityZone('nova')] def _g
et_heat_stack_list(**kwargs): if (kwargs.get('filters') and kwargs.get('filters').get('name') == 'test-heat'): return [FakeStack('test-heat')] return [] class FakeStack(object): def __init__(self, name): self.stack_name = name class FakeNetwork(object): def __init__(self,...
mhbu50/frappe
frappe/desk/doctype/workspace_shortcut/workspace_shortcut.py
Python
mit
235
0.008511
# -*- coding: utf-8 -*- # Copyright (c) 2021, Fr
appe Technologies and contributors # For license information, please see license.txt # import frappe from frappe.model.document import Document class WorkspaceShortcut(Document):
pass
spivachuk/sovrin-node
indy_client/cli/constants.py
Python
apache-2.0
11,175
0.021119
from plenum.cli.constants import CLIENT_GRAMS_CLIENT_COMMAND_REG_EX, relist, \ CLI_CMDS, getPipedRegEx, CLIENT_GRAMS_USE_KEYPAIR_REG_EX from indy_common.roles import Roles from indy_common.transactions import IndyTransactions CLIENT_GRAMS_CLIENT_WITH_DID_FORMATTED_REG_EX = getPipedRegEx( CLIENT_GRAMS_CLIENT_CO...
*.*\}}) \s*)? " \ "(\s+ (?P<timeout_key>timeout=)\s*(?P<timeout>[0-9+]+))?)" \ "(\s+ (?P<force_key>force=)\s*(?P<force>True|False))?" \ "(\s+ (?P<reinstall_key>reinstall=)\s*(?P<r
einstall>True|False))?".format( poolU
mehdidc/scikit-learn
sklearn/metrics/ranking.py
Python
bsd-3-clause
21,796
0
"""Metrics to assess performance on classification task given scores Functions named as ``*_score`` return a scalar value to maximize: the higher the better Function named as ``*_error`` or ``*_loss`` return a scalar value to minimize: the lower the better """ # Authors: Alexandre Gramfort <alexandre.gramfort@inria....
urve. For computing the area under
the ROC-curve, see :func:`roc_auc_score`. Parameters ---------- x : array, shape = [n] x coordinates. y : array, shape = [n] y coordinates. reorder : boolean, optional (default=False) If True, assume that the curve is ascending in the case of ties, as for an ROC cu...
Gustry/inasafe
safe/report/extractors/aggregate_result.py
Python
gpl-3.0
9,641
0
# coding=utf-8 """Module used to generate context for aggregation result section.""" from safe.definitions.exposure import exposure_all, exposure_population from safe.definitions.fields import ( affected_exposure_count_field, aggregation_name_field, total_affected_field, exposure_type_field, expos...
ure_count_field['field_name'] % type_name type_index = aggregation_summary.fieldNameIndex(field_name) type_field_index.append(type_index) for feat in aggregation_summary.getFeatures(): total_affected_value = format_number( feat[total_field_index],
enable_rounding=is_rounded, is_population=is_population) if total_affected_value == '0': # skip aggregation type if the total affected is zero continue item = { # Name is the header for each row 'name': feat[aggregation_name_index], ...
takavfx/Bento
python2.7libs/Bento/CacheManager/core.py
Python
mit
5,069
0.009667
# -*- coding: utf-8 -*- #------------------------------------------------------------------------------- ## Description """ Core program to exchange datas. """ #------------------------------------------------------------------------------- import sys sys.dont_write_bytecode = True import os import re import hou fr...
finition error" @classmethod
def getEvalStringPath(self, path, node_type): try: for item in Define.CACHE_NODES: if item.get("name") == node_type: parmName = item.get("parmName") parmPath = path + '/' + parmName evalPath = hou.evalParm(parmPath) return ev...
pengyuan/markov2tensor
recommendation/no_markov_recommend.py
Python
mit
6,979
0.003416
#!/usr/bin/env python # coding: UTF-8 from __future__ import division from util.hosvd import HOSVD, unfold, reconstruct, frobenius_norm from util.mobility import trans, init_data, init_data2, trans2 import numpy as np import math import pylab # 第一步:构建转移概率tensor # tensor = trans(count(init_db())) # tensor = trans(count...
平均值) check_predict = predicts[user][slot] check_recommend = recommends[user][slot] count_predict = 0 count_recommend = 0 for item in result_predict: if item in check_predict: count_predict += 1 for item in res...
ecommend += 1 total += 1 if use_type == "recommendation": if len(result_recommend) == 0: print "用户"+str(user)+"在时间"+str(slot)+"的f1_score(推荐): 没有生成推荐数据,无法完成推荐" else: precision = count_recommend / len(result_recommend) ...
Rastii/seproxer
seproxer/mitmproxy_extensions/master.py
Python
mit
3,377
0.00385
""" Extensions to mitmproxy master. """ import multiprocessing from seproxer import mitmproxy_extensions import seproxer.mitmproxy_extensions.addons # NOQA import seproxer.mitmproxy_extensions.options import mitmproxy.addons import mitmproxy.proxy.server import mitmproxy.master class ProxyMaster(mitmproxy.master.M...
ueue = results_queue self.push_event = push_event self.active_flows_state = active_flows_state def tick(self, timeout): """
Extends the Master's tick method to update our active flows state and to push our results into the results queue if the push_event is set """ tick_result = super().tick(timeout) # Update our active flow state has_active_flows = self._memory_stream_addon.has_active_flows()...
PanDAWMS/panda-bigmon-core
core/mlflowdynamic/openshiftcontroller.py
Python
apache-2.0
6,651
0.004661
import json, socket, random, string from core.settings.local import OC_TOKEN, OC_ENDPOINT, OC_NAMESPACE import requests from typing import Dict from os import path from kubernetes import client, config from openshift.dynamic import DynamicClient import yaml import logging logger = logging.getLogger('bigpandamon-error')...
o/v1', 'DeploymentConfig') resp = self.openshift_action("07-nginx-svc.yml", 'v1', 'Service') resp = self.openshift_action("08-route.yml", 'route.openshift.io/v1', 'Route')
def openshift_action(self, yml_file_name, api_version, kind): with open(path.join(path.dirname(__file__), yml_file_name)) as f: dep = yaml.safe_load(f) self.patchConfig(dep, self.INSTANCE, str(self.taskid)) handle = self.ocp_client.resources.get(api_version=api_version, kind=...
GeoMop/GeoMop
src/LayerEditor/ui/gitems/diagram_view.py
Python
gpl-3.0
1,929
0.006739
import PyQt5.QtWidgets as QtWidgets import PyQt5.QtGui as QtGui import PyQt5.QtCore as QtCore from LayerEditor.leconfig import cfg class DiagramView(QtWidgets.QGraphicsItem): """ Represents some diagram view in edited diagram background """ ZVALUE = -9 def __init__(self, diagram_uid,...
sing) for line in view_diagram.lines: painter.drawLine(line.p1.qpointf(), lin
e.p2.qpointf()) for point in view_diagram.points: painter.drawEllipse(point.qpointf(), r, r) pen.setStyle(QtCore.Qt.SolidLine) painter.setPen(pen) def release_view(self): del cfg.diagram.views_object[self.uid]
lepisma/audire
src/server.py
Python
gpl-3.0
1,838
0.001088
""" Tornado websocket server """ import tornado.ioloop import tornado.web import tornado.websocket import os from threading import Thread from modules import noise, anomaly, message, event settings = {"static_path": os.path.join(os.path.dirname(__file__), "static")} # Runt the audio level thread Thread(target=noise....
ake a global level var # Update it using a threaded script # Return its value here self.write(str(noise.level)) class WebSocketHandler(tornado.websocket.WebSocketHandler): """ Handle messages from server to dash. Work involves sending anomaly values and s
peech to text values. """ def open(self): print("WebSocket Opened") # Pass the object to different modules # so that they can communicate with the dash Thread(target=anomaly.anomaly_detection, args=(self, )).start() Thread(target=message.speech_win, args=(self, )).start(...
smozaffari/WASP
mapping/test_filter_remapped_reads.py
Python
apache-2.0
18,537
0.003884
import sys import os import subprocess import filter_remapped_reads import util # # filter_remapped_reads.py # INPUT FILES: # to_remap_bam - input BAM file containing original set of reads # that need to be remapped after having their alleles flipped # # remap_bam - input BAM file containing rem...
NM:i:2 MD:Z:7G44C48 YS:i:0 YT:Z:CP", "readpair2 163 chr22 150 12 101M = 250 201 TGGAGACATAAAATGAGGCATATCTGACCTCCACTTCCAAAAACATCTGAGATAGGTCTCAGTTAATTAAGAAAGTTTGTTCTGCCTAGTTTAAGGACATG CCCFFFFFHHHHHJJJJ
JJJJJJJJJJJIJJJJJJJJJJJJJJJJJIJJIHIJJJJEHIJJJHJJJJJJJJJJJJ=DHHHHHFFFFFFEEEEEEDDCDDDC AS:i:-11 XS:i:-17 XN:i:0 XM:i:2 XO:i:0 XG:i:0 NM:i:2 MD:Z:7G44C48 YS:i:0 YT:Z:CP", "readpair1 83 chr22 200 12 101M = 100 -201 TCCTGACAGCATGTGCCCAAGGTGGTCAGGATACAGCTTGCTTCTATATATTTTAGGGAGAAAATACATCAGCCTGTAAACAAAAAATTAAA...
willkg/socorro-collector
collector/external/crashstorage_base.py
Python
mpl-2.0
51,948
0.00179
# 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/. """This is the base of the crashstorage system - a unified interfaces for saving, fetching and iterating over raw crashe...
ollections import datetime from collector.lib.util import DotDict as SocorroDotDict from configman import Namespace, RequiredConfig from configman.converters import classes_in_namespaces_converter, \ class_converter from configman.dotdict import DotDict as ConfigmanDotDict #========...
ss MemoryDumpsMapping(dict): """there has been a bifurcation in the crash storage data throughout the history of the classes. The crash dumps have two different representations: 1) a mapping of crash names to binary data blobs 2) a mapping of crash names to file pathnames. It has been a manne...
knuu/competitive-programming
aoj/24/aoj2400.py
Python
mit
671
0.002981
while True: t, p, r = map(int, input().split()) if t == 0 and p == 0 and r == 0: break logs = [input().split() for _ in range(r)] sc
ore = [[0, 0, -i, [0] * p] for i in range(t)] c_n, pen, w_n = 0, 1, 3 for tid, pid, time, msg in logs: tid, pid, time = int(tid) - 1, int(pid) - 1, int(time) if msg == 'WRONG': score[tid][w_n][pid] += 1 elif msg == 'CORRECT': score[tid][c_n] += 1 score...
for c_n, pen, t, _ in score: print(abs(t) + 1 , c_n, abs(pen))
taigaio/taiga-contrib-letschat
back/taiga_contrib_letschat/tasks.py
Python
agpl-3.0
5,188
0.001735
# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz> # Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com> # Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com> # Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net> # Copyright (C) 2014-2017 Andrea Stagi <stagi.andrea@gmail.com> # ...
quests import logging from django.conf import settings from django.template import loader, Context from taiga.base.api.renderers import UnicodeJSONRenderer from taiga.base.utils.db import get_typename_for_model_instance from taiga.celery import app logger = logging.getLogger(__name__) def _get_type(obj): conte...
")[1] def _send_request(url, token, data): serialized_data = UnicodeJSONRenderer().render(data) headers = { 'Authorization': 'Bearer ' + token, 'Content-type': 'application/json', } if settings.CELERY_ENABLED: requests.post(url, data=serialized_data, headers=headers) re...
openstack/python-openstacksdk
openstack/cloud/_block_storage.py
Python
apache-2.0
36,405
0.000027
# 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...
, [])) break try: _list(data) break except exc.OpenStackCloudURINotFound: pass else: self.log.debug( "List volumes failed to retrieve all volumes after" " {attempts} attempts. Ret...
f._normalize_volumes( self._get_and_munchify(key=None, data=volumes)) @_utils.cache_on_arguments() def list_volume_types(self, get_extra=True): """List all available volume types. :returns: A list of volume ``munch.Munch``. """ resp = self.block_storage.get( ...
adviti/melange
app/soc/views/helper/gdata_apis/__init__.py
Python
apache-2.0
638
0.003135
# # Copyright
2011 the Melange authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, so...
or implied. # See the License for the specific language governing permissions and # limitations under the License. """Package contains helpers for gdata library. """
heyrict/cindy
sui_hei/templatetags/decodes.py
Python
mit
622
0.006431
from django import template from django.utils.tran
slation import ugettext_lazy as _ from django.db.models import Count, Q from ..models import mondai_genre_enum, mondai_status_enum register = template.Library() @register.filter def mondai_genre(value): return mondai_genre_enum[value] @register.filter def mondai_status(value):
return mondai_status_enum[value] @register.filter def normalize_star(value): return '%.1f' % value @register.filter def get_quescount(ques): unanswered = ques.filter(Q(kaitou="") | Q(kaitou__isnull=True)) return {'ques': ques.count(), 'unanswered': unanswered.count()}
fintech-circle/edx-platform
openedx/core/djangoapps/theming/middleware.py
Python
agpl-3.0
794
0.002519
""" Middleware for theming app Note: This middleware depends on "django_sites_extensions" app So it must be added to INSTALLED_APPS in django settings files. """ from django.conf import settings from openedx.core.djangoapps.theming.models import SiteTheme class CurrentSiteThemeMiddleware(object): """ ...
d it to the request object. """ default_theme = None if settings.DEFAULT_SITE_THEME: default_theme = SiteTheme(site=request.site, theme_dir_name=settings.DEFAULT_SITE_THEME) request.
site_theme = SiteTheme.get_theme(request.site, default=default_theme)
weiting-chen/manila
manila/tests/scheduler/weights/test_pool.py
Python
apache-2.0
6,709
0
# Copyright 2015 Mirantis Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
# host1: weight = 1*(-1.0) # host2: weight = 0*(-1.0) # host3: weight = 1*(-1.0) # host4: weight = 1*(-1.0) # host5: weight = 1*(-1.0) # so, host2 should win:
weighed_host = self._get_weighed_host(self._get_all_hosts(), weight_properties) self.assertEqual(0.0, weighed_host.weight) self.assertEqual( 'host2@BBB', utils.extract_host(weighed_host.obj.host)) def test_pool_weigher_all_pools_with_share_s...
mpi-array/mpi_array
mpi_array/globale_ufunc_test.py
Python
mit
33,737
0.003142
""" ============================================== The :mod:`mpi_array.globale_ufunc_test` Module ============================================== Module defining :mod:`mpi_array.globale` unit-tests. Execute as:: python -m mpi_array.globale_ufunc_test and with parallelism:: mpirun -n 2 python -m mpi_array.glob...
ff->f?', 'ddd->d?'], inputs=inp, outputs=out) self.assertSequenceEqual((_np.dtype('float64'), _np.dtype('uint16')), dtypes) finally: inp[2].free() out[0].free() out[1].free() class BroadcastShapeTest(_unittest.TestCase): """ :obj:`unittest.TestCase` for...
c.broadcast_shape` raises a :obj:`ValueError` if shapes are not broadcastable. """ self.assertRaises( ValueError, broadcast_shape, (4,), (5,) ) self.assertRaises( ValueError, broadcast_shape, (5,...
sgiavasis/nipype
nipype/interfaces/slicer/registration/tests/test_auto_BRAINSDemonWarp.py
Python
bsd-3-clause
3,971
0.027449
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT from .....testing import assert_equal from ..specialized import BRAINSDemonWarp def test_BRAINSDemonWarp_inputs(): input_map = dict(args=dict(argstr='%s', ), arrayOfPyramidLevelIterations=dict(argstr='--arrayOfPyramidLevelIterations %s', sep=',', ...
monWarp.output_spec() for key, metadata in list(output_map.items()): for metakey, value in list(metadata.items()): yie
ld assert_equal, getattr(outputs.traits()[key], metakey), value
rohitranjan1991/home-assistant
homeassistant/components/isy994/cover.py
Python
mit
3,841
0.00026
"""Support for ISY994 covers.""" from __future__ import annotations from typing import Any from pyisy.constants import ISY_VALUE_UNKNOWN from homeassistant.components.cover import ( ATTR_POSITION, DOMAIN as COVER, SUPPORT_CLOSE, SUPPORT_OPEN, SUPPORT_SET_POSITION, CoverEntity, ) from homeassi...
command to the ISY994 cover device.""" val = 100 if self._node.
uom == UOM_BARRIER else None if not await self._node.turn_on(val=val): _LOGGER.error("Unable to open the cover") async def async_close_cover(self, **kwargs: Any) -> None: """Send the close cover command to the ISY994 cover device.""" if not await self._node.turn_off(): ...
edlunde-dnastar/StarCluster
starcluster/clustersetup.py
Python
gpl-3.0
18,382
0
# Copyright 2009-2014 Justin Riley # # This file is part of StarCluster. # # StarCluster is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation, either version 3 of the License, or (at your option) any # later ...
self._master.ssh umap = self._master.get_user_map(key_by_uid=True) uid_db = {} files = mconn.ls('/home') for file in files: if mconn.isdir(file): f = mconn.stat(file) uid_db[f.st_uid] = (file, f.st_gid) if uid
_db.keys(): max_uid = max(uid_db.keys()) max_gid = uid_db[max_uid][1] uid, gid = max_uid + 1, max_gid + 1 # make sure the newly selected uid/gid is >= 1000 uid = max(uid, first_uid) gid = max(gid, first_uid) # make sure newly selected uid i...
evfredericksen/pynacea
pynhost/pynhost/platforms/windows.py
Python
mit
5,180
0.005985
''' Collection of Windows-specific I/O functions ''' import msvcrt import time import ctypes as ct from pynhost.platforms import winconstants EnumWindows = ct.windll.user32.EnumWindows EnumWindowsProc = ct.WINFUNCTYPE(ct.c_bool, ct.POINTER(ct.c_int), ct.POINTER(ct.c_int)) GetWindowText = ct.windll.user32.GetWindowTex...
'up'): for key_stroke in keys: keyup(winconstants.WINDOWS_KEY
CODES[key_stroke]) def keydown(hex_key_code): extra = ct.c_ulong(0) ii_ = winconstants.INPUT_I() ii_.ki = winconstants.KEYBOARD_INPUT(hex_key_code, 0x48, 0, 0, ct.pointer(extra)) x = winconstants.INPUT(ct.c_ulong(1), ii_) ct.windll.user32.SendInput(1, ct.pointer(x), ct.sizeof(x)) def keyup(hex_key...
nop33/indico
indico/modules/rb/controllers/__init__.py
Python
gpl-3.0
1,686
0.000593
# This file is part of Indico. # Copyright (C) 2002 - 2017 European Organization for Nuclear Research (CERN). # # Indico is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 3 of the # License, or (a...
require_user(self): if not config.ENABLE_ROOMBOOKING: raise NotFound(_('The room booking module is not enabled.')) RHProtected._require_user(self) if not rb_check_user_access(session.user): raise Forbidden(_('Your are not authorized to access the room booking system.')) ...
ght still show unsanitized content from the DB # so we need to keep the sanitizer running until everything in # roombooking has been moved to Jinja templates CHECK_HTML = True
sebastien-forestier/NIPS2017
ros/nips2017/src/nips2017/learning/test_learning.py
Python
gpl-3.0
3,920
0.008929
import numpy as np from environment_explauto.environment import TestEnvironment from learning import Learning if __name__ == "__main__": print "Create environment" environment = TestEnvironment() print "Create agent" learning = Learning(dict(m_mins=environment.conf.m_mins, ...
r_move_joystick_1", learning.produce(context, goal="joystic
k_1_forward") print "motor_move_joystick_1 again", learning.produce(context, goal="joystick_1_forward") print "motor_move_joystick_2", learning.produce(context, goal="joystick_2_forward") print "motor_move_ergo", learning.produce(context, goal="ergo_right") print "\nPloting interests..." le...
Digilent/u-boot-digilent
tools/binman/etype/gbb.py
Python
gpl-2.0
3,381
0.000296
# SPDX-License-Identifier:
GPL-2.0+ # Copyright (c) 2018 Google, Inc # Written by Simon Glass <sjg@chromium.org> # # Support for a Chromium OS Google Binary Block, used to record read-only # information mostly used by firmware. from collections import OrderedDict from patman import command from binman.entry import Entry, EntryArg from dtoc ...
erence/firmware/include/gbb_header.h) gbb_flag_properties = { 'dev-screen-short-delay': 0x1, 'load-option-roms': 0x2, 'enable-alternate-os': 0x4, 'force-dev-switch-on': 0x8, 'force-dev-boot-usb': 0x10, 'disable-fw-rollback-check': 0x20, 'enter-triggers-tonorm': 0x40, 'force-dev-boot-legacy': 0x80, 'fa...
handroll/handroll
transifex.py
Python
bsd-2-clause
1,809
0
# Copyright (c) 2017, Matt Layman from ConfigParser import ConfigParser, NoOptionError, NoSectionError import os import sys import requests API_URL = 'https://www.transifex.com/api/2' LANGUAGES = [ 'ar', 'de', 'el', 'es', 'fr', 'it', 'nl', 'pt_BR', ] def
fetch_po_for(language, username, pas
sword): print('Downloading po file for {0} ...'.format(language)) po_api = '/project/handroll/resource/handrollpot/translation/{0}/'.format( language) po_url = API_URL + po_api params = {'file': '1'} r = requests.get(po_url, auth=(username, password), params=params) if r.status_code == 2...
holdenk/spark
python/pyspark/ml/classification.py
Python
apache-2.0
127,312
0.001869
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not us...
sRegParam, HasMaxIter, HasFitIntercept, HasTol, HasStandardization, HasWeightCol, HasAggregationDepth, HasThreshold, HasBlockSize, HasMaxBlockSizeInMB, Param, Params, TypeConverters, HasElasticNetParam, HasSeed, HasStepSize, HasSolver, HasParal
lelism, ) from pyspark.ml.tree import ( _DecisionTreeModel, _DecisionTreeParams, _TreeEnsembleModel, _RandomForestParams, _GBTParams, _HasVarianceImpurity, _TreeClassifierParams, ) from pyspark.ml.regression import _FactorizationMachinesParams, DecisionTreeRegressionModel from pyspark.ml.bas...
pygeo/pycmbs
scripts/pattern_correlation.py
Python
mit
619
0.006462
""" This file is part of pyCMBS. (c) 2012- Alexander Loew For COPYING and LICENSE details, please refer to the LICENSE
file """ """ development script for pattern correlation analysis """ from pycmbs.diagnostic import PatternCorrelation from pycmbs.data import Data import numpy as np import matplotlib.pyplot as plt plt.close('all') fname = '../pycmbs/examples/example_data/air.mon.mean.nc' # generate two datasets x = Data(fname, '...
plt.show()
Propanu/mraa
tests/check_samplenames.py
Python
mit
2,291
0.00873
#!/usr/bin/python # Copyright (c) 2016 Intel Corporation. # SPDX-License-Identifier: MIT import unittest as u import re, fnmatch, os, sys sampleMappingFile = '../examples/samples.mapping.txt' cSamplesDir = '../examples/' javaSamplesDir = '../examples/java/' cppSamplesDir = '../examples/c++/' class SampleNames(u.Test...
1] #check for C files if cSampleName.endswith('.c'):
ok = False for file in os.listdir(cSamplesDir): if file == cSampleName: ok = True break if not ok: missing_c_files.append(cSampleName) #check for Cpp files ...
PMBio/limix
limix/deprecated/utils/plot.py
Python
apache-2.0
8,612
0.046679
# Copyright(c) 2014, The LIMIX developers (Christoph Lippert, Paolo Francesco Casale, Oliver Stegle) # #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...
mport scipy.stats as st import copy import os import pickle import glob def plot_manhattan(posCum,pv,chromBounds=None, thr=None,qv=None,lim=None,xticklabels=True, alphaNS=0.1,alphaS=0.5,colorNS='DarkBlue',colorS='Orange',plt=None,thr_plotting=None,labelS=None,labelNS=None): """ This script makes a manhatta...
tted into a single chromosome qv qvalues if provided, threshold for significance is set on qvalues but pvalues are plotted thr threshold for significance default: 0.01 bonferroni correceted significance levels if qvs are not specified, or 0.01 on qvs if qvs specified lim top limit on y-axis ...
miguelgrinberg/python-engineio
tests/common/test_packet.py
Python
mit
4,720
0
import unittest import pytest from engineio import packet class TestPacket(unittest.TestCase): def test_encode_default_packet(self): pkt = packet.Packet() assert pkt.packet_type == packet.NOOP assert pkt.data is None assert not pkt.binary assert pkt.encode() == '6' d...
pkt.packet_type == packet.MESSAGE assert pkt.data == 123 assert not pkt.binary assert pkt.encode() == '4123' def test_decode_number_packet(self): pkt = packet.Packet(encoded_packet='4123') assert pkt.packet_type == packet.MESSAGE # integer payloads are parsed as str...
ot pkt.binary assert pkt.encode() == '4123' def test_binary_non_message_packet(self): with pytest.raises(ValueError): packet.Packet(packet.NOOP, b'\x01\x02\x03')
chfw/pyexcel
tests/test_book.py
Python
bsd-3-clause
609
0
import pyexcel as p from nose.tools import eq_ def test_a_dictionary_of_sheet(): test_data = [["a", "b"]] book_dict = {"test": p.Sheet(test_data)} book = p.Book(book_dict) eq_(book.test.array, test_data) def test_book_len():
test_data = [["a", "b"]] book_dict = {"test": p.Sheet(test_data)} book = p.Book(book_dict) eq_(len(book.test.array), 1) def test_sheet_ordering(): test_data = [["a", "b"]] book_dict = {"first": test_data, "middle": test_data, "last": test_data} book
= p.Book(book_dict) eq_(book.sheet_names(), ["first", "middle", "last"])
sumanth-nirmal/self-driving-car-predict-steering
model/scripts/train_left.py
Python
mit
1,982
0.010091
#!/usr/bin/python ## Author: akshat ## Date: Dec, 3,2016 # trains the model from keras.models import model_from_json import load_data import numpy import matplotlib.pyplot as plt import time # load json model json_file = open('model.json', 'r') loaded_model = json_file.read() json_file.close() model = model_from_json...
s for plotting trainPredictPlot = numpy.empty_like(y_train_data) trainPredictPlot[:, :] = numpy.nan trainPredictPlot[0:len(trainPredict), :] = trainPredict # plot baseline and predictions plt.plot(y_train_data, label = 'Dataset') plt.plot(trainPredictPlot, label = 'Training Prediction') plt.legend(loc = 'upper left') ...
print("Saved weights to disk")
comic/comic-django
app/grandchallenge/profiles/forms.py
Python
apache-2.0
2,671
0
from django import forms from django.utils.safestring import mark_safe from django.utils.translation import gettext_lazy as _ from grandchallenge.core.templatetags.remove_whitespace import oxford_comma from grandchallenge.policies.models import Policy from grandchallenge.profiles.models import UserProfile class User...
Field(required=True) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # mark_safe ok here as we control the policy page titles self.fields["accept_terms"].label = mark_safe( "I have read and agree to {}.".format( oxford_comma( ...
for p in Policy.objects.all() ] ) ) ) def signup(self, request, user): user.first_name = self.cleaned_data["first_name"] user.last_name = self.cleaned_data["last_name"] user.save() user_profile = user.user_profile ...
puddl3glum/gen_scraper
example/example_processor.py
Python
mit
158
0.031646
import aiohttp def example_processor(): # extends processor from gen_scraperV2 async def route(scrape_bundle): pass
return route
Magicked/crits
crits/core/management/commands/runscript.py
Python
mit
5,573
0.00323
import getpass import os import socket from crits.settings import crits_config from django.core.management.base import BaseCommand, CommandError from crits.core.user import CRITsUser from crits.core.handlers import login_user from crits.vocabulary.acls import GeneralACL class Command(BaseCommand): """ Scrip...
ype totp_pass: str :returns: :class:`django.core.management.base.CommandError` if failed. """ result = login_user(username, password, next_url=None, user_agent=user_agent, remote_addr=remote_addr, ...
esult['type'] == "no_secret": totp_pass = getpass.getpass("Enter New TOTP Pin: ") try_login(username, password, user_agent, remote_addr, accept_language, totp_pass) if result['type'] == "secret_generated": print "Use %s to setup your authenticator.\n" ...
simonla/cyxbs_bot
network.py
Python
apache-2.0
1,669
0.001813
import requests from PIL import Image from course import * from utils import is_on_time, get_week from io import BytesIO url_course = 'https://wx.idsbllp.cn/redapi2/api/kebiao' url_stu_info = 'https://we.cqu.pt/api/others/student.php?key=' url_photo = 'https://we.cqu.pt/api/others/photos.php?id=' data...
['hash_day'], offset), courses) this_week_course = list(map(lambda x: Course(x['course'], x['teacher'], x['classroom'], x['lesson']), courses)) return ''.join(i.get_course() for i in this_week_course) def get_name_by_stu_num(stu_num): resp = requests.get(url_stu_info + str(stu_num)).json() retu...
requests.get(url_stu_info + info).json()['data']['rows'] def get_photo(stu_num_photo): url = 'https://we.cqu.pt/api/others/photos.php?id=%s' % (stu_num_photo,) photo_url = requests.get(url).json()['data'] photo = requests.get(photo_url).content image = Image.open(BytesIO(photo)) bio = Byte...
MaxTyutyunnikov/lino
obsolete/src/lino/apps/contacts/tables.py
Python
gpl-3.0
8,256
0.02156
## Copyright 2005-2006 Luc Saffre ## This file is part of the Lino project. ## Lino 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 versio...
site") def __str__(self): return self.name class Address(StoredDataRow): "abstract" def initTable(self,table): table.addPointer('nation',Nation) table.addPointer('city',City) table.addField('zip',STRING) table.addField('street',STRING) table.addFiel...
ct,Address): "An Organisation is any named group of people." tableName="Organisations" def initTable(self,table): table.addField('id',ROWID,\ doc="the internal id number") Contact.initTable(self,table) Address.initTable(self,table) table.addField('name',...
hasadna/anyway
anyway/vehicle_type.py
Python
mit
7,301
0.000822
from enum import Enum from typing import List, Union import logging import math try: from flask_babel import _ except ModuleNotFoundError: pass class VehicleType(Enum): CAR = 1 TRUCK_UPTO_4 = 2 PICKUP_UPTO_4 = 3 TRUCK_4_TO_10 = 4 TRUCK_12_TO_16 = 5 TRUCK_16_TO_34 = 6 TRUCK_ABOVE_3...
3_5_TO_10, VehicleType.TRUCK_10_TO_12, ], VehicleCategory.MOTORCYCLE: [ VehicleType.MOTORCYCLE_UPTO_50, VehicleType.MOTORCYCLE_50_TO_250,
VehicleType.MOTORCYCLE_250_TO_500, VehicleType.MOTORCYCLE_ABOVE_500, ], VehicleCategory.BICYCLE_AND_SMALL_MOTOR: [ VehicleType.BIKE, VehicleType.ELECTRIC_SCOOTER, VehicleType.ELECTRIC_BIKE, ], VehicleCat...
anryko/ansible
lib/ansible/modules/network/vyos/_vyos_lldp_interface.py
Python
gpl-3.0
6,588
0.00167
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2017, Ansible by Red Hat, inc # # This file is part of Ansible by Red Hat # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the Li...
required_one_of=required_one_of, mutually_exclusive=mutually_exclusive, supports_check_mode=True) warnings = list() result = {'changed': False} if warnings: result['warnings'] = warnings want = map_params_to_obj(module) have = map_c...
((want, have), module) result['commands'] = commands if commands: commit = not module.check_mode load_config(module, commands, commit=commit) result['changed'] = True module.exit_json(**result) if __name__ == '__main__': main()
tchellomello/home-assistant
tests/components/blebox/conftest.py
Python
apache-2.0
3,402
0.00147
"""PyTest fixtures and test helpers.""" from unittest import mock import blebox_uniapi import pytest from homeassistant.components.blebox.const import DOMAIN from homeassistant.const import CONF_HOST, CONF_PORT from homeassistant.setup import async_setup_component from tests.async_mock import AsyncMock, PropertyMoc...
the HA entity config.""" return MockConfigEntry(domain=DOMAIN, data={CONF_HOST: ip_address, CONF_PORT: 80}) @pytest.fixture(name="config") def config_fixture(): """Create hass config fixture.""" return {DOMAIN: {CONF_HOST: "172.100.123.4", CO
NF_PORT: 80}} @pytest.fixture(name="feature") def feature_fixture(request): """Return an entity wrapper from given fixture name.""" return request.getfixturevalue(request.param) async def async_setup_entities(hass, config, entity_ids): """Return configured entries with the given entity ids.""" conf...
haraldschilly/smc
src/dev/project/start_rethinkdb.py
Python
gpl-3.0
365
0.008219
#!/usr/bin/env python import os, util util.chdir() ports = util.get_ports() if not os.path.exists('rethinkdb_data'): util.cmd('rethinkdb create -d "rethinkdb_data"') util.cmd('rethinkdb serve
--cluster-port {cluster_port} --driver-port {driver_port} -
-no-http-admin'.format( driver_port=ports['rethinkdb'], cluster_port=ports['rethinkdb_cluster']))
amerc/phimii
chips2/chips/compiler/allocator.py
Python
mit
1,644
0.001825
__author__ = "Jon Dawson" __copyright__ = "Copyright (C) 2012, Jonathan P Dawson" __version__ = "0.1" class Allocator: """Maintain a pool of registers, variables and arrays. Keep track of what they are used for.""" def __init__(self, reuse): self.registers = [] self.all_registers = {} ...
reg = self.memory_size_4 self.memory_size_4 += int(size) if contents is not None: for location, value in enumerate(contents, reg): self.memory_content_4[location] = value return reg def regsize(self, reg): return self.all_registers[re...
r (reg in self.all_registers and self.regsize(reg) != size): reg += 1 self.registers.append(reg) self.all_registers[reg] = (name, size) return reg def free(self, register): if register in self.registers and self.reuse: self.registers.remove(register)
bitoffdev/perkins-blues
interfaces/telegram/interface.py
Python
mit
7,601
0.010262
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Python Telegram bot for the Perkins Light Project """ from telegram.ext import Updater, CommandHandler import telegram import logging import time from controller import * from color import * from solid_animation import * from fade_animation import * # Enable loggin...
try:
fadetime = float(arg[1]) except: update.message.reply_text('Time must be an decimal value for' '`/wipe`', parse_mode=telegram.ParseMode.MARKDOWN) return #Build WipeAnimation startColor = lastSolid currentTime = time.time() futureTime = time.t...
bsmedberg/socorro
socorro/external/postgresql/error.py
Python
mpl-2.0
1,846
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 socorro.external import MissingArgumentError from socorro.external.postgresql.base import PostgreSQLBase from socor...
ent the /error service with PostgreSQL. """ def get(self, **kwargs): """Return a single error report from its UUID. """
filters = [ ("uuid", None, "str"), ] params = external_common.parse_arguments(filters, kwargs) if params.uuid is None: raise MissingArgumentError('uuid') crash_date = datetimeutil.uuid_to_date(params.uuid) sql = """/* socorro.external.postgresql.err...
SITools2/pySitools2_1.0
sitools2/clients/__init__.py
Python
gpl-3.0
829
0.003619
# SITools2 client for Python # Copyright (C) 2013 - Institut d'astrophysique spatiale # # 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 # (a...
neral Public License # along with this program. If not, see <http://www.gnu.org/l
icenses/>. __author__="Jean-Christophe Malapert" __date__ ="$8 mai 2013 02:03:07$"
simongibbons/numpy
numpy/core/_dtype.py
Python
bsd-3-clause
9,843
0.000102
""" A place for code to be called from the implementation of np.dtype String handling is much easier to do correctly in python. """ import numpy as np _kind_to_stem = { 'u': 'uint', 'i': 'int', 'c': 'complex', 'f': 'float', 'b': 'bool', 'V': 'void', 'O': 'object', 'M': 'datetime', ...
er to th
e dtype constructor, and if no additional constructor parameters are given, will reproduce the exact memory layout. Parameters ---------- short : bool If true, this creates a shorter repr using 'kind' and 'itemsize', instead of the longer type name. include_align : bool ...
renalreg/radar
radar/api/views/forgot_username.py
Python
agpl-3.0
814
0.002457
from cornflake.exceptions import ValidationError from flask import Response from radar.api.serializers.auth import ForgotUsernameSerializer from radar.api.views
.generics import ApiView, request_json fro
m radar.auth.exceptions import UserNotFound from radar.auth.forgot_username import forgot_username class ForgotUsernameView(ApiView): @request_json(ForgotUsernameSerializer) def post(self, data): email = data['email'] try: forgot_username(email) except UserNotFound: ...
EliRibble/enlil
tests/api/test_root.py
Python
mit
150
0.006667
def test_root(client): response = client.get('/') assert re
sponse.status_code == 200 assert res
ponse.data.decode('utf-8') == 'Hey enlil'
willu47/smif
src/smif/decision/decision.py
Python
mit
22,709
0.002026
"""The decision module handles the three planning levels Currently, only pre-specified planning is implemented. The choices made in the three planning levels influence the set of interventions and assets available within a model run. The interventions available in a model run are stored in a dict keyed by name. """...
planned_names = set(name for build_year, name in self.planned_interventions) edited_register = {name: self._register[name] for name in self._register.keys() - planned_names} return edited_register def get_intervention(self, value):
try: return self._register[value] except KeyError: msg = "" raise SmifDataNotFoundError(msg.format(value)) def decision_loop(self): """Generate bundles of simulation steps to run Each call to this method returns a dict: { ...
nojhan/weboob-devel
modules/entreparticuliers/browser.py
Python
agpl-3.0
5,079
0.001969
# -*- coding: utf-8 -*- # Copyright(C) 2015 Bezleputh # # This file is part of weboob. # # weboob is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your opt...
charset=utf-8", "Accept": "application/json, text/javascript, */*; q=0.01"}) result = self.form_item.open(data="{'rubrique': '%s'}" % self.TYPES.get(type)) biens = json.loads(json.loads(result.content)['d']) for house_type in house_types: id_typ...
'1') data = {} data['rubrique'] = self.TYPES.get(type) data['ach_id'] = None data['FromMoteur'] = "true" for bien in biens: if bien['Idchoix'] == int(id_type): data['lstSSTbien'] = bien['SsTypebien'] da...
yuhangwang/ninjag-python
test/frontend/c/test_2.py
Python
mit
443
0
import ninjag import os from read_all import read_all def
test():
f_inputs = [ "input/in1_const.yaml", "input/in1_rules.yaml", "input/in1_tasks.yaml", ] f_answer = "output/out1_combined.ninja" f_solution = "solution/sol1.ninja" cmd = " ".join(["ninjag", f_answer, *f_inputs]) os.system(cmd) answer = read_all(f_answer) soluti...
emsrc/pycornetto
bin/cornetto-add-counts.py
Python
gpl-3.0
4,585
0.01374
#!/usr/bin/env python # -*- coding: utf-8 -*- """ add word counts to Cornetto lexical units database file The word count file should have three columns, delimited by white space, containing (1) the count, (2) the lemma, (3) the main POS tag. The tagset is assumed to be the Spoken Dutch Corpus tagset, and the characte...
lem(counts, cdb_
lu_file): #""" #adds a separate <statistics> element, #which accomodates for other counts for other sources #""" #parser = iterparse(cdb_lu_file) #for event, elem in parser: #if elem.tag == "cdb_lu": #try: #count = counts[form][cat] #except ...
misnyo/searx
searx/utils.py
Python
agpl-3.0
9,614
0.000936
import csv import hashlib import hmac import os import re from babel.dates import format_date from codecs import getincrementalencoder from imp import load_source from numbers import Number from os.path import splitext, join from random import choice import sys from searx.version import VERSION_STRING from searx.lang...
TMLParser.__init__(self) self.result = [] self.tags = [] def handle_starttag(self, tag, attrs): self.tags.append(tag) def handle_endtag(self, tag): if not self.tags: r
eturn if tag != self.tags[-1]: raise Exception("invalid html") self.tags.pop() def is_valid_tag(self): return not self.tags or self.tags[-1] not in blocked_tags def handle_data(self, d): if not self.is_valid_tag(): return self.result.append(d) ...
pinax/pinax-lms-activities
pinax/lms/activities/migrations/0009_auto_20160207_2149.py
Python
mit
858
0
# -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-02-07 21:49 from __future__ import unicode_literals from django.db import migrations import jsonfield.fields class Migration(migrations.Migration): dependencies = [ ('pinax_lms_activities', '0008_schema_fix'), ] operations = [ migrations.AlterField( ...
efault=dict), ), migrations.AlterField( model_name='activitystate', name='data', field=jsonfield.fields.JSONField(blank=True, default=dict), ), migrations.AlterField( model_name='userstate', name='data', field=jsonfi...
thejunglejane/datums
datums/models/base.py
Python
mit
5,846
0.000515
# -*- coding: utf-8 -*- import os from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm
import sessionmaker, scoped_session # Initialize Base class Base = declarative_b
ase() metadata = Base.metadata session_maker = sessionmaker() session = scoped_session(session_maker) engine = create_engine(os.environ['DATABASE_URI']) session.configure(bind=engine) def database_setup(engine): '''Set up the database. ''' metadata.create_all(engine) def database_teardown(engine): ...
batazor/MyExampleAndExperiments
Python/odoo_worker_tracking/test/odoo_worker_tracking/controllers/main.py
Python
mit
213
0.004695
# -
*- coding: utf-8 -*- from odoo import http class Worker(http.Controller): @http.route('/worker') def Main(self, **kwargs): return http.request.rend
er( 'worker_app.index_template')
yasuyuky/chainer-ya-utils
chainer/ya/utils/check_memory_usage.py
Python
mit
530
0
import cha
iner from chainer.training import extension class MemoryUsage(extension.Extension): def __init__(self, trigger=(1, "epoch")): self.total = [] self.trigger = trigger def initialize(self, _): if chainer.cuda.available: chainer.cuda.memory_pool.free_all_blocks() def __ca...
pass
terrai/rastercube
rastercube/scripts/create_glcf_worldgrid.py
Python
mit
3,828
0
""" Import the given GLCF tile into the provided worldgrid. Example invocation:: python rastercube/scripts/create_glcf_worldgrid.py --year 2004 --tile ML1920 --worldgrid=hdfs:///user/test/ """ import os import sys import time import gzip import shutil import argparse import tempfile import...
_num, 0), glcf_data) print 'Finished %d' % cell_num return True if
__name__ == '__main__': args = parser.parse_args() tilename = args.tile year = int(args.year) glcf_dir = args.glcf_dir if glcf_dir is None: glcf_dir = utils.get_glcf_tif_dir() glcf_grid_root = os.path.join(args.worldgrid, 'glcf/%d' % year) worldgrid = grids.GLCFGrid() if not j...
rpm-software-management/yum-utils
verifytree.py
Python
gpl-2.0
11,046
0.006428
#!/usr/bin/python -tt # 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 distributed in the hope that i...
rl to the repo" sys.exit(1) # FIXME: check that "args" is a valid dir before proceeding # (exists, isdir, contains .treeinfo, etc) url =
args[0] if url[0] == '/': url = 'file://' + url s = urlparse.urlsplit(url)[0] h,d = urlparse.urlsplit(url)[1:3] if s != 'file': print "Must be a file:// url or you will not like this" sys.exit(1) repoid = '%s/%s' % (h, d) repoid = repoid.replace('/', '_') # Bad thin...
repotvsupertuga/tvsupertuga.repository
plugin.video.plexus-streams/resources/core/parsers/torrenttvruall/main.py
Python
gpl-2.0
3,711
0.054354
# -*- coding: utf-8 -*- """ This plugin is 3rd party and not it is not part of the plexus-streams addon Torrent-tv.ru (All categories) """ import sys,os current_dir = os.path.dirname(os.path.realpath(__file__)) basename = os.path.basename(current_dir) core_dir = current_dir.replace(basename,'').replace('parsers','...
езерв": return translate(40086) elif string == "Донецк": return translate(40087) elif string == "Региональные": return translate(40088) elif string == "Для взрослых": return translate(40089) elif string == "TV21": return translate(40090) elif string == "Украина": return translate(40091) elif string == "Детс...
e(40092) elif string == "Фильмы": return translate(40093) elif string == "Ночной канал": return translate(40094) elif string == "Европа": return translate(40095) elif string == "укр": return translate(40096) elif string == "Музыка": return translate(40097) elif string == "Религиозные": return translate(4009...
sfenu/google-appengine-wx-launcher
launcher/html_info_dialog_unittest.py
Python
apache-2.0
1,929
0.005702
#!/usr/bin/env python # # Copyright 2008 Google Inc. # # Licensed under the Apache License, Version 2.0 (t
he "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, # WIT...
he License. # """Unittests for html_info_dialog.py""" import unittest import mox import wx import launcher class HtmlInfoDialogTest(unittest.TestCase): def setUp(self): # Must always create a wx.App first self.app = wx.PySimpleApp() def testCreate(self): hidt = launcher.HtmlInfoDialog(None, -1) ...
arocks/steel-rumors
steelrumors/settings.py
Python
mit
5,450
0.002202
# Django settings for steelrumors project. DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@example.com'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'N
AME': 'database.db', # Or path to database file if using sqlite3. # The following settings are not used with sqlite3: 'USER': '', 'PASSWORD': '', 'HOST': '', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP. ...
his site; required if DEBUG is False # See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts ALLOWED_HOSTS = [] # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating system...
olymk2/serJax
serjax/connect.py
Python
gpl-3.0
1,798
0.001112
import glob import serial import logging class serialPort(): """ Serial port wrapper """ port = '/dev/ttyACM0' coms = None connected = False def isOpen(self): return self.connected def connect(self, port='/tmp/ttyS11'): self.port = port try: self.coms = se...
('/dev/pts/*'): yield port for port in glob.glob('/dev/ptmx'): yield port def inWaiting(self): return self.coms.inWaiting() def write(self, data):
self.coms.write(data) def send(self, data): self.coms.write(data) def read(self): """ Read entire buffer """ out = '' while self.coms.inWaiting(): out += self.coms.read(1) return out def recv(self, length=1): """ Read limited length buffer"""...
cristian99garcia/guido-van-robot-activity
worldMap.py
Python
gpl-3.0
5,535
0.010479
# Copyright (C) 2001 Steve Howell # You must read the file called INFO.txt before distributing this code. # --- # Worlds for Karel are defined with simple text files that we parse out # in this module. See the worlds folder for examples. from world import NORTH,SOUTH,EAST,WEST from utils import trace_error import ...
if dir not in lookup_dir_dict.values(): raise WorldMapException(line, _("In line %d:\n%s is not a valid direction -- use N, S, E, or W") % (line, dir)) def removeComment(lin
e): foundComment = False for i in range(len(line)): if line[i] == "#": foundComment = True break if foundComment: return line[:i] else: return line def readWorld(lines, world): definedRobot = 0 useGuido = False linenumber = 0 worldSize = ...
VirusTotal/content
Packs/IntegrationsAndIncidentsHealthCheck/Scripts/IncidentsCheck_Widget_NumberofErrors/IncidentsCheck_Widget_NumberofErrors.py
Python
mit
497
0.002012
impor
t demistomock as demisto # noqa: F401 from CommonServerPython import * # noqa: F401 def main(): list_data = demisto.executeCommand("getList", {"listName": "XSOAR Health - Error Entries ID"}) list_content = list_data[0].get('Contents', '').split(",") entries_id_errors_count = len(list_content) if li...
"builtins"]: main()
TaliesinSkye/evennia
src/comms/admin.py
Python
bsd-3-clause
2,737
0.008403
# # This sets up how models are displayed # in the web admin interface. # from django.contrib import admin from src.comms.models import Channel, Msg, PlayerChannelConnection, ExternalChannelConnection class MsgAdmin(admin.ModelAdmin): list_display = ('id', 'db_date_sent', 'db_sender', 'db_receivers', 'db_channels...
rch_fields = ['id', '^db_date_sent', '^db_message'] save_as = True
save_on_top = True list_select_related = True #admin.site.register(Msg, MsgAdmin) class PlayerChannelConnectionInline(admin.TabularInline): model = PlayerChannelConnection fieldsets = ( (None, { 'fields':(('db_player', 'db_channel')), 'classes':('collapse',)}),) ...
henryroe/ztv
ztv/source_panel.py
Python
mit
29,058
0.005713
from __future__ import absolute_import import wx from wx.lib.pubsub import pub from .file_picker import FilePicker from .fits_header_dialog import FITSHeaderDialog from .image_process_action import ImageProcessAction import numpy as np import os import glob import sys import time import threading from .ztv_wx_lib impor...
nit__(self, source_panel, condition): if not stomp_install_is_ok: sys.stderr.write("ztv source_panel warning: stomp not installed OK, ActiveMQ functionality not available\n") raise ActiveMQNotAvailable threading.Thread.__init__(self) self.source_panel = source_panel ...
l.activemq_selected_instance]['server'] port = self.source_panel.activemq_instances_info[self.source_panel.activemq_selected_instance]['port'] dest = self.source_panel.activemq_instances_info[self.source_panel.activemq_selected_instance]['destination'] conn = stomp.Connection([(server, port)]) ...
napalm-automation/napalm-yang
napalm_yang/models/openconfig/network_instances/network_instance/protocols/protocol/isis/levels/level/link_state_database/lsp/tlvs/tlv/is_reachability/neighbors/neighbors_/delay_metric/state/__init__.py
Python
apache-2.0
23,483
0.001363
# -*- coding: utf-8 -*- from operator import attrgetter from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType from pyangbind.lib.yangtypes import RestrictedClassType from pyangbind.lib.yangtypes import TypedListType from pyangbind.lib.yangtypes import YANGBool from pyangbind.lib.yangtypes import YANGListTy...
lf._extmethods, register_paths=True, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='oc-isis-types:narrow-metric', is_config=False)""",
} ) self.__metric = t if hasattr(self, "_set"): self._set() def _unset_metric(self): self.__metric = YANGDynClass( base=RestrictedClassType( base_type=RestrictedClassType( base_type=int, restriction_dict={"range"...
jawilson/home-assistant
homeassistant/components/intesishome/__init__.py
Python
apache-2.0
28
0
""
"Intesishome platform."""
findhy/kafka-python
kafka/common.py
Python
apache-2.0
4,660
0.003219
from collections import namedtuple ############### # Structs # ############### # Request payloads ProduceRequest = namedtuple("ProduceRequest", ["topic", "partition", "messages"]) FetchRequest = namedtuple("FetchRequest", ["topic", "partition", "offset", "max...
navailableError(KafkaError): pass class LeaderUnavailableError(KafkaError): pass class PartitionUnavailableError(KafkaError): pass class FailedPayloadsError(KafkaError): pass class ConnectionError(KafkaError): pass class BufferUnderflowError(KafkaError): pass class ChecksumError(Kafk...
ass class ProtocolError(KafkaError): pass class UnsupportedCodecError(KafkaError): pass kafka_errors = { -1 : UnknownError, 1 : OffsetOutOfRangeError, 2 : InvalidMessageError, 3 : UnknownTopicOrPartitionError, 4 : InvalidFetchRequestError, 5 : LeaderNotAvailableError, 6 :...
Guymer/PyGuymer
load_GPS_EXIF.py
Python
apache-2.0
993
0.008056
# -*- coding: utf-8 -*- ########################################################################
###################### # This file is deprecated because Python 2.x is deprecated
# # A Python 3.x version of this file can be found at: # # # # https://github.com/Guymer/PyGuymer3/blob/master/load_GPS_EXIF.py # #################...
L5hunter/TestCoin
qa/rpc-tests/zapwallettxes.py
Python
mit
3,033
0.014507
#!/usr/bin/env python2 # Copyright (c) 2014 The Testcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. from test_framework import TestcoinTestFramework from util import * c
lass ZapWalletTXesTest (TestcoinTestFramework): def setup_chain(self): print("Initializing test directory "+self.options.tmpdir) initialize_chain_clean(self.options.tmpdir, 3) def setup_network(self, split=False): self.nodes = start_nodes(3, self.options.tmpdir) connect_nodes_b...
self.is_network_split=False self.sync_all() def run_test (self): print "Mining blocks..." self.nodes[0].setgenerate(True, 1) self.sync_all() self.nodes[1].setgenerate(True, 101) self.sync_all() assert_equal(self.nodes[0].getbalance(), 50) ...
karrtikr/ete
ete3/tools/phylobuild_lib/task/prottest2.py
Python
gpl-3.0
6,445
0.002638
# #START_LICENSE########################################################### # # # This file is part of the Environment for Tree Exploration program # (ETE). http://etetoolkit.org # # ETE is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by # the...
E PACKAGE # ===================== # # ETE is distributed under the GPL copyleft license (2008-2015). # # If you make use of ETE in published work, please cite: # # Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. # ETE: a python Env
ironment for Tree Exploration. Jaime BMC # Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 # # Note that extra references to the specific methods implemented in # the toolkit may be available in the documentation. # # More info at http://etetoolkit.org. Contact: huerta@embl.de # # # #END_LICENSE#####################...
cc14514/hq6
dist/support/src/main/resources/scripts/support.py
Python
unlicense
4,294
0.011877
#!/usr/bin/python # # Frontend for running support related commands on hyperic installations. # # Opens as an interactive shell if no parameters are passed, otherwise runs # the command and parameters that have been passed on the command line. # # Enter help to see available commands. # # # Adding a new command is do...
"""get_variables - Retrieves the values of all support-related variables""" for k in sorted(gd.globalData.keys()): print "%s: %s" % (k,gd.globalData[k]) def do_sigar(self,line): """Run a sigar command. See help for details""" if line.strip() != '': siga...
print "Could not find sigar JAR file - Please build the project before using this command" else: print "Could not find sigar JAR file in. Expected location is %s" % sigar_jar return run_java_jar(sigar_jar,line) else: ...
jf-parent/webbase
{{cookiecutter.project_name}}/server/model/migrationbase.py
Python
mit
4,218
0.000237
import traceback from datetime import datetime import os from tempfile import gettempdir import subprocess from dateutil import tz from mongoalchemy.session import Session from pymongo import MongoClient class MigrationBase(object): def __init__(self, name, db_name): self.name = name self.db_name...
nect( db_name, tz_aware=True, timezone=tz.gettz('UTC') ) # TODO get the mongo client from server/utils:get_mongo_client self.mongo_client = MongoClient() self.db = self.mongo_client[self.db_name] def validate_model_name(self, model_name): ...
abase" .format(model_name=model_name) ) def add_field(self, model_name, field_name, default_value): self.validate_model_name(model_name) cursor = self.db[model_name].find( { field_name: { '$exists': False }...
wilfriedE/PoliticalMashup
settings.py
Python
gpl-3.0
21
0.047619
CONGRE
SS_API_KEY =
""
Parsely/parsely_raw_data
parsely_raw_data/stream.py
Python
apache-2.0
4,716
0.00106
from __future__ import absolute_import, print_function import json import threading import time from collections import defaultdict import boto3 from botocore.exceptions import ClientError, ParamValidationError from six import iteritems from six.moves.queue import Queue, Empty from . import utils __license__ = """ ...
continue iterator = response.get("NextShardIterator", "") records = response.get("Records", [])
for record in records: event_data = record.get("Data") if event_data is not None: try: event_data = json.loads(event_data) except ValueError: continue event_queue.put(event_data) ...
samstav/simpl
simpl/incubator/rest.py
Python
apache-2.0
7,797
0
# Copyright (c) 2011-2015 Rackspace US, Inc. # All Rights Reserved. # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless...
e of items which conform to `schema`.""" def validate(val):
"""Apply schema check/version to each item.""" return [volup.Coerce(schema)(x) for x in val] return validate def schema(body_schema=None, body_required=False, query_schema=None, # noqa content_types=None, default_body=None): """Decorator to parse and validate API body and query string. ...
pfalcon/micropython
tests/io/open_textio.py
Python
mit
898
0.002257
try: import uos as os except ImportError: import os if not hasattr(os, "remove"): print("SKIP") raise SystemExit try: import uio as io io.TextIOWrapper except: try: import io io.TextIOWrapper except: print("SKIP") raise SystemExit # cleanup in case t...
tf1.flush() f2 = open("testfile", "rb") s = f2.read() f2.close() assert s == "привет".encode() tf1.close() try: t
f1.write("should fail") assert False, "Could write to closed textio wrapper" except ValueError: pass try: f1.write(b"should fail2") assert False, "Could write to closed underlying file" except ValueError: pass # cleanup try: os.remove("testfile") except OSError: pass
piyushroshan/fossmeet
views.py
Python
bsd-2-clause
27,799
0.003707
# -*- coding: utf-8 -*- import re from datetime import datetime from markdown import Markdown from flask import render_template, redirect, request, g, url_for, Markup, abort, flash, escape from flask.ext.lastuser import LastUser from flask.ext.lastuser.sqlalchemy import UserManager from coaster.views import get_next_...
n') def newsection(name): space = ProposalSpace.query.filter_by(name=name).first() if not space: abort(404) form = SectionForm() if form.validate_on_submit(): sectio
n = ProposalSpaceSection(proposal_space=space) form.populate_obj(section) db.session.add(section) db.session.commit() flash("Your new section has been added", "info") return redirect(url_for('viewspace', name=space.name), code=303) return render_template('autoform.html', form...
thinkAmi-sandbox/Django_iis_global_static_sample
redblue_project/urls.py
Python
unlicense
991
0
"""redblue_project URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.
com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') ...
Add a URL to urlpatterns: url(r'^blog/', include(blog_urls)) """ from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^red/', include('apps.red_app.urls', namespace='red_namespace')), url(r'^blue/', include('apps.blue_app.urls', namespace='blue_namespace')), ur...
ladyrassilon/presser
setup.py
Python
gpl-3.0
1,357
0.008843
from setuptools import setup with open("README.rst") as readme_file:
long_description = readme_file.read() setup(name="Presser", version="0.1.8", packages=["presser",], license="GNU GPL v3.0", description="Extracts data from vine, in lieu of an API", author="Gemma Hentsch", author_email="contact@halfapenguin.com", install_requires=[ "beautifulsoup4...
uests>=2.4.0", "PyExecJS>=1.0.4", ], tests_require=[ "beautifulsoup4", "requests", "mock", "coverage", "nose", "PyExecJS", "responses" ], long_description=long_description, test_suite="nose.collector", url="https://github.com/ladyra...
eaobservatory/hedwig
lib/hedwig/facility/example/control.py
Python
gpl-3.0
2,612
0
# Copyright (C) 2016 East Asian Observa
tory # All Rights Reserved. # # 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 # Found
ation; either version 2 of the License, or (at your option) any later # version. # # This program is distributed in the hope that it will be useful,but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # detail...
eduNEXT/edx-platform
openedx/core/djangoapps/heartbeat/tasks.py
Python
agpl-3.0
215
0
""" A trivial task for health checks """ from celery import shared_task from edx_djan
go_utils.monitoring import set_code_owner_attribute @shared_task @set_code_owner_attribute def sample_task
(): return True
lovetox/gajim
test/runtests.py
Python
gpl-3.0
1,510
0.003311
#!/usr/bin/env python3 ''' Runs Gajim's Test Suite Unit tests tests will be run on each commit. ''' import sys import unittest import getopt use_x = True verbose = 1 try: shortargs = 'hnv:' longargs = 'help no-x verbose=' opts, args = getopt.getopt(sys.argv[1:], shortargs, longargs.split()) except geto...
or as msg: print(msg) print('for help use --help') sys.exit(2) for o, a in opts: if o in ('-h', '--help'): print('runtests [--help] [--no-x] [--verbose level]') sys.exit() elif o in ('-n', '--no-x'): use_x = False elif o in ('-v', '--verbose'): try: ve...
be a number >= 0') sys.exit(2) # new test modules need to be added manually modules = ( 'unit.test_protocol_caps', 'unit.test_caps_cache', 'unit.test_contacts', 'unit.test_account', 'unit.test_gui_interface', ) if use_x: modules += ( 'unit.tes...
Teknologforeningen/tf_arsfest
tf_arsfest/migrations/0001_initial.py
Python
mit
8,064
0.007688
# -*- 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 'Guest' db.create_table('tf_arsfest_guest', ( ('id', self.gf('django.db.models.fi...
ax_length': '120'}), 'places': ('django.db.models.fields.PositiveIntegerField', [], {}), 'registration_description': ('django.db.models.fields.TextField', [], {}), 'round1_closes': ('django.db.models.fields.DateTimeField', [], {}), 'round1_opens': ('django.db.models.
fields.DateTimeField', [], {}), 'round2_closes': ('django.db.models.fields.DateTimeField', [], {}), 'round2_opens': ('django.db.models.fields.DateTimeField', [], {}), 'silliz_price': ('django.db.models.fields.PositiveIntegerField', [], {}), 'year': ('django.db.models.fiel...
Vagab0nd/SiCKRAGE
lib3/qbittorrentapi/app.py
Python
gpl-3.0
6,184
0.002264
import logging from json import dumps from qbittorrentapi.decorators import Alias from qbittorrentapi.decorators import aliased from qbittorrentapi.decorators import login_required from qbittorrentapi.decorators import response_json from qbittorrentapi.decorators import response_text from qbittorrentapi.decorators imp...
eve qBittorrent application preferences. :return: Dictionary of pr
eferences. Each preference is an attribute. Properties: https://github.com/qbittorrent/qBittorrent/wiki/WebUI-API-(qBittorrent-4.1)#get-application-preferences """ return self._get(_name=APINames.Application, _method='preferences', **kwargs) @Alias('app_setPreferences') @login_requi...
c2corg/v6_api
c2corg_api/views/sitemap_xml.py
Python
agpl-3.0
7,153
0
import functools import logging from c2corg_api import DBSession, caching from c2corg_api.caching import cache_sitemap_xml from c2corg_api.models.cache_version import CacheVersion from c2corg_api.models.document import Document, DocumentLocale from c2corg_api.models.route import ROUTE_TYPE, RouteLocale from c2corg_api...
sitemaps.extend(sitemaps_for_type) return """<?xml version="1.0" encoding="UTF-8"?> <sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> {} </sitemapindex>""".format("\n".joi
n(sitemaps)) def _get_sitemap(doc_type, i): fields = [ Document.document_id, DocumentLocale.lang, DocumentLocale.title, CacheVersion.last_updated ] # include `title_prefix` for routes is_route = doc_type == ROUTE_TYPE if is_route: fields.append(RouteLocale.title_prefix) ...
skosukhin/spack
var/spack/repos/builtin/packages/yajl/package.py
Python
lgpl-2.1
1,554
0.001287
############################################################################## # Copyright (c) 2017, Los Alamos National Security, LLC # Produced at the Los Alamos National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-647188 # # For details, ...
te it and/or modify # it under the terms of the GNU Lesser General Public License (as # published by the Free Software Foundation) version 2.1, February 1999. # # 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...
s and # conditions of the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #############################...
jdowner/lrc
lrc/compiler.py
Python
mit
2,676
0
#!/usr/bin/env python3 import logging import logging.config import re from . import core logger = logging.getLogger(__name__) class UnrecognizedInstruction(Exception): pass class Compiler(object): def __init__(self): self._opcodes = {op.MNEUMONIC: op for op in ( core.Load, ...
# Compile the instructions instructions = list() for line in lines: if self.is_label(line): instructions.append(core.Null(lo=0, hi=0)) continue if self.is_opcode(line): opcode = self.parse_opcode(labels, line) i...
continue raise UnrecognizedInstruction(line) return instructions def prepare(self, program): lines = program.splitlines() lines = [line.strip() for line in lines if not self.is_comment(line)] return lines def find_labels(self, lines): labels = {} f...
jleclanche/fireplace
fireplace/cards/ungoro/rogue.py
Python
agpl-3.0
697
0.032999
from ..utils import * ## # Minions class UNG_058: """Razorpetal Lasher""" pass class UNG_063: """Biteweed""" pass clas
s UNG_064: """Vilespine Slayer""" requirements = {PlayReq.REQ_MINION_TARGET: 0, PlayReq.REQ_TARGET_FOR_COMBO: 0} pass class UNG_065: """Sherazin, Corpse Flower""" pass ## # Spells class UNG_057: """Razorpetal Volley""" pass class UNG_060: """Mimic Pod""" requirements = {PlayReq.REQ_MINION_TARGET: 0} pa...
ss UNG_823: """Envenom Weapon""" requirements = {PlayReq.REQ_WEAPON_EQUIPPED: 0} pass class UNG_856: """Hallucination""" pass ## # Weapons class UNG_061: """Obsidian Shard""" pass
jPhy/Gomoku
game.py
Python
mit
872
0.010321
#! /usr/bin/env python from __future__ import print_function import lib class ErrorHandler(object): def __enter__(self): pass def __exit__(self, error_type, error_args, traceback): if error_type is None: return if error_type is lib.gui.tk.TclError: print("WARNI...
if issubclass(error_type, Exception): # Only catch real exceptions not ``BaseException`` lib.gui.Message(message=repr(error_args), icon='warning', title='Gomoku - Error').show() return False # reraise nonTcl errors => stderr message and nonzero exit if __name__ == '__main__': main_window = l...
with ErrorHandler(): main_window.mainloop()
davidam/python-examples
scikit/latentsemantic.py
Python
gpl-3.0
2,544
0.00669
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (C) 2019 David Arroyo Menéndez # Author: David Arroyo Menéndez <davidam@gnu.org> # Maintainer: David Arroyo Menéndez <davidam@gnu.org> # This file is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as p...
0) print("Train set has total {0} entries with {1:.2f}% negative, {2:.2f}% positive".format(len(X_train), (len(X_train[y_train == 0]) / (len(X_train)*1.))*100, (len(X_...
.2f}% negative, {2:.2f}% positive".format(len(X_test), (len(X_test[y_test == 0]) / (len(X_test)*1.))*100, (len(X_test[y_test == 1]) / (len(X_test)*1.))*100))