prefix stringlengths 0 918k | middle stringlengths 0 812k | suffix stringlengths 0 962k |
|---|---|---|
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'... | utput_file = open(output_path, 'w')
output_file.write('Confidence' + '\n')
first_val = True
for confid in confidence_values:
if not first_val:
output_file.w | rite(str(confid) + '\n')
else:
output_file.write(str(confid) + '\n')
first_val = False
output_file.close()
if __name__ =="__main__":
_report_path = sys.argv[1]
_output_path = sys.argv[2]
generate_R_input(_report_path, _output_path)
|
import requests,sys
from config_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.statu... | em_resp.text
sys.exit()
f = open('..\pemfile.pem','w')
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_code
print "API Message: "+resp.text
sys.e... |
#!/usr/bin/env python
"""Transform a CSV file exported from the Recorded Future UI into Maltego entities."""
import json
import sys
import csv
import Tkinter, tkFileDialog
from MaltegoTransform import *
mt = MaltegoTransform()
# Use Tkinter to open up a file dialog.
root = Tkinter.Tk()
root.lift()
root.withdraw()
s... | ds("firstpublished","First Published",False,row['First Published Time']);
rfevent.addAdditionalFields("lastpublished","Last Published",False,row['La | st Published Time']);
rfevent.addAdditionalFields("sourcecount","Source Count",False,row['Source Count']);
rfevent.addAdditionalFields("pos_sentiment","Positive Sentiment",False,row['Positive Sentiment']);
rfevent.addAdditionalFields("neg_sentiment","Negative Sentiment",False,row['Negative Sentiment']);
mt... |
# -*- 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... | ssbook_contact_unblocked(self, contact):
self._contactlist_manager.on_contact_unblocked(contact)
def on_addressbook_grou | p_added(self, group):
self._contactlist_manager.on_group_added(group)
def on_addressbook_group_deleted(self, group):
self._contactlist_manager.on_group_deleted(group)
def on_addressbook_group_renamed(self, group):
self._contactlist_manager.on_group_renamed(group)
def on_addressboo... |
""" 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)... | data = self.cached_data['players'].get(str(uid), None)
if data is not None:
nick = data.get('nick', None)
comment = data.get('comment', | None)
return {'nick':nick,'comment':comment}
def setXvmContactData(self, uid, value):
try:
if self.cached_data is None or 'players' not in self.cached_data:
raise Exception('[INTERNAL_ERROR]')
if (value['nick'] is None or value['nick'] == '') and (value['c... |
# 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... | D"generator" content=3D"Windows Mail 17.5.9600.20911">
<style data-externalstyle=3D"true"><!--
| p.MsoListParagraph, li.MsoListParagraph, div.MsoListParagraph {
margin-top:0in;
margin-right:0in;
margin-bottom:0in;
margin-left:.5in;
margin-bottom:.0001pt;
}
p.MsoNormal, li.MsoNormal, div.MsoNormal {
margin:0in;
margin-bottom:.0001pt;
... |
#!/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
##################################################################... | get_enabled_channels(confdir):
CHANNELS = {}
for config_file in glob(confdir + "*.ini"):
config = ConfigParser()
config.read(config_file)
PATH, NAME = os.path.split(config_file)
NAME, EXT = os.path.splitext(NAME)
PID = get_ffmpeg_pid(config.get('General', 'MCAST_OUT_IP'), config... | ig.get('General', 'MCAST_OUT_IP'),
"MCAST_PORT": config.get('General', 'MCAST_OUT_PORT'),
"INPUT_STREAM": config.get('General', 'INPUT_STREAM'),
"VIDEO_BITRATE": config.get('General', 'VIDEO_BITRATE'),
"AUDIO_BITRATE": config.get('General', 'AUDIO_BITRATE'),
"CODEC... |
# -*- 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 ... | },
bases=('board.basepost',),
),
migrations.AlterModelOptions(
name='boardbanner',
options={'verbose_name': '게시판 배너', 'verbose_name_plural': '게시판 배너(들)' | },
),
migrations.AlterField(
model_name='board',
name='role',
field=models.CharField(choices=[('DEFAULT', '기본'), ('PROJECT', '사업'), ('PLANBOOK', '정책자료집'), ('DEBATE', '논의'), ('ARCHIVING', '아카이빙'), ('WORKHOUR', '상근관리'), ('SPONSOR', '제휴리스트'), ('SWIPER', '격주보고'), ('STORE'... |
#!/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\temp '
r'/M * /C "cmd /c if @isdir==TRUE rmdir /S /Q @file"')
else:
os.sys | tem(r'rm -rf /tmp/*')
|
#!/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... | += tag.pack()
for surface in self.surfaces:
pack_str += surface.pack()
return pack_str
def importAsset(model, asset):
raise NotImplementedError
def exportAsset(model, asset):
out = toolbox.writeAn | y(asset)
md3_object = MD3Object()
meshes = model.getMeshes()
#TODO: Put stuff into the MD3Object here()
out.write(md3_object.pack())
out.close()
def encodeNormal(x,y,z):
"""Returns (azimuth, zenith) angles of the normal vector
"""
azimuth = math.atan2(y, x) * 255 / (2 * math.pi)
zen... |
from mpi4py import MPI
from cplpy import CPL
comm = MPI.COMM_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, ... | time, recv_arr | ay[0,0,0,0])
send_array[0,:,:,:] = 2.*time
CPL.send(send_array)
CPL.finalize()
MPI.Finalize()
|
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... | context
notice = notice.replace('NOTICE: ', '')
prefix = ''
logger.debug('%s%s' % (prefix, notice.strip()))
return r
return wrapped
def load_sql_files(app, stage):
"""
Look for SQL files in Django app, and load them into database.
We... | app_dir = app.path
sql_dir = os.path.normpath(os.path.join(app_dir, 'sql'))
custom_sql_dir = os.path.join(settings.VAR_DIR, 'conf/extra_sql', app.label)
sql_files = []
r = re.compile(r'^{}_.*\.sql$'.format(stage))
if os.path.exists(sql_dir):
sql_files += [
os.path.join(sql_dir, ... |
"""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... |
'detailed': int(bool(detailed))
}
if isinstance(metadata, dict):
metadata = json.dumps(metadata)
| if metadata:
opts['metadata'] = metadata
qparams = {}
for opt, val in opts.items():
if val:
if isinstance(val, six.text_type):
val = val.encode('utf-8')
qparams[opt] = val
query_string = '?%s' % parse.urlencode... |
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#registeri | ng-an-adapter-callable
return time.mktime(ts.timetuple())
def convert_datetime(ts):
try:
return datetime.datetime.fromtimestamp(float(ts))
except ValueError:
return None
sqlite3.register_adapter(datetime.datetime, adapt_datetime)
sqlite3.register_converter('timestamp', convert_datetime)
pa... | PES)
conn.row_factory = sqlite3.Row
except Exception as detail:
xbmc.log("EXCEPTION: (script.stargate.guide) %s" % detail, xbmc.LOGERROR)
c = conn.cursor()
startDate = datetime.datetime.fromtimestamp(float(start))
c.execute('SELECT DISTINCT * FROM programs WHERE channel=? AND start_date = ?', [channel,startDa... |
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 -= {'slash-in-hosts'}
def post_conn... | '
}
self.umodes = umodes
self.extbans_matching.clear()
# halfops is mandatory on Hybrid
self.prefixmodes = {'o': '@', 'h': '%', 'v': '+'}
# https://github.com/grawity/irc-docs/blob/master/server/ts6.txt#L55
f('PASS %s TS 6 %s' % (self.serverdata["sendpass"], se... | on for certain commands
# EX: Support for ban exemptions (+e)
# IE: Support for invite exemptions (+e)
# CHW: Allow sending messages to @#channel and the like.
# KNOCK: Support for /knock
# SVS: Deal with extended NICK/UID messages that contain service IDs/stamps
# TBURST... |
#! /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... | , ( "std::allocator", ["int"] ) ] )
def test_split_on_string(self):
self.__test_is_call_invocation_impl( "basic_string(char,std:: | char_traits(char),std::allocator(char) )" )
self.__test_split_impl( "basic_string(char,std::char_traits(char),std::allocator(char) )"
, "basic_string"
, [ "char", "std::char_traits(char)", "std::allocator(char)" ] )
def test_split_on_ma... |
l):
util.info("Examining url " + url)
if MOVIES_GENRE in url:
return self.list_by_genres(url)
if self.is_most_popular(url):
if "movie" in url:
return self.list_movies_by_letter(url)
if "tv" in url:
return self.list_tv_shows_by_l... | 'rokvydani'))
| item['title'] = '%s - %s' % (basetitle, film.findtext('kvalita').upper())
item['name'] = item['title']
item['img'] = film.findtext('obrazekmaly')
item['url'] = self.base_url + '/player/' + self.parent.make_name(
film.findtext('nazeven').e... |
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)'... | :
for s in scatterers:
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 / (... | tmatrix')
c_fixed = scattering.scatterer(cband, temp, 'water', diameters=d, shape='oblate')
c_fixed.set_scattering_model('tmatrix')
s_fixed = scattering.scatterer(sband, temp, 'water', diameters=d, shape='oblate')
s_fixed.set_scattering_model('tmatrix')
plot_csecs(d, [x_fixed, c_fixed, s_fixed])
plt.legend(loc = 'up... |
# Copyright 2018 Tecnativa - David Vidal
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
'name': 'Stock Picking Procure Method',
'summary': 'Allows to force t | he procurement method from the picking',
'version': '12.0.1.0.0',
'category': 'Warehouse',
'author': 'Tecnativa,'
'Odoo Community | Association (OCA)',
'website': 'https://github.com/OCA/stock-logistics-warehouse',
'license': 'AGPL-3',
'depends': [
'stock',
],
'data': [
'views/stock_picking_views.xml',
],
'installable': True,
}
|
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... | ss that just uses the standard Django authenticate mechanism
"""
auth_class = SocialAuthentication
class TokenLogin(account_auth.TokenLogin):
"""
A login class that returns a user authentication token. This method, in its default
configuration is only available if rest_framework.authtoken is | in installed_apps
"""
auth_class = SocialAuthentication
# class OAuth2Login(account_auth.OAuth2Login):
# """
# A login class that accepts oauth2 authentication requests and returns the appropriate
# access tokens. This login method, in its default configuration is only available if
# oauth2_... |
#! /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... | o(old_name, new_id, args.ext)
new_path = new_dir + "/" + new_name
old_path = old_dir + "/" + old_name
ln_out, ln_err = (Popen(['ln', "-s", old_path, new_path],
stdout=PIPE, stderr=PIPE).communicate())
if ln_err:
pr... | '__main__':
main()
sys.exit(0)
|
__author__ = 'xubinggui'
class Studen | t(object):
def __init__(self, name, score):
self.name = name
self.score = score
def print_score(self):
print(self.score)
bart = Student('Bart Simpson', 59)
bart.print_sc | ore() |
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... | 'body',
'group',
'tags',
'source',
'website',
'release_dt',
| 'timezone',
)
}),
(_('Contributor'), {'fields': ('contributor_type',)}),
(_('Author'), {'fields': ('first_name',
'last_name',
'google_profile',
'phone',
... |
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)
... | t_sln is True:
build_sln = True
if build_sln is T | rue:
generate_sln = True
if generate_sln is True:
generate(**kwargs)
else:
raise Exception('Did not enable at least one of "generate", "build" or "test"');
def main(argv=sys.argv[1:]):
parser = argparse.ArgumentParser(description='Manage CMake projects')
parser.add_argument('-... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes | may cause incorrect behavior and will be lost | if the code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.serialization import Model
class StorageProfile(Model):
"""Specifies the storage settings for the virtual machine disks.
:param image_reference: Specifies information about the image to us... |
#!/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 = argparse.ArgumentParser(
description="Collate Mojo application manifests.")
parser.add_argument("--parent")
parser.add_argument("--output")
parser.add_argument("--application-name")
args, children = parser.parse_known_args()
parent = ParseJSONFile(args.parent)
if parent == None:
ret... | "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." %
(args.application_name, app_path))
applications = []
for child in ... |
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 tim... | Rabbit has (\d+) farms in database")
def fill_tables(step, count):
db = dbmanager.DB(lib.world.config['connections']['mysql'])
lib.world.f | arms_ids = list()
for i in range(int(count)):
while True:
farm_id = random.randint(1, 9999)
query = "SELECT id FROM farms WHERE id={0}".format(farm_id)
if bool(db.execute(query)):
continue
break
query = "INSERT INTO farms (id) VALUES ({... |
#!/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>
#
#####################... | ######################
import sys
sys.path.append( '../pymod' )
import gdaltest
###############################################################################
# Read test of simple byte reference data.
def paux_1():
tst = gdaltest.GDALTest( 'PAux', 'small16.raw', 2, 12816 )
| return tst.testOpen()
###############################################################################
# Test copying.
def paux_2():
tst = gdaltest.GDALTest( 'PAux', 'byte.tif', 1, 4672)
return tst.testCreateCopy( check_gt = 1 )
###########################################################################... |
__author | __ = 'Anat | oli Kalysch'
|
n mediatypes) and not
xbmc.getCondVisibility("Skin.HasSetting(SkinHelper.view.Disabled.%s)" % viewid)):
image = "special://skin/extras/viewthumbs/%s.jpg" % viewid
listitem = xbmcgui.ListItem(label=label, iconImage=image)
listitem.setPro... | Close(script-skin_helper_service-CustomInfo.xml)")
xbmc.sleep(1000)
xbmc.executebuiltin('PlayMedia("%s")' % result.getProperty("path"))
del result
def getcastmedia(self):
'''helper to show a dialog with all media for a specific actor'''
xbmc.executebuiltin("A... | "")
results = []
items = self.kodidb.castmedia(name)
items = process_method_on_list(self.kodidb.prepare_listitem, items)
for item in items:
if item["file"].startswith("videodb://"):
item["file"] = "ActivateWindow(Videos,%s,return)" % item["file"]
e... |
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):
... | sponse(result.json())
except Exception as e:
logger.error('RESTful {classname} call failed. {message}'.format(
classname=self.__class__.__name__, message=e),
exc_info=True)
raise e
class PostMixin(object):
meth | od = 'post'
|
#!/u | sr/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 mai... | ain()
|
#!/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 ... | rom io import TextIOWrapper
import sqlparse
from sqlparse.exceptions import SQLParseError
# TODO: Add CLI Tests
# TODO: Simplify formatter by using argparse `type` arguments
def create_parser():
_CASE_CHOICES = ['upper', 'lower', 'capitalize']
parser = argparse.ArgumentParser(
prog='sqlformat',
... | scription='Format FILE according to OPTIONS. Use "-" as FILE '
'to read from stdin.',
usage='%(prog)s [OPTIONS] FILE, ...',
)
parser.add_argument('filename')
parser.add_argument(
'-o', '--outfile',
dest='outfile',
metavar='FILE',
help='write out... |
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_name + " " + self.classification
def was_published_recentl... | datetime.timedelta(days=1)
was_published_recently.admin_order_field = 'pub_date'
was_published_recently.boolean = True
was_published_recently.short_description = 'Published recently?'
|
# -*- 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/... | .payment_mode_id', '=', False))
# del domain[index - 1]
# domain.removemove(('invoice.payment_mode_id', '=', False))
# index = domain.index(('da | te_maturity', '<=', self.duedate))
# del domain[index - 1]
# domain.remove(('date_maturity', '=', False))
# domain.remove(('date_maturity', '<=', self.duedate))
elif payment_order.mode.type.code == '500':
if payment_order.mode.payment_order_type == 'payment':
... |
operty for **self.__splitter** attribute.
:return: self.__splitter.
:rtype: unicode
"""
return self.__splitter
@splitter.setter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def splitter(self, value):
"""
Setter for **se... | "{0} | '{1}' attribute is not deletable!".format(self.__class__.__name__, "network_access_manager"))
def __initialize_ui(self):
"""
Initializes the Widget ui.
"""
umbra.ui.common.set_window_default_icon(self)
LOGGER.debug("> Initializing '{0}' ui.".format(self.__clas... | else:
self.Logo_label.setPixmap(QPixmap(os.path.join(self.__ui_resources_directory, self.__ui_logo_image)))
self.Your_Version_label.setText(self.__releases[Constants.application_name].local_version)
self.Latest_Version_label.setText(self.__releases[Constants.application_name].reposit... |
ils
#from seq2seq.models import SimpleSeq2Seq
from gensim import models, matutils
from sklearn.utils import shuffle
from sklearn.preprocessing import MinMaxScaler
import theano
theano.config.openmp = True
from sklear | n.linear_model import LogisticRegression
#OMP_NUM_THREADS=24 python sentiment.py
def read_data(file_path, w2v_model, max_len = 300, hidden_dim = 32):
X = []
with open(file_path, "r") as f:
for line in f:
x = np.zeros(hidden_dim)
tokens = line.strip().split()
index = ... | ]
index += 1
if index >= max_len:
break
x /= index
X.append(x)
return np.array(X)
def normalize(word):
word = re.sub(r'[^\w\s]' , "", word.decode("utf-8"), re.UNICODE)
word = word.lower()
return word
class Generator:
... |
"""Test functions for simbad.util.pdb_util"""
__author__ = "Ada | m 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_csv"""
csv_temp_file = tempfile.NamedTemporaryFile("w"... | a,gamma,length_penalty,angle_penalty,total_penalty,volume_difference,probability_score
1DTX, ,23.15,39.06,73.53,90.0,90.0,90.0,0.418,0.0,0.418,398.847,0.842"""
)
csv_temp_file.close()
data = simbad.util.result_by_score_from_csv(csv_temp_file.name, "total_penalty")
reference_data = ["1DT... |
from ..base import ParametrizedValue
class BalancingAlgorithm(ParametrizedValue):
name_separator = ''
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 algorithm.
"""
name = 'wrr'
class LeastReferenceCount(BalancingAlgorithmWithBackup):
"""Le... | unt algorithm with backup support."""
name = 'lrc'
class WeightedLeastReferenceCount(BalancingAlgorithmWithBackup):
"""Weighted least reference count algorithm with backup support."""
name = 'wlrc'
class IpHash(BalancingAlgorithmWithBackup):
"""IP hash algorithm with backup support."""
name =... |
White = 15
class Coord(ctypes.Structure):
_fields_ = [('X', ctypes.c_short), ('Y', ctypes.c_short)]
class SmallRect(ctypes.Structure):
_fields_ = [('Left', ctypes.c_short),
('Top', ctypes.c_short),
('Right', ctypes.c_short),
('Bottom', ctypes.c_short... | = [('dwSize', Coord),
('dwCursorPosition', Coord),
('wAttributes', ctypes.c_uint),
('srWindow', SmallRect),
('dwMaximumWindowSize', Coord),
]
class Win32API():
'''Some native methods for python calling' | ''
StdOutputHandle = -11
ConsoleOutputHandle = None
DefaultColor = None
@staticmethod
def SetConsoleColor(color):
'''Change the text color on console window'''
if not Win32API.DefaultColor:
if not Win32API.ConsoleOutputHandle:
Win32API.ConsoleOu... |
"""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:
... | Define as hours
habcat_ra.append(ra.degree) # Convert to degree
de = coord.Angle(row[2], unit=u.deg)
habcat_de.append(de.degree)
print(len(habcat_id), 'HabCat datalines loaded')
# Nested loop through all Pulsars to find closest 180deg HabCat for each
for currentpulsar in range(len(pu... | ce = 180 * 60 # set to max, in arcminutes
for currenthabcat in range(len(habcat_id)): # HabCat loop
# Correct calculation is very slow, thus only try the best candidates:
if (abs(habcat_ra[currenthabcat] -
flipra(pulsar_ra[currentpulsar])) < 5.
and abs(habcat_de[currenthabc... |
# -*- 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(SimpleDownloader):
__name__ = "UpleaCom"
__type__ = "downloader"
__version__ = "0.21"
__status__ = "testing"
__pattern__ = r"https?://(?:www\.)?uplea\.com/dl/\w{15}"
__config__ = [
| ("enabled", "bool", "Activated", True),
("use_premium", "bool", "Use premium account if available", True),
("fallback", "bool", "Fallback to free download if premium fails", True),
("chk_filesize", "bool", "Check file size", True),
("max_wait", "int", "Reconnect if waiting time i... |
else:
return super(DoctestItem, self).repr_failure(excinfo)
def reportinfo(self):
return self.fspath, self.dtest.lineno, "[doctest] %s" % self.name
def _get_flag_lookup():
import doctest
return dict(
DONT_ACCEPT_TRUE_FOR_1=doctest.DONT_ACCEPT_TRUE_FOR_1,
DONT_ACC... | ionflags_str = parent.config.getini("doctest_optionflags")
flag_lookup_table = _get_flag_lookup()
flag_acc = 0
for flag in optionflags_str:
flag_acc |= flag_lookup_table[flag]
return flag_acc
def _get_continue_on_failure(config):
| continue_on_failure = config.getvalue("doctest_continue_on_failure")
if continue_on_failure:
# We need to turn off this if we use pdb since we should stop at
# the first failure
if config.getvalue("usepdb"):
continue_on_failure = False
return continue_on_failure
class Doct... |
# 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... | initialIdx = tmpIdx
ai | rportDist[tmpIdx] = MIN
print tmpIdx
print airportDist
|
# -*- coding: utf-8 -*-
"""
***************************************************************************
FixedDistanceBuffer.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
*******************... | *
***************************************************************************
"""
__author__ = 'Victor Olaya'
__date__ = 'August 2012'
__copyright__ = '(C) 2012, Victor Olaya'
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'
import os
from qgis.PyQt.Qt... | |
from JumpScale import j
descr = "" | "
remove old redis cache from system
"""
organization = "jumpscale"
author = "deboeckj@codescalers.com"
license = "bsd"
version = "1.0"
category = "redis.cleanup"
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... | xcept:
import json
import JumpScale.grid.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... |
""" Run target checks using snactor """
from generic_runner import run, pprint, get_actor
d | ef check_target():
""" Run multiple checks at target machine """
targetinfo = {}
get_actor('check_target_group').execute(targetinfo)
get_actor('check_target').execute(targetinfo)
pprint(t | argetinfo['targetinfo'])
if __name__ == '__main__':
run(check_target, tags=['check_target'])
|
# -*- 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... | tya.lib.create_project(
session,
name='subsurface',
homepage='http://subsurface.hohndel.org/',
version_url='http://subsurface.hohndel.org/downloads/',
regex='DEFAULT',
user_id='noreply@fedoraproject.org',
)
anitya.lib.create_project(
| session,
name='R2spec',
homepage='https://fedorahosted.org/r2spec/',
user_id='noreply@fedoraproject.org',
)
def create_ecosystem_projects(session):
""" Create some fake projects from particular upstream ecosystems
Each project name is used in two different ecosystems
""... |
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 version.
#
# This program is distributed in the ... | at type a parameter is without looking at usage. Instead of doing that,
this walks the AST node describing the function and considers the type to be
the set of all methods called on the parameter."""
assert isinstance(function, ast.FunctionDef), "Tried to get usage of parameter in a non-function."
# Ch... | r this parameter
if config.type_hinting():
for arg in function.args.args:
if arg.arg == parameter:
if arg.annotation:
return _HintedType(arg.annotation.id)
if not config.structural_typing():
return _dynamic
# TODO: Don't completely ommit 'sel... |
""" Helpers for making some things in PIL easier """
from PIL import ImageDraw, ImageFont, ImageStat
from math import ceil
def drawTextWithBorder(draw, text, coords,
fontname="Impact", fontsize=80,
color="#fff", strokecolor="#000"):
""" Draw text with a border. Althou... | eft, using a text color
that will ensure appropriate contrast. """
d = ImageDraw.Draw(im)
textsize = ImageFont.load_default().getsize(t | ext)
coords = im.size[0] - textsize[0] - 5, im.size[1] - textsize[1] - 5
# Check color of image where the text would go
textarea = im.crop(coords + im.size)
textareabrightness = ImageStat.Stat(textarea.convert("L")).mean[0]
color = (0, 0, 0) if textareabrightness > 128 else (255, 255, 255)
# Dra... |
import bpy
from bpy.props import *
from mathutils import Vector
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"... | elf.resolution)
parameter = spline.toUniformParameter(parameter)
return spline. | evaluate(parameter), spline.evaluateTangent(parameter)
else:
return Vector((0, 0, 0)), Vector((0, 0, 0))
|
self.name = name
self.tmp_name = "kernelconfig_tmp_{!s}".format(self.name)
self.masters = None
self.packages = {}
self.categories = set()
kwargs.setdefault("logger_name", self.name)
super().__init__(overlay_dir, **kwargs)
# --- end of __init__ (...) ---
de... | lay ---
class TemporaryOverlay(_TemporaryOverlay):
"""
@ivar linux_info_eclass_src: path to the linux-info eclass file
in the original repo
(or in one of its master repos)
@type linux_info_eclass_src: C{str} (initially C{None}
"""
... | super().__init__(overlay_dir, name, **kwargs)
self.linux_info_eclass_src = None
# --- end of __init__ (...) ---
def assign_repo_config(self, port_iface, fallback_repo_config=True):
# pylint: disable=E1101
if fallback_repo_config is True:
fallback_repo_config = self.get_... |
#!/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... | run_set_result = tablegenerator.RunSetResult.create_fro | m_xml(
options.result[0], tablegenerator.parse_results_file(options.result[0])
)
for results_file in options.result[1:]:
run_set_result.append(
results_file, tablegenerator.parse_results_file(results_file)
)
run_set_result.collect_data(options.correct_only or options.scor... |
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
:return: URL
:rtype: String
"""
| return reverse('csa_practice_api:csa_theme_detail', kwargs={'slug': self.slug})
class Meta:
ordering = ['-time_created', '-last_update']
verbose_name_plural = 'CSA Practice Themes'
@property
def csa_practice_relation(self):
"""
Get related CSA practice
:retur... | instance = self
qs = CsaPractice.objects.filter_by_model_type(instance)
return qs
@receiver(pre_save, sender=CsaTheme)
def pre_save_csa_theme_receiver(sender, instance, *args, **kwargs):
"""
Create a slug before save.
:param sender: Signal sending object
:param instance: Object inst... |
"IsWeight",
"Weight",
tooltip).IsWeight = True
# Add the mass property for puntual weights
tooltip = str(QtGui.QApplication.translate(
"ship_weight",
"Mass [kg]",
None))
obj.addProp... |
rho = Units.parseQuantity('{0} kg/m^2'. | format(fp.AreaDens))
a = Units.Quantity(shape.Area, Units.Area)
return rho * a
def _getVolumetricMass(self, fp, shape):
"""Compute the mass of a volumetric element.
Position arguments:
fp -- Part::FeaturePython object affected.
shape -- Solid shape object.
... |
citable')
ins('excited')
ins('exciting')
ins('exotic')
ins('expensive')
ins('experienced')
ins('expert')
ins('extraneous')
ins('extroverted')
ins('extra-large')
ins('extra-small')
ins('fabulous')
ins('failing')
ins('faint')
ins('fair')
ins('faithful')
ins('fake')
ins('false')
ins('familiar')
ins('famous')
ins('fancy')
... | )
ins('juvenile')
ins('kaleidoscopic')
ins('keen')
ins('key')
ins('kind')
ins('kindhearted')
ins('kindly')
ins('klutzy')
ins('knobby')
ins('knotty')
ins('knowledgeable')
ins('knowing')
ins('known')
ins('kooky')
ins('kosher')
ins('lame')
ins('lanky')
ins('large')
ins('last')
ins('lasting')
ins('late')
ins('lavish')
ins(... | ('left')
ins('legal')
ins('legitimate')
ins('light')
ins('lighthearted')
ins('likable')
ins('likely')
ins('limited')
ins('limp')
ins('limping')
ins('linear')
ins('lined')
ins('liquid')
ins('little')
ins('live')
ins('lively')
ins('livid')
ins('loathsome')
ins('lone')
ins('lonely')
ins('long')
ins('long-term')
ins('loose... |
oring 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_without_comments,
)
from .data impo | rt (
data_context,
)
@dataclasses.dataclass(frozen=True)
class CompletionConfig(metaclass=abc.ABCMeta):
"""Base class for completion configuration."""
name: str
@property
@abc.abstractmethod
def is_default(self):
"""True if the completion entry is only used for defaults, otherwise Fal... |
#!../../../.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 'expe | cted_max_values:', expected_max_values
t0 = time.time()
actual_max_rows = list(np.argmax(a, axis=0))
td = time.time() - t0
actual_max_values = list(np.amax(a, axis=0))
print 'td:', round(td, 4)
print 'actual_max_rows:', actual_max_rows
pri | nt 'actual_max_values:', actual_max_values
assert actual_max_rows == expected_max_rows
assert actual_max_values == expected_max_values
|
"""
pyN | EAT
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 Fre | e 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; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more... |
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)._... | t("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(self, color):
glColor(color[0], color[1 | ], color[2])
glMaterial(GL_FRONT, GL_AMBIENT, color)
glMaterial(GL_FRONT, GL_DIFFUSE, color)
if __name__ == '__main__':
print("Hit ESC key to quit.")
view = GlutViewController()
view.frameTime = 1.0/60.0
view.startFramework()
|
, operator,
"operator should be %r, got %r" % (operator, audit_operator))
eq_(audit_notes, notes,
"notes should be %r, got %r" % (notes, audit_notes))
# Check we've only got one key left (audit_changes):
expected_keys = ['audit_changes']
found_keys = en... | rator="Admin",
flight_deck="Port side")
hot_dog.save()
# Retrieve the log as a check:
initial_log = hot_dog.get_creation_log()
# Make another entry:
hot_dog.fastest_landing = Decimal("99.98")
hot_dog.save()
... | ogs, got %d" % found_logs)
# Now check the creation log:
creation_log = hot_dog.get_creation_log()
eq_(creation_log, initial_log, "Expecting initial log entry to be the "
"same as the creation log. Expected:\n%r,\n\ngot\n%r" %
(initial_log, creation_log))
... |
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:... | presence of new values at this level
L.status.updated = True
# # do the sweep (alternative description)
# for m in range(0, M):
# # build rhs, consisting of the known values from above and new values from previous nodes (at k+1)
# L.u[m + 1] = P.dtype_u(integral[m])
... | j in range(1, m + 1):
# # add QxF(u^{k+1})
# L.u[m + 1].pos += L.dt * (L.dt * self.Qx[m + 1, j] * L.f[j])
#
# # get RHS with new positions
# L.f[m + 1] = P.eval_f(L.u[m + 1], L.time + L.dt * self.coll.nodes[m])
#
# for m in range(0, M):
... |
#!/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))
|
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, view):
widget = model... | objects.get(pk=view.kwargs["widget_pk"])
return IsOwnerOrPublic.has_object_permission(self, request, view, widget)
def has_object_permission(self, request, view, obj):
if request.user == obj.widget.owner:
return True
if request.method in permissions.SAFE_METHODS:
... |
#!/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... | e(".git", "") # Cut off the .git part, so GH will n | ot 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)
continue
els... |
have an even sum.
See Also
--------
is_valid_degree_sequence
Notes
-----
As described by Newman [1]_.
A non-graphical degree sequence (not realizable by some simple
graph) is allowed since this function returns graphs with self
loops and parallel edges. An exception is raised if ... | etworks",
SIAM REVIEW 45-2, pp 167-256, 2003.
Exampl | es
--------
>>> from networkx.utils import powerlaw_sequence
>>> z=nx.utils.create_degree_sequence(100,powerlaw_sequence)
>>> G=nx.configuration_model(z)
To remove parallel edges:
>>> G=nx.Graph(G)
To remove self loops:
>>> G.remove_edges_from(G.selfloop_edges())
"""
if sum(d... |
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... | strict dependency, we issue a warning when it is not
# available.
try:
from Cython.Distutils import build_ext
cython_available = True
except ImportError:
warnings.warn("Cython was not found and hence pylearn2.utils._window_flip "
"and pyle | arn2.utils._video and classes that depend on them "
"(e.g. pylearn2.train_extensions.window_flip) will not be "
"available")
cython_available = False
if cython_available:
cmdclass = {'build_ext': build_ext}
ext_modules = [Extension("pylearn2.utils._window_flip",
... |
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,
sele | ct,
text,
)
from formatters import (
pretty_html | ,
pretty_spec
)
|
# Copyright 2015 Google 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.
# Yo | u may obtain a copy of the License at
#
# http://www.a | pache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# li... |
import uuid
from google.appengine.api import memcache
|
cla | ss CollectionCache:
def __init__(self, timeout=480, hash=None):
self.contents = [];
if hash:
self.contents = memcache.get(hash)
self.timeout = timeout
def add(self, item):
hash = uuid.uuid1().hex
memcache.add(hash, item, time = self.timeout)
self.co... |
from pygame import *
'''
The music 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 inpu | t() == 'pause':
break; |
the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
#
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'com... | description:
- Specify desired state of the resource.
default: present
choices: ['present','absent']
'''
EXAMPLES = '''
- name: mlag interface module test
hosts: cloud | engine
connection: local
gather_facts: no
vars:
cli:
host: "{{ inventory_hostname }}"
port: "{{ ansible_ssh_port }}"
username: "{{ username }}"
password: "{{ password }}"
transport: cli
tasks:
- name: Set interface mlag error down
ce_mlag_interface:
interface: 10G... |
"""
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 CONF_NAME
from homeassistant.helpers.ent... | Return the name of the sensor."""
return self._name
@property
def state(self):
"""Return the state of the sensor."""
return self._state
@property
def unit_of_measurement(self):
"""Return the unit of measurement of this entity, if any."""
return "µg/m³"
def ... | self._state = self._collector.read_data()[self._pmname]
except KeyError:
_LOGGER.error("Could not read PM%s value", self._pmname)
def should_poll(self):
"""Sensor needs polling."""
return True
|
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(va... | es.items()))
return Http | Response(var_catalog, content_type = 'text/javascript') |
# 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 Soft | ware Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# sixoclock is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for mo... |
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... | >')
def taskstatus(task_id):
task = long_task.AsyncResult(task_id)
if task.state == 'PENDING':
response = {
'state': task.state,
'current': 0,
'total': 1,
'status': 'Pending...'
}
elif task.state != | 'FAILURE':
response = {
'state': task.state,
'current': task.info.get('current', 0),
'total': task.info.get('total', 1),
'status': task.info.get('status', '')
}
if 'result' in task.info:
response['result'] = task.info['result']
els... |
#
# 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... | mitations under the License.
#
# pytype: skip-file
import logging
import math
import time
from apache_beam.metrics.metric import Metrics
from apitools.base.py import exceptions
from apitools.base.py import http_wrapper
from apitools.base.py import util
_LOGGER = logging.getLogger(__name__)
class GcsIOOverrides(ob | ject):
"""Functions for overriding Google Cloud Storage I/O client."""
_THROTTLED_SECS = Metrics.counter('StorageV1', "cumulativeThrottlingSeconds")
@classmethod
def retry_func(cls, retry_args):
# handling GCS download throttling errors (BEAM-7424)
if (isinstance(retry_args.exc, exceptions.BadStatusCo... |
#!/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 = ['=', '<', '>', '==', '>=', '<=', '!=', '+', '-', '*', '... | self.right = binary_tree(value)
def __contains__(self, value):
"""
Search for `value` in the tree.
"""
if value == self.value:
return True
return (self.left and value in self.left) or (self.right and value in self.right)
def index(self, v | alue):
"""
Return the parent and sibling node of `value`. Return None if it is not found,
and (None, None) for root node.
"""
if self.value == value:
return (None, None)
if self.right and value == self.right.value:
return self.value, self.l... |
import logging
from ..direc | tives 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
Stanza instances have a `head... | ection_name
self.header = section_name
self.lines = []
def add_lines(self, lines):
"""
Simple helper method for adding multiple lines at once.
"""
for line in lines:
self.add_line(line)
def add_line(self, line):
"""
Adds a given line ... |
ssh:// from url
url = url.lstrip("ssh://")
# get port
port, url = _extract_ssh_port_url(url)
args = (_rsync_exec, "--no-motd", "--compress", "--progress",
"--stats", "--inplace", "--timeout=%d" % (self.__timeout,),
"-e", "ssh -p %s" % (port... | bytes_read = int(bytes_read)
except ValueError:
bytes_read = 0
try:
average = int(pct.strip("%"))
except ValueError:
average = 0
# update progress info
# _rsync_commit
self.__downloadedsiz... | elf.__average = average
self._update_speed()
if self.__show_speed:
self.handle_statistics(self.__th_id, self.__downloadedsize,
self.__remotesize, self.__average, self.__oldaverage,
self.__updatestep, self.__show_speed, self.__datatransfer,... |
"""
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 version 3 of the License, or
(at your option) an | y later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the G... |
s['msg'] = 'One or more items failed'
else:
res['msg'] = 'All items completed'
else:
res = dict(changed=False, skipped=True, skipped_reason='No items in the list', results=[])
else:
display.debug("calling self._e... | l need to default it back to 'item'
loop_var = self._task.loop_control.loop_var or 'item'
if loop_var in task_vars:
raise AnsibleError("the loop variable '%s' is already in use. You should set the `loop_var` value in the `loop_control` option for the task to something else to avoid var... | items = self._squash_items(items, loop_var, task_vars)
for item in items:
task_vars[loop_var] = item
try:
tmp_task = self._task.copy()
tmp_play_context = self._play_context.copy()
except AnsibleParserError as e:
results.ap... |
__au | thor__ = 'sandro'
from distutils.core import setup
setup(
author='Sandro Covo',
author_email="sandro@covo.ch",
packages=['brainfuck'],
scripts=['scripts/pyfuck'],
name="Pyfuc | k",
description="Brainfuck interpreter written in python"
) |
#-*- coding: utf- | 8 -*-
| |
#!/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... | .decode('utf-8')
self.soup = BeautifulSoup(self.html, 'html.parser')
self.num_results = None
for f in self.soup.find_all('strong'):
if 'αγγελίες' in f.text:
if f.text.split()[0].isdigit():
self.num_results = int(f.text.split()[0])
def parse(se... | -item clsfd_list_row'):
yield str(int(a.get('href').replace('/', '').split('-')[0].replace('classifiedscarsview', '')))
def __len__(self):
return self.num_results
class CarItemParser:
def __init__(self, car_id):
self.car_id = car_id
self.req = Request(
'https:/... |
import requests
import time
from selenium import webdriver
# file path
import os
BASE_DIR = os.path.dirname(__file__)
phjs_pa | th = os.path.join(BASE_DIR,'login.phjs.js')
print ('*******'+phjs_path+'*******')
driver = webdriver.PhantomJS(executable_path= | phjs_path)
driver.get('http://autoinsights.autodmp.com/user/login')
time.sleep(3)
print(driver.find_element_by_tag_name('form').text)
driver.close() |
# 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 ... | 'system': self.system} | )
elif self.system == 'urn:xccdf:scoring:absolute':
scores = {}
for item_id in benchmark.items:
item = benchmark.items[item_id]
if not isinstance(item, GroupType) \
and not isinstance(item, RuleType):
continue
... |
__author__ = 'Archana V | Menon, | Sujith V'
|
"""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... | visualize.
render: Whether to render the simulation.
"""
super(MinitaurBallGymEnv, self).__init__(urdf_root=urdf_root,
self_collision_enabled=self_collision_enabled,
pd_control_enabled=pd_control_enabled,
... | render=render)
self._cam_dist = 2.0
self._cam_yaw = -70
self._cam_pitch = -30
self.action_space = spaces.Box(np.array([-1]), np.array([1]))
self.observation_space = spaces.Box(np.array([-math.pi, 0]), np.array([math.pi, 100]))
def reset(self):
self._ball_... |
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):
... |
mock.sentinel.verbose,
mock.sentinel.jvm_opts,
)
def test__build_storm_cmd_no_port(self, cluster):
cluster.nimbus_host = "test-host"
c | luster.nimbus_port = None
storm_cmd = cluster._build_storm_cmd(["a", "cmd"])
assert storm_cmd == [mock.sentinel.storm_cmd_path, "a", "cmd", "-c",
"nimbus.host=test-host"]
def test__build_storm_cmd_with_port(self, cluster):
cluster.nimbus_host = "test-host"
... |
#
# 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 d | ocumentation
# files (the "Software"), to deal in the Software without restriction,
# including 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... | 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. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY... |
# 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... | :
_logger.warning("Unknown data type '%s': %r", data_type, data)
except Queue.Empty as e:
pass
def sta | rt(self):
self._main()
def stop(self):
if self._running:
_logger.debug("Stoping ant.easy")
self._running = False
self.ant.stop()
self._worker_thread.join()
|
://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, either version 3 of the License, or
# (at your option) any later version.
#
# SickRage is distributed in | the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with SickRage. If not, see <ht... |
cense for more details.
#
# You should have received a copy of the GNU General Public License
# along with qutebrowser. If not, see <http://www.gnu.org/licenses/>.
"""Tests for qutebrowser.utils.urlmatch.
The tests are mostly inspired by Chromium's:
https://cs.chromium.org/chromium/src/extensions/common/url_pattern_... | match_subdomains
assert not up._match_all
assert up._path == r'/foo-bar\*baz'
@pytest.mark.parametrize('url, expected', [
# We use - instead of ? so it doesn't get treated as query
(r"file:///foo-bar\hellobaz", True),
(r"file:///fooXbar\hell | obaz", False),
])
def test_urls(self, up, url, expected):
assert up.matches(QUrl(url)) == expected
class TestMatchIpAddresses:
@pytest.mark.parametrize('pattern, host, match_subdomains', [
("http://127.0.0.1/*", "127.0.0.1", False),
("http://*.0.0.1/*", "0.0.1", True),
])
... |
"""
PASSIVE Plugin for Tes | ting_for_SSL-TLS_(OWASP-CM-001)
"""
from framework.dependency_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").GetResourc... | nt
|
#!/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 redistribute it and/or modify
it under the terms of the GNU General Publi | c 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 the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR ... | General Public License along
with this program. If not, see http://www.gnu.org/licenses/gpl-3.0.html
"""
class Countries_Greece():
'''Class that manages this specific menu context.'''
def open(self, plugin, menu):
menu.add_xplugins(plugin.get_xplugins(dictionaries=["Channels",
"Even... |
# -*- 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._... | out=10)
except requests.exceptions.ReadTimeout:
msg.reply('URL Timeout')
return
content_type, params = cgi.parse_header(r.headers['Content-Type'])
if not content_type in content_types:
return
r.encoding = 'utf-8'
if 'charset' in params:
... | = TitleParser()
for line in r.iter_lines(chunk_size=1024, decode_unicode=True):
parser.feed(line)
if parser.title:
break
msg.reply('\x031,0URL\x03 %s' % parser.title)
|
# 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... | IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE... |
ENTITY_CONDITIONS
from homeassistant.const import STATE_ON, STATE_OFF, CONF_PLATFORM
from homeassistant.setup import async_setup_component
import homeassistant.components.automation as automation
from homeassistant.helpers import device_registry
import homeassistant.util.dt as dt_util
from tests.common import (
M... | ass.async_block_till_done()
assert len(calls) == 0
# Time travel 10 secs into the future
mock_utcnow.return_value = point2
hass.bus.async_fire("test_event1")
await hass.async_block_till_done()
assert len(calls) == 0
hass.states.async_set(sensor1.entity_id, STATE... | nc_block_till_done()
assert len(calls) == 0
# Time travel 20 secs into the future
mock_utcnow.ret |
from PyQt4.QtGui import QFileDialog
def get_pcv_filename():
"""Opens the P | CV file with a QFileDialog."""
return QFileDialog.getOpenFileName(None,
"Open Pcoords graph", "",
"Pcoords Files (*.pgdl * | .pcv)")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.