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 |
|---|---|---|---|---|---|---|---|---|
guneysus/packathon2016 | packathon2016/__init__.py | Python | bsd-3-clause | 85 | 0 | #!/usr/bin/env pyt | hon
# coding=utf-8
__author__ = u'Ahmed Şeref GÜNEYSU'
import | ui
|
sanaldavis/Google-Python-Exercies | basic/mimic.py | Python | apache-2.0 | 2,511 | 0.010753 | #!/usr/bin/python -tt
# Copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
# Google's Python Class
# http://code.google.com/edu/languages/google-python-class/
"""Mimic pyquick exercise -- optional extra exercise.
Google's Python Class
Read in the ... | ic_dict['']
word=random.choice(nexts)
# Provided main(), calls mimic_dict() and mimic()
def main():
if len(sys.argv) != 2:
print 'usage: ./mimic.py file-to-read'
sys.exit(1)
dict = mimic_dict(sys.argv[1])
print dict
print_mimic(dict, '')
if __name__ | == '__main__':
main()
|
retrography/scancode-toolkit | tests/cluecode/data/ics/markdown-markdown-extensions/html_tidy.py | Python | apache-2.0 | 225 | 0.031111 | [uTidylib]: http://utidylib.berlios.de/
[options]: http://tidy.sourceforge.net/docs/qui | ckref.html
Copyright (c)2008 [Waylan Limberg](http://achinghead.com)
License: [BSD](http://www.opensource.or | g/licenses/bsd-license.php) |
mogoweb/webkit_for_android5.1 | webkit/Tools/Scripts/webkitpy/tool/steps/postdiffforcommit.py | Python | apache-2.0 | 1,879 | 0.001597 | # Copyright (C) 2010 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and th... | on.
#
# THIS | SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS 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 DIR... |
willharris/django | tests/template_backends/test_utils.py | Python | bsd-3-clause | 1,198 | 0 | from django.core.exceptions import ImproperlyConfigured
from django.template import engines
from django.test import SimpleTestCase, override_settings
class TemplateStringsTests(SimpleTestCase):
@override_settings(TEMPLATES=[{
'BACKEND': 'raise.import.error',
}])
def test_backend_import_error(self... | with self.assertRaises(ImportError):
engines.all()
@override_settings(TEMPLATES=[{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
# Incorrect: APP_DIRS and loaders are mutually incompatible.
'APP_DIRS': True,
'OPTIONS': {'loaders': []},
}])
... | improperly_configured(self):
"""
Failing to initialize a backend keeps raising the original exception.
Regression test for #24265.
"""
with self.assertRaises(ImproperlyConfigured):
engines.all()
with self.assertRaises(ImproperlyConfigured):
engine... |
ptroja/spark2014 | testsuite/gnatprove/tests/O824-010__flow_no_computed_calls_for_ll_subprogram/test.py | Python | gpl-3.0 | 199 | 0.015075 | from test_support impo | rt *
import re, os
do_flow()
hand = open(os.path.join("gnatprove", "main.ali"))
for line in hand :
line = line.rstrip()
if re.search('^F ', line | ) :
print line
|
tmaiwald/OSIM | OSIM/Modeling/Components/NPN_Vertical_Bipolar_Intercompany_Model/VBIC_Currents/IBC.py | Python | bsd-2-clause | 4,274 | 0.007253 | import numpy as np
from numba import jit
import OSIM.Simulation.Utils as u
from OSIM.Modeling.AbstractComponents.NonlinearComponent import NonlinearComponent
class IBC(NonlinearComponent):
def __init__(self, nodes, name, value, superComponent, **kwargs):
super(IBC, self).__init__(nodes, name, value, supe... | '''
for v in self.variableDict:
variableExpr = "".join((v, "=", self.variableDict[v]))
exec(variableExpr)
self.UT = eval(self.paramDict.get("ut", "0.026"))
self.IBCI = eval(self.paramDict.get("ibci", "1.5E-18"))
self.IBCN = eval(self.paramDic | t.get("ibcn", "1E-15"))
self.NCN = eval(self.paramDict.get("ncn", "1.7"))
self.NCI = eval(self.paramDict.get("nci", "1.05"))
self.AVC1 = eval(self.paramDict.get("avc1", "2.4"))
self.AVC2 = eval(self.paramDict.get("avc2", "11.5"))
self.MC = eval(self.paramDict.get("mc", "0.12"))
... |
kiddinn/plaso | tests/parsers/winreg_plugins/typedurls.py | Python | apache-2.0 | 4,083 | 0.00147 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Tests for the MSIE typed URLs Windows Registry plugin."""
import unittest
from plaso.parsers.winreg_plugins import typedurls
from tests.parsers.winreg_plugins import test_lib
class MsieTypedURLsPluginTest(test_lib.RegistryPluginTestCase):
"""Tests for the MSIE ty... | dows:registry:typedurls',
'entries': expected_entries,
'key_path' | : key_path,
# This should just be the plugin name, as we're invoking it directly,
# and not through the parser.
'parser': plugin.plugin_name}
self.CheckEventValues(storage_writer, events[0], expected_event_values)
if __name__ == '__main__':
unittest.main()
|
CarltonShepherd/political-tweet-classifier | data/usermapping.py | Python | gpl-2.0 | 1,522 | 0.032852 |
# Dict of Twitter handles and known political views
data_tuples = {
"jeremycorbyn" : "Labour",
"ken4london" : "Labour",
"Imran_HussainMP" : "Labour",
"GloriaDePiero" : "Labour",
"tom_watson" : "Labour",
"JonAshworth" : "Labour",
"UKLabour" : "Labour",
"RupaHuq" : "Labour",
"heidi_mp... | d_Cameron" : "Tory",
"NickyMorgan01" : "Tory",
"Freeman_George" : "Tory",
"lucyallan" : "Tory",
"edvaizey" : "Tory",
"ChrisWhite_MP" : "Tory",
"BrandonLewis" : "Tory",
"NicolaSturgeon" : "SNP",
"theSNP" : "SNP",
"StewartHosieSNP" : "SNP",
"DougChapmanSNP" : "SNP",
"AngusMacNe... | SDoughtyMP" : "Labour",
"Keith_Vaz" : "Labour",
"CWhittakerMP" : "Tory",
"Owen_PatersonMP" : "Tory",
"NigelFarage" : "UKIP",
"DouglasCarswell" : "UKIP",
"paulnuttallukip" : "UKIP",
"Steven_Woolfe" : "UKIP",
"RogerHelmerMEP" : "UKIP",
"oflynnmep" : "UKIP",
"rog_ukip" : "UKIP",
... |
ezequielpereira/Time-Line | autopilot/autopilotlib/wrappers/messagedialog.py | Python | gpl-3.0 | 1,500 | 0.003333 | # Copyright (C) 2009, 2010, 2011 Rickard Lindberg, Roger Lindberg
#
# This file is part of Timeline.
#
# Timeline 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... | ilotlib.wrappers.wrapper import Wrapper
from autopilotlib.app.constants import TIME_TO_WAIT_FOR_DIALOG_TO_SHOW_IN_MILLISECONDS
wxMessageDialog = wx.MessageDialog
class MessageDialog(wxMessageDialog, Wrapper):
def __init__(self, *args, **kw):
wxMessageDialog.__init__(self, *args, **kw)
... | SECONDS,
self._explore, MessageDialog.listener)
super(MessageDialog, self).ShowModal()
@classmethod
def wrap(self, listener):
wx.MessageDialog = MessageDialog
MessageDialog.listener = listener
|
sreenathmenon/billing-dashboard | billingdashboard/dashboards/project/cust_invoice/views.py | Python | apache-2.0 | 1,151 | 0.004344 | from django.views import generic
from django.core.urlresolvers import reverse
from django.core.urlresolvers import reverse_lazy
from django.utils.translation import ugettext_lazy as _
from horizon impor | t exceptions
from horizon import forms
from horizon import tabs
from horizon import tables
from billingdashboard.common import get_user_invoices
from billingdashboard.dashboards.project.cust_invoice \
import tables as invoice_table
from astutedashboard.common import get_invoices, get_invoice
class Index... | = invoice_table.UserInvoiceListingTable
template_name = 'project/cust_invoice/index.html'
page_title = _("Invoices")
def get_data(self):
return get_user_invoices(self.request, verbose=True)
class UserInvoiceDetailsView(generic.TemplateView):
template_name = 'project/cust_invoice/invoice.html'... |
hryamzik/ansible | lib/ansible/modules/network/nxos/nxos_interface_ospf.py | Python | gpl-3.0 | 17,076 | 0.001464 | #!/usr/bin/python
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distribut... | ype':
value = value_list[1]
elif arg == 'message_digest_encryption_type':
value = value_list[2]
if value == '3':
value = '3des'
elif value == '7':
value = 'cisco_type_7'
elif arg == 'message_d... | value = value_list[3]
elif arg == 'passive_interface':
has_no_command = re.search(r'\s+no\s+{0}\s*$'.format(command), config, re.M)
value = False
if has_command and not has_no_command:
value = True
elif arg in BOOL_PARAMS:
value = bool(has_command)
else:
... |
astagi/twitterene | twitterene/tweepy/cgi.py | Python | gpl-3.0 | 34,465 | 0.002234 | #! /usr/bin/python2.6
# NOTE: the above "/usr/local/bin/python" is NOT a mistake. It is
# intentionally NOT "/usr/bin/env python". On many systems
# (e.g. Solaris), /usr/local/bin is not in $PATH as passed to CGI
# scripts, and /usr/local/bin is the default directory where Python is
# installed, so /usr/bin/env woul... | ss
log = initl | og # The current logging function
# Parsing functions
# =================
# Maximum input we will accept when REQUEST_METHOD is POST
# 0 ==> unlimited input
maxlen = 0
def parse(fp=None, environ=os.environ, keep_blank_values=0, strict_parsing=0):
"""Parse a query in the environment or from a file (def... |
1a1a11a/mimircache | PyMimircache/cacheReader/csvReader.py | Python | gpl-3.0 | 8,745 | 0.003316 | # coding=utf-8
"""
a csv trace reader
Author: Jason Yang <peter.waynechina@gmail.com> 2016/06
"""
import string
from PyMimircache.const import ALLOW_C_MIMIRCACHE, INSTALL_PHASE
from PyMimircache.utils.printing import *
if ALLOW_C_MIMIRCACHE and not INSTALL_PHASE:
import PyMimircache.CMimircache.CacheRead... | for i in range(len(self.headers)):
d[self.headers[i]] = line_split[i].str | ip(string.whitespace)
else:
for key, value in enumerate(line_split):
d[key] = value
line = self.trace_file.readline()
yield d
# raise StopIteration
def lines(self):
"""
a generator for reading all the information of... |
pepitogithub/PythonScripts | crypto.py | Python | gpl-2.0 | 5,608 | 0.023894 | import Aplicacion
import Probabilidades as pr
from Menu import *
from Variable import *
from validador import *
#------------------------------------------------
#--------------- TODO ---------------------------
#------------------------------------------------
# 1) Lista de tareas pendientes a implementar.
# ... | illa"].valor)
#-----------------------
#--- Funciones ---------
#-- | ---------------------
def base36encode(self,number, alphabet='0123456789abcdefghijklmnopqrstuvwxyz'):
"""Converts an integer to a base36 string."""
if not isinstance(number, (int, long)):
raise TypeError('number must be an integer')
base36 = ''
sign = ''
... |
WatchPeopleCode/WatchPeopleCode | migrations/versions/177b55430b61_.py | Python | mit | 679 | 0.013255 | """empty message
Revision ID: 177b55430b61
Revises: None
Create Date: 2015-01-29 22:29:18.963249
"""
# revision identifiers, used by Alembic.
revision = '177b55430b61'
down_revision = None
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###... | llable=False),
sa.Column('type', sa.String(length=50), nullable=True),
sa.PrimaryKeyConstraint('id')
)
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_table('stream')
### end Alemb | ic commands ###
|
jfillmore/hoops | tests/models_tests/test_model_language.py | Python | mit | 1,525 | 0.001311 | from tests.models_tests import ModelsTestBase
from test_models.core import Language
from tests import dbhelpe | r
from sqlalchemy.exc import IntegrityError
class TestLanguageModel(ModelsTestBase):
def test_00_init(self):
assert Language
def test_01_populate(self):
dbhelper.add(Language(lang='en', name='English'), self.db)
| dbhelper.add(Language(lang='en-us', name='English US'), self.db)
dbhelper.add(Language(lang='es', name='Espanol'), self.db)
dbhelper.add(Language(lang='fr', name='French'), self.db)
# Duplicate entry
try:
dbhelper.add(Language(lang='fr', name='French'), self.db)
... |
naziris/HomeSecPi | venv/lib/python2.7/site-packages/gunicorn/workers/gthread.py | Python | apache-2.0 | 10,785 | 0.000649 | # -*- coding: utf-8 -
#
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
# design:
# a threaded worker accepts connections in the main loop, accepted
# connections are are added to the thread pool as a connection job. On
# keepalive connections are put back in the ... | self.sock.setblocking(False)
def init(self):
self.sock.setblocking(True)
if self.parser is None:
# wrap the socket if needed
if self.cfg.is_ssl:
self.sock = ssl.wrap_socket(client, server_side=True,
**self.cfg.ssl_options)
... | the parser
self.parser = http.RequestParser(self.cfg, self.sock)
return True
return False
def set_timeout(self):
# set the timeout
self.timeout = time.time() + self.cfg.keepalive
def __lt__(self, other):
return self.timeout < other.timeout
__cmp__ ... |
rjw57/streamkinect2 | setup.py | Python | bsd-2-clause | 1,148 | 0.016551 | #!/usr/bin/env python
import os
from setuptools import setup, find_packages
import streamkinect2.version as meta
# Utility function to read the README file.
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name = meta.__project__,
version = meta.__version__,
... | 2",
packages=find_packages(exclude='test'),
long_description=read('README.md'),
classifiers=[
"Development Status :: 3 - Alpha",
"Topic :: Utilities",
"License :: OSI Approved :: BSD License",
],
install_requires=[
'blinker',
'enum34',
'lz4',
... | 'coverage'
],
extras_require={
'docs': [ 'sphinx', 'docutils', ],
},
)
|
koyadovic/Dia | predictive/systems/statistical/analysis/tools/property.py | Python | gpl-2.0 | 271 | 0.00369 |
def propertycached(fn):
attr_name = "_cached_" + fn.__name__
| @property
def _propertycached(self):
if not hasattr(self, attr_name):
setattr(self, attr_name, fn(self))
return getattr(self, attr_name)
return _propertycached
| |
yuhaozhang/nnjm-global | code/train_nnjm_gplus.py | Python | mit | 15,583 | 0.005134 | #!/usr/bin/env python
"""
Train a NNJM (with global context and extended architecture) model.
"""
usage = 'To train NNJM (with global context and extended architecture) using Theano'
import cPickle
import gzip
import os
import sys
import time
import re
import codecs
import argparse
import datetime
import numpy as n... | f.shared_test_set_y, 'int32')
self.test_set_loaded = True
def loadBatchData(self, isInitialLoad=False):
src_lang = self.src_lang
tgt_lang = self.tgt_lang
tgt_vocab_size = self.tgt_vocab_size
ngram_size = self.ngram_size
chunk_size = self.chunk_size
src_windo... | io_read_ngram.get_joint_ngrams_with_src_global_matrix(self.src_f, self.tgt_f, self.align_f, \
max_src_sent_length, tgt_vocab_size, ngram_size, src_window, opt, num_read_lines=chunk_size, stopword_cutoff=self.stopword_cutoff)
if isInitialLoad == False:
assert(type(self.model) == model_gp... |
jjscarafia/CUPS-Cloud-Print | ccputils.py | Python | gpl-3.0 | 10,118 | 0.000297 | # CUPS Cloudprint - Print via Google Cloud Print
# Copyright (C) 2014 Simon Cadman
#
# 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 y... | = False
return status
@staticmethod
def Base64Encode(data, jobtype):
"""Convert a file to a base64 encoded file.
Args:
pathname: data to base64 encode
jobtype: job type being encoded - pdf, jpg etc
Returns:
string, base64 encoded string. |
For more info on data urls, see:
http://en.wikipedia.org/wiki/Data_URI_scheme
"""
# Convert binary data to base64 encoded data.
mimetype = Utils._MIMETYPES_JOBTYPES['other']
if jobtype in Utils._MIMETYPES_JOBTYPES:
mimetype = Utils._MIMETYPES_JOBTYPES[jobty... |
Acidity/PyPermissions | pypermissions/permission.py | Python | mit | 8,509 | 0.004231 | class Permission(object):
"""This class represents the most basic permission possible. It has any number of segments, but is fully defined by
it's name. It may have wildcards, allowing for easily giving multiple permissions of the same form to users,
especially when the number of permissions is large, infin... | rue or False
"""
raise NotImplementedError()
| def create_stateful_permission(self, state):
if self.state:
raise Exception("You cannot create a stateful permission from a stateful permission")
new_perm = self.__class__(name=self.name, description=self.description,
delimiter=self.delimiter, wildcard=sel... |
enj/origin | vendor/github.com/heketi/heketi/extras/tools/comparison.py | Python | apache-2.0 | 5,562 | 0.001079 | #!/usr/bin/env python
#
# Copyright (c) 2018 The heketi Authors
#
# This file is licensed to you under your choice of the GNU Lesser
# General Public License, version 3 or any later version (LGPLv3 or
# later), or the GNU General Public License, version 2 (GPLv2), in all
# cases as published by the Free Software Founda... | , matches, heketi_info)
class Printer(object):
"""Utility class for printing columns w/ headers | ."""
def __init__(self, header):
self._did_header = False
self.header = header or []
def line(self, *columns):
if self.header and not self._did_header:
self._print_header(columns)
self._did_header = True
print (' '.join(columns))
def _print_header(se... |
jtoppins/beaker | IntegrationTests/src/bkr/inttest/server/selenium/test_distros.py | Python | gpl-2.0 | 9,272 | 0.001294 |
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
import xmlrpclib
import requests
from turbogears.database import sessi... | self.distro = data_setup.create_distro()
self.server = self.get_server()
# https://bugzilla.redhat.com/show_bug.cgi?id=1173368
def test_empty_version(self):
self.server.auth.login_password(data_setup.ADMIN_USER,
data_setup.ADMIN_PASSWORD)
try:
... | tros.edit_version(self.distro.name, '')
self.fail('should raise')
except xmlrpclib.Fault, e:
self.assertIn('OSMajor cannot be empty', e.faultString)
class DistroTaggingXmlRpcTest(XmlRpcTestCase):
@with_transaction
def setUp(self):
self.distro = data_setup.create_distr... |
acrazing/dbapi | scripts/join_group.py | Python | mit | 1,512 | 0 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2018 acrazing <joking.young@gmail.com>. All rights reserved.
# @since 2018-12-03 00:03:40
import time
from dbapi.DoubanAPI import DoubanAPI
class GroupAPI:
def __init__(self):
self.api = DoubanAPI(flush=False)
self._applied = {}
s... | print('skip user: %s' % (user['alias']))
def join_user_groups(sel | f, user_alias):
groups = self.api.group.list_joined_groups(user_alias)['results']
for group in groups:
if self._applied.get(group['alias'], None) is None:
self.api.group.join_group(group['alias'], 'Hello ~')
self._applied[group['alias']] = True
... |
mrkm4ntr/incubator-airflow | tests/dags/test_scheduler_dags.py | Python | apache-2.0 | 1,500 | 0.001333 | #
# 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... | 'airflow', start_date=DEFAULT_DATE + timedelta(days=3)
)
dag2_task2 = DummyOperator(task_id='dummy2 | ', dag=dag2, owner='airflow')
|
napsternxg/gensim | gensim/test/utils.py | Python | gpl-3.0 | 5,981 | 0.002508 | #!/usr/bin/env python
# encoding: utf-8
"""Module contains common utilities used in automated code tests for Gensim modules.
Attr | ibutes:
-----------
module_path : str
Full path to this module directory.
common_texts : list of list of | str
Toy dataset.
common_dictionary : :class:`~gensim.corpora.dictionary.Dictionary`
Dictionary of toy dataset.
common_corpus : list of list of (int, int)
Corpus of toy dataset.
Examples:
---------
It's easy to keep objects in temporary folder and reuse'em if needed:
.. sourcecode:: pycon
>>> from... |
RawEvan/sharephotos | site-packages/sinastorage/__init__.py | Python | gpl-3.0 | 605 | 0.02314 | from _ | _future__ import absolute_import
__version__ = "1.1.6"
from .bucket import SCSFile, SCSBucket, SCSError, KeyNotFound
SCSFile, SCSBucket, SCSError, KeyNotFound
__all__ = "SCSFile", "SCSBucket", "SCSError"
class appinfo(object):
def __init__(self,access_key,secret_key,secure):
self.access_key=access_key
... | ltAppInfo():
pass
def setDefaultAppInfo(access_key,secret_key,secure=False):
default = appinfo(access_key,secret_key,secure)
global getDefaultAppInfo
getDefaultAppInfo = lambda: default |
sh01/gonium | src/pid_filing.py | Python | gpl-2.0 | 2,162 | 0.019889 | #!/usr/bin/env python
#Copyright 2004,2008 Sebastian Hagen
# This file is part of gonium.
#
# gonium 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 l... | argv0 = argv0.encode()
| filename = os.path.basename(argv0) + b'.pid'
if (os.path.exists(filename)):
mode = 'r+b'
else:
mode = 'wb'
# The feature allowing for calling open() on bytes filenames was added
# somewhere between CPython 3.0-rc1 and -rc3. This version is written
# for 3.0 final,... |
twitter/pants | src/python/pants/scm/git.py | Python | apache-2.0 | 22,734 | 0.011261 | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import absolute_import, division, print_function, unicode_literals
import binascii
import io
import logging
import os
import traceback
from builtins import ... | cmd,
raise_type=Scm.LocalException)
files.update(committed_changes.split())
if include_untracked:
untracked_ | cmd = ['ls-files', '--other', '--exclude-standard', '--full-name'] + rel_suffix
untracked = self._check_output(untracked_cmd,
raise_type=Scm.LocalException)
files.update(untracked.split())
# git will report changed files relative to the worktree: re-relativize to rel... |
CCI-MOC/GUI-Backend | core/migrations/0045_allow_blank_membership_AND_rename_project_links.py | Python | apache-2.0 | 583 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0044_cm_d | efaults_for_allocation_and_quota'),
]
operations = [
migrations.AlterField(
model_name='machinerequest',
name='new_version_membership',
field=models.ManyToManyField(to='core.Group', blank=True),
),
migrations.AlterModelTable(
name='project... | ink',
table='project_links',
),
]
|
rodluger/planetplanet | planetplanet/photo/trappist1.py | Python | gpl-3.0 | 7,549 | 0.015511 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
trappist1.py |github|
---------------------
This module hosts TRAPPIST-1-specific routines.
.. role:: raw-html(raw)
:format: html
.. |github| replace:: :raw-html:`<a href = "https://github.com/rodluger/planetplanet/blob/master/planetplanet/photo/trappis... | e, distance = 12, seed = None, **kwargs):
'''
Returns an instance of :py:obj:`planetplanet.photo.System` for the full
TRAPPIST-1 system. Star and plan | et parameters are drawn from their
respective prior distributions, which are based on the observed values
from Gillon et al. (2017), Luger et al. (2017), and
Burgasser & Mamajek (2017). Longitudes of ascending node are
drawn from the :math:`\\theta` distribution derived in the paper.
:param ... |
loli/semisupervisedforests | sklearn/feature_selection/univariate_selection.py | Python | bsd-3-clause | 18,609 | 0 | """Univariate features selection."""
# Authors: V. Michel, B. Thirion, G. Varoquaux, A. Gramfort, E. Duchesnay.
# L. Buitinck, A. Joly
# License: BSD 3 clause
import numpy as np
import warnings
from scipy import special, stats
from scipy.sparse import issparse
from ..base import BaseEstimator
from ..prepr... | ures features with the
highest values for the test chi-squared statistic from X, which must
contain booleans or frequencies (e.g., term counts in document
classification), relative to the classes.
Recall that the chi-square test measures dependence between stochastic
variables, so using this functi... | meters
----------
X : {array-like, sparse matrix}, shape = (n_samples, n_features_in)
Sample vectors.
y : array-like, shape = (n_samples,)
Target vector (class labels).
Returns
-------
chi2 : array, shape = (n_features,)
chi2 statistics of each feature.
pval : array... |
JulienMcJay/eclock | windows/kivy/doc/autobuild.py | Python | gpl-2.0 | 6,361 | 0.008018 | '''
Script to generate Kivy API from source code.
Code is messy, but working.
Be careful if you change anything in !
'''
ignore_list = (
'kivy._event',
'kivy.factory_registers',
'kivy.graphics.buffer',
'kivy.graphics.vbo',
'kivy.graphics.vertex',
'kivy.lib.osc'
)
import os
import sys
from gl... | 'r') as fd:
d = fd.read().strip()
d = '\t' + '\n\t'.join(d.split('\n'))
example_output.append(d)
t = template.replace('$SUMMARY', summary)
t = t.replace('$PACKAGE', module)
if len(example_output):
refid += 1
example_output = template_examples % (refid, '\... |
else:
t = t.replace('$EXAMPLES_REF', '')
t = t.replace('$EXAMPLES', '')
writefile('api-%s.rst' % module, t)
# Generation finished
print('Generation finished, do make html')
|
googlegenomics/pipelines-api-examples | set_vcf_sample_id/set_vcf_sample_id.py | Python | bsd-3-clause | 2,263 | 0.011931 | #!/usr/bin/env python
# Copyright 2017 Google Inc.
#
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file or at
# https://developers.google.com/open-source/licenses/bsd
# set_vcf_sample_id.py
#
# This script processes a single sample VCF file and replaces the
# sample I... | "ERROR: Current sample ID does not match expected: %s != %s\n" % (
curr_id, original_id)
sys.exit(1)
# Set the new value into the fields array and recreate the line
fi | elds[-1] = new_id
line = '\t'.join(fields) + '\n'
lines_changed = lines_changed + 1
# Emit the current line
sys.stdout.write(line)
# Emit some statistics to stderr
print >> sys.stderr, "Total lines: %d" % lines_processed
print >> sys.stderr, "Changed lines: %d" % lines_changed
if lines_c... |
cberry777/dd-agent | utils/kubernetes/kubeutil.py | Python | bsd-3-clause | 8,888 | 0.002025 | # (C) Datadog, Inc. 2015-2016
# All rights reserved
# Licensed under Simplified BSD License (see LICENSE)
# stdlib
from collections import defaultdict
import logging
import os
from urlparse import urljoin
# project
from util import check_yaml
from utils.checkfiles import get_conf_path
from utils.http import retrieve_... | ds_list
def retrieve_json_auth(self, url, auth_token, timeout=10):
"""
Kubernetes API | requires authentication using a token available in
every pod.
We try to verify ssl certificate if available.
"""
verify = self.CA_CRT_PATH if os.path.exists(self.CA_CRT_PATH) else False
log.debug('ssl validation: {}'.format(verify))
headers = {'Authorization': 'Bearer {}... |
OpenWinCon/OpenWinNet | web-gui/AP/urls.py | Python | apache-2.0 | 119 | 0 | from django.conf.urls impor | t url
from . import views
urlpatterns = [
url(r'^ | $', views.AP_list, name='AP_list'),
]
|
scaphilo/koalixcrm | koalixcrm/crm/documents/contract.py | Python | bsd-3-clause | 11,821 | 0.003215 | # -*- coding: utf-8 -*-
from django.db import models
from django.contrib import admin
from django.utils.translation import ugettext as _
from koalixcrm.plugin import *
from koalixcrm.crm.contact.phone_address import PhoneAddress
from koalixcrm.crm.contact.email_address import EmailAddress
from koalixcrm.crm.contact.p... | ion',
'default_customer',
'default_supplier',
'staff',
'default_currency',
'date_of_creation',
'last_modification',
'last_modified_by')
list_display_links = ('id',)
| list_filter = ('default_customer',
'default_supplier',
'staff',
'default_currency')
ordering = ('id', )
search_fields = ('id',
'contract')
fieldsets = (
(_('Basics'), {
'fields': ('description',
... |
jhazelwo/python-awscli | python2awscli/model/securitygroup.py | Python | mit | 6,235 | 0.001123 | """ -*- coding: utf-8 -*- """
from python2awscli import bin_aws
from python2awscli.error import AWSNotFound, ParseError, AWSDuplicate
from python2awscli import must
class BaseSecurityGroup(object):
def __init__(self, name, region, vpc, description, inbound=None, outbound=None):
"""
:param name: S... | bin_aws(command, key='SecurityGroups | ', max=1) # will raise NotFound if empty
me = result[0]
self.id = me['GroupId']
self.owner = me['OwnerId']
self.IpPermissions = self._break_out(me['IpPermissions'])
self.IpPermissionsEgress = self._break_out(me['IpPermissionsEgress'])
print('Got {0}'.format(command)) # ... |
Tristan79/ComicStreamer | comicstreamerlib/server.py | Python | apache-2.0 | 80,525 | 0.009637 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from datetime import date
import tornado.escape
import tornado.ioloop
import tornado.web
import urllib
import mimetypes
import re
import threading
from urllib2 import quote
from sqlalchemy import desc
from sqlalchemy.orm import joinedload,subqueryload,aliased
from sqlal... | :
def setContentType(self):
self.add_header("Content-type","application/json; charset=UTF-8")
def processPagingArgs(self, query):
per_page = self.get_argument(u"per_page", default=None)
offset = self.get_argument(u"offset", default=None)
# offset and max_results should be proces... | = None
if per_page is not None:
total_results = query.distinct().count()
try:
max = 0
max = int(per_page)
if total_results > max:
query = query.limit(max)
except:
pass
if... |
pforret/python-for-android | python3-alpha/python-libs/pyxmpp2/sasl/gssapi.py | Python | apache-2.0 | 3,008 | 0.003324 | #
# (C) Copyright 2008 Jelmer Vernooij <jelmer@samba.org>
# (C) Copyright 2011 Jacek Konieczny <jajcus@jajcus.net>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License Version
# 2.1 as published by the Free Software Foundation.
#
# This p... | .username = None
self._gss = None
self.step = None
self.authzid = None
def start(self, username, authzid):
self.username = username
self.authzid = authzid
_unused, self._gss = kerberos.authGSSClientInit(authzid or
"{0}@{1}".format("xmpp",
... | if self.step == 0:
ret = kerberos.authGSSClientStep(self._gss,
base64.b64encode(challenge))
if ret != kerberos.AUTH_GSS_CONTINUE:
self.step = 1
elif self.step == 1:
ret = kerberos.authGSSClientUnwrap(self... |
sunmont/textclassifier | tokenizer.py | Python | apache-2.0 | 1,809 | 0.007756 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import re
import numpy as np
import six
TOKENIZER_RE = re.compile(r"[A-Z]{2,}(?![a-z])|[A-Z][a-z]+(?=[A-Z])|[\'\w\-]+",
re.UNICODE)
class Tokenizer(object):
def __init__(self):
... | They also run an online retail store and maintainan active forum community.Q-workshop was established in 2001 by Patryk Strzelewicz – a student from Poznań. Initiallythe company sold its products via online auction services but in 2005 a website and online store wereestablished."
]
# test
i | f __name__ == '__main__':
tokenizer = Tokenizer()
tokenizer_ = tokenizer.tokenizer1
for tokens in tokenizer_(raw_doc):
for token in tokens:
print(token)
|
takluyver/Love | love/__main__.py | Python | mit | 147 | 0.020408 | fro | m __future__ import absolute_import
from .love import main
import s | ys
argv = sys.argv
if len(argv)>=2:
main(argv[1])
else:
main()
|
rachmansenpai/rach-devp | chivasbot.py | Python | gpl-3.0 | 83,839 | 0.010302 | # -*- coding: utf-8 -*-
import LineAlpha
from LineAlpha.Gen.ttypes import *
from datetime import datetime
import time,random,sys,json,codecs,threading,glob
cl = LineAlpha.LINE()
cl.login(qr=True)
cl.loginResult()
kk = LineAlpha.LINE()
kk.login(qr=True)
kk.loginResult()
ki = LineAlpha.LINE()
ki.login(qr=True)
ki.logi... | d:
| if op.param2 in Cmid:
X = kc.getGroup(op.param1)
X.preventJoinByTicket = False
kc.updateGroup(X)
Ti = kc.reissueGroupTicket(op.param1)
kk.acceptGroupInvitationByTicket(op.param1,Ti)
... |
misaki-nyanya/MyPieces | kancolle/buildCalc/run.py | Python | gpl-3.0 | 840 | 0.018519 | # -*- coding: cp936 -*-
import sys
default_encoding = 'utf-8'
if sy | s.getdefaultencoding() != default_encoding:
reload(sys)
sys.setdefaultencoding(default_encoding)
inf = open("F:/workspace/kancolle/log.txt",'r')
dahe=open("F:/workspace/kancolle/5-13-dahe.txt",'w')
dafeng=open("F:/workspace/kancolle/5-13-dafeng.txt",'w')
bsm=open("F:/workspace/kancolle/5-13-bsm.txt",'w')
m... | 果:大鳳')>0:
dafeng.write(line)
elif line.find(u'結果:Bismarck')>0:
bsm.write(line)
elif line.find(u'結果:まるゆ')>0:
maruyu.write(line)
line = inf.readline()
inf.close()
dahe.close()
dafeng.close()
bsm.close()
maruyu.close()
|
philanthropy-u/edx-platform | lms/djangoapps/onboarding/email_utils.py | Python | agpl-3.0 | 3,876 | 0.003354 | import base64
from django.conf import settings
from crum import get_current_request
from openedx.core.lib.request_utils import safe_get_host
from common.lib.mandrill_client.client import MandrillClient
def send_admin_activation_email(first_name, org_id, org_name, claimed_by_name, claimed_by_email, dest_addr, hash_ke... | e is either accepted as admin or rejected
Arguments:
org_name -- the name of the organization
current_admin -- the current admin of the organization
new_admin -- the new admin of the organization
confirm -- 1 if the current_admin has confirmed resignation else 0
"""
if confirm == 1:
... | il(MandrillClient.ORG_ADMIN_CLAIM_CONFIRMATION, current_admin.email, {
"first_name": current_admin.first_name,
"org_name": org_name,
"claimed_by_name": new_admin.email,
})
MandrillClient().send_mail(MandrillClient.NEW_ADMIN_CLAIM_CONFIRMATION, new_admin.email, {
... |
ubidiscordbot/ubi | src/lib/modules/clear.py | Python | mit | 108 | 0.009259 | #Short module amiright
def | main(message) | :
return [["purgeText", int(message.content.split(' ', 1)[1])]]
|
zepheira/exhibit | src/webapp/api/extensions/curate/files/admin/simplejson/__init__.py | Python | bsd-3-clause | 10,786 | 0.002781 | r"""
A simple, fast, extensible JSON encoder and decoder
JSON (JavaScript Object Notation) <http://json.org> is a subset of
JavaScript syntax (ECMA-262 3rd edition) used as a lightweight data
interchange format.
simplejson exposes an API familiar to uses of the standard library
marshal and pickle modules.
Encoding b... | h that indent level. An indent level
of 0 will only insert newlines. ``None`` is the most compact representation.
If ``separators`` is an ``(item_separator, dict_separator)`` tuple
then it will be used instead of the default ``(', ', ': ')`` separators.
``(',', ':')`` is the most compact JSON repres | entation.
``encoding`` is the character encoding for str instances, default is UTF-8.
To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
``.default()`` method to serialize additional types), specify it with
the ``cls`` kwarg.
"""
# cached encoder
if (skipkeys is False an... |
lewischeng-ms/pox | pox/core.py | Python | gpl-3.0 | 11,128 | 0.012491 | # Copyright 2011 James McCauley
#
# This file is part of POX.
#
# POX 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.
#
# POX is distri... | Ano | ther purpose to the central registration is that it decouples
functionality from a specific module. If myL2Switch and yourL2Switch
both register as "switch" and both provide the same API, then it doesn't
matter. Doing this with imports is a pain.
Additionally, a number of commmon API functions are vailable h... |
alcides/rdflib | rdflib/sparql/graphPattern.py | Python | bsd-3-clause | 15,809 | 0.013349 | # -*- coding: utf-8 -*-
#
#
# $Date: 2005/11/04 14:06:36 $, by $Author: ivan $, $Revision: 1.1 $
#
"""
Graph pattern class used by the SPARQL implementation
"""
import sys, os, time, datetime
from rdflib.term import Literal, BNode, URIRef, Variable
from types import *
from rdflib.namespace import NamespaceManager
from... | st of tuples")
def _generatePattern(self,tupl) :
"""
Append a tuple to the local patterns. Possible type literals
are converted to real literals on the fly. Each tuple should
be contain eit | her 3 elements (for an RDF Triplet pattern) or
four, where the fourth element is a per-pattern constraint
(filter). (The general constraint of SPARQL can be optimized
by assigning a constraint to a specific pattern; because it
stops the graph expansion, its usage might be much more
... |
lliendo/SimpleFSM | simplefsm/__init__.py | Python | lgpl-3.0 | 8,624 | 0.000464 | # -*- coding: utf-8 -*-
"""
This file is part of SimpleFSM.
SimpleFSM is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SimpleFSM is ... | ct):
"""
The Transition class models a transition between two given states.
To create a new transition three mandatory arguments must be supplied :
from_state : The state from which you want to transit.
to_state : The state you want to transit to.
transition_function : The function used to actu... | test if a symbol matches
the transition. This function must take only the symbol to be tested.
"""
def __init__(self, from_state, to_state, transition_function):
self._from_state = from_state
self._to_state = to_state
self._transition_function = transition_function
@property
... |
stackforge/solum | solum/tests/api/controllers/v1/test_trigger.py | Python | apache-2.0 | 14,612 | 0 | # Copyright 2013 - Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... | resp_mock, request_mock):
obj = trigger.TriggerController()
query = {'workflow': 'unittest+build+deploy'}
workflow = obj._get_workflow(query)
self.assertEqual(['unittest', 'build', 'deploy'], list(workflow))
| def test_trigger_get_workflow_with_invalid_stage(self, assem_mock,
resp_mock, request_mock):
obj = trigger.TriggerController()
query = {'workflow': 'unittest+unitunitunittest'}
workflow = obj._get_workflow(query)
self.assertEqual(['... |
devs1991/test_edx_docmode | venv/lib/python2.7/site-packages/opaque_keys/edx/tests/test_course_locators.py | Python | agpl-3.0 | 10,010 | 0.001598 | """
Tests of CourseKeys and CourseLocators
"""
import ddt
from bson.objectid import ObjectId
from opaque_keys import InvalidKeyError
from opaque_keys.edx.keys import CourseKey
from opaque_keys.edx.locator import BlockUsageLocator, CourseLocator
from opaque_keys.edx.tests import LocatorBaseTest, TestDeprecated
@dd... | ANCH_PREFIX,
'mit.eecs+' + CourseLocator.BRANCH_PREFIX + '@this ',
'mit.eecs+' + CourseLocator.BRANCH_PREFIX + '@th%is ',
u | '\ufffd',
)
def test_course_constructor_bad_package_id(self, bad_id):
"""
Test all sorts of badly-formed package_ids (and urls with those package_ids)
"""
with self.assertRaises(InvalidKeyError):
CourseLocator(org=bad_id, course='test', run='2014_T2')
with se... |
hyperspy/hyperspy | hyperspy/misc/utils.py | Python | gpl-3.0 | 51,574 | 0.000856 | # -*- coding: utf-8 -*-
# Copyright 2007-2022 The HyperSpy developers
#
# This file is part of HyperSpy.
#
# HyperSpy 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 y... | entation of the object.
set_item : easily set items, creating any necessary nodes on the way.
has_item: given a path, or part of a path, checks if the item exists.
get_item given a path, or part of a path, return the value of the item.
add_node : add all non existing nodes in a given path.
add_dict... | ryTreeBrowser()
>>> tree.set_item("Branch.Leaf1.color", "green")
>>> tree.set_item("Branch.Leaf2.color", "brown")
>>> tree.set_item("Branch.Leaf2.caterpillar", True)
>>> tree.set_item("Branch.Leaf1.caterpillar", False)
>>> tree
└── Branch
├── Leaf1
│ ├── caterpillar = False
... |
Danyc0/boatd | boatd/__init__.py | Python | lgpl-3.0 | 3,800 | 0 | from __future__ import print_function
import argparse
import logging
import imp
import os
import sys
from . import logger
from . import plugin
from . import nmea # noqa
from .api import BoatdHTTPServer, BoatdRequestHandler
from .behaviour import Be | haviour
from .behaviour import BehaviourManager
from .boat import Boat
from .color import color
from .config import Config
from .driver import BaseBoatdDriver # noqa
from .base_plugin import BasePlugin # noqa
__version__ = '2.0.0'
log = logging.getLogger()
def load_conf( | conf_file):
'''
Return the configuration object. Reads from the first argument by default,
otherwise falls back to 'boatd-config.yaml'.
'''
_, ext = os.path.splitext(conf_file)
if ext == '.json':
conf = Config.from_json(conf_file)
else:
conf = Config.from_yaml(conf_file)
... |
nickjhughes/polyominohs | generator.py | Python | mit | 7,968 | 0.005146 |
""" generator.py: Contains the Generator class. """
import random
import copy
import graphics
from helpers import *
# Just to check we have generated the correct number of polyominoes
# {order: number of omiones}
counts = {1: 1, 2: 1, 3: 2, 4: 7, 5: 18, 6: 60}
class Generator:
""" A class for generatin... | ax([v for k, v in colfractions.iteritems() \
if k in rowpicked_rotations])
colpicked_rotations = [k for k, v in colfractions.iteritems() \
if v == colpick and k in rowpicked_rotations]
if len(colpicked_rotations) == 0:
... | ons[0]
else:
rotations = rowpicked_rotations[0]
normalised = copy.deepcopy(polyomino)
for rotation in xrange(rotations):
normalised = self._rotate(normalised)
normalised = self._move(normalised)
return normalised
def _move(self, polyomino... |
jelmer/isso | isso/utils/html.py | Python | mit | 3,145 | 0.000954 | # -*- encoding: utf-8 -*-
from __future__ import unicode_literals
import html
import bleach
import misaka
from configparser import NoOptionError
class Sanitizer(object):
def __init__(self, elements, attributes):
# attributes found in Sundown's HTML serializer [1]
# except for <img> tag,
... | "em",
"h1", "h2", "h3", "h4", "h5", "h6",
"table", "thead", "tbody", "th", "td"] + elements
# href for <a> and align for <table>
| self.attributes = ["align", "href"] + attributes
def sanitize(self, text):
clean_html = bleach.clean(text, tags=self.elements, attributes=self.attributes, strip=True)
def set_links(attrs, new=False):
href_key = (None, u'href')
if href_key not in attrs:
... |
FrozenPigs/Taigabot | plugins/_broken/chatbot.py | Python | gpl-3.0 | 874 | 0.006865 | import urllib
import urllib2
import xml.dom.minidom
import re
import socket
from util import hook
c | hatbot_re = (r'(^.*\b(taiga|taigabot)\b.*$)', re.I)
@hook.regex(*chatbot_re)
@hook.command
def chatbot(inp, reply=None, nick=None, conn=None):
inp = inp.group(1).lower().replace('taigabot', '').replace('taiga' | , '').replace(':', '')
args = {'bot_id': '6', 'say': inp.strip(), 'convo_id': conn.nick, 'format': 'xml'}
data = urllib.urlencode(args)
resp = False
url_response = urllib2.urlopen('http://api.program-o.com/v2/chatbot/?', data)
response = url_response.read()
response_dom = xml.dom.minidom.parseSt... |
quozl/sugar-toolkit-gtk3 | examples/ticket2855.py | Python | lgpl-2.1 | 1,719 | 0 | # Copyright (C) 2007, Red Hat, Inc.
#
# This library 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 2 of the License, or (at your option) any later version.
#
# This library is distrib... | ='go-previous', pixel_size=style.STANDARD_ICON_SIZE)
toggle.set_image(icon)
bo | x.pack_start(toggle, False, False, 0)
toggle.show()
radio = Gtk.RadioButton()
icon = Icon(icon_name='go-next', pixel_size=style.STANDARD_ICON_SIZE)
radio.set_image(icon)
radio.set_mode(False)
box.pack_start(radio, False, False, 0)
radio.show()
palette.set_content(box)
box.show()
if __name__ == '__main__':
comm... |
cleverhans-lab/cleverhans | cleverhans_v3.1.0/cleverhans/experimental/certification/nn.py | Python | mit | 11,199 | 0.001429 | """This file defines the neural network class, where a network is reinitialized from configuration files.
The class also has a forward propagation method.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import json
import numpy as np
import tensorflow ... | :
vector: vector that has to be p | assed through in forward pass
layer_index: index of the layer
is_transpose: whether the weights of the layer have to be transposed
is_abs: whether to take the absolute value of the weights
Returns:
tensor that corresponds to the forward pass through the layer
Rai... |
dmacvicar/spacewalk | backend/server/rhnServer/server_kickstart.py | Python | gpl-2.0 | 28,246 | 0.002868 | #
# Copyright (c) 2008--2012 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a c... | are(_query_get_next_action_id)
h.execute(action_id=action_id, next_action_type=next_action_type)
row = h.fetchone_dict()
if not row:
return None
return row['id']
_query_lookup_kickstart_session_id = rhnSQL.Statement("""
select ks.id
from rhnKickstartSession ks
where (
... | server_id is NULL)
or ks.new_server_id = :server_id
or ks.host_server_id = :server_id
)
and ks.action_id = :action_id
""")
def get_kickstart_session_id(server_id, action_id):
h = rhnSQL.prepare(_query_lookup_kickstart_session_id)
h.execute(server_id=server_id, action... |
MuckRock/muckrock | muckrock/communication/importers.py | Python | agpl-3.0 | 2,224 | 0 | """
Custom importers for addresses
"""
# Django
from django.conf import settings
# Standard Library
import csv
import re
# Third Party
from localflavor.us.us_states import STATE_CHOICES
from smart_open.smart_open_lib import smart_open
# MuckRock
from muckrock.communication.models import Address
# columns
AGENCY_PK... | try:
address.save()
except Exception as exc:
print( | "Data Error", exc, row[ADDRESS_PK])
print(row)
|
mansonul/events | events/contrib/plugins/form_elements/fields/ip_address/__init__.py | Python | mit | 382 | 0 | __title__ = 'fobi.contrib.plugins.form_elements.fields.ip_address'
__author__ = 'Artur | Barseghyan <artur.barseghyan@gmail.com>'
__copyright__ = '2014-2017 Artur Barseghyan'
__license__ = 'GPL 2.0/LGPL 2.1'
__all__ = ('default_app_config', 'UID',)
default_app_config = 'fobi.contrib.plugins.form_elements.fields.' \
| 'ip_address.apps.Config'
UID = 'ip_address'
|
antoinecarme/sklearn2sql_heroku | tests/regression/RandomReg_500/ws_RandomReg_500_GradientBoostingRegressor_sqlite_code_gen.py | Python | bsd-3-clause | 146 | 0.013699 | from sklearn2sql_heroku.tests.regression import generic as reg_gen
reg_gen.test_model("GradientB | oostingRegressor" , "RandomReg_50 | 0" , "sqlite")
|
pattisdr/osf.io | website/files/utils.py | Python | apache-2.0 | 1,720 | 0.002907 |
def copy_files(src, target_node, parent=None, name=None):
"""Copy the files from src to the target node
:param Folder src: The source to copy children from
:param Node target_node: The node to copy files to
:param Folder parent: The parent of to attach the clone of src to, if applicable
"""
ass... | versions.add(*fileversions[1:])
# create a new most recent version and update the region before adding
new_fileversion = most_recent_fileversion.clone()
new_fileversion.region = target_node.osfstorage_region
new_fileversion.save()
| cloned.versions.add(new_fileversion)
else:
cloned.versions.add(*src.versions.all())
# copy over file metadata records
if cloned.provider == 'osfstorage':
for record in cloned.records.all():
record.metadata = src.records.get(schema__name=record.schema.n... |
JaneliaSciComp/osgpyplusplus | examples/rough_translated1/osgwidgetprogress.py | Python | bsd-3-clause | 2,695 | 0.014842 | #!/bin/env python
# Automatically translated python version of
# OpenSceneGraph example program "osgwidgetprogress"
# !!! This program will need manual tuning before it will work. !!!
import sys
from osgpypp import osgDB
from osgpypp import osgWidget
# Translated from file 'osgwidgetprogress.cpp'
# -*-c++-*- osg... |
canvas = osgWidget.Canvas("canvas")
pOutline = osgWidget.Widget("pOutline", 512.0, 64.0) |
pMeter = osgWidget.Widget("pMeter", 0.0, 64.0)
pLabel = osgWidget.Label("pLabel", "0% Done")
pOutline.setImage("osgWidget/progress-outline.png", True)
pOutline.setLayer(osgWidget.Widget.LAYER_MIDDLE, 2)
pMeter.setImage("osgWidget/progress-meter.png")
pMeter.setColor(0.7, 0.1, 0.1, 0.7)
... |
labordus/cornice | common.py | Python | gpl-2.0 | 8,653 | 0.008321 | # common.py: global variables
# arch-tag: global variables
# author: Alberto Griggio <agriggio@users.sourceforge.net>
# license: GPL
import wx
import os, sys, locale, Image
import threading
__version__ = '0.6.1'
if os.path.expanduser('~') != '~':
bookmarks_file = os.path.expanduser('~/.cornice/bookmarks')
co... | sk.SetData(pil_image.convert('RGB').tostring())
## color = wx.Colour(*[ord(c) for c in rgb[:3]])
## if wx.VERSION[:3] >= (2, 5, 2):
## return wx.Mask(mask.ConvertToBitmap(), color)
## else:
## return wx.MaskColour(mas | k.ConvertToBitmap(), color)
## else:
if wx.Platform != '__WXGTK__': c1, c2 = 255, 0
else: c1, c2 = 0, 255
palette = [c1] * 768 #[255] * 768
palette[transparency*3 : transparency*3 + 3] = [c2, c2, c2]#[0, 0, 0]
pil_image = pil_image.copy()
... |
nextgis-extra/tests | lib_gdal/gcore/hfa_read.py | Python | gpl-2.0 | 2,508 | 0.005183 | #!/usr/bin/env python
###############################################################################
# $Id: hfa_read.py 32166 2015-12-13 19:29:52Z goatbar $
#
# Project: GDAL/OGR Test Suite
# Purpose: Test basic read support for all datatypes from a HFA file.
# Author: Frank Warmerdam <warmerdam@pobox.com>
#
#####... | ('uint32.img', 1, 4672, None),
('float32.img', 1, 4672, None),
('float64.img', 1, 4672, None),
('utmsmall.img', 1, 50054, None),
('2bit_compressed.img', 1, 11918, None)]
for item in init_list:
ut = gdaltest.GDALTest( 'HFA', item[0], item[1], i | tem[2] )
if ut is None:
print( 'HFA tests skipped' )
sys.exit()
gdaltest_list.append( (ut.testOpen, item[0]) )
if __name__ == '__main__':
gdaltest.setup_run( 'hfa_read' )
gdaltest.run_tests( gdaltest_list )
gdaltest.summarize()
|
numenta/nupic.vision | src/nupic/vision/data/OCR/characters/parseJPG.py | Python | agpl-3.0 | 7,772 | 0.019429 | #!/usr/bin/python2
'''
This script parses JPEG images of text documents to isolate and save images
of individual characters. The size of these output images in pixels is
specified by the parameters desired_height and desired_width.
The JPEG images are converted to grey scale using a parameter called
luminance_thre... | ay(list(im.getdata())).reshape(im.size[1],im.size[0])
elif | im.mode == 'RGB':
pixels = np.array(list(im.convert('L').getdata())).reshape(im.size[1],
im.size[0])
#im.show()
##############################################################################
# Removed all logic for determining the value to use to distinguish between
# light and dark pixels beca... |
trhongbinwang/data_science_journey | deep_learning/keras/examples/imdb_cnn.py | Python | apache-2.0 | 2,519 | 0.004367 | '''This example demonstrates the use of Convolution1D for text classification.
Gets to 0.89 test accuracy after 2 | epochs.
90s/epoch on Intel i5 2.4Ghz CPU.
10s/epoch on Tesla K40 GPU.
'''
from __future__ import print_function
from tensorflow.contrib | .keras.python.keras.preprocessing import sequence
from tensorflow.contrib.keras.python.keras.models import Model
from tensorflow.contrib.keras.python.keras.layers import Dense, Dropout, Activation
from tensorflow.contrib.keras.python.keras.layers import Input, Embedding
from tensorflow.contrib.keras.python.keras.layers... |
flipcoder/litebot | plugins/highfive.py | Python | mit | 268 | 0.029851 | def highfive(ctx, serv, nick, dest, msg):
if msg=="\o":
| serv.say(dest, "o/")
elif msg=="o/":
serv.say(dest, "\o")
elif msg=="o'":
serv.say(dest, "'o")
elif msg=="'o":
serv.say(dest, "o'")
serv.on_msg.connect(highf | ive)
|
Suwmlee/XX-Net | gae_proxy/server/lib/google/appengine/datastore/document_pb.py | Python | bsd-2-clause | 55,713 | 0.021144 | #!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | # See the License for the specific language governing permissions and
# l | imitations under the License.
#
from google.net.proto import ProtocolBuffer
import array
import _dummy_thread as thread
__pychecker__ = """maxreturns=0 maxbranches=0 no-callinit
unusednames=printElemNumber,debug_strs no-special"""
if hasattr(ProtocolBuffer, 'ExtendableProtocolMessage'):
_exten... |
doudz/checkfeedmail | icon.py | Python | bsd-2-clause | 9,632 | 0.012978 | import cStringIO
import zlib
import wx
#----------------------------------------------------------------------
def getMailData():
return zlib.decompress(
"x\xda\x01M\x01\xb2\xfe\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00 \x00\
\x00\x00 \x08\x06\x00\x00\x00szz\xf4\x00\x00\x00\x04sBIT\x08\x08\x08\x08|\... | f\xbd\xc7\xf7\xf5:\xff\xfa\xf7G\xd2\xdf\n\
\xb0w\xff>\xd7\x83\x80\xeah\x84q\xe5\x93F#:GG\xec\x95\xcb\xdb\x86C\xdaV\x03\
\xdfjj\xfeZ\x9e#\xc71\xf2|\x0e\xc0\\\x96\x99\xab*?J\x12oF\xf1V+\xb0\xb5\x06\
\x1cUE\xccfEr\x00y>G\xccf8\xaa\xbam8\xc4\x7f>\xf98\xcf\xf3|\xc9\xd9n\xb7\xd9\
\xdb\xdbCQ\x94%\xff\xf5\xef\xbe\xa3~\xef\... | xfa\xf4\xe9*@\xa5RYu\nA\x92$\xe8\xba\
\x8eeY\xc5cw\xbb\xe8\xba\xbe\xf1kt]g\x7f\x7f\x1f\xeb\xe5\x97\xf1}\xbfx\x82 @\
\x08A\xb5Z]\xcd\xb5.\x90\xe7y\x84a\xc8\xee\xee.\x86a`\x9a&\xedv\x1b\xab\xd1@\
<g\x99UU\xa5\xd1h\xa0\xb7\xdbt\xbb]...\x18\x8dF\xf4\xfb}\xd24];g\t`\x91L\x92\
.u\x94\xe79\xc3\xe1\x10UU)\x97\xcb\x94\xc2\x... |
Clarity-89/clarityv2 | src/clarityv2/utils/storages.py | Python | mit | 685 | 0 | from django.conf import settings
from django.core.files.storage import FileSystemStorage
from django.utils.functional import LazyObject
class PrivateMediaFileSystemStorage(FileSystemSt | orage):
"""
Storage that puts files in the private media folder that isn't
globally available.
"""
def __init__(self, *args, **kwargs):
| kwargs.setdefault('location', settings.PRIVATE_MEDIA_ROOT)
kwargs.setdefault('base_url', settings.PRIVATE_MEDIA_URL)
super().__init__(*args, **kwargs)
class PrivateMediaStorage(LazyObject):
def _setup(self):
self._wrapped = PrivateMediaFileSystemStorage()
private_media_storage = Pr... |
fbradyirl/home-assistant | homeassistant/components/zha/core/const.py | Python | apache-2.0 | 5,498 | 0.000182 | """All constants related to the ZHA component."""
import enum
import logging
from homeassistant.components.binary_sensor import DOMAIN as BINARY_SENSOR
from homeassistant.components.device_tracker import DOMAIN as DEVICE_TRACKER
from homeassistant.components.fan import DOMAIN as FAN
from homeassistant.components.light... | IGURATION = "power"
CHANNEL_ZDO = "zdo"
CHANNEL_ZONE = ZONE = "ias_zone"
CLUSTER_COMMAND_SERVER = "server"
CLUSTER_COMMANDS_CLIENT = "client_commands"
CLUSTER_COMMANDS_SERVER = "server_commands"
CLUSTER_TYPE_IN = "in"
CLUSTER_TYPE_OUT = "out"
COMPONENTS = (BINARY_SENSOR, DEVICE_TRACKER, FAN, LIGHT, LOCK, SENSOR, SWIT... | CE_CONFIG = "device_config"
CONF_ENABLE_QUIRKS = "enable_quirks"
CONF_RADIO_TYPE = "radio_type"
CONF_USB_PATH = "usb_path"
CONTROLLER = "controller"
DATA_DEVICE_CONFIG = "zha_device_config"
DATA_ZHA = "zha"
DATA_ZHA_CONFIG = "config"
DATA_ZHA_BRIDGE_ID = "zha_bridge_id"
DATA_ZHA_CORE_EVENTS = "zha_core_events"
DATA_ZH... |
HydrelioxGitHub/home-assistant | homeassistant/components/rainmachine/__init__.py | Python | apache-2.0 | 10,913 | 0 | """Support for RainMachine devices."""
import logging
from datetime import timedelta
import voluptuous as vol
from homeassistant.config_entries import SOURCE_IMPORT
from homeassistant.const import (
ATTR_ATTRIBUTION, CONF_BINARY_SENSORS, CONF_IP_ADDRESS, CONF_PASSWORD,
CONF_PORT, CONF_SCAN_INTERVAL, CONF_SENS... | c_dispatcher_send(hass, PROGRAM_UPDATE_TOPIC)
for service, method, schema in [
('pause_watering', pause_watering, SERVICE_PAUSE_WATERING),
('start_program', start_program, SERVICE_START_PROGRAM_SCHEMA),
('start_zone', start_zone, SERVICE_START_ZO | NE_SCHEMA),
('stop_all', stop_all, {}),
('stop_program', stop_program, SERVICE_STOP_PRO |
AccelAI/accel.ai | flask-aws/lib/python2.7/site-packages/docker/api/image.py | Python | mit | 9,342 | 0 | import logging
import six
import warnings
from ..auth import auth
from ..constants import INSECURE_REGISTRY_DEPRECATION_WARNING
from .. import utils
from .. import errors
log = logging.getLogger(__name__)
class ImageApiMixin(object):
@utils.check_resource
def get_image(self, image):
res = self._get... | epository)
registry, repo_name = auth.resolve_repository_name(repository)
u = self._url("/images/{0}/push", repository)
params = {
'tag': tag
}
headers = {}
if uti | ls.compare_version('1.5', self._version) >= 0:
# If we don't have any auth data so far, try reloading the config
# file one more time in case anything showed up in there.
if not self._auth_configs:
self._auth_configs = auth.load_config()
authcfg = auth.res... |
lukecwik/incubator-beam | website/append_index_html_to_internal_links.py | Python | apache-2.0 | 4,461 | 0.008518 | # 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 use... | ursively walk content directory and find all html files.
for root, | dirnames, filenames in os.walk(args.content_dir):
for filename in fnmatch.filter(filenames, '*.html'):
# Javadoc does not have the index.html problem, so omit it.
if 'javadoc' not in root:
matches.append(os.path.join(root, filename))
print('Matches: ' + str(len(matches)))
# Iterates over each matched ... |
cliffton/localsecrets | offers/migrations/0001_initial.py | Python | mit | 3,179 | 0.004404 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-05-07 16:56
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import model_utils.fields
class Migration(migrations.Migration):
... | ls.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related | _name='offers_reviewed', to=settings.AUTH_USER_MODEL)),
],
options={
'abstract': False,
},
),
]
|
aluchies/impedance_map | impedance_map/tests/test_sphere.py | Python | bsd-3-clause | 6,422 | 0.001246 | from impedance_map.sphere import correlation_coefficient, form_factor, \
pair_distribution_function_PY, structure_factor_function_PY, \
cross_section_dimension, fit_correlation_coefficient_nls, \
fit_form_factor_nls
import numpy as np
import math
import unittest
class TestCode(unittest.TestCase):
def ... | (0.01, 3, 10)
y = form_factor(a=a, k=k)
a_guess = fit_form_factor_nls(k, y)
self.assertTrue(np.allclose(a, a_guess))
if __name__ == '__main__':
print 'Running unit tests for impedance_map.sphere'
un | ittest.main()
|
abc612008/datatoaster | setup.py | Python | mit | 474 | 0.004219 | from | setuptools import setup, find_packages
with open('README.md', encoding = "utf-8") as f:
readme = f.read()
setup(
name='datatoaster',
version='0.1.0',
description='A Python library that can convert raw data to chart data',
long_description=readme,
author='Harry Yu',
author_email='harryyunul... | ackages(exclude=('tests', 'docs', 'demo'))
)
|
AerisCloud/AerisCloud | aeriscloud/cli/aeris/destroy.py | Python | mit | 271 | 0 | #!/usr/bin/env python
import click
from aerisclou | d.cli.helpers import standard_options, Command
@click.command(cls=Command)
@standard_options(start_prompt=False)
def cli(box):
"""
Destroy a box
"""
box. | destroy()
if __name__ == '__main__':
cli()
|
Fokko/incubator-airflow | airflow/gcp/example_dags/example_spanner.py | Python | apache-2.0 | 8,612 | 0.002206 | # -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
#... | d Spanner instance.
* GC | P_SPANNER_INSTANCE_ID - Cloud Spanner instance ID.
* GCP_SPANNER_DATABASE_ID - Cloud Spanner database ID.
* GCP_SPANNER_CONFIG_NAME - The name of the instance's configuration. Values are of the
form ``projects/<gcp_project>/instanceConfigs/<configuration>``. See also:
https://cloud.google.com/spanner/docs/reference... |
vernnobile/Gnu_Free_Font | tools/test/ranges/Arabic/unicode_joining.py | Python | gpl-3.0 | 8,257 | 0.016108 | #!/usr/bin/python
from __future__ import print_function, unicode_literals
__license__ = """
This file is part of GNU FreeFont.
GNU FreeFont 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 ... | g.py
to generate
arabic_shaping.py"""
try:
from arabic_shaping import arabic_shapings, joining_type
except:
print( _module_missing_msg, file=sys.stderr)
sys.exit( 1 )
if len(sys.argv) > 1:
outfile = sys.argv[1]
else:
outfile = 'Unicode joining test page.html'
sys.stdout = open(outfile, 'w', 'utf-8')
class Ord... | aultDict(OrderedDict):
def __missing__(self, key):
self[key] = rv = []
return rv
def move_to_end(self, key):
tmp = self[key]
del self[key]
self[key] = tmp
arabic_ranges = tuple(chain(range(0x600, 0x6FF +1), range(0x750, 0x77F +1), range(0x8A0, 0x8FF)))
unicode61_new_ranges = [0x604, 0x8A0]
unicode61_new_ra... |
per7inac1ousQ/Directories | DirectoriesBackupFiles/models.py | Python | apache-2.0 | 7,043 | 0.015618 | # This is an auto-generated Django model module.
# You'll have to do the following manually to clean this up:
# * Rearrange models' order
# * Make sure each model has one field with primary_key=True
# * Remove `managed = False` lines for those models you wish to give write DB access
# Feel free to rename the mode... | e instantiate a def _unicode_ function that will return model's name?
class Dep | artment(models.Model):
id = models.AutoField(primary_key=True)
tmima_per = models.TextField()
proedros = models.IntegerField(default='0')
pr_spoudwn = models.TextField()
pr_spoudwn_en = models.TextField()
tmima_per_en = models.TextField()
tmima_en = models.CharField(max_length=5)
homepag... |
ankanaan/chimera | src/chimera/util/vizquery.py | Python | gpl-2.0 | 3,452 | 0.000579 | from chimera.util.votable import VOTable
from httplib import HTTPConnection
import tempfile
import os
import urllib
class VizQuery(object):
"""
Queries A catalog in Vizier
within a given radius or box of the zenith
"""
def __init__(self):
self.args = {}
self.args["-mime"] = "xml... | lts = tempfile.NamedTemporaryFile(mode='w+',
prefix="chimera.vizquery",
dir= | tempfile.gettempdir())
# query the catalog in Vizier's database
conn = HTTPConnection("webviz.u-strasbg.fr")
s = urllib.urlencode(self.args)
conn.request("POST", "/viz-bin/votable", s)
resp = conn.getresponse()
ret = resp.read()
f = open(results.name, "w")
... |
fametrano/BitcoinBlockchainTechnology | tests/test_hashes.py | Python | mit | 1,276 | 0.000784 | #!/usr/bin/env python3
# Copyright (C) 2017-2021 The btclib developers
#
# This file is part of btclib. It is subject to the license terms in the
# LICENSE file found in the top-level directory of this distribution.
#
# No part of btclib including this file, may be copied, modified, propagated,
# or distributed except... | ,
)
def test_hash160_hash256() -> None:
test_vectors = (
plain_prv_keys
+ net_unaware_compressed_pub_keys
+ net_unaware_uncompressed_pub_keys
)
for hexstring in test_vectors:
hash160(hexstring)
hash256(hexstrin | g)
# def test_fingerprint() -> None:
#
# seed = "bfc4cbaad0ff131aa97fa30a48d09ae7df914bcc083af1e07793cd0a7c61a03f65d622848209ad3366a419f4718a80ec9037df107d8d12c19b83202de00a40ad"
# xprv = rootxprv_from_seed(seed)
# pf = fingerprint(xprv) # xprv is automatically converted to xpub
# child_key = derive(... |
tucbill/manila | manila/scheduler/filter_scheduler.py | Python | apache-2.0 | 8,816 | 0.000113 | # Copyright (c) 2011 Intel Corporation
# Copyright (c) 2011 OpenStack, LLC.
# 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/l... | es is None:
filter_properties = {}
self._populate_retry_share(filter_properties, resource_properties)
filter_properties.update({'context': context,
'request_spec': request_spec,
'config_options': config_options,
... | 'share_type': share_type,
'resource_type': resource_type
})
self.populate_filter_properties_share(request_spec, filter_properties)
# Find our local list of acceptable hosts by filtering and
# weighing our options... |
djo938/GPSPythonSharingWithPyro | pysharegps/gpsSharedData.py | Python | gpl-3.0 | 1,548 | 0.016796 |
import sys
class sharedGpsData(object):
def __init__(self):
self.pos = (0.0,0.0,None,) # float latitude(from equateur),float longitude(from greenwitch),datetime (Universal Time Coordinated)
self.alt = (0.0, "M", None,) # float altitude, string scale unit, datetime (Universal Time Coordinated... | hareDaemonId
###
def setPosition(self, latitude, longitude, dtime):
self.pos = (latitude, longitude, dtime,)
|
def getPosition(self):
return self.pos
###
def setAltitude(self, altitude, dtime, unit = "M"):
self.alt = (altitude, unit, dtime,)
def getAltitude(self):
return self.alt
###
def setPlace(self, placename, distance, distanceType, dtime, unit ... |
YeoLab/gscripts | gscripts/general/downsample_bam.py | Python | mit | 4,356 | 0.008494 | __author__ = 'gpratt'
__author__ = 'gpratt'
import argparse
import subprocess
import os
def wrap_wait_error(wait_result):
if wait_result != 0:
raise NameError("Failed to execute command correctly {}".format(wait_result))
def pre_process_bam(bam, bam01, bam02, bam03, bam04, bam05, bam06, bam07, bam08, ba... | bam, percent, bam_file)
else: #sort
cmd = "samtools view -h {0}.bam | head -n {1} | samtools view -bS - | samtools sort - -o {2} && samtools index {2}".format(shuffled_bam, | percent, bam_file)
print cmd
p1 = subprocess.Popen(cmd, shell=True)
wrap_wait_error(p1.wait())
if not no_shuffle: #if we are aren't shuffling, don't delete
p1 = subprocess.Popen("rm {0}.bam".format(shuffled_bam), shell=True)
wrap_wait_error(p1.wait())
retu... |
Arcbot-Org/Arcbot | tests/discord/test_permission.py | Python | gpl-3.0 | 1,719 | 0 | import unittest
from bolt.discord.permissions import Permission
class TestPermission(unittest.TestCase):
def test_permission_from_list_to_list(self):
expected = ['MANAGE_WEBHOOKS', 'USE_EXTERNAL_EMOJIS']
permission = Permission(['MANAGE_WEBHOOKS', 'USE_EXTERNAL_EMOJIS'])
actual = permiss... | (2056)
self.assertTrue(permission.allows("ADMINISTRATOR"))
self.assertFalse(permission.allows("MENTION_EVERYONE"))
permission.add(" | MENTION_EVERYONE")
self.assertTrue(permission.allows("MENTION_EVERYONE"))
def test_permission_remove(self):
permission = Permission(2056)
self.assertTrue(permission.allows("ADMINISTRATOR"))
self.assertTrue(permission.allows("SEND_MESSAGES"))
permission.remove("SEND_MESSAGES... |
tanglei528/glance | glance/tests/unit/v2/test_registry_client.py | Python | apache-2.0 | 24,618 | 0.000081 | # Copyright 2013 Red Hat, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by... | unjsonify=False)
def test_get_index_sort_status_desc(self):
"""
Tests that the registry API returns list of
public images sorted alphabetically by status | in
descending order.
"""
uuid4_time = timeutils.utcnow() + datetime.timedelta(seconds=10)
UUID3 = _gen_uuid()
extra_fixture = self.get_fixture(id=UUID3, name='asdf',
status='queued')
db_api.image_create(self.context, extra_fixtur... |
thomasanderson9000/ipredator_btt | transmission/healthcheck.py | Python | apache-2.0 | 1,116 | 0.005376 | #!/usr/bin/env python
from __future__ import print_function
from time import sleep
from subprocess import call
import os
from drive import get_active_torrents_count, get_vpn_ip, WAIT_CYCLE
MAX_FAIL=2
def transmission_down():
try:
_ = get_active_torrents_count()
return False
except Exception as... | etting vpn IP: {}".format(exc))
return True
def suicide():
"""Kill tini which will cause everything to restart properly."""
print("Something went wrong, comitting suicide.")
call("pkill -f tini", shell=True)
if __name__ == "__main__":
fail_count = 0
while True:
sleep(WAIT_CYCLE)
... | print("Fail count: {}".format(fail_count))
else:
fail_count = 0
if fail_count >= MAX_FAIL:
suicide()
|
wikimedia/pywikibot-core | pywikibot/families/meta_family.py | Python | mit | 564 | 0 | """Family module for Meta Wiki." | ""
#
# (C) Pywikibot team, 2005-2020
#
# Distributed under the terms of the MIT license.
#
from pywikibot import family
# The Wikimedia Meta-Wiki family
class Family(family.WikimediaOrgFamily):
"""Family class for Meta Wiki."""
| name = 'meta'
interwiki_forward = 'wikipedia'
cross_allowed = ['meta', ]
category_redirect_templates = {
'meta': (
'Category redirect',
),
}
# Subpages for documentation.
doc_subpages = {
'_default': (('/doc',), ['meta']),
}
|
selfcommit/gaedav | pyxml/sax/saxutils.py | Python | lgpl-2.1 | 24,606 | 0.005486 | """
A library of useful helper classes to the saxlib classes, for the
convenience of application and driver writers.
$Id: saxutils.py,v | 1.35 2004/03/20 07:46:04 fdrake Exp $
"""
import os, urlparse, urllib2, types
import handler
import xmlreader
import sys, _exceptions, saxlib
try:
_StringTypes = [types.S | tringType, types.UnicodeType]
except AttributeError: # 1.5 compatibility:UnicodeType not defined
_StringTypes = [types.StringType]
def __dict_replace(s, d):
"""Replace substrings of a string using a dictionary."""
for key, value in d.items():
s = s.replace(key, value)
return s
def escape(data,... |
tensorflow/tfx | tfx/dsl/compiler/testdata/foreach_pipeline.py | Python | apache-2.0 | 2,580 | 0.003488 | # Copyright 2021 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | with_id('latest_stats_resolver')
s | chema_gen = SchemaGen(statistics=latest_stats_resolver.outputs['statistics'])
with for_each.ForEach(example_gen.outputs['examples']) as each_example:
trainer = Trainer(
module_file='/src/train.py',
examples=each_example,
schema=schema_gen.outputs['schema'],
train_args=trainer_pb2.... |
goodmami/penman | penman/transform.py | Python | mit | 13,014 | 0 |
"""
Tree and graph transformations.
"""
from typing import Optional, Dict, Set, List, Tuple
import logging
from penman.types import (Variable, Target, BasicTriple, Node)
from penman.exceptions import ModelError
from penman.epigraph import (Epidatum, Epidata)
from penman.surface import (Alignment, RoleAlignment, alig... | riple] = out_epis
# we don't know where to put the final POP without configuring
# the tree; maybe this should be a tree operation?
else:
new_triples.append(triple)
g = Graph(new_triples,
epidata=new_epidata,
metadata=g.metadata)
logger.inf... | e reifications in *model*.
Args:
g: a :class:`~penman.graph.Graph` object
Returns:
A new :class:`~penman.graph.Graph` object with dereified
edges.
Example:
>>> from penman.codec import PENMANCodec
>>> from penman.models.amr import model
>>> from penman.transf... |
jawilson/home-assistant | homeassistant/components/ovo_energy/__init__.py | Python | apache-2.0 | 3,757 | 0.000799 | """Support for OVO Energy."""
from __future__ import annotations
from datetime import datetime, timedelta
import logging
import aiohttp
import async_timeout
from ovoenergy import OVODailyUsage
from ovoenergy.ovoenergy import OVOEnergy
from homeassistant.config_entries import ConfigEntry
from homeassistant.const impo... | ,
coordinator: DataUpdateCoordinator,
client: OVOEnergy,
) -> None | :
"""Initialize the OVO Energy entity."""
super().__init__(coordinator)
self._client = client
class OVOEnergyDeviceEntity(OVOEnergyEntity):
"""Defines a OVO Energy device entity."""
@property
def device_info(self) -> DeviceInfo:
"""Return device information about this OVO ... |
edenhuangSH/STA663_Final_Project | setup.py | Python | gpl-3.0 | 1,203 | 0.010806 |
"""Hidden Markov Models implemented in linear memory/running time"""
from distutils.core import setup
from distutils.extension import Extension
import numpy
try:
from Cython.Distutils import build_ext
except ImportError:
use_cython = False
else:
use_cython = True
cmdclass = { }
ext_modules = [ ]
if use... | arhmm.score", [ "linearhmm/score.c" ],include_dirs=[numpy.get_include()]),
]
import linearhmm
VERSION = linearhmm.__version__
# MAINTAINER = "Sergei Lebedev"
# MAINTAINER_EMAIL = "superbobry@gmail.com"
install_require | s = ["numpy"]
tests_require = install_requires + ["pytest"]
setup_options = dict(
name="linearhmm",
version=VERSION,
# maintainer=MAINTAINER,
# maintainer_email=MAINTAINER_EMAIL,
url="https://github.com/hmmlearn/hmmlearn",
packages=["linearhmm"],
ext_modules=ext_modules,
cmdclass=cmdcl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.