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
emvecchi/mss
src/utils/crowdflower/retrieve_stats.py
Python
apache-2.0
925
0.025946
import sys,
csv, string def generate_R_input(report_path, output_path): confidence_values = [] report_file = open(report_path, 'r') first_line = True for
line in report_file: if first_line: first_line = False continue line = line.strip().split(',') if line[5] == 'Yes': confidence_values.append(line[6]) elif line[5] == 'No': confid = 1 - float(line[6]) confidence_values.append(confid) output_file = open(output_path, 'w') ...
nramanan/nellie-bot
libs/rest.py
Python
mit
833
0.016807
import requests,sys from con
fig_helper import get_proxies def get_pem(): if get_proxies()==None: return None pem_resp = requests.get('http://curl.haxx.se/ca/cacert.pem', proxies=get_proxies()) if pem_resp.status_code != 200: print "ERROR: Received bad response from api: %d" % pem_resp.status_code print "API Me...
f.write(pem_resp.text.encode('utf-8')) f.close() return '..\pemfile.pem' def get(url, proxies=None, auth=None,verify = True): resp = requests.get(url, proxies=get_proxies(), auth=auth, verify=verify) if resp.status_code != 200: print "ERROR: Received bad response from api: %d" % resp.status_cod...
cmlh/Maltego-Recorded_Future
src/RF_Maltego_Package_1.0/rf_csv_maltegoload.py
Python
apache-2.0
2,043
0.040137
#!/usr/bin/env python """Tr
ansform a CSV file exported from the Recorded Future UI into Maltego entities.""" import json import sys import csv impor
t Tkinter, tkFileDialog from MaltegoTransform import * mt = MaltegoTransform() # Use Tkinter to open up a file dialog. root = Tkinter.Tk() root.lift() root.withdraw() sys.stderr.write("Click the Python icon to select a file.") csvfilename = tkFileDialog.askopenfilename() data = csv.DictReader(open(csvfilename), deli...
kakaroto/amsn2
amsn2/protocol/events/addressbook.py
Python
gpl-2.0
2,240
0.000893
# -*- coding: utf-8 -*- # # amsn - a python client for the WLM Network # # Copyright (C) 2008 Dario Freddi <drf54321@gmail.com> # # 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...
def on_addressbook_group_renamed(self, group): self._contactlist_manager.on_group_renamed(group) def on_addressbook_group_contact_added(self, group, contact): self._contactlist_manager.on_group_contact_added(group, contact) def on_addressbook_group_contact_deleted(self, group, contact): ...
ontact)
peterbartha/ImmunoMod
res_mods/mods/packages/xvm_contacts/python/contacts.py
Python
mit
4,916
0.00773
""" XVM (c) www.modxvm.com 2013-2017 """ # PUBLIC def initialize(): return _contacts.initialize() def isAvailable(): return _contacts.is_available def getXvmContactData(uid): return _contacts.getXvmContactData(uid) def setXvmContactData(uid, value): return _contacts.setXvmContactData(uid, value)...
ached_data = None errstr = _SYSTEM_MESSAGE_TPL.replace('%VALUE%', '<b>{0}</b>\n\n{1}\n\n{2}'.format( l10n('Error loading comments'), str(ex), l10n('Comments disabled'))) SystemMessages.pushMessage(errstr, type=SystemMessages.SM_TYPE.Warning) ...
mment = None if not self.contacts_disabled and self.cached_data is None: self.initialize() if not self.contacts_disabled and self.cached_data is not None and 'players' in self.cached_data: data = self.cached_data['players'].get(str(uid), None) if data is not None: ...
timlinux/watchkeeper
django_project/event_mapper/tasks/notify_priority_users.py
Python
bsd-2-clause
3,622
0.003313
# coding=utf-8 """Select users to be notified.""" __author__ = 'Christian Christelis <christian@kartoza.com>' __project_name = 'watchkeeper' __date__ = '27/05/15' __copyright__ = 'kartoza.com' __doc__ = '' from celery import shared_task from notifications.tasks.send_email import send_email_message from notification...
yle=3D"background-color:white"><br></font><div><font size=3D"1" style=3D"background-color:white"><font face
=3D"Arial, Helvetica, sans-serif">iMMAP, 1300 Pennsylvania Avenue, N.W.,=C2=A0</font>Suite 470=C2=A0Washington DC 20004, <a href=3D"http://www.immap.org" target=3D"_blank">www.immap.org</a></font></div></div></div> """ return html_report @shared_task def notify_priority_users(event_id): event = Ev...
buzzdev/udpwatch
udpwatch.py
Python
gpl-2.0
6,405
0.012646
#!/usr/bin/env python import os, sys, fcntl, socket, subprocess, struct, signal, time, logging import datetime from glob import glob from ConfigParser import ConfigParser ####################################################################### # CONFIG ##################################################################...
l_name, PID, bytes, mcast_ip, mcast_port) #logger.normal("%s PID %s is running with %s:%s", channel_name, PID, mcast_ip, mcast_port) else: logger.error("%s %s:%s is not running.", channel_name, mcast_ip, mcast_port) def main(): # some dirty commandline argument
parser ;) if len(sys.argv) < 2: logger.error("No arguments - Please specify command line arguments") logger.info(sys.argv[0] + " <CHANNEL_NAME> <MCAST_IP> <MCAST_PORT> <UDP_DATA_TIMEOUT> <PROBE_TIME>") logger.info("Example: " + sys.argv[0] + " 239.255.14.5 3199 RCKTV 5 10") logger.info("Exiting...") ...
hangpark/kaistusc
apps/board/migrations/0007_auto_20180311_1704.py
Python
bsd-2-clause
1,864
0.003476
# -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2018-03-11 17:04 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('board', '0006_merge_20180311_1702'), ] operations ...
le_ko', models.CharField(max_length=128, null=True, verbose_name='제목')), ('title_en', models.CharField(max_length=128, null=True, verbose_name='제목')), ('image', models.ImageField(upload_to='banner', verbose_name='이미지')), ], options={
'verbose_name': '메인포스터', 'verbose_name_plural': '메인포스터(들)', }, bases=('board.basepost',), ), migrations.AlterModelOptions( name='boardbanner', options={'verbose_name': '게시판 배너', 'verbose_name_plural': '게시판 배너(들)'}, ), ...
google/skia-buildbot
scripts/run_on_swarming_bots/delete_tmp_dirs.py
Python
bsd-3-clause
562
0.003559
#!/usr/bin/env python # # Copyright 2021 Google Inc. # # Use of this source code is governed by a BSD-style license that can be # found in
the LICENSE file. """Delete files from the temporary directory on a Swarming bot.""" import os import sys if sys.platform == 'win32': os.system(r'forfiles /P c:\users\chrome~1\appdata\local\temp ' r'/M * /C "cmd /c if @isdir==FALSE del @file"') os.system(r'forfiles /P c:\users\chrome~1\appdata\local\...
sdir==TRUE rmdir /S /Q @file"') else: os.system(r'rm -rf /tmp/*')
kblin/plunger
plunger/plugins/md3.py
Python
gpl-2.0
7,657
0.004963
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2007 by Kai Blin # # Plunger is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; version 2 of the License. # # This program is distributed in the hop...
och, as the specfile # is kind of inaccurate. MD3_IDENT = "IDP3" MD3_VERSION = 15 MD3_MAX_FRAMES =
1024 MD3_MAX_TAGS = 16 MD3_MAX_SURFACES = 32 MD3_MAX_SHADERS = 256 MD3_MAX_VERTS = 4096 MD3_MAX_TRIANGLES = 8192 class Md3Frame: def __init__(self): self.min_bounds = [0,0,0] self.max_bounds = [0,0,0] self.local_origin = [0,0,0] self.radius = 0.0 self.name = "" self....
Crompulence/cpl-library
examples/multi_send_recv/minimal_CFD.py
Python
gpl-3.0
946
0.015856
from mpi4py import MPI from cplpy import CPL comm = MPI.C
OMM_WORLD CPL = CPL() CFD_COMM = CPL.init(CPL.CFD_REALM) cart_comm = CFD_COMM.Create_cart([1, 1, 1]) CPL.setup_cfd(cart_comm, xyzL=[1.0, 1.0, 1.0], xyz_orig=[0.0, 0.0, 0.0], ncxyz=[32, 32, 32]) recv_array, send_array = CPL.get_arrays(recv_size=4, send_siz
e=1) for time in range(5): recv_array, ierr = CPL.recv(recv_array) print("CFD", time, recv_array[0,0,0,0]) send_array[0,:,:,:] = 2.*time CPL.send(send_array) CPL.finalize() #Start again CFD_COMM = CPL.init(CPL.CFD_REALM) CPL.setup_cfd(cart_comm, xyzL=[1.0, 1.0, 1.0], xyz_orig=[0.0, 0....
GeotrekCE/Geotrek-admin
geotrek/common/utils/postgresql.py
Python
bsd-2-clause
6,597
0.001516
import logging import traceback from functools import wraps import os import re from django.conf import settings from django.db import connection from django.db.models import ManyToManyField logger = logging.getLogger(__name__) def debug_pg_notices(f): @wraps(f) def wrapped(*args, **kwargs): r = No...
values patter
n = re.compile(r'{{\s*([^\s]*)\s*}}') for m in pattern.finditer(sql): value = getattr(settings, m.group(1)) sql = sql.replace(m.group(0), str(value)) # Replace sharp braces with schemas pattern = re.compile(r'{#\s*([^\s]*)\s*#}') for m in ...
absalon-james/randomload
randomload/actions/glance/usage.py
Python
apache-2.0
2,200
0
"""This is just a playing around module. Please ignore it""" import json import six from randomload.log import logging from six.moves.urllib import parse logger = logging.getLogger('randomload.actions.glance.usage') class Controller(object): def __init__(self, http_client): self.http_client = http_clien...
logger.info("Total GB Hours: {0}".
format( tenant_usage.get('total_gb_hours') )) for usage in tenant_usage.get('image_usages', []): logger.info( "Name: {0} - Size: {1} GB - Status: {2}".format( usage['name'], bytes_to_GB(usage['size']), us...
TheWardoctor/Wardoctors-repo
script.stargate.guide/resources/playwith/playwithchannel.py
Python
apache-2.0
2,920
0.008562
import sys import xbmc,xbmcaddon,xbmcvfs import sqlite3 from subprocess import Popen import datetime,time # from vpnapi import VPNAPI channel = sys.argv[1] start = sys.argv[2] ADDON = xbmcaddon.Addon(id='script.stargate.guide') def adapt_datetime(ts): # http://docs.python.org/2/library/sqlite3.html#registering-a...
e) name = name.encode("cp1252") filename = xbmc.translatePath("special://temp/%s.ts" % name) #filename = "/storage/recordings/%s.ts" % name ffmpeg = r"c:\utils\ffmpeg.exe" ffmpeg = r"/usr/bin/ffmpeg" cmd = [ffmpeg, "-y", "-i", url, "-c", "copy", "-t", str(seconds), filename] p = P
open(cmd,shell=True) #p = Popen(cmd,shell=False)
GLolol/PyLink
protocols/hybrid.py
Python
mpl-2.0
12,742
0.003375
""" hybrid.py: IRCD-Hybrid protocol module for PyLink. """ import time from pylinkirc import conf from pylinkirc.classes import * from pylinkirc.log import log from pylinkirc.protocols.ts6 import TS6Protocol __all__ = ['HybridProtocol'] # Th
is protocol module inherits from the TS6 protocol. class HybridProtocol(TS6Protocol): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.casemapping = 'ascii' self.hook_map = {'EOB': 'ENDBURST', 'TBURST': 'TOPIC', 'SJOIN': 'JOIN'} self.protocol_caps -= {'sla...
in-hosts'} def post_connect(self): """Initializes a connection to a server.""" ts = self.start_ts f = self.send # https://github.com/grawity/irc-docs/blob/master/server/ts6.txt#L80 # Note: according to hybrid source code, +p is paranoia, noknock, # AND rfc1459-style...
avaitla/Haskell-to-C---Bridge
pygccxml-1.0.0/unittests/call_invocation_tester.py
Python
bsd-3-clause
4,057
0.027114
#! /usr/bin/python # Copyright 2004-2008 Roman Yakovenko. # Distributed under the Boost Software License, Version 1.0. (See # accompanying file LICENSE_1_0.txt or copy at # http://www.boost.org/LICENSE_1_0.txt) import unittest import autoconfig import pygccxml from pygccxml.utils import * from pygccxml.parse...
st_join_on_vector(self): self.failUnless( "vector( int, std::allocator(int) )" == declarations.call_invocation.join("vector", ( "int", "std::allocator(int)" ) ) ) def test_find_args(self): temp = 'x()()' found = declarations.call_invocation.find_args( temp ) ...
ations.call_invocation.find_args( temp, found[1]+1 ) self.failUnless( (3, 4) == found ) temp = 'x(int,int)(1,2)' found = declarations.call_invocation.find_args( temp ) self.failUnless( (1,9) == found ) found = declarations.call_invocation.find_args( temp, found[1]+1 ) ...
bbaronSVK/plugin.video.sosac.ph
resources/lib/sosac.py
Python
gpl-2.0
25,065
0.003152
# -*- coding: UTF-8 -*- # /* # * Copyright (C) 2015 Libor Zoubek + jondas # * # * # * 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, or (at your option) # * any lat...
movies_by_letter(url) if "tv" in url: return self.list_tv_shows_by_letter(url) if self.is_recently_added(url): util.debug("is recently added") if "movie" in url: return self.list_movie_recently_added(url) if "tv" in url: ...
rl): return self.list_search(url) if self.is_base_url(url): self.base_url = url if "movie" in url: return self.a_to_z(MOVIES_A_TO_Z_TYPE) if "tv" in url: return self.a_to_z(TV_SHOWS_A_TO_Z_TYPE) if self.particular_letter(ur...
dopplershift/Scattering
scripts/test_delta_units.py
Python
bsd-2-clause
1,224
0.011438
import matplotlib.pyplot as plt import numpy as np import scattering import scipy.constants as consts import quantities as pq def plot_csec
(scatterer, d, var, name): lam = scatterer.wavelength.rescale('cm') plt.plot(d, var, label='%.1f %s' % (lam, lam.dimensionality)) plt.xlabel('Diameter (%s)' % d.dimensionality) plt.ylabel(name) def plot_csecs(d, scatterers): for s in scatte
rers: plt.subplot(1,1,1) plot_csec(s, d, np.rad2deg(np.unwrap(-np.angle(-s.S_bkwd[0,0].conj() * s.S_bkwd[1,1]).squeeze())), 'delta') plt.gca().set_ylim(-4, 20) d = np.linspace(0.01, 0.7, 200).reshape(200, 1) * pq.cm sband = pq.c / (2.8 * pq.GHz) cband = pq.c / (5.4 * pq.GHz) xband =...
Vauxoo/stock-logistics-warehouse
stock_picking_procure_method/__manifest__.py
Python
agpl-3.0
587
0
# Copyright 2018 Tecnativa - David Vidal # License AGPL-3.0 or later (http://ww
w.gnu.org/licenses/agpl.html). { 'name': 'Stock Picking Procure Method', 'summary': 'Allows to force the procurement method from the picking', 'version': '12.0.1.0.0', 'category': 'Warehouse', 'author': 'Tecnativa,' 'Odoo Community Association (OCA)', 'website': 'https://github.com...
'views/stock_picking_views.xml', ], 'installable': True, }
jannon/django-allauth-api
src/allauth_api/socialaccount/rest_framework/authentication.py
Python
bsd-2-clause
1,984
0.00252
from django.utils.translation import ugettext as _ from rest_framework.authentication import BaseAuthentication from rest_framework.exceptions import AuthenticationFailed from allauth_api.account.rest_framework import authentication as account_auth from allauth_api.settings import allauth_api_settings from allauth_ap...
# access tokens. This login method, in its default configuration is only available if # oauth2_provider is in installed_apps # """ # # auth_class = SocialAuthentica
tion
Brazelton-Lab/system
rename.py
Python
gpl-2.0
5,082
0.007674
#! /usr/bin/env python """ This program is for renaming files (through symbolic links) using a file conversion table. The columns should be ordered as so: new directory, new id, old directory, old file name. Columns can be separated using any standard ASCII character. If files are paired-end and follow the standard co...
)) reverses = glob.glob('{}/{}*R2_*'.format(old_dir, old_name[:-1])) if len(forwards) != len(reverses): print(textwrap.fill("Warning: missing pair in {}. The use " "of '*' should only be used for paired-end reads in " "s...
derr) continue if len(forwards) > 1: add_det = True else: add_det = False for strand in (forwards, reverses): for filename in strand: if add_det: ...
xu6148152/Binea_Python_Project
oop/student/student.py
Python
mit
246
0.012195
__author__ = 'xubinggui' class Student(object): def __init__(self, name, s
core): self.name = name self.score = score def print_score(self): print(self.score)
bart = Student('Bart Simpson', 59) bart.print_score()
alirizakeles/tendenci
tendenci/apps/news/admin.py
Python
gpl-3.0
1,737
0.01209
from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from tendenci.apps.perms.admin import TendenciBaseModelAdmin from tendenci.apps.news.models import News from tendenci.apps.news.forms import NewsForm class NewsAdmin(TendenciBaseModelAdmin): list_display = ['headline', 'updat...
, { 'fields': ('headline', 'slug', 'summary', 'body', 'group', 'tags', 'source', 'website', 'release_dt', 'timezone', ) }), (_('Cont...
'last_name', 'google_profile', 'phone', 'fax', 'email', ), 'classes': ('contact',), }), (...
sh4d0/openvix
manage.py
Python
gpl-3.0
3,933
0.003051
import argparse import os import subprocess import sys SCRIPT_DIR = os.path.dirname(__file__) class ExecException(Exception): pass class Exec(object): @staticmethod def run(cmd, workingdir=None): p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=workingdir) ...
alse, help='Run tests') parser.add_argument('--arch', default=None, choices=['x86', 'x64'], help='Arch of Visual Studio if not run from VS command prompt') parser.add_argument('--version', default=None, choices=[7, 8, 9, 10, 11, 12, 14], type=i
nt, help='Version of Visual Studio of not run from VS command prompt') args = parser.parse_args(argv) Exec.cmake_version() # Make sure we have located cmake if args.arch is None or args.version is None: vs_info = Exec.vs_info() if args.arch is None: ar...
lmazuel/azure-sdk-for-python
azure-mgmt-compute/azure/mgmt/compute/v2016_03_30/models/storage_profile_py3.py
Python
mit
2,421
0.000413
# 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 ...
file(Model): """Specifies the storage settings for the virtual machine disks. :param image_reference: Specifies information about the image to use. You can specify information about platform images, marketplace images, or virtual machine images. This element is required when you want
to use a platform image, marketplace image, or virtual machine image, but is not used in other creation operations. :type image_reference: ~azure.mgmt.compute.v2016_03_30.models.ImageReference :param os_disk: Specifies information about the operating system disk used by the virtual machine....
junhuac/MQUIC
src/mojo/public/tools/manifest/manifest_collator.py
Python
mit
1,675
0.017313
#!/usr/bin/env python # Copyright 2016 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ A collator for Mojo Application Manifests """ import argparse import json import shutil import sys import urlparse def ParseJSONF...
parser.parse_known_args() parent = ParseJSONFile(args.parent) if parent == None: return 1 app_path = parent['name'].split(':')[1] if app_path.startswith('//'): raise Val
ueError("Application name path component '%s' must not start " \ "with //" % app_path) if args.application_name != app_path: raise ValueError("Application name '%s' specified in build file does not " \ "match application name '%s' specified in manifest." % ...
kikov79/scalr
app/python/tests/scalrpytests/load_statistics_cleaner/steps.py
Python
apache-2.0
3,146
0.005086
from gevent import monkey monkey.patch_all(subprocess=True) import os import sys cwd = os.path.dirname(os.path.abspath(__file__)
) scalrpy_dir = os.path.normpath(os.path.join(cwd, '../../..')) sys.path.insert(0, scalrpy_dir) scalrpytests_dir = os.path.join(cwd, '../..') sys.path.insert(0, scalrpytests_dir) import time from gev
ent import pywsgi from scalrpy.util import rpc from scalrpy.util import helper from scalrpy.load_statistics_cleaner import LoadStatisticsCleaner from scalrpytests.steplib import lib from scalrpytests.steplib.steps import * from lettuce import step, before, after class LoadStatisticsCleanerScript(lib.Script): ...
nextgis-extra/tests
lib_gdal/gdrivers/paux.py
Python
gpl-2.0
2,669
0.010116
#!/usr/bin/env python ############################################################################### # $Id: paux.py 32163 2015-12-13 17:44:50Z goatbar $ # # Project: GDAL/OGR Test Suite # Purpose: Test read/write functionality for PAux driver. # Author: Frank Warmerdam <warmerdam@pobox.com> # #####################...
####### # Test copying. def paux_2(): tst = gdaltest.GDALTest( 'PAux', 'byte.tif', 1, 4672) return tst.testCreateCopy( check_gt = 1 ) ############################################################################### # Test /vsimem based. def paux_3(): tst = gdaltes
t.GDALTest( 'PAux', 'byte.tif', 1, 4672 ) return tst.testCreateCopy( vsimem = 1 ) ############################################################################### # Cleanup. def paux_cleanup(): gdaltest.clean_tmp() return 'success' gdaltest_list = [ paux_1, paux_2, paux_3, paux_cleanup ] ...
anatolikalysch/VMAttack
ui/__init__.py
Python
mit
31
0
__aut
hor__ = 'Anatoli Kalys
ch'
mrquim/mrquimrepo
script.skin.helper.service/resources/lib/main_module.py
Python
gpl-2.0
31,819
0.002326
#!/usr/bin/python # -*- coding: utf-8 -*- ''' script.skin.helper.service Helper service and scripts for Kodi skins mainmodule.py All script methods provided by the addon ''' import xbmc import xbmcvfs import xbmcgui import xbmcaddon from skinsettings import SkinSettings from simplecache import SimpleC...
to choose from''' cur_view_select_id = None label = "" all_views = [] if display_none: listitem = xbmcgui.ListItem(label="None") listitem.setProperty("id", "None") all_views.append(listite
m) # read the special skin views file views_file = xbmc.translatePath('special://skin/extras/views.xml').decode("utf-8") if xbmcvfs.exists(views_file): doc = parse(views_file) listing = doc.documentElement.getElementsByTagName('view') itemcount = 0 ...
dstegelman/rocket-python
rocketchat/calls/base.py
Python
mit
3,656
0
import logging import pprint import requests logger = logging.getLogger(__name__) class RocketChatBase(object): settings = None endpoint = None headers = {} method = 'get' auth_token = None auth_user_id = None files = None def __init__(self, settings=None, *args, **kwargs): ...
('token') and self.settings.get('user_id'): self.auth_token = self.settings.get('token') self.auth_user_id = self.settings.get('user_id') return url = '{do
main}/api/v1/login'.format( domain=self.settings['domain'] ) response = requests.post(url, data={'user': self.settings['username'], 'password': self.settings['password']}) try: self.auth_token = resp...
arantebillywilson/python-snippets
py3/abw-things/progress.py
Python
mit
399
0.002506
#!/usr/bin/python3 # # progress.py # # Author: Billy Wilson Arante # Created: 2016/02/05 PHT # Modified:
2016/08/19 PHT # def progress(): """Progress icon The Python 3 version of loading_icon.py. """ while True: for i in ["/", "-", "|", "\\", "|"]: print("%s\r" % i, end=
"") def main(): """Main""" progress() if __name__ == "__main__": main()
andialbrecht/sqlparse
sqlparse/cli.py
Python
bsd-3-clause
5,712
0
#!/usr/bin/env python # # Copyright (C) 2009-2020 the sqlparse authors and contributors # <see AUTHORS file> # # This module is part of python-sqlparse and is released under # the BSD License: https://opensource.org/licenses/BSD-3-Clause """Module that contains the command line app. Why does this file exist, and why ...
d_argument( '--indent_width', dest='indent_width', default=2, type=int, help='indentation width (defaults to 2 space
s)') group.add_argument( '--indent_after_first', dest='indent_after_first', action='store_true', default=False, help='indent after first line of statement (e.g. SELECT)') group.add_argument( '--indent_columns', dest='indent_columns', action='stor...
fiquett/SupportLogger
logs/models.py
Python
gpl-2.0
623
0.020867
from
django.db import models class Log(models.Model): entry = models.CharField(max_length=255) comments = models.TextField() device_name = models.CharField(max_length=200) classification = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __unicode__(self): return self.device_n...
ecently.admin_order_field = 'pub_date' was_published_recently.boolean = True was_published_recently.short_description = 'Published recently?'
fernandomr/odoo-brazil-banking
l10n_br_account_banking_payment_cnab/wizard/payment_order_create.py
Python
gpl-3.0
5,746
0.000696
# -*- coding: utf-8 -*- # ########################################################################### # # Author: Luis Felipe Mileo # Fernando Marcato Rodrigues # Daniel Sadamo Hirayama # Copyright 2015 KMEE - www.kmee.com.br # # This program is free software: you can redistribute it and/...
f.duedate)) elif payment_order.mode.type.code == '400': if payment_order.mode.payment_order_type == 'cobranca': domain += [ ('debit', '>',
0), ('account_id.type', '=', 'receivable'), '&', ('payment_mode_id', '=', payment_order.mode.id), '&', ('invoice.state', '=', 'open'), ('invoice.fiscal_category_id.property_journal.revenue_expense', '...
KelSolaar/sIBL_GUI
sibl_gui/components/addons/online_updater/remote_updater.py
Python
gpl-3.0
31,337
0.003893
#!/usr/bin/env python # -*- coding: utf-8 -*- """ **remote_updater.py** **Platform:** Windows, Linux, Mac Os X. **Description:** Defines the :class:`RemoteUpdater` class and others online update related objects. **Others:** """ from __future__ import unicode_literals import os import platform from PyQt4....
class RemoteUpdater(foundations.ui.common.QWidget_factory(ui_file=UI_FILE)): """ | Defines the Application remote updater. | The remote updater is initialized with a list of available online releases ( List of :class:`ReleaseObject` class instances ). """ def __init__(self, parent, relea...
he class. :param parent: Object parent. :type parent: QObject :param releases: Releases. :type releases: dict :param \*args: Arguments. :type \*args: \* :param \*\*kwargs: Keywords arguments. :type \*\*kwargs: \*\* """ LOGGER.debug("> Ini...
b29308188/Deep-Generative-Model-for-Text-Data
src/basic_sentiment.py
Python
mit
8,591
0.014317
import sys import re import numpy as np from keras.models import Sequential from keras.layers import Dense, TimeDistributed, Dropout, Activation, LSTM, BatchNormalization from keras.optimizers import RMSprop, Adam from keras.layers.advanced_activations import LeakyReLU from keras.utils import np_utils #from seq2seq.mod...
D" L = [
] for index in range(0, len(X), batch_size): batch = X[index:index+batch_size] noise = self.generate_noise(batch.shape) gen_batch = self.G.predict(noise) Y = [1]*len(batch) + [0]*len(batch) Y = np_utils.to_categorical(Y, nb_classes = 2) combined_b...
rigdenlab/SIMBAD
simbad/util/tests/test_util.py
Python
bsd-3-clause
2,611
0.000766
"""Test functions for simbad.util.pdb_util""" __author__ = "Adam Simpkin" __date__ = "19 Jan 2018" import os import tempfile import unittest import simbad.util class Test(unittest.TestCase): """Unit test""" def test_result_by_score_from_csv_1(self): """Test case for simbad.util.result_by_score_from...
2z19,38.05,79.03,64.98,11.8,57.7,15.9,12.8,1.0,7.
1,5.9,5.0 1jj1,28.99,82.92,245.93,12.5,57.3,15.6,11.3,1.0,7.0,5.9,5.0 4j7v,28.54,86.74,246.59,12.0,57.4,14.2,10.2,1.0,7.0,5.7,5.0 2pc2,28.71,76.6,257.7,10.8,57.7,13.4,8.0,1.0,6.7,5.3,5.0""" ) csv_temp_file.close() data = simbad.util.result_by_score_from_csv(csv_temp_file.name, "CC_F_Z_score") ...
idlesign/uwsgiconf
uwsgiconf/options/subscriptions_algos.py
Python
bsd-3-clause
863
0
from ..base import ParametrizedValue class BalancingAlgorithm(ParametrizedValue): name_se
parator = '' class BalancingAlgorithmWithBackup(BalancingAlgorithm): def __init__(self, backup_level=None): self.backup_level = backup_level super().__init__() class WeightedRoundRobin(BalancingAlgorithmWithBackup): """Weighted round robin algorithm with backup support. The default algo...
thm. """ name = 'wrr' class LeastReferenceCount(BalancingAlgorithmWithBackup): """Least reference count algorithm with backup support.""" name = 'lrc' class WeightedLeastReferenceCount(BalancingAlgorithmWithBackup): """Weighted least reference count algorithm with backup support.""" name ...
xylsxyls/xueyelingshuang
src/storageMysql/scripts/rebuild_storage.py
Python
mit
13,961
0.008547
#!python3 # -*- coding:utf-8 -*- import os import sys import time import ctypes import shutil import subprocess IsPy3 = sys.version_info[0] >= 3 if IsPy3: import winreg else: import codecs import _winreg as winreg BuildType = 'Release' IsRebuild = True Build = 'Rebuild' Update = False C...
except FileNotFoundError as e: Logger.WriteLine('can not find IncrediBuild', ConsoleColor.Red) def UpdateCode(): # put git to path first if not shutil.which('git.exe'): Logger.Log('找不到git.exe. 请确认安装git时将git\bin目录路径加入到环境变量path中!!!\n, 跳过更新代码!!!', ConsoleColor.Yellow) return f...
os.getcwd() for dir in UpdateDir: os.chdir(dir) ret = os.system('git pull') os.chdir(oldDir) if ret != 0: Logger.Log('update {0} failed'.format(dir), ConsoleColor.Yellow) return false return True def BuildProject(cmd): for i in range(6): ...
hippke/Pulsar-HabCat
matchATNF-full.py
Python
mit
3,210
0.002181
"""Compare Pulsar and HabCat coordinates""" import csv import astropy.units as u from astropy.coordinates import SkyCoord, Angle from astropy import coordinates as coord def flipra(coordinate): """Flips RA coordinates by 180 degrees""" coordinate = coordinate + 180 if coordinate > 360: ...
for currenthabcat in range(len(habcat_id)): # HabCat loop # Correct calculat
ion is very slow, thus only try the best candidates: if (abs(habcat_ra[currenthabcat] - flipra(pulsar_ra[currentpulsar])) < 5. and abs(habcat_de[currenthabcat] - flipde(pulsar_de[currentpulsar])) < 5.): habcat_coordinate = SkyCoord( habcat_ra[cur...
vuolter/pyload
src/pyload/plugins/downloaders/UpleaCom.py
Python
agpl-3.0
2,715
0.001842
# -*- coding: utf-8 -*- import re import urllib.parse from ..base.simple_downloader import SimpleDownloader def decode_cloudflare_email(value): email = "" key = int(value[:2], 16) for i in range(2, len(value), 2): email += chr(int(value[i : i + 2], 16) ^ key) return email class UpleaCom(...
ink" LINK_PATTERN = r'"(https?://\w+\.uplea\.com/anonym/.*?)"' PREMIUM_ONLY_PATTERN = ( r"You need to have a Premium subscription to download this file" ) WAIT_PATTERN = r"timeText: ?(\d+)," STEP_PATTERN = r'<a href="(/step/.+)">' NAME_REPLACEMENTS = [ ( r'(<a clas...
_cf_email__" .+? data-cfemail="(\w+?)".+)', lambda x: decode_cloudflare_email(x.group(2)), ) ] def setup(self): self.multi_dl = False self.chunk_limit = 1 self.resume_download = True def handle_free(self, pyfile): m = re.search(self.STEP_PATTERN, self.da...
hackebrot/pytest
src/_pytest/doctest.py
Python
mit
18,770
0.001332
""" discover and run doctests in modules and test files.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import inspect import platform import sys import traceback from contextlib import contextmanager import pytest from _pytest._code.code import Excepti...
out.append(failure) else: raise failure return PytestDoctestRunner def _get_runner(checker=None, verbose=None, optionflags=0, continue_on_failure=True): # We need this in order to do a lazy import on doctest global RUNNER_CLASS if RUNNER_CLASS is None: RUNNER_C...
optionflags=optionflags, continue_on_failure=continue_on_failure, ) class DoctestItem(pytest.Item): def __init__(self, name, parent, runner=None, dtest=None): super(DoctestItem, self).__init__(name, parent) self.runner = runner self.dtest = dtest self.obj = None ...
Octoberr/swmcdh
Schedul/unceshi.py
Python
apache-2.0
1,831
0.013318
# coding=utf-8 import numpy as np from numpy import random # a=np.array([[2,3,4,1,2],[1,3,4,5,4],[4,2,3,10,2],[3,5,6,7,9],[10,3,4,2,9]]) # # for i in xrange(5): # # a[i,i]=1000 # #b=a.argmin(axis=1) # print a # a=random.randint(1,100,size=(8,8)) MAX = 1000 MIN = 0 CARSEATS = 6 distMat = np.array([[0, 1, 15, 1...
shape[0])) print airportDist #存储上车的人 idxMat = np.zeros([airportDist.shape[0]], dtype=int) #第一个上车的人 initialIdx = np.argmax(airportDist) idxMat[0] = initialIdx #第一个人已经上车 airportDist[initialIdx] = MIN
print initialIdx #排除点到点的距离 for k in xrange(distMat.shape[0]): distMat[k][k] = MAX # print("airport distance matrix: ") # print airportDist # # print("distance matrix:") # print distMat for i in range(1,distMat.shape[0]): if i%CARSEATS == 0: print("new cars") #第六个上车的人 d...
nirvn/QGIS
python/plugins/processing/algs/qgis/FixedDistanceBuffer.py
Python
gpl-2.0
5,246
0.002859
# -*- coding: utf-8 -*- """ *************************************************************************** FixedDistanceBuffer.py --------------------- Date : August 2012 Copyright : (C) 2012 by Victor Olaya Email : volayaf at gmail dot com *******************...
hm from . import Buffer as buff pluginPath = os.path.split(os.path.split(os.path.dir
name(__file__))[0])[0] class FixedDistanceBuffer(QgisAlgorithm): INPUT = 'INPUT' OUTPUT = 'OUTPUT' FIELD = 'FIELD' DISTANCE = 'DISTANCE' SEGMENTS = 'SEGMENTS' DISSOLVE = 'DISSOLVE' END_CAP_STYLE = 'END_CAP_STYLE' JOIN_STYLE = 'JOIN_STYLE' MITER_LIMIT = 'MITER_LIMIT' def icon(...
Jumpscale/jumpscale6_core
apps/agentcontroller/jumpscripts/core/cleanup/cleanupredisac.py
Python
bsd-2-clause
1,530
0.004575
from JumpScale import j descr = """ remove old redis cache from system """ organization = "jumpscale" author = "deboeckj@codescalers.com" license = "bsd" version = "1.0" category = "redis.cleanu
p" period = 300 # always in sec timeout = period * 0.2 # max runtime = 20% of period order = 1 enable = True async = True log = False roles = ['master'] def action(): import time EXTRATIME = 120 now = time.time() try: import ujson as json except: import json import JumpScale....
d.agentcontroller acl = j.clients.agentcontroller.get() rcl = j.clients.redis.getRedisClient('127.0.0.1', 9999) for jobkey in rcl.keys('jobs:*'): if jobkey == 'jobs:last': continue jobs = rcl.hgetall(jobkey) for jobguid, jobstring in jobs.iteritems(): job = j...
leapp-to/snactor
examples/scripts/checktarget.py
Python
apache-2.0
400
0
""" Run target checks using snactor """ from generic_runner import run, pprint, get_actor def check_target(): """ Run multiple checks at target
machine """ targetinfo = {} get_actor('check_target_group').execute(targetinfo) get_actor('check_target').execute(targetinfo) pprint(targetinfo['targetinfo']) if __name__ == '__main__':
run(check_target, tags=['check_target'])
pombredanne/anitya
anitya/tests/base.py
Python
gpl-2.0
6,973
0.001291
# -*- coding: utf-8 -*- # # Copyright © 2014-2017 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions # of the GNU General Public License v.2, or (at your option) any later # version. This program is distributed...
package_name='geany', ) session.add(package) package = model.Packages( project_id=2, distro='Fed
ora', package_name='subsurface', ) session.add(package) session.commit() def create_flagged_project(session): """ Create and flag a project. Returns the ProjectFlag. """ project = anitya.lib.create_project( session, name='geany', homepage='http://www.geany.org/', ...
cshtarkov/autobump
autobump/handlers/python.py
Python
gpl-3.0
8,380
0.000955
# Copyright 2016-2017 Christian Shtarkov # # This file is part of Autobump. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later ver...
API. continue if isinstance(node, ast.ClassD
ef): units[node.name] = _container_to_unit(node.name, node) elif isinstance(node, ast.FunctionDef): functions[node.name] = Function(node.name, _dynamic, _get_signature(node)) elif isinstance(node, ast.Assign): # TODO: Handle other forms of assignment. for ...
The-Penultimate-Defenestrator/memefarm
memefarm/pilutil.py
Python
mit
2,924
0
""" Helpers for making some things in PIL easier """ from PIL import ImageDraw, ImageFont, ImageStat from math import ceil def dra
wTextWithBorder(draw, text, coords, fontname="Impact", fontsize=80, color="#fff", strokecolor="#000"): """ Draw text with a border. Although PIL doesn't support this, it can be faked by drawing the text in the border color, with offsets, and then drawing the tex...
strokewidth = ceil(3 * fontsize / 80.0) # Use ceiling to prevent 0 font = ImageFont.truetype(fontname, fontsize) x, y = coords # Draw background for c in ((x - strokewidth, y - strokewidth), (x + strokewidth, y - strokewidth), (x - strokewidth, y + strokewidth), ...
Thortoise/Super-Snake
Blender/animation_nodes-master/nodes/spline/evaluate_spline.py
Python
gpl-3.0
1,278
0.007042
import bpy from bpy.props import * from mathutils import Vect
or from ... base_types.node import AnimationNode from . spline_evaluation_base import SplineEvaluationBase class EvaluateSplineNode(bpy.types.Node, AnimationNode, SplineEvaluationBase): bl_idname = "an_EvaluateSplineNode" bl_label = "Evaluate Spline"
def create(self): self.newInput("Spline", "Spline", "spline", defaultDrawType = "PROPERTY_ONLY") self.newInput("Float", "Parameter", "parameter", value = 0.0) self.newOutput("Vector", "Location", "location") self.newOutput("Vector", "Tangent", "tangent") def draw(self, layout)...
dywisor/kernelconfig
kernelconfig/pm/portagevdb/overlay.py
Python
gpl-2.0
14,668
0
# This file is part of kernelconfig. # -*- coding: utf-8 -*- import abc import errno import os import shutil
from ...abc import loggable
from ...util import fs from ...util import fspath from . import _eclass __all__ = ["TemporaryOverlay", "TemporaryOverlayUnion"] class AbstractTemporaryOverlayBase(loggable.AbstractLoggable): """ @ivar root: @type root: C{str} """ # not inheriting AbstractSourceInformed, # overlay objects...
ultimate-pa/benchexec
contrib/plots/quantile-generator.py
Python
apache-2.0
5,188
0.001542
#!/usr/bin/env python3 # This file is part of BenchExec, a framework for reliable benchmarking: # https://github.com/sosy-lab/benchexec # # SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org> # # SPDX-License-Identifier: Apache-2.0 import argparse import itertools import sys from benchexec import...
t.CATEGORY_MISSING: sys.exit( f"Property missing for task {run_result.task_id}, " f"cannot produce score-based quantile data." ) elif run_result.category == result.CATEGORY_CORRECT: results.append(run_result) ...
esult.category in { result.CATEGORY_ERROR, result.CATEGORY_UNKNOWN, } else: start_index = 0 index_increment = lambda run_result: 1 # noqa: E731 if options.correct_only: results = [ run_result ...
nkoech/csacompendium
csacompendium/csa_practice/models.py
Python
mit
9,828
0.001933
# -*- coding: utf-8 -*- from __future__ import unicode_literals from csacompendium.utils.abstractmodels import ( AuthUserDetail, CreateUpdateTime, ) from csacompendium.utils.createslug import create_slug from csacompendium.utils.modelmanagers import ( model_instance_filter, model_foreign_key_qs, mo...
eme model. Creates CSA theme entity. """ slug = models.SlugField(max_length=12
0, unique=True, blank=True) csa_theme = models.CharField(max_length=80, unique=True, verbose_name='CSA theme') def __unicode__(self): return self.csa_theme def __str__(self): return self.csa_theme def get_api_url(self): """ Get CSA theme URL as a reverse from model ...
bblacey/FreeCAD-MacOS-CI
src/Mod/Ship/WeightInstance.py
Python
lgpl-2.1
12,814
0.001795
#*************************************************************************** #*
* #* Copyright (c) 2011, 2016 * #* Jose Luis Cercos Pita <jlcercos@gmail.com> * #* * #* This program is free software; you can redistribute it...
rms of the GNU Lesser General Public License (LGPL) * #* as published by the Free Software Foundation; either version 2 of * #* the License, or (at your option) any later version. * #* for detail see the LICENCE text file. * #* ...
cjbauer/brainphrase
adjectives.py
Python
agpl-3.0
20,322
0.000295
# Collection of adjectives # September 19 2014 # Christian Bauer d = { } drev = { } num = 0 def ins(x): global num,d,drev d[num] = x drev[x] = num num = num + 1 ins('abandoned') ins('able') ins('absolute') ins('adorable') ins('adventurous') ins('academic') ins('acceptable') ins('acclaimed') ins('acco...
y') ins('creamy') ins('creative') ins('creepy') ins('criminal') ins('crisp') ins('critical') ins('crooked') ins('crowded') ins('cruel') ins('crushing') ins('cuddly') ins('cultivated') ins('cultured') ins('cumbersome') ins('curly') ins('curvy') ins('cute') ins('cylindrical') ins('d
amaged') ins('damp') ins('dangerous') ins('dapper') ins('daring') ins('darling') ins('dark') ins('dazzling') ins('dead') ins('deadly') ins('deafening') ins('dear') ins('dearest') ins('decent') ins('decimal') ins('decisive') ins('deep') ins('defenseless') ins('defensive') ins('defiant') ins('deficient') ins('definite') ...
nitzmahone/ansible
test/lib/ansible_test/_internal/completion.py
Python
gpl-3.0
8,217
0.003529
"""Loading, parsing and storing of completion configurations.""" from __future__ import annotations import abc import dataclasses import os import typing as t from .constants import ( CONTROLLER_PYTHON_VERSIONS, SUPPORTED_PYTHON_VERSIONS, ) from .util import ( ANSIBLE_TEST_DATA_ROOT, read_lines_witho...
ntry is only used for defaults, otherwise False.""" return False @dataclasses.dataclass(frozen=True) class DockerCompletionConfig(PythonCo
mpletionConfig): """Configuration for Docker containers.""" image: str = '' seccomp: str = 'default' placeholder: bool = False @property def is_default(self): """True if the completion entry is only used for defaults, otherwise False.""" return False def __post_init__(self)...
chrisspen/homebot
src/test/max_column/test_max_column.py
Python
mit
690
0.008696
#!../../../.env/bin/python import os import numpy as np import time a = np.array([ [1,0,3], [0,2,1], [0.1,0,0], ]) print a row = 1 col = 2 print a[row][col] assert a[row][col] == 1 expected_max_rows = [0, 1, 0] expected_max_values = [1, 2, 3] print 'expected_max_rows:', expected_max_rows print 'expected_...
_values:', expected_max_values t0 = time.time() actual_max_rows = list(np.argmax(a, axis=0)) td = time.time() - t0 actual_max_values = l
ist(np.amax(a, axis=0)) print 'td:', round(td, 4) print 'actual_max_rows:', actual_max_rows print 'actual_max_values:', actual_max_values assert actual_max_rows == expected_max_rows assert actual_max_values == expected_max_values
liquidkarma/pyneat
pyNEAT/Mutator.py
Python
gpl-2.0
790
0.005063
""" pyNEAT Copyright (C) 2007-2008 Brian Greer 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 it will be useful, but WITHOUT ANY WARRANTY; wi
thout even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, ...
kosystem/PythonGlutWrapper
GlutViewController.py
Python
mit
2,389
0.000837
from OpenGL.GL import * from OpenGL.GLUT import * from OpenGL.GLU import * from OpenGL.GLUT.freeglut import * import GlutWrapper import math ESCAPE = b'\033' class GlutViewController(GlutWrapper.GlutWrapper): """docstring for GlutViewController""" def __init__(self): super(GlutViewController, self)._...
self.camera.tilt += float(movedY)/100.0 if self.camera.tilt > math.pi/2.0: self.camera.tilt = math.pi/2.0-0.01 if self.camera.tilt < -math.pi/2.0: self.camera.tilt = -(math.pi/2.0-0.01) self.mouseS
tate.x = x self.mouseState.y = y def keyboard(self, key, x, y): print("KeyboardPress: %s" % key) if key == ESCAPE: sys.exit() elif key == b'p': self.camera.distance *= 0.875 elif key == b'n': self.camera.distance *= 1.125 def setColor...
rdkls/django-audit-mongodb
tests/test_models.py
Python
bsd-3-clause
25,093
0.009923
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (c) 2010, 2degrees Limited <egoddard@tech.2degreesnetwork.com>. # All Rights Reserved. # # This file is part of djangoaudit <https://launchpad.net/django-audit/>, # which is subject to the provisions of ...
"A change should result in a database object being " "created") saved_record = self.fetch_record_by_id(result) eq_(saved_record['foo'], 'bar', "The saved record should contain a sing
le difference key") def test_model_data_write_out(self): """Check the correct data is written out for the model""" result = _audit_model(self.profile, dict(foo=None), dict(foo='bar')) assert_not_equal(result, None, "A change should result i...
Parallel-in-Time/pySDC
pySDC/implementations/sweeper_classes/verlet.py
Python
bsd-2-clause
7,323
0.002048
import numpy as np from pySDC.core.Sweeper import sweeper from pySDC.implementations.collocation_classes.gauss_lobatto import CollGaussLobatto class verlet(sweeper): """ Custom sweeper class, implements Sweeper.py Second-order sweeper using velocity-Verlet as base integrator Attributes: QQ:...
right-hand side Returns: list of dtype_u: containing the integral as values """ # get current level and problem description L = self.level P = L.prob # create new instance of dtype_u, initialize values with 0 p = []
for m in range(1, self.coll.num_nodes + 1): p.append(P.dtype_u(P.init, val=0.0)) # integrate RHS over all collocation nodes, RHS is here only f(x)! for j in range(1, self.coll.num_nodes + 1): p[-1].pos += L.dt * (L.dt * self.QQ[m, j] * L.f[j]) + L.dt * self.c...
tleonhardt/machine_learning
optimize_me.py
Python
apache-2.0
437
0.011442
#!/usr/bin/env python import numpy as np import scipy.optimize as spo def integer_optimize(): x = np.arange(1,101) f = (x % 6)**2 % 7 - np.sin(x) return x[np.argmax(f)] def f(x): return -x**4 + 1000 * x**3 - 20 * x**2 + 4*x -6 if __
name__
== '__main__': print("Integer optimium: x = {}\n".format(integer_optimize())) max_x = spo.fmin(lambda x: -f(x), 0) print("Rational optimum: x = {}\n".format(max_x))
kfdm/django-simplestats
quickstats/permissions.py
Python
mit
1,370
0.00073
from rest_framework import permissions from . import models class IsOwnerOrPublic(permissions.IsAuthenticatedOrReadOnly): message = "Not object owner or public" def has_object_permission(self, request,
view, obj): if
request.user == obj.owner: return True if request.method in permissions.SAFE_METHODS: return obj.public return False class IsWidgetOwnerOrPublic(permissions.IsAuthenticatedOrReadOnly): message = "Not object owner or public" def has_permission(self, request, v...
sebbASF/infrastructure-puppet
modules/git_self_serve/files/githubcron.py
Python
apache-2.0
4,335
0.00692
#!/usr/bin/env python3.4 # -*- 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...
/git/mirrors/%s" % reponame): print("%s is there, adding web hooks" % reponame) try: xreponame = reponame.replace(".git"
, "") # Cut off the .git part, so GH will not bork inp = subprocess.check_output("/usr/local/etc/git_self_serve/add-webhook.sh %s" % xreponame, shell = True).decode('ascii', 'replace') except subprocess.CalledProcessError as err: print("Borked: %s" % err.output) ...
SanketDG/networkx
networkx/generators/degree_seq.py
Python
bsd-3-clause
27,099
0.005573
# -*- coding: utf-8 -*- """Generate graphs with a given degree sequence or expected degree sequence. """ # Copyright (C) 2004-2016 by # Aric Hagberg <hagberg@lanl.gov> # Dan Schult <dschult@colgate.edu> # Pieter Swart <swart@lanl.gov> # All rights reserved. # BSD license. import heapq from itertools i...
ops: >>> D.remove_edges_from(D.selfloop_edges()) """ if not sum(in_degree_sequence) == sum(out_degree_sequence): raise nx.NetworkXError('Invalid degree sequences. ' 'Sequences must have equal sums.') if create_using is None: create_using = nx.MultiDiGraph...
n(in_degree_sequence) nout=len(out_degree_sequence) # pad in- or out-degree sequence with zeros to match lengths if nin>nout: out_degree_sequence.extend((nin-nout)*[0]) else: in_degree_sequence.extend((nout-nin)*[0]) # start with empty N-node graph N=len(in_degree_sequence) ...
ml-lab/pylearn2
setup.py
Python
bsd-3-clause
3,408
0
import sys import warnings from setuptools import setup, find_packages, Extension import numpy if 'develop' not in sys.argv: raise NotImplementedError("since Pylearn2 is under rapid, active " "development, `python setup.py install` is " "intentionally dis...
s. Run `python setup.py develop` to " "install Pylearn2.") # Detailed notes: # This modification of setup.py is designed to prevent two problems # novice users frequently encountered: # 1) Novice users frequently used "git clone" to get a copy of Pylearn2, # then ran se...
then would use "git pull" to get a bug fix # but would forget to run "setup.py install" again. # 2) Novice users frequently used "sudo" to make an "installed" copy of # Pylearn2, then try to use the tutorials in the "scripts" directory in # the "installed" copy. Since the tutorials are then in a direct...
thomasdunton/python-html-assert
pha/__init__.py
Python
mit
351
0
from matchers
import ( linear_match as html_match, prune_unmatched_elements ) from spec import ( a, accordion, acc_body, acc_group, acc_heading, div, elem, heading, html, img, input, option, option_xhtml, select, text, ) from formatters import ( pretty_html,
pretty_spec )
Avinash-Raj/appengine-django-skeleton
todo/tests.py
Python
bsd-3-clause
692
0
# Copyright 2015 Google Inc. All rights reserved. # # Licensed under
the Apache License, Version 2.0 (the "Licen
se"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARR...
rmoskal/e-springpad
collection_cache.py
Python
mit
845
0.014201
import uuid from google.appengine.api import memcache class CollectionCache: def __init__(self, timeout=480, hash=None): self.contents = []; if hash: self.contents = memcache.get(hash) self.time
out = timeout def add(self, item): hash = uuid.uuid1().hex memcache.add(hash, item, time = self.timeout) self.contents.append(hash) return hash def commit(self): hash = uuid.uuid1().hex memcache.add(hash, self.contents, time = self.timeout) return hash ...
s: return [] return [[key,memcache.get(key)] for key in self.contents] def fetch(self): for key in self.contents: item = memcache.get(key) if item: yield key,item
HoussemCharf/FunUtils
Fun Scripts/Player.py
Python
mit
351
0.005698
from pygame import * ''' The mus
ic must be in the same folder/project to work You have to install pygame command: pip install pygame ''' mixer.init() msc = input('Song Name: ') mixer.music.load('{}.mp3'.format(msc)) mixer.music.play() while mixer.music.get_busy(): time.Clock().tick(10) if input() == 'p
ause': break;
roadmapper/ansible
lib/ansible/modules/network/cloudengine/ce_mlag_interface.py
Python
gpl-3.0
36,992
0.001892
#!/usr/bin/python # # This file is part of Ansible # # 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 License, or # (at your option) any later version. # # Ansible is distribut...
-port suspend"} ''' import re from xml.etree import ElementTree from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.network.cloudengine.ce import load_config from ansible.module_utils.network.cloudengine.ce import get_nc_config, set_nc_config, ce_argument_spec CE_NC_GET_MLAG_INFO = """ <fil...
%s </mlagInstance> </mlagInstances> </mlag> </filter> """ CE_NC_CREATE_MLAG_INFO = """ <config> <mlag xmlns="http://www.huawei.com/netconf/vrp" content-version="1.0" format-version="1.0"> <mlagInstances> <mlagInstance operation="merge"> <dfsgroupId>%s</dfsgroupId> <mlagId>%s</mlagId> <...
jamespcole/home-assistant
homeassistant/components/serial_pm/sensor.py
Python
apache-2.0
2,805
0
""" Support for particulate matter sensors connected to a serial port. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/sensor.serial_pm/ """ import logging import voluptuous as vol from homeassistant.const import C
ONF_NAME from homeassistant.helpers.entity import Entity import homeassistant.helpers.config_validation as cv from homeassistant.components.sensor import PLATFORM_SCHEMA REQUIREMENTS = ['pmsensor==0.4'] _LOGGER = logging.getLogger(__name__) CONF_SERIAL_DEVICE = 'serial_device' CONF_BRAND = 'brand' PLATFORM_SCHEMA =...
BRAND): cv.string, vol.Required(CONF_SERIAL_DEVICE): cv.string, vol.Optional(CONF_NAME): cv.string, }) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the available PM sensors.""" from pmsensor import serial_pm as pm try: coll = pm.PMDataCollector( ...
Mezgrman/mezgrmanDE
mezgrman/views.py
Python
agpl-3.0
434
0.013825
from django.http import HttpResponse from django.conf import settings import json def javascript_variables(request): variables = { 'STATIC_PREFIX': settings.STATIC_URL } var_catalog = "// VARIABLE CATALOG FOR DJANGO VARIABLES\n\n" var_catalog += "\n".join(("%s = %s;" % (key, json
.dumps(value)) for key, value in variables.items())) return HttpResponse(var_catalog, content_type = 'text/javasc
ript')
kahowell/sixoclock
sixoclock/cli.py
Python
gpl-3.0
6,455
0.003098
# Copyright 2017 Kevin Howell # # This file is part of sixoclock. # # sixoclock is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # six...
filters.append(File.md5 == args.md5) if args.sha1: filters.append(File.sha1 == args.sha1) if args.sha256: filters.append(File.sha256 == args.sha256) if args.size: filters.append(File.size == arg
s.size) collections = self.configuration.collections.values() if args.collection: collections = [self.configuration.collections[args.collection]] if args.mirror: filters.append(File.mirror_uri == args.mirror) for collection in collections: collection...
bdh1011/wau
app.py
Python
mit
4,092
0.000244
import os import random import time from flask import Flask, request, render_template, session, flash, redirect, \ url_for, jsonify from flask.ext.mail import Mail, Message from flask.ext.sqlalchemy import SQLAlchemy from celery import Celery app = Flask(__name__) app.config['SECRET_KEY'] = 'top-secret!' # Flask...
rong in the background job response = { 'state': task.state, 'current':
1, 'total': 1, 'status': str(task.info), # this is the exception raised } return jsonify(response) if __name__ == '__main__': app.run(debug=True)
lukecwik/incubator-beam
sdks/python/apache_beam/io/gcp/gcsio_overrides.py
Python
apache-2.0
2,063
0.003393
# # 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...
.base.py import util _LOGGER = logging.getLogger(__name__) class GcsIOOverrides(object): """Functions for overriding Google Cloud Storage I/O client.""" _THROTTLED_SECS = Metrics.counter('StorageV1', "cumulativeThrottl
ingSeconds") @classmethod def retry_func(cls, retry_args): # handling GCS download throttling errors (BEAM-7424) if (isinstance(retry_args.exc, exceptions.BadStatusCodeError) and retry_args.exc.status_code == http_wrapper.TOO_MANY_REQUESTS): _LOGGER.debug( 'Caught GCS quota error (%...
rolisz/hw3
LFTC/L2/lexer.py
Python
bsd-3-clause
6,145
0.002929
#!/usr/bin/python from fsm import parse_automaton, accept import re __author__ = 'Roland' import sys keywords = ['float', 'char', 'print', 'input', 'break', 'continue', 'return', 'def', 'if', 'elif', 'else', 'while', 'or', 'and', 'not'] operators = ['=', '<', '>', '==', '>=', '<=', '!=', '+', '-', '*', '...
ts.elements.index(atom) var_lang = ["i a-z s B", "i A-Z s B", "s a-z s F", "s A-z s F",
"s 0-9 s F", "s [ t", "t 0-9 f", "f 0-9 f", "f ] l F"] var_aut = parse_automaton(var_lang) num_lang = ["i 0 s B", "i 1-9 t B", "s . n", "t 0-9 f", "t . n", "f 0-9 f", "f . n", "n 0-9 n F"] num_aut = parse_automaton(num_lang) de...
wglass/lighthouse
lighthouse/haproxy/stanzas/stanza.py
Python
apache-2.0
2,087
0
import logging from ..directives import directives_by_section logger = logging.getLogger(__name__) class Stanza(object): """ Subclass for config file stanzas. In an HAProxy config file, a stanza is in the form of:: stanza header directive directive directive S...
ame] ]) def __str__(self): """ Returns the string representation of a Stanza, meant for use in config file content. if no lines are defined an empty string is returned. ""
" if not self.lines: return "" return self.header + "\n" + "\n".join([ "\t" + line for line in self.lines ])
mudler/entropy
lib/entropy/fetchers.py
Python
gpl-2.0
52,462
0.003298
# -*- coding: utf-8 -*- """ @author: Fabio Erculiani <lxnay@sabayon.org> @contact: lxnay@sabayon.org @copyright: Fabio Erculiani @license: GPL-2 B{Entropy Transceivers Fetchers submodule}. """ import os import errno import sys import time try: import httplib except ImportError: # python 3...
value is not None, the download method will return that value. The function takes a path (the download path) and the download id as arguments. @type pre_download_hook: callable @keyword po
st_download_hook: hook called after the download is complete, inside the download_context_func context. This can be used to verify the integrity of the downloaded data. The function takes a path (the download path) and the download status and the download id as arguments....
karacos/karacos-wsgi
py/karacos/core/mail.py
Python
lgpl-3.0
2,688
0.007068
""" KaraCos - web platform engine - http://karacos.org/ Copyright (C) 2009-2010 Nicolas Karageuzian - Cyril Gratecis 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 the Free Software Foundation, either...
import MIMEMultipart from email.MIMEText import MIMEText def valid_email(email): import re reg = re.compile("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3
})(\\]?)$") return reg.match(email) def send_mail(destmail, msg): """ """ try: server = smtplib.SMTP(karacos.config.get('mail','smtp_server'), karacos.config.get('mail','smtp_server_port')) server.ehlo() if karacos.config.has_option('mail',...
vegitron/ansible
lib/ansible/executor/task_executor.py
Python
gpl-3.0
31,968
0.003191
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # # This file is part of Ansible # # 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 License, or # (at your option) an...
rms if not templar._contains_vars(t)] else:
try: loop_terms = listify_lookup_plugin_terms(terms=self._task.loop_args, templar=templar, loader=self._loader, fail_on_undefined=True, convert_bare=True) except AnsibleUndefinedVariable as e: display.deprecated("Skipping task due to un...
sacovo/brainfuck
setup.py
Python
gpl-2.0
262
0.003817
__author__ = 'sandro' from distutils.core import setup setup( author='Sandro Covo', au
thor_email="sandro@covo.ch", packages=['brainfuck'], scripts=['scripts/pyfuck'], name="Pyfuck", desc
ription="Brainfuck interpreter written in python" )
hzlf/openbroadcast
website/shop/shop_ajax/admin.py
Python
gpl-3.0
24
0.083333
#
-*-
coding: utf-8 -*-
Florents-Tselai/PyCarGr
pycargr/parser.py
Python
mit
5,387
0.000931
#!/usr/bin/env python3 # -*- encoding: utf-8 -*- __author__ = 'Florents Tselai' from datetime import datetime from urllib.request import urlopen, Request from bs4 import BeautifulSoup from fake_useragent import UserAgent from pycargr.model import Car class SearchResultPageParser: def __init__(self, search_pag...
try: return self.soup.find('span', itemprop='addressRegion').text except Exception: return None def parse_postal_code(self): try: return int(self.soup.find('span', itemprop='postalCode').text)
except Exception: return None def parse_transmission(self): try: return self.soup.find(id='clsfd_transmision_%s' % self.car_id).text except Exception: return None def parse_images(self): try: images_urls = [] for img in s...
Veblin/pythonDemo
spiders/logins.py
Python
mit
401
0.009975
import requests import time from selenium import webdriver # file path import os BASE_DIR = os.
path.dirname(__file__) phjs_path = os.path.join(BASE_DIR,'login.phjs.js') print ('*******'+phjs_path+'*******') driver = webdriver.PhantomJS(executable_path=phjs_pat
h) driver.get('http://autoinsights.autodmp.com/user/login') time.sleep(3) print(driver.find_element_by_tag_name('form').text) driver.close()
cjaymes/pyscap
src/scap/model/xccdf_1_2/ModelType.py
Python
gpl-3.0
6,764
0.003999
# Copyright 2016 Casey Jaymes # This file is part of PySCAP. # # PySCAP is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # PySCAP is ...
s: if scores[rule_id]['result'] in ['notapplicable', 'notchecked', 'informational', 'notselected']: continue max_score += scores[rule_id]['weight'] if scores[rule_id]['result'] in ['pass', 'fixed']: score += scores[rule_id]['weight...
str(score)) host.facts['checklist'][benchmark.id]['profile'][profile_id]['scores'].append({'score': score, 'system': self.system}) else: raise NotImplementedError('Scoring model ' + self.system + ' is not implemented')
sujithvm/skynet
code/__init__.py
Python
mit
41
0
__author__ = 'Archana
V Menon, Suji
th V'
MadManRises/Madgine
shared/bullet3-2.89/examples/pybullet/gym/pybullet_envs/minitaur/envs/minitaur_ball_gym_env.py
Python
mit
5,864
0.00648
"""This file implements the gym environment of minitaur. """ import math import random import os, inspect currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parentdir = os.path.dirname(os.path.dirname(currentdir)) os.sys.path.insert(0, parentdir) from gym import spaces import nump...
_ball_id)) minitaur_tr
anslation_world, minitaur_rotation_world = (self._pybullet_client.invertTransform( world_translation_minitaur, world_rotation_minitaur)) minitaur_translation_ball, _ = (self._pybullet_client.multiplyTransforms( minitaur_translation_world, minitaur_rotation_world, world_translation_ball, worl...
jirafe/pyleus
tests/cli/storm_cluster_test.py
Python
apache-2.0
1,989
0.001508
import os import pytest from pyleus.cli.storm_cluster import _get_storm_cmd_env from pyleus.cli.storm_cluster import STORM_JAR_JVM_OPTS from pyleus.cli.storm_cluster import StormCluster from pyleus.cli.storm_cluster import TOPOLOGY_BUILDER_CLASS from
pyleus.testing import mock class TestGetStormCmdEnd(object): @pytest.fixture(autouse=T
rue) def mock_os_environ(self, monkeypatch): monkeypatch.setattr(os, 'environ', {}) def test_jvm_opts_unset(self): assert _get_storm_cmd_env(None) is None def test_jvm_opts_set(self): jvm_opts = "-Dfoo=bar" env = _get_storm_cmd_env(jvm_opts) assert env[STORM_JAR_JVM...
longde123/MultiversePlatform
tools/Machinima/sendXmlJobs.py
Python
mit
4,886
0.00614
# # The Multiverse Platform is made available under the MIT License. # # Copyright (c) 2012 The Multiverse Foundation # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation # files (the "Software"), to deal in the Software without restrict...
ng without limitation the rights to use, copy, modify, # merge, publish, distribute, sublicense, and/or sell copies # of the Software, and to permit persons to whom the Software # is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be # in...
R IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, ...
ddboline/Garmin-Forerunner-610-Extractor_fork
ant/easy/node.py
Python
mit
4,653
0.004083
# Ant # # Copyright (c) 2012, Gustav Tiger <gustav@tiger.name> # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, m...
llowing conditions: # # The above copyrigh
t notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT....
giggsey/SickRage
sickbeard/providers/xthor.py
Python
gpl-3.0
8,500
0.004471
# -*- coding: latin-1 -*- # Author: adaur <adaur.underground@gmail.com> # URL: http://code.google.com/p/sickbeard/ # # This file is part of SickRage. # # SickRage is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation...
else: logger.log(u'Login to ' + self.name + ' was unsuccessful.', logger.DEBUG) return False retu
rn True def _doSearch(self, search_params, search_mode='eponly', epcount=0, age=0, epObj=None): logger.log(u"_doSearch started with ..." + str(search_params), logger.DEBUG) results = [] items = {'Season': [], 'Episode': [], 'RSS': []} # check for auth if not self._doLogin...
toofar/qutebrowser
tests/unit/utils/test_urlmatch.py
Python
gpl-3.0
17,880
0
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: # Copyright 2018 Florian Bruhin (The Compiler) <mail@qutebrowser.org> # # This file is part of qutebrowser. # # qutebrowser is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Softwa...
w/", "May not contain NUL byte"), # Chromium: PARSE_ERROR_INVALID_HOST_WILDCARD ("http://*foo/bar", "Invalid host wildcard"), ("http://foo.*.bar/baz", "Invalid host wildcard"), ("http://fo.*.ba:123/baz", "Invalid host wildcard"), ("http://foo.*/bar", "TLD wildcards ar
e not implemented yet"), # Chromium: PARSE_ERROR_INVALID_PORT ("http://foo:/", "Invalid port: Port is empty"), ("http://*.foo:/", "Invalid port: Port is empty"), ("http://foo:com/", "Invalid port: invalid literal for int() with base 10: 'com'"), pytest.param("http://foo:123456/", ...
DarKnight24/owtf
plugins/web/passive/Testing_for_SSL-TLS@OWTF-CM-001.py
Python
bsd-3-clause
489
0.00409
""" PASSIVE Plugin for Testing_for_SSL-TLS_(OWASP-CM-001) """ from framework.dependen
cy_management.dependency_resolver import ServiceLocator DESCRIPTION = "Third party resources" def run(PluginInfo): # Vuln search box to be built in core and resued in different plugins: resource = ServiceLocator.get_component("resource").GetResources('PassiveSSL') Content = ServiceLocator.get_component(...
line Resources', resource) return Content
xbmcmegapack/plugin.video.megapack.dev
resources/lib/menus/home_countries_greece.py
Python
gpl-3.0
1,109
0.00271
#!/usr/bin/python # -*- coding: utf-8 -*- """ This file is part of XBMC Mega Pack Addon. Copyright (C) 2014 Wolverine (xbmcmegapack@gmail.com) This program is free software: you can redis
tribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even ...
ranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General 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/gpl-3.0.html """ class Countries_Greece(): '''Cla...
jrspruitt/jkent-pybot
pybot/plugins/anyurl.py
Python
mit
2,136
0.004682
# -*- coding: utf-8 -*- # vim: set ts=4 et import cgi import requests from six.moves.html_parser import HTMLParser from plugin import * content_types = ( 'text/html', 'text/xml', 'application/xhtml+xml', 'application/xml' ) class TitleParser(HTMLParser): def __init__(self): HTMLParser._...
parser = TitleParser() for line in r.iter_lines(chunk_size=1024, decode_unicode=True): parser.feed(line) if parser.title: break msg.reply('\x031,0
URL\x03 %s' % parser.title)
meghana0507/grpc-java-poll
lib/netty/protobuf/python/google/protobuf/internal/api_implementation.py
Python
bsd-3-clause
4,621
0.004112
# Protocol Buffers - Google's data interchange format # Copyright 2008 Google Inc. All rights reserved. # https://developers.google.com/protocol-buffers/ # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redi...
was None') del _use_fast_cpp_protos _api_version = 2 except ImportError: if _proto_extension_modules_exist_in_build: if sys.version_info[0] >= 3: # Python 3 defaults to C++ impl v2. _api_ver
sion = 2 # TODO(b/17427486): Make Python 2 default to C++ impl v2. _default_implementation_type = ( 'python' if _api_version <= 0 else 'cpp') # This environment variable can be used to switch to a certain implementation # of the Python API, overriding the compile-time constants in the # _api_implementation ...
joopert/home-assistant
tests/components/binary_sensor/test_device_condition.py
Python
apache-2.0
8,656
0.001733
"""The test for binary_sensor device automation.""" from datetime import timedelta import pytest from unittest.mock import patch from homeassistant.components.binary_sensor import DOMAIN, DEVICE_CLASSES from homeassistant.components.binary_sensor.device_condition import ENTITY_CONDITIONS from homeassistant.const impor...
component(hass, DOMAIN, {DOMAIN: {CONF_PLATFORM: "test"}}) expected_conditions = [ { "condition": "device", "domain": DOMAIN, "type": condition["type"], "device_id": device_entry.id, "entity_id": platform.ENTITIES[device_class].entity_id, ...
ONDITIONS[device_class] ] conditions = await async_get_device_automations(hass, "condition", device_entry.id) assert conditions == expected_conditions async def test_get_condition_capabilities(hass, device_reg, entity_reg): """Test we get the expected capabilities from a binary_sensor condition.""" ...
mike-perdide/pcoords-gui
pcoordsgui/utils.py
Python
gpl-3.0
292
0
from PyQt4.QtGui import QFileDialog def get_pcv_filename(): """Opens t
he PCV file with a QFileDialog.""" return QFileDialog.getOpenFileName(None, "Open Pcoords graph", "",
"Pcoords Files (*.pgdl *.pcv)")