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
mlperf/training_results_v0.7
Google/benchmarks/gnmt/implementations/gnmt-research-TF-tpu-v4-16/utils/nmt_utils.py
Python
apache-2.0
1,514
0.007926
# Copyright 2017 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 by applicable law or agreed to in writing, software # distributed under the License is distribut
ed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Utility functions specifically fo...
STLInspector/STLInspector
STLInspector/core/temporallogic/next.py
Python
apache-2.0
4,414
0.004078
from clause import * class NEXT(Clause): """ This class represents the temporal logic operation 'next'. The class can be used for both STL and LTL Next-operators. When it is used for LTL the interval bound is simply set to None. Attributes: operand (Clause) : Operand o...
y in self.operand1.lro()] @remove_duplicates def tro(self): from _finally import FINALLY from globally import GLOBALLY return [FINALLY(self.operand1, self.lower_bound, self.lower_bound), GLOBALLY(self.operand1, self.lower_bound, self.lower_bound)] \ ...
+ [NEXT(y, self.lower_bound) for y in self.operand1.tro()] @remove_duplicates def io(self): return [NEXT(self.operand1, self.lower_bound + 1)] \ + [NEXT(self.operand1, self.lower_bound - 1) for fake_iterator in [1] if not self.lower_bound == 0] \ + [NEXT(y, self.low...
red-hood/calendarserver
txdav/common/datastore/upgrade/sql/upgrades/addressbook_upgrade_from_1_to_2.py
Python
apache-2.0
3,445
0.002903
# -*- test-case-name: txdav.common.datastore.upgrade.sql.test -*- # # # Copyright (c) 2011-2015 Apple 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....
ributed on an "AS I
S" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # from twext.enterprise.dal.syntax import Update from twisted.internet.defer import inlineCallbacks from txdav.base.propertysto...
ApocalypticOctopus/automaticat
msbuild.py
Python
gpl-2.0
345
0.005797
''' Created on Oct 29, 2015 @author: Apocalyptic Oct
opus ''' from subprocess import Popen, PIPE ms
build_path = "C:\\Program Files (x86)\\MSBuild\\14.0\\Bin\\amd64\\MSBuild.exe" def build(path): cmd = '"' + msbuild_path + '" "' + path + '"' print(cmd) p = Popen(cmd, stdout=PIPE, stderr=PIPE) stdout, stderr = p.communicate()
SALib/SALib
src/SALib/analyze/morris.py
Python
mit
16,738
0.00006
from typing import Dict, List import numpy as np from scipy.stats import norm from . import common_args from ..util import (read_param_file, compute_groups_matrix, ResultDict, _define_problem_with_groups, _compute_delta, _check_groups) def analyze(problem: Dict, X: np.ndarray, Y: np.ndarray, ...
or the groups of parameter values """ groups = np.array(groups, dtype=bool) mu_star_masked = np.ma.masked_array(u
ngrouped_metric * groups.T, mask=(groups ^ 1).T) mean_of_mu_star = np.ma.mean(mu_star_masked, axis=1) return mean_of_mu_star def _reorganize_output_matrix(output_array: np.ndarray, value_increased: np.ndarray, ...
DavidMikeSimon/bolero
plottimes.py
Python
gpl-3.0
1,597
0.035066
#!/usr/bin/python import sys, numpy, pylab, matplotlib, re pat = re.compile(r"[^-]+-[^-]+-(\S+)") # First pass
: Figure out the minimum and maximum values vmin, vmax = -1, -1 for name in sys.argv[1:]: match = pat.match(name) if match: fh = open(name) vals = [] for line in fh: vals.append(int(line.strip())/1000.0) if vmin == -1: vmin = numpy.min(vals) else: v
min = min(numpy.min(vals), vmin) if vmax == -1: vmax = numpy.max(vals) else: vmax = max(numpy.max(vals), vmax) fh.close() binwidth = (vmax-vmin)/200.0 # Second pass: Generate the plots fig = pylab.figure(facecolor = "white") a1rect = (0.09, 0.08, 0.67, 0.85) a2rect = (0.82, 0.08, 0.16, 0.85) lines = ...
schollz/extract_recipe
get_recipes/downloadRecipes.py
Python
apache-2.0
3,312
0.023249
import json import os import urllib2 import urllib import html2text from unidecode import unidecode import time import urllib import logging import os import os.path import sys import threading if os.path.isfile('recipeitems-latest.json'): pass else: os.system('wget http://openrecipes.s3.amazo...
tr(start)+"_"+str(increment),'rU').read()
''' h = html2text.HTML2Text() h.ignore_links = True h.ignore_images = True h.body_width = 10000 data = h.handle(unidecode(unicode(data,errors='ignore'))) return unidecode(data) def worker(start,increment): logger = logging.getLogger('worker'+str(start)+"_"+str(increment)) """threa...
stormi/tsunami
src/secondaires/navigation/commandes/matelot/renommer.py
Python
bsd-3-clause
3,241
0.00031
# -*-coding:Utf-8 -* # Copyright (c) 2013 LE GOFF Vincent # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # lis...
LL THE COPYRIGHT OWNER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED T
O, PROCUREMENT # OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # ...
rflynn/sqlacodegen
sqlacodegen/main.py
Python
mit
2,382
0.007137
""" """ from __future__ import unicode_literals, division, print_function, absolute_import import argparse import codecs import sys from sqlalchemy.engine import create_engine from sqlalchemy.schema import MetaData from sqlacodegen.codegen import CodeGenerator import sqlacodegen def main(): parser = argparse.Ar...
help='ignore indexes') parser.add_argument('--noconstraints', action='store_true', help='ig
nore constraints') parser.add_argument('--nojoined', action='store_true', help="don't autodetect joined table inheritance") parser.add_argument('--noinflect', action='store_true', help="don't try to convert tables names to singular form") parser.add_argument('--noclasses', action='store_true', help="don't g...
rspeer/solvertools
scripts/build_search_index.py
Python
mit
3,318
0.000904
from solvertools.wordlist import WORDS from solvertools.normalize import slugify, sanitize from solvertools.util import data_path, corpus_path from whoosh.fields import Schema, ID, TEXT, KEYWORD, NUMERIC from whoosh.analysis import StandardAnalyzer from whoosh.index import create_in import nltk import os from tqdm impo...
pen(data_path('corpora/wikipedia.txt')), desc='wikipedia'): title, summary = line.split('\t', 1) summary = summary.rstrip() if title and summary: slug = slugify(title) writer
.add_document( slug=slug, text=title, definition=summary, length=len(slug) ) # Add lookups from a phrase to a word in that phrase for slug, freq, text in tqdm(WORDS.iter_all_by_freq(), desc='phrases'): words = text.split() ...
org-arl/dronesim
dronesim.py
Python
bsd-3-clause
6,968
0.014351
############################################################################### # # Drone Simulator # # Copyright (c) 2017, Mandar Chitre # # This file is part of dronesim which is released under Simplified BSD License. # See file LICENSE or go to http://www.opensource.org/licenses/BSD-3-Clause # for full license detai...
.thrust1 * up) torque = torque + _vp.cross(tpos2, self.thrust2 * up) torque = torque + _vp.cross(tpos3, self.thrust3 * up) torque = torque + _vp.cross(tpos4, self.thrust4 * up) torque = torque - _rot_drag_coef * self.pqr_dot aa = torque/self.inertia if _vp.mag(aa) > 0: ...
aai, aaj, aak = _euler.axangle2euler((aa.x, aa.y, aa.z), _vp.mag(aa)) aa = _vp.vector(aai, aaj, aak) self.pqr_dot = self.pqr_dot + aa * dt else: self.pqr_dot = _vp.vector(0,0,0) # ground interaction if self.xyz.y <= 0: self.xyz.y = 0 ...
Mikhus/wsgikit
setup.py
Python
mit
1,542
0.049287
from distutils.core import setup from distutils.extension import Extension from Cython.Build import cythonize import re module_src = "wsgikit/wsgikit.pyx" def version(): fp = open( module_src) version = re.search( "^__version__\s*=\s*['\"]([^'\"]*)['\"]", fp.read(), re.M).group(1) fp.close() return version __ver...
ntation, file upload handling, HTTP requests s
ecurity, etc. """ )
SpaceGroupUCL/qgisSpaceSyntaxToolkit
esstoolkit/external/networkx/algorithms/tests/test_link_prediction.py
Python
gpl-3.0
18,091
0.000884
import math from functools import partial import pytest import networkx as nx def _test_func(G, ebunch, expected, predict_func, **kwargs): result = predict_func(G, ebunch, **kwargs) exp_dict = {tuple(sorted([u, v])): score for u, v, score in expected} res_dict = {tuple(sorted([u, v])): score for u, v, s...
ty"] = 0 self.test(G, [(1, 2)], [(1, 2, 2)]) def test_notimplemented(self): G = nx.DiGraph([(0, 1), (1, 2)]) G.add
_nodes_from([0, 1, 2], community=0) assert pytest.raises(nx.NetworkXNotImplemented, self.func, G, [(0, 2)]) G = nx.MultiGraph([(0, 1), (1, 2)]) G.add_nodes_from([0, 1, 2], community=0) assert pytest.raises(nx.NetworkXNotImplemented, self.func, G, [(0, 2)]) G = nx.MultiDiGraph([(0...
LICEF/edx-platform
cms/djangoapps/contentstore/management/commands/course_id_clash.py
Python
agpl-3.0
2,127
0.003761
""" Script for finding all courses whose org/name pairs == other courses when ignoring case """ from django.core.management.base import BaseCommand from xmodule.modulestore.django import modulestore from xmodule.modulestore import ModuleStoreEnum # # To run from command line: ./manage.py cms --settings dev course_id_...
}, query={'_id.category': 'course'}, finalize=finalize ) results = results.get('results') for entry in results: if entry.get('value') is not None: print '{:-^40}'.format
(entry.get('_id')) for course_id in entry.get('value').get('target'): print ' {}/{}/{}'.format(course_id.get('org'), course_id.get('course'), course_id.get('name'))
andrew-lundgren/gwpy
gwpy/plotter/axes.py
Python
gpl-3.0
7,620
0.000262
# -*- coding: utf-8 -*- # Copyright (C) Duncan Macleod (2013) # # This file is part of GWpy. # # GWpy 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 ...
to_refresh def ylabel(self): self.set_ylabel("") # ----------------------------------------------- # limit properties @property def xlim(self): """Limits for the x-axis :type: `tuple` """ return self.get_xlim() @xlim.setter @auto_refr
esh def xlim(self, limits): self.set_xlim(*limits) @xlim.deleter @auto_refresh def xlim(self): self.relim() self.autoscale_view(scalex=True, scaley=False) @property def ylim(self): """Limits for the y-axis :type: `tuple` """ return self....
zrhans/python
exemplos/Examples.lnk/bokeh/plotting/file/bollinger.py
Python
gpl-2.0
567
0
import numpy as np from bokeh.plotting import * #
Define Bollinger Bands. upperband = np.random.random_integers(100, 150, size=100) lowerband = upperband - 100 x_data = np.arange(1, 101) # Bollinger shading glyph: band_x = np.append(x_data, x_data[::-1]) band_y = np.append(lowerband, upperband[::-1]) output_file('bollinger.html', title='Bollinger bands (file)') p =...
ill_alpha=0.2) p.title = 'Bollinger Bands' p.plot_height = 600 p.plot_width = 800 p.grid.grid_line_alpha = 0.4 show(p)
phrocker/accumulo
test/system/auto/simple/nativeMap.py
Python
apache-2.0
1,323
0.003779
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work
for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use 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...
red by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import...
lihui7115/ChromiumGStreamerBackend
tools/telemetry/telemetry/internal/platform/power_monitor/powermetrics_power_monitor_unittest.py
Python
bsd-3-clause
3,002
0.007328
# 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 logging import os import unittest from telemetry.core import os_version from telemetry.core import util from telemetry import decorators from telemet...
l.platform.power_monitor import powermetrics_power_monitor def _parsePowerMetricsDataFromTestFile(output_file): test_data_path = os.path.join(util.GetUnittestDataDir(), output_file) with open(test_data_path, 'r') as f
: process_output = f.read() return (powermetrics_power_monitor.PowerMetricsPowerMonitor. ParsePowerMetricsOutput(process_output)) class PowerMetricsPowerMonitorTest(unittest.TestCase): @decorators.Enabled('mac') def testCanMonitorPowerUsage(self): backend = mac_platform_backend.MacPlatformBackend(...
glaudsonml/kurgan-ai
libs/WebServer.py
Python
apache-2.0
3,716
0.016954
''' Kurgan AI Web Application Security Analyzer. http://www.kurgan.com.br/ Author: Glaudson Ocampos - <glaudson@vortexai.com.br> Created in May, 11th 2016. ''' import db.db as db import config as cf class WebServer(object): banner = None os = None server = None framework = None version = None ...
ian","Fedora","Windows","SuSE","marrakesh","RedHat","Unix"} for i in
os_possibles: if i in self.banner: self.os = i break def check_server(self): #server_possibles = {"nginx", "Apache", "Tomcat", "JBoss", "IIS", "X-Varnish"} mydb = db.DB(); query = "SELECT DISTINCT name FROM server" database = cf.D...
Alberto-Beralix/Beralix
i386-squashfs-root/usr/share/pyshared/libxml2.py
Python
gpl-3.0
341,257
0.004542
import libxml2mod import types import sys # The root of all libxml2 errors. class libxmlError(Exception): pass # # id() is sometimes negative ... # def pos_id(o): i = id(o) if (i < 0): return (sys.maxint - i) return i # # Errors raised by the wrappers when some tree handling failed. # class treeE...
if type(_obj) == type(''): print "write io from a string" self.o = None elif type(_obj) == types.InstanceType: print "write io from instance of %s" % (_obj.__class__) ioWrapper.__init__(self, _obj) self._o = libxml2mod.xmlCreateOutputBuffer(self, en...
if file != None: ioWrapper.__init__(self, file) else: ioWrapper.__init__(self, _obj) self._o = _obj def __del__(self): # print "__del__" self.io_close() if self._o != None: libxml2mod.xmlOutputBufferClose(self._o) ...
stackdump/txbitwrap
txbitwrap/test/__init__.py
Python
mit
2,474
0.002425
""" run tests against a webserver running in the same reactor NOTE: this test uses port 8888 on localhost """ import os import ujson as json import cyclone.httpclient from twisted.internet import defer from twisted.application import internet from twisted.trial.unittest import TestCase from twisted.python import log ...
(url, postdata=data) @staticmethod def broadcast(**event): """ rpc client """ resource = 'broadcast/%s/%s' % (event['schema'], event['id']) url = ApiTest.url(resource) data = json.dumps(event) return cyclone.httpclient
.fetch(url, postdata=data)
tuanvu216/udacity-course
designing-restful-apis/Lesson_3/06_Adding Features to your Mashup/Starter Code/findARestaurant.py
Python
mit
3,690
0.01084
# -*- coding: utf-8 -*- import json import httplib2 import sys import codecs sys.stdout = codecs.getwriter('utf8')(sys.stdout) sys.stderr = codecs.getwriter('utf8')(sys.stderr) foursquare_client_id = 'SMQNYZFVCIOYIRAIXND2D5SYBLQUOPDB4HZTV13TT22AGACD' foursquare_client_secret = 'IHBS4VBHYWJL53NLIY2HSVI5A1144GJ3MDTYYY1...
Info['image'] return restaurantInfo else: #print "No Restaurants Found for %s" % l
ocation return "No Restaurants Found" if __name__ == '__main__': findARestaurant("Pizza", "Tokyo, Japan") findARestaurant("Tacos", "Jakarta, Indonesia") findARestaurant("Tapas", "Maputo, Mozambique") findARestaurant("Falafel", "Cairo, Egypt") findARestaurant("Spaghetti", "New Delhi, Ind...
daniel-j/lutris
lutris/sysoptions.py
Python
gpl-3.0
12,134
0.000165
"""Options list for system config.""" import os from collections import OrderedDict from lutris import runners from lutris.util import display, system def get_optirun_choices(): """Return menu choices (label, value) for Optimus""" choices = [("Off", "off")] if system.find_executable("primusrun"): ...
minal's command or path." "Note: Not all terminal emulators are guaranteed to work." ), }, { "option": "env", "type": "mapping", "label": "Environment variables", "help": "Environment variables loaded at run time", }, { "option": "prefix_comman...
e": "string", "label": "Command prefix", "advanced": True, "help": ( "Command line instructions to add in front of the game's " "execution command." ), }, { "option": "manual_command", "type": "file", "label": "Manual command", ...
obulpathi/poppy
poppy/transport/validators/schemas/flavor.py
Python
apache-2.0
2,741
0
# Copyright (c) 2014 Rackspace, 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 wr...
ue }, "rel": { "type": "string", "enum": ["provider_url"], "required": True
} } }, "minItems": 1 } } }, "minItems": 1 ...
Architektor/PySnip
venv/lib/python2.7/site-packages/twisted/internet/test/test_iocp.py
Python
gpl-3.0
5,182
0.002316
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Tests for L{twisted.internet.iocpreactor}. """ import errno from array import array from struct import pack from socket import AF_INET6, AF_INET, SOCK_STREAM, SOL_SOCKET, error, socket from zope.interface.verify import verifyClass from twis...
preactor.reactor import IOCPReactor, EVENTS_PER_LOOP, KEY_NORMAL from twisted.internet.iocpreactor.interfaces import IReadWriteHandle from twisted.internet.iocpreactor.c
onst import SO_UPDATE_ACCEPT_CONTEXT from twisted.internet.iocpreactor.abstract import FileHandle except ImportError: skip = 'This test only applies to IOCPReactor' try: socket(AF_INET6, SOCK_STREAM).close() except error, e: ipv6Skip = str(e) else: ipv6Skip = None class SupportTests(unittest.TestC...
mlflow/mlflow
examples/hyperparam/search_hyperopt.py
Python
apache-2.0
6,367
0.002984
""" Example of hyperparameter search in MLflow using Hyperopt. The run method will instantiate and run Hyperopt optimizer. Each parameter configuration is evaluated in a new MLflow run invoking main entry point with selected parameters. The runs are evaluated based on validation set loss. Test set score is calculated...
1e-1), hp.uniform("momentum", 0.0, 1.0), ] with mlflow.start_run() as run: experiment_id = run.info.experiment_id # Evaluate null model first. train_null_loss, valid_null_loss, test_null_loss = new_eval( 0, experiment_
id, _inf, _inf, _inf, True )(params=[0, 0]) best = fmin( fn=new_eval(epochs, experiment_id, train_null_loss, valid_null_loss, test_null_loss), space=space, algo=tpe.suggest if algo == "tpe.suggest" else rand.suggest, max_evals=max_runs, ) m...
wanghongjuan/crosswalk-test-suite
apptools/apptools-android-tests/apptools/manifest_multiple_icons.py
Python
bsd-3-clause
7,176
0.002508
#!/usr/bin/env python # # Copyright (c) 2015 Intel Corporation. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of works must retain the original copyright notice, this # list of conditions and t...
self.assertEquals(buildstatus, 0) def test_icon_change_any_size(self): comm.setUp() comm.create(self) os.chdir('org.xwalk.test') jsonfile = open(comm.ConstPath + "/../tools/org.xwalk.test/app/manifest.json", "r") jsons = jsonfile.read() jsonfile.close() ...
ct["icons"][0]["sizes"] = "any" json.dump(jsonDict, open(comm.ConstPath + "/../tools/org.xwalk.test/app/manifest.json", "w")) buildcmd = comm.HOST_PREFIX + comm.PackTools + "crosswalk-app build" buildstatus = os.system(buildcmd) comm.run(self) comm.clear("org.xwalk.test") ...
chyla/pat-lms
web/slas-web/web/views.py
Python
mit
912
0.004386
# -*- coding: utf-8 -*- from django.shortcuts import render_to_response, render, redirect from django.http import HttpResponseRedirect from django.contrib import auth from django.contrib.auth import authenticate, login, logout def user_login(request): return render(request, 'user/login.html', ...
: login(request, user) return HttpResponseRedirect("/") else: return HttpResponseRedirect("/user/invalid_login") def user_logout(request): logout(request) return HttpResponseRedirect("
/user/login") def user_invalid_login(request): return render(request, 'user/invalid_login.html', {})
robhudson/zamboni
apps/zadmin/tests/test_views.py
Python
bsd-3-clause
87,057
0.000138
# -*- coding: utf-8 -*- import csv import json from cStringIO import StringIO from datetime import datetime from django.conf import settings from django.core import mail, management from django.core.cache import cache import mock from nose.plugins.attrib import attr from nose.tools import eq_ from piston.models impor...
01-01', 'description': 'bar', }
response = self.client.post(url, modified_event, follow=True) eq_(response.status_code, 200) events = response.context['events'] eq_(events[0].description, 'bar') def test_delete(self): url = reverse('zadmin.site_events.delete', args=[1]) response = self.client.get(url, fo...
totoro72/pt1
ep/tests/test_item_32_use_get_attr_for_lazy_attributes.py
Python
mit
459
0.004357
import unittest from item_32_use_get_attr_for_lazy_attributes import EasyLookup cl
ass TestGetSetAttr(unittest.TestCase): def test_easy_lookup(self): """simple est to make sure it runs""" d = {'asdf': 1, 'APPLE': 'hi'} r = EasyLookup(d) self.assertEqual(r.asdf, 1) self.assertEqual(r.APPLE, 'hi') with self.assertRaises(Attrib
uteError): r._data # because _data is not in self._data! muahaha
ngannguyen/immunoseq
src/clusterBlastXml.py
Python
mit
16,441
0.011313
#!/usr/bin/env python2.6 """ Tue Dec 4 11:54:18 PST 2012 Parse Blast XML output file and cluster sequences using greedy approach. Input: Blast xml file Output: Text file, each line = 1 cluster, each element of a cluster is space-separated Algorithm summary: Sorted sequences by descending in size Start with the large...
small clones
with similar motifs Cutoffs includes: a/ minimum number of clones contribute to one motif, b/ number of samples 2.1: the clones carrying the motif are from the same sample with seed 2.2: the clones carrying the motif are from at least one different sample than seed sample 3/ Seed has no simi...
tgquintela/Mscthesis
FirmsLocations/IO/io_aggfile.py
Python
mit
557
0.001795
""" Module which groups all the aggregated precomputed information in order to save computational power. """ import pandas as pd fr
om FirmsLocations.Preprocess.preprocess_cols import cp2str def read_agg(filepath): "Read file of aggregated info." table = pd.read_csv(filepath, sep=';') table = cp2str(table) return table def read_aggregation(filepath, typevars): ## TODO aggtable = read_agg(filepath) aggfeatures = aggta...
tures
meissnert/StarCluster-Plugins
root_6_04_14.py
Python
mit
1,099
0.018198
from starcluster.clustersetup import ClusterSetup from starcluster.logger import log class RootInstaller(ClusterSetup): def run(self, nodes, master, user, user_shell, volumes): for node in nodes: log.info("Installing Root 6.04/14 on %s " % (node.alias)) node.ssh.execute('mkdir -p /opt/software/root') node....
make') node.ssh.execute('mkdir -p /usr/local/Modules/applications/root/;touch /usr/local/Modules/applications/root/6.04.14') node.ssh.execute('echo "#%Module" >> /usr/local/Modules/applications/root/6.04.14') node.ssh.execute('echo "set root /opt/software/root/root-6.04.14" >> /usr/local/Modules/applications...
d-path\tPATH\t\$root" >> /usr/local/Modules/applications/root/6.04.14')
mbouchar/xc2424scan
src/xc2424scan/ui/widgets/scanwidget.py
Python
gpl-2.0
27,979
0.004147
# -*- coding: utf-8 -*- # This file is part of the xc2424scan package # Copyright (C) 2005 Mathieu Bouchard
<mbouchar@bioinfo.ulaval.ca> # # 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. # # This program is distri...
r 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 this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA """ Th...
openNSS/enigma2
RecordTimer.py
Python
gpl-2.0
54,247
0.028739
import os from enigma import eEPGCache, getBestPlayableServiceReference, eStreamServer, eServiceReference, iRecordableService, quitMainloop, eActionMap, setPreferredTuner from Components.config import config from Components.UsageConfig import defaultMoviePath from Components.SystemInfo import SystemInfo from Component...
e eActionMap.getInstance().bindAction('', -maxint - 1, RecordTimerE
ntry.keypress) @staticmethod def setWasInStandby(): if not RecordTimerEntry.wasInStandby: if not RecordTimerEntry.wasInDeepStandby: eActionMap.getInstance().bindAction('', -maxint - 1, RecordTimerEntry.keypress) RecordTimerEntry.wasInDeepStandby = False RecordTimerEntry.wasInStandby = True @staticme...
sgraham/nope
tools/telemetry/telemetry/core/backends/chrome/cros_unittest.py
Python
bsd-3-clause
4,879
0.009633
# 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 logging from telemetry import decorators from telemetry.core import exceptions from telemetry.core import util from telemetry.core.backends.chrome im...
User']) self.assertEquals(self._is_guest, login_status['isGuest']) self.asser
tEquals(login_status['email'], self._username) self.assertFalse(login_status['isScreenLocked']) @decorators.Enabled('chromeos') def testLogout(self): """Tests autotestPrivate.logout""" if self._is_guest: return with self._CreateBrowser(autotest_ext=True) as b: extension = self._GetAut...
leleopard/pyXPArduino
gui/alert_dialog.py
Python
gpl-3.0
2,716
0.002946
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'alert_dialog.ui' # # Created by: PyQt5 UI code generator 5.10 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Dialog(object): def setupUi(self, Dialog): Dialog.setObj...
lotsByName(Dialog) def retranslateUi(self, Dialog): _translate = QtCore.QCoreApplication.translate Dialog.setWindowTitle(_translate("Dialog", "Dialog")) self.msg_label.setText(_translate("Dialog", "T
extLabel")) self.exception_label.setText(_translate("Dialog", "TextLabel")) import resources_rc
gangadharkadam/shfr
frappe/website/doctype/blog_post/blog_post.py
Python
mit
3,543
0.024273
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt from __future__ import unicode_literals import frappe, re from frappe.website.website_generator import WebsiteGenerator from frappe.website.render import clear_cache from frappe.utils import today, cint, global_dat...
if category: condition += " and t1.blog_category='%s'
" % category.replace("'", "\'") query = """\ select t1.title, t1.name, concat(t1.parent_website_route, "/", t1.page_name) as page_name, t1.published_on as creation, day(t1.published_on) as day, monthname(t1.published_on) as month, year(t1.published_on) as year, ifnull(t1.blog_intro, t1.content...
byrnereese/uphold-sdk-python
uphold/uphold.py
Python
mit
15,514
0.00419
""" Uphold Python SDK This is a python module to ease integration between python apps and the Uphold API. Repo: http://github.com/byrnereese/uphold-python-sdk TODO * Create custom exceptions for common errors * Add support for updating records * Turn off authentication/authorization for public transactions (or make t...
t(transaction)) def get_transactions(self): """ Requests a list of transactions associated
with the current user. :rtype: An array of hashes containing all the current user's transactions. """ return self._get('/me/transactions') def prepare_txn(self, card, to, amount, denom): """ Developers can optionally prepare a transaction in order to preview a tr...
carlospalol/money
money/tests/test_docs.py
Python
mit
424
0.004717
# -*- coding: utf-8 -*- """ Money doctests as unittest Suite """ # RADAR: Python2 from __future__ import absolute_import import doctest import unittest # RADAR: Python2 import money.six FILES
= ( '../../README.rst', ) def load_tests(loader, tests, pattern): # RADAR Python 2.x if money.six.PY2: # Doc tests are Python 3.x return
unittest.TestSuite() return doctest.DocFileSuite(*FILES)
dhh1128/lect
docs/source/conf.py
Python
apache-2.0
9,538
0.007968
# -*- coding: utf-8 -*- # # lect documentation build configuration file, created by # sphinx-quickstart on Fri Aug 2 17:40:25 2013. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all pos
sible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commen
ted out # serve to show the default. import sys, os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path....
cppisfun/GameEngine
foreign/boost/tools/build/v2/test/conditionals3.py
Python
gpl-3.0
713
0.001403
#!/usr/bin/python # Copyright 2003 Vladimir Prus # Distributed under the Boost Software License, Version 1.0. # (See accompanying file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) # Test that conditional properties work, even if property is free, and
value # includes a colon. import BoostBuild t = BoostBuild.Tester() t.write("jamroot.jam", """ exe hello : hello.cpp : <variant>debug:<define>CLASS=Foo::Bar ; """) t.write("hello.cpp", """ namespace Foo { class Bar { } ; } int main() { CLASS c; c; // Disables the unused variable warning. }...
ect_addition("bin/$toolset/debug/hello.exe") t.cleanup()
Zen-CODE/kivy
kivy/adapters/dictadapter.py
Python
mit
5,874
0.00017
''' DictAdapter =========== .. versionadded:: 1.5 .. warning:: This code is still experimental, and its API is subject to change in a future version. A :class:`~kivy.adapters.dictadapter.DictAdapter` is an adapter around a python dictionary of records. It extends the list-like capabilities of the :class:`~k...
ta and sorted_keys, data must be reset # first, followed by a reset of sorted_keys, if needed. def initialize_sorted_keys(self, *args): stale_sorted_keys = False for key in self.sorted_keys: if not key in self.data:
stale_sorted_keys = True break else: if len(self.sorted_keys) != len(self.data): stale_sorted_keys = True if stale_sorted_keys: self.sorted_keys = sorted(self.data.keys()) self.delete_cache() self.initialize_selectio...
thusser/rtml-parse
rtmlparse/__init__.py
Python
mit
227
0.004405
__desc
ription__ = "MASTER event parser and VOEvent publisher" __url__ = "http://rtml.saao.ac.za/" __author__ =
"Tim-Oliver Husser" __contact__ = "husser@astro.physik.uni-goettingen.de" __version__ = "0.1" from rtml import RTML
mvidalgarcia/indico
indico/modules/events/tracks/operations.py
Python
mit
2,614
0.001913
# This file is part of Indico. # Copyright (C) 2002 - 2019 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from __future__ import unicode_literals from flask import session from indico.core.db import db from ind...
te_track(event, data): track = Track(event=event) track.populate_from_dict(data) db.session.flush() logger.info('Track %r created by %r', track, session.user) event.log(EventLogRealm.management, EventLogKind.positive, 'Tracks', 'Track "{}" has been created.'.format(track.title), sessio...
def update_track(track, data): track.populate_from_dict(data) db.session.flush() logger.info('Track %r modified by %r', track, session.user) track.event.log(EventLogRealm.management, EventLogKind.change, 'Tracks', 'Track "{}" has been modified.'.format(track.title), session.user) d...
sonntagsgesicht/regtest
.aux/venv/lib/python3.9/site-packages/pygments/lexers/teal.py
Python
apache-2.0
3,519
0.001137
# -*- coding: utf-8 -*- """ pygments.lexers.teal ~~~~~~~~~~~~~~~~~~~~ Lexer for TEAL. :copyright: Copyright 2006-2021 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ from pygments.lexer import RegexLexer, bygroups, include, words from pygments.token import Comment, ...
}, suffix = r'\b') identifier = r'[^ \t\n]+(?=\/\/)|[^ \t\n
]+' newline = r'\r?\n' tokens = { 'root': [ include('whitespace'), # pragmas match specifically on the space character (r'^#pragma .*' + newline, Comment.Directive), # labels must be followed by a space, # but anything after that is ignored ...
bndr/pycycle
tests/_projects/large_without_circle/a_module/b_module/b_file.py
Python
mit
58
0.034483
from c_module.c_file
im
port c_func def b_func(): pass
xsunfeng/cir
cir/phase5.py
Python
mit
3,009
0.02559
import json from django.template.loader import render_to_string from django.http import HttpResponse from django.utils impor
t timezone from django.shortcuts import render_to_re
sponse from cir.models import * import claim_views from cir.phase_control import PHASE_CONTROL import utils def get_statement_comment_list(request): response = {} context = {} forum = Forum.objects.get(id = request.session['forum_id']) thread_comments = ForumComment.objects.filter(forum = forum) ...
enfancemill/litchi
litchi/urls.py
Python
gpl-3.0
894
0
"""litchi URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-bas...
her URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^captcha/',
include('captcha.urls')), url(r'^session/', include('apps.session.urls', namespace='session')), ]
gjermv/potato
sccs/gpx/dtmdata.py
Python
gpl-2.0
6,663
0.025514
''' Created on 14 Jun 2016 @author: gjermund.vingerhagen ''' import numpy as np import scipy.interpolate as intp import linecache import utmconverter as utm def splitHead(inp): return inp def lineToArr(l1): arra = np.array(np.fromstring(l1[144:1024],dtype=int,sep=' ')) for i in
range(1,30): arra = np.append(arra,np.fromstring(
l1[1024*i:1024*(i+1)],dtype=int,sep=' ')) return arra def findClosestPoint(east,north): try: dtminfo = getDTMFile(east,north) eastLine = round((east-dtminfo[1])//10) northLine = round((north-dtminfo[2])//10) east_delta = (east-dtminfo[1])%10 north_delta = (north...
Parcks/core
test/domain/parse/test_installation_file_parser.py
Python
gpl-2.0
4,254
0.007522
""" Scriptable Packages Installer - Parcks Copyright (C) 2017 JValck - Setarit 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....
eate_valid_json(self): JSON = """\ { "name":"PHP installer", "install": [ {"package": "php", "post-installation": [] } ] } """ return json.loads(JSON) def create_invalid_test_install_file(self): JSON = """\ { "name":"PHP installer" ...
,'w') as ofile: json.dump(jsonData, ofile) return tempJsonPath def create_invalid_file_extension_install_file(self): jsonData = self.create_valid_json() tempJsonPath = path.join(self.testDir,"invalid_extension.json") with open(tempJsonPath ,'w') as ofile: ...
fake-name/ReadableWebProxy
WebMirror/management/rss_parser_funcs/feed_parse_extractMiratlsWordpressCom.py
Python
bsd-3-clause
554
0.034296
def extractMiratlsWordpressCom(item): ''' Parser for 'miratls.wordpress.com' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None tagmap =
[ ('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel'), ] for tagname, name, tl_type in tagmap: if tagname in item['tags']: return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix,
tl_type=tl_type) return False
xczheng/swift-encrypt-compress-middleware
myswift/encrypt.py
Python
apache-2.0
3,355
0.004173
from swift.common.swob import Request from swift.common.utils import split_path from Crypto.Cipher import AES from Crypto import Random import hashlib AES_BLOCK = 32 def create_encrypt(raw, password): raw = _pad(raw) key = hashlib.sha256(password.encode()).digest() iv = Random.new().read(AES.block_size) ...
response = request.get_response(self.app) if container: if not request.params.has_key('encrypt'): response
.body = response.body.replace(self.encrypt_suffix, '') return response(env, start_response) original_path_info = request.path_info request.path_info += self.encrypt_suffix if request.method == 'GET': if not request.params.has_key('encrypt'): # we need to ...
lawrencebenson/thefuck
tests/shells/conftest.py
Python
mit
459
0
import pytest @pytest.fixture def builtins_open(mock
er): return mocker.patch('six.moves.builtins.open') @pytest.fixture def isfile(mocker): return
mocker.patch('os.path.isfile', return_value=True) @pytest.fixture @pytest.mark.usefixtures('isfile') def history_lines(mocker): def aux(lines): mock = mocker.patch('io.open') mock.return_value.__enter__ \ .return_value.readlines.return_value = lines return aux
ngtuna/kubeless
docker/runtime/python-3.6/http-trigger/kubeless.py
Python
apache-2.0
2,152
0.003717
#!/usr/bin/env python import os import imp from multiprocessing import Process, Queue import bottle import prometheus_client as prom mod = imp.load_source('function', '/kubeless/%s.py' % os.getenv('MOD_NAME')) func = getattr(mod, os.getenv('FUNC_HANDLER')) func_port = os.getenv('FUNC_PORT', 808...
xceptions(): with func_hist.labels(method).time(): q = Queue() p = Process(target=funcWrap, args=(q,bottle.request,))
p.start() p.join(timeout) # If thread is still active if p.is_alive(): p.terminate() p.join() return bottle.HTTPError(408, "Timeout while processing the function") else: return q.get() @app.get('/health...
jf87/smap
python/tinyos/__init__.py
Python
bsd-2-clause
1,659
0
# # Copyright (c) 2005 # The President and Fellows of Harvard College. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of...
NY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLU...
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF # SUCH DAMAGE. # # Author: Geoffrey Mainland <mainland@eecs.harvard.edu> # __all__ = ["message", "packet", "utils", "tossim"]
openconnectome/ocptilecache
tilecache/migrations/0003_auto_20160317_1521.py
Python
apache-2.0
512
0
# -*- coding: utf-8 -*- # Generated by Django 1.9.4 on 2016-03-17 19:21 from __future__ import unicode_literals from django.db import mig
rations class Migration(migrations.Migration): dependencies = [ ('tilecache', '0002_auto_20160317_1519'), ]
operations = [ migrations.AlterModelOptions( name='channel', options={'managed': True}, ), migrations.AlterModelTable( name='channel', table='channels', ), ]
dronekit/dronekit-python
dronekit/test/sitl/test_waypoints.py
Python
apache-2.0
4,352
0.001838
import time from dronekit import connect, LocationGlobal, Command from pymavlink import mavutil from dronekit.test import with_sitl from nose.tools import assert_not_equals, assert_equals @with_sitl def test_empty_clear(connpath): vehicle = connect(connpath) # Calling clear() on an empty object should not cr...
in [ Command(0, 0, 0, 0, 16, 1, 1, 0.0, 0.0, 0.0, 0.0, -35.3605, 149.172363, 747.0), Command(0, 0, 0, 3, 22, 0, 1, 0.0, 0.0, 0.0, 0.0, -35.359831, 149.166334, 100.0), Command(0, 0, 0, 3, 16, 0, 1, 0.0, 0.0, 0.0, 0.0, -35.363489, 149.167213, 100.0), Command(0, 0, 0, 3, 16, 0, 1, 0.0, 0.0,...
9.175839, 100.0), Command(0, 0, 0, 3, 113, 0, 1, 0.0, 0.0, 0.0, 0.0, -35.362666, 149.178715, 22222.0), Command(0, 0, 0, 3, 115, 0, 1, 2.0, 22.0, 1.0, 3.0, 0.0, 0.0, 0.0), Command(0, 0, 0, 3, 16, 0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), ]: vehicle.commands.add(command) vehicle.co...
lavish/drs
snippets/tracker/tracker.py
Python
mit
1,608
0.005597
#!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import division from time import sleep from ev3.ev3dev import Motor from ev3.lego import LargeMotor from ev3.lego import ColorSensor import sys # left motor motor_b = LargeMotor(port = Motor.PORT.B) # right motor motor_c = LargeMotor(port = Motor.PORT.C) colo...
) - speed, speed), -speed))) motor_b.run_forever(speed, regulation_mode=False) motor_c.run_forever(cur_spee
d, regulation_mode=False) else: # go straight motor_b.run_forever(speed, regulation_mode=False) motor_c.run_forever(speed, regulation_mode=False) except KeyboardInterrupt: motor_b.stop() motor_c.stop() sys.exit() if...
PythonT/Crawler
pickling.py
Python
apache-2.0
800
0.016949
#!/usr/bin/python #coding:utf-8 # Filename: pickling.py import pickle # the name of the file where we will store the o
bject shoplistfile = 'shoplist.data' # the list of things to buy shoplist = ['apple', 'mango', 'carrot'] # Write to the file f = open(shoplistfile, 'wb') pickle.dump(shoplist, f) # 转储对象到文件 f.close() del shoplist # 销毁shoplist变量 # 从文件找回对象 f = open(shoplistfile, 'rb') storedlist = pickle.load(f) # 从文件加载对象 ...
封(unpickling)对象。
frankwiles/django-pagebits
pagebits/utils.py
Python
bsd-3-clause
171
0.005848
fro
m django.conf import settings def bitgroup_cache_key(slug): return "%s:%s" % ( getattr(settings, 'PAGEBIT_CACHE_PREFIX', 'pagebits'),
slug )
SenseHawk/dispatch
app.py
Python
apache-2.0
2,442
0.009009
#!flask/bin/python from flask import Flask, request, abort, render_template import config import sqlite3 import emails from data import func import json # FLASK part app = Flask(__name__) @app.route('/send', methods=[
'POST']) def capture_post_send(): if not request.json or not 'subject' in request.json: abort(400) data = request.get_json() send = send_email(data['html'], data['raw'], data['subject'], da
ta['email_from'], data['email_to']) return send def send_email(html, raw, subject, email_from, email_to): email_to = str(email_to.encode('utf8')) email_to = email_to.split(",") # Sending the email email = emails.Email(to=email_to, from_addr=email_from, subject=subject) email.te...
amancevice/agador
agador/microservice.py
Python
mit
1,138
0.000879
""" Agador Metaservice Usage: agador [options] Options: -c --config URI # Service config URI -d --debug # Run in debug mode -h --host HOST # Host IP [default: 0.0.0.0] -p --port PORT # Port no [default: 8500] """ import furi from envopt import envopt from f...
ort jsonify from . import __version__ APP = Flask("Agador") OPT = envopt(__doc__, env_prefix="MRMET") def config(): """ Helper to get server config. """ try: return dict(furi.map(OPT["--config"])) except AttributeError: return {} @APP.route("/") def version(): """ Health Check. """ ...
return jsonify(version=__version__, services=config()) @APP.route("/<svc>") def service(svc): """ Get microservice. """ return jsonify(service=config().get(svc, {})) def runserver(): """ Run microservice. """ # Strip -- from opts opts = dict((key.lstrip("-"), val) for key, val in OPT.iteritems()...
plotly/python-api
packages/python/plotly/plotly/validators/scatter3d/marker/_symbol.py
Python
mit
863
0.001159
import _plotly_utils.basevalidators class SymbolValidator(_plotly_utils.basevalidators.EnumeratedValidator): def __init__(self, plotly_name="symbol", parent_name="scatter3d.marker", **kwargs): super(SymbolValidator, self).
__init__( plotly_name=plotly_name, parent_name=parent_name, array_ok=kwargs.pop("array_ok", True), edit_type=kwargs.pop("edit_type", "calc"), role=kwargs.pop("role", "style"), values=kwargs.pop( "values", [ ...
"diamond-open", "cross", "x", ], ), **kwargs )
operasoftware/dragonfly-build-tools
df2/codegen/node.py
Python
apache-2.0
4,544
0.006382
INDENT = " " def escape_text_html(str): return str.replace("&", "&amp;").replace("<", "&lt;") def escape_attr_html(str): return str.replace("\"", "&quot;") class Node(object): ELEMENT = 1 TEXT = 2 ROOT = 3 type = 0 parent = None def insert_before(self, node): if node.parent: node.pa...
.is_text: text.append(child.value) elif child.is_element: text.append(child.text_content) return "".join(text) @text_content.setter def text_content(self, value): self.children = [Text(value)] def serialize(self, initial_depth=0): attrs = "".join((" %s=\"%s\"" % (key, e...
= (initial_depth + self.depth) * INDENT if self.contains_blocklevel: return "\n%s<%s%s>%s\n%s</%s>" % (indent, name, attrs, content, indent, name) if self.is_blocklevel: return "\n%s<%s%s>%s</%s>" % (indent, self.name, attrs, content, self.name) return "<%s%s>%s</%s>" % ...
fgaudin/aemanager
core/templatetags/filetags.py
Python
agpl-3.0
268
0.003731
import os from django import template from django.template.default
filters import stringfilter register = template.Library() @register.filter @stringfilter def base
name(path): """ Returns os.path.basename from a path """ return os.path.basename(path)
steveb/heat
heat/tests/test_validate.py
Python
apache-2.0
54,212
0
# # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # ...
", "Description" : "test.", "Parameters" : { "KeyName" : { "Description" : "Name of an existing EC2 KeyPai", "Type" : "String" } }, "Resources" : { "WikiDatabase": { "Type": "AWS::EC2::Instance", "Properties": { "ImageId": "image_name", ...
nown" } } } } ''' test_template_unimplemented_property = ''' { "AWSTemplateFormatVersion" : "2010-09-09", "Description" : "test.", "Parameters" : { "KeyName" : { "Description" : "Name of an existing EC2KeyPair", "Type" : "String" } }, "Resources" : { ...
sander76/home-assistant
tests/components/onewire/test_switch.py
Python
apache-2.0
2,860
0.001049
"""Tests for 1-Wire devices connected on OWServer.""" import copy from unittest.mock import patch import pytest from homeassistant.components.onewire.switch import DEVICE_SWITCHES from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN from homeassistant.const import ATTR_ENTITY_ID, SERVICE_TOGGLE, STATE_...
ITCH_DOMAIN] # Force enable switches patch_device_switches = copy.deepcopy(DEVICE_SWITCHES) for item in patch_device_switches[device_id[0:2]]: item.entity_registry_enabled_default = True with patch( "homeassistant.components.onewire.PLATFORMS", [SWITCH_DOMAIN] ), patch.dict( ...
h_device_switches ): await setup_onewire_patched_owserver_integration(hass) await hass.async_block_till_done() assert len(entity_registry.entities) == len(expected_entities) for expected_entity in expected_entities: entity_id = expected_entity["entity_id"] registry_entry = ...
vsoch/singularity-python
singularity/package/clone.py
Python
agpl-3.0
2,880
0.007292
''' Copyright (C) 2017-2019 Vanessa Sochat. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distribute...
ngle partition. :param root: the root of the node to package, default is / :param name: the name for the image. If not specified, will use machine's psutil.disk_partitions() ''' if
name is None: name = platform.node() if root is None: root = "/" tmpdir = tempfile.mkdtemp() image = "%s/%s.tgz" %(tmpdir, name) excludes = ['--exclude', "'/tmp'", '--exclude', image] print("Preparing to package root %s into %s" %(root, name)) cmd = ["tar","--one-file-system...
wangwei7175878/tutorials
theanoTUT/theano7_activation_function.py
Python
mit
705
0.007092
# View more python tutorials on my Youtube
and Youku channel!!! # Youtube video tutorial: https://www.youtube.com/channel/UCdyjiB5H8Pu7aDTNVXTTpcg # Youku video tutorial: http://i.youku.com/pythontutorial # 7 - Activation function """ The available activation functions in theano ca
n be found in this link: http://deeplearning.net/software/theano/library/tensor/nnet/nnet.html The activation functions include but not limited to softplus, sigmoid, relu, softmax, elu, tanh... For the hidden layer, we could use relu, tanh, softplus... For classification problems, we could use sigmoid or softmax for ...
GoogleCloudPlatform/python-compat-runtime
appengine-compat/exported_appengine_sdk/google/net/proto2/python/public/descriptor.py
Python
apache-2.0
31,685
0.006596
#!/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...
ll GetOptions() which will happily return the default instance. However, it's sometimes useful for efficiency, and also useful inside the protobuf implementation to avoid some bootstrapping issues. """ __metaclass__ = DescriptorMetaclass if _USE_C_DESCRIPTORS: _C_DESCRIPTOR_CLASS =...
ven its options message and the name of the class of the options message. The name of the class is required in case the options message is None and has to be created. """ self._options = options self._options_class_name = options_class_name self.has_options = options is not None def _SetOpt...
quattor/aquilon
lib/aquilon/worker/commands/reconfigure_membersof.py
Python
apache-2.0
1,488
0
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2009,2010,2011,2012,2013,2014,2016 Contributor # # Licensed under the Apache Lice
nse, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "...
License for the specific language governing permissions and # limitations under the License. """Contains the logic for `aq reconfigure --membersof`.""" from aquilon.aqdb.model import Cluster, MetaCluster from aquilon.worker.broker import BrokerCommand # pylint: disable=W0611 from aquilon.worker.commands.reconfigure_...
GoogleCloudPlatform/functions-framework-python
src/functions_framework/_function_registry.py
Python
apache-2.0
4,301
0.000698
# Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
needs to be of " "type function. Got: invalid type {target_type}".format( source=source, target=target, target_type=type(function) ) ) return function def load_function_module(source): """Load user function source file.""" # 1. Extract the module name from ...
extension = os.path.splitext(filename) # 2. Create a new module spec = importlib.util.spec_from_file_location( name, realpath, submodule_search_locations=[directory] ) source_module = importlib.util.module_from_spec(spec) # 3. Add the directory of the source to sys.path to allow the functio...
openNSS/enigma2
lib/python/Screens/SleepTimerEdit.py
Python
gpl-2.0
10,279
0.02724
from Screens.InfoBar import InfoBar from Screens.Screen import Screen from Screens.MessageBox import MessageBox from Components.ActionMap import ActionMap from Components.ConfigList import ConfigListScreen from Components.Label import Label from Components.Sources.StaticText import StaticText from Components.config imp...
) def ok(self): if self["config"].isChanged(): for x in self["config"].list: x[1].save() if self.getCurrentEntry().startswith(_
("Sleeptimer")): sleepTimer = config.usage.sleep_timer.value if sleepTimer == "event_standby": sleepTimer = self.currentEventTime() else: sleepTimer = int(sleepTimer) if sleepTimer or not self.getCurrentEntry().endswith(_("(not activated)")): InfoBar.instance.setSleepTimer(sleepTimer) self.cl...
Carryzhou/MyPython-
bubble_sort.py
Python
gpl-3.0
511
0.037182
#!/usr/bin/python #Python version: bubble sort algorithm import random def bubble_sort(numbers): for j in xrange(len(numbers) - 1, -1,
-1): for i in xrange(j): if numbers[ i ] > numbers[ i + 1 ]: numbers[ i ], numbers[ i + 1 ] = numbers[ i + 1], numbers[ i ] print numbers def main():
numbers = [] for i in range(10): numbers.append(random.randint(1,100)) bubble_sort(numbers) print numbers if __name__ == '__main__': main()
astropy/astropy
astropy/io/misc/asdf/tags/coordinates/spectralcoord.py
Python
bsd-3-clause
1,569
0.000637
# Licensed under a 3-clause BSD style license - see LICENSE.rst # -*- coding: utf-8 -*- from asdf.tags.core import NDArrayType from astropy.coordinates.spectral_coordinate import SpectralCoord from astropy.io.misc.asdf.types import AstropyType from astropy.io.misc.asdf.tags.unit.unit import UnitType __all__ = ['Spec...
_tree(cls, node, ctx): if isinstance(node, SpectralCoord): return node
unit = UnitType.from_tree(node['unit'], ctx) value = node['value'] observer = node['observer'] if 'observer' in node else None target = node['target'] if 'observer' in node else None if isinstance(value, NDArrayType): value = value._make_array() return SpectralCoord(...
heuermh/cloudbiolinux
contrib/flavor/pjotrp/biotest/biotestflavor.py
Python
mit
1,800
0.007778
from fabric.api import * from fabric.contrib.files import * from cloudbio.flavor import Flavor from cloudbio.custom.shared import (_fetch_and_unpack) class BioTestFlavor(Flavor): """A Flavor for cross Bio* tests """ def __init__(self, env): Flavor.__init__(self,env) self.name = "Bio* cros...
s def post_install(self): env.logger.info("Starting post-install") env.logger.info("Load Scalability tests") if exists('Scalability'): with cd('Scalability'): run('git pull') else: _fetch_and_unpack("git clone git://github.com
/pjotrp/Scalability.git") # Now run a post installation routine (for the heck of it) run('./Scalability/scripts/hello.sh') env.logger.info("Load Cross-language tests") if exists('Cross-language-interfacing'): with cd('Cross-language-interfacing'): run('git pul...
googleapis/python-aiplatform
samples/generated_samples/aiplatform_v1beta1_generated_job_service_list_custom_jobs_sync.py
Python
apache-2.0
1,526
0.000655
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
.cloud import aiplatform_v1beta1 def sample_list_custom_jobs(): # Create a client client = aiplatform_v1beta1.JobServiceClient() # Initialize request argument(s) request = aiplatform_v1beta1.ListCustomJobsRequest( parent="parent_value", ) # Make the
request page_result = client.list_custom_jobs(request=request) # Handle the response for response in page_result: print(response) # [END aiplatform_v1beta1_generated_JobService_ListCustomJobs_sync]
DFEC-R2D2/r2d2
pygecko/states/remote.py
Python
mit
11,721
0.013224
import time import random from random import randint # from library import Trigger, Axis # from library import PS4 from library import Joystick import RPi.GPIO as GPIO # remove!!! from emotions import angry, happy, confused # from pysabertooth import Sabertooth # from smc import SMC from library import LEDDisplay from...
Flash.pwm.set_pwm(15, 0, 130) # if btnCircle == 1: # # FlashLight OFF # GPIO.output(26, GPIO.LOW) # Flash.pwm.set_pwm(15, 0, 0) # if btnX == 1: # for x in [0, 1, 2, 3, 4, 5, 6, 7]: # for y in [
0, 1, 2, 3, 4, 5, 6, 7]: # if x == randint(0, 8) or y == randint(0, 8): # for i in range(1, 5): # leds[i].set(x, y, randint(0, 4)) # else: # for i in range(1, 5): # leds[i].set(x, y, 4) # for i in range(1, 5): # leds[i].write() # time.sleep(0.1) # ...
pataquets/namecoin-core
test/functional/feature_maxuploadtarget.py
Python
mit
6,579
0.001368
#!/usr/bin/env python3 # Copyright (c) 2015-2021 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test behavior of -maxuploadtarget. * Verify that getdata requests for old blocks (>1week) are dropped ...
g_old_block)] peer.send_and_ping(getdata_request) self.log.info("Peer still connected after trying to download old block (download permission)") peer_info = self.nodes[0].getpeerinf
o() assert_equal(len(peer_info), 1) # node is still connected assert_equal(peer_info[0]['permissions'], ['download']) if __name__ == '__main__': MaxUploadTest().main()
saltstack/salt
salt/modules/ifttt.py
Python
apache-2.0
2,334
0.002142
""" Support for IFTTT .. versionadded:: 2015.8.0 Requires an ``api_key`` in ``/etc/salt/minion``: .. code-block:: yaml ifttt: secret_key: '280d4699-a817-4719-ba6f-ca56e573e44f' """ import logging import time import salt.utils.http import salt.utils.json log = logging.getLogger(__name__) def __virtua...
:param event: The name of the event to trigger. :return: A dictionary with status, text, and error if result was failure. """
res = {"result": False, "message": "Something went wrong"} data = {} for value in ("value1", "value2", "value3", "Value1", "Value2", "Value3"): if value in kwargs: data[value.lower()] = kwargs[value] data["occurredat"] = time.strftime("%B %d, %Y %I:%M%p", time.localtime()) result = ...
rueberger/MJHMC
mjhmc/samplers/markov_jump_hmc.py
Python
gpl-2.0
14,817
0.002025
""" This file contains the core MJHMC algorithm, as well the algorithms for several HMC variants including standard HMC As there is a significant amount of logic common to all algorithms, all of the different variants are implemented as classes that inherit from a common base class. """ import numpy as np from mjh...
wise if np.random.random() < self.p_r: # corrupt the momentum self.r_count += self.nbatch self.state.R() FL_idx
= set(fl_idx) F_idx = set(flip_idx) self.l_count += len(FL_idx & F_idx) self.f_count += len(F_idx - FL_idx) self.fl_count += len(FL_idx - F_idx) def sample(self, n_samples=1000, preserve_order=False): """ Draws nsamples, returns them all Args: n_...
DigitalPublishingToolkit/epubtrailer.py
epubtrailer.py
Python
lgpl-3.0
8,278
0.022348
#!/usr/bin/env python #-*- coding:utf-8 -*- """ (C) 2014 Contributors to the Digital Publishing Toolkit License: GPL3 This code has been developed as part of the [Digital Publishing Toolkit](http://digitalpublishingtoolkit.org). with the support of Institute for [Network Cultures](http://networkcultures.org) and [Cr...
(_bytes(line)) # d_usr = d_usr.text(((W-w)/2,(H-h)/2), line, fontColor, font=usr_font) d_usr.text((padding, y_text), _bytes(line), fontColor, font=usr_font) y_text += height filename = 'new-pictures/' + seqall + '.jpeg' image.save(f
ilename, 'jpeg', quality=quality) # Create Screen for Title screen(title, '00', int(fontratio * 6), titleDuration*8) # Create Screen for 'by' screen('A book by', '01', int(fontratio * 2.8), titleDuration*4) # Create Screens for Authors i = 0 for name in authors: screen(name, '02-' + str(i), int(fontratio * 4), title...
jmohr/conrad
conrad/test/resources/rest_test_server.py
Python
bsd-3-clause
1,320
0.007576
#!/usr/bin/env python import flask artist_map = { 1: { 'id': 1, 'name': 'James Brown', }, 2: { 'id': 2, 'name': 'Richard D. James', }, 3: { 'id': 3, 'name': 'Fugazi', }, 4: { 'id': 4, 'name': 'Dinosaur Jr.', }, } app = ...
st_map[id] = { 'id': id, 'name': flask.request.form['name'], } return flask.jsonify(artist_map[id]) @app.route('/api/artist/<int:id>', methods=['PUT']) def update_artist(id): if not artist_map.
has_key(id): flask.abort(404) artist_map[id] = { 'id': id, 'name': flask.request.form['name'], } return flask.jsonify(artist_map[id]) @app.route('/api/artist/<int:id>', methods=['DELETE']) def delete_artist(id): if not artist_map.has_key(id): flask.abort(404) del art...
dimagi/commcare-hq
corehq/apps/registration/migrations/0002_alter_request_ip.py
Python
bsd-3-clause
477
0
# -*- coding: utf-8 -*- # Generated by Django 1.11.27 on 2020-02-13 22:21 from __future__ import unicode_literals from d
jango.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('registration', '0001_initial'), ] operations = [ migrations.AlterField( model_name='sqlregistrationreque
st', name='request_ip', field=models.CharField(max_length=31, null=True), ), ]
davidnotplay/mpiece
mpiece/renderer.py
Python
bsd-3-clause
5,413
0.027526
""" mpiece.renderer ~~~~~~~~~~~~~~~~~~~~~~~~~ Renderer Classes. :license: BSD, see LICENSE for details. :author: David Casado Martinez <dcasadomartinez@gmail.com> """ class Renderer(object): """ Base renderer class. All renderer classes should be subclasses of this class. This class and their subclass ...
ic(text) def render_strike(self, text): return '<del>%s</del>' % self.escape(text) def render_code_inline(self, code): return '<code>%s</code>' % self.escape(code) def render_link(self, text, href, title=''): text = self.escape(text) href = self.escape_link(href) i
f title: return '<a href="%s" title="%s">%s</a>' % (href, self.escape(title), text) return '<a href="%s">%s</a>' % (href, text) def render_image(self, src, alt, title=''): alt = self.escape(alt) src = self.escape_link(src) if title: title = self.escape(title) return '<img src="%s" alt="%s" title="%s...
ballotify/django-backend
ballotify/apps/accounts/factories.py
Python
agpl-3.0
353
0
import factory from .models import User USER_PASSWORD = "2fast2furious" class UserFactory(factory.DjangoModelFactory): name = "John Doe" email = factory.Sequence(lambda n: "john{}@example.com".format(n)) pa
ssword = factory.PostGenerationMethodCall('set_pa
ssword', USER_PASSWORD) gender = "male" class Meta: model = User
yashchandak/GNN
Sample_Run/DOPE/parser.py
Python
mit
4,549
0.009453
import argparse class Parser(object): def __init__(self): parser = argparse.ArgumentParser() parser.add_argument("--path", default='/home/priyesh/Desktop/Expt_Deep_CC', help="Base path for the code") parser.add_argument("--project", default='DO...
"--pat", default=2, help="Patience", type=int) parser.add_argument("--pat_inc", default=2, help=
"Patience Increase", type=int) parser.add_argument("--pat_improve", default=1, help="Improvement threshold for patience", type=float) parser.add_argument("--save_after", default=0, help="Save after epochs", type=int) parser.add_argument("--val_freq", default=1, help="Validation frequ...
MungoRae/home-assistant
tests/components/alarm_control_panel/test_manual.py
Python
apache-2.0
16,012
0
"""The tests for the manual Alarm Control Panel component.""" from datetime import timedelta import unittest from unittest.mock import patch from homeassistant.setup import setup_component from homeassistant.const import ( STATE_ALARM_DISARMED, STATE_ALARM_ARMED_HOME, STATE_ALARM_ARMED_AWAY, STATE_ALARM_ARMED_...
D_HOME, self.hass.states.get(entity_id).state) def test_arm_home_with_pending(self): """Test arm home method.""" self.assertTrue(setup_component( self.hass, alarm_control_panel.DOMAIN, {'alarm_control_panel': { 'platform': 'manual', ...
'code': CODE, 'pending_time': 1, 'disarm_after_trigger': False }})) entity_id = 'alarm_control_panel.test' self.assertEqual(STATE_ALARM_DISARMED, self.hass.states.get(entity_id).state) alarm_control_panel.alarm...
michalliu/OpenWrt-Firefly-Libraries
staging_dir/host/lib/scons-2.3.1/SCons/Scanner/Dir.py
Python
gpl-2.0
3,822
0.002616
# # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction...
__revision__ = "src/engine/SCons/Scanner/Dir.py 2014/03/02 14:18:15 garyo" import SCons.Node.FS import SCons.Scanner def only_dirs(nodes): is_Dir = lambda n: isinstance(n.disambiguate(), S
Cons.Node.FS.Dir) return list(filter(is_Dir, nodes)) def DirScanner(**kw): """Return a prototype Scanner instance for scanning directories for on-disk files""" kw['node_factory'] = SCons.Node.FS.Entry kw['recursive'] = only_dirs return SCons.Scanner.Base(scan_on_disk, "DirScanner", **kw) def D...
bmi-forum/bmi-pyre
pythia-0.8/packages/pyre/applications/app.py
Python
gpl-2.0
3,881
0.002577
#!/usr/bin/env python # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # # Michael A.G. Aivazis # California Institute of Technology # (C) 1998-2005 All Rights Reserved # # <LicenseText> # # ~~~~~~~~~~~~~~~~~...
mport Script", "", "", " class %sApp(Script):" % appName, "", "",
" class Inventory(Script.Inventory):", "", " import pyre.inventory", "", " name = pyre.inventory.str('name', default='world')", " name.meta['tip'] = 'the entity to greet'", "", "", " ...
xuru/pyvisdk
pyvisdk/do/ip_pool.py
Python
mit
1,191
0.010915
import logging from pyvisdk.exceptions import InvalidArgumentError ######################################## # Automatically generated, do not edit. ######################################## log = logging.getLogger(__name__) def IpPool(vim, *args, **kwargs): '''Specifications of the network configuration to be us...
zip(required+optional, args): setattr(obj, name, arg) for name, value in kwargs.items(): if
name in required + optional: setattr(obj, name, value) else: raise InvalidArgumentError("Invalid argument: %s. Expected one of %s" % (name, ", ".join(required + optional))) return obj
MLAB-project/weewx
bin/weewx/drivers/cc3000.py
Python
gpl-3.0
42,551
0.000705
#!/usr/bin/env python # # Copyright 2014 Matthew Wall # See the file LICENSE.txt for your rights. """Driver for CC3000 data logger http://www.rainwise.com/products/attachments/6832/20110518125531.pdf There are a few variants: CC-3000_ - __ | | | 41 = 418 MHz | 42 = 433 MHz | __ =...
time import weeutil.weeutil import weewx.drivers DRIVER_NAME = 'CC3000' DRIVER_VERSION = '0.16' def loader(config_dict, engine): return CC3000Driver(**config_dict[DRIVER_NAME]) def configurator_loader(config_dict): return CC3000Configurator() def confeditor_loader(): return CC3000ConfEditor() DEBUG_S...
def loginf(msg): logmsg(syslog.LOG_INFO, msg) def logerr(msg): logmsg(syslog.LOG_ERR, msg) class ChecksumError(weewx.WeeWxIOError): def __init__(self, msg): weewx.WeeWxIOError.__init__(self, msg) class ChecksumMismatch(ChecksumError): def __init__(self, a, b, buf=None): msg = "Checksu...
loveyoupeng/rt
modules/web/src/main/native/Tools/Scripts/webkitpy/style/checkers/cmake_unittest.py
Python
gpl-2.0
5,918
0.002366
# Copyright (C) 2012 Intel Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the f...
duplicate', 5, 'The item "a" should be added only once to the list.'), (35, 'list/order', 5, 'Alphabetical sorting problem. "a" should
be before "b".'), (41, 'list/order', 5, 'Alphabetical sorting problem. "c/c.c" should be before "c/b/a.a".'), (49, 'list/emptyline', 5, 'There should be no empty line between "a" and "b".'), (54, 'list/emptyline', 5, 'There should be exactly one empty line instead of 0 between "a/b....
felipenaselva/repo.felipe
plugin.video.uwc/cam4.py
Python
gpl-2.0
3,936
0.017022
''' Ultimate Whitecream Copyright (C) 2016 mortael This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. ...
am4 images cleared') except: pass def List(url, page): if utils.addon.getSetting("chaturbate") == "true": clean_database() listhtml = utils.getHtml(url, url) match = re.compile('profileDataBox"> <a href="([^"]+)".*?src="([^"]+)" title
="Chat Now Free with ([^"]+)"', re.DOTALL | re.IGNORECASE).findall(listhtml) for videourl, img, name in match: name = utils.cleantext(name) videourl = "http://www.cam4.com" + videourl utils.addDownLink(name, videourl, 282, img, '', noDownload=True) if re.search('<link rel="next"', listht...
plotly/python-api
packages/python/plotly/plotly/validators/sunburst/marker/colorbar/_tickvals.py
Python
mit
483
0.00207
import _plotly_utils.basevalidators class TickvalsValidator(_plotly_utils.basevalidators.DataArrayValidator): def __init__( self, plotly_name="tickvals", parent_name="sunburst.marker.colorbar", **kwargs ): super(TickvalsValidator, self).__init__( plotly_name=plotly_name, ...
arent_name=parent_name, edit_type=kwargs.pop("edit_type", "colorbars"), role=kwargs.pop("role",
"data"), **kwargs )
pculka/SkyDrop
skydrop/utils/hex2bin/main.py
Python
gpl-2.0
2,182
0.017874
#!/usr/bin/python import sys import serial from intelhex impor
t IntelHex import time import datetime import struct def add8(a, b): return (a + b & 0xFF) page_size = 255 class Hex2BinConv(): def __init__(self, out): self.hex = IntelHex() self.out = out def load(self, filename): print
print "Loading application from hex" self.hex.loadfile(filename, "hex") size = self.hex.maxaddr() - self.hex.minaddr() print " size: %0.2f KiB (%d B)" % (size/1024, size) def conv(self, label): done = False adr = self.hex.minaddr() max_adr = sel...
dustymabe/ansible-modules-core
cloud/amazon/ec2_elb_lb.py
Python
gpl-3.0
52,548
0.002836
#!/usr/bin/python # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed...
load_balancer_port: 80 instance_port: 80 purge_listeners: no # Normally, this module will leave availability zones that are enabled # on the ELB alone. If purge_zones is true, then any extraneous zones # will be removed - local_action: module: ec2_elb_lb name: "test-please-delete" state: pres...
purge_zones: yes # Creates a ELB and
metpy/MetPy
v0.5/_downloads/GINI_Water_Vapor.py
Python
bsd-3-clause
1,923
0.00156
# Copyright (c) 2008-2016 MetPy Developers. # Distributed under the terms of the BSD 3-Clause License. # SPDX-License-Identifier: BSD-3-Clause """ GINI Water Vapor Imagery ======================== Use MetPy's support for GINI files to read in a water vapor satellite image and plot the data using CartoPy. """ import ca...
e data, (x, y) coordinates, and the projection # information. ds = f.to_dataset() x = ds.variables['x'][:] y = ds.variables['y'][:] dat = ds.variables['WV'] proj_var = ds.variables[dat.grid_mappin
g] print(proj_var) ########################################### # Create CartoPy projection information for the file globe = ccrs.Globe(ellipse='sphere', semimajor_axis=proj_var.earth_radius, semiminor_axis=proj_var.earth_radius) proj = ccrs.LambertConformal(central_longitude=proj_var.longitude_of_c...
ESOedX/edx-platform
lms/djangoapps/courseware/date_summary.py
Python
agpl-3.0
22,031
0.001997
""" This module provides date summary blocks for the Course Info page. Each block gives information about a particular course-run-specific date which will be displayed to the user. """ from __future__ import absolute_import import datetime import crum from babel.dates import format_timedelta from django.conf import s...
te_format=
'shortTime') def __repr__(self): return u'DateSummary: "{title}" {date} is_enabled={is_enabled}'.format( title=self.title, date=self.date, is_enabled=self.is_enabled ) class TodaysDate(DateSummary): """ Displays today's date. """ css_class = 'to...