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 |
|---|---|---|---|---|---|---|---|---|
3v1n0/pywws | src/pywws/__init__.py | Python | gpl-2.0 | 67 | 0 | __v | ersion__ = '19.10.0.cwop'
_release = '1665'
_c | ommit = 'd22c19c'
|
HybridF5/jacket | jacket/tests/compute/unit/virt/disk/mount/test_api.py | Python | apache-2.0 | 7,718 | 0.001166 | # Copyright 2015 Hewlett-Packard Development Company, L.P.
#
# 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 requir... | self.assertIsInstance(inst, nbd.NbdMount)
def test_instance_for_device_nbd_partition(self):
image = mock.MagicMock()
mount_dir = '/mount/dir'
partition = 1
device = '/dev/mapper/nbd0p1'
| inst = api.Mount.instance_for_device(image, mount_dir, partition,
device)
self.assertIsInstance(inst, nbd.NbdMount)
def test_instance_for_device_block(self):
image = mock.MagicMock()
mount_dir = '/mount/dir'
partition = -1
... |
patsissons/Flexget | flexget/plugins/metainfo/imdb_url.py | Python | mit | 1,526 | 0.002621 | from __future__ import unicode_literals, division, absolute_import
import re
import logging
from flexget import plugin
from flexget.event import event
from flexget.utils.imdb import extract_id, make_url
log = logging.getLogg | er('metainfo_imdb_url')
class MetainfoImdbUrl(object):
"""
Scan entry information for imdb url.
"""
schema = {'type': 'boolean'}
def on_task_metainfo(self, task, config):
# check if disabled (value set to false)
if 'scan_imdb' in task.config:
if | not task.config['scan_imdb']:
return
for entry in task.entries:
# Don't override already populated imdb_ids
if entry.get('imdb_id', eval_lazy=False):
continue
if not 'description' in entry:
continue
urls = re.findal... |
gscarella/pyOptFEM | pyOptFEM/common.py | Python | gpl-3.0 | 5,804 | 0.037216 | from scipy import sparse
import matplotlib.pyplot as plt
import os, errno, ctypes
from numpy import log
def NormInf(A):
"""This function returns the norm Inf of a *Scipy* sparse Matrix
:param A: A *Scipy* sparse matrix
:returns: norm Inf of A given by :math:`\| A\|_\infty=\max_{i,j}(|A_{i,j}|)`.
"""
if (A... | ctypes.c_ulong
class MEMORYSTATUS(ctypes.Structure):
_fields_ = [
("dwLength", c_ulong),
("dwMemoryLoad", c_ulong),
("dwTotalPhys", c_ulong),
("dwAvailPhys", c_ulong),
("dwTotalPageFile", c_ulong),
("dwA... | c_ulong)
]
memoryStatus = MEMORYSTATUS()
memoryStatus.dwLength = ctypes.sizeof(MEMORYSTATUS)
kernel32.GlobalMemoryStatus(ctypes.byref(memoryStatus))
return int(memoryStatus.dwTotalPhys/1024**2)
def linuxRam(self):
"""Returns the RAM of a linux system"""
... |
stonebig/bokeh | bokeh/embed/notebook.py | Python | bsd-3-clause | 3,803 | 0.0071 | #-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2019, Anaconda, Inc., and Bokeh Contributors.
# All rights reserved.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#-------------------------------------------------------------------... | me`` instance in the current docume | nt.
Setting this to ``None`` uses the default theme or the theme
already specified in the document. Any other value must be an
instance of the ``Theme`` class.
Returns:
script, div, Document
.. note::
Assumes :func:`~bokeh.io.notebook.load_notebook` or the e... |
MalloyPower/parsing-python | front-end/testsuite-python-lib/Python-3.1/Lib/distutils/fancy_getopt.py | Python | mit | 17,855 | 0.00112 | """distutils.fancy_getopt
Wrapper around the standard getopt module that provides the following
additional features:
* short and long options are tied together
* options have help strings, so fancy_getopt could potentially
create a complete usage summary
* options set attributes of a passed-in object
"""
__... | "aliased option '%s' takes a value"
% (long, alias_to))
self.long_opts[-1] = long # XXX redundant?!
self.ta | kes_arg[long] = 0
# If this is an alias option, make sure its "takes arg" flag is
# the same as the option it's aliased to.
alias_to = self.alias.get(long)
if alias_to is not None:
if self.takes_arg[long] != self.takes_arg[alias_to]:
r... |
the-new-sky/BlogInPy | markdown/extensions/smartLegend.py | Python | gpl-3.0 | 10,615 | 0.009232 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import markdown
from markdown.treeprocessors import Treeprocessor
from markdown.blockprocessors import BlockProcessor
import re
from markdown import util
import xml.etree.ElementTree as ET
import copy
from markdown.inlinepatterns im... | for nelem in elem:
if nelem.tag in self.configs["PARENTS"] and nelem not in elemsToInspect:
elemsToInspect.append(nelem)
if nelem.tag == "customlegend" and precedent is not None : # and len(list(nelem.itertext())) == 0 :
proc =... | proc.transform(elem, precedent, nelem, i-1)
Restart = True
break
precedent = nelem
i+=1
return root
def parse_autoimg(self, root):
elemsToInspect = [root]
while len(elemsToInspect) > 0:
... |
iamantony/PythonNotes | src/algorithms/search/__init__.py | Python | mit | 124 | 0 | __author__ | = 'Antony Cherepanov'
from inversionscount import InversionsCounter
from closestpoints import Clos | estPoints
|
pde/torbrowser-launcher | lib/Parsley-1.1/ometa/test/test_pymeta.py | Python | mit | 48,024 | 0.003082 | import operator
from textwrap import dedent
from twisted.trial import unittest
from ometa.grammar import OMeta, TermOMeta, TreeTransformerGrammar
from ometa.compat import OMeta1
from ometa.runtime import (ParseError, OMetaBase, OMetaGrammarBase, EOFError,
expected, TreeTransformerBase)
from o... | ts ::= <digit>+
""")
self.assertEqual(g.bits('0110110'), '0110110')
def test_negate(self):
"""
Input can be matched based on its fai | lure to match a pattern.
"""
g = self.compile("foo ::= ~'0' <anything>")
self.assertEqual(g.foo("1"), "1")
self.assertRaises(ParseError, g.foo, "0")
def test_ruleValue(self):
"""
Productions can specify a Python expression that provides the result
of the par... |
coinbox/coinbox-mod-base | cbmod/base/views/window.py | Python | mit | 7,111 | 0.006609 | from pydispatch import dispatcher
from PySide import QtCore, QtGui
import cbpos
logger = cbpos.get_logger(__name__)
from .page import BasePage
class MainWindow(QtGui.QMainWindow):
__inits = []
def __init__(self):
super(MainWindow, self).__init__()
self.tabs = QtGui... | event):
"""
Perform necessary operations before closing the window.
"""
self.saveWindowState()
#do any other thing before closing...
event.accept()
@classmethod
def addInit(cls, init):
"""
Adds the `init` method to the list of exte... | callInit(self):
"""
Handle calls to `__init__` methods of extensions of the MainWindow.
"""
for init in self.__inits:
init(self)
|
antoinecarme/pyaf | tests/artificial/transf_Anscombe/trend_Lag1Trend/cycle_30/ar_12/test_artificial_128_Anscombe_Lag1Trend_30_12_20.py | Python | bsd-3-clause | 265 | 0.086792 | import pyaf.Bench.TS_datasets as tsds
import | tests.artificial.process_artificial_dataset as art
art.process_dataset(N = 128 , FREQ = 'D', seed = 0, trendtype = "Lag1T | rend", cycle_length = 30, transform = "Anscombe", sigma = 0.0, exog_count = 20, ar_order = 12); |
dhuang/incubator-airflow | airflow/providers/sftp/hooks/sftp.py | Python | apache-2.0 | 11,761 | 0.001786 | #
# 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... | str(extra_options['ignore_hostkey_verification']).lower() == 'true'
)
if 'no_host_key_check' in extra_options:
self.no_host_key_check = str(extra_options['no_host_key_check']).lower() == 'true'
if 'ciphers' in extra_options:
... | |
atiberghien/makerscience-server | makerscience_profile/migrations/0007_auto__add_field_makerscienceprofile_website.py | Python | agpl-3.0 | 8,044 | 0.007708 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'MakerScienceProfile.website'
db.add_column(u'makerscience... | h.Permission']"}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
u'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_... | b.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
u'makerscience_profile.makerscienceprofile': {
'Meta': {'ob... |
pandas-dev/pandas | pandas/tests/indexes/timedeltas/test_timedelta.py | Python | bsd-3-clause | 4,517 | 0.00155 | from datetime import timedelta
import numpy as np
import pytest
import pandas as pd
from pandas import (
Index,
NaT,
Series,
Timedelta,
TimedeltaIndex,
timedelta_range,
)
import pandas._testing as tm
from pandas.core.indexes.api import Int64Index
from pandas.tests.indexes.datetimelike import D... | oat64))
tm.assert_index_equal(res, expected)
# check this matches Series and TimedeltaArray
res = tdi._data.astype("m8[s]")
tm.assert_numpy_array_equal(res, expected._values)
res = tdi.to_series().astype("m8[s]")
tm.assert_numpy_array_equal(res._values, expected._values... | version(self, index_or_series):
# doc example
scalar = Timedelta(days=31)
td = index_or_series(
[scalar, scalar, scalar + timedelta(minutes=5, seconds=3), NaT],
dtype="m8[ns]",
)
result = td / np.timedelta64(1, "D")
expected = index_or_series(
... |
sniemi/SamPy | sandbox/src1/subplot_demo.py | Python | bsd-2-clause | 349 | 0.002865 | from pylab | import *
t1 = arange(0.0, 5.0, 0.1)
t2 = arange(0.0, 5.0, 0.02)
t3 = arange(0.0, 2.0, 0.01)
subplot(211)
plot(t1, cos(2*pi*t1)*exp(-t1), 'bo', t2, cos(2*pi*t2)*exp(-t2), 'k')
grid(True)
title('A tale of 2 subplots')
ylabel('Damped')
subplot(212 | )
plot(t3, cos(2*pi*t3), 'r--')
grid(True)
xlabel('time (s)')
ylabel('Undamped')
show()
|
kshmirko/pysolar-py3 | Pysolar/elevation.py | Python | gpl-3.0 | 2,481 | 0.026199 | #!/usr/bin/python
# Copyright Sean T. Hammond
#
# This file is part of Pysolar.
#
# Pysolar 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 opt... | TE: results might be odd for elevations below 0 (sea level), | like Dead Sea.
#h=elevation relative to sea level (m)
#Ps= static pressure (pascals) = 101325.00 P
#Ts= standard temperature (kelvin) = 288.15 K
#Tl= temperature lapse rate (kelvin/meter) = -0.0065 K/m
#Hb= height at the bottom of the layer = 0
#R= universal gas constant for air = 8.31432 N*m/s^2
#g= gravitatio... |
wking/cpython-extension | grab-cores.py | Python | cc0-1.0 | 403 | 0 | #!/usr/bin/env python
import threading
im | port spam
def grab_cores(threads=1, count=int(1e9)):
_threads = []
for i in range(threads):
thread = threading.Thread(target=spam.busy, args=(count,))
_threads.append(thread)
thread.start()
for thread in _threads:
thread.join()
if __name__ == '__main__':
import sys
... | grab_cores(threads=int(sys.argv[1]))
|
palash1992/GEM | gem/evaluation/evaluate_graph_reconstruction.py | Python | bsd-3-clause | 3,704 | 0.00108 | try: import cPickle as pickle
except: import pickle
from gem.evaluation import metrics
from gem.utils import evaluation_util, graph_util
import networkx as nx
import numpy as np
def evaluateStaticGraphReconstruction(digraph, graph_embedding,
X_stat, node_l=None, file_suffix=None,... | is_undirected
)
else:
eval_edge_pairs = None
if file_suffix is None:
estimated_adj = graph_embedding.get_reconstructed_adj(X_stat, node_l)
else:
estimated_adj = graph_embedding.get_reconstructed_adj(
X_stat,
file_suffix,
node_l
... | e_pairs=eval_edge_pairs
)
MAP = metrics.computeMAP(predicted_edge_list, digraph, is_undirected=is_undirected)
prec_curv, _ = metrics.computePrecisionCurve(predicted_edge_list, digraph)
# If weighted, compute the error in reconstructed weights of observed edges
if is_weighted:
digraph_adj = n... |
sigopt/sigopt-python | test/cli/test_cli_config.py | Python | mit | 1,165 | 0.007725 | import click
import mock
import pytest
from click.testing import CliRunner
from sigopt.cli import cli
class TestRunCli(object):
@pytest.mark.parametrize('opt_into_log_collection', [False, True])
@pytest.mark.parametrize('opt_into_cell_tracking', [False, True])
def test_config_command(self, opt_into_log_collect... | acking' if opt_into_cell_tracking else '--no-enable-cell-tracking'
with mock.patch('sigopt.cli.commands.config._config.persist_configuration_options') as persist_configuration_options:
result = runner.invoke(cli, [
'config',
'--api-token=some_test_token',
log_collectio | n_arg,
cell_tracking_arg,
])
persist_configuration_options.assert_called_once_with({
'api_token': 'some_test_token',
'code_tracking_enabled': opt_into_cell_tracking,
'log_collection_enabled': opt_into_log_collection,
})
assert result.exit_code == 0
assert result... |
yujikato/DIRAC | src/DIRAC/StorageManagementSystem/DB/StorageManagementDB.py | Python | gpl-3.0 | 58,271 | 0.010262 | """ StorageManagementDB is a front end to the Stager Database.
There are five tables in the StorageManagementDB: Tasks, CacheReplicas, TaskReplicas, StageRequests.
The Tasks table is the place holder for the tasks that have requested files to be staged.
These can be from different systems and have differe... | nection(connection)
if not taskIDs:
return S_OK(taskIDs)
# * -> Failed
if newTaskState == 'Failed':
oldTaskState = []
# StageCompleting -> Done
elif newTaskState == 'Done':
oldTaskState = ['StageC | ompleting']
# StageSubmitted -> StageCompleting
elif newTaskState == 'StageCompleting':
oldTaskState = ['StageSubmitted']
# Waiting -> StageSubmitted
elif newTaskState == 'StageSubmitted':
oldTaskState = ['Waiting', 'Offline']
# New -> Waiting
elif newTaskState == 'Waiting':
ol... |
VRaviTheja/SDN-policy | testing/testing_detection.py | Python | apache-2.0 | 3,341 | 0.055373 | #!/usr/bin/python
import pytricia
import reading_file_to_dict
import sys
import pprint
import csv
import p_trie
def patricia(device_values):
pyt_src = pytricia.PyTricia()
pyt_dst = pytricia.PyTricia()
return pyt_src,pyt_dst
def check_tcp_udp(flow_rule):
if(flow_rule["nw_proto"]=="6"):
return Tru... | return False
def detection_algorithm(r,gamma):
if(check_tcp_udp(r)==check_tcp_udp(gamma)):
add_rule_to_newft(r)
return
if(subset(pyt_src,pyt_dst,r,gamma)=="equal"): #do subset here
if(r["action "]==gamma["action "]):
conflict_resolver(gamma,r,redundancy)
print "Conflict is Redundancy : Sent to resol... | conflict_resolver(r,gamma,correlation)
print "Conflict is Correlation : Sent to resolving"
else:
print "Conflict is Generalization : Sent to resolving"
if(subset(pyt_src,pyt_dst,r,gamma)=="reverse"): #do subset here
if(r["action "]==gamma["action "]):
print "Conflict is Redundancy : Sent to resolving"... |
antoinecarme/pyaf | tests/artificial/transf_Anscombe/trend_LinearTrend/cycle_7/ar_12/test_artificial_32_Anscombe_LinearTrend_7_12_0.py | Python | bsd-3-clause | 264 | 0.087121 | import pyaf.Bench.TS_datasets as tsds
import tests.artificial.process_artificial_dataset as art
art.process_dataset(N = 32 , FREQ = 'D', seed = 0, trend | type = | "LinearTrend", cycle_length = 7, transform = "Anscombe", sigma = 0.0, exog_count = 0, ar_order = 12); |
arsenypoga/ImageboardDownloader | DownloaderConstants.py | Python | mit | 278 | 0 | # -*- coding: UTF-8 -*-
DOWNLOADER_VERSION = "0.0.1"
DOWNLOADER_LOG_FILE = "downloader.l | og"
DOWNLOADER_LOG_SIZE = 10485760
DOWNLOADER_LOG_COUNT = 10
DOWNLOADER_LOG_FORMAT = "%(asctime)s - %(name)s - %(levelname) | s - %(message)s"
DOWNLOADER_REQUIREMENTS_PATH = "requirements.txt"
|
csirtgadgets/bearded-avenger-sdk-py | cifsdk/msg.py | Python | mpl-2.0 | 3,924 | 0.000255 | import ujson as json
from pprint import pprint
import msgpack
import logging
from cifsdk.constants import PYVERSION
import os
TRACE = os.environ.get('CIFSDK_CLIENT_MSG_TRACE')
logger = logging.getLogger(__name__)
logger.setLevel(logging.ERROR)
if TRACE:
logger.setLevel(logging.DEBUG)
MAP = {
1: 'ping',
2... | self.token = self.token.encode('utf-8')
if PYVERSION == 2:
if isinstance(self.token, unicode):
self.token = self.token.encode('utf-8')
m.append(self.token)
if self.mtype:
if isinstance(self.mtype, bytes):
se... | self.data = [self.data]
if isinstance(self.data, list):
self.data = json.dumps(self.data)
if isinstance(self.data, str):
self.data = self.data.encode('utf-8')
if PYVERSION == 2:
if isinstance(self.data, unicode):
self.data = self... |
drphilmarshall/StatisticalMethods | lessons/graphics/notparallel_chain_fit.py | Python | gpl-2.0 | 3,306 | 0.013914 | # Copied from LMC documentation
# Modified to use MPI (but not enable parallelization), to increase the parameter degeneracy, and to disperse the start points
# Here is a simple example. As shown it will run in non-parallel mode; comments indicate what to do for parallelization.
from lmc import *
## for MPI
from mpi4... | the chain in a text file.
#chainfile = open("chain.txt", 'w')
## For filesystem parallelization, each instance should write to a different file.
## For MPI, the same is true, e.g.
chainfile = open( | "notparallel" + str(MPI.COMM_WORLD.Get_rank()) + ".txt", 'w')
backends = [ textBackend(chainfile) ]
### Print the chain to the terminal as well
#backends.append( stdoutBackend() )
### Run the chain for 10000 iterations
engine(10000, thing, backends)
### Close the text file to clean up.
chainfile.close()
## If this ... |
Trebek/pydealer | docs/conf.py | Python | gpl-3.0 | 8,642 | 0.005439 | # -*- coding: utf-8 -*-
#
# PyDealer documentation build configuration file, created by
# sphinx-quickstart on Tue Jul 22 21:57:58 2014.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# ... | an appendix to all manuals.
#latex_appendices = []
# If false, no | module index is generated.
#latex_domain_indices = True
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'pydealer', u'PyDealer Documentation',
[u... |
gegenschall/cython-ldns | tools/stripcomments.py | Python | bsd-3-clause | 244 | 0.004098 | import fileinput |
for line in fileinput.input():
_line = line.strip()
# super dumb...
if _line.startswith( | '//') or _line.startswith('/*') or _line.startswith('*') or _line.startswith('*/'):
continue
print line.rstrip()
|
Ledoux/ShareYourSystem | Pythonlogy/ShareYourSystem/Specials/Predicters/Predicter/tests/01_tests_dynamic_rate/01_test_dynamic_rate_oneagent_onesensor_ExampleCell.py | Python | mit | 852 | 0.051643 | #/###################/#
# Import modules
#
#ImportModules
import ShareYourSystem as SYS
#/###################/#
# Build the model
#
#Simulation time
BrianingDebugVariable=25.
#A - transition matrix
JacobianTimeFloat = 30. #(ms)
A = (-1./float(JacobianTimeFloat)
)*SYS.numpy.array([[1.]])
#Define
MyPredicter=SYS.P... | View
#
MyPredicter.mapSet(
{
'PyplotingFigureVariable':{
'figsize':(10,8)
},
'PyplotingGridVariable':(30,30)
}
).view(
).pyplot(
).show(
)
#/###################/#
# Print
#
#Definition the AttestedStr
| print('MyPredicter is ')
SYS._print(MyPredicter)
|
raghakot/keras-vis | vis/grad_modifiers.py | Python | mit | 1,247 | 0 | from __future__ import absolute_import
import numpy as np
from keras import backend as K
from .utils import utils
def negate(grads):
| """Negates the gradients.
Args:
grads: A numpy array of grads to use.
Returns:
The negated gradients.
"""
return -grads
def absolute(grads):
"""Computes absolute gradients.
Args:
grads: A numpy array of grads to use.
Ret | urns:
The absolute gradients.
"""
return np.abs(grads)
def invert(grads):
"""Inverts the gradients.
Args:
grads: A numpy array of grads to use.
Returns:
The inverted gradients.
"""
return 1. / (grads + K.epsilon())
def relu(grads):
"""Clips negative gradient... |
rapydo/do | controller/commands/volatile.py | Python | mit | 802 | 0.001247 | """
[DEPRECATED] Run a single container in debug mode
"" | "
import typer
from controller import print_and_exit
from controller.app import Application
# Deprecated since 2.1
@Application.app.command(help="Replaced by run --debug command")
def volatile(
service: str = typer.Argument(
...,
help="Service name",
shell_complete=Application.autocomplet... | e,
),
command: str = typer.Argument(
"bash", help="UNIX command to be executed on selected running service"
),
user: str = typer.Option(
None,
"--user",
"-u",
help="User existing in selected service",
show_default=False,
),
) -> None:
# Deprecated ... |
acopar/crow | crow/crow/transfer/mocktransfer.py | Python | gpl-3.0 | 150 | 0.013333 | def | empty_reduce(rank, device_list, output, source=0):
pass
def empty_sync_matrix(rank, device_list, output, source=0, collect= | False):
pass
|
DmitryTsybin/Study | Coursera/Algorithmic_Thinking/Project_1/Project_1_Degree_distributions_for_graphs.py | Python | mit | 2,805 | 0.002496 | import random
"""Define const graphs"""
EX_GRAPH0 = {0: set([1, 2]), 1: set([]), 2: set([])}
EX_GRAPH1 = {
0: set([1, 4, 5]),
1: set([2, 6]),
2: set([3]),
3: set([0]),
4: set([1]),
5: set([2]),
6: set([])
}
EX_GRAPH2 = {
0: set([1, 4, 5]),
1: set([2, 6]),
2: set([3, 7]),
3: ... | bution:
divisor += distribution[value]
for value in distribution:
| normalized_distribution[value] = distribution[value] / float(divisor)
return normalized_distribution
#print in_degree_distribution(EX_GRAPH0)
#print normalized_in_degree_distribution(EX_GRAPH0)
#print in_degree_distribution(EX_GRAPH1)
#print normalized_in_degree_distribution(EX_GRAPH1)
#print in_degree_dist... |
jemandez/creaturas-magicas | Configuraciones básicas/scripts/addons/blendertools-1.0.0/maketarget/export_mh_obj.py | Python | gpl-3.0 | 8,237 | 0.004856 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
**Project Name:** MakeHuman
**Product Home Page:** http://www.makehuman.org/
**Code Home Page:** http://code.google.com/p/makehuman/
**Authors:** Thomas Larsson
**Copyright(c):** MakeHuman Team 2001-2014
**Licensing:** AGPL3 (see also ht... | for f in faces:
faceNeighbors[f.index] = []
uvFaceVerts[f.index] = []
for f in faces:
for e i | n faceEdges[f.index]:
for f1 in edgeFaces[e.index]:
if f1 != f:
faceNeighbors[f.index].append((e,f1))
vtn = 0
texVerts = {}
if BMeshAware:
uvloop = me.uv_layers[0]
n = 0
for f in faces:
for vn in f.vertices:
... |
hpcleuven/easybuild-easyblocks | easybuild/easyblocks/o/openfoam.py | Python | gpl-2.0 | 18,326 | 0.003929 | ##
# Copyright 2009-2016 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be),
# Flemish Research Foundation (F... | rs in %s", script)
# disable any third party stuff, we use EB controlled builds
regex_subs = [(r"^(setenv|export) WM_THIRD_PARTY_USE_.*[ =].*$", r"# \g<0>")]
WM_env_var = ['WM_COMPILER', 'WM_MPLIB', 'WM_THIRD_PARTY_DIR']
# OpenFOAM >= 3.0.0 can use 64 bit integers
... |
for env_var in WM_env_var:
regex_subs.append((r"^(setenv|export) (?P<var>%s)[ =](?P<val>.*)$" % env_var,
r": ${\g<var>:=\g<val>}; export \g<var>"))
apply_regex_substitutions(script, regex_subs)
# inject compiler variables into wmake/r... |
texuf/myantname | main.py | Python | mit | 869 | 0.004603 | from app import app
import argparse
import os
import routes
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description='Run the MightySpring backend server.')
parser.add_argument('--debug',
'-d',
default=True)
parser.a... | get('PORT', 5000)),
type=int)
parser.add_argument('--bind-address',
'-b',
nargs='?',
default=u'0.0.0.0',
type=unicode)
args = parser.parse_args()
debug = args.debug
por | t = args.port
bind_address = args.bind_address
app.run(host=bind_address, port=port, debug=debug) |
geelweb/geelweb-django-contactform | tests/views.py | Python | mit | 202 | 0.009901 | from djan | go.http import HttpResponse
from django.shortcuts import render
def index(request):
return HttpResponse('Page content')
def custom(request):
retu | rn render(request, 'custom.html', {})
|
wulczer/ansible | v2/ansible/plugins/lookup/inventory_hostnames.py | Python | gpl-3.0 | 1,756 | 0.003417 | # (c) 2012, Michael DeHaan <[email protected]>
# (c) 2013, Steven Dossett <[email protected]>
#
# 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 versio... | u.org/licenses/>.
from ansible.utils import safe_eval
import ansible.utils as utils
import ansible.errors as errors
import ansible.inventory as inventory
def flatten(terms):
ret = []
for term in terms:
if isinstance(term, list):
| ret.extend(term)
else:
ret.append(term)
return ret
class LookupModule(object):
def __init__(self, basedir=None, **kwargs):
self.basedir = basedir
if 'runner' in kwargs:
self.host_list = kwargs['runner'].inventory.host_list
else:
raise erro... |
anish/buildbot | master/buildbot/util/sautils.py | Python | gpl-2.0 | 2,925 | 0.000342 | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without eve... | //www.sqlalchemy.org/docs/core/compiler.html#compiling-sub-elements-of-a-custom-expression-construct # noqa pylint: | disable=line-too-long
# _execution_options per
# http://docs.sqlalchemy.org/en/rel_0_7/core/compiler.html#enabling-compiled-autocommit
# (UpdateBase requires sqlalchemy 0.7.0)
class InsertFromSelect(Executable, ClauseElement):
_execution_options = \
Executable._execution_options.union({'autocommit': True}... |
kgadek/evogil | statistic/stats_bootstrap.py | Python | gpl-3.0 | 4,906 | 0.003474 | import random
from math import sqrt
import numpy
def validate_cost(result, boot_size, delta=500):
budget = result["budget"]
for metric_name, _, data_process in result['analysis']:
if metric_name == "cost":
cost_data = list(x() for x in data_process)
data_analysis = yield_analys... | tion, k)) for i in range(n))
return {
"confidence": 100.0 * (1 - 2 * alpha),
"from": btstrp[int(1.0 * n * alpha)],
"to": btstrp[int(1.0 * n * (1 - alpha))],
"metrics": f(population)
}
def yield_analysis(data_process, boot_size):
q1 = numpy.percentile(data_process, 25)
q3... | upp_inn_fence = q3 + 1.5*iq
low_out_fence = q1 - 3*iq
upp_out_fence = q3 + 3*iq
# noinspection PyRedeclaratione
extr_outliers = len([x
for x in data_process
if (x < low_out_fence or upp_out_fence < x)])
# noinspection PyRedeclaration
mild_outl... |
mbolivar/zephyr | scripts/parse_syscalls.py | Python | apache-2.0 | 4,506 | 0.000444 | #!/usr/bin/env python3
#
# Copyright (c) 2017 Intel Corporation
#
# SPDX-License-Identifier: Apache-2.0
import sys
import re
import argparse
import os
import json
api_regex = re.compile(r'''
__syscall\s+ # __syscall attribute, must be first
([^(]+) # type and name of system ... | at_args
flat_args = [sys_id, func_name] + flat_args
argslist = ", ".join(flat_args)
invocation = "%s(%s);" % (macro, argslist)
handler = "_handler_" + func_name
# Entry in _k_syscall_table
table_entry = "[%s] = %s" % (sys_id, handler)
return (fn, handler, invocation, sys_id, table_entry)... | l which we
# don't want to trip over
path = os.path.join(root, fn)
if not fn.endswith(".h") or path.endswith(os.path.join(os.sep, 'toolchain', 'common.h')):
continue
with open(path, "r", encoding="utf-8") as fp:
try:
re... |
ffsdmad/af-web | cgi-bin/plugins2/doc_view_list.py | Python | gpl-3.0 | 444 | 0.010336 | # -*- coding: utf8 -*-
SQL = """select SQL_CALC_FOUND_ROWS * FROM doc_view order by `name` asc limit %(offset)d,%(limit)d ;"""
FOUND_ROWS = True
ROOT = "doc_view_list"
ROOT_PREFIX = "<doc_view_edit />"
ROOT_POSTFIX= None
XSL_TEMPLATE = "data/af-w | eb.xsl"
EVENT = None
WHERE = ()
PARAM = None
TITLE="Список видов документов"
MESSAGE="ошибка получен | ия списка видов документов"
ORDER = None
|
hammerlab/immuno | test/test_mhc_formats.py | Python | apache-2.0 | 2,503 | 0.002397 | from immuno.mhc_formats import parse_netmhc_stdout
from immuno.peptide_binding_measure import (
IC50_FIELD_NAME,
PERCENTILE_RANK_FIELD_NAME,
)
def test_mhc_stdout():
s = """
# Affinity Threshold for Strong binding peptides 50.000',
# Affinity Threshold for Weak binding peptides 500.000',
# Ran... | 32176.84 50.00
4 HLA-A*02:03 QYFPEITHI id0 0.085 19847.09 32.00
5 HLA-A*02:03 YFPEITHII id0 0.231 4123.85 15.00
| 6 HLA-A*02:03 FPEITHIII id0 0.060 26134.28 50.00
7 HLA-A*02:03 PEITHIIIA id0 0.034 34524.63 50.00
8 HLA-A*02:03 EITHIIIAS id0 0.076 21974.48 50.00
9 HLA-A*02:03 ITHIIIASS id0 0.170 7934.26 32.00
10 HLA-A*02:03 ... |
ResearchSoftwareInstitute/MyHPOM | myhpom/migrations/0017_ad_thumbnail.py | Python | bsd-3-clause | 527 | 0.001898 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db imp | ort migrations, models
class Migration(migrati | ons.Migration):
dependencies = [
('myhpom', '0015_userdetails_updated'),
]
operations = [
migrations.AddField(
model_name='advancedirective',
name='thumbnail',
field=models.FileField(help_text=b"The first-page thumbnail image of the user's Advance Direct... |
CeltonMcGrath/TACTIC | src/tactic/ui/widget/scrollbar_wdg.py | Python | epl-1.0 | 4,809 | 0.004367 | ###########################################################
#
# Copyright (c) 2014, Southpaw Technology
# All Rights Reserved
#
# PROPRIETARY INFORMATION. This software is proprietary to
# Southpaw Technology, and is not to be reproduced, transmitted,
# or disclos | ed in any way without written permission.
#
#
#
__all__ = ['ScrollbarWdg', 'TestScrollbarWdg']
from tactic.ui.common import BaseRefreshWdg
from pyasm.web import DivWdg
class TestScrollbarWdg(BaseRefreshWdg):
|
def get_display(my):
top = my.top
top.add_style("width: 600px")
top.add_style("height: 400px")
return top
class ScrollbarWdg(BaseRefreshWdg):
def get_display(my):
top = my.top
top.add_class("spt_scrollbar_top")
content = my.kwargs.get("content")... |
qk4l/Flexget | flexget/plugins/parsers/parser_internal.py | Python | mit | 1,607 | 0.001867 | fr | om __future__ import unicode_literals, division, absolute_import
from builtins import * # noqa pylint: disable=unused-import, redefined-builtin
import logging
import time
| from flexget import plugin
from flexget.event import event
from flexget.utils.log import log_once
from flexget.utils.titles.movie import MovieParser
from flexget.utils.titles.series import SeriesParser
from .parser_common import ParseWarning
log = logging.getLogger('parser_internal')
class ParserInternal(object):
... |
morenopc/edx-platform | common/lib/xmodule/xmodule/modulestore/xml_exporter.py | Python | agpl-3.0 | 10,461 | 0.002868 | """
Methods for exporting course data to XML
"""
import logging
import lxml.etree
from xblock.fields import Scope
from xmodule.contentstore.content import StaticContent
from xmodule.exceptions import NotFoundError
from xmodule.modulestore import Location
from xmodule.modulestore.inheritance import own_metadata
from fs... | ource_dir, target_dir):
"""
Converts a version 0 export format to version 1, and vice versa.
@param source_dir: the directory structure with the course export that should be converted.
The contents of source_dir will not be altered.
@param target_dir: the directory where | the converted export should be written.
@return: the version number of the converted export.
"""
def convert_to_version_1():
""" Convert a version 0 archive to version 0 """
os.mkdir(copy_root)
with open(copy_root / EXPORT_VERSION_FILE, 'w') as f:
f.write('{{"{export_key... |
neerajvashistha/pa-dude | lib/python2.7/site-packages/pptx/action.py | Python | mit | 7,551 | 0 | # encoding: utf-8
"""
Objects related to mouse click and hover actions on a shape or text.
"""
from __future__ import (
absolute_import, division, print_function, unicode_literals
)
from .enum.action import PP_ACTION
from .opc.constants import RELATIONSHIP_TYPE as RT
from .shapes import Subshape
from .util impor... | raise ValueError('no next slide')
return self._slides[next_slide_idx]
eli | f self.action == PP_ACTION.PREVIOUS_SLIDE:
prev_slide_idx = self._slide_index - 1
if prev_slide_idx < 0:
raise ValueError('no previous slide')
return self._slides[prev_slide_idx]
elif self.action == PP_ACTION.NAMED_SLIDE:
rId = self._hlink.rId
... |
zhlooking/LearnPython | helloworld.py | Python | mit | 196 | 0.005102 | print "Hello Python!"
pr | int "Something change to the file"
print "Git is a distributed version control system"
print "Git has mutable index called stage"
print "Git | tracks changes again and again" |
waseem18/oh-mainline | vendor/packages/twisted/twisted/internet/test/test_time.py | Python | agpl-3.0 | 615 | 0 | # Copyright (c) Twisted Matrix Laboratories.
# | See LICENSE for details.
"" | "
Tests for implementations of L{IReactorTime}.
"""
__metaclass__ = type
from twisted.internet.test.reactormixins import ReactorBuilder
class TimeTestsBuilder(ReactorBuilder):
"""
Builder for defining tests relating to L{IReactorTime}.
"""
def test_delayedCallStopsReactor(self):
"""
... |
nirmeshk/oh-mainline | vendor/packages/sphinx/sphinx/directives/code.py | Python | agpl-3.0 | 7,800 | 0.001026 | # -*- coding: utf-8 -*-
"""
sphinx.directives.code
~~~~~~~~~~~~~~~~~~~~~~
:copyright: Copyright 2007-2013 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import sys
import codecs
from docutils import nodes
from docutils.parsers.rst import Directive, directives
from sphin... |
as the threshold for line numbers.
"""
has_content = False
required_arguments = 1
optional_arguments = 0
final_argument_whitespace = False
option_spec = {
'linenothreshold': directives.unchanged,
}
def run(self):
if 'linenothreshold' in self.options:
tr... | linenothreshold = 10
else:
linenothreshold = sys.maxint
return [addnodes.highlightlang(lang=self.arguments[0].strip(),
linenothreshold=linenothreshold)]
class CodeBlock(Directive):
"""
Directive for a code block with special highlight... |
wolverineav/neutron | neutron/tests/common/config_fixtures.py | Python | apache-2.0 | 2,517 | 0 | # Copyright 2015 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 agre... | f.flush()
def dict_to_config_parser(self, config_dict):
config_parser = six.moves.configparser.SafeConfigParser()
for section, section_dict in six.iteritems(config_dict):
if section != 'DEFAULT':
config_parser.add_section(section)
for option, valu... | n_dict):
config_parser.set(section, option, value)
return config_parser
|
testvidya11/ejrf | questionnaire/migrations/0043_auto__del_field_questionnaire_published__del_field_questionnaire_is_op.py | Python | bsd-3-clause | 20,582 | 0.007239 | # -*- coding: 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):
# Deleting field 'Questionnaire.published'
db.delete_column(u'questionnaire_questionnaire', 'published')
... | to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField' | , [], {'unique': 'True', 'max_length': '30'})
},
u'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField',... |
Yelp/git-code-debt | tests/server/servlets/commit_test.py | Python | mit | 741 | 0 | import flask
from testing.asserti | ons.response import assert_no_response_errors
def test_it_loads(server_with_data):
resp = server_with_data.server.client.get(
flask.url_for(
'commit.show',
sha=server_with_data.cloneable_with_commits.commits[3].sha,
),
)
assert_no_response_errors(resp)
import_ro... | t_commit(server_with_data):
resp = server_with_data.server.client.get(
flask.url_for(
'commit.show',
sha=server_with_data.cloneable_with_commits.commits[0].sha,
),
)
assert_no_response_errors(resp)
|
endlessm/chromium-browser | testing/scripts/run_performance_tests.py | Python | bsd-3-clause | 27,620 | 0.008653 | #!/usr/bin/env python
# Copyright 2017 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.
"""Runs telemetry benchmarks and gtest perf tests.
This script attempts to emulate the contract of gtest-style tests
invoked via recip... | ium/chrome_sandbox'
SHARD_MAPS_DIRECTORY = os.path.join(
os.path.dirname(__file__), | '..', '..', 'tools', 'perf', 'core',
'shard_maps')
# See https://crbug.com/923564.
# We want to switch over to using histograms for everything, but converting from
# the format output by gtest perf tests to histograms has introduced several
# problems. So, only perform the conversion on tests that are whitelisted ... |
b-e-p/bep | Bep/run.py | Python | bsd-3-clause | 24,761 | 0.010218 | #! /usr/bin/env python
#----------------------------------------------------------------
# Author: Jason Gors <jasonDOTgorsATgmail>
# Creation Date: 07-30-2013
# Purpose: this is where the program is called into action.
#----------------------------------------------------------------
import argparse
import os
from o... | # want this instead b/c otherwise the above hides the help pages
#additional_args = [] # set back to empty to avoid the flag at the end of argparse stuff
#else:
#error_msg = "An already installed package name must be passed in with {}".format(cmd)
... | #top_parser.error(error_msg)
else:
additional_args = [] # set back to empty to avoid the flag at the end of argparse stuff
if build_up_subparsers:
top_subparser = top_parser.add_subparsers(title='Commands',
description='[ ... |
Phoenyx/TruemaxScriptPackage | Truemax/exportAnimFBX.py | Python | gpl-2.0 | 3,473 | 0.004319 | __author__ = 'sofiaelm'
# version 1.0
"""
"""
from pymel.all import *
import maya.cmds as cmds
# Regex for our scene name structure. Example: genericTurnLeft45A_v013_sm
SCENE_FILE_NAME_REGEX = r'[a-zA-Z]+[0-9]+[A-Z]{1}_v[0-9]{3}_[a-zA-Z]{2}'
# Regex for our top node name structure. Example: genericTurnLeft45A
SCEN... | ut exporting ia not allowed in Python
# It exports the selection as FBX using a preset file. Writes message to command line when finished.
preset_file = "{0}{1}{2}".format(os.path.dirname(os.path.realpath(__file__)), os.path.sep,
"UnityExportAnim.fbxexportpreset"... | /")
mel.eval('FBXLoadExportPresetFile -f "{0}";'.format(preset_file))
mel.eval('FBXExport -f "{0}" -s;'.format(scene_fbx.replace("\\", "/")))
sys.stdout.write(">>>>> FBX with Animation Exported! <<<<<")
|
hankcs/HanLP | hanlp/layers/embeddings/contextual_string_embedding_tf.py | Python | apache-2.0 | 4,988 | 0.002005 | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-12-19 03:24
from typing import List
import tensorflow as tf
import numpy as np
from hanlp.components.rnn_language_model_tf import RNNLanguageModel
from hanlp_common.constant import PAD
from hanlp.utils.io_util import get_resource
from hanlp.utils.tf_util import copy... | ars = tokenizer(word)
chars = chars[:self.max_word_len]
if space:
chars += [' ']
end = start + len(chars)
offsets.append((start, end))
start = end
raw_string += chars
return raw_string, offsets
def get_config(self):
... | {
'forward_model_path': self.forward_model_path,
'backward_model_path': self.backward_model_path,
'max_word_len': self.max_word_len,
}
base_config = super(ContextualStringEmbeddingTF, self).get_config()
return dict(list(base_config.items()) + list(config.items... |
yamitzky/dotfiles | home/.ipython/profile_default/startup/01-function.py | Python | mit | 3,117 | 0 | def ulen(li):
return len(set(li))
def set_style():
import seaborn as sns
sns.set_style("whitegrid")
sns.set_context("poster")
set_japanese_font()
def set_japanese_font():
import matplotlib as __matplotlib
font_path = '/Library/Fonts/Osaka.ttf'
font_prop = __matplotlib.font_manager.Fo... | ed axis.
In other words, ``a[index_array]`` yields a sorted `a`.
See Also
--------
sor | t : Describes sorting algorithms used.
lexsort : Indirect stable sort with multiple keys.
ndarray.sort : Inplace sort.
argpartition : Indirect partial sort.
Notes
-----
See `sort` for notes on the different sorting algorithms.
As of NumPy 1.4.0 `argsort` works with real/complex arrays cont... |
flake123p/ProjectH | Make/PY02_dump_dependent_tree/mod6/list_to_build_script.py | Python | gpl-3.0 | 1,336 | 0.023952 | #!/usr/bin/python
# Usage: list_to_make_var.py <input file (mod list)> <output file 1(build script)> <output file 2(clean script)> <OS>
# argv: argv[0] argv[1] argv[2] argv[3] argv[4]
#
# Include library
#
import os
import sys
def OpenF... | _os = str(sys.argv[4])
if curr_os == 'WIN':
mod_build_file = 'build_mod.bat'
mod_clean_file = 'clean_mod.bat'
else:
mod_build_file = 'build_mod.sh'
mod_clean_file = 'clean_mod.sh'
#
# main
#
if len(sys.argv) != 5:
print("Arguments Number Error. It should be 5.")
sys.exit(1)
finList = OpenFile(str(sys.argv... | List:
each_mod = each_line.strip()
# build files
str = mod_base_path + each_mod + '/' + mod_build_file + '\n'
foutBuildfile.write(str)
# clean files
str = mod_base_path + each_mod + '/' + mod_clean_file + '\n'
foutCleanfile.write(str)
finList.close()
foutBuildfile.close()
foutCleanfile.close() |
RGU5Android/PythonLectureNotes | HomeWork/09-27-14/toggle_bit_at_position.py | Python | gpl-2.0 | 635 | 0.007874 | #!/usr/bin/python
def toggle_bit_at_position(variable, position):
if type(variable) is long or type(variable) is int:
if type(position) is long or type(position) is int:
position = position - 1
value = variable ^ (1 << position)
return ("Variable: " + str(variable) + " ... | b = input("Enter the value for variable and position to be toggled: ")
print (toggle_bit_at_position(a, b)) | ;
|
saeki-masaki/cinder | cinder/openstack/common/report/views/text/process.py | Python | apache-2.0 | 1,233 | 0 | # Copyright 2014 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 t | he 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
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for th... | ocesses in human-readable formm
"""
import cinder.openstack.common.report.views.jinja_view as jv
class ProcessView(jv.JinjaView):
"""A Process View
This view displays process models defined by
:class:`openstack.common.report.models.process.ProcessModel`
"""
VIEW_TEXT = (
"Process {{ pid... |
evangeline97/localwiki-backend-server | localwiki/versionutils/versioning/fields.py | Python | gpl-2.0 | 645 | 0.004651 | from django.db import models
from django.contrib.auth.models import User
class AutoSetField(object):
pass
class AutoUserField(models.ForeignKey, AutoSetField):
def __init__(self, **kws):
if 'to' in kws:
# Fixes south. We always want this to point to the User
# model.
... | on_rules
add_introspection_rules([], ["^versionutils\.versioning\.fields"])
except ImportError:
pass | |
Duoxilian/home-assistant | homeassistant/components/climate/wink.py | Python | mit | 15,904 | 0 | """
Support for Wink thermostats.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/climate.wink/
"""
from homeassistant.components.wink import WinkDevice, DOMAIN
from homeassistant.components.climate import (
STATE_AUTO, STATE_COOL, STATE_HEAT, Climate... | t (
TEMP_CELSIUS, STATE_ON,
STATE_OFF, STATE_UNKNOWN)
DEPENDENCIES = [' | wink']
STATE_AUX = 'aux'
STATE_ECO = 'eco'
STATE_FAN = 'fan'
SPEED_LOWEST = 'lowest'
SPEED_LOW = 'low'
SPEED_MEDIUM = 'medium'
SPEED_HIGH = 'high'
ATTR_EXTERNAL_TEMPERATURE = "external_temperature"
ATTR_SMART_TEMPERATURE = "smart_temperature"
ATTR_ECO_TARGET = "eco_target"
ATTR_OCCUPIED = "occupied"
def setup_platf... |
aikikode/tomboy2evernote | tomboy2evernote/command_line.py | Python | mit | 5,742 | 0.003135 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
from datetime import timedelta, date
import glob
import os
import sys
import pyinotify
from evernote.edam.error.ttypes import EDAMUserException
from tomboy2evernote.tomboy2evernote import Evernote, convert_tomboy_to_evernote
__author__ = 'Denis Kovalev... | self.process_IN_MOVED_TO(event)
def process_IN_DELETE(self, event):
| self.process_IN_MOVED_FROM(event)
def process_IN_MODIFY(self, event):
self.process_IN_MOVED_TO(event)
def process_IN_MOVED_TO(self, event):
# New note / Modify note
tomboy_note = event.pathname
if os.path.isfile(tomboy_note) and os.path.splite... |
absalon-james/usage | usage/meter.py | Python | apache-2.0 | 4,874 | 0 | import datetime
import itertools
import query
import utils
from | exc import InvalidTimeRangeError
from exc import NoSamplesError
from log import logging
from reading import Reading
logger = logging.getLogger('usage.meter')
def _cmp_sample(a, b):
"""Compare two samples.
First compare the resource ids. Compa | re the timestamps if the
resource ids are the same.
:param a: First sample
:param b: Second sample
:return: Result of cmp function.
:rtype: Integer
"""
result = cmp(a.resource_id, b.resource_id)
if result == 0:
result = cmp(a.timestamp, b.timestamp)
return result
class Met... |
Execut3/CTF | IRAN Cert/2016/1- Easy/PPC & Web/project/project/urls.py | Python | gpl-2.0 | 567 | 0.007055 | from django.conf.urls import include, url, patt | erns
from django.contrib import admin
urlpatterns = patterns('',
#url(r'^admin/', include(admin.site.urls)),
url(r'^index$', 'app.views.index'),
url(r'^$', 'app.views.index'),
url(r'^login$', 'app.views.login'),
url(r'^logout$', 'app.views.log_out'),
url(r'^register$', 'app.views.register'),
... | llenge-2', 'challenge_easy_math_50pt.views.index'),
) |
plumdog/myhome | urls.py | Python | mit | 620 | 0 | from urls_base import Urls
from slugify import slugify
from settings import ASSET_TAG
urls = Urls()
urls.add('index', '/')
urls.add('projects', '/projects/')
urls. | add('blog', '/blog/ | ')
urls.add('404.html', '/404.html')
urls.add('post', '/post/{slug}.html',
format_func=lambda **kwargs: dict(slug=slugify(kwargs['post'].title)))
urls.add('tag', '/post/tag/{slug}.html',
format_func=lambda **kwargs: dict(slug=slugify(kwargs['tag'])))
urls.add('static', '/static/{path}?_/{asset_tag}',
... |
magfest/panels | panels/site_sections/attractions_admin.py | Python | agpl-3.0 | 16,616 | 0.001143 | from uber.common import *
from panels.models.attraction import *
from panels.site_sections.attractions import _attendee_for_badge_num
@all_renderable(c.STUFF)
class Root:
@renderable_override(c.STUFF, c.PEOPLE, c.REG_AT_CON)
def index(self, session, filtered=False, message='', **params):
admin_account... | t message:
if not attraction.department_id:
attraction.department_id = None
session.add(attraction)
raise HTTPRedirect(
'form?id={}&message={}',
attraction.id,
'{} updated successfully'.format... | y(Attraction) \
.filter_by(id=attraction_id) \
.options(
subqueryload(Attraction.department),
subqueryload(Attraction.features)
.subqueryload(AttractionFeature.events)
.subqueryload(AttractionEven... |
congminghaoxue/learn_python | xml_rpc/SimpleXMLRPCServer.py | Python | apache-2.0 | 1,576 | 0.003173 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2016-08-15 10:11:05
# @Author : Zhou Bo ([email protected])
# @Link : http://onlyus.online
# @Version : $Id$
try:
from SimpleXMLRPCServer import SimpleXMLRPCServer
from SimpleXMLRPCServer import SimpleXMLRPCRequestHandler
from SocketServer imp... | rver.register_introspection_functions()
# Register pow() function; this will use the value of
# pow.__name__ as the name, which is just 'pow'.
server.register_function(pow)
# add two value
def adder_function(x, y):
'''
add two value
'''
return x + y
server.register_function(adder_function, 'add')
... | # Register an instance; all the methods of the instance are
# published as XML-RPC methods (in this case, just 'mul').
class MyFuncs:
def mul(self, x, y):
return x * y
server.register_instance(MyFuncs())
# Run the server's main loop
server.serve_forever()
|
nirbheek/cerbero | cerbero/packages/wix_packager.py | Python | lgpl-2.1 | 13,420 | 0.000745 | # cerbero - a multi-platform build system for Open Source software
# Copyright (C) 2012 Andoni Morales Alastruey <[email protected]>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free Software Foundation; eit... | _merge_module(output_dir, PackageType.RUNTIME, force,
self.package.version, keep_temp)
paths.append(p)
if devel:
p = self.create_merge_module(output_dir, PackageType.DEVEL, force,
self.package.version, keep_temp)
... | p_temp_dir=False):
self.package.set_mode(package_type)
files_list = self.files_list(package_type, force)
if isinstance(self.package, VSTemplatePackage):
mergemodule = VSMergeModule(self.config, files_list, self.package)
else:
mergemodule = MergeModule(self.config,... |
spvkgn/youtube-dl | youtube_dl/extractor/giga.py | Python | unlicense | 3,820 | 0.002357 | # coding: utf-8
from __future__ import unicode_literals
import itertools
from .common import InfoExtractor
from ..utils import (
qualities,
compat_str,
parse_duration,
parse_iso8601,
str_to_int,
)
class GigaIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?giga\.de/(?:[^/]+/)*(?P<id>[^/]+... | 'url': 'http://www.giga.de/games/channel/giga-top-montag/giga-topmontag-die-besten-serien-2014/',
| 'only_matching': True,
}, {
'url': 'http://www.giga.de/extra/netzkultur/videos/giga-games-tom-mats-robin-werden-eigene-wege-gehen-eine-ankuendigung/',
'only_matching': True,
}, {
'url': 'http://www.giga.de/tv/jonas-liest-spieletitel-eingedeutscht-episode-2/',
'only_matching'... |
giorgiobornia/femus | applications/2021_fall/hdongamm/input/parametric_squre_himali2.py | Python | lgpl-2.1 | 2,834 | 0.016937 | #!/usr/bin/env python
###
### This file is generated automatically by SALOME v9.7.0 with dump python functionality
###
import sys
import salome
salome.salome_init()
import salome_notebook
notebook = salome_notebook.NoteBook()
sys.path.insert(0, r'/home/student/software/femus/applications/2021_fall/hdongamm/input')
... | l_y", 1)
Translation_1 = geompy.MakeTranslation(Face_1, "l_x_half", "l_y_half", 0)
Translation_2 = geompy.MakeTranslation(Face_1, "l_x_half", "l_y_half", 0)
geompy.addToStudy( O, 'O' )
geompy.addToStudy( OX, 'OX' )
geompy.addToStudy | ( OY, 'OY' )
geompy.addToStudy( OZ, 'OZ' )
geompy.addToStudy( O_1, 'O' )
geompy.addToStudy( OX_1, 'OX' )
geompy.addToStudy( OY_1, 'OY' )
geompy.addToStudy( OZ_1, 'OZ' )
geompy.addToStudy( Face_1, 'Face_1' )
geompy.addToStudy( Translation_1, 'Translation_1' )
geompy.addToStudy( Translation_2, 'Translation_2' )
###
### ... |
benfinke/ns_python | nssrc/com/citrix/netscaler/nitro/resource/config/snmp/snmpoid.py | Python | apache-2.0 | 6,179 | 0.036899 | #
# Copyright (c) 2008-2015 Citrix Systems, 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 l... | se SNMP OIDs you want the NetScaler appliance to display.<br/>Possible values = VSERVER, SERVICE, SERVICEGROUP
"""
try :
self._entitytype = entitytype
except Exception as e:
raise e
@property
def name(self) :
ur"""Name of the entity wh | ose SNMP OID you want the NetScaler appliance to display.<br/>Minimum length = 1.
"""
try :
return self._name
except Exception as e:
raise e
@name.setter
def name(self, name) :
ur"""Name of the entity whose SNMP OID you want the NetScaler appliance to display.<br/>Minimum length = 1
"""
try :
... |
AlvarBer/Persimmon | persimmon/view/util/types.py | Python | mit | 673 | 0.002972 | from enum import Enum
from abc import ABCMeta
from kivy.uix.widget import WidgetMetaclass
class AbstractWidget(ABCMeta, WidgetMetaclass):
""" Necessary because python meta | class | es do not support multiple
inheritance. """
pass
class Type(Enum):
ANY = 0.9, 0.9, 0.9
DATAFRAME = .667, .224, .224
CLASSIFICATOR = .667, .424, .224
CROSS_VALIDATOR = .133, .4, .4
STATE = .667, .667, .224
STR = .408, .624, .608
class BlockType(Enum):
IO = .667, .224, .224
CLASS... |
uian/docker-py | docker/unixconn/unixconn.py | Python | apache-2.0 | 2,986 | 0 | # Copyright 2013 dotCloud 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 t... |
self.timeout = timeout
def connect(self):
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.settimeout(self.timeout)
sock.connect(self.base_url.rep | lace("http+unix:/", ""))
self.sock = sock
def _extract_path(self, url):
# remove the base_url entirely..
return url.replace(self.base_url, "")
def request(self, method, url, **kwargs):
url = self._extract_path(self.unix_socket)
super(UnixHTTPConnection, self).request(me... |
pombredanne/or-tools | tools/setup_py3.py | Python | apache-2.0 | 2,291 | 0.014841 | from setuptools import setup, Extension
from os.path import join as pjoin
from os.path import dirname
# Utility function to read the README file.
# Used for the long_description. It's nice, because now 1) we have a top level
# README file and 2) it's easier to type in the README file than to put a raw
# string in bel... | = [dummy_module],
install_requires = [
'protobuf >= 2.8.0'],
package_data = {
'ortools.constraint_solver' : ['_pywrapcp.dll'],
'ortools.linear_solver' : ['_pywraplp.dll'],
'ortools.graph' : ['_pywrapgraph.dll'],
'ortools.algorithms' : ['_pywrapknapsack_solver.dll'],
... | nc',
author_email = '[email protected]',
description = 'Google OR-Tools python libraries and modules',
keywords = ('operations research, constraint programming, ' +
'linear programming,' + 'flow algorithms,' +
'python'),
url = 'https://developers.google.com/optimization/... |
jsbUSMC/django-edge-api | apps/core/renderers.py | Python | mit | 977 | 0 | import json
from rest_framework.renderers import JSONRenderer
class CustomJSONRenderer(JSONRenderer):
charset = 'utf-8'
object_label = 'object'
pagination_object_label = 'objects'
pagination_count_label = 'count'
def render(self, data, media_type=None, renderer_context=None):
if data.get... | ch as the user can't be authenticated
# or something similar), `data` will contain an `errors` key. We want
# the default JSONRenderer to handle rendering errors, so we need to
# check for t | his case.
elif data.get('errors', None) is not None:
return super(CustomJSONRenderer, self).render(data)
return json.dumps({
self.object_label: data
})
|
iwm911/plaso | plaso/lib/timelib_test.py | Python | apache-2.0 | 19,167 | 0.004017 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2012 The Plaso Project Authors.
# Please see the AUTHORS file for details on individual authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the L... | id time string.')
try:
year = int(time_string[0:4], 10)
except ValueError:
raise ValueError(u'Unable to parse year.' | )
try:
month = int(time_string[5:7], 10)
except ValueError:
raise ValueError(u'Unable to parse month.')
if month not in range(1, 13):
raise ValueError(u'Month value out of bounds.')
try:
day_of_month = int(time_string[8:10], 10)
except ValueError:
raise ValueError(u'Unable to parse day ... |
ronnix/fabtools | fabtools/service.py | Python | bsd-2-clause | 3,226 | 0 | """
System services
===============
This module provides low-level tools for managing system services,
using the ``service`` command. It supports both `upstart`_ services
and traditional SysV-style ``/etc/init.d/`` scripts.
.. _upstart: http://upstart.ubuntu.com/
"""
from fabric.api import hide, settings
from fabt... | s.service.is_running('foo'):
fabtools.service.stop('foo')
"""
_service(service, 'stop')
def restart(service):
"""
Restart a service.
::
import fabtools
# Start service, or restart it if it is already running
if fabtools.service.is_running('foo'):
... | e:
fabtools.service.start('foo')
"""
_service(service, 'restart')
def reload(service):
"""
Reload a service.
::
import fabtools
# Reload service
fabtools.service.reload('foo')
.. warning::
The service needs to support the ``reload`` operation.
... |
wonder-sk/QGIS | python/plugins/processing/algs/qgis/ui/FieldsCalculatorDialog.py | Python | gpl-2.0 | 9,650 | 0.000933 | # -*- coding: utf-8 -*-
"""
***************************************************************************
FieldsCalculatorDialog.py
---------------------
Date : October 2013
Copyright : (C) 2013 by Alexander Bruy
Email : alexander dot bruy at gmail dot com
**... | field name length
self.mOutputFieldNameLineEdit.setMaxLength(10)
self.manageGui()
def manageGui(self):
if hasattr(self.leOutputFile, 'setPlaceholderText' | ):
self.leOutputFile.setPlaceholderText(
self.tr('[Save to temporary file]'))
self.mOutputFieldTypeComboBox.blockSignals(True)
for t in self.alg.type_names:
self.mOutputFieldTypeComboBox.addItem(t)
self.mOutputFieldTypeComboBox.blockSignals(False)
... |
Just-D/chromium-1 | tools/telemetry/telemetry/decorators_unittest.py | Python | bsd-3-clause | 5,452 | 0.005869 | # Copyright 2014 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.
import unittest
from telemetry import decorators
from telemetry.core import util
util.AddDirToPythonPath(util.GetTelemetryDir(), 'third_party', 'mock')
imp... | , possible_browser)[0])
test.SetDisabledStrings(['os_version_name'])
| self.assertTrue(decorators.ShouldSkip(test, possible_browser)[0])
test.SetDisabledStrings(['os_name', 'another_os_name'])
self.assertTrue(decorators.ShouldSkip(test, possible_browser)[0])
test.SetDisabledStrings(['another_os_name', 'os_name'])
self.assertTrue(decorators.ShouldSkip(test, possible_bro... |
petrjasek/superdesk-server | superdesk/__init__.py | Python | agpl-3.0 | 3,012 | 0.001992 | # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
"""Superdesk... | int)
def get_backend():
"""Returns the available backend, this will be changed in a factory if needed."""
return eve_backend
def get_resource_service(resource_name):
return resources[resource_name].service
def get_resource_privileges(resource_name):
attr = getattr(resources[resource_name], 'privil... | r_preferences[preference_name] = preference
def register_default_session_preference(preference_name, preference):
default_session_preferences[preference_name] = preference
from .commands import * # noqa
|
joshzarrabi/e-mission-server | emission/clients/data/data.py | Python | bsd-3-clause | 4,698 | 0.020647 | # Standard imports
import logging
import time as systime
from datetime import datetime, time, timedelta
import json
# Our imports
import emission.analysis.result.carbon as carbon
import emission.net.api.stats as stats
from emission.core.wrapper.user import User
# BEGIN: Code to get and set client specific fields in t... | uld potentially slow down user response time
msNow = systime.time()
stats.storeResultEntry(user_uuid, stats.STAT_MY_CARBON_FOOTPRINT, msNow, getCategorySum(myModeCarbonFootprint))
stats.storeResultEntry(user_uuid, stats.STAT_MY_CARBON_FOOTPRINT_NO_AIR, msNow, getCategorySum(myModeCarbonFootprintNoLongMotorized))
... | PTIMAL_FOOTPRINT_NO_AIR, msNow, getCategorySum(myOptimalCarbonFootprintNoLongMotorized))
stats.storeResultEntry(user_uuid, stats.STAT_MY_ALLDRIVE_FOOTPRINT, msNow, getCategorySum(myModeShareDistance) * (278.0/(1609 * 1000)))
stats.storeResultEntry(user_uuid, stats.STAT_MEAN_FOOTPRINT, msNow, getCategorySum(avgModeC... |
J1bz/ecoloscore | coffeecups/urls.py | Python | bsd-3-clause | 406 | 0 | # -*- coding: utf-8 -*-
from | django.conf.urls import url, patterns, include
from rest_framework.routers import DefaultRouter
from coffeecups.views import TakeView, ThrowView, C | upPolicyView
router = DefaultRouter()
router.register(r'takes', TakeView)
router.register(r'throws', ThrowView)
router.register(r'policies', CupPolicyView)
urlpatterns = patterns(
'',
url(r'^', include(router.urls)),
)
|
otron/zenodo | zenodo/modules/deposit/tasklets/__init__.py | Python | gpl-3.0 | 922 | 0.017354 | # -*- coding: utf-8 -*-
#
## This file is part of Zenodo.
## Copyright (C) 2012, 2013 CERN.
##
## Zenodo 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... | will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with Zenodo. If not, see <http://www.gnu.org... | granted to it by virtue of its status as an Intergovernmental Organization
## or submit itself to any jurisdiction. |
zwChan/VATEC | ~/eb-virt/Lib/site-packages/pip/index.py | Python | apache-2.0 | 37,235 | 0.000027 | """Routines related to PyPI, indexes"""
from __future__ import absolute_import
import logging
import cgi
from collections import namedtuple
import itertools
import sys
import os
import re
import mimetypes
import posixpath
import warnings
from pip._vendor.six.moves.urllib import parse as urllib_parse
from pip._vendor.... | PackageFinder']
SECURE_ORIGINS = [
# protocol, hostname, port
# Taken from Chr | ome's list of secure origins (See: http://bit.ly/1qrySKC)
("https", "*", "*"),
("*", "localhost", "*"),
("*", "127.0.0.0/8", "*"),
("*", "::1/128", "*"),
("file", "*", None),
# ssh is always secure.
("ssh", "*", "*"),
]
logger = logging.getLogger(__name__)
class InstallationCandidate(obj... |
theshammy/GenAn | src/main/common.py | Python | mit | 1,218 | 0 | class GeneratorAdapter:
def visit_selector_view(self, view):
pass
def visit_selector_object(self, object, property):
pass
def visit_selector_fk_object(self, object, property, fk_properties):
pass
def visit_view(self, view):
pass
def visit_page(self, page):
... | lf.model = model
self.builtins = builtins
self.path = path
self.base_url = "http://localhost:8080/"
class BColors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = | '\033[4m'
|
shifvb/hash_photos | _tools/get_hash.py | Python | apache-2.0 | 605 | 0 | import hashlib
def | get_hash(instance, abs_filename: str):
"""
得到特定文件十六进制哈希值
:param instance:
:param abs_filename: 文件绝对路径
:return: 十六进制哈希值字符串
"""
_value = instance.choose_hash_method_var.get()
m = None
if _value == 0:
m = hashlib.md5()
elif _value == 1:
m = hashlib.sha1()
elif _... | m = hashlib.sha512()
with open(abs_filename, 'rb') as f:
for data in f:
m.update(data)
return m.hexdigest()
|
kreatorkodi/repository.torrentbr | plugin.video.yatp/site-packages/hachoir_parser/video/__init__.py | Python | gpl-2.0 | 324 | 0.003086 | from hachoir_par | ser.video.asf import AsfFile
from hachoir_parser.video.flv import FlvFile
from hachoir_parser.video.mov import MovFile
from hachoir_parser.video.mpeg_video import MPEGVideoFile
from hachoir_parser.video.mpeg_ts import MPEG_TS
from hachoir_parser.video.avchd import AVCHDINDX, AVCHDMOBJ, AVCHDMPLS, AVC | HDCLPI
|
shearichard/membaman | membaman/fees/migrations/0005_auto_20150320_2255.py | Python | gpl-3.0 | 2,159 | 0.003242 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('members', '0012_auto_20150318_2331'),
('fees', '0004_auto_20150312_1747'),
]
operations = [
migrations.CreateModel(
... | ('date', models.DateField()),
],
options={
},
bases=(models.Model, | ),
),
migrations.CreateModel(
name='AccountDebt',
fields=[
('accountentry_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='fees.AccountEntry')),
('invoice_reference', models.CharField(max_length... |
validata/ExaminationChat | Server/Controller/Server_threading.py | Python | mit | 1,049 | 0.000953 | import threading
class Server_recv(threading.Thread):
def __init__(self, client_sock_, list_of_sockets_):
threading.Thread.__init__(self)
self.client_sock = client_sock_
self.list_of_sockets = list_of_sockets | _
def run(self):
while True:
msg_from_client = self.client_sock.recv(1024).decode()
if msg_from_client == "/quit":
self.client_sock.close()
self.list_of_sockets.remove(self.client_sock)
return
print("Message from client: ... | ient)
for sock in self.list_of_sockets:
sock.send(msg_from_client.encode())
class Server_send(threading.Thread):
def __init__(self, client_sock_, list_of_sockets_):
threading.Thread.__init__(self)
self.client_sock = client_sock_
self.list_of_sockets = list_of_so... |
bdusell/pycfg | demos/cnf_html_test.py | Python | mit | 318 | 0.003145 | '''Convert a grammar to CNF form | and print it to stdout in HTML.'''
from cfg import core, cnf
CFG = core.ContextFreeGrammar
CNF = cnf.ChomskyNormalForm
G = CFG('''
S -> ASA | aB
A -> B | S
B -> b |
''')
print '<h1><var>G</var>:</h1>'
print G.html()
print
print '<h1><var>G′ | </var>:</h1>'
print CNF(G).html()
|
obi-two/Rebelion | data/scripts/templates/object/installation/manufacture/shared_weapon_factory.py | Python | mit | 465 | 0.045161 | #### NOTICE: THIS FILE IS AUTO | GENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Installation()
result.template = "object/installation/manufacture/shared_weapon_factory.iff"
result.attribute_template_id = -1
result.stfName(... | |
SUSE/azure-sdk-for-python | azure-mgmt-resource/azure/mgmt/resource/policy/v2016_04_01/models/policy_assignment.py | Python | mit | 1,773 | 0.001128 | # 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 display_name: str
:param policy_definition_id: The ID of the policy definition.
:type policy_definition_id: str
:param scope: The scope for the policy assignment.
:type scope: str
:param id: The ID of the policy assignment.
:type id: str
:param type: The type of the policy assignment.... | e name: str
"""
_attribute_map = {
'display_name': {'key': 'properties.displayName', 'type': 'str'},
'policy_definition_id': {'key': 'properties.policyDefinitionId', 'type': 'str'},
'scope': {'key': 'properties.scope', 'type': 'str'},
'id': {'key': 'id', 'type': 'str'},
... |
ahmadpgh/deepSimDEF | deepSimDEF_for_gene_expression.py | Python | mit | 24,970 | 0.009491 | # CUDA_VISIBLE_DEVICES=gpu-number python deepSimDEF_for_gene_expression.py arguments
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # or any {'0', '1', '2'}
import sys
import logging
import random
import numpy as np
import pprint
import argparse
import tensorflow.keras
import tensorflow as tf
tf.compat.v1.logging... | networks import deepSimDEF_network
from datasets import gene_expression_dataset, generic_production_dataset
from dataloaders import generic_dataloader, generic_production_dataloader
from scipy.stats.stats import pearsonr, spearmanr
import datetime
from pytz import timezone
import collections
from utils import *
tz ... | one('US/Eastern') # To monitor training time (showing start & end points of a fixed timezone when the code runs on a remote server)
pp = pprint.PrettyPrinter(indent=4)
#checkpoint = '[base_dir]/2020.03.04-23h40m37s_server_name/model_checkpoints/epoch_58'
checkpoint = None
parser = argparse.ArgumentParser(description... |
obi-two/Rebelion | data/scripts/templates/object/tangible/medicine/shared_stimpack_sm_s1.py | Python | mit | 454 | 0.046256 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/medicine/shared_stimpack_sm_s1.iff"
result.attribute_template_id = ... | #### BEGIN MODIFICATIONS ####
#### E | ND MODIFICATIONS ####
return result |
luftdanmark/fifo.li | config/urls.py | Python | mit | 1,716 | 0.004662 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.views.generic import TemplateView
from django.views import defaults as default_views
urlpat... | ', default_views.permission_denied, kwargs={'exception': Exception('Permission | Denied')}),
url(r'^404/$', default_views.page_not_found, kwargs={'exception': Exception('Page not Found')}),
url(r'^500/$', default_views.server_error),
]
admin.site.site_header = 'fifo.li admin site'
admin.site.site_title = 'fifo.li staff '
|
molgor/spystats | HEC_runs/fit_fia_sppn.py | Python | bsd-2-clause | 4,595 | 0.019808 | #!/usr/bin/env python
#-*- coding: utf-8 -*-
"""
Automatic Batch processing for GP models
========================================
Requires:
* TensorFlow
* GPFlow
* Pandas
* GeoPandas
* Numpy
* shapely
"""
__author__ = "Juan Escamilla Mólgora"
__copyright__ = "Copyright 2017, JEM"
__lic... | the size of the grid partitioning.
* GPFlowModel : a GpFlow regressor object (the model that predicts).
"""
Nn = num_of_predicted_coordinates
dsc = inputGeoDataFrame
longitudes = dsc.apply(lambda c : c.geometry.x, axis=1)
latitudes = dsc.apply(lambda c : c.geometry.y, axis=1)
predicted_... | s),max(latitudes),Nn)
Xx, Yy = np.meshgrid(predicted_x,predicted_y)
predicted_coordinates = np.vstack([ Xx.ravel(), Yy.ravel()]).transpose()
#predicted_coordinate
means,variances = GPFlowModel.predict_y(predicted_coordinates)
results = pd.DataFrame([means,variances,longitudes,latitudes])
return... |
linuxwhatelse/plugin.audio.linuxwhatelse.gmusic | addon/routes/files.py | Python | gpl-3.0 | 1,076 | 0 | import mapper
from addon.routes import my_library
from addon.routes import actions
from addon.routes import generic
MPR = mapper.Mapper.get()
@MPR.s_url('/track/<track_id>/')
@MPR.s_u | rl('/track/<track_id>/<title>/')
def track(track_id, title=''):
actions.play_track(track_id, track_title=title)
@MPR.s_url('/artist/<artist_id>/')
def artist(artist_id):
generic.artist_top_trac | ks(artist_id)
@MPR.s_url('/album/<album_id>/')
def album(album_id):
generic.album(album_id)
@MPR.s_url('/playlist/')
def playlist(playlist_id=None, playlist_token=None):
if playlist_id:
my_library.my_library_playlist(playlist_id)
elif playlist_token:
generic.listen_now_shared_playlist(p... |
nguenanhvu/bioinformatics | rosalind_reversecomplement.py | Python | mit | 1,528 | 0.007199 | #rosalind_reversecomplement
#Objective: produce a DNA complementary stra | nd
'''The question is why we've gotta to reverse?
Note that DNA reading invention is starting from 5-end to 3-end direction.
Only producing the complementary sequence without reversing will result in
a 3-end to 5-end sequence => we would be reading the result in the wrong direction
'''
import os
os.chdir('/home/vu/D... | open('rosalind_revc (1).txt', 'r').read()[:-1]
s = ''.join(d[i] for i in f) #3-end to 5-end complementary sequence
s = s[::-1] #reverse the complementary sequence
print s
'''Result
AGCAATTCGTTCCGCCGTAGGAGAATGTTAAATTGTTCCCACGCGGGCCTC
TTACCCTGGGCTATTCCAAGCGCGATACCGTGAGTATCGAAGTCAATTAAT
CCCCCCCGCTTATGCTGATACATCTCTCCGATA... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.