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 |
|---|---|---|---|---|---|---|---|---|
montaggroup/montag-token-redeemer | web2py/applications/token_redeemer/languages/pl-pl.py | Python | gpl-3.0 | 3,788 | 0.022703 | # coding: utf8
{
'"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"Uaktualnij" jest dodatkowym wyra\xc5\xbceniem postaci "pole1=\'nowawarto\xc5\x9b\xc4\x87\'". Nie mo\xc5\xbcesz uaktualni\xc4\x87 lub usun\xc4\x85\xc4\x87 wynik\xc3\xb3w z JOIN:',
'%Y-%m... | d more complex queries.': 'U\xc5\xbcyj (...)&(...) jako AND, (...)|(... | ) jako OR oraz ~(...) jako NOT do tworzenia bardziej skomplikowanych zapyta\xc5\x84.',
'View': 'View',
'Welcome %s': 'Welcome %s',
'Welcome to web2py': 'Witaj w web2py',
'appadmin is disabled because insecure channel': 'appadmin is disabled because insecure channel',
'cache': 'cache',
'change password': 'change passwo... |
ArnossArnossi/checkmate | checkmate/contrib/plugins/python/metrics/issues_data.py | Python | agpl-3.0 | 813 | 0.00246 | # -*- coding: utf-8 -*-
"""
This file is part of checkmate, a meta code checker written in Python.
Copyright (C) 2015 Andreas Dewes, QuantifiedCode UG
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 Foun... | ven the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/ | >.
"""
issues_data = {
} |
Fendoe/open-hackathon-o | open-hackathon-server/src/hackathon/util.py | Python | mit | 5,753 | 0.001912 | # -*- coding: utf-8 -*-
#
# -----------------------------------------------------------------------------------
# Copyright (c) Microsoft Open Technologies (Shanghai) Co. Ltd. All rights reserved.
#
# The MIT License (MIT)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this softw... | ):
"""Get configured value from configuration file according to specified key and a default value
.. seealso:: safe_get_config out | side Utility class
"""
return safe_get_config(key, default_value)
def mkdir_safe(self, path):
"""Create a directory if it doesn't exist
:return the directory path
"""
if path and not (os.path.exists(path)):
os.makedirs(path)
return path
|
AlbertoPeon/invenio | modules/bibformat/lib/elements/bfe_references.py | Python | gpl-2.0 | 3,979 | 0.012315 | # -*- coding: utf-8 -*-
##
## This file is part of Invenio.
## Copyright (C) 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
## ... | isplayed after each reference
| """
from invenio.config import CFG_SITE_URL, CFG_ADS_SITE
from invenio.search_engine import get_mysql_recid_from_aleph_sysno, \
print_record
if CFG_ADS_SITE:
## FIXME: store external sysno into 999 $e, not into 999 $r
# do not escape field values for now because of things like A&... |
Morgan-Stanley/treadmill | lib/python/treadmill/sproc/cleanup.py | Python | apache-2.0 | 1,571 | 0 | """Runs the Treadmill container cleanup job.
"""
from __future__ import absolute_import
from __fut | ure__ import division
from __future__ import print_function
from __future__ import unicode_literals
import click
from treadmill import appenv
from treadmill import cleanu | p
from treadmill import cli
from treadmill import utils
def init():
"""Top level command handler."""
@click.group(name='cleanup')
def cleanup_grp():
"""Cleanup click group."""
@cleanup_grp.command('watcher')
@click.option('--approot', type=click.Path(exists=True),
envva... |
whyflyru/django-seo | djangoseo/version.py | Python | bsd-3-clause | 54 | 0 | # | -*- coding: | utf-8 -*-
__version__ = '2.6.0+whyfly.3'
|
leopoul/mupy | muparse/migrations/0001_initial.py | Python | apache-2.0 | 7,178 | 0.00822 | # encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'NodeGroup'
db.create_table('muparse_nodegroup', (
('url', self.gf('django.... | gField')(max_length=255, db_index=True)),
))
db.send_create_signal('muparse', ['Graph'])
# Addi | ng model 'Node'
db.create_table('muparse_node', (
('url', self.gf('django.db.models.fields.CharField')(max_length=512)),
('group', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['muparse.NodeGroup'])),
('id', self.gf('django.db.models.fields.AutoField')(primary_... |
PrivacyScore/PrivacyScore | privacyscore/api/views.py | Python | gpl-3.0 | 7,028 | 0.000711 | import re
from django.db import transaction
from django.db.models import Count, Q
from django.utils.translation import ugettext_lazy as _
from rest_framework.decorators import api_view
from rest_framework.exceptions import NotFound, ParseError
from rest_framework.request import Request
from rest_framework.response imp... | "Schedule a scan for the list."""
try:
s | can_list = ScanList.objects.get(pk=scan_list_id)
# This always succeeds as rate limit check is done per-site
scan_list.scan()
return Response({
'type': 'success',
'message': 'ok',
})
except ScanList.DoesNotExist:
raise NotFound
@api_view(['POST'])
d... |
rbian/virt-test | virttest/staging/utils_memory.py | Python | gpl-2.0 | 8,312 | 0.001444 | import re
import glob
import math
import logging
import os
from autotest.client import utils
from autotest.client.shared import error
# Returns total memory in kb
def read_from_meminfo(key):
cmd_result = utils.run('grep %s /proc/meminfo' % key, verbose=False)
meminfo = cmd_result.stdout
return int(re.sear... | fo_content = buddy_info.read()
buddy_info.close()
re_buddyinfo = "Node\s+"
if nodes == "all":
re_buddyinfo += "(\d+)"
else:
re_buddyinfo += "(%s)" % "|".join(nodes.split())
if not re.findall(re_buddyinfo, buddy_info_content):
logging.warn("Can not find Nodes %s" % nodes)
... | "all":
re_buddyinfo += "(\w+)"
else:
re_buddyinfo += "(%s)" % "|".join(zones.split())
if not re.findall(re_buddyinfo, buddy_info_content):
logging.warn("Can not find zones %s" % zones)
return None
re_buddyinfo += "\s+([\s\d]+)"
buddy_list = re.findall(re_buddyinfo, budd... |
TomAugspurger/pandas | pandas/tests/indexes/interval/test_astype.py | Python | bsd-3-clause | 7,740 | 0.000904 | import numpy as np
import pytest
from pandas.core.dtypes.dtypes import CategoricalDtype, IntervalDtype
from pandas import (
CategoricalIndex,
Index,
IntervalIndex,
NaT,
Timedelta,
Timestamp,
interval_range,
)
import pandas._testing as tm
class Base:
"""Tests common to IntervalIndex w... | @pytest.fixture(params=indexes)
def index(self, request):
return request.param
@pytest.mark.parametrize("subtype", ["int64", "uint64"])
def test_subtype_integer(self, subtype):
index = interval_range(0.0, 10.0)
dtype = IntervalDtype(subtype)
result = index.astype(dtype)
... | losed=index.closed
)
tm.assert_index_equal(result, expected)
# raises with NA
msg = r"Cannot convert non-finite values \(NA or inf\) to integer"
with pytest.raises(ValueError, match=msg):
index.insert(0, np.nan).astype(dtype)
@pytest.mark.xfail(reason="GH#15832"... |
coreos/depot_tools | my_activity.py | Python | bsd-3-clause | 36,618 | 0.009504 | #!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Get stats about your activity.
Example:
- my_activity.py for stats for the current week (last week on mondays).
- my_activ... | 'email_domain': 'chromium.org',
},
]
gerrit_instances = [
{
'url': 'chromium-review.googlesource.com',
'shorturl': 'crosreview.com',
},
# TODO(deymo): chrome-internal-review requires login credentials. Enable once
# login support is added to this client. See crbug.com/281695.
#{
# 'url': 'ch... | rit-int.chromium.org',
'port': 29419,
},
]
google_code_projects = [
{
'name': 'chromium',
'shorturl': 'crbug.com',
},
{
'name': 'chromium-os',
'shorturl': 'crosbug.com',
},
{
'name': 'chrome-os-partner',
},
{
'name': 'google-breakpad',
},
{
'name': 'gyp',
},
{
... |
Stratoscale/yumcache | yumcache/downloader.py | Python | apache-2.0 | 5,695 | 0.003687 | import requests
import logging
import urllib2
import traceback
import threading
from yumcache import growingblob
class Downloader(threading.Thread):
INVALID_LENGTH = -1
def __init__(self, common, path, url):
self._common = common
self._path = path
self._url = url
self._content... | Downloading '%(url)s'", dict(url=self._url))
self._retryLiveDownload(retry | )
logging.info("Done Downloading '%(url)s'", dict(url=self._url))
break
except:
logging.exception("While Downloading '%(url)s'", dict(url=self._url))
if retry == RETRIES - 1:
logging.exception("Unable to download %(url)s", d... |
dmilith/SublimeText3-dmilith | Packages/Debugger/modules/views/debugger_panel.py | Python | mit | 3,906 | 0.027906 | from __future__ import annotations
from ..typecheck import *
from ..import ui
from ..import dap
from . import css
from .breakpoints_panel import BreakpointsPanel
from .input_list_view import InputListView
if TYPE_CHECKING:
from ..debugger import Debugger
class DebuggerPanel(ui.div):
on_settings: Callable[[], ... | i.Images.shared.pause_disable, 'Pause (Disabled)'))
if self.debugger.is_paused():
items.extend([
DebuggerCommandButton(self.on_step_over, ui.Images.shared.down, 'Step Over'),
DebuggerCommandButton(self.on_step_out, ui.Images.shared.left, 'Step Out'),
DebuggerCommandButton(self.on_step_in, ui.Images.sh... | 'Step In'),
])
else:
items.extend([
DebuggerCommandButton(self.on_step_over, ui.Images.shared.down_disable, 'Step Over (Disabled)'),
DebuggerCommandButton(self.on_step_out, ui.Images.shared.left_disable, 'Step Out (Disabled)'),
DebuggerCommandButton(self.on_step_in, ui.Images.shared.right_disable, '... |
PegasusWang/pyhome | test/_env.py | Python | mit | 328 | 0 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import sys
from os.path import abspath, dirn | ame, join
if sys.getdefaultencoding() != 'utf-8':
reload(sys)
sys.setdefaultencoding('utf-8')
PREFIX = abspath(
joi | n(
dirname(abspath(__file__)), '../'
)
)
if PREFIX not in sys.path:
sys.path.append(PREFIX)
|
ewandor/home-assistant | homeassistant/components/cloud/iot.py | Python | apache-2.0 | 7,667 | 0 | """Module to handle messages from Home Assistant cloud."""
import asyncio
import logging
from aiohttp import hdrs, client_exceptions, WSMsgType
from homeassistant.const import EVENT_HOMEASSISTANT_STOP
from homeassistant.components.alexa import smart_home
from homeassistant.util.decorator import Registry
from homeassi... | response = {
'msgid': msg['msgid'],
}
try:
result = yield from async_handle_message(
hass, self.cloud, msg['handler'], msg['payload'])
# No response from handler
if res... | response['payload'] = result
except UnknownHandler:
response['error'] = 'unknown-handler'
except Exception: # pylint: disable=broad-except
_LOGGER.exception('Error handling message')
response['error'] = 'exception'
... |
opengovt/ckan-agency-management-tool | decorators.py | Python | agpl-3.0 | 2,547 | 0 | from functions import *
from settings import *
import urllib
def required_permission(permissions=[]): # this is a handler level decorator
def decorator(fn):
def wrapper(self, *args, **kwargs):
if not self.user.permissions:
self.render("frontend/error404.html")
... | sel | f.redirect(get_login_url(self.request.uri, "Please Log In"))
return
else:
return fn(self, *args, **kwargs)
return wrapper
def allowed_users(permissions=[]): # this is a handler level decorator
def decorator(fn):
def wrapper(self, *args, **kwargs):
if s... |
invisiblek/python-for-android | python3-alpha/python3-src/Doc/includes/sqlite3/execute_3.py | Python | apache-2.0 | 212 | 0.009434 | import sqlite3
con = sqlite | 3.connect("mydb")
cur = con.cursor()
who = "Yeltsin"
age = 72
cur.execute("select name_last, age from people where name_last=:who and age=:age",
locals())
print | (cur.fetchone())
|
nkgilley/home-assistant | homeassistant/components/ads/sensor.py | Python | apache-2.0 | 2,424 | 0.001238 | """Support for ADS sensors."""
import logging
import voluptuous as vol
from homeassistant.components import ads
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import CONF_NAME, CONF_UNIT_OF_MEASUREMENT
import homeassistant.helpers.config_validation as cv
from . import CONF_ADS_F... | urn self._state_dict[STATE_KEY_STATE]
@property
def unit_of_measurement(self):
"""Return the unit o | f measurement."""
return self._unit_of_measurement
|
tivek/conan | conans/test/model/options_test.py | Python | mit | 12,830 | 0.001871 | import unittest
from conans.model.options import OptionsValues, PackageOptions, Options, PackageOptionValues,\
option_undefined_msg
from conans.model.ref import ConanFileReference
from conans.test.utils.tools import TestBufferConanOutput
from conans.errors import ConanException
class OptionsTest(unittest.TestCase... | Hel | lo1": hello1_values}
down_ref = ConanFileReference.loads("Hello2/0.1@diego/testing")
with self.assertRaisesRegexp(ConanException, "Hello2/0.1@diego/testing tried to change "
"Hello1/0.1@diego/testing option optimized to 2"):
self.sut.propagate_upstream(o... |
andyliuliming/WALinuxAgent | tests/ga/test_exthandlers.py | Python | apache-2.0 | 2,603 | 0.000768 | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the Apache License.
import json
from azurelinuxagent.common.protocol.restapi import ExtensionStatus
from azurelinuxagent.ga.exthandlers import parse_ext_status
from tests.tools import *
class TestExtHandlers(AgentTestCase):
def test_par... | ed.', ext_status.message)
self.assertEqual('Daemon', ext_status.operation)
self.assertEqual('success', ext_status.status)
self.assertEqual(0, ext_status.sequenceNumber)
self.assertEqual(0, len(ext_status.substatus | List))
def test_parse_extension_status01(self):
"""
Parse a status report for a failed execution of an extension.
The extension returned a bad status/status of failed.
The agent should handle this gracefully, and convert all unknown
status/status values into an error.
... |
mserjx/pytube | setup.py | Python | mit | 1,352 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from pytube import __version__
import os
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
def open_file(fname):
return open(os.path.join(os.path.dirname(__file__), fname))
setup(
name="pytube",
version=__versi... | cano.com",
license=open_file('LICENSE.txt').read(),
scripts=['scripts/pytubectl'],
classifiers=[
"Development Status :: 4 - Beta",
"Environment :: Console",
"Intended Audience :: Developers",
"Programming Language :: Python",
"Natural Language :: English",
"Li... | anguage :: Python :: 2.7",
"Programming Language :: Python :: 3.0",
"Programming Language :: Python :: 3.4",
"Topic :: Software Development :: Libraries :: Python Modules",
"Topic :: Utilities",
"Topic :: Internet",
"Topic :: Multimedia :: Video"
],
description="A... |
yann2192/vpyn | Client.py | Python | gpl-3.0 | 2,459 | 0.004067 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2011 Yann GUIBET <yannguibet@gmail.com>
# See LICENSE for details.
import sys, os
from gevent import select, monkey, spawn, Greenlet, GreenletExit, sleep, socket
from base64 import b64encode
from hashlib import md5
from struct import pack, unpack
from zl... | , pubkey):
self.send_id()
myiv = self.send_iv()
i | v = self.get_iv(pubkey)
self.init_cipher(pubkey, myiv, iv)
def recv_file(self):
if self.srecvall(1) != "\x01":
self.ssend("\xFF")
raise Exception, "Bad Flags (0x01 expected)"
size = self.srecvall(4)
checksum = self.srecvall(4)
if adler32(size) != unpa... |
vanant/googleads-dfa-reporting-samples | python/v2.0/create_image_creative.py | Python | apache-2.0 | 3,754 | 0.005328 | #!/usr/bin/python
#
# Copyright 2014 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... | r__ = ('api.jimper@gmail.com (Jonathon Imperiosi)')
import argparse
import sys
from apiclient import sample_tools
from apiclient.http import MediaFileUpload
from oauth2client import client
# Declare command-line flags.
argparser = argparse.ArgumentParser(add_help=False)
argparser.add_argument(
'profile_id', type... | creative with.')
argparser.add_argument(
'size_id', type=int,
help='The ID of the size of this creative.')
argparser.add_argument(
'image_name',
help='Suggested name to use for the uploaded creative asset.')
argparser.add_argument(
'path_to_image_file',
help='Path to the asset file to be uploade... |
ForeverWintr/ImageClassipy | clouds/util/farmglue.py | Python | mit | 2,342 | 0.003416 | """
Glue for interfacing with a farm object
"""
import os
import ast
from .constants import HealthStatus
def imagesAndStatuses(outputDir):
"""
Return a dictionary of images and corresponding human assigned statuses from output.
"""
controlPath = os.path.join(outputDir, 'controls', 'HealthImageryControl... | 'yes':
continue
segStatus = _pickStatus(control[fieldname][segname]['healthStatus'])
| segRGBTiff = os.path.join(seg, 'rgb', 'rgb.tif')
segRGBPng = os.path.join(seg, 'rgb', 'rgb.png')
#choose png if it exists, as it'll save us converting later
if os.path.exists(segRGBPng):
images[segRGBPng] = segStatus
else:
images[segRGBTi... |
WiserTogether/aurproxy | tellapart/aurproxy/share/adjusters/ramp.py | Python | apache-2.0 | 2,700 | 0.007407 | # Copyright 2015 TellApart, 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 writi... |
return 1.0
else:
total = end_time - start_time
elapsed = as_of - start_time
p = float(elapsed.total_seconds()) / float(total.total_seconds())
return p
_CURVE_FNS = {
'linear': linear }
class RampingShareAdjuster(ShareAdjuster):
def __init__(self,
endpoint,
sign... | ramp_delay,
ramp_seconds,
curve='linear',
update_frequency=10,
as_of=None):
super(RampingShareAdjuster, self).__init__(endpoint, signal_update_fn)
self._ramp_delay = ramp_delay
self._ramp_seconds = ramp_seconds
self._curve_fn = _CUR... |
jkonecki/autorest | AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/resource.py | Python | mit | 1,309 | 0.001528 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
:type id: str
:param type: Resource Type
:type type: str
:param tags:
:type tags: dict
:param location: Resource Location
:type location: str
:param name: Resource Name
:type name: str
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'type': {'key... | e': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'location': {'key': 'location', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
}
def __init__(self, id=None, type=None, tags=None, location=None, name=None, **kwargs):
self.id = id
self.type = type
se... |
alirizakeles/zato | code/zato-server/test/zato/server/service/internal/kvdb/data_dict/test_impexp.py | Python | gpl-3.0 | 1,497 | 0.004008 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2013 Dariusz Suchojad <dsuch at zato.io>
Licensed under LGPLv3, see LICENSE.txt for terms and conditions.
"""
from __future__ import absolute_import, division, print_function, unicode_literals
# Bunch
from bunch import Bunch
# Zato
from zato.common imp | ort zato_namespace
from zato.common.test import rand_string, ServiceTestCase
from zato.server.service.internal.kvdb.data_dict.impexp import Import
##############################################################################
class ImportTestCase(ServiceTestCase):
def setUp(self):
self.service_class = Im... | ce_class.SimpleIO
def get_request_data(self):
return {'data':rand_string()}
def get_response_data(self):
return Bunch()
def test_sio(self):
self.assertEquals(self.sio.request_elem, 'zato_kvdb_data_dict_impexp_import_request')
self.assertEquals(self.sio.response_elem, 'zato... |
sedden/django-basic-apps | basic/events/views.py | Python | bsd-3-clause | 1,774 | 0.003946 | import re, datetime
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.http import Http404
from django.views.generic import date_bas | ed, list_detail
from basic.events.models import *
def event_list(request, page=0):
return list_detail.object_list(
request,
queryset=EventTime.objects.all(),
paginate_by=20,
page=page,
)
event_list.__doc__ = list_detail.object_list.__doc__
def event_archi | ve_year(request, year):
return date_based.archive_year(
request,
year=year,
date_field='start',
queryset=EventTime.objects.all(),
make_object_list=True,
allow_future=True,
)
event_archive_year.__doc__ = date_based.archive_year.__doc__
def event_archive_month(req... |
mstave/Todo.txt-python | todo.py | Python | gpl-3.0 | 36,444 | 0.005213 | #!/usr/bin/env python
# TODO.TXT-CLI-python
# Copyright (C) 2011-2012 Sigmavirus24
#
# 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 ... | one)]
i = len(lines)
pad = 1
while i >= 10:
pad += 1
i /= 10
| return pad
def iter_todos(include_done=False):
"""Opens the file in read-only mode; returns an iterator for the todos."""
files = [CONFIG["TODO_FILE"]]
if not os.path.isfile(files[0]):
return
if include_done and os.path.isfile(CONFIG["DONE_FILE"]):
files.append(CONFIG["DONE_FILE"])
... |
leandron/steinlib | steinlib/state.py | Python | mit | 163 | 0 | class ParsingState(object):
"""
States of the pars | ing process.
"""
wait_for_header = 0
| wait_for_section = 1
inside_section = 2
end = 4
|
drgarcia1986/simple-settings | tests/samples/special.py | Python | mit | 74 | 0 | SIMPLE_S | ETTINGS = {
'OVERR | IDE_BY_ENV': True
}
MY_VAR = u'Some Value'
|
genenetwork/genenetwork2_diet | wqflask/base/data_set.py | Python | agpl-3.0 | 45,353 | 0.00452 | # Copyright (C) University of Tennessee Health Science Center, Memphis, TN.
#
# 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 la... | n g.db.execute(query).fetchall():
#The query at the beginning of this function isn't necessary here, but still would
#rather just reuse it
#print("type: {}\tname: {}".format(dataset_type, result.Name))
dataset = create_dataset(result.Name, ... | s, pickle.HIGHEST_PROTOCOL))
Redis.expire(key, 60*60)
return datasets
def create_in_clause(items):
"""Create an in clause for mysql"""
in_clause = ', '.join("'{}'".format(x) for x in mescape(*items))
in_clause = '( {} )'.format(in_clause)
return in_clause
def mescape(*items):
"""Mul... |
nanomolina/JP | src/odontology/person/migrations/0050_auto_20160710_0431.py | Python | apache-2.0 | 422 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2016-07-10 07:31
from __ | future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('person', '0049_patient_ph | oto'),
]
operations = [
migrations.RenameField(
model_name='patient',
old_name='photo',
new_name='picture',
),
]
|
mganeva/mantid | scripts/HFIR_4Circle_Reduction/detector2dview.py | Python | gpl-3.0 | 14,054 | 0.00249 | # Mantid Repository : https://github.com/mantidproject/mantid
#
# Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,
# NScD Oak Ridge National Laboratory, European Spallation Source
# & Institut Laue - Langevin
# SPDX - License - Identifier: GPL - 3.0 +
#pylint: disable=W0403,R0902,R0903,R0904,W021... | lower_left_y = min(self._roiStart[1], self._roiEnd[1])
lower_left = lower_left_x, lower_left_y
# ROI upper right
upper_right_x = max(self._roiStart[0], self._roiEnd[0])
upper_ri | ght_y = max(self._roiStart[1], self._roiEnd[1])
upper_right = upper_right_x, upper_right_y
return lower_left, upper_right
def plot_detector_counts(self, raw_det_data, title=None):
"""
plot detector counts as 2D plot
:param raw_det_data:
:return:
"""
... |
adrianomargarin/wttd-eventex | eventex/core/admin.py | Python | gpl-3.0 | 1,325 | 0.000755 | from django.contrib import admin
from eventex.core.models import Talk
from eventex.core.models import Course
from eventex.core.models import Speaker
from eventex.core.models import Contact
class ContactInline(admin.TabularInline):
model = Contact
extra = 1
class SpeakerModelAdmin(admin.ModelAdmin):
i... | _link(self, obj):
return '<a href="{0}">{0}</a>'.format(obj.websit | e)
website_link.allow_tags = True
website_link.short_description = 'Website'
def photo_img(self, obj):
return '<img width="32px" src="{}"/>'.format(obj.photo)
photo_img.allow_tags = True
photo_img.short_description = 'Foto'
def email(self, obj):
return obj.contact_set.emails(... |
pattisdr/osf.io | scripts/remove_after_use/find_timeseries_preprints.py | Python | apache-2.0 | 1,686 | 0.004152 | from __future__ import division
import argparse
import logging
import csv
import io
from website.app import setup_django
setup_django()
from osf.metrics import PreprintDownload
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
def generate_preprint_csv(preprint_ids):
search = Prepri... | preprint_csv(args.guids)
with open('top_ten_preprints.csv', 'wb') as writeFile:
wri | teFile.write(preprint_csv.getvalue())
if __name__ == '__main__':
main()
|
Suwmlee/XX-Net | gae_proxy/server/lib/google/appengine/api/yaml_listener.py | Python | bsd-2-clause | 7,554 | 0.003839 | #!/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... | er.
Args:
stream: String document or open file object to process as per the
yaml.parse method. Any object that implements a 'read()' method which
returns a string document will work.
Loader: Loader class to use as per the yaml.parse method. Used to
instantiate new yaml.loader ... | der_class is not None
try:
loader = loader_class(stream)
while loader.check_event():
yield (loader.get_event(), loader)
except yaml.error.YAMLError as e:
raise yaml_errors.EventListenerYAMLError(e)
def Parse(self, stream, loader_class=yaml.loader.SafeLoader):
"""Call YAML parser... |
blackboarddd/PyTest | mstr/PILTest.py | Python | gpl-3.0 | 2,261 | 0.01946 | '''
Created on May 21, 2016
@author: zlp
'''
# import Image
hello = 100
class PILTest(object):
hello = 200
def __init__(self, name):
self._name = name
def printName(self):
print self._name
def printHelloInClass(self):
print self.hello
class2 = PILTest... | e2
# print t2.name
# print t2.name2
# t1.name = 'HEIHEI | !'
# print t1.name
# print t2.name
print 'T1\'s name is ',Test1.name
|
interactiveinstitute/watthappened | python_modules/socketpool/pool.py | Python | mit | 6,292 | 0.000795 | # -*- coding: utf-8 -
#
# This file is part of socketpool.
# See the NOTICE for more information.
import contextlib
import sys
import time
from socketpool.util import load_backend
class MaxTriesError(Exception):
pass
class MaxConnectionsError(Exception):
pass
class ConnectionPool(object):
"""Pool of co... | found = candidate
break
else:
| # conn is dead for some reason.
# reap it.
self._reap_connection(candidate)
if i <= 0:
break
if unmatched:
for candidate in unmatched:
self.pool.pu... |
syci/OCB | addons/website_sale/models/product.py | Python | agpl-3.0 | 9,392 | 0.006601 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import openerp
from openerp import tools
from openerp.osv import osv, fields
class product_style(osv.Model):
_name = "product.style"
_columns = {
'name' : fields.char('Style Name', required=True),
... | gory', select=True),
'child_id': fields.one2many('product.public.category', 'parent_id', string='Children Categories'),
'sequence': fields.integer('Sequence', help="Gives the sequence order | when displaying a list of product categories."),
}
# NOTE: there is no 'default image', because by default we don't show
# thumbnails for categories. However if we have a thumbnail for at least one
# category, then we display a default image on the other, so that the
# buttons have consistent styli... |
KodiColdkeys/coldkeys-addons | repository/plugin.video.white.devil/resources/lib/sources/dailyrls_wp_jh.py | Python | gpl-2.0 | 6,200 | 0.018065 | # -*- coding: utf-8 -*-
'''
Exodus Add-on
Copyright (C) 2016 Exodus
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 l... | lparse.urlparse(url.strip().lower()).netloc)[0]
if not host in hostDict: raise Exception()
host = client.replaceHTMLCodes(host)
host = host.encode | ('utf-8')
sources.append({'source': host, 'quality': quality, 'provider': 'Dailyrls', 'url': url, 'info': info, 'direct': False, 'debridonly': True})
except:
pass
check = [i for i in sources if not i['quality'] == 'CAM']
if check: sources... |
EcmaXp/PyCraft | misc/tinypy/tinypy/py2bc.py | Python | gpl-2.0 | 1,121 | 0.02587 | if not (str(1.0) == "1"):
from boot import *
import tokenize,parse,encode
def _compile(s,fname):
tokens = tokenize.tokenize(s)
t = parse.parse(s,tokens)
r = encode.encode(fname,s,t)
return r
def _import(name):
if name in MODULES:
return MODULES[name]
py = name+".py"
tpc = name... |
def _init():
BUILTINS['compile'] = _compile
BUILTINS['import'] = _import
def import_fname(fname,name):
g = {}
g['__name__'] = name
MODULES[name] = g
s = load(fname)
code = _compile(s,fname)
g['__code__'] = code
exec(code,g)
return g
def ti | nypy():
return import_fname(ARGV[0],'__main__')
def main(src,dest):
s = load(src)
r = _compile(s,src)
save(dest,r)
if __name__ == '__main__':
main(ARGV[1],ARGV[2])
|
Mlieou/oj_solutions | leetcode/python/ex_294.py | Python | mit | 311 | 0.009646 | class Solution(object):
_memo = {}
def canWin(self, s):
"""
:type s: str
| :rtype: bool
"""
memo = self._memo
if s not in memo:
return any(s[i:i+2] == '++' and not self.canWin(s[:i] + '-' | + s[i+2:]) for i in range(len(s)))
return memo[s] |
andrewromanenco/pyjvm | pyjvm/class_path.py | Python | gpl-3.0 | 3,299 | 0 | # PyJVM (pyjvm.org) Java Virtual Machine implemented in pure Python
# Copyright (C) 2014 Andrew Romanenco (andrew@romanenco.com)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version ... | lookup_paths.append(path)
else:
if zipfile.is_zipfile(path):
read_from_jar(path, jars)
else:
raise Exception("Class path entry %s is not a jar file" % path)
return (lookup_paths, jars, rt)
def read_from_jar(jar, dict_data):
'''Read file li... | raise Exception("Not a jar file: %s" % jar)
with zipfile.ZipFile(jar, "r") as j:
for name in j.namelist():
if name.endswith(".class"): # at some point save all files
dict_data[name] = jar
|
pytrainer/pytrainer | pytrainer/gui/windowcalendar.py | Python | gpl-2.0 | 1,204 | 0.016611 | # -*- coding: utf-8 -*-
#Copyright (C) Fiz Vazquez vud1@sindominio.net
#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.
#T... | Public License
#along with this program; if not, write to the Free Software
#Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
import warnings
from pytrainer.gui.dialogs import calendar_dialog
class WindowCalendar(object):
| def __init__(self, data_path = None, parent = None, date = None):
warnings.warn("Deprecated WindowCalendar class called", DeprecationWarning, stacklevel=2)
self.parent = parent
self.date = date
def run(self):
date = calendar_dialog(date=self.date)
if date:
self... |
jkettleb/iris | lib/iris/tests/unit/fileformats/pp/test_PPField.py | Python | lgpl-3.0 | 11,449 | 0 | # (C) British Crown Copyright 2013 - 2015, Met Office
#
# This file is part of Iris.
#
# Iris 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 l... | rotated field.
self._check_cs(bplat=75, bplon=180, rotated=True)
def test_odd_bplon_rotated(self):
# Show that BPLON != 0 or 180 produces a rotated field.
self._check_cs(bplat=90, bplon=123.45, rotated=True)
class Test__init__(tests.IrisTest):
| def setUp(self):
header_longs = np.zeros(pp.NUM_LONG_HEADERS, dtype=np.int)
header_floats = np.zeros(pp.NUM_FLOAT_HEADERS, dtype=np.float)
self.header = list(header_longs) + list(header_floats)
def test_no_headers(self):
field = TestPPField()
self.assertIsNone(field._raw_hea... |
SavinaRoja/Kerminal | kerminal/escape_forwarding_containers.py | Python | gpl-3.0 | 574 | 0.001742 | # -*- coding: utf-8 -*-
import npyscreen2
class EscapeForwardingContainer(npyscreen2.Co | ntainer):
def set_up_exit_condition_handlers(self):
super(EscapeForwardingContainer, self).set_up_exit_condition_handlers()
self.how_exited_handlers.update({'escape': self.h_exit_escape})
class EscapeForwardingSmartContainer(EscapeForwardingContainer,
npyscreen... | npyscreen2.GridContainer):
pass |
braysia/CellTK | celltk/utils/_munkres.py | Python | mit | 201 | 0.004975 | im | port numpy as np
from scipy.optimize import linear_sum_assignment
def munkres(arr):
temp = np.zeros(arr.shape, np.bool)
ind = linear_sum_assignment(arr)
| temp[ind] = True
return temp |
Transkribus/TranskribusDU | TranskribusDU/graph/pkg_GraphBinaryConjugateSegmenter/PageXmlSeparatorRegion.py | Python | bsd-3-clause | 6,028 | 0.008461 | # -*- coding: utf-8 -*-
"""
A class to load the SeparatorRegion of a PageXml to add features to the
edges of a graph conjugate used for segmentation.
It specialises the _index method to add specific attributes to the edges
, so that the specific feature transformers can be used.
Copyright... | oolean %s (#1)" % (self.__class__)
class Separator_num(Pipeline):
"""
Node neighbour count feature quantiled |
"""
nQUANTILE = 16
class Selector(Transformer):
"""
Characterising the neighborough by the number of neighbour before and after
"""
def transform(self, lO):
nb = len(lO)
a = np.zeros((nb, 4), dtype=np.float64)
for i, o in enumerate(lO):
... |
CenterForOpenScience/SHARE | api/ingestjobs/urls.py | Python | apache-2.0 | 210 | 0 | from rest_framework.routers import SimpleRouter
from api.ingestjobs im | port views
router = SimpleRouter()
router.register(r'ingestj | obs', views.IngestJobViewSet, basename='ingestjob')
urlpatterns = router.urls
|
paulmartel/voltdb | lib/python/voltcli/voltadmin.d/show.py | Python | agpl-3.0 | 1,129 | 0.008857 | # This file is part of VoltDB.
# Copyright (C) 2008-2016 VoltDB Inc.
#
# 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 ver... | more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with VoltDB. If not, see <http://www. | gnu.org/licenses/>.
def show_snapshots(runner):
response = runner.call_proc('@SnapshotStatus', [], [])
print response.table(0).format_table(caption = 'Snapshot Status')
@VOLT.Multi_Command(
bundles = VOLT.AdminBundle(),
description = 'Display information about a live database.',
modifiers = VOLT.M... |
mozilla/firefox-flicks | vendor-local/lib/python/celery/tests/utilities/test_timer2.py | Python | bsd-3-clause | 4,966 | 0 | from __future__ import absolute_import
from __future__ import with_statement
import sys
import time
from kombu.tests.utils import redirect_stdouts
from mock import Mock, patch
import celery.utils.timer2 as timer2
from celery.tests.utils import Case, skip_if_quick
class test_Entry(Case):
def test_call(self):
... | chedule.apply_entry(fun)
fun.assert_called_with()
self.assertFalse(stderr.getvalue())
@patch('os._exit')
def test_thread_crash(self, _exit):
t = timer2.Timer()
t._next_entry = Mock()
t._next_entry.side_effect = OSError(131)
t.run()
_exit.assert_called_wit... | ide_effect = TypeError()
t._is_shutdown.set()
t.run()
t._is_stopped.set.assert_called_with()
def test_to_timestamp(self):
self.assertIs(timer2.to_timestamp(3.13), 3.13)
def test_test_enter(self):
t = timer2.Timer()
t._do_enter = Mock()
e = Mock()
... |
GbalsaC/bitnamiP | venv/lib/python2.7/site-packages/pylint/test/input/func_e0203.py | Python | agpl-3.0 | 339 | 0 | """check | for method without self as first argument
"""
__revision__ = 0
class Abcd(object):
"""dummy class"""
def __init__(self):
| pass
def abcd(yoo):
"""another test"""
abcd = classmethod(abcd)
def edf(self):
"""justo ne more method"""
print('yapudju in', self)
|
fayf/pyload | module/plugins/crypter/CryptItCom.py | Python | gpl-3.0 | 542 | 0.012915 | # -*- coding: utf-8 -*-
from module.plugins.internal.DeadCrypter import DeadCrypter, create_getInfo
class Cry | ptItCom(DeadCrypter):
__name__ = "CryptItCom"
__type__ = "crypter"
__version__ = "0.12"
__status__ = "testing"
__pattern__ = r'http://(?:www\.)?crypt-it\.com/(s|e|d|c)/\w+'
__config__ = [] #@TODO: Remove in 0.4.10
__description__ = """Cryp | t-it.com decrypter plugin"""
__license__ = "GPLv3"
__authors__ = [("jeix", "jeix@hasnomail.de")]
getInfo = create_getInfo(CryptItCom)
|
pombredanne/frappe | frappe/desk/form/load.py | Python | mit | 4,558 | 0.027644 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
import frappe, json
import frappe.utils
import frappe.share
import frappe.defaults
import frappe.desk.form.meta
from frappe.permissions import get_doc_permissions
from frappe impo... | ppe.msgprint(_('Did not load'))
raise
if doc and not name.startswith('_'):
frappe.get_user().update_recent(doctype, name) |
frappe.response.docs.append(doc)
@frappe.whitelist()
def getdoctype(doctype, with_parent=False, cached_timestamp=None):
"""load doctype"""
docs = []
# with parent (called from report builder)
if with_parent:
parent_dt = frappe.model.meta.get_parent_dt(doctype)
if parent_dt:
docs = get_meta_bundle(parent... |
acutesoftware/AIKIF | aikif/.z_prototype/test_agent_agg_context.py | Python | gpl-3.0 | 559 | 0.010733 | #!/usr/bin/python3
# test_agent_agg_context.py
import os
im | port unittest
import sys
root_fldr = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
sys.path.insert(0, root_fldr)
import aikif.agents.aggregate.agg_context as mod_agg
class TestAgentAggContext(unittest.TestCase):
def test_01_(self):
agentFileList = mod_agg.AggContext()
agentFileLis... | rt(),[])
if __name__ == '__main__':
unittest.main()
|
newspipe/newspipe | dags/dag_factory/components/utils.py | Python | agpl-3.0 | 1,480 | 0.004054 | import os
import yaml
import time
from datetime import datetime
def get_all_csv_paths(path):
csv_paths = []
for root, dirs, files in os.walk(path):
for file in files:
if file.endswith(".csv"):
csv_paths.append(os.path.join(root, file))
return csv_paths
def date_str_to... | ime(date_str)
except:
pass
try:
| d = datetime.strptime(date_str, '%a, %d %b %Y %H:%M:%S %Z')
except:
pass
try:
d = datetime.strptime(date_str, '%a, %d %b %Y %H:%M:%S %z')
except:
pass
try:
d = datetime.strptime(date_str.split(
'+')[0].replace("T", " "), '%... |
alestic/townclock-ping-timercheck | code/lambda_function.py | Python | apache-2.0 | 1,751 | 0.006282 | #!/usr/bin/env python3.6
import sys
sys.path.insert(1, 'lib')
import os
import json
import logging
import requests
from requests.packages.urllib3.util.retry import Retry
from requests.adapters import HTTPAdapter
logger = logging.getLogger()
logger.setLevel(logging.INFO)
# Retry until AWS Lambda function times out
ret... | rcheck-demo'
seconds='1200'
os.environ['url'] = 'https://timercheck.io/'+timer+'/'+seconds
lambda_handler({
"source": "townclock.chime",
"type": "chime",
"version": "3.0",
"timestamp": "2017-05-20 01:45 UTC",
"year": "2017",
"month": "05",
"day": "20",
"hour":... | "minute": "45",
"day_of_week": "Sat",
"unique_id": "02976691-0e70-4dbd-8191-a2f26819e1f7",
"region": "us-east-1",
"sns_topic_arn": "arn:aws:sns:us-east-1:522480313337:unreliable-town-clock-topic-178F1OQACHTYF",
"reference": "http://townclock.io",
"support": "First Last <nobody@... |
ljbin/meiyou | soft/identifyporn/avatar_model.py | Python | apache-2.0 | 8,414 | 0.007776 | # -*- coding: utf-8 -*-
'''
Created on 2018年3月27日
@author: baimb
'''
import logging as log
log.basicConfig(level=log.INFO, format='%(asctime)s - [%(filename)s:%(funcName)s:%(lineno)s] - %(message)s')
import os
import platform
import tensorflow as tf
from image_similarity import ImageSimilaritySearch
... | t_exc()
return -1
finally:
# 删除文件
if os.path.exists(image_path) and image_path.startswith("tmp/"):
os.remove(image_ | path)
log.info("score:%s,image:%s,cost:%s" % (score, image_path, time.time() - st))
return score
if __name__ == '__main__':
if len(sys.argv) < 3:
print("python dl/nsfw/avatar_model.py model_dir image_path")
exit()
classifer = Av... |
zordsdavini/qtile | libqtile/dgroups.py | Python | mit | 8,861 | 0.000451 | # Copyright (c) 2011-2012 Florian Mounier
# Copyright (c) 2012-2014 roger
# Copyright (c) 2012 Craig Barnes
# Copyright (c) 2012-2014 Tycho Andersen
# Copyright (c) 2013 Tao Sauvage
# Copyright (c) 2014 ramnes
# Copyright (c) 2014 Sebastian Kricner
# Copyright (c) 2014 Sean Vig
#
# Permission is hereby granted, free of... | added = self.qtile.add_group(rule.group, layout, layouts, label)
client.togroup(rule.group)
group_set = True
group_obj = self.qtile.groups_map[rule.group]
group = self.groups_map.get(rule.group)
if group and g | roup_added:
for k, v in list(group.layout_opts.items()):
if isinstance(v, collections.Callable):
v(group_obj.layout)
else:
setattr(group_obj.layout, k, v)
... |
hbrunn/bank-statement-reconcile | account_statement_transactionid_completion/__init__.py | Python | agpl-3.0 | 971 | 0 | # -*- coding: utf-8 -*-
##############################################################################
#
# Author: Joel Grand-Guillaume
# Copyright 2011-2012 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License a... |
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy | of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from . import statement
|
lypnol/adventofcode-2016 | day-13/part-1/ayoub.py | Python | gpl-3.0 | 1,423 | 0.007027 | from submission import Submission
from heapq import *
class AyoubSubmission(Submission):
def author(self):
return 'Ayoub'
def run(self, s):
s = s.rstrip()
N = int(s)
start = 1, 1
goal = 31,39
def is_wall(x, y):
r = x*x + 3*x + 2*x*y + y + y*y
... | _, (x, y) = heappop(openset)
| if x == goal[0] and y == goal[1]:
return dist[(x, y)]
closedset.add((x, y))
for u,v in [(1,0), (0,1), (-1,0), (0, -1)]:
node = (x+u, y+v)
if x+u >= 0 and y+v >=0 and\
not is_wall(*node) and node not in closedset:
... |
CottageLabs/OpenArticleGauge | openarticlegauge/tests/plugins/test_workflow/test_11_1/test_11_1.py | Python | bsd-3-clause | 543 | 0.016575 | from openarticlegauge import plugin
class mock_licence_plugin(plugin.Plugin):
_short_name="mock_doi"
def capabilities(self):
return {
"type_detect_verify" : False,
"canonicalise" : [],
"detect_provider" : [],
| "license_detect" : True
}
def supports(self, provider):
return True
def license_detect(self, record):
record.record['bibjson'] = {}
record.record['bibjson']['license'] = [{}]
record.record['bibjson'][' | title'] = "mytitle"
|
Thomsen22/MissingMoney | Peak Load Reserve - EU system/PLR_function.py | Python | gpl-3.0 | 4,572 | 0.013123 | # Python standard modules
import pandas as pd
# Own modules
from PLR_optclass import PLRMarket
import PLR_optimization as plrmodel
def PeakLoadReserveFunction():
market = PLRMarket()
market.optimize()
df_generators = market.data.generators
gens_for_zones = market.data.gens_for_country
... | s[z]) > (peakload[z] * reservemargin):
#df_generators = plrmodel.plantdeactivation(zones, gens_for_zones, df_zonalconsumption, reservemargin, Gen_dataframe)
#elif sum(df_generators['capacity'][g] for g in gens_for_zones[z]) < (peakload[z] * reservemargin):
#df_gener | ators = plrmodel.plantactivation(zones, gens_for_zones, df_zonalconsumption, reservemargin)
#df_generators = plrmodel.plantinvestment(df_price_DA, zones, gens_for_zones, timeperiod, reservemargin, peakload)
# Data to csv files, remove the #
#df_price_DA.to_csv('1dayaheadmarketprices.csv')
#... |
capitalone/cloud-custodian | tools/c7n_org/c7n_org/utils.py | Python | apache-2.0 | 814 | 0 | # Copyright 2017 Capital One Services, LLC
# Copyright The Cloud Custodian Authors.
# SPDX-License-Identifier: Apache-2.0
import os
from c7n.utils import reset_session_cache
from conte | xtlib import contextmanager
def account_tags(account):
tags = {'AccountName': account['name'], 'AccountId': account['account | _id']}
for t in account.get('tags', ()):
if ':' not in t:
continue
k, v = t.split(':', 1)
k = 'Account%s' % k.capitalize()
tags[k] = v
return tags
@contextmanager
def environ(**kw):
current_env = dict(os.environ)
for k, v in kw.items():
os.environ[k]... |
ujdhesa/unisubs | apps/videos/types/bliptv.py | Python | agpl-3.0 | 2,824 | 0.003895 | # Amara, universalsubtitles.org
#
# Copyright (C) 2013 Participatory Culture Foundation
#
# 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 ... | ]
video_obj.save()
return video_obj
def _parse_url(self):
matches = self.pattern.match(self.url).groupdict()
return matches['subsite'], matches['file_id']
def _fetch_json(self):
# bliptv just knows how to return jsonp. argh.
url = self.url + "?skin=json&callba... | n {}
# strip the json parentesis. argh.
if jsonp.endswith(');'):
jsonp = jsonp[1:-2]
json = simplejson.loads(jsonp)
return json[0].get('Post', {}) if len(json) > 0 else None
|
ixlab/trendquery | offline/src/parse_zip_test.py | Python | apache-2.0 | 528 | 0.003788 | """This module is used first to read inpu | t files and create year, [word]
dict"""
__author__ = 'kamat'
import unittest
from parse_zip import write_year_title
class ParseZipTest(unittest.TestCase):
def test_write_year_title(self):
"""This method is used to create year, [word] dict that
nsf_stats.py uses to create db. Others are just relics of help... | ory, output_file)
|
HarrisonHDU/myerp | apps/depot/views.py | Python | mit | 4,631 | 0.002385 | # Create your views here.
from django import forms
from django.template import RequestContext
from django.http import HttpResponse, HttpResponseRedirect
from django.template.loader import get_template
from django.core.paginator import Paginator
from django.core.urlresolvers import reverse
import datetime
from... | ializers.serialize('json', python_object.items),
'total_price': str(python_object.total_price)
}
}
raise TypeError(repr(python_object) + ' is not JSON serializable')
def from_json(json_object):
if '__class__' in json_object:
if json_object['__class__'] == '... | urn Cart(items=[deserialized_object.object for deserialized_object in serializers.deserialize('json', json_object['__value__']['items'])],
total=decimal.Decimal(json_object['__value__']['total_price']))
return json_object
def create_product(request):
form = ProductForm(request.PO... |
psnj/petl | petl/test/io/test_pandas.py | Python | mit | 1,286 | 0 | # -*- coding: utf-8 -*-
from __future__ import division, print_function, absolute_import
import sys
import petl as etl
from petl.test.helpers import ieq
from petl.io.pandas import todataframe, fromdataframe
try:
# noinspection PyUnresolvedReferences
import pandas as pd
except ImportError as e:
print('... | ges', 3, 4.4),
('pears', 7, .1)]
expect = pd.DataFrame.from_records(tbl[1:], columns=tbl[0])
actual = todataframe(tbl)
assert expect.equals(actual)
def test_fromdataframe():
tbl = [('foo', 'bar', 'baz'),
('apples', 1, 2.5),
('ora | nges', 3, 4.4),
('pears', 7, .1)]
df = pd.DataFrame.from_records(tbl[1:], columns=tbl[0])
ieq(tbl, fromdataframe(df))
ieq(tbl, fromdataframe(df))
def test_integration():
tbl = [('foo', 'bar', 'baz'),
('apples', 1, 2.5),
('oranges', 3, 4.4... |
Andrew-McNab-UK/DIRAC | Core/DISET/private/BaseClient.py | Python | gpl-3.0 | 26,577 | 0.025247 | """ This module exposes the BaseClient class,
which serves as base for InnerRPCClient and TransferClient.
"""
__RCSID__ = "$Id$"
import time
import thread
import DIRAC
from DIRAC.Core.DISET.private.Protocols import gProtocolDict
from DIRAC.FrameworkSystem.Client.Logger import gLogger
from DIRAC.Core.Utilities imp... | Lapse ):
result = initFunc()
if not result[ 'OK' ] and self.__initStatus[ 'OK' ]:
self.__initStatus = result
self.numberOfURLs = 0
self._initialize()
#HACK for thread-safety:
self.__allowedThreadID = False
d | ef _initialize( self ):
pass
def getDestinationService( self ):
return self._destinationSrv
def getServiceName( self ):
return self._serviceName
def __discoverSetup( self ):
""" Discover which setup to use and stores it in self.setup
The setup is looked for:
* kwargs of the c... |
garrettcap/Bulletproof-Backup | wx/tools/Editra/src/syntax/_kix.py | Python | gpl-2.0 | 4,682 | 0.001709 | ###############################################################################
# Name: kix.py #
# Purpose: Syntax configuration module for KIXtart scripts #
# Author: Cody Precord <cprecord@editra.org> #
... | ldomain "
"ldrive lm logonmode longhomedir lserver maxpwage mdayno mhz "
"monthno month msecs pid primarygroup priv productsuite "
"producttype pwage ras result rserver scriptdir scriptexe "
"scriptname serror sid site startdir syslang ticks time userid "
... | yle'),
(stc.STC_KIX_DEFAULT, 'default_style'),
(stc.STC_KIX_FUNCTIONS, 'funct_style'),
(stc.STC_KIX_IDENTIFIER, 'default_style'),
(stc.STC_KIX_KEYWORD, 'keyword_style'),
(stc.STC_KIX_MACRO, 'pre_style'),
(stc.STC_KIX_NUMBER,... |
toobaz/pandas | pandas/tests/frame/test_block_internals.py | Python | bsd-3-clause | 22,034 | 0.000499 | from datetime import datetime, timedelta
from io import StringIO
import itertools
import numpy as np
import pytest
import pandas as pd
from pandas import (
Categorical,
DataFrame,
Series,
Timestamp,
compat,
date_range,
option_context,
)
from pandas.core.arrays import IntervalArray, integer... | at_frame._data.is_consolidated()
def test_modify_values(self, float_frame):
float_frame.values[5] = 5
assert (float_frame.values[5] == | 5).all()
# unconsolidated
float_frame["E"] = 7.0
float_frame.values[6] = 6
assert (float_frame.values[6] == 6).all()
def test_boolean_set_uncons(self, float_frame):
float_frame["E"] = 7.0
expected = float_frame.values.copy()
expected[expected > 1] = 2
... |
juanshishido/project-eta | code/make_plots_smoothing.py | Python | bsd-3-clause | 1,263 | 0.020586 | from utils.ols import *
########before preproccessing
betas_before_process = apply_ols_to_subject(16, 3, r_outliers = False, smooth = False)
##average across all runs
avg_before = average_betas(betas_before_process)
## shape to 4d
avg_before = beta_2d_to_4d(avg_before)
plt.figure()
plt.imshow(avg_before[:,... | t', cmap='gray')
plt.title('Middle Slice Beta(Gain) Before smoothing')
plt.savefig("Before_preproccessing_gain")
plt.figure()
plt.imshow(avg_before[:, :, 16, 1], interpolation='nearest', cmap='gray')
plt.title('Middle Slice Beta(Loss) Before smoothing')
plt.savefig("Before_preproccessing_loss")
###### After Prepro... | ter_process)
## shape to 4d
avg_after = beta_2d_to_4d(avg_after)
plt.figure()
plt.imshow(avg_after[:, :, 16, 0], interpolation='nearest', cmap='gray')
plt.title('Middle Slice Beta(Gain) After Smoothing')
plt.savefig("After_preproccessing_gain")
plt.figure()
plt.imshow(avg_after[:, :, 16, 1], interpolation='nearest... |
getsentry/zeus | zeus/db/func.py | Python | apache-2.0 | 1,373 | 0.002185 | import re
from sqlalchemy.sql import func
from sqlalchemy.types import String, TypeDecorator
# https://bitbucket.org/zzzeek/sqlalchemy/issues/3729/using-array_agg-around-row-function-does
class ArrayOfRecord(TypeDecorator):
_array_regexp = re.compile(r"^\{(\".+?\")*\}$")
_chunk_regexp = re.compile(r'"(.*?)"... | lems
]
def array_agg_row(*arg):
return func.array_agg(func.row(*arg), type_=ArrayOfRecord(arg))
| |
minscof/wemoJeedomPlugin | resources/wemo_server.py | Python | gpl-3.0 | 16,264 | 0.001969 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import sys
import logging
import argparse
#import subprocess
import json
import pywemo
import urllib.request
import urllib.error
import urllib.parse
import socketserver
from datetime import datetime
__version__ = '0.93'
logging.basicConfig(level=logging.DEBUG,
... | g.getLogger('apiRequestHandler')
#self.logger.debug('__init__')
socketserver.BaseRequestHandler.__init__(
self, request, client_address, server)
def start_response(self, code, contentType, data):
self.logger.debug(
'start_response() code = %s payload = %s', code, dat... | self.request.send(code.encode())
response_headers = {
'Content-Type': contentType + '; encoding=utf8',
'Content-Length': len(data),
'Connection': 'close',
}
response_headers_raw = ''.join('%s: %s\n' % (
k, v) for k, v in response_headers.items... |
UManPychron/pychron | pychron/canvas/canvas2D/extraction_line_canvas2D.py | Python | apache-2.0 | 10,949 | 0.001005 | # ===============================================================================
# Copyright 2011 Jake Ross
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses... | alSwitch
from pychron.canvas.scene_viewer import SceneCanvas
from pyc | hron.globals import globalv
W = 2
H = 2
class ExtractionLineAction(Action):
chamber = Str
class ExtractionLineCanvas2D(SceneCanvas):
"""
"""
scene_klass = ExtractionLineScene
use_backbuffer = True
border_visible = False
active_item = Any
selected_id = Str
show_axes = False
... |
devs1991/test_edx_docmode | venv/lib/python2.7/site-packages/django_extensions/management/utils.py | Python | agpl-3.0 | 2,188 | 0.001828 | import logging
import os
import sys
from django_extensions.management.signals import post_command, pre_command
def _make_writeable(filename):
"""
Make sure that the file is writeable. Useful if our source is
read-only.
"""
import stat
if sys.platform.startswith('java'):
# On Jython t... | l(logging.INFO)
outfile.setFormatter(logging.Formatter("%(asctime)s " + (fmt if fmt else '%(message)s')))
logger.addHandler(outfile)
class RedirectHandler(logging.Handler):
"""Redirect logging sent to | one logger (name) to another."""
def __init__(self, name, level=logging.DEBUG):
# Contemplate feasibility of copying a destination (allow original handler) and redirecting.
logging.Handler.__init__(self, level)
self.name = name
self.logger = logging.getLogger(name)
def emit(self... |
smallyear/linuxLearn | salt/salt/states/elasticsearch_index.py | Python | apache-2.0 | 2,188 | 0.001828 | # -*- coding: utf-8 -*-
'''
State module to manage Elasticsearch indices
.. versionadded:: 2015.8.0
'''
# Import python libs
from __future__ import absolute_import
import logging
# Import salt libs
log = logging.getLogger(__name__)
def absent(name):
'''
Ensure that the named index is absent
'''
r... | ndex=name)
if ret['result']:
ret['comment'] = 'Removed index {0} successfully'.format(name)
# TODO show pending changes (body)
else:
r | et['comment'] = 'Failed to remove index {0}'.format(name) # TODO error handling
elif not index_exists:
ret['comment'] = 'Index {0} is already absent'.format(name)
else:
ret['comment'] = 'Failed to determine whether index {0} is absent, see Minion log for more information'.format(name)
r... |
BQLQ/BQLQ | drum-0.4.0/drum/links/migrations/0003_auto_20171126_2314.py | Python | bsd-2-clause | 1,322 | 0.003026 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2017-11-26 15:14
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('generic', '0003_auto_20170... | appable_dependency(settings.AUTH_USER_MODEL),
('links', '0002_auto_20171104_180 | 9'),
]
operations = [
migrations.CreateModel(
name='UserTag',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('tag', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='ge... |
pbrf/example_api_python | example.py | Python | mit | 862 | 0.001277 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib
import json
data = {}
data['type_blank'] = 'a'
data['from_nam | e'] = 'Ивана Ивановича'
data['from_city'] = 'г. Москва'
data['from_street'] = 'ул. Стахановская'
data['from_build'] = '999'
data['from_appartment'] = '99'
data['from_zip'] = '109428'
data['whom_surname'] = 'Петрову'
data['whom_name'] = 'Петру Петровичу'
data['whom_city'] = 'г. Санкт-Петербург'
data['whom_street'] = 'ул... | 888'
data['whom_appartment'] = '88'
data['whom_zip'] = '190000'
data['declared_value'] = '1000.00'
data['COD_amount'] = '1100.00'
params = {}
params['access_token'] = ''
params['data'] = json.dumps(data)
params = urllib.urlencode(params)
f = urllib.urlopen("http://pbrf.ru/pdf.F7", params)
print f.read()
|
2mny/mylar | lib/cherrypy/_cpserver.py | Python | gpl-3.0 | 7,535 | 0.005574 | """Manage HTTP servers with CherryPy."""
import warnings
import cherrypy
from cherrypy.lib import attributes
from cherrypy._cpcompat import basestring
# We import * because we want to export check_port
# et al as attributes of this module.
from cherrypy.process.servers import *
class Server(ServerAdapter):
"""... | if not self.httpserver:
self.httpserver, self.bind_addr = self.httpserver_from_self()
ServerAdapter.start(self)
start.priority = 75
def _get_bind_addr(self):
if self.socket_file:
return self.socket_file
if self.socket_host is None and se | lf.socket_port is None:
return None
return (self.socket_host, self.socket_port)
def _set_bind_addr(self, value):
if value is None:
self.socket_file = None
self.socket_host = None
self.socket_port = None
elif isinstance(value, basestring):
... |
cogu/py-apx | tests/data_type_test.py | Python | mit | 3,285 | 0.006088 | import os, sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
import apx
import unittest
import remotefile
import autosar
class TestApxDataType(unittest.TestCase):
def setUp(self):
pass
def test_create_uint8_type(self):
dt = apx.DataType('MyU8_T','C')
... | self.assertEqual(dt.dataElement.typeCode, apx.UINT8_TYPE_CODE)
self.assertEqual(str(dt), 'T"MyU8_T"C(0,3)')
def test_create_uint8_array_type(self):
dt = apx.DataType('MyU8_T','C[8]')
self.assertIsInstance(dt, apx.DataType)
self.assertEqual(dt.dataElement.typeCode, apx.UINT8_T... |
dt2 = dt1.clone()
self.assertIsInstance(dt2, apx.DataType)
self.assertEqual(dt2.dataElement.typeCode, apx.UINT8_TYPE_CODE)
self.assertEqual(str(dt2), 'T"MyU8_T"C')
def test_create_uint16_type(self):
dt = apx.DataType('MyU16_T','S')
self.assertIsInstance(dt, apx.Data... |
bitmazk/django-linklist | linklist/tests/test_settings.py | Python | mit | 2,306 | 0 | """Settings that need to be set in order to run the tests."""
import os
DEBUG = True
SITE_ID = 1
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": ":memory:",
}
}
ROOT_URLCONF = 'linklist.tests.urls'
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
STATIC_ROOT = os.pa... | temFinder',
'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
TEMPLATE_DIRS = (
os.path.join(os.path.dirname(__file__), '../templates'),
)
COVERAGE_REPORT_HTML_OUTPUT_DIR = os.path.join(
o | s.path.dirname(__file__), 'coverage')
COVERAGE_MODULE_EXCLUDES = [
'tests$', 'settings$', 'urls$', 'locale$',
'migrations', 'fixtures', 'admin$', 'django_extensions',
]
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'djan... |
h4ck3rm1k3/OpenWrt-Firefly-SDK | staging_dir/host/lib/scons-2.3.1/SCons/Environment.py | Python | gpl-2.0 | 96,203 | 0.002276 | """SCons.Environment
Base class for construction Environments. These are
the primary objects used to communicate dependency and
construction information to the build engine.
Keyword arguments supplied when the construction Environment
is created are construction variables used to initialize the
Environment
"""
#
# ... | , to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom t | he 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 substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMIT... |
sdjcw/python-getting-started | app.py | Python | mit | 638 | 0 | # coding: utf-8
from datetime import datetime
from flask import Flask
from flask import render_template
from views.todos import todos_view
app = Flask(__name__)
ap | p.register_blueprint(todos_view, url_prefix='/todos')
@app.route('/')
def index():
return render_template('index.html')
@app.route('/time')
def time():
return str(datetime.now())
@app.route('/1/ping')
def ping():
"""健康监测
LeanEngine 会根据 `/1/ping` 判断应用是否正常运行。
如果返回状态码为 200 则认为正常。
其他状态码或者超 | 过 5 秒没响应则认为应用运行异常。
"""
return 'pong'
|
william-richard/moto | moto/awslambda/__init__.py | Python | apache-2.0 | 305 | 0 | from __future__ im | port unicode_literals
from .models import lambda_backends
from ..core.models import base_decorator, deprecated_base_decorator
lambda_backend = lambda_backends["us-east-1"]
mock_lambda = base_decorator(lambda_backends)
mock_lambda_deprecated = depreca | ted_base_decorator(lambda_backends)
|
DMOJ/judge | dmoj/executors/clang_executor.py | Python | agpl-3.0 | 293 | 0 | from .gcc_executor import | GCCExecutor, MAX_ERRORS
class ClangExecutor(GCCExecutor):
arch = 'clang_target_arch'
def get_flags(se | lf):
return self.flags + ['-ferror-limit=%d' % MAX_ERRORS]
@classmethod
def get_version_flags(cls, command):
return ['--version']
|
jht0664/Utility_python_gromacs | MonteCarlo/python/initial.py | Python | mit | 9,683 | 0.030776 | #!/usr/bin/env python3
# ver 0.1 - coding python by Hyuntae Jung on 6/1/2017
import argparse
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
description='Initial coordiante of particles for MC simulation')
## args
#parser.add_argument('-i', '--input', default='init... | ntry/nmod)%nmod == 0:
nmod = nmod*nmod
icx = np.trunc(np.random.random_sample()*box[0]/maxsize)
icy = np.trunc(np.random.random_sample()*box[1]/maxsize)
if args.sep == 'YES' and curr_index < args.nmola+maxb:
icz = np.trunc((np.random.random_sample()*0.50+0.50)*box[2]/maxsize)
elif args.sep == 'YES'... | box[2]/maxsize)
else:
icz = np.trunc(np.random.random_sample()*box[2]/maxsize)
randx = (icx+0.5)*maxsize
randy = (icy+0.5)*maxsize
randz = (icz+0.5)*maxsize
coordinates[curr_index] = [randx,randy,randz]
ntry = ntry + 1
if icx >= ncellx or icy >= ncelly or icz >= ncellz:
continue
elif occ... |
TeamAADGT/CMPUT404-project-socialdistribution | social/app/migrations/0007_merge_20170408_2326.py | Python | apache-2.0 | 334 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-04-08 23:26
from __future__ import unicode_literals
from django.db import m | igrations
class Migration(migrations.Migration):
dependencies = [
('app', '0006_author_has_github_task'),
('app', '0006_auto_20170405_1957'),
| ]
operations = [
]
|
AaronWatters/inferelator_strawman | inferelator_strawman/condition.py | Python | bsd-2-clause | 1,467 | 0.004772 |
import pandas as pd
class Condition:
"""
A condition maps gene names to numbers which often represent expression levels.
Parameters
----------
condition_name: str
A unique name identifying the condition.
gene_mapping: pd.Series
A pandas Series holding the gene to... | rn a 1d array of transcription factor coefficients for condition."
return self.gene_mapping[transcription_factors]
def meta_data_tsv_line(self, isTs=False, is1stLast="e", prevCol=None, delt=None):
def f(s):
if s is None:
return "NA"
else:
retu... | self.name]
return "\t".join(map(f, data)) + "\n"
|
Hainish/cerealbox | server/serial_comm.py | Python | gpl-3.0 | 372 | 0.024194 | import serial, sys
class SerialComm():
def __init | __(self, serial_device):
try:
self.ser = serial.Serial(serial_device, 9600, timeout=5)
except serial.serialutil.SerialException, e:
print "Unable to open serial port "+serial_device
sys.exit()
|
def close(self):
self.ser.close()
def writeln(self, line):
self.ser.write(line+"\n")
|
pkerpedjiev/ernwin | fess/scripts/bounding_box_coords.py | Python | agpl-3.0 | 2,959 | 0.007435 | #!/usr/bin/python
import sys
import numpy as np
import Bio.PDB as bp
import tess.threedee.model.coarse_grain as ttmc
import borgy.graph.graph_pdb as cgg
import borgy.visual.pymol as cvp
from optparse import OptionParser
def main():
usage = './bounding_box_coords.py temp.comp temp.pdb'
usage += "Print out ... | the pdb file.'
parser = OptionParser()
#parser.add_option('-o', '--options', dest='some_option', default='yo', help="Place holder for a real option", type='str')
parser.add_option('-e', '--edge', dest='edge', default=False, action='store_true', help='Include the edge nucleotides in the statistics.')
p... | cgo format.')
parser.add_option('-a', '--averages', dest='averages', default=False, action='store_true', help='Output the average coordinates of the bounding boxes')
(options, args) = parser.parse_args()
if len(args) < 2:
parser.print_help()
sys.exit(1)
chain = list(bp.PDBParser().get... |
JaxxC/goodgame.xbmc | plugin.video.goodgame/resources/lib/m3u8/model.py | Python | gpl-2.0 | 22,352 | 0.002058 | # coding: utf-8
# Copyright 2014 Globo.com Player authors. All rights reserved.
# Use of this source code is governed by a MIT License
# license that can be found in the LICENSE file.
from collections import namedtuple
import os
import errno
import math
try:
import urlparse as url_parser
except ImportError:
i... | path = self.base_path
self.media.base_path = self.base_path
self.segments.base_path = self.base_path
self.playlists.base_path = self.base_path
def add_playlist(self, playlist):
self.is_variant = True
self.playlists.append(playlist)
def add_iframe_playlist(self, iframe_p... | ant = True
self.iframe_playlists.append(iframe_playlist)
def add_media(self, media):
self.media.append(media)
def add_segment(self, segment):
self.segments.append(segment)
def dumps(self):
'''
Returns the current m3u8 as a string.
You could also use uni... |
lmmsoft/LeetCode | LeetCode-Algorithm/1243. Array Transformation/1243.py | Python | gpl-2.0 | 992 | 0.002016 | from typing import List
class Solution:
def transformArray2(self, arr: List[int]) -> List[int]:
while True:
arr2 = [a for a in arr]
changed = 0
for id in range(1 | , len(arr) - 1):
l = arr[id - 1]
r = arr[id + 1]
m = arr[id]
if l > m and r > m:
m += 1
changed += 1
elif l < m and r < m:
m -= 1
changed += 1
a... | def transformArray(self, A):
for _ in range(100):
A = A[:1] + [b + (a > b < c) - (a < b > c) for a, b, c in zip(A, A[1:], A[2:])] + A[-1:]
return A
if __name__ == '__main__':
assert Solution().transformArray([6, 2, 3, 4]) == [6, 3, 3, 4]
assert Solution().transformArray([1, 6, 3... |
kevinkle/semantic | superphy/src/upload/python/sparql/user.py | Python | apache-2.0 | 2,243 | 0.009808 | #!/usr/bin/python
#Filename: user_query_strings.py
#Author: Bryce Drew
#Date: Sept. 30, 2015
#Functionality:
#These are sparql queries. They are designed to be specific for the user ontology:
from sparql.endpoint import Endpoint
def add_literal_by_email(email, predicate, literal):
update = """
PREFIX emai... | al:.
indv: RDF_type: user:.
indv: email: '%s'
}""" % (sparql_id, email.lower()))
#Called by sign_up app vi | ew
def insert_next_user(email="no"):
#See if email exists
if email_exists(email.lower()):
#This doesn't acutally stop anything with the sql though, so don't
#think this is a good place to put a validator. -Bryce
print "Already Exists!"
return False
#Get next user id
resul... |
dmsovetov/pygling | Pygling/__main__.py | Python | mit | 3,421 | 0.042093 | #!/usr/bin/python
#################################################################################
#
# The MIT License (MIT)
#
# Copyright (c) 2015 Dmitry Sovetov
#
# https://github.com/dmsovetov
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documen... | g = 'Pygling', description = 'Pygling C++ workspace generator.', prefix_chars = '--', formatter_class = argparse.ArgumentDefaultsHelpFormatter )
parser.add_argument( "action", type = str, help = "Action", choices = ["configure", "build", "install"] )
parser.add_argument( "-... | "--platform", default = 'all', type = str, help = "Target platform" )
parser.add_argument( "-s", "--source", default = '.', type = str, help = "Project source path" )
parser.add_argument( "-o", "--output", default = 'projects', type = str, help = "Output path" )
parser.a... |
CBE544/CBE544.github.io | ASE/Getting_Started/run_sp.py | Python | gpl-2.0 | 2,085 | 0.026859 | from ase import *
from espresso import espresso
from ase.lattice import bulk
import matplotlib
matplotlib.use('Agg') #turn off screen output so we can plot from the cluster
import matplotlib.pyplot as plt
import numpy as np
metal = 'Pt'
metal2 = None # if you have an alloy, specify the second metal
name = metal
if... | cutoff
xc='BEEF-vdW', #exchange-correlation functional
kpts=(k,k,k), #sampling grid of the Brillouin zone
#(is internally folded back to the
#irreducible Brillouin zone | )
nbands=-10, #10 extra bands besides the bands needed to hold
#the valence electrons
sigma=0.1,
psppath='/home/vossj/suncat/psp/gbrv1.5pbe', #pseudopotential path
convergence= {'energy':1e-5,
'mixing':0.1,
... |
ArduPilot/MAVProxy | MAVProxy/modules/mavproxy_restserver.py | Python | gpl-3.0 | 5,314 | 0.002446 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Server Module
Patrick Jose Pereira
April 2018
'''
import time
import json
import socket
from threading import Thread
from flask import Flask
from werkzeug.serving import make_server
from MAVProxy.modules.lib import mp_module
def mavlink_to_json(msg):
'''Translate... | ": "No message"}'
try:
status_dict = json.loads(mpstatus_to_json(self.status))
except Exception as e:
print(e)
return
# If no key, send the entire json
if not arg:
return json.dumps(statu | s_dict)
# Get item from path
new_dict = status_dict
args = arg.split('/')
for key in args:
if key in new_dict:
new_dict = new_dict[key]
else:
return '{"key": "%s", "last_dict": %s}' % (key, json.dumps(new_dict))
return jso... |
resamsel/dbnavigator | src/dbmanagr/wrapper.py | Python | gpl-3.0 | 3,349 | 0 | # -*- coding: utf-8 -*-
#
# Copyright © 2014 René Samselnig
#
# This file is part of Database Navigator.
#
# Database Navigator 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, ... | is INFO or higher
log.log_error(e) # pragma: no cover
def exec | uter(self, *args): # pragma: no cover
"""Execute remotely"""
options = self.options
try:
# from dbmanagr import daemon
# if not daemon.is_running(options):
# daemon.start_server(options)
url = 'http://{host}:{port}/{path}'.format(
... |
freedomtan/workload-automation | wlauto/workloads/andebench/__init__.py | Python | apache-2.0 | 3,485 | 0.003443 | # Copyright 2013-2015 ARM Limited
#
# Licensed under the Apache License, Version 2.0 (the "Lice | nse");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WAR... |
import re
from wlauto import AndroidUiAutoBenchmark, Parameter, Alias
from wlauto.exceptions import ConfigError
class Andebench(AndroidUiAutoBenchmark):
name = 'andebench'
description = """
AndEBench is an industry standard Android benchmark provided by The
Embedded Microprocessor Benchmark Consort... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.