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 |
|---|---|---|---|---|---|---|---|---|
AlexanderVangelov/pjsip | tests/pjsua/scripts-sipp/uas-subscribe-terminated-retry.py | Python | gpl-2.0 | 374 | 0.026738 | # $Id: uas-subscribe-terminated-retry.py 4188 2012-06-29 09:01:17Z nanang $
#
import inc_const as const
PJSUA = ["--null-audio --max-calls=1 --id sip:pjsua@localhost --add-buddy $SIPP_URI"]
PJSUA_EXPECTS | = [[0, "", "s"],
[0, "Subscribe presence of:", "1"],
[0, "Presence subscription .* is TERMINATED", ""],
[0, "Resubscribing .* in 5000 ms", "" | ]
]
|
j4v/DS_Store-Scanner | dsstore_scanner.py | Python | gpl-3.0 | 6,357 | 0.001573 | from ds_store import DSStore, DSStoreEntry
from burp import IBurpExtender
from burp import IScannerCheck
from burp import IExtensionStateListener
from burp import IScanIssue
import StringIO
from urlparse import urlparse
def traverse_ds_store_file(d):
"""
Traverse a DSStore object from the node and yeld each ... | content_url = "%s://%s%s/%s" % (protocol, host, path.rsplit("/", 1)[0], | content)
print content_url
return (self.scan_issues)
def consolidateDuplicateIssues(self, existingIssue, newIssue):
if existingIssue.getUrl() == newIssue.getUrl() and \
existingIssue.getIssueDetail() == newIssue.getIssueDetail():
return -1
... |
ValorNaram/isl | inputchangers/002.py | Python | mit | 1,044 | 0.029693 | blocklevel = ["blockquote", "div", "form", | "p", "table", "video", "h1", "h2", "h3", "h4", "h5", "h6", "hr", "details", "article", "header", "main"]
def normalizeEnter(src):
#Deletes all user defined for readability reason existing line breaks that are issues for the HTML output
for elem in blocklevel:
while src.find("\r<" + elem) > -1:
src = src.replace... | c.find("</" + elem + ">\r") > -1:
src = src.replace("</" + elem + ">\r", "</" + elem + ">")
while src.find(">\r") > -1:
src = src.replace(">\r", ">") #It is really needed, it created some other bugs?!
while src.find("\r</") > -1:
src = src.replace("\r</", "</") ##It is really needed, it created some other ... |
shashi792/courtlistener | alert/lib/filesize.py | Python | agpl-3.0 | 789 | 0 | alternative = [
(1024 ** 5, 'PB'),
(1024 ** 4, 'TB'),
(1024 ** 3, 'GB'),
(1024 ** 2, 'MB'),
(1024 ** 1, 'KB'),
(1024 ** 0, (' byte', ' bytes')),
]
def size(bytes, system=alternative):
"""Human-readable file size.
"""
for factor, suffix in system:
if bytes >= factor:
... | :
singular, multiple = suffix
if amount == 1:
suffix = singular
else:
suffix = multiple
if suffix == 'PB':
return '%.3f%s' % (amount, suffix)
elif suffix == 'TB':
return '%.2f%s' % (amount, suffix | )
elif suffix == 'GB':
return '%.1f%s' % (amount, suffix)
else:
return '%d%s' % (amount, suffix)
|
hubo1016/vlcp | vlcp/utils/zookeeper.py | Python | apache-2.0 | 26,134 | 0.034438 | '''
Created on 2016/8/25
:author: hubo
'''
from namedstruct import *
from namedstruct.namedstruct import BadFormatError, BadLenError, Parser, _create_struct
def _copy(buffer):
try:
if isinstance(buffer, memoryview):
return buffer.tobytes()
else:
return buffer[:]
excep... | t64, 'mzxid'), # last modified zxid
(int64, 'ctime'), # created
(int64, 'mtime'), # last modified
(int32, 'version'), # version
(int32, 'cversion'), # child version
(int32, 'aversion'), # acl version
(int64, 'ephemeralOwner'), # owner id if epheme... | 32, 'dataLength'), #length of the data in the node
(int32, 'numChildren'), #number of children of this node
(int64, 'pzxid'), # last modified children
name = 'Stat',
padding = 1
)
# information explicitly stored by the server persistently
StatPersisted = nstruct(
(int64... |
ubuntu-core/snapcraft | tests/unit/plugins/v2/test_go.py | Python | gpl-3.0 | 3,433 | 0.000874 | # -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# Copyright (C) 2020 Canonical Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the h... | neral Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from testtools. | matchers import Equals
from testtools import TestCase
from snapcraft.plugins.v2.go import GoPlugin
class GoPluginTest(TestCase):
def test_schema(self):
schema = GoPlugin.get_schema()
self.assertThat(
schema,
Equals(
{
"$schema": "http:/... |
UManPychron/pychron | pychron/spectrometer/tasks/spectrometer_task.py | Python | apache-2.0 | 11,184 | 0.00152 | # ===============================================================================
# Copyright 2013 Jake Ross
#
# 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... | me = 'Spectrometer'
id = 'pychron.spectrometer'
_scan_editor = Instance(ScanEditor)
tool_bars = [SToolBar(StopScanAction(), )]
def info(self, msg, *args, **kw):
super(SpectrometerTask, self).info(msg)
def spy_position_magnet | (self, *args, **kw):
self.scan_manager.position_magnet(*args, **kw)
def spy_peak_center(self, name):
peak_kw = dict(confirm_save=False, warn=True,
new_thread=False,
message='spectrometer script peakcenter',
on_end=self._on_peak_ce... |
dsloop/FranERP | app/google_drive_api.py | Python | mit | 3,922 | 0.000255 | import httpli | b2
import os
impo | rt mimetypes
import time
from apiclient import discovery, errors
from googleapiclient.http import MediaFileUpload
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage
try:
import argparse
flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
... |
edx-solutions/edx-platform | openedx/tests/completion_integration/test_views.py | Python | agpl-3.0 | 9,482 | 0.001476 | # -*- coding: utf-8 -*-
"""
Test models, managers, and validators.
"""
import ddt
from completion import waffle
from completion.test_utils import CompletionWaffleTestMixin
from django.urls import reverse
from rest_framework.test import APIClient
import six
from openedx.core.djangolib.testing.utils import skip_unless... | UserFactory(username=self.UNENROLLED_USERNAME)
# Enrol one user in the course
CourseEnrollmentFactory.create(user=self.enrolled_user, course_id=self.course.id)
CourseEnrollmentFactory.create(user=self.enrolled_user, course_id=self.course_deprecated.id)
# Login the enrolled user by for... | _user)
def test_enable_completion_tracking(self):
"""
Test response when the waffle switch is disabled (default).
"""
with waffle.waffle().override(waffle.ENABLE_COMPLETION_TRACKING, False):
response = self.client.post(self.url, {'username': self.ENROLLED_USERNAME}, form... |
castelao/CoTeDe | cotede/qctests/fuzzylogic.py | Python | bsd-3-clause | 2,680 | 0.002985 | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Quality Control based on fuzzy logic.
"""
import logging
import numpy as np
from .core import QCCheckVar
from .gradient import gradient
from .spike import spike
from .woa_normbias import woa_normbias
from cotede.fuzzy im... | zylogic(self.features, self.cfg)
def test(self):
self.flags = {}
cfg = self.cfg
flag = np.zeros(np.shape(self.data[self.varname]), dtype="i1")
uncertainty = self.features["fuzzylogic"]
# FIXME: As it is now, it wil | l have no zero flag value. Think about cases
# where some values in a profile would not be estimated, hence flag=0
# I needed to use np.nonzeros because now uncertainty is a masked array,
# to accept when a feature is masked.
flag[np.nonzero(uncertainty <= 0.29)] = 1
flag[np.... |
jungla/ICOM-fluidity-toolbox | 2D/U/plot_drate_z.py | Python | gpl-2.0 | 3,339 | 0.03504 | import os, sys
import myfun
import numpy as np
import matplotlib as mpl
mpl.use('ps')
import matplotlib.pyplot as plt
import lagrangian_stats
import fio
## READ archive (too many points... somehow)
# args: name, dayi, dayf, days
#label = 'm_25_1_particles'
#label_25 = 'm_25_1_particles'
label = 'm_25_2_512'
label_2... | ent(W_25[i,j,:]-np.mean(W_25[i,j,:]))/dz_25)**2)
FW_25[j,i,:,t] = 0.5*nu_h | *((np.gradient(U_25[i,j,:])/dz_25)**2 + (np.gradient(V_25[i,j,:])/dz_25)**2) + 0.5*nu_v*(np.gradient(W_25[i,j,:])/dz_25)**2
FW_t25 = np.mean(np.mean(FW_25,0),0)
# plt.figure(figsize=(4,8))
# p25, = plt.semilogx(7.5*0.05*FW_t25[:,t],Zlist,'k--',linewidth=2)
FW_m = -11
FW_M = -7
plt.figure(figsize=(8,4))
plt.contour... |
JoKaWare/WTL-DUI | tools/grit/grit/tool/postprocess_interface.py | Python | bsd-3-clause | 1,029 | 0.004859 | #!/usr/bin/env python
# Copyright (c) 2012 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.
''' Base class for postprocessing of RC files.
'''
import sys
class PostProcessor(object):
''' Base class for postprocessing of the RC file data before being
outpu | t through the RC2GRD tool. You should implement this class if
you want GRIT to do specific things to the RC files after it has
converted the data into GRD format, i.e. change the content of the
RC file, and put it into a P4 changelist, etc.'''
def Process(self, rctext, rcpath, grdnode):
''' Processes the ... |
GajaZ/Locevanje_odpadkov | kamera_klik.py | Python | gpl-3.0 | 666 | 0.016517 | from SimpleCV import Camera, Dis | play
import time
import wx
def slika_klik():
| cam = Camera(0)
display = Display()
cam.getImage().show()
i = 0
while display.isNotDone():
start_time = time.clock()
img = cam.getImage()
if display.mouseLeft:
img.save("C:\Users\Gaja\Desktop\DIR2017\Locevanje_odpadkov-master\Zajete_slike\slika_v_obdelav... |
edespino/gpdb | src/test/tinc/tincrepo/mpp/gpdb/tests/storage/walrepl/gpinitstandby/__init__.py | Python | apache-2.0 | 6,141 | 0.007816 | """
Copyright (c) 2004-Present Pivotal Software, Inc.
This program and the accompanying materials are made available under
the terms of the 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.... | nt host other than master available to have remote standby')
d | ef get_primary_pid(self):
pid = self.pgutil.get_pid_by_keyword(pgport=os.environ.get('PGPORT'), keyword=self.mdd)
if int(pid) == -1:
raise WalReplException('Unable to get pid of primary master process')
else:
return int(pid)
def compare_primary_pid(self, initial_pid)... |
adamhadani/HBasta | hbasta/__init__.py | Python | apache-2.0 | 69 | 0 | #!/u | sr/bin/env python
from _api im | port *
from _intoptparse import *
|
cnvogelg/fs-uae-gles | launcher/fs_uae_launcher/ui/LauncherFileDialog.py | Python | gpl-2.0 | 2,280 | 0.002632 | from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
from __future__ import unicode_literals
import os
import fs_uae_launcher.fsui as fsui
from ..Settings import Settings
from ..I18N import _, ngettext
from .Skin import Skin
class LauncherFileDialog(fsui.FileDia... | self.settings_key = "last_{0}_dir".format(type)
| directory = ""
if last_path and last_path not in ["internal"]:
print("last_path", repr(last_path))
#if os.path.isdir(last_path):
# last_path_dir = last_path
#else:
last_path_dir = os.path.dirname(last_path)
print("last_path_dir", ... |
isotoma/KeenClient-Python | keen/persistence_strategies.py | Python | mit | 1,595 | 0 | __author__ = 'dkador'
class BasePersistenceStrategy(object):
"""
A persistence strategy is responsible for persisting a given event
somewhere (i.e. directly to Keen, a local cache, a Redis queue, etc.)
"""
def per | sist(self, event):
"""Persists the given event somewhere.
:param event: the event to persist
"""
raise NotImplementedError()
class DirectPersistenceStrategy(BasePersistenceStrategy):
"""
A persistence strategy that saves directly to Keen and bypasses any local
cache.
"... | r DirectPersistenceStrategy.
:param api: the Keen Api object used to communicate with the Keen API
"""
super(DirectPersistenceStrategy, self).__init__()
self.api = api
def persist(self, event):
""" Posts the given event directly to the Keen API.
:param event: an Ev... |
henryiii/semester | semester/gui/sandals.py | Python | mit | 15,589 | 0.007569 | from contextlib import contextmanager
import threading
try: # python 3
import tkinter
from tkinter import messagebox
from tkinter import filedialog
from tkinter import simpledialog
from tkinter import scrolledtext
from tkinter import Scrollbar
from tkinter import N
from tkinter import ... | self.frame = tkinter.Frame(self.canvas)
self.frame.columnconfigure(0, w | eight=1)
self.frame.columnconfigure(1, weight=1)
_pack_side = TOP
_root = self.frame
return self # was _root for some reason
def __exit__(self, type, value, traceback):
global _root, _pack_side
# puts tkinter widget onto canvas
self.canvas.create_window(0,... |
martinrotter/textilosaurus | src/libtextosaurus/3rd-party/scintilla/gtk/DepGen.py | Python | gpl-3.0 | 752 | 0.014628 | #!/usr/bin/env python3
# DepGe | n.py - produce a make dependencies file for Scintilla
# Copyright 2019 by Neil Hodgson <neilh@sc | intilla.org>
# The License.txt file describes the conditions under which this software may be distributed.
# Requires Python 3.6 or later
import sys
sys.path.append("..")
from scripts import Dependencies
topComment = "# Created by DepGen.py. To recreate, run DepGen.py.\n"
def Generate():
sources = ["../src/*.cxx"... |
sniperganso/python-manilaclient | manilaclient/tests/functional/base.py | Python | apache-2.0 | 10,433 | 0 | # Copyright 2014 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... | cleanup_in_class=True, microversion=None):
if client is None:
client = cls.get_admin_client()
share_type = client.create_share_type(
name=name,
| driver_handles_share_servers=driver_handles_share_servers,
snapshot_support=snapshot_support,
is_public=is_public,
microversion=microversion,
)
resource = {
"type": "share_type",
"id": share_type["ID"],
"client": client,
... |
FishPi/FishPi-POCV---Command---Control | fishpi/ui/main_view_tk.py | Python | bsd-2-clause | 13,484 | 0.010902 |
#
# FishPi - An autonomous drop in the ocean
#
# Main View classes for POCV UI.
#
import tkFont
from Tkinter import *
from PIL import Image, ImageTk
class MainView(Frame, object):
""" MainView class for POCV UI. """
def __init__(self, master, view_controller):
super(MainView, self).__init__(mas... | ,190,75,230), width=2, fill="white")
self.top.create_text((55,210), text="H", font=14)
self.image=photo
self.top.bind("<Button-1>", self.click_callback)
self.top.bin | d("<B1-Motion>", self.move_callback)
self.top.pack(fill=X)
def click_callback(self, event):
print "clicked at", event.x, event.y
def move_callback(self, event):
print event.x, event.y
class CameraFrame(Frame, object):
""" UI Frame displaying camera image. """
def __init__... |
MostlyOpen/odoo_addons_jcafb | myo_professional_cst/__openerp__.py | Python | agpl-3.0 | 1,550 | 0.000645 | # -*- coding: utf-8 -*-
###############################################################################
#
# Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
#... | rogram 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# ... | ###################################################
{
'name': 'Professional (customizations for CLVhealth-JCAFB Solution)',
'summary': 'Professional Module customizations for CLVhealth-JCAFB Solution.',
'version': '2.0.0',
'author': 'Carlos Eduardo Vercelino - CLVsol',
'category': 'Generic Modules/... |
pmagwene/unscanny | scanit.py | Python | gpl-3.0 | 1,722 | 0.013937 | #!/usr/bin/env python
import sys
import argparse
import collections
import numpy as np
import tifffile as TIFF
import sane
import click
import toml
def quick_scan(settings = {}, test = False):
"""Make scan using first scanning device found by SANE driver.
"""
# init and find devices
sane.init()
... | = True)
if test:
devices = [("test", "SANE", "SA | NE", "SANE")]
settings["source"]= "Flatbed"
settings["test_picture"] = "Color pattern"
settings["mode"] = "Color"
settings["resolution"] = 75
settings["depth"] = 8
if not len(devices):
return None
dev_name = devices[0][0]
# open scanner
scanner = sane.op... |
jedie/django-secure-js-login | tests/test_utils/selenium_test_cases.py | Python | gpl-3.0 | 5,276 | 0.003033 | # coding: utf-8
"""
Secure JavaScript Login
~~~~~~~~~~~~~~~~~~~~~~~
:copyleft: 2012-2015 by the secure-js-login team, see AUTHORS for more details.
:created: by JensDiemer.de
:license: GNU GPL v3 or above, see LICENSE for more details
"""
from __future__ import unicode_literals, print_function
i... | source': %s" % e)
else:
page_source = "\n".join([line for line in page_source.splitlines() if line.rstrip()])
print(page_source, file=sys.stderr)
sys.stderr.write("*" * 79)
sys.stderr.write("\n")
sys.stderr.write("\n\n")
sys.stderr.flush()
raise ... | ext = alert.text
alert.accept() # Confirm a alert dialog, otherwise access to driver.page_source will failed!
try:
raise self.failureException("Alert is preset: %s" % alert_text)
except AssertionError as err:
self._verbose_assertion_error(err)
def... |
dmS0Zq/ganeti_webmgr | ganeti_webmgr/ganeti_web/views/importing.py | Python | gpl-2.0 | 7,249 | 0 | # Copyright (C) 2010 Oregon State University et al.
#
# 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 i... | vm = VirtualMachine.objects.get(id=id)
vm.owner = owner
vm.save()
orphaned[vm.cluster_id] -= 1
# remove updated vms from the list
vms_wi | th_cluster = [i for i in vms_with_cluster
if unicode(i[0]) not in vm_ids]
else:
# strip cluster from vms
form = ImportForm([(i[0], i[1]) for i in vms_with_cluster])
clusterdict = {}
for i in clusters:
clusterdict[i.id] = i.hostname
vms = [(i[0], ... |
calve/cerberus | cerberus/cerberus.py | Python | isc | 45,426 | 0.000154 | """
Extensible validation for Python dictionaries.
This module implements Cerberus Validator class
:copyright: 2012-2015 by Nicola Iarocci.
:license: ISC, see LICENSE for more details.
Full documentation is available at http://python-cerberus.org
"""
from collections import Callable, Hashable, It... |
'required' will always be validated, regardless of any dependencies.
.. versionadded:: 0.9
'anyof', 'noneof', 'allof', 'anyof' validation rules.
PyPy support.
'coerce' rule.
'propertyschema' validation rule.
'validator.validated' takes a doc | ument as argument and returns a
validated document or 'None' if validation failed.
.. versionchanged:: 0.9
Use 'str.format' in error messages so if someone wants to override them
does not get an exception if arguments are not passed.
'keyschema' is renamed to 'valueschema'. Clos... |
nicolaiarocci/eve-oauth2 | run.py | Python | bsd-3-clause | 917 | 0.001091 | # -*- coding: utf-8 -*-
"""
Eve Demo (Secured)
~~~~~~~~~~~~~~~~~~
This is a fork of Eve Demo (https://github.com/pyeve/eve-demo)
intended to demonstrate how a Eve API can be secured by means of
Flask-Sentinel.
For demonstration purposes, besides protecting a couple API endpoints
with a Be... | static html
endpoint an protecting with via decorator.
:copyright: (c) 2015 by Nicola Iarocci.
:license: BSD, see LICENSE for more details.
"""
from eve import Eve
from oauth2 import BearerAuth
from flask.ext.sentinel import ResourceOwnerPasswordCredentials, oauth
app = Eve(auth=BearerAuth)
ResourceOwner... | through and accessed the protected resource!"
if __name__ == '__main__':
app.run(ssl_context='adhoc')
|
s-leger/archipack | pygeos/op_valid.py | Python | gpl-3.0 | 31,278 | 0.000959 | # -*- coding:utf-8 -*-
# ##### BEGIN LGPL LICENSE BLOCK #####
# GEOS - Geometry Engine Open Source
# http://geos.osgeo.org
#
# Copyright (C) 2011 Sandro Santilli <strk@kbt.io>
# Copyright (C) 2005 2006 Refractions Research Inc.
# Copyright (C) 2001-2002 Vivid Solutions Inc.
# Copyright (C) 1995 Olivier Devill... |
)
from .op_overlay import (
MinimalEdgeRing,
MaximalEdgeRing,
OverlayNodeFactory
)
class TopologyErrors():
eError = 0
eRepeatedPoint = 1
eHoleOutsideShell = 2
eNestedHoles = 3
eDisconnectedInterior = 4
eSelfIntersection = 5
eRingSelfIntersection = 6
... | dinate = 10
eRingNotClosed = 11
msg = (
"Topology Validation Error",
"Repeated Point",
"Hole lies outside exterior",
"Holes are nested",
"Interior is disconnected",
"Self-intersection",
"Ring Self-intersection",
"Nested exteriors",
... |
amerlyq/airy | ranger/plugins/macro_date.py | Python | mit | 866 | 0 | # Compatible with ranger 1.6.0 through 1.7.*
#
# This plugin adds the new macro %date which is substituted with the current
# date in commands | that allow macros. You can test it with the command
# ":shell echo %date; read"
# from __future__ import (absolute_import, division, print_function)
import time
import ranger.core.actions
# Save the original macro function
GET_MAC | ROS_OLD = ranger.core.actions.Actions.get_macros
# Define a new macro function
def get_macros_with_date(self):
macros = GET_MACROS_OLD(self)
macros['dt'] = time.strftime('%Y%m%d')
macros['dT'] = time.strftime('%Y-%m-%d')
macros['dw'] = time.strftime('%Y-%m-%d-%a')
macros['dW'] = time.strftime('%Y-... |
algorythmic/bash-completion | test/t/test_ncftp.py | Python | gpl-2.0 | 245 | 0 | import pytest
class TestNcftp:
@pytest.mark.complete("ncftp ")
def test_1( | self, completion):
assert completion
| @pytest.mark.complete("ncftp -", require_cmd=True)
def test_2(self, completion):
assert completion
|
apruden/opal | opal-python-client/src/main/python/opal/perm_project.py | Python | gpl-3.0 | 1,309 | 0.00382 | """
Apply permissions on a project.
"""
import sys
import opal.core
import opal.perm
PERMISSIONS = {
'administrate': 'PROJECT_ALL'
}
def add_arguments(parser):
"""
Add command specific options
"""
opal.perm.add_permission_arguments(parser, PERMISSIONS.keys())
parser.add_argument('--project', ... | ssion command
"""
# Build and send requests
try:
opal.perm.validate_args(args, PERMISSIONS)
request = opal.core.OpalClient.build(opal.core.OpalClient.LoginInfo.parse(args)).new_request()
if args.verbose:
request.verbose()
# send request
if args.delete:
... | (args, ['project', args.project, 'permissions', 'project'], PERMISSIONS)).send()
except Exception, e:
print Exception, e
# format response
if response.code != 200:
print response.content
except Exception, e:
print e
sys.exit(2)
except pycurl.err... |
VirgiliaBeatrice/VocabularyGenerator | src/sqlbase.py | Python | mit | 4,534 | 0.001764 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created by iFantastic on 15/09/05
import sqlite3
#TODO: Add more class method for Database Class.
class Database():
def __init__(self, db_name):
self.db = sqlite3.connect(db_name.decode('utf-8'))
# self.db = sqlite3.connect(':memory:')
self.... | nd))
return self.cr.fetchall()
def update(self, table_name, values, conditions):
command = [
('', False),
'UPDATE',
table_name,
'SET',
values,
'WHERE',
conditions
]
print create_str(command)
... | .db.commit()
def insert(self, table_name, values):
query_qmark = ['?' for dummy_idx in range(len(values))]
query_qmark.insert(0, (',', True))
command = [
('', False),
'INSERT INTO',
table_name,
'VALUES',
query_qmark
]
... |
markYoungH/chromium.src | tools/telemetry/telemetry/core/backends/chrome_inspector/inspector_backend.py | Python | bsd-3-clause | 9,745 | 0.008722 | # Copyright 2013 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 logging
import os
import sys
from telemetry import decorators
from telemetry.core import exceptions
from telemetry.core import util
from telemetry.co... | pector_network.InspectorNetwork(self._websocket)
self._timeline_model = None
def __del__(self):
self._websocket.Disconnect()
@property
def app(self):
return self._app
@property
def url(self):
for c in self._devtools_client.ListInspectableContexts():
if c['id'] == self._context['id']:
... | property
def id(self):
return self.debugger_url
@property
def debugger_url(self):
return self._context['webSocketDebuggerUrl']
# Public methods implemented in JavaScript.
@property
@decorators.Cache
def screenshot_supported(self):
if (self.app.platform.GetOSName() == 'linux' and (
o... |
WheatonCS/Lexos | lexos/receivers/base_receiver.py | Python | mit | 1,956 | 0 | """This is the base receiver for the base model."""
from flask import request
from typing import Optional, Union, Dict, List
RequestData = Dict[str, Union[str, dict, List[dict]]]
class BaseReceiver:
"""This is the base receiver class for | the base model."""
def __init__(self):
"""Use base model for all the models.
used to handle requests and other common stuff
"""
pass
@property
def _front_end_data_nullable(self) -> Optional[RequestData]:
"""Get nullable front-end data.
the front end data,... | in an request context, you will get None
- if no request data is sent in current request, you will get None
:return: the front end data, possibly None.
"""
try:
return self._get_all_options_from_front_end()
except RuntimeError: # working out of request context
... |
estuans/django-oscar-gmerchant | gmerchant/migrations/0007_auto__add_field_googleproduct_google_shopping_updated.py | Python | bsd-3-clause | 13,944 | 0.00753 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as 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 'GoogleProduct.google_shopping_updated'
db.add_column(u'gm... | ': 'True'}),
'recommended_products': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['catalogue.Product']", 'symmetrical': 'False', 'through': "orm['catalogue.ProductRecommendation']", 'blank': 'True'}),
'slug': ('django.db.mode | ls.fields.SlugField', [], {'max_length': '255'}),
'structure': ('django.db.models.fields.CharField', [], {'default': "'standalone'", 'max_length': '10'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
'upc': ('oscar.models.fields.NullChar... |
IEMLdev/propositions-restful-server | ieml/dictionary/table/table_structure.py | Python | gpl-3.0 | 3,891 | 0.003341 | import sys
from collections import defaultdict
from itertools import chain
from ieml import error
from ieml.commons import logger
from ieml.dictionary.table.table import *
class TableStructure:
# define a forest of root paradigm
# This class defines :
# - for each paradigm :
# o the parent tab... | nces[0] + " not found")
continue
roots[root_ss[s.singular_sequences[0]]].append(s)
root_paradigms | = {}
for root in root_scripts:
tables, cells = TableStructure._define_root(root=root, paradigms=roots[root])
root_paradigms[root] = tables | cells
tables = {}
for t in chain.from_iterable(root_paradigms.values()):
tables[t.script] = t
return tables,... |
ProfessorX/Config | .PyCharm30/system/python_stubs/-1247971765/PyKDE4/kdecore/KDateTime.py | Python | gpl-2.0 | 5,923 | 0.011312 | # encoding: utf-8
# module PyKDE4.kdecore
# from /usr/lib/python3/dist-packages/PyKDE4/kdecore.cpython-34m-x86_64-linux-gnu.so
# by generator 1.135
# no doc
# imports
import PyQt4.QtCore as __PyQt4_QtCore
import PyQt4.QtNetwork as __PyQt4_QtNetwork
class KDateTime(): # skipped bases: <class 'sip.wrapper'>
# no d... | : # real signature unknown
pass
def addMonths(self, *args, **kwargs): # real signature unknown
pass
def addMSecs(self, *args, **kwargs): # real signature unknown
pass
def addSecs(self, *args, **kwargs): # real signature unknown
pass
def addYears(self, *args, **kwargs)... | nature unknown
pass
def compare(self, *args, **kwargs): # real signature unknown
pass
def currentDateTime(self, *args, **kwargs): # real signature unknown
pass
def currentLocalDate(self, *args, **kwargs): # real signature unknown
pass
def currentLocalDateTime(self, *a... |
knaffe/Face_Recog_sys | person_detectior/detect_motion.py | Python | mit | 2,007 | 0.014449 | '''
Date : 2017-4-21
Author : Chilam
Application : Person Detector based on OpenCV HOG and SVM detector
'''
# import the necessary packages
from __future__ import print_function
from imutils.object_detection import non_max_suppression
from imutils import paths
import numpy as np
import argparse
import im... | e
# and (2) improve detection accuracy
image = cv2.imread(imagePath)
image = imutils.resize(image, width=min(400, image.shape[1]))
orig = image.copy()
# detect people in the ima | ge
(rects, weights) = hog.detectMultiScale(image, winStride=(4, 4),
padding=(8, 8), scale=1.05)
# draw the original bounding boxes
for (x, y, w, h) in rects:
cv2.rectangle(orig, (x, y), (x + w, y + h), (0, 0, 255), 2)
# apply non-maxima suppression to the bounding boxes using a
# fairly large overla... |
Azure/azure-sdk-for-python | sdk/compute/azure-mgmt-compute/azure/mgmt/compute/v2019_12_01/_compute_management_client.py | Python | mit | 12,428 | 0.004425 | # 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 ... | ations, VirtualMachineScaleSetExtensionsOperations, VirtualMachineScaleSetRollingUpgradesOperations, VirtualMachineScaleSetVMExtensionsOperations, VirtualMachineScaleSetVMsOperations, VirtualMachineScaleSetsOperations, VirtualMachineSizesOperations, VirtualMachinesOperations
if TYPE_CHECKING:
# pylint: disable=unu... | Credential
class ComputeManagementClient:
"""Compute Client.
:ivar operations: Operations operations
:vartype operations: azure.mgmt.compute.v2019_12_01.operations.Operations
:ivar availability_sets: AvailabilitySetsOperations operations
:vartype availability_sets:
azure.mgmt.compute.v2019_12... |
schreiberx/sweet | tests/20_platforms_job_generation/benchmark_create_job_scripts.py | Python | mit | 3,673 | 0.002723 | #! /usr/bin/env python3
import sys
from itertools import product
from mule_local.JobMule import *
from mule.exec_program import *
from mule.InfoError import *
jg = JobGeneration()
"""
Compile parameters
"""
params_compile_sweet_mpi = ['enable', 'disable']
params_compile_threading = ['omp', 'off']
params_compile_th... |
jg.compile.sweet_mpi
) in product(
params_compile_threading,
params_compile_thread_parallel_sum,
params_compile_sweet_mpi
):
if 'exp' in jg.runtime | .timestepping_method:
jg.runtime.rexi_method = 'ci'
jg.gen_jobscript_directory()
jg.runtime.rexi_method = ''
else:
if jg.compile.sweet_mpi == 'enable':
continue
if jg.compil... |
DarthMaulware/EquationGroupLeaks | Leak #1 - Equation Group Cyber Weapons Auction - Invitation/EQGRP-Free-File/Firewall/EXPLOITS/ELCO/fosho/requests/structures.py | Python | unlicense | 1,453 | 0.002753 | # -*- coding: utf-8 -*-
"""
requests.structures
~~~~~~~~~~~~~~~~~~~
Data structures that power Requests.
"""
class CaseInsensitiveDict(dict):
''''''
@property
def lower_keys(self):
if not hasattr(self, '_lower_keys') or not self._lower_keys:
self._lower_keys = dict((k.lower(), k) ... | rn dict.__getitem__(self, self.lower_keys[key.lower()])
def get(self, key, default=None):
if key in self:
return self[key]
else:
return default
class LookupDict(dict):
''''''
def __init__(self, name=None):
self.name = name
super(LookupDict, self)._... | % (self.name)
def __getitem__(self, key):
##
return self.__dict__.get(key, None)
def get(self, key, default=None):
return self.__dict__.get(key, default)
|
vignettist/image-import | import_classify.py | Python | mit | 4,535 | 0.005072 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os.path
import re
import sys
import tarfile
import numpy as np
from six.moves import urllib
import tensorflow as tf
import time
class Classifier:
def __init__(self, prefix):
self.DATA_URL... | ownload_and_extract(self):
"""Download and extract model tar file.
If the pretrained model we're using doesn't already ex | ist, this function
downloads it from the TensorFlow.org website and unpacks it into a directory.
"""
dest_directory = self.FLAGS.model_dir
if not os.path.exists(dest_directory):
os.makedirs(dest_directory)
filename = self.DATA_URL.split('/')[-1]
filepath = os.... |
googleapis/python-aiplatform | samples/generated_samples/aiplatform_generated_aiplatform_v1_dataset_service_list_annotations_sync.py | Python | apache-2.0 | 1,539 | 0.0013 | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | Y KIND, either express or implied.
# See the License for the specific la | nguage governing permissions and
# limitations under the License.
#
# Generated code. DO NOT EDIT!
#
# Snippet for ListAnnotations
# NOTE: This snippet has been automatically generated for illustrative purposes only.
# It may require modifications to work in your environment.
# To install the latest published package ... |
microcom/clouder | clouder_template_docker/__openerp__.py | Python | gpl-3.0 | 1,398 | 0 | # -*- coding: utf-8 -*-
##############################################################################
#
# Author: Yannick Buron
# Copyright 2015, TODAY Clouder SASU
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License with Attribution
# ... | ########################################
{
'name': 'Clouder Template Docker',
'version': '1.0',
'category': 'Clouder',
'depends': ['clouder'],
'author': 'Yannick Buron (Clouder)',
'license': 'Other OSI approved licence',
'website': 'htt | ps://github.com/clouder-community/clouder',
'description': """
Clouder Template Docker
""",
'demo': [],
'data': ['clouder_template_docker_data.xml'],
'installable': True,
'application': True,
}
|
dmccloskey/component-contribution | component_contribution/kegg_database.py | Python | mit | 860 | 0.004651 | # -*- coding: utf-8 -*-
"""
Created on Tue May 31 10:57:02 2016
@author: noore
"""
import bioservices.kegg
import pandas as pd
kegg = bioservices.kegg.KEGG | ()
cid2name = kegg.list('cpd')
cid2name = filter(lambda x: len(x) == 2, map(lambda l : l.split('\t'), cid2name.split('\n')))
cid_df = pd.DataFrame(cid2name, columns=['cpd', 'names'])
cid_df['cpd'] = cid_df['cpd'].apply(lambda x: x[4:])
cid_df['name'] = cid_df['names'].apply(lambda s: s.split(';')[0])
cid_df.set_index('... | df['inchi'] = None
for cid in cid_df.index[0:10]:
ChEBI = re.findall('ChEBI: ([\d\s]+)\n', kegg.get(cid))
if len(ChEBI) == 0:
print 'Cannot find a ChEBI for %s' % cid
elif len(ChEBI) > 1:
print 'Error parsing compound %s' % cid
else:
cid2chebi.at[cid, 'ChEBI'] = ChEBI[0]
cid2ch... |
ToonTownInfiniteRepo/ToontownInfinite | toontown/golf/DistributedPhysicsWorldAI.py | Python | mit | 2,425 | 0.004536 | from math import *
import math
import random, time
import BuildGeometry
from direct.directnotify import DirectNotifyGlobal
from direct.distributed import DistributedObjectAI
from pandac.PandaModules import *
from toontown.golf import PhysicsWorldBase
from toontown.toonbase import ToontownGlobals
class DistributedPhy... | lf.holdingUpObjectData = 1
self.commonHoldData = objectData
if self.storeAction:
self.doAction | ()
def setupCommonObjects(self):
print 'setupCommonObjects'
print self.commonHoldData
if not self.commonHoldData:
return
elif self.commonHoldData[0][1] == 99:
print 'no common objects'
else:
self.useCommonObjectData(self.commonHoldData, 0)... |
yanadsl/ML-Autocar | test.py | Python | mit | 519 | 0.00578 | import sys
import pigpio
import time
from colorama import Fore, Back, Style
def set_speed(lspeed, rspeed):
pi.hardware_PWM(left_servo_pin, 800, int(lspeed)*10000)
pi.hardware_PWM(right_servo_pin, 800, int(rspeed)*10000)
pi = pigpio.pi()
left_servo_pin = | 13
right_servo_pin = 12
dead_pin = 17
die_distance = 8
ls = 100
rs = 100
print("start")
try:
while True:
set_speed(ls, rs)
if pi.read(dead_pin) == pigpio.LOW:
set_speed(0, 0)
except :
set_speed(0, 0)
sys.e | xit(0)
|
mozilla/user-advocacy | lib/web_api/google_services.py | Python | mpl-2.0 | 4,807 | 0.008945 | #!/usr/local/bin/python
"""
Handles Google Service Authentication
"""
# TODO(rrayborn): Better documentation
__author__ = "Rob Rayborn"
__copyright__ = "Copyright 2014, The Mozilla Foundation"
__license__ = "MPLv2"
__maintainer__ = "Rob Rayborn"
__email__ = "rrayborn@mozilla.com"
__status__ = "Development"
from Ope... | _PATH = environ['SECRETS_PATH']
# Header and Grant Type are always the same for Google's API so making a
# variable instead of a file
_HEADER_JSON = {'alg':'RS256','typ':'jwt'}
_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:jwt-bearer'
# Default filenames
_CLAIMS_FILE = _SECRETS_PATH + 'claims.json'
_P12_FILE ... | s
_GOOG_PASSPHRASE = 'notasecret' # notasecret is the universal google passphrase
class google_service_connection(object):
def __init__(self, json_web_token=None, expiration=None, claims_file=_CLAIMS_FILE,
p12_file=_P12_FILE, auth_file=_AUTH_FILE):
self._json_web_token = None
self... |
comandrei/django-shortcircuit | setup.py | Python | bsd-3-clause | 2,291 | 0.000873 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import re
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
def get_version(*file_paths):
filename = os.path.join(os.path.dirname(__file__), *file_paths)
version_file = open(filename).read()
ve... | l wheel"')
| sys.exit()
os.system('python setup.py sdist upload')
os.system('python setup.py bdist_wheel upload')
sys.exit()
if sys.argv[-1] == 'tag':
print("Tagging the version on github:")
os.system("git tag -a %s -m 'version %s'" % (version, version))
os.system("git push --tags")
sys.exit()
re... |
beeldengeluid/linkedtv-editortool | src/linkedtv/text/TextAnalyzer.py | Python | gpl-2.0 | 1,003 | 0.013958 | import codecs
import logging
logger = logging.getLogger(__name__)
class TextAnalyzer:
def __init__(self):
logger.debug('-- Initializing TextAnalyzer --')
"""
Deze functie leest een stopwoorden file (stoplist_tno.tab) in en retourneert deze woorden in
een dic | tionary
"""
def readStopWordsFile(self, strStopFile):
if not strStopFile:
strStopFile = self | ._stopWordsFile
""" read stopwords from file as dictionary. """
stopWords = {}
try:
f = codecs.open(strStopFile,'rU','utf-8') # NB. Use 'U'-mode for UniversalNewline Support
for line in f.readlines():
word = line.partition('::')[0].strip()#.decode(... |
drweaver/py_garage_server | garage_state_mon.py | Python | mit | 1,828 | 0.036105 | from threading import Thread, Event
from time import sleep
from garage import Garage
import logging
from time import time
logger = logging.getLogger('garage_state_mon')
class LastStateTransitionMonitor(Thread):
def __init__(self, dao, config, state=Garage.closed, notify_callback=None):
Thread.__init__(... | f._state = state
self._stop_event = Event()
def check_now(self):
last_time = self._dao.last_state_transition_from(self._state)
if last_time is None:
logger.info("No notification required, already in "+self._state+" state")
return
if last_time == 0:
msg = 'Garage Door has never been ... | t_time ) / 60)
self._config.reload()
limit = self._config['state_monitor_limit_mins']
if diff < limit: return
if diff > 99: diff_msg = str(round(diff/60))+' hours'
elif diff > 2880: diff_msg = str(round(diff/1440))+' days'
else: diff_msg = str(diff)+' minutes'
msg = 'Garage Door has not been... |
chrcoe/code-kata | legacy/python/hashtable/__init__.py | Python | mit | 4,107 | 0.000487 | '''
Basic hash table to practice working through hash table logic...
'''
class HashTable():
def __init__(self):
CURRENT_SIZE = 10
self.table_size = CURRENT_SIZE
# self.table = [0] * self.table_size
# TODO: make this more dynamic .. check for collisions instead of filling every slo... | resize if the | table is full...
# TODO: implement table resizing
self.table[self.__simple_str_hash(input_str)].append(input_str)
def remove(self, input_str):
self.table[self.__simple_str_hash(input_str)].remove(input_str)
def exists(self, input_str):
return self.table[self.__simple_str_hash(... |
facetothefate/contrail-controller | src/vnsw/opencontrail-vrouter-netns/opencontrail_vrouter_netns/vrouter_docker.py | Python | apache-2.0 | 10,235 | 0.000195 | import argparse
import json
import netaddr
import os
import uuid
import docker
import sys
from docker.errors import APIError
from vrouter_netns import validate_uuid, NetnsManager
class VRouterDocker(object):
"""
Creates and drestoys service instance inside Docker.
It needs to be run as superuser to connec... | ult mask to /32"))
create_parser.add_argument(
| "--vmi-management-id",
default=None,
help="Management virtual machine interface UUID")
create_parser.add_argument(
"--vmi-management-mac",
default=None,
help=("Management virtual machine interface MAC. Default: "
"automatically ge... |
remremrem/EV-Tribute | world/Net/netbase.py | Python | mit | 6,335 | 0.027466 | import socket,select,sys,time
from errors import *
from communicate import SendData, ReceiveData, ReceiveDataUDP
class TCPServer():
def __init__(self):
self.sending_socket = None
def input_func(self,sock,host,port,address):pass
def output_func(self,sock,host,port,address):pass
de... | ould not be opened. It must be created first with a server object.")
def send_data(self, | data,compress=False):
SendData(self.socket,data,compress,includelength=True)
def wait_for_data(self):
input_ready,output_ready,except_ready = select.select([self.socket],[],[])
return ReceiveData(self.socket)
def check_for_data(self):
input_ready,output_ready,except_ready =... |
mica-gossip/MiCA | tools/micavis/custom/RoundRobinMerge.py | Python | bsd-3-clause | 31 | 0 | from MergeI | ndepende | nt import *
|
lukehinds/anteater | anteater/src/virus_total.py | Python | apache-2.0 | 6,371 | 0.001727 | # noinspection PyInterpreter
import json
import logging
import os
import re
import requests
import redis
import sys
import time
import urllib
import uuid
from pylimit import PyRateLimit
import six.moves.configparser
class VirusTotal():
def __init__(self, *args):
self.logger = logging.getLogger(__name__)
... | f.HTTP | _OK:
json_response = response.json()
return json_response
elif response.status_code == self.HTTP_RATE_EXCEEDED:
time.sleep(20)
else:
self.logger.error("sent: %s, HTTP: %d", filename, response.status_code)
def rescan_file(self, ... |
dropbox/changes | changes/artifacts/collection_artifact.py | Python | apache-2.0 | 1,917 | 0.004173 | from __future__ import absolute_import
import json
from changes.config import db
from changes.constants import Result
from changes.models.jobplan import JobPlan
from changes.utils.http import build_web_uri
from .base import ArtifactHandler, ArtifactParseError
class CollectionArtifactHandler(ArtifactHandler):
""... | sion.add(self.step)
| db.session.commit()
class TestsJsonHandler(CollectionArtifactHandler):
# only match in the root directory
FILENAMES = ('/tests.json',)
|
burakince/ocl_web | ocl_web/libs/ocl/star.py | Python | mpl-2.0 | 216 | 0 | # from ..ocl import | ApiResource
# class Star(ApiResource):
# def __init__(self):
# super(Star, sel | f).__init__()
# self.resource = {}
# self.username = ""
# self.dateStarred = ""
|
pombreda/djapian | src/djapian/tests/query.py | Python | bsd-3-clause | 718 | 0.002786 | from djapian.tests.utils impor | t BaseIndexerTest, BaseTestCase, Entry
def query_test(query, count):
class _QueryTest(BaseIndexerTest, BaseTestCase):
def setUp(self):
super(_QueryTest, self).setUp()
self.result = Entry.indexer.search(query)
def test_result_count(self):
self.assertEqual(len(sel... | rSearchAliasFieldTest = query_test("subject:test", 2)
IndexerSearchBoolFieldTest = query_test("active:True", 3)
IndexerSearchAndQueryTest = query_test("title:test AND title:another", 1)
|
timkrentz/SunTracker | IMU/VTK-6.2.0/Web/Python/vtk/web/protocols.py | Python | mit | 11,069 | 0.003523 | r"""protocols is a module that contains a set of VTK Web related
protocols that can be combined together to provide a flexible way to define
very specific web application.
"""
from time import time
import os, sys, logging, types, inspect, traceback, logging, re
from vtkWebCorePython import vtkWebApplication, ... | owAxis):
"""
| RPC callback to show/hide OrientationAxis.
"""
view = self.getView(view)
# FIXME seb: view.OrientationAxesVisibility = (showAxis if 1 else 0);
self.getApplication().InvalidateCache(view)
return str(self.getGlobalId(view))
@exportRpc("viewport.axes.center.visibi... |
bnaul/scikit-learn | examples/miscellaneous/plot_johnson_lindenstrauss_bound.py | Python | bsd-3-clause | 7,785 | 0.001413 | r"""
=====================================================================
The Johnson-Lindenstrauss bound for embedding with random projections
=====================================================================
The `Johnson-Lindenstrauss lemma`_ states that any high dimensional
dataset can be randomly projected i... | uclidean_distances
from sklearn.utils.fixes import parse_version
# `normed` is being deprecated in favor of `density` in histograms
if parse_version(matplotlib.__version__) >= parse_version('2.1'):
density_param = {'density': True}
else:
density_param = {'normed': True}
# %%
# Theor | etical bounds
# ==================
# The distortion introduced by a random projection `p` is asserted by
# the fact that `p` is defining an eps-embedding with good probability
# as defined by:
#
# .. math::
# (1 - eps) \|u - v\|^2 < \|p(u) - p(v)\|^2 < (1 + eps) \|u - v\|^2
#
# Where u and v are any rows taken from ... |
alexfalcucc/anaconda | anaconda_lib/linting/anaconda_pep8.py | Python | gpl-3.0 | 4,416 | 0.000226 | # -*- coding: utf8 -*-
# Copyright (C) 2013 - Oscar Campos <oscar.campos@member.fsf.org>
# This program is Free Software see LICENSE file for details
import os
import pep8
from linting import linter
class Pep8Error(linter.LintError):
"""PEP-8 linting error class
"""
def __init__(self, filename, loc, o... | if code in self.counters:
self.counters[code] += 1
else:
self.counters[code] = 1
self.messages[code] = message
if code in self.expected:
return
... | r = code.startswith('E')
klass = Pep8Error if pep8_error else Pep8Warning
messages.append(klass(
filename, col, offset, code, message, levels[code[0]]
))
return code
params = {'reporter': AnacondaReport... |
nanchenchen/script-analysis | pyanalysis/precompilers.py | Python | mit | 843 | 0.002372 | # This file is a fix for this issue with django-compressor
# https:// | github.com/django-compressor/django-compressor/issues/226
# This is a less filter that explicitly calls CssAbsoluteFilter.
# After adding the relative-urls flag to the lessc command,
# it appears to be unnecessary but I'm leaving it here in case
# we need it later for other deployment setups.
from compressor.filters... | _(self, content, attrs, **kwargs):
super(LessFilter, self).__init__(content, command=settings.BIN_LESSC_COMMAND, **kwargs)
def input(self, **kwargs):
content = super(LessFilter, self).input(**kwargs)
return CssAbsoluteFilter(content).input(**kwargs)
|
rohitranjan1991/home-assistant | homeassistant/components/homekit_controller/binary_sensor.py | Python | mit | 4,745 | 0.000211 | """Support for Homekit motion sensors."""
from __future__ import annotations
from aiohomekit.model.characteristics import CharacteristicsTypes
from aiohomekit.model.services import Service, ServicesTypes
from homeassistant.components.binary_sensor import (
BinarySensorDeviceClass,
BinarySensorEntity,
)
from h... | -> bool:
"""Return true if occupancy is currently detected."""
return self.service.value(CharacteristicsTypes.OCCUPANCY_DETECTED) == 1
class HomeKitLeakSensor(HomeKitEntity, BinarySensorEntity):
"""Representation of a Homekit leak sensor."""
_attr_device_class = Binar | ySensorDeviceClass.MOISTURE
def get_characteristic_types(self) -> list[str]:
"""Define the homekit characteristics the entity is tracking."""
return [CharacteristicsTypes.LEAK_DETECTED]
@property
def is_on(self) -> bool:
"""Return true if a leak is detected from the binary sensor."... |
owlabs/incubator-airflow | tests/www/test_utils.py | Python | apache-2.0 | 14,133 | 0.001132 | # -*- coding: utf-8 -*-
#
# 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
#... | t Session
from airflow.utils.state import State
from airflow.utils import dates, timezone
from airflow.www import utils, app as application
from tests.test_utils.config import conf_vars
if six.PY2:
| # Need `assertRegex` back-ported from unittest2
import unittest2 as unittest
else:
import unittest
class UtilsTest(unittest.TestCase):
def setUp(self):
super(UtilsTest, self).setUp()
def test_empty_variable_should_not_be_hidden(self):
self.assertFalse(utils.should_hide_value_for_k... |
jacburge/wewillremember | app/views.py | Python | apache-2.0 | 610 | 0.013115 | from app import app
from flask import render_template
@app.route('/')
def index():
return render_template('index.html')
@app.route('/story/')
def story():
return render_template('story.html')
@app.route('/bio/')
def bio():
return render_template('bio.html')
@app.route('/contact/')
def contact():
return render_t... | r_template('fun.html')
# @app.route('/por | tfolio/')
# def portfolio():
# return render_template('portfolio.html')
# @app.route('/boot_index/')
# def boot_index():
# return render_template('bootstrap_index.html')
|
art-of-dom/hash-it | test/test_validate_hash.py | Python | mit | 4,257 | 0.00047 | '''Tests for the ValidateHash object'''
from __future__ import absolute_import
import unittest
from nose.tools import assert_true, assert_false
from hashit.core.hash_data import HashData
from hashit.core.hash_type import HashType
from hashit.service.validate_hash import ValidateHash
from hashit.utils.data_encap impo... | t/example.bin"))
def tearDown(self):
pass
def test_verify_hash_crc8_expected_result(self):
assert_true(ValidateHash(
result="14",
hash_type=HashType.CRC8,
data=self.data
).is_vaild())
def test_verify_hash_crc8_bad_result(self):
assert_fa... | data=self.data
).is_vaild())
def test_verify_hash_crc16_expected_result(self):
assert_true(ValidateHash(
result="BAD3",
hash_type=HashType.CRC16,
data=self.data
).is_vaild())
def test_verify_hash_crc16_bad_result(self):
assert_false(Validate... |
pdav/khal | tests/ui/tests_walker.py | Python | mit | 2,702 | 0.00111 | import datetime as dt
from freezegun import freeze_time
from khal.ui import DayWalker, DListBox, StaticDayWalker
from ..utils import LOCALE_BERLIN
from .canvas_render import CanvasTranslator
CONF = {'locale': LOCALE_BERLIN, 'keybindings': {},
'view': {'monthdisplay': 'firstday'},
'default': {'timede... | False,
toggle_delete_all=None,
toggle_delete_instance=None,
dynamic_days=False,
)
canvas = elistbox.render((50, 10), True)
assert CanvasTranslator(canvas, palette).transform() == \
"""\x1b[34mToday (Wednesday, 07.06.2017)\x1b[0m
\x1b[32mTomorrow (Thursday, 08.06.2017)\x1b[0m
... | 09.06.2017 (2 days from now)\x1b[0m
"""
@freeze_time('2017-6-7')
def test_staticdaywalker_3(coll_vdirs):
collection, _ = coll_vdirs
this_date = dt.date.today()
conf = dict()
conf.update(CONF)
conf['default'] = {'timedelta': dt.timedelta(days=1)}
daywalker = StaticDayWalker(this_date, N... |
patrickporto/soldajustica | soldajustica/gallery/apps.py | Python | mit | 123 | 0.008264 | from django.apps import AppConfig
| class GalleryAppConfi | g(AppConfig):
name = 'gallery'
verbose_name = 'Galeria' |
salcho/antares | core/PluginManager.py | Python | mit | 5,590 | 0.005546 | '''
Created on Feb 28, 2013
@author: Santiago Diaz M - salchoman@gmail.com
'''
from core.plugs import fuzzdb_plugin
from core.utils.wsresponse_object import wsResponse
from core.data import logger
from core.Singleton import Singleton
import sys
import inspect
import threading
import Queue
import gtk
class PluginMan... | se_list:
# Report results to analyzer
core.initAnalyzer(self.response_list)
return self.response_list
return None
| def stopAttack(self):
for thread in self.thread_pool:
thread.stop()
with self.request_queue.mutex:
self.request_queue.queue.clear()
# Return the plugin that sent this payload
def getPlugin(self, payload):
ret = None
try:
plugin = self.... |
DavidBarishev/DDtankFarmingBot | Ddtank_farm_bot/Framework/Capture.py | Python | gpl-3.0 | 1,336 | 0.000749 | """This modules is used to capture the screen
"""
import pyautogui
import time
import Globals
PATH = './Captur | es/'
def capture_area(area):
"""
Captures area of the screen
Args:
area (Tuple (x,y,width,height)): Area to capture
Returns:
Image : Image of the area captured
"""
img = pyautogui.screenshot(region=area)
return img
def save_area(area, filename=None):
"""
Saves a... | area (Tuple (x,y,width,height)): Area to capture save
filename (String): File name to save
"""
if filename is None:
filename = ('area_snap_' + str(area).replace('(', ' ').replace(')', ' '))
save_img(capture_area(area=area), filename)
def get_game_screen():
"""
Get game screen ima... |
kappapolls/kappapolls | kappahistory/migrations/0008_auto_20150303_2155.py | Python | gpl-2.0 | 649 | 0 | # -*- coding | : utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('kappahistory', '0007_auto_20150303_2154'),
]
operations = [
migrations.AddField(
model_name='drive',
name='name'... | ),
migrations.AlterField(
model_name='drive',
name='url',
field=models.URLField(null=True, blank=True),
preserve_default=True,
),
]
|
Juniper/tempest | tempest/scenario/test_volume_boot_pattern.py | Python | apache-2.0 | 10,161 | 0 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... | ance %s", server_from_snapshot)
# check the content of written file
| LOG.info("Logging into third instance to get timestamp: %s",
server_from_snapshot)
server_from_snapshot_ip = self.get_server_ip(server_from_snapshot)
timestamp3 = self.get_timestamp(server_from_snapshot_ip,
private_key=keypair['private_key'])
... |
AFFogarty/SEP-Bot | public/sep_search/models/__init__.py | Python | mit | 90 | 0 | from sep_ | search.models.article import Article
from | sep_search.models.author import Author
|
UrLab/incubator | stock/migrations/0007_auto_20200904_2351.py | Python | agpl-3.0 | 587 | 0.001704 | # Generated by Django 3.0.9 on 2020-09-04 21:51
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
| ('stock', '0006_auto_20200904_2343'),
]
operations = [
migrations.RemoveField(
model_name='paymenttransaction',
name='method',
),
migrations.AddField(
model_name='fundzone',
name='method',
field=models.CharField(choices=... | ]
|
ClaudiuGeorgiu/PlaystoreDownloader | playstoredownloader/playstore/meta.py | Python | mit | 1,902 | 0.001052 | #!/usr/bin/env python3
import logging
import requests
logger = logging.getLogger(__name__)
class PackageMeta:
def __init__(self, api, package_name) -> None:
self.api = api
self.package_name = package_name
self.details = self.app_details()
if not self.details:
excepti... | ere was an error when "
f"requesting details for app '{self.package_name}'"
)
logging.exception(exception)
raise exception
def app_details(self) -> object:
"""
Get the details for a certain app (identified by the package name) in the
Googl... | will be None if there was something wrong with the query.
"""
# Prepare the query.
path = "details"
query = {"doc": requests.utils.quote(self.package_name)}
# Execute the query.
# noinspection PyProtectedMember
response = self.api._execute_request(path, query)... |
sonymoon/algorithm | src/main/python/geeksforgeeks/list/mmerge-sort-for-linked-list.py | Python | apache-2.0 | 1,384 | 0 | # key point is to find the half node
class Node:
def __init__(self, val):
self.val = val
self.next = None
class LinkList:
def __init__(self):
self.head = None
def push(self, val):
node = Node(val | )
if self.head:
node.next = self.head
self.head = node
else:
self.head = node
def printList(self):
p = self.head
while p:
print p.val,
p = p.next
print
def mergeSort(head):
if not head | :
return
if not head.next:
return
slow = head
fast = head.next
while fast:
fast = fast.next
if fast:
slow = slow.next
fast = fast.next
# 2 3 20 5 10 15
frontHalf = head
backHalf = slow.next
slow.next = None
mergeSort(frontHalf)... |
pychess/pychess | utilities/arena.py | Python | gpl-3.0 | 6,460 | 0.008363 | #!/usr/bin/python
# -*- coding: utf-8 -*-
'''
PyChess arena tournament script.
This script executes a tournament between the engines installed on your
system. The script is executed from a terminal with the usual environment.
'''
import os
import sys
######################################################... | .write(".")
###############################################################################
# Ask the user for details
engines = []
results = []
minutes = 0
current = [0,0]
def start(discoverer):
global engines, results, minutes
engines | = discoverer.getEngines()
n = len(engines)
for i in range(n):
results.append([None]*n)
print()
print("Your installed engines are:")
for i, engine in enumerate(engines):
name = discoverer.getName(engine)
print("[%s] %s" % (name[:3], name))
print("The total amount of figh... |
phalcon/readthedocs.org | readthedocs/core/djangome_urls.py | Python | mit | 821 | 0.014616 | from django.conf.urls.defaults import patterns, url
from urls import urlpatterns as main_patterns
ALL_VERSIONS_RE = '(?P<version>.+)'
urlpatterns = patterns(
'', # base view, flake8 complains if it is on the previous line.
url('^$',
'djangome.views.redirect_home',
{'version': 'latest'}),
... | \w\-\. | ]+)/stats$' % ALL_VERSIONS_RE,
'djangome.views.show_term',
name='show_term'),
)
urlpatterns += main_patterns
|
itJunky/web-tasker.py | db_repository/versions/026_migration.py | Python | gpl-2.0 | 1,017 | 0.001967 | from sqlalchemy import *
from migrate import *
from migrate.changeset import schema
pre_meta = MetaData()
post_meta = MetaData()
project = Table('project', post_meta,
Column('id', Integer, primary_key=True, nullable=False),
Column('name', String(length=255)),
)
project_association = Table('project_associatio... | eta.bind = migrate_engine
post_meta.tables['project'].create()
post_meta.tables['project_association'].create()
def downgrade(migrate_ | engine):
# Operations to reverse the above upgrade go here.
pre_meta.bind = migrate_engine
post_meta.bind = migrate_engine
post_meta.tables['project'].drop()
post_meta.tables['project_association'].drop()
|
uw-it-aca/myuw | myuw/dao/affiliation.py | Python | apache-2.0 | 7,365 | 0 | # Copyright 2022 UW-IT, University of Washington
# SPDX-License-Identifier: Apache-2.0
"""
This module provides affiliations of the current user
"""
import logging
import traceback
from myuw.dao import log_err
from myuw.dao.exceptions import IndeterminateCampusException
from myuw.dao.enrollment import (
get_main_... | return request.myuw_user_affiliations
not_major_affi = (not is_applicant(request) and
not is_employee(request) and
not is_clinician(request) and
n | ot is_instructor(request) and
not is_student(request))
(is_sea_stud, is_undergrad, is_hxt_viewer) = get_is_hxt_viewer(request)
data = {"class_level": None,
"latest_class_level": get_latest_class_level(request),
"grad": is_grad_student(request),
"undergra... |
mbayon/TFG-MachineLearning | venv/lib/python3.6/site-packages/numpy/distutils/msvc9compiler.py | Python | mit | 2,258 | 0.000443 | from __future__ import division, absolute_import, print_function
import os
from distutils.msvc9compiler import MSVCCompiler as _MSVCCompiler
from .system_info import platform_bits
def _merge(old, new):
"""Concatenate two environment paths avoiding rep | eats.
Here `old` is the environment string before the base class initialize
function is called and `new` is the string after the call. The new string |
will be a fixed string if it is not obtained from the current environment,
or the same as the old string if obtained from the same environment. The aim
here is not to append the new string if it is already contained in the old
string so as to limit the growth of the environment string.
Parameters
... |
nityansuman/Hack-Code | transistor_and_the_house.py | Python | mit | 354 | 0 | # | -*- coding: utf-8 -*-
"""
Created on Thu Nov 10 22:48:20 2016
@author: k nityan suman
"""
n, k = input().strip().split(' ')
n, k = [int(n), int(k)]
x = [int(x_temp) for x_temp in input().strip().split(' ')]
x.sort()
# print(x)
dist = x[-1] - x[0]
# print(dist
k = 2*k
# maximum number of transistor ... | (dist / k)
|
LethusTI/supportcenter | vendor/django/tests/regressiontests/templates/custom.py | Python | gpl-3.0 | 24,013 | 0.010453 | from __future__ import absolute_import
from django import template
from django.utils.unittest import TestCase
from .templatetags import custom
class CustomFilterTests(TestCase):
def test_filter(self):
t = template.Template("{% load custom %}{{ string|trim:5 }}")
self.assertEqual(
t.r... | must be present wh | en takes_context is True
self.assertRaisesRegexp(template.TemplateSyntaxError,
"'simple_tag_without_context_parameter' is decorated with takes_context=True so it must have a first argument of 'context'",
template.Template, '{% load custom %}{% simple_tag_without_context_parameter 123 %}'... |
ashutoshvt/psi4 | tests/pytests/test_np_views.py | Python | lgpl-3.0 | 2,472 | 0 | """
This is a simple script that verifies several ways of accessing numpy arrays
and ensures that their memory is properly cleaned.
"""
import pytest
from .addons import using
import numpy as np
import psi4
p | ytestmark = pytest.mark.quick
# If it's too small, something odd happens with the memory manager
mat_size = 10000
def snapshot_memory():
import memory_profiler as mp
return mp.memory_usage()[0] * 1048576
def check_leak(func, tol=1.e6):
start = snapshot_memory()
func()
diff = abs(start - snapsh... | lean up")
else:
print("Function %s: PASSED" % func.__name__)
return True
def build_mat():
mat = psi4.core.Matrix(mat_size, mat_size)
return mat
def build_view_mat():
mat = psi4.core.Matrix(mat_size, mat_size)
view = mat.np
return mat, view
def build_viewh_mat():
mat = p... |
jingriver/stocktracker | pytoolkit/regular_expression/pyqt3to4.py | Python | mit | 4,237 | 0.032334 | import re, sys, os
from subprocess import *
QT_IMPORT = {re.compile(r"\bfrom qt import\b"):"from PyQt4.Qt import",
re.compile(r"\bfrom qttable import\b"):"#from qttable import",
re.compile(r"\bfrom qtcanvas import\b"):"#from qtcanvas import"}
QT_CLS = {re.compile(r"\bQCanvasText\b"):"QGraphicsSimpleTextItem... |
while match_obj:
all_groups = match_obj.groups()
# Retrieve group(s) by index
group_1 = match_obj.group(1)
if group_1[0]=="(" and group_1[0]=="(":
repl=group_1[1:-1]
group_1 = "\(" + repl + "\)"
repl = repl.strip()
... | print "[%s]----[%s]" % (group_1, repl)
# Replace string
newstr = re.sub(group_1,repl, newstr)
match_obj = compile_obj.search(newstr)
return newstr
def replace_gen_class(s):
#s = ' from genchartitemarroweditor import genChartItemArrowEditor'
... |
jbzdak/data-base-checker | bdcheckerapp/autograding/zaj5/unit5/task3.py | Python | gpl-3.0 | 1,459 | 0.004838 | # -*- coding: utf-8 -*-
from bdchecker.api import NewDatabaseTaskChecker
from bdcheckerapp.autograding.zaj5.unit5.utils import Zaj5TaskChecker, UserList
class TaskChecker(NewDatabaseTaskChecker):
display_stdout = True
class TestSuite(Zaj5TaskChecker):
def test_has_procedure(self):
self.... | def test | _view_is_empty_at_the_beginning(self):
self.assertEqual(len(list(self.session.query(UserList.username))), 0,
msg="Widok \"LIST_USERS\" powinien być pusty zaraz po stworzeniu schematu")
def test_user_role_can_add_users(self):
user = self.get_session("user")
... |
guorendong/iridium-browser-ubuntu | tools/telemetry/telemetry/user_story/user_story_set_unittest.py | Python | bsd-3-clause | 2,649 | 0.004908 | # Copyright 2014 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 os
import unittest
from telemetry.story import shared_state
from telemetry import user_story
from telemetry.user_story import user_story_set
from tel... | serStorySetFoo(user_story_set.UserStorySet):
""" UserStorySetFoo is a user story created for testing purpose. """
pass
class UserStorySetTest(unittest.TestCase):
def testUserStoryTestName(self):
self.assertEquals('user_story_set_unittest', Us | erStorySetFoo.Name())
def testUserStoryTestDescription(self):
self.assertEquals(
' UserStorySetFoo is a user story created for testing purpose. ',
UserStorySetFoo.Description())
def testBaseDir(self):
uss = UserStorySetFoo()
base_dir = uss.base_dir
self.assertTrue(os.path.isdir(bas... |
gtesei/fast-furious | competitions/jigsaw-toxic-comment-classification-challenge/eda.py | Python | mit | 11,538 | 0.012307 | import sys
import numpy as np
import os
import pandas as pd
from sklearn import preprocessing
import re
from nltk.corpus import stopwords
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.feature_extraction.text import TfidfVectorizer
f... | ort TfidfTransformer
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics import roc_auc_score, log_loss
from numpy import linalg as LA
from sklearn import neighbors
from sklearn.neural_network import MLPClassifier
from bs4 import BeautifulSoup
#import xgboost as xgb
import datetime as dt
#... | lass StemmedTfidfVectorizer(TfidfVectorizer):
def build_analyzer(self):
analyzer = super(TfidfVectorizer, self).build_analyzer()
return lambda doc: english_stemmer.stemWords(analyzer(doc))
def text_to_wordlist( review, remove_stopwords=False ):
# Function to convert a document to a sequence of... |
klusta-team/kwiklib | kwiklib/dataio/loader.py | Python | bsd-3-clause | 17,513 | 0.00217 | """This module provides utility classes and functions to load spike sorting
data sets."""
# -----------------------------------------------------------------------------
# Imports
# -----------------------------------------------------------------------------
import os
import os.path
import re
from collections import ... | der):
x_reordered[x == o] = i
return x_reordered
def renumber_clusters(clusters, cluster_info):
clusters_unique = get_array(get_indices(cluster_info))
ncluster | s = len(clusters_unique)
assert np.array_equal(clusters_unique, np.unique(clusters))
clusters_array = get_array(clusters)
groups = get_array(cluster_info['group'])
colors = get_array(cluster_info['color'])
groups_unique = np.unique(groups)
# Reorder clusters according to the group.
clusters_... |
joelbitar/rfinder | analyzer/show.py | Python | lgpl-3.0 | 4,016 | 0.005976 | import re
import settings
from analyzer import Analyzer
class ShowAnalyzer(Analyzer):
patterns_and_values = [
(r'.*season[\s_\-\.](\d{1,2}).*', 60, ('season', None)),
(r'.*season(\d{1,2}).*', 60, ('season', None)),
(r'.*s(\d{1,2})[ex](\d{1,2}).*', 80, ('season', 'episode')), # ____s01e... | f.get_cleaned_name(" ".join(match.groups()))
if cleaned_name:
return cleaned_name
for path_part in self.file.get_path_parts():
cleaned_name = self.get_cleaned_name(path_part)
if cleaned_name:
return cleaned_name
def get_pretty_pa... | return str(season)
if season <= 9:
season_str = '0' + season_str
return "%s %s" % (
settings.SEASON_FOLDER_NAME,
season_str
)
def get_pretty_path_list(self):
return [
self.get_show_name(),
self.get_pretty_path_se... |
patrickm/chromium.src | content/test/gpu/run_gpu_test.py | Python | bsd-3-clause | 416 | 0.007212 | #!/usr/bin/env python
# | Copyright 2014 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 os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__),
os.pardir, os.pardir, os.pardir, 'tools', 'telemetry'))
from telemetry impor... | .Main())
|
alxgu/ansible | lib/ansible/plugins/callback/selective.py | Python | gpl-3.0 | 10,438 | 0.002491 | # (c) Fastly, inc 2016
# (c) 2017 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
DOCUMENTATION = """
callback: selective
callback_type: stdout
requirements:... | bold': '\033[1m\033[34m',
'changed': '\033[{0}m'.format(codeCodes[C.COLOR_CHANGED]),
'failed': '\033[{0}m | '.format(codeCodes[C.COLOR_ERROR]),
'endc': '\033[0m',
'skipped': '\033[{0}m'.format(codeCodes[C.COLOR_SKIP]),
}
def dict_diff(prv, nxt):
"""Return a dict of keys that differ with another config object."""
keys = set(prv.keys() + nxt.keys())
result = {}
for k in keys:
if prv.get(k) != ... |
google/flight-lab | controller/utils/display.py | Python | apache-2.0 | 3,167 | 0.003158 | # Copyright 2018 Flight Lab 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in w... | n assumes Chrome browser is available on given machine and
use it to display generated html content in kiosk mode so it appears as an app
and works on any platform.
"""
def __init__(self, chrome_path, *args, **kwargs):
"""Crea | tes Display instance.
Args:
chrome_path: path to chrome executable.
"""
super(Display, self).__init__(*args, **kwargs)
self._chrome_path = chrome_path
self._temp_path = tempfile.gettempdir()
self._index_file = tempfile.mktemp(suffix='.html')
self._chrome_app = app.Application(
... |
imageio/imageio | tests/test_pillow.py | Python | bsd-2-clause | 19,210 | 0.000729 | """ Tests for imageio's pillow plugin
"""
from pathlib import Path
from imageio.core.request import Request
import os
import io
import pytest
import numpy as np
from PIL import Image, ImageSequence
import imageio as iio
from imageio.core.v3_plugin_api import PluginV3
from imageio.plugins.pillow import PillowPlugin
f... |
im_path = test_images / im_in
with iio.imopen(im_path, "r", legacy_mode=True, plugin="GIF-PIL") as file:
iio_im = file.read(pilmode=mode, index=None)
pil_im = np.asarray(
[
np.array(frame.convert(mode))
for frame in ImageSequence.Iterator(Image.open(im_path))
... | ssion(test_images, tmp_path):
# Note: Note sure if we should test this or pillow
im = np.load(test_images / "chelsea.npy")
iio.v3.imwrite(tmp_path / "1.png", im, plugin="pillow", compress_level=0)
iio.v3.imwrite(tmp_path / "2.png", im, plugin="pillow", compress_level=9)
size_1 = os.stat(tmp_path ... |
deepmind/dm_control | dm_control/suite/reacher.py | Python | apache-2.0 | 4,233 | 0.004725 | # Copyright 2017 The dm_control 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 i... | (self.named.data.geom_xpos['target', :2] -
self.named.data.geom_xpos['finger', :2])
def finger_to_target_dist(self):
"""Returns the signed distance between the finger and target surface."""
return np.linalg.norm(self.finger_to_target())
class Reacher(base.Task):
"""A reacher `Task` to reach ... | eached the
target.
random: Optional, either a `numpy.random.RandomState` instance, an
integer seed for creating a new `RandomState`, or None to select a seed
automatically (default).
"""
self._target_size = target_size
super().__init__(random=random)
def initialize_episode... |
iotk/iochibity-java | site_scons/iotivityconfig/compiler/configuration.py | Python | epl-1.0 | 6,546 | 0.000458 | # ------------------------------------------------------------------------
# Copyright 2015 Intel Corporation
#
# 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/li... |
Arguments:
context -- the scons configure context
"""
if type(self) is Configuration:
raise TypeErro | r('abstract class cannot be instantiated')
self._context = context # scons configure context
self._env = context.env # scons environment
def check_c99_flags(self):
"""
Check if command line flag is required to enable C99
support.
Returns 1 if no flag is r... |
iw3hxn/LibrERP | dt_price_security/models/product.py | Python | agpl-3.0 | 3,879 | 0.005414 | # -*- 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... | type="float", readonly=True, store=False, string='Sale Price', digits_compute=dp.get_precision('Sale Price'),
help='Base price for computing the customer price. Sometimes called the catalog price.'),
'can_modify_prices': fields.boolean('Can modify prices',
h... |
'can_modify_prices': False,
}
def onchange_list_price(self, cr, uid, ids, list_price, uos_coeff, context=None):
return {'value': {'list_price_copy': list_price}}
def fields_get(self, cr, uid, allfields=None, context=None):
if not context:
context = {}
group_obj... |
nataddrho/DigiCue-USB | Python3/src/venv/Lib/site-packages/pip/_internal/distributions/sdist.py | Python | mit | 4,077 | 0 | import logging
from pip._internal.build_env import BuildEnvironment
from pip._internal.distributions.base import AbstractDistribution
from pip._internal.exceptions import InstallationError
from pip._internal.utils.subprocess import runner_with_spinner_message
from pip._internal.utils.typing import MYPY_CHECK_RUNNING
... | flicts(conflicting_with, conflicting_reqs):
# type: (str, Set[Tuple[str, str]]) -> None
format_string = (
"Some build dependencies for {requirement} "
"conflict with {conflicting_with}: {description}."
)
error_message = format_string.format... | icting_with=conflicting_with,
description=', '.join(
f'{installed} is incompatible with {wanted}'
for installed, wanted in sorted(conflicting)
)
)
raise InstallationError(error_message)
# Isolate in a BuildEnvironme... |
legendlee1314/ooni | hdfs2mongo_distributed.py | Python | mit | 3,868 | 0.002844 | # Author: legend
# Mail: legendlee1314@gmail.com
# File: hdfs2mongo_distributed.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
from bs4 import BeautifulSoup as bs
from bson.json_util import loads
from pymongo import MongoClient as mc
import pymongo
import pydoop.hdfs as hdfs
import zmq
import hashlib
import os
import ... | except pymongo.errors.DuplicateKeyError, e:
print e
elif collection.find_one({'md5': doc['md5']}) is None:
collection.insert_one(doc)
count += 1
time.sleep(1)
print host_name + ' write ' + str(count)
def client():
pri | nt 'Client...'
#docs = xml_from_hdfs('/datasets/corpus/enwiki-11g')
#write_to_mongo(docs, 'enwiki', True)
context = zmq.Context()
socket = context.socket(zmq.REQ)
socket.connect(client_tcp)
socket.send("connect:" + host_name)
message = socket.recv()
if message != 'connected':
ret... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.