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 |
|---|---|---|---|---|---|---|---|---|
nerosketch/djing | agent/commands/dhcp.py | Python | unlicense | 2,115 | 0.000473 | from typing import Optional
from django.core.exceptions import MultipleObjectsReturned
from abonapp.models import Abon
from devapp.models import Device, Port
def dhcp_commit(client_ip: str, client_mac: str,
switch_mac: str, switch_port: int) -> Optional[str]:
try:
dev = Device.objects.get(... | '
if client_ip == abon.ip_address:
return 'Ip has already attached'
abon.attach_ip_addr(client_ip, strict=False)
if abon.is_access():
r = abon.nas_sync_self()
return r if r else None
else:
return 'User %s is not access to service' % abon.us... | % switch_mac
except Device.DoesNotExist:
return 'Device with mac %s not found' % switch_mac
except Port.DoesNotExist:
return 'Port %(switch_port)d on device with mac %(switch_mac)s does not exist' % {
'switch_port': int(switch_port),
'switch_mac': switch_mac
}
... |
mrinalpande/Music_Encrypt | misc/text.py | Python | mit | 73 | 0.041096 | def main():
| f = open("test.txt","w")
f.writ | e("A"*10000000)
main() |
kho/mr-cdec | python/pkg/cdec/sa/extract.py | Python | apache-2.0 | 4,239 | 0.00519 | #!/usr/bin/env python
import sys
import os
import re
import gzip
import argparse
import logging
import signal
import multiprocessing as mp
import cdec.sa
from cdec.sa._sa import monitor_cpu
extractor, prefix = None, None
online, compress = False, False
def make_extractor(args):
global extractor, prefix, online, c... | racting grammars
if online:
extractor.add_instance(sentence, reference, alignment)
grammar_file = os.path.abspath(grammar_file)
return '<seg grammar="{}" id="{}">{}< | /seg>{}'.format(grammar_file, i, sentence, suffix)
def main():
global online
logging.basicConfig(level=logging.INFO)
parser = argparse.ArgumentParser(description='Extract grammars from a compiled corpus.')
parser.add_argument('-c', '--config', required=True,
help='extractor conf... |
enthought/python-analytics | python_analytics/events.py | Python | bsd-3-clause | 583 | 0 | from __future__ import absolute_import, unicode_literals
from six import add_metaclass, text_type
from .event_en | coder import Parameter, EventEncoder
@add_metaclass(EventEncoder)
class Event(object):
hit = Parameter('t', text_type, required=True)
category = Parameter('ec', text_type, required=True)
action = Parameter('ea', text_type, required=True)
label = Parameter('el', text_type)
value = Parameter('ev', ... | for name, value in kwargs.items():
setattr(self, name, value)
|
UstadMobile/eXePUB | twisted/test/test_lockfile.py | Python | gpl-2.0 | 1,423 | 0.003514 | # Copyright (c) 2005 Divmod, Inc.
# See LICENSE for details.
from twisted.trial import unittest
from twisted.python import l | ockfile
class LockingTestCase(unittest.TestCase):
def testBasics(self):
lockf = self.mktemp()
lock = lockfile.FilesystemLock(lockf)
self.failUnless(lock.lock())
self.failUnless(lock.clean)
lock.unlock()
self.failUnless(lock.lock())
self.failUnless(lock.clean)... | tProtection(self):
lockf = self.mktemp()
lock = lockfile.FilesystemLock(lockf)
self.failUnless(lock.lock())
self.failUnless(lock.clean)
self.failIf(lock.lock())
lock.unlock()
def testBigLoop(self):
lockf = self.mktemp()
lock = lockfile.FilesystemLock... |
geodrinx/gearthview | ext-libs/twisted/trial/_dist/test/test_distreporter.py | Python | gpl-3.0 | 2,019 | 0.001981 | # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Tests for L{twisted.trial.distreporter}.
"""
from cStringIO import StringIO
from twisted.trial._dist.distreporter import DistReporter
from twisted.trial.unittest import TestCase
from twisted.trial.reporter import TreeReporter
class DistRe... | (self.stream.getvalue(), "")
def test_forwardedMethods(self):
"""
Calling methods of L{DistReporter} add calls to the running queue of
the test.
"""
self.distReporter.startTest(self.test)
self.di | stReporter.addFailure(self.test, "foo")
self.distReporter.addError(self.test, "bar")
self.distReporter.addSkip(self.test, "egg")
self.distReporter.addUnexpectedSuccess(self.test, "spam")
self.distReporter.addExpectedFailure(self.test, "err", "foo")
self.assertEqual(len(self.distR... |
BoPeng/simuPOP | docs/statGenoFreq.py | Python | gpl-2.0 | 1,692 | 0.004728 | #!/usr/bin/env python
#
# $File: statGenoFreq.py $
#
# This file is part of simuPOP, a forward-time population genetics
# simulation environment. Please visit http://simupop.sourceforge.net
# for details.
#
# Copyright (C) 2004 - 2010 Bo Peng ([email protected])
#
# This program is free software: you can redistribu... | see <http://www.gnu.org/licenses/>.
#
# This script is an example in the simuPOP u | ser's guide. Please refer to
# the user's guide (http://simupop.sourceforge.net/manual) for a detailed
# description of this example.
#
import simuPOP as sim
pop = sim.Population(100, loci=[1, 1, 1], lociNames=['A', 'X', 'Y'],
chromTypes=[sim.AUTOSOME, sim.CHROMOSOME_X, sim.CHROMOSOME_Y])
sim.initGenotype(pop, fre... |
aldebaran/qibuild | python/qitoolchain/test/test_qipackage.py | Python | bsd-3-clause | 9,535 | 0.000839 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2012-2021 SoftBank Robotics. All rights reserved.
# Use of this source code is governed by a BSD-style license (see the COPYING file).
""" Test QiPackage """
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ impor... | ")
foo_xml = foo1.join("package.xml")
foo_xml.write("""<package name="foo" version="0.1"/>""")
foo1.ensure("include", "foo.h", file=True)
foo1.ensure("lib", "libfoo.so", file=True)
| package = qitoolchain.qipackage.QiPackage("foo", path=foo1.strpath)
dest = tmpdir.join("dest")
package.install(dest.strpath)
assert dest.join("include", "foo.h").check(file=True)
assert dest.join("lib", "libfoo.so").check(file=True)
assert not dest.join("package.xml").check(file=True)
def test_r... |
111pontes/ydk-py | cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_rgmgr_cfg.py | Python | apache-2.0 | 35,273 | 0.020696 | """ Cisco_IOS_XR_rgmgr_cfg
This module contains a collection of YANG definitions
for Cisco IOS\-XR rgmgr package configuration.
This module contains definitions
for the following management objects\:
redundancy\-group\-manager\: Redundancy Group Manager
Configuration
Copyright (c) 2013\-2016 by Cisco Systems,... | Redundancy Group Configuration
**type**\: list of :py:class:`Group <ydk.models.cisco_ios_xr.Cisco_IOS_XR_rgmgr_cfg.RedundancyGroupManager.Aps.Groups.Group>`
"""
_prefix = 'rgmgr-cfg'
_revision = '2015-07-30'
def __init__(se... | self.group.name = 'group'
class Group(object):
"""
Redundancy Group Configuration
.. attribute:: group_id <key>
The redundancy group ID
**type**\: int
**r... |
suyashphadtare/vestasi-erp-jan-end | erpnext/accounts/report/bank_reconciliation_statement/bank_reconciliation_statement.py | Python | agpl-3.0 | 2,556 | 0.024257 | # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
from frappe.utils import flt
from frappe import _
def execute(filters=None):
if not filters: filters = {}
columns = get_columns()
... | filters.get("account"): return columns, []
data = get_entries(filters)
from erpnext.accounts.utils import get_balance_on
balance_as_per_system = get_balance_on(filters["account"], filters["report_date"])
total_debit, total_credit = 0,0
for d in data:
total_debit += flt(d[2])
total_credit += flt(d[3])
amou... | ct sum(ifnull(jvd.debit, 0) - ifnull(jvd.credit, 0))
from `tabJournal Voucher Detail` jvd, `tabJournal Voucher` jv
where jvd.parent = jv.name and jv.docstatus=1 and jvd.account=%s
and jv.posting_date > %s and jv.clearance_date <= %s
""", (filters["account"], filters["report_date"], filters["report_date"]))
am... |
wevote/WeVoteServer | voter/controllers_contacts.py | Python | mit | 10,847 | 0.003227 | # voter/controllers_contacts.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
from dateutil import parser
from wevote_functions.functions import positive_value_exists
from .models import VoterContactEmail, VoterManager
def assemble_contact_display_name(
first_name=None,
last_name=None,... | turn results
def get_voter_contact_email_value(voter_contact_email=None, best_option='', fallback_option=''):
if hasattr(voter_contact_email, best_option) and positive_value_exists(getattr(voter_contact_email, best_option)):
return getattr(voter_contact_email, best_option | )
else:
return getattr(voter_contact_email, fallback_option)
def voter_contact_list_retrieve_for_api(voter_we_vote_id=''): # voterContactListRetrieve
status = ''
voter_manager = VoterManager()
voter_contact_results = voter_manager.retrieve_voter_contact_email_list(
imported_by_voter_w... |
colorisa/openacademy-proyect | openacademy/model/partner.py | Python | apache-2.0 | 392 | 0.02551 | # -*- coding: utf-8 -*-
from openerp import fields, models
class Partner(models.Model):
_inherit = 'res.partner'
# Le agrego una nueva columna al modelo res.partner, por defecto los partner
# no son instructores
instructor = fields.Boo | lean("Instructor", default=False)
session_ids = fields.Many2many('openacademy.session',
strin | g="Attended Sessions", readonly=True) |
PaulSD/cgroupsd | lib/cgroupsd_listener.py | Python | gpl-3.0 | 12,128 | 0.013522 | #!/usr/bin/env python
#
# Copyright 2015 Paul Donohue <[email protected]>
#
# 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 vers... | at the same time, however it may handle a process and its threads differently if
# necessary. If necessary, this callback is responsible for creating and configuring cgroups
# before assigning processes to them. When practical, any created cgroups should be namespac | ed to
# allow an associated "cleanup" callback to identify and remove only the relevant cgroups. See
# http://www.freedesktop.org/wiki/Software/systemd/PaxControlGroups/ for additional cgroups
# rules/conventions.
# Note that any new processes spawned by this callback will trigger additional calls to this
# ... |
BSI-CERT-Bund/cortex-analyzers | analyzers/GoogleSafebrowsing/safebrowsing.py | Python | agpl-3.0 | 2,689 | 0.004091 | import json
import requests
class SearchTypeNotSupportedError(Exception):
pass
class SafebrowsingClient:
"""Simple API to Google Safebrowsing and historic.
:param key: API key for google safebrowsing
:param client_id: ClientId for Safebrowsing API
:param client_version: ClientVersion for Safebr... | # TODO: Only found threatEntry 'url' in the docs. What to use for ip_range?
data['threatEntries'] = [{'url': search_value}]
body['threatInfo'] = data
return body
def __query_safebrowsing(self, search_value: str, search_type: str):
return json.loads(
self.sessio... | search_type=search_type
)
).text
)
def query_url(self, url):
return self.__query_safebrowsing(search_value=url, search_type='url')
# TODO: Add another function for querying IPs
#def query_ip(self, ip):
# return self.__query_safebrow... |
jni/networkx | networkx/algorithms/components/tests/test_biconnected.py | Python | bsd-3-clause | 6,615 | 0.037793 | #!/usr/bin/env python
from nose.tools import *
import networkx as nx
from networkx.algorithms.components import biconnected
from networkx import NetworkXNotImplemented
def assert_components_equal(x,y):
sx = set((frozenset([frozenset(e) for e in c]) for c in x))
sy = set((frozenset([frozenset(e) for e in c]) fo... | h([(1,3),(1,5),(3,4),(4,5)])))
assert_true(nx.is_isomorphic(g2,nx.Graph([(0,1),(0,2),(1,2)])))
assert_equal(g1[1][3]['eattr'],'red')
assert_equal(g1.node[1]['nattr'],'blue')
assert_equal(g1.graph['gattr'],'green')
g1[1][3]['eattr']='blue'
assert_equal(g1[1][3]['eattr'],'b... | gorithm.html
edges=[(0,1),
(0,5),
(0,6),
(0,14),
(1,5),
(1,6),
(1,14),
(2,4),
(2,10),
(3,4),
(3,15),
(4,6),
(4,7),
(4,10),
(5,14),
(6,14),
(... |
kYc0o/RIOT | tests/pkg_wolfcrypt-ed25519-verify/tests/01-run.py | Python | lgpl-2.1 | 192 | 0 | #!/usr/bin/env python3
import sys
from testrunner imp | ort run
def testfunc(child):
child.expect_exact("The signature is valid!")
if __name__ == "__main__":
sys.exit(run(testf | unc))
|
topaz1874/srvup | src/notification/views.py | Python | mit | 3,083 | 0.011028 | import json
from django.http import HttpResponse
from django.shortcuts import render,Http404,HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required
from .models import Notifications
# Create your views here.
@login_required
def all(request):
obje... | ote.action_object and not target_url:
| url_lst.append(
("%s"%note.recipient,
"%(sender)s %(verb)s %(target)s with %(action)s" %context,
"%s"%note.read))
elif note.target_object and not note.action_object and not target_url:
url_lst.append(
("%s"%note.... |
dbarbier/privot | python/test/t_SymmetricMatrix_std.py | Python | lgpl-3.0 | 4,523 | 0.018351 | #! /usr/bin/env python
from openturns import *
from math import *
TESTPREAMBLE()
try :
# TEST NUMBER ZERO : DEFAULT CONSTRUCTOR AND STRING CONVERTER
print "test number zero : default constructor and string converter"
# Default constructor
symmetricMatrix0 =Sy | mmetricMat | rix()
# String converter
print "symmetricMatrix0 = " , repr(symmetricMatrix0)
# TEST NUMBER ONE : CONSTRUCTOR WITH SIZE, OPERATOR() AND STRING CONVERTER
print "test number one : constructor with size, operator() and string converter"
# Constructor with size
symmetricMatrix1 = SymmetricMatr... |
potatosushi/Discord-Notification-Bot | discord/server.py | Python | mit | 13,502 | 0.001926 | # -*- coding: utf-8 -*-
"""
The MIT License (MIT)
Copyright (c) 2015-2016 Rapptz
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 r... | |
+-----------+--------------------------------------+
| x != y | Checks if two servers are not equal. |
+-----------+--------------------------------------+
| hash(x) | Returns the serve | r's hash. |
+-----------+--------------------------------------+
| str(x) | Returns the server's name. |
+-----------+--------------------------------------+
Attributes
----------
name : str
The server name.
me : :class:`Member`
Similar to :a... |
amcat/amcat | api/rest/tests/test_renderer.py | Python | agpl-3.0 | 2,580 | 0.003488 | ###########################################################################
# (C) Vrije | Universiteit, Amsterdam (the Netherl | ands) #
# #
# This file is part of AmCAT - The Amsterdam Content Analysis Toolkit #
# #
# AmCAT is free software: you can redistribute it and/or modify it under ... |
bryanveloso/avalonstar-tv | apps/subscribers/management/commands/updatetickets.py | Python | apache-2.0 | 2,623 | 0.00305 | # -*- coding: utf-8 -*-
import logging
logger = logging.getLogger(__name__)
import requests
import os
from django.core.management.base import NoArgsCommand
from apps.subscribers.models import Ticket
class Command(NoArgsCommand):
help = 'Loops through all subscribers and marks each ticket appropriately.' |
def handle_noargs(self, **o | ptions):
# Prepare our request.
headers = {
'Authorization': 'OAuth %s' % os.environ.get('TWITCH_OAUTH_TOKEN'),
'Accept': 'application/vnd.twitchtv.v3+json' }
url = 'https://api.twitch.tv/kraken/channels/avalonstar/subscriptions'
# Let's not invalidate anything u... |
joshsmith2/superlists | lists/tests/test_views.py | Python | gpl-2.0 | 5,826 | 0.001202 | from django.core.urlresolvers import resolve
from django.template.loader import render_to_string
from django.test import TestCase
from django.http import HttpRequest
from django.utils.html import escape
from unittest import skip
from lists.views import home_page
from lists.models import Item, List
from lists.forms im... | response = self.client.get('/lists/%d/' % (list_.id))
self.assertIsInstance(response.context['form'], ExistingListItemForm)
self.assertContains(response, 'name="text"')
class NewListTest(TestCase):
def test_saving_a_POST_request(self):
self.client.post(
'/lists/new',
... | self.assertEqual(Item.objects.count(), 1)
new_item = Item.objects.first()
self.assertEqual(new_item.text, 'A new list item')
def test_redirects_after_POST(self):
response = self.client.post(
'/lists/new',
data={'text':'A new list item'}
)
new_li... |
sbidoul/buildbot | master/buildbot/test/unit/test_www_service.py | Python | gpl-2.0 | 10,362 | 0.000579 | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without eve... | heck(_):
| self.assertNotEqual(self.svc.site, None)
self.assertNotEqual(self.svc.port_service, None)
self.assertEqual(self.svc.port, 20)
return d
def test_reconfigService_expiration_time(self):
new_config = self.makeConfig(port=80, cookie_expiration_time=datetime.timedelta(mi... |
chrisspen/asklet | asklet/settings.py | Python | lgpl-3.0 | 348 | 0 | from django.conf | import settings
from . import constants as c
# Where the data, primarily the weights, are stored.
settings.ASKLET_BACKEND = getattr(
settings,
'ASKLET_BACKEND',
c.SQL)
# What mechanism we use to calculate ranks.
# Dependent on backend.
settings.ASKLET_RANKER = getattr(
settings,
'ASKLET_RANKER',... | SQL)
|
NewpTone/hotzenplotz | hotzenplotz/db/sqlalchemy/session.py | Python | apache-2.0 | 4,028 | 0 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2013 xxxx Corporation
# All Rights Reserved.
# Author: Yu xingchao <[email protected]>
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the L... | sql_max_retries -= 1
time.sleep(rec | onnect_interval)
return _ENGINE
def get_session(autocommit=True, expire_on_commit=True):
"""Helper method to grab session"""
global _MAKER, _ENGINE
if not _MAKER:
engine = get_engine()
_MAKER = orm.sessionmaker(bind=engine,
autocommit=autocommit,
... |
Ichaelus/Github-Classifier | Application/Models/ClassificationModules/foldernameslstm.py | Python | mit | 3,635 | 0.006059 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from Models.FeatureProcessing import *
from keras.models import Sequential
from keras.layers import Activation, Dense, LSTM
from keras.optimizers import Adam, SGD
import numpy as np
import abc
from ClassificationModule import ClassificationModule
class foldernameslstm(Cla... | ta(sample)
return np.argmax(self.model.predict(sample))
def predictLabelAndProbability(self, sample):
"""Return the probability the module assignes each label"""
if not self.isTrained:
return [0, 0, 0, 0, 0, 0, 0, 0]
sample = self.formatInputData(samp | le)
prediction = self.model.predict(sample)[0]
return [np.argmax(prediction)] + list(prediction) # [0] So 1-D array is returned
def formatInputData(self, sample):
"""Extract description and transform to vector"""
sd = getFoldernames(sample)
# Returns numpy array which contai... |
pgularski/snippets | python/algorithms/topsort.py | Python | mit | 1,733 | 0.00058 | #!/usr/bin/env python
# −*− coding: UTF−8 −*−
# To | pological Sorting
from collections import defa | ultdict
def topsort(graph):
if not graph:
return []
# 1. Count every node's dependencies
count = defaultdict(int)
for node in graph:
for dependency in graph[node]:
count[dependency] += 1
# 2. Find initial nodes - The ones with no incoming edges, so the ones that
# n... |
stdweird/aquilon | tests/broker/test_make.py | Python | apache-2.0 | 20,622 | 0.000485 | #!/usr/bin/env python2.6
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-
# ex: set expandtab softtabstop=4 shiftwidth=4:
#
# Copyright (C) 2009,2010,2011,2012,2013 Contributor
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# Y... | aqd-unittest.ms.com"
out = self.commandtest(command.split(" "))
self.matchoutput(out, "Template: service/netmap/q.ny.ms.com", command)
| def testmakenetmappers_2_maplocsvc_pers(self):
"""Maps a location based personality service map to be overridden by a
network based personality service map"""
self.noouttest(["map", "service", "--building", "ut", "--personality",
"eaitools", "--archetype", "aquilon",
... |
watchdogpolska/poradnia.siecobywatelska.pl | poradnia/cases/migrations/0035_case_jst.py | Python | bsd-3-clause | 635 | 0.001575 | # Generated by Django 1.11.21 on 2019-06-13 17:49
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [("teryt", "0001_initial"), ("cases", "0034_auto_20180104_0436")]
operations = [
migrations.AddField(
model_na... | verbose_name="Unit of administrative division",
),
)
] | |
relic7/prodimages | python/dload_orcl-mysql-server_imgs_byPOorStyleList.py | Python | mit | 5,989 | 0.012692 | #!/usr/bin/env python
import os, sys, re, csv
######################################## ##### ########################################
######################################## Order ########################################
######################################## ##### ########################################
def arg... | ath.join(os.path.abspath(os.curdir), colorstyle + ext_PNG)
#try:
url_download_file(netsrv101_url_file, colorstyle_file)
alt = 0
imgs = []
for x in range(1,6):
try:
alt = x
ext_ALT = '_alt0{0}{1}'.format(str(alt),ext_PNG)
colorstylealt = colorstyl... | alt = os.path.join(os.path.abspath(os.curdir), colorstylealt)
netsrv101_url_filealt = os.path.join(netsrv101_url, colorstyle[:4], colorstylealt)
if urllib.urlretrieve(netsrv101_url_filealt, colorstyle_filealt) == None:
xf = url_download_file(netsrv101_ur... |
halfflat/nestmc-proto | doc/scripts/divio_docs_theme/__init__.py | Python | bsd-3-clause | 352 | 0 | from os impor | t path
__version__ = '0.0.22'
__version_full__ = __version__
def get_html_theme_path():
"""Return list of HTML theme paths."""
cur_dir = path.abspath(path.dirname(path.dirname(__file__)))
return cur_dir
def setup(app):
app.add_html_theme(
'divio_doc | s_theme',
path.abspath(path.dirname(__file__))
)
|
jreiberkyle/Kaggle_Data-Science-London | main.py | Python | bsd-3-clause | 900 | 0.016667 | '''
Created on May 9, 2014
@author: Jennifer Reiber Kyle
'''
from kaggle import Submitter, DataReader
from prediction import Preprocessor, Classifier
def runPrediction(sourceDirectory,submitDirectory):
reader = DataReader(dataDir)
p = Preprocessor(*reader.getData())
submitter = Submitter(submitDir)
... | dictions = classifier.ModelSVM()
submitter.saveSubmission(predictions, "modelSVMSubmission")
if __name__ == '__main__':
dataDir = r"D:\NWR\Kaggle\DataScienceLondon"
submitDir = r"D:\NWR\Kaggle\DataScienceLondon\tut_svm"
runPrediction(dataDir, submitDir | )
|
EricSB/discover | parsers/parse-nessus.py | Python | mit | 6,845 | 0.005844 | #!/usr/bin/env python
#
# Original code from - https://github.com/Clete2/NessusReport, modded by Lee Baird
# John Kim - additional modification completed to support UTF-8, support cli help, renaming output files
# Thanks to Securicon, LLC. for sponsoring development
import csv
import datetime
import re
import sys
impo... | ugin_output")
if(len(pluginElements) >= 1):
detai | ls['plugin_output'] = pluginElements[0].text
solutionElements = reportItem.findall("./solution")
if(len(solutionElements) >= 1):
details['solution'] = solutionElements[0].text
seealsoElements = reportItem.findall("./see_also")
if(len(seealsoElements) >= 1):
deta... |
lesh1k/VKStalk | src/core/models.py | Python | mit | 6,912 | 0.000145 | from __future__ import unicode_literals
from sqlalchemy import create_engine, Column, ForeignKey, Integer, String,\
Boolean, Unicode, Date, DateTime, and_, func
from sqlalchemy.orm import relationship, backref, sessionmaker
from sqlalchemy.engine.url import URL
from sqlalchemy.ext.declarative import declarative_bas... | ose()
return user_url
@property
def last_visit_tex | t(self):
last_log = self.activity_logs[-1]
if last_log.is_online:
last_seen_line = 'Online'
else:
now = pytz.timezone(settings.CLIENT_TZ).localize(datetime.now())
last_visit_in_client_tz = as_client_tz(last_log.last_visit)
minutes_ago = delta_minut... |
jotes/pontoon | pontoon/sync/tests/test_sync_projects.py | Python | bsd-3-clause | 4,440 | 0.001126 | import io
from unittest.mock import ANY, patch, PropertyMock
from django.core.management.base import CommandError
import pytest
from pontoon.base.models import Project
from pontoon.base.tests import ProjectFactory, TestCase
from pontoon.base.utils import aware_datetime
from pontoon.sync.management.commands import sy... | _with(
handle_project.pk, ANY, no_pull=False, no_commit=False, force=False,
)
def test_no_matching_projects(self):
"""
If no projects are found that match the given slugs, raise a
CommandError.
"""
| with pytest.raises(CommandError):
self.execute_command(projects="does-not-exist")
def test_invalid_slugs(self):
"""
If some of projects have invalid slug, we should warn user about them.
"""
handle_project = ProjectFactory.create()
self.execute_command(pr... |
thomasw/djproxy | tests/helpers.py | Python | mit | 399 | 0 | from mock import patch
class RequestPatchMixin(object):
def patch_request(s | elf, mock_proxy_response=None):
"""patches requests.request and sets its return_value"""
request_patcher = patch('djproxy.views.request')
request = request_patcher.start()
request.return_value = mock_proxy_response
self.addCleanup(request_patcher.stop)
return request
| |
camomile-project/camomile-client-python | example/populate.py | Python | mit | 3,552 | 0.002252 | # The MIT License (MIT)
# Copyright (c) 2014-2015 CNRS
# 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 t | he 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 included in all
# copies or substanti... | ANTABILITY, 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, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN T... |
Instanssi/Instanssi.org | Instanssi/common/rest.py | Python | mit | 677 | 0 | # -*- coding: utf-8 -*-
from django.http import HttpResponse
import json
def rest_api(view_func):
def json_view(request, *args, **kwargs):
request.json_data = {}
if request.method == 'POST':
try:
request.json_data = json.loads(request.body)
except ValueErro... | pass
return view_func(request, *args, **kwargs)
json_view.csrf_exempt = True
return json_view
def RestResponse(data=None, code=200, error_text=''):
out = {
'code': code,
'errortext': error_text,
'content': data,
}
return HttpResponse(json.dumps(out), c... | tion/json')
|
ehuggett/send-cli | tests/test_common.py | Python | gpl-3.0 | 3,116 | 0.007702 | from sendclient.common import splitkeyurl
def test_splitkeyurl():
url = 'https://send.firefox.com/download/c8ab3218f9/#39EL7SuqwWNYe4ISl2M06g'
service, urlid, key = splitkeyurl(url)
assert service == 'https://send.firefox.com/'
assert urlid == 'c8ab3218f9'
assert key == '39EL7SuqwWNYe4ISl2M06g'
fro... | debug messages to {"commit":"188b28f" | ,"source":"https://github.com/mozilla/send/","version":"v1.2.4"}
testdata = {
'secretKey': b'q\xd94B\xa1&\x03\xa5<8\xddk\xee.\xea&',
'encryptKey': b'\xc4\x979\xaa\r\n\xeb\xc7\xa16\xa4%\xfd\xa6\x91\t',
'authKey': b'5\xa0@\xef\xd0}f\xc7o{S\x05\xe4,\xe1\xe4\xc2\x8cE\xa1\xfat\xc1\x11\x94e[L\x89%... |
timbroder/ai-stager | stager/jira/forms.py | Python | mit | 771 | 0.006485 | from django import forms
from stager.jira.models import *
from django.utils.functional import lazy
def type_choices():
return [(type.key, type.name) for type in JiraType.objects.filter | (allowed=True)]
class JiraTicketForm(forms.Form):
def __init__(self | , *args, **kwargs):
super(JiraTicketForm, self).__init__(*args, **kwargs)
self.fields['issue_type'] = forms.ChoiceField(choices=type_choices())
self.fields['description'] = forms.CharField(widget=forms.Textarea)
self.fields['steps_to_reproduce'] = forms.CharField(widget=forms.Textarea)
... |
kaldonis/ft-event-manager | src/lib/paste/auth/auth_tkt.py | Python | gpl-2.0 | 16,006 | 0.000375 | # (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org)
# Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
##########################################################################
#
# Copyright (c) 2005 Imaginary Landscape LLC and Contributors.
#
# Permiss... | 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. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT ... | Y CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
##########################################################################
"""
Implementation of cookie signing as done in `... |
jwallen/ChemPy | chempy/species.py | Python | mit | 8,105 | 0.005059 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
################################################################################
#
# ChemPy - A chemistry toolkit for Python
#
# Copyright (c) 2010 by Joshua W. Allen ([email protected])
#
# Permission is hereby granted, free of charge, to any person obtaining a
# co... | lectrons for atom in self.molecule[0].atoms]) > 0:
# Iterate over resonance isomers
index = 0
while index < len(self.molecule):
isomer = self.molecule[index]
newIsomers = isomer.getAdjacentResonanceIsomers()
for | newIsomer in newIsomers:
# Append to isomer list if unique
found = False
for isom in self.molecule:
if isom.isIsomorphic(newIsomer): found = True
if not found:
self.molecule.append(newIsomer)
... |
anhstudios/swganh | data/scripts/templates/object/weapon/mine/shared_wp_mine_xg.py | Python | mit | 434 | 0.048387 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY | BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy. | object import *
def create(kernel):
result = Weapon()
result.template = "object/weapon/mine/shared_wp_mine_xg.iff"
result.attribute_template_id = 10
result.stfName("weapon_name","mine_xg")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
NicovincX2/Python-3.5 | Statistiques/Économétrie/Série temporelle/Damped-driven pendulum/tsa_constants.py | Python | gpl-3.0 | 299 | 0.006689 | # -*- coding: utf-8 -*-
"""
Define the global constants for the problem.
"""
import math
import os
q = 0.5
b0 = 0.9
omega | d = 2.0 / 3.0
l = 9.8
m = 1.0
g = 9.8
tmax = 1000
theta0_degree = 25.0
theta0 = math.radians(theta0_degree)
| dt = 0.05
bstep = 0.05
path = "plots/"
os.system("pause")
|
murphydavis/turbo-bear | forms.py | Python | mit | 4,475 | 0.001788 | from app import app
from fields import PreValidatedFormField
from flask_wtf import Form
from wtforms import (TextField, TextAreaField, FormField, FieldList,
HiddenField, SubmitField)
from wtforms.validators import (DataRequired, Optional, StopValidation)
EMPTY_VALUES = ['', None]
def DynamicList... | again per field (classification)
'''
#metadata = FormField(ReportMetadataForm)
#operators = DynamicListForm(FormField(OperatorForm), min_entries=1)
#description = FormField(DynamicListForm())
def __init__(self, *args, **k | wargs):
super(ReportEntryForm, self).__init__(*args, **kwargs)
#Use a completely separate form to add or remove fields from the page perhaps?
|
1flow/1flow | oneflow/processors/newspaper_common.py | Python | agpl-3.0 | 592 | 0 | # -*- coding: utf-8 -*-
""" 1flow base processor pack (see metadata for details). """
# Always import this, it will giv | e you a bunch of useful things handy.
from oneflow.core.models.reldb.processor.utils import * # NOQA
__all__ = [
'PROC | ESSOR_METADATA',
]
PROCESSOR_METADATA = {
'slug': '1fs-newspaper-common',
'name': u'NewsPaper (common)',
'author': 'Olivier Cortès <[email protected]>',
'version': '1.0',
'requirements': u'''
newspaper==0.0.9.8
''',
'description': u'requirements-only processor for mutualized requirements.',
'cate... |
ruleant/weblate | weblate/trans/models/unitdata.py | Python | gpl-3.0 | 10,092 | 0.000099 | # -*- coding: utf-8 -*-
#
# Copyright © 2012 - 2014 Michal Čihař <[email protected]>
#
# This file is part of Weblate <http://weblate.org/>
#
# 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, eithe... | ='user_votes'
)
objects = SuggestionManager()
class Meta(object):
permissions = (
('accept_suggestion', "Can accept suggestion"),
('override_suggestion', 'Can override suggestion state'),
('vote_suggestion', 'Can vote for suggestion'),
)
app_labe... | self.user.username if self.user else 'unknown',
)
def accept(self, translation, request):
allunits = translation.unit_set.filter(
contentsum=self.contentsum,
)
for unit in allunits:
unit.target = self.target
unit.fuzzy = False
u... |
hashbang/dotfiles | weechat/.weechat/python/otr.py | Python | mit | 75,565 | 0.001906 | # -*- coding: utf-8 -*-
# otr - WeeChat script for Of | f-the-Record IRC messaging
#
# DISCLAIMER: To the best of my knowledge this script securely provides OTR
# messaging in WeeChat, but I offer no guarantee. Please report any security
# holes you find.
#
# Copyright (c) 2012-2015 Matthew M. Boedicker <[email protected]>
# Nils Görs <weechatte... | sues at https://github.com/mmb/weechat-otr
#
# 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 distribu... |
thegreathippo/crispy | crispy/customdicts.py | Python | mit | 2,133 | 0.000469 | from imbroglio import InnerDict
NULL = object()
class CustomDict(InnerDict):
def __repr__(self):
return type(self).__name__ + super().__repr__()
def copy(self):
return type(self)(*self.items())
class CollisionError(ValueError):
def __init__(self, key1, val1, key2, val2):
txt = ... | ear()
self.inverse.clear()
def __setitem__(self, item, value):
if value in self.inverse and self.inverse[value] != item:
item_val = self.get(item, NULL)
raise CollisionError(item, item_val, self.inverse[value], value)
if item in self:
| del self.inverse[self[item]]
super().__setitem__(item, value)
self.inverse[self[item]] = item
def __delitem__(self, item):
value = self[item]
del self.inverse[value]
super().__delitem__(item)
class ReversibleDict(CustomDict):
def __init__(self):
self.in... |
pwong-mapr/private-hue | desktop/libs/hadoop/setup.py | Python | apache-2.0 | 1,344 | 0.014137 | # Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file ex... | ng, 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
# limitations under t | he License.
from setuptools import setup, find_packages
setup(
name = "hadoop",
version = "3.5.0",
url = 'http://github.com/cloudera/hue',
description = "Hadoop Libraries",
# Note that we're cheating by installing gen-py
# in hadoop's __init__.py.
packages = find_packages('sr... |
vortex-ape/scikit-learn | sklearn/externals/joblib/externals/loky/backend/compat.py | Python | bsd-3-clause | 635 | 0 | # flake8: noqa
###############################################################################
# Compat file to | import the correct modules for each platform and python
# version.
#
# author: Thomas Moreau and Olivier grisel
#
import sys
if sys.version_info[:2] >= (3, 3):
import queue
else:
import Queue as queue
from pickle import PicklingError
if sys.version_info >= (3, 4):
from multiprocessing.process import Base... |
# Platform specific compat
if sys.platform == "win32":
from .compat_win32 import *
else:
from .compat_posix import *
|
jmartinm/InvenioAuthorLists | modules/websubmit/lib/functions/Insert_Modify_Record.py | Python | gpl-2.0 | 2,196 | 0.007286 | ## This file is part of Invenio.
## Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 CERN.
##
## Invenio 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.
##
## Invenio is distributed in the hope that it will be useful, but
## WITHOUT ANY WARRANTY; without even the implied warranty of
#... |
vishalkuo/codeStats | utils/writer.py | Python | mit | 636 | 0.004717 | import json
def writeLanguageStats(name, percentages, individual, weights,total):
with open('report.txt', 'w') as outfile:
outfile.write('Total byte | s: ' | + str(total))
outfile.write('\n\nOverall code usage for '+name+':\n')
outfile.write(json.dumps(percentages, indent=1))
outfile.write('\n\nLanguage weights, this is avg(langPercentPerProject)/sum(allAvgs): ')
outfile.write(json.dumps(weights, indent=1))
outfile.write('\n\nBreakdow... |
bike-barn/red-green-refactor | tests/assignment_two/test_calc.py | Python | isc | 2,854 | 0 | import pytest
from calc import INTEGER, EOF, PLUS, Calc, CalcError
def test_calc_raises_error_on_invalid_tokens():
"""
Test that invalid tokens cause a ``CalcError`` and that the exception stack
trace contains useful information.
"""
input_text = "lumberjack" # Now with 100% more Monty Python re... | LUS
def test_parse_supports_addition():
"""Test that a :class:`Calc` can correctly parse the addition operation."""
# Note: This function name was briefly duplicated and therefore didn't run.
input_text = "1+1"
calc = Calc(text=input_text)
assert calc.parse() == 2
def test_parse_sets_eof():
| """
Test that successfully parsing an arithmetic expression sets the
``current_token`` attribute of a :class:`Calc` to EOF.
"""
input_text = "1+1"
calc = Calc(text=input_text)
calc.parse()
assert calc.current_token.type == EOF
def test_parse_raises_error_on_invalid_expression():
"""
... |
ThaTiemsz/jetski | rowboat/plugins/censor.py | Python | mit | 9,546 | 0.001152 | import re
import json
import urlparse
from holster.enum import Enum
from unidecode import unidecode
from disco.types.base import cached_property
from disco.types.channel import ChannelType
from disco.util.sanitize import S
from disco.api.http import APIException
from rowboat.redis import rdb
from rowboat.util.stats i... | event.delete()
self.call(
'ModLogPlugin.log_action_ext',
Actions.CENSORED,
event.guild.id,
e=event,
c=c)
except APIException:
... | ent.content)
if s:
raise Censorship(CensorReason.ZALGO, event, ctx={
'position': s.start()
})
def filter_invites(self, event, config):
invites = INVITE_LINK_RE.findall(event.content)
for _, invite in invites:
invite_info = self.get_invite... |
jdpepperman/baseballStats | Batters.py | Python | gpl-2.0 | 2,886 | 0.043659 | #Joshua Pepperman
class Batters:
def __init__(self):
self.batters = []
def __iter__(self):
return iter(self.batters)
def __getitem__(self, key):
return self.batters[key]
def __len__(self):
return len(self.batters)
def indexOf(self, player):
index = 0
for p in self.batters:
if p == player:
r... | elif 'COL' in team:
rank = 1
elif 'CLE' in team:
rank = 1
elif | 'CIN' in team:
rank = 1
elif 'CHW' in team:
rank = 1
elif 'CHC' in team:
rank = 1
elif 'BOS' in team:
rank = 1
elif 'BAL' in team:
rank = 1
elif 'ATL' in team:
rank = 1
elif 'ARI' in team:
rank = 1
def getBatter(self, playerName):
for player in self.batters:
if player.getStat('na... |
JuniorJPDJ/aerogui | aerogui_config.py | Python | gpl-2.0 | 416 | 0.016827 | #nazwa komendy sluzacej do ponownego polaczenia aero
#reconnect = "reconnects\\android-flightmode\\adb shell < reconnects\\android-flightmode\\reconnect.adb"
reconnect = "reconnects\\windows-rasdial\\rasdial.bat"
#czas co jaki ma byc sprawdzane czy jest juz captcha (sekundy)
sleeptime | = 3
#odleglosc okna captchy od dolnej | krawedzi ekranu
oddolu = 100
#odleglosc okna captchy od prawej krawedzi ekranu
odprawej = 30 |
IntelLabs/numba | numba/cuda/tests/cudapy/test_sm.py | Python | bsd-2-clause | 14,079 | 0.000142 | from numba import cuda, int32, float64, void
from numba.core.errors import TypingError
from numba.cuda.testing import unittest, CUDATestCase, skip_on_cudasim
import numpy as np
from numba.np import numpy_support as nps
from .extensions_usecases import test_struct_model_type, TestStruct
recordwith2darray = np.dtype(... | _dtype(arr.dtype)
@cuda.jit
def use_sm_chunk_copy(x, y):
sm = cuda.shared.array(nthreads, dtype=dt)
tx = cuda.threadIdx.x
bx = cuda.blockIdx.x
bd = cuda.blockDim.x
# Load this block's chunk i | nto shared
i = bx * bd + tx
if i < len(x):
sm[tx] = x[i]
cuda.syncthreads()
# One thread per block writes this block's chunk
if tx == 0:
for j in range(nthreads):
y[bd * bx + j] = sm[j]
d_result = ... |
proxeIO/name-panel | addon/interface/operator/shared.py | Python | gpl-3.0 | 1,967 | 0.001017 |
# sort
def sort(layout, option):
# separate
layout.separator()
# row
row = layout.row(align=True)
# sub
sub = row.row(align=True)
# scale x
sub.scale_x = 0.2
# sort
sub.prop(option, 'sort', toggle=True)
# sub sub
subsub = sub.row(align=True)
# active
subsub.ac... | icon = 'LINKED' if option.link else 'UNLINKED'
# link
subsub.prop(option, 'link', text='', icon=icon)
# pad
subsub.prop(option, 'pad', text='Pad')
# | start
subsub.prop(option, 'start', text='Start')
# step
subsub.prop(option, 'step', text='Step')
# sub
subsubsub = subsub.row(align=True)
# scale
subsubsub.scale_x = 0.1
# separate
subsubsub.prop(option, 'separator', text='')
# ignore
# subsub.prop(option, 'ignore', text... |
nicoechaniz/IPP | bdd/features/environment.py | Python | agpl-3.0 | 3,472 | 0.004616 | # IPP, Plataforma web del Índice de Precios Popular
# Copyright (c) 2016 Nicolás Echániz and contributors.
#
# This file is part of IPP
#
# IPP 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 Foun... |
context.MARCA_POR_DEFECTO = "UnaMarca"
def after_all(context):
context.browser.quit()
context.browser = None
def after_step(context, step):
if step.status == "failed":
# -- SOLUTION: But note that step.exc_info | does not exist, yet.
import ipdb
ipdb.post_mortem(step.exc_traceback)
|
Teino1978-Corp/pycallgraph | pycallgraph/pycallgraph.py | Python | gpl-2.0 | 2,634 | 0 | import locale
from .output import Output
from .config import Config
from .tracer import AsyncronousTracer, SyncronousTracer
from .exceptions import PyCallGraphException
class PyCallGraph(object):
def __init__(self, output=None, config=None):
'''output can be a single Output instance or an iterable with m... | put.done()
def add_output(self, output):
self.output.append(output)
self.prepare_output(output)
def prepare_output(self, output):
output.sanity_check()
output.set_processor(self.tracer.processor)
output.r | eset()
|
seewindcn/tortoisehg | src/tortoisehg/hgqt/messageentry.py | Python | gpl-2.0 | 9,500 | 0.001368 | # messageentry.py - TortoiseHg's commit message editng widget
#
# Copyright 2011 Steve Borho <[email protected]>
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2, incorporated herein by reference.
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from ... | e('msgentry/lexer', True).toBool():
self.setLexer(QsciLexerMakefile(self))
self.lexer().setColor(QC | olor(Qt.red), QsciLexerMakefile.Error)
self.lexer().setFont(font)
else:
self.setLexer(None)
self.setFont(font)
@pyqtSlot(QPoint)
def menuRequested(self, point):
menu = self._createContextMenu(point)
menu.exec_(self.viewport().mapToGlobal(point))
... |
shimpe/frescobaldi | frescobaldi_app/qpopplerview/locking.py | Python | gpl-2.0 | 1,381 | 0.002896 | # This file is part of the qpopplerview package.
#
# Copyright (c) 2010 - 2014 by Wilbert Berendsen
#
# 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 yo... | er.Document inst | ances.
"""
import threading
import weakref
_locks = weakref.WeakKeyDictionary()
_lock = threading.RLock()
def lock(document):
"""Returns a threading.RLock instance for the given Poppler.Document.
Use:
with lock(document):
do_something
"""
with _lock:
try:
... |
AnnalisaS/migration_geonode | geonode/base/models.py | Python | gpl-3.0 | 21,558 | 0.005566 | from datetime import datetime
import os
import hashlib
from django.db import models
from django.db.models import Q
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
from django.core.exceptions import ValidationError, ObjectDoesNotExist
from django.core.files.base impor... | ail(self):
return getattr(self, "_missing_thumbnail", staticfiles.static(settings.MISSING_THUMB | NAIL))
def get_thumbnail_url(self):
thumb = self.thumbnail
return thumb == None and self._get_default_thumbnail() or thumb.thumb_file.url
def has_thumbnail(self):
'''Determine if the thumbnail object exists and an image exists'''
thumb = self.thumbnail
return os.path.e... |
valeriog-crytek/glad | glad/lang/c/generator.py | Python | mit | 9,993 | 0.005404 | import os
import sys
from glad.lang.common.generator import Generator
from glad.lang.common.util import makefiledir
if sys.version_info >= (3, 0):
from urllib.request import urlretrieve
else:
from urllib import urlretrieve
KHRPLATFORM = 'https://www.khronos.org/registry/egl/api/KHR/khrplatform.h'
class C... | ber))
f.write('}\n\n')
if api == 'glx':
f.write('int gladLoad{}Loader(GLADloadproc load, Display *dpy, int screen) {{\n'.format(api.upper()))
elif api == 'wgl':
f.write('int gladLoad{}Loader(GLADloadproc load, HDC hdc) {{\n'.format(api.upper()))
... | {{\n'.format(api.upper()))
self.loader.write_begin_load(f)
if api == 'glx':
f.write('\tfind_core{}(dpy, screen);\n'.format(api.upper()))
elif api == 'wgl':
f.write('\tfind_core{}(hdc);\n'.format(api.upper()))
else:
f.write... |
showa-yojyo/note | source/_sample/scipy/kdtree.py | Python | mit | 629 | 0 | #!/usr/bin/env python
"""kdtree.py: Demonstrate cl | ass KDTree of SciPy.
"""
import numpy as np
from scipy.spatial import KDTree
# pylint: disable=invalid-name
# Genrate 3D points: (0, 0, 0), | (0, 0, 10), (0, 0, 20), ...
x, y, z = np.mgrid[0:100:10, 0:100:10, 0:100:10]
points = list(zip(x.ravel(), y.ravel(), z.ravel()))
# Construct a KDTree.
tree = KDTree(points)
# A target point included in [0, 100) * [0, 100) * [0, 100).
target = [43.831, 54.762, 83.131]
print(f"Target: {target}")
# Query for the close... |
crisely09/horton | horton/espfit/test/test_mask.py | Python | gpl-3.0 | 3,493 | 0.004867 | # -*- coding: utf-8 -*-
# HORTON: Helpful Open-source Research TOol for N-fermion systems.
# Copyright (C) 2011-2016 The HORTON Development Team
#
# This file is part of HORTON.
#
# HORTON is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by th... | id_cell()
i = np.round(grid_cell.to_frac(coordinates[2] - ugrid.origin)).astype(int)
i[0] = i[0]%10
i[2] = i[2]%20
assert weights[i[0], i[1], i[ | 2]] == 0.0
def test_mask_near2():
coordinates, numbers, ugrid = get_fake_system()
weights = setup_weights(coordinates, numbers, ugrid, near={1: (0.5, 0.5), 2: (1.0, 0.2)})
weights1 = setup_weights(coordinates, numbers, ugrid, near={1: (0.5, 0.5)})
weights2 = setup_weights(coordinates, numbers, ugrid, ... |
wilywampa/python-mode | pymode/libs/pylama/async.py | Python | lgpl-3.0 | 1,615 | 0 | """Support for asyncronious checking."""
import logging
import threading
try:
import Queue
except ImportError:
import queue as Queue
try:
import multiprocessing
CPU_COUNT = multiprocessing.cpu_count()
except (ImportError, NotImplementedError):
CPU_COUNT = 1
from .core import run
LOGGER = lo... | lt_queue.put(errors)
self.path_queue.task_done()
def check_async(paths, options, rootdir=None):
"""Check given paths asynchronously.
:return list: list of errors
"""
LOGGER.info('Async code checking is enabled.' | )
path_queue = Queue.Queue()
result_queue = Queue.Queue()
for num in range(CPU_COUNT):
worker = Worker(path_queue, result_queue)
worker.setDaemon(True)
LOGGER.info('Start worker #%s', (num + 1))
worker.start()
for path in paths:
path_queue.put((path, dict(option... |
nkgeorgiev/tarator | old/modules/DHT/opendht/python/tools/benchmark.py | Python | gpl-3.0 | 9,414 | 0.006694 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (C) 2015-2016 Savoir-faire Linux Inc.
# Author(s): Adrien Béraud <[email protected]>
# Simon Désaulniers <[email protected]>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the... | t import *
class WorkBench():
"""
This contains the initialisation information, such as ipv4/ipv6, number of
nodes and cluster to create, etc. This class is also used to initialise and
finish the network.
"""
def __init__(self, ifname='ethdht', virtual_locs=8, node_num=32, remote_bootstrap=Non... | al_locs
self.node_num = node_num
self.clusters = min(virtual_locs, node_num)
self.node_per_loc = int(self.node_num / self.clusters)
self.loss = loss
self.delay = delay
self.disable_ipv4 = disable_ipv4
self.disable_ipv6 = disable_ipv6
... |
EterniusVGM/Renju | competition/backend.py | Python | mit | 235 | 0.008511 | import renju
import sys
|
def wait_for_game_update():
data = sys.stdin.buffer.readline().rstrip()
return renju.Game.loads(data.decode())
def move(move):
sys.stdout.buffer.write(move.encode() + b'\n')
sys.stdout.flush | ()
|
bwasti/caffe2 | caffe2/python/operator_test/momentum_sgd_test.py | Python | apache-2.0 | 3,891 | 0 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import core
import caffe2.python.hypothesis_test_util as hu
import hypothesis
from hypothesis import given
import hypothesis.strategies as st
import n... | w = momentum_sgd(grad, m[i], lr)
m[i] = m_new
| param[i] -= grad_new
return (grad_new, m, param)
self.assertReferenceChecks(gc, op, [grad, m, lr, w, indices], sparse)
if __name__ == "__main__":
unittest.main()
|
zackmdavis/python-swiftclient | tests/test_multithreading.py | Python | apache-2.0 | 14,131 | 0 | # Copyright (c) 2010-2013 OpenStack, LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to ... | assertEqual(Exception, self.qft.exc_infos[1][0])
self.assertEqua | l(('I went boom!',), self.qft.exc_infos[0][1].args)
self.assertEqual(('I went boom!',), self.qft.exc_infos[1][1].args)
class TestQueueFunctionManager(ThreadTestCase):
def setUp(self):
super(TestQueueFunctionManager, self).setUp()
self.thread_manager = mock.create_autospec(
mt.M... |
twerkmeister/iLID | preprocessing/audio/__init__.py | Python | mit | 141 | 0.007092 | __all__ | = ["melfilterbank", "windowing", "spectrogram", "resample"]
import melfilterbank
import windowing
i | mport spectrogram
import resample |
dark1729dragon/pixutils | pixutils/BridgeIt.py | Python | bsd-2-clause | 7,874 | 0.002413 | from __future__ import nested_scopes, generators, division, absolute_import, with_statement, print_function, unicode_literals
from pixutils.one_shot_import import *
# ------------------ these modules will take some time to import but for simple implementation clumped together ------------------ #
'''
These functions ... | g)
plt.show()
win('plt2cv', 0)(imgs)
'''
fig.canvas.draw()
w, h = fig.canvas.get_width_height()
img = np.array(fig.canvas.buffer_rgba(), dtype='u1').reshape(h, w, 4)
return img[..., [2, 1, 0]]
def rectmid((a, b, c, d)):
return int((a + c) / 2), int((b + d) / 2)
def splitpath(path, se... | pixutils'
# print(splitpath(path))
['192.168.1.2', 'pixutils']
:param your_path:
:return:
'''
path = path.replace('\\',sep)
path = path.replace('/', sep)
return [p for p in path.split(sep) if p]
def im2txt(img, bookpath=None, resolution=1.0, sep=''):
'''
This function c... |
luzfcb/projetoteste | projeto/urls.py | Python | lgpl-3.0 | 308 | 0.006494 | from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
url(r'^$ | ', 'core.views.empresta_list_view', name | ='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
)
|
mortardata/luigi | test/test_ssh.py | Python | apache-2.0 | 1,733 | 0 | # Copyright (c) 2012 Spotify AB
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy of
# the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | nder
# the License.
from luigi.contrib.ssh import RemoteContext
import unittest
import subprocess
class TestMockedRemoteContext(unittest.TestCase):
def test_subprocess_delegation(self):
""" Test subprocess call structure using mock module """
orig_Popen = subprocess.Popen
self.last_test =... | "luigi",
key_file="/some/key.pub"
)
context.Popen(["ls"])
self.assertTrue("ssh" in self.last_test)
self.assertTrue("-i" in self.last_test)
self.assertTrue("/some/key.pub" in self.last_test)
self.assertTrue("luigi@some_host" in self.last_test)
self.asse... |
gangadharkadam/office_erp | erpnext/projects/doctype/change_request/change_request.py | Python | agpl-3.0 | 275 | 0.010909 | # Copyright (c) | 2013, Web Notes Technologies Pvt. Ltd. and Contributors and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
class ChangeRequest(Document):
pass
| |
jarvis-fga/Projetos | Problema 2/lucas/src/testecomvetorizacao.py | Python | mit | 3,680 | 0.013381 | #!-*- coding: utf8 -*-
import pandas as pd
from sklearn.model_selection import cross_val_score
from collections import Counter
import numpy as np
classificacoes = pd.read_csv('all.csv', sep='\t') #Leia o arquivo e separe as tabulações
comentarios = classificacoes['comments'] #pegar a coluna de comentarios (titulada m... | OneVsOne = treinarePrever("OneVsOne", modeloOneVsOne, treino_dados, treino_marcacoes)
re | sultados[resultadoOneVsOne] = modeloOneVsOne
from sklearn.naive_bayes import MultinomialNB
modeloMultinomial = MultinomialNB()
resultadoMultinomial = treinarePrever("MultinomialNB", modeloMultinomial, treino_dados, treino_marcacoes)
resultados[resultadoMultinomial] = modeloMultinomial
from sklearn.ensemble import Ada... |
tensorflow/tpu | models/official/resnet/benchmark/resnet_benchmark.py | Python | apache-2.0 | 8,651 | 0.005895 | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | )
for step in ckpt_steps:
ckpt = os.path.join(FLAGS.model_dir, 'model.ckpt | -%d' % step)
batches_per_epoch = NUM_TRAIN_IMAGES // FLAGS.train_batch_size
current_epoch = step // batches_per_epoch
if FLAGS.use_fast_lr:
if current_epoch < 18:
eval_input_fn = imagenet_eval_small.input_fn
if current_epoch >= 18 and current_epoch < 41:
eval_inpu... |
ecsnavarretemit/sarai-interactive-maps-backend | bootstrap.py | Python | mit | 251 | 0.003984 | #!/usr/bin/env python
# bootstrap.py
#
# Copyright(c) Exequiel Ceas | ar Navarrete <[email protected]>
# Licensed under MIT
# Version 1.0.0-alpha6
from app import db
# create all databases and tables included in the ap | plication
db.create_all()
|
tarballs-are-good/sympy | sympy/physics/quantum/anticommutator.py | Python | bsd-3-clause | 4,489 | 0.001782 | """The anti-commutator: {A,B} = A*B + B*A."""
from sympy import S, Expr, Mul, Integer
from sympy.printing.pretty.stringpict import prettyForm
from sympy.physics.quantum.qexpr import split_commutative_parts
from sympy.physics.quantum.operator import Operator
from sympy.physics.quantum.dagger import Dagger
__all__ = [... | _part | ), cls(Mul(*a), Mul(*b)))
# Canonical ordering of arguments
if a.compare(b) == 1:
return cls(b,a)
def _eval_expand_anticommutator(self, **hints):
# No changes, so return self
return self
def doit(self, **hints):
A = self.args[0]
B = self.args[1]
... |
vicnet/weboob | weboob/tools/capabilities/housing/housing_test.py | Python | lgpl-3.0 | 5,981 | 0.000167 | # -*- coding: utf-8 -*-
# Copyright(C) 2018 Phyks
#
# This file is part of weboob.
#
# weboob is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any ... | vert_type)
def check_single_housing_any(self, housing, counter):
for field in self.FIELDS_ANY_SINGLE_HOUSING:
if not empty(getattr(housing, field)):
counter[field] += 1
for photo in housing.photos:
self.assertRegexpMatches(photo.url, r'^http(s?)://')
... | g listing results
results = self.check_housing_lists(query)
# Check mandatory fields in all housings
housing = self.backend.get_housing(results[0].id)
self.backend.fillobj(housing, 'phone') # Fetch phone
self.check_single_housing_all(
housing,
results[0]... |
benbaptist/pymine2 | plugin.py | Python | gpl-2.0 | 849 | 0.007067 | import glob, imp
import events
class EventManager:
def __init__(self):
self.Chat_Message_Event = events.ChatMessageEventHandler()
self.Player_Join_Event = events.PlayerJoinEventHandler()
self.Player_Leave_Event = events.PlayerLeaveEventHan | dler()
self.Player_Move_Event = events.PlayerMoveEventHandler()
self.Command_Event = events.CommandEventHandler()
self.Packet_Recv_Event = events.PacketRecvEventHandler()
class PluginManager:
def __init__(self, server):
self.plugins = {}
self.server = server
def loa... | lf):
for plugin in glob.glob("plugins/*_plugin.py"):
plugin_name = plugin[8:-10]
self.plugins[plugin_name] = imp.load_source(plugin_name, plugin)
getattr(self.plugins[plugin_name],plugin_name)(self.server) |
team-vigir/vigir_behaviors | behaviors/vigir_behavior_trigger_cutting_tool/src/vigir_behavior_trigger_cutting_tool/trigger_cutting_tool_sm.py | Python | bsd-3-clause | 17,004 | 0.022406 | #!/usr/bin/env python
###########################################################
# WARNING: Generated code! #
# ************************** #
# Manual changes may get lost if file is generated again. #
# Only code inside the [MANUAL] tags will be kept. ... | ansitions={'done': 'Check_Inner_Index'},
autonomy={'done': Autonomy.Off},
re | mapping={'input_value': 'poking_index', 'output_value': 'poking_index'})
# x:392 y:178
OperatableStateMachine.add('Check_Inner_Index',
DecisionState(outcomes=['continue','finished'], conditions=lambda x: 'continue' if x<attempts_per_point else 'finished'),
transitions={'continue': 'Plan_To_Po... |
mvaled/sentry | src/sentry/south_migrations/0391_auto__add_fileblobowner__add_unique_fileblobowner_blob_organization__a.py | Python | bsd-3-clause | 99,198 | 0.008045 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
from sentry.utils.db import is_postgres
class Migration(SchemaMigration):
# Flag to indicate if this migration is too risky
# to run online and... | .fields.CharField', [], {'default': "'a41ddfc7e4ca49a39d2b7e3edc26dcaf'", 'max_length': '64', 'db_index': 'True'}),
'expires_at': ( | 'django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2018, 2, 8, 0, 0)', 'db_index': 'True'}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'redirect_uri': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
... |
DTMilodowski/LiDAR_canopy | src/LiDAR_tools.py | Python | gpl-3.0 | 3,971 | 0.0345 | import numpy as np
import laspy as las
# Determine if a point is inside a given polygon or not
# Polygon is a list of (x,y) pairs. This function
# returns True or False. The algorithm is called
# the "Ray Casting Method".
# the point_in_poly algorithm was found here:
# http://geospatialpython.com/2011/01/point-in-pol... | s in polygon")
return pts
# filter lidar by circular neighbourhood
def filter_lidar_data_by_neighbourhood(in_pts,target_xy,radius | ):
pts = np.zeros((0,in_pts.shape[1]))
if in_pts.shape[0]>0:
x,y,inside = points_in_radius(in_pts[:,0],in_pts[:,1],target_xy[0],target_xy[1],radius)
pts = in_pts[inside,:]
else:
print( "\t\t\t no points in neighbourhood")
return pts
|
plotly/plotly.py | packages/python/plotly/plotly/validators/scatter/hoverlabel/font/_size.py | Python | mit | 506 | 0.001976 | import _plotly_utils.basevalidators
| class SizeValidator(_plotly_utils.basevalidators.NumberValidator):
def __init__(
self, plotly_name="size", parent_name="scatter.hoverlabel.font", **kwargs
):
super(SizeValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
array_ok=kwargs... | ok", True),
edit_type=kwargs.pop("edit_type", "none"),
min=kwargs.pop("min", 1),
**kwargs
)
|
fcopantoja/sips | sips/asuntos/models.py | Python | mit | 2,019 | 0.000991 | import uuid
from django.contrib.auth.models import User
from django.db import models
STATUS_CHOICES = (
('atendido', 'Atendido'),
('no_atendido', 'No Atendido'),
('en_proceso', 'En Proceso'),
)
class Municipio(models.Model):
name = models.CharField(max_length=100, blank=False, null=False)
def _... | def folio_(self):
return (str(self.folio)[:8]).upper()
def status_(self):
for choice in STATUS_CHOICES:
if self.status == choice[0]:
return choice[1]
class AsuntoEvento(models.Model):
asunto = models.ForeignKey(Asunto)
fecha_cita_usuario = models.DateTimeFi... | ateTimeField(null=False)
juzgado = models.CharField(max_length=100, blank=False, null=False)
observaciones_visita_juzgado = models.TextField(blank=True, null=False)
|
lptorres/noah-inasafe | web_api/third_party/raven/utils/encoding.py | Python | gpl-3.0 | 3,604 | 0.00222 | """
raven.utils.encoding
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
import warnings
def force_unicode(s, encoding='utf-8', errors='strict'):
"""
Similar to smart_unicode, except that lazy i... | ion's standard str()
# output should be.
s = ' '.join([force_unicode(arg, encoding,
errors) for arg in s])
elif not isinstance(s, unicode):
# Note: We use .decode() here, instead of unicode(s, encoding,
# errors), ... | is a SafeString, it ends up being a
# SafeUnicode at the end.
s = s.decode(encoding, errors)
except UnicodeDecodeError, e:
if not isinstance(s, Exception):
raise UnicodeDecodeError(s, *e.args)
else:
# If we get to here, the caller has passed in... |
joyxu/kernelci-backend | app/utils/__init__.py | Python | agpl-3.0 | 5,533 | 0 | # Copyright (C) 2014 Linaro Ltd.
#
# 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) any later version.
#
# This program is distribute... | rname):
| """Local function to replace the found arch value.
:param arch: The name of the architecture.
:type arch: str
:param dirname: The name of the directory.
:param dirname: str
:return The directory name without the architecture value.
"""
return dirname.repla... |
dstufft/ooni-backend | oonib/policy/api.py | Python | bsd-2-clause | 161 | 0 | fro | m oonib.policy import handlers
policyAPI = [
(r"/policy/nettest", handlers.NetTestPolicyHandler),
(r"/policy/input", handlers | .InputPolicyHandler),
]
|
datafiniti/Diamond | src/collectors/filestat/test/testfilestat.py | Python | mit | 1,903 | 0.002102 | #!/usr/bin/python
# coding=utf-8
################################################################################
from test import CollectorTestCase
from test import get_collector_config
from test import unittest
from mock import Mock
from mock import patch
try:
from cStringIO import StringIO
StringIO # work... | st_should_open_ | proc_sys_fs_file_nr(self, publish_mock, open_mock):
open_mock.return_value = StringIO('')
self.collector.collect()
open_mock.assert_called_once_with('/proc/sys/fs/file-nr')
@patch.object(Collector, 'publish')
def test_should_work_with_real_data(self, publish_mock):
FilestatColle... |
AndroidSecurityTools/lobotomy | framework/enums/enums.py | Python | mit | 5,361 | 0.003544 | class ADBEnum(object):
commands = {
"am start": "adb shell am start"
}
class D2JEnum(object):
commands = {
"decompile": "dex2jar-2.0/d2j-dex2jar.sh --force --output"
}
class APIMappings(object):
mappings = {
"install_shortcut":
{
"permiss... | ofService"
]
}
},
},
"access_coarse_location":
| {
"permission": "android.permission.ACCESS_COARSE_LOCATION",
"classes":
{
"android.location.LocationManager":
{
"methods":
[
... |
imaluengo/SMURFS-Superpixels | run_smurfs.py | Python | mit | 1,927 | 0.016087 | #!/usr/bin/env python
import argparse
import os
import numpy as np
from skimage import io, util
from pysmurfs import SMURFS, qSMURFS, rSMURFS, qrSMURFS, visualize
base_dir = os.path.dirname(os.path.realpath(__file__))
smurfs_desc ='SMURFS: Superpixels from Multiscale Refinement of Super-regions'
parser = argparse.... | .input_file))
if args.num_superpixels <= 0 or args.num_superpixels >= np.prod(img.shape[:2]):
raise Exception('Invalid number of superpixels: {}'.format(args.num_superpixels))
if args.regular:
if args.quick:
result = qrSMURFS(img, args.num_superpixels)
else:
result = qSMURFS(img, args.num_superpixels)
else:
i... | result = SMURFS(img, args.num_superpixels)
fileId = os.path.basename(args.input_file)
fileId = fileId[:fileId.rfind('.')]
out_file = 'result-{}.png'.format(fileId)
out_file = os.path.join(args.out, out_file)
io.imsave(out_file, result.astype(np.uint16))
if args.plot:
visualize(img, result)
|
SylvainCecchetto/plugin.video.catchuptvandmore | plugin.video.catchuptvandmore/resources/lib/channels/ch/lemanbleu.py | Python | gpl-2.0 | 5,905 | 0.000339 | # -*- coding: utf-8 -*-
"""
Catch-up TV & More
Copyright (C) 2019 SylvainCecchetto
This file is part of Catch-up TV & More.
Catch-up TV & More 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 Foundat... | d':
all_datas_videos_path.append(
stream_url.replace('mp4-231', 'mp4-323'))
elif quality == 'hq':
all_datas_videos_path.append(
stream_url.replace('mp4-231', 'mp4-12')) |
else:
all_datas_videos_path.append(stream_url)
url = ''
if desired_quality == "DIALOG":
seleted_item = xbmcgui.Dialog().select(
plugin.localize(30709),
all_datas_videos_quality)
if seleted_item == -1:
url = ''
url = all_datas_vide... |
ciandcd/ciandcd-web | htmlExtractor/HECommon.py | Python | mit | 5,015 | 0.02333 | import os
import re
from datetime import *
import feedparser
from newspaper import Article,Config
import ne | wspaper
import urllib.request
def writeFile(outPath,content):
file = open(outPath, 'w')
if file:
file.write( | content)
file.close()
else:
print ("Error Opening File " + outPath)
def writeHtml(outPath,content,title,link,date,authors,tags):
print('date:authors:tags' + date + authors + tags)
html = '''<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="utf-8"/>
<title>
'''
... |
partofthething/home-assistant | homeassistant/components/template/binary_sensor.py | Python | apache-2.0 | 7,122 | 0.000983 | """Support for exposing a templated binary sensor."""
import voluptuous as vol
from homeassistant.components.binary_sensor import (
DEVICE_CLASSES_SCHEMA,
ENTITY_ID_FORMAT,
PLATFORM_SCHEMA,
BinarySensorEntity,
)
from homeassistant.const import (
ATTR_ENTITY_ID,
ATTR_FRIENDLY_NAME,
CONF_DEVI... | .All(
cv.deprecated(ATTR_ENTITY_ID),
vol.Schema(
{
vol.Required(CONF_VALUE_TEMPLATE): cv.template,
| vol.Optional(CONF_ICON_TEMPLATE): cv.template,
vol.Optional(CONF_ENTITY_PICTURE_TEMPLATE): cv.template,
vol.Optional(CONF_AVAILABILITY_TEMPLATE): cv.template,
vol.Optional(CONF_ATTRIBUTE_TEMPLATES): vol.Schema(
{cv.string: cv.template}
),
vol... |
nkhuyu/airflow | airflow/www/app.py | Python | apache-2.0 | 68,914 | 0.000653 | from __future__ import print_function
from __future__ import division
from builtins import str
from past.utils import old_div
import copy
from datetime import datetime, timedelta
import dateutil.parser
from functools import wraps
import inspect
import json
import logging
import os
import socket
import sys
import time
... | on=None):
settings.Session.remove()
def dag_link(v, c, m, p):
url = url_for(
'airflow.gra | ph',
dag_id=m.dag_id)
return Markup(
'<a href="{url}">{m.dag_id}</a>'.format(**locals()))
class DagModelView(wwwutils.SuperUserMixin, ModelView):
column_list = ('dag_id', 'owners')
column_editable_list = ('is_paused',)
form_excluded_columns = ('is_subdag', 'is_active')
column_searc... |
khchine5/lino | lino/management/commands/makescreenshots.py | Python | bsd-2-clause | 8,696 | 0.005175 | # -*- coding: UTF-8 -*-
# Copyright 2012-2013 Luc Saffre
# License: BSD (see file COPYING for details)
"""
Writes screenshots to <project_dir>/media/cache/screenshots
"""
# from future import standard_library
# standard_library.install_aliases()
from builtins import str
import logging
logger = logging.getLogger(__nam... | g("Loading",address,'to',output);
page.open(address,on_o | pened);
"""
class Command(BaseCommand):
help = __doc__
option_list = BaseCommand.option_list + (
make_option('--force', action='store_true',
dest='force', default=False,
help='Overwrite existing files.'),
)
def handle(self, *args, **options):
... |
yannrouillard/weboob | weboob/capabilities/bill.py | Python | agpl-3.0 | 5,143 | 0.004667 | # -*- coding: utf-8 -*-
# Copyright(C) 2012 Romain Bignon, Florent Fourcot
#
# This file is part of weboob.
#
# weboob is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, o... | etails.
#
# You should have received a copy of the GNU Affero General Public License
# along with weboob. If not, see <http://www.gnu.org/licenses/>.
from .base import CapBaseObject, StringField, DateField, DecimalField, UserError
from .collection import ICapCollection
__all__ = ['SubscriptionNotFound', 'BillNotFou... |
class SubscriptionNotFound(UserError):
"""
Raised when a subscription is not found.
"""
def __init__(self, msg='Subscription not found'):
UserError.__init__(self, msg)
class BillNotFound(UserError):
"""
Raised when a bill is not found.
"""
def __init__(self, msg='Bill not foun... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.