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
dtrckd/pymake
pymake/util/math.py
Python
gpl-3.0
7,677
0.01029
# -*- coding: utf-8 -*- import numpy as np from numpy import ma import scipy as sp import networkx as nx from .utils import nxG from pymake import logger lgg = logger ########################## ### Stochastic Process ########################## def lognormalize(x): return np.exp(x - np.logaddexp.reduce(x)) def ...
################ ### Array routine Operation ########################## from collections import Counter def sorted
_perm(a, label=None, reverse=False): """ return sorted $a and the induced permutation. Inplace operation """ # np.asarray applied this tuple lead to error, if label is string # because a should be used as elementwise comparison if label is None: label = np.arange(a.shape[0]) hist, la...
zasdfgbnm/qutip
qutip/tests/test_wigner.py
Python
bsd-3-clause
6,312
0.000158
# This file is part of QuTiP: Quantum Toolbox in Python. # # Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: ...
=2) W_analytic = 2 / np.pi * (-1) ** n * \ np.exp(-2 * abs(a) ** 2) * np.polyval(laguerre(n), 4 * abs(a) ** 2) # check difference assert_(np.sum(abs(W_qutip - W_analytic)) < 1e-4) # check normalization assert_(np.sum(W_qutip) * dx * dy - 1.0 < 1e-8) assert_(...
m density matrices" xvec = np.linspace(-5.0, 5.0, 100) yvec = xvec X, Y = np.meshgrid(xvec, yvec) # a = X + 1j * Y # consistent with g=2 option to wigner function dx = xvec[1] - xvec[0] dy = yvec[1] - yvec[0] N = 15 for n in range(10): # try ten different random density ma...
inventree/InvenTree
InvenTree/InvenTree/fields.py
Python
mit
4,623
0.001298
""" Custom fields used in InvenTree """ # -*- coding: utf-8 -*- from __future__ import unicode_literals import sys from .validators import allowable_url_schemes from django.utils.translation import ugettext_lazy as _ from django.forms.fields import URLField as FormURLField from django.db import models as models fro...
laces) return value class RoundingDecimalFormField(forms.DecimalField): def to_python(self, value): value = super(RoundingDecimalFormField, self).to_python(value) value = round_decimal(value, self.decimal_places) return value def prepare_value(self, value): """ Ove...
. Why? It looks nice! """ if type(value) == Decimal: return InvenTree.helpers.normalize(value) else: return value class RoundingDecimalField(models.DecimalField): def to_python(self, value): value = super(RoundingDecimalField, self).to_python(value)...
axinging/chromium-crosswalk
tools/perf/measurements/task_execution_time.py
Python
bsd-3-clause
7,687
0.008846
# 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. from telemetry.page import legacy_page_test from telemetry.timeline.model import TimelineModel from telemetry.timeline import tracing_config from telemetry.u...
ks.values()) def _AddSlowestTasksToResults(self, tasks): sorted_tasks = sorted( tasks, key=lambda slice: slice.median_self_duration, reverse=True) for task in sorted_tasks[:self.GetExpectedResultCount()]: self._results.AddValue(scalar.ScalarValue( self._results.curren...
ues, metric_prefix): all_sectionstotal_duration = sum( section.total_duration for section in section_values) if not all_sectionstotal_duration: # Nothing was recorded, so early out. return for section in section_values: section_name = section.name or TaskExecutionTime.NORMAL_SECT...
CartoDB/cartoframes
tests/unit/data/observatory/catalog/test_variable_group.py
Python
bsd-3-clause
5,716
0.002274
import pandas as pd from unittest.mock import patch from cartoframes.data.observatory.catalog.entity import CatalogList from cartoframes.data.observatory.catalog.variable_group import VariableGroup from cartoframes.data.observatory.catalog.repository.variable_repo import VariableRepository from cartoframes.data.obser...
able_group_str == 'VariableGroup({d
ict_str})'.format(dict_str=str(db_variable_group1)) @patch.object(VariableGroupRepository, 'get_all') def test_get_all_variables_groups(self, mocked_repo): # Given mocked_repo.return_value = test_variables_groups # When variables_groups = VariableGroup.get_all() # Then...
vortex-ape/scikit-learn
sklearn/linear_model/tests/test_bayes.py
Python
bsd-3-clause
6,251
0
# Author: Alexandre Gramfort <[email protected]> # Fabian Pedregosa <[email protected]> # # License: BSD 3 clause import numpy as np from sklearn.utils.testing import assert_array_equal from sklearn.utils.testing import assert_array_almost_equal from sklearn.utils.testing import assert_almos...
e, the expected shape of `sigma_` is (1, 1). assert_equal(clf.sigma_.shape, (1, 1))
# Ensure that no error is thrown at prediction stage clf.predict(X, return_std=True) def test_toy_ard_object(): # Test BayesianRegression ARD classifier X = np.array([[1], [2], [3]]) Y = np.array([1, 2, 3]) clf = ARDRegression(compute_score=True) clf.fit(X, Y) # Check that the model coul...
Typecraft/norsourceparser
norsourceparser/__init__.py
Python
mit
126
0
# -*- coding: utf-8 -*- __author__ = """Tormod Haugland""" __ema
m' __version__ = '1.0.0-rc2'
lastweek/gem5
configs/spec2k6_classic/Caches.py
Python
bsd-3-clause
3,186
0.002511
# Copyright (c) 2006-2007 The Regents of The University of Michigan # 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 ...
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 POSSIBILITY OF SUCH
DAMAGE. # # Authors: Lisa Hsu from m5.objects import * class L1Cache(BaseCache): assoc = 2 block_size = 64 hit_latency = '3ns' response_latency = '1ns' mshrs = 10 tgts_per_mshr = 20 is_top_level = True def connectCPU(self, bus): self.mem_side = bus.slave class L1ICache(L1Cac...
olafhauk/mne-python
examples/visualization/plot_publication_figure.py
Python
bsd-3-clause
11,270
0
""" .. _ex-publication-figure: =================================== Make figures more publication ready =================================== In this example, we show several use cases to take MNE plots and customize them for a more publication-ready look. """ # Authors: Eric Larson <[email protected]> # ...
evoked, 'Left Auditory') evoked.pick_types(meg=
'grad').apply_baseline((None, 0.)) max_t = evoked.get_peak()[1] stc = mne.read_source_estimate(fname_stc) ############################################################################### # During interactive plotting, we might see figures like this: evoked.plot() stc.plot(views='lat', hemi='split', size=(800, 400), ...
denisbalyko/checkio-solution
count-inversions.py
Python
mit
619
0
def count_inversion(sequence): flag, answer, sequence = True, 0, list(sequence) while flag: flag = False for i in xrange(1, len(sequence)): if sequence[i-1] > sequence[i]: sequence[i], sequence[i-1] = sequence[i-1], sequence[i]
answer += 1 flag = True return answer def test_function(): assert count_inversion((1, 2, 5, 3, 4, 7, 6)) == 3, "Example" assert count_inversion((0, 1, 2, 3)) == 0, "Sorted" assert count_inversion((99, -99)) == 1, "Two numbers" assert count_inversion((5, 3, 2, 1, 0)) == 10, ...
sed"
devicehive/devicehive-python
devicehive/subscription.py
Python
apache-2.0
2,598
0.000385
# Copyright (C) 2018 DataArt # # 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, ...
ubscription does not exist.') def _get_subscription_type(self): raise NotImplementedError def subscribe(self): subscription = self._call(*self._args) self._id = subscription[self.ID_KEY] @property def id(self): return self._id def remove(self): self._ensur...
.subscription_id(self._id) api_request = ApiRequest(self._api) api_request.action('%s/unsubscribe' % self._get_subscription_type()) api_request.set('subscriptionId', self._id) api_request.remove_subscription_request(remove_subscription_api_request) api_request.execute('Unsubscrib...
iulian787/spack
var/spack/repos/builtin/packages/bcftools/package.py
Python
lgpl-2.1
3,898
0.002565
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) class Bcftools(AutotoolsPackage): """BCFtools is a set of utilities that manipulate variant calls in the Varia...
t BCF. All commands work transparently with both VCFs and BCFs, both uncompressed and BGZF-compressed.""" homepage = "http://samtools.github.io/bcftools/" url = "https://github.com/samtools/bcfto
ols/releases/download/1.3.1/bcftools-1.3.1.tar.bz2" version('1.10.2', sha256='f57301869d0055ce3b8e26d8ad880c0c1989bf25eaec8ea5db99b60e31354e2c') version('1.9', sha256='6f36d0e6f16ec4acf88649fb1565d443acf0ba40f25a9afd87f14d14d13070c8') version('1.8', sha256='4acbfd691f137742e0be63d09f516434f0faf617a5c60f466...
dmlc/tvm
apps/topi_recipe/gemm/gemm_int8.py
Python
apache-2.0
5,879
0.001531
# 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 u...
sure_option=measure_option, callbacks=[autotvm.callback.log_to_file(log_name)], ) dispatch_context = autotvm.apply_history_best(log_name)
best_config = dispatch_context.query(task.target, task.workload) print("\nBest config:") print(best_config) else: config = task.config_space.get(PRETUNED_INDEX) dispatch_context = autotvm.task.ApplyConfig(config) print("Using pretuned config:") print(config) ...
vardis/pano
src/pano/external/interactiveConsole/console.py
Python
mit
4,407
0.025414
# ----- # customConsoleClass # ----- # by Reto Spoerri # rspoerri AT nouser.org # http://www.nouser.org # ----- # wraps the interactiveConsole # ----- from shared import * from completer import completePython import sys, inspect from code import InteractiveConsole class FileCacher: "Cache the ...
spect.getsourcelines( %s )[0][0:6]" % pythonText ) if 'SyntaxError' in inspectString[1][0] or \ 'T
raceback' in inspectString[1][0] or \ len(inspectString) > 6: print "discarding inspect of %s l(%i): %s" % (pythonText, len(inspectString), inspectString) inspectString = None else: print "accepting inspect string %s" % inspectString inspectString = inspectString[1][0] ...
tensorflow/datasets
tensorflow_datasets/image/flic_test.py
Python
apache-2.0
1,130
0.006195
# coding=utf-8 # Copyright 2022 The TensorFlow Datasets 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 License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
(testing.DatasetBuilderTestCase): DATASET_CLASS = flic.Flic BUILDER_CONFIG_NAMES_TO_TEST = ["small"] SPLITS = { "train": 1, "test": 1, } class FlicTestFull(testing.DatasetBuilderTestCase): DATAS
ET_CLASS = flic.Flic BUILDER_CONFIG_NAMES_TO_TEST = ["full"] SPLITS = { "train": 1, "test": 1, } if __name__ == "__main__": testing.test_main()
bartoszj/Mallet
mallet/CFNetwork/NSCFBackgroundDownloadTask.py
Python
mit
2,176
0.005055
#! /usr/bin/env python # -*- coding: utf-8 -*- # The MIT License (MIT) # # Copyright (c) 2015 Bartosz Janda # # Permission is hereby granted, free of charge, to any person obtaining a copy of # this software and associated documentation files (the "Software"), to deal in # the Software without restriction, including w...
tive_value_function=SummaryBase.get_bool_value, summary_function=self.get_finished_summary) @staticmethod def get_finished_summary(value): if value: return "finish
ed" return None def summary_provider(value_obj, internal_dict): return helpers.generic_summary_provider(value_obj, internal_dict, NSCFBackgroundDownloadTaskSyntheticProvider)
googleads/google-ads-python
google/ads/googleads/v10/services/types/campaign_asset_service.py
Python
apache-2.0
6,424
0.000934
# -*- coding: utf-8 -*- # Copyright 2020 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...
remove (str): Remove operation: A resource name for the removed campaign asset is expected, in this format: ``customers/{customer_id}/campaignAssets/{campaign_id}~{asset_id}~{field_type}`` This field is a member of `oneof`_ ``operation``. """ update_mask...
ge=field_mask_pb2.FieldMask, ) create = proto.Field( proto.MESSAGE, number=1, oneof="operation", message=gagr_campaign_asset.CampaignAsset, ) update = proto.Field( proto.MESSAGE, number=3, oneof="operation", message=gagr_campaign_asset.Camp...
edublancas/titanic
pipeline/feature_extraction.py
Python
mit
1,081
0.012026
import pandas as pd import re df = pd.read_csv('data/combined_clean.csv', index_col='id') #Replace name wit title regex = '.*,{1}\s{1}([a-zA-Z\s]+)\.{1}.*' name_title = df.name.map(lambda name: re.search(regex, name).group(1)) df.name = name_title #Cabin with first letter prefix_cabin = df.cabin.map(lambda c: c[:1])...
ldren df['fam_mul_size'] = df.siblings_and_spouses * df.parents_and_children df['fare_mul_pclass'] = df.fare/df.p_class.astype(float) df['fare_mul_age'] = df.fare*df.age df['fare_div_age'] = df.fare/df.age.astype(float) df['pclass_mul_age'] = df.p_class*df.age.astype(float) df['pclass_div_age'] = df.p_class/df.age.ast...
('data/combined_with_features.csv')
popazerty/e2_sh4
lib/python/Screens/Standby.py
Python
gpl-2.0
9,640
0.028112
from Screens.Screen import Screen from Components.ActionMap import ActionMap from Components.config import config from Components.AVSwitch import AVSwitch from Components.SystemInfo import SystemInfo from GlobalActions import globalActionMap from enigma import eDVBVolumecontrol, eTimer, eServiceReference from boxbrandi...
next_rec_time = session.nav.RecordTimer.getNextRecordingTime() if len(jobs): reason = (ngettext("%d job is running in the background!", "%d jobs are running in the background!", len(jobs)) % len(job
s)) + '\n' if len(jobs) == 1: job = jobs[0] reason += "%s: %s (%d%%)\n" % (job.getStatustext(), job.name, int(100*job.progress/float(job.end))) else: reason += (_("%d jobs are running in the background!") % len(jobs)) + '\n' if inTimeshift: reason = _("You seem to be in timeshift!") + '\n' if r...
mfherbst/spack
var/spack/repos/builtin/packages/nnvm/package.py
Python
lgpl-2.1
1,955
0.000512
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, [email protected], All righ
ts reserved. # LLNL-CODE-647188 # # For details, see https://github.com/spack/spack # Please also see the LICENSE file for our notice and the LGPL. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License (as # published by the Free Software ...
UT ANY WARRANTY; without even the IMPLIED WARRANTY OF # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and # conditions of the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this program; if not, write to ...
willprice/arduino-sphere-project
scripts/example_direction_finder/temboo/Library/Foursquare/OAuth/FinalizeOAuth.py
Python
gpl-2.0
5,006
0.004994
# -*- coding: utf-8 -*- ############################################################################### # # FinalizeOAuth # Completes the OAuth process by retrieving a Foursquare access token for a user, after they have visited the authorization URL returned by the InitializeOAuth choreo and clicked "allow." # # Pytho...
plicable 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. # #
############################################################################### from temboo.core.choreography import Choreography from temboo.core.choreography import InputSet from temboo.core.choreography import ResultSet from temboo.core.choreography import ChoreographyExecution import json class FinalizeOAuth(Ch...
fametrano/BitcoinBlockchainTechnology
tests/mnemonic/test_entropy.py
Python
mit
10,702
0.000561
#!/usr/bin/env python3 # Copyright (C) 2017-2021 The btclib developers # # This file is part of btclib. It is subject to the license terms in the # LICENSE file found in the top-level directory of this distribution. # # No part of btclib including this file, may be copied, modified, propagated, # or distributed except...
int_entropy211) bytes_entropy216 = int_entropy211.to_bytes(27, byteorder="big", signed=False) entropy = bin_str_entropy_from_entropy(bytes_entropy216, 214) assert entropy == bin_str_entropy214 entropy = bin_str_entropy_from_entropy(bytes_entropy216, 216) assert entropy != bin_str_entropy216 e...
r, match=err_msg): bin_str_entropy_from_entropy(bytes_entropy216, 224) with pytest.raises(BTClibValueError, match=err_msg): bin_str_entropy_from_entropy(tuple()) # type: ignore with pytest.raises(ValueError): bin_str_entropy_from_int("not an int") # type: ignore with pytest.rais...
jamespcole/home-assistant
homeassistant/components/abode/camera.py
Python
apache-2.0
2,683
0
"""Support for Abode Security System cameras.""" from datetime import timedelta import logging import requests from homeassistant.components.camera import Camera from homeassistant.util import Throttle from . import DOMAIN as ABODE_DOMAIN, AbodeDevice DEPENDENCIES = ['abode'] MIN_TIME_BETWEEN_UPDATES = timedelta(s...
t_devices(generic_type=CONST.TYPE_CAMERA): if data.is_excluded(device): continue devices.append(AbodeCamera(data, device, TIMELINE.CAPTURE_IMAGE)) data.devices.extend(devices) add_entities(devices)
class AbodeCamera(AbodeDevice, Camera): """Representation of an Abode camera.""" def __init__(self, data, device, event): """Initialize the Abode device.""" AbodeDevice.__init__(self, data, device) Camera.__init__(self) self._event = event self._response = None asy...
colaftc/webtool
top/api/rest/RefundsReceiveGetRequest.py
Python
mit
506
0.033597
''' Created by auto_sdk on 2015.10.22 ''' from top.api.base import RestApi class RefundsReceiveGetRequest(RestApi):
def __init__(self,domain='gw.api.taobao.com',port=80): RestApi.__init__(self,domain, port) self.buyer_nick = None self.end_modified = None self.fields = None self.page_no = None self.page_size = None self.start_modified = None self.status = None self.type = None self.use_has_next = None ...
ame(self): return 'taobao.refunds.receive.get'
CaptainHayashi/lass
website/models/website_class.py
Python
gpl-2.0
2,747
0.000364
""" The singleton class that allows metadata and other attachables to be attached to the entire website. As the website at this level is one item of data rather than an entire model, we have to use a singleton class to attach metadata to it. """ from django.conf import settings from django.contrib.
sites.models import Site from metadata.models import PackageEntry, ImageMetadata, TextMetadata from metadata.mixins import MetadataSubjectMixin class Website(MetadataSubjectMixin): """ Class representing the website itself. This does not hold any data on its own, so in order to acquire a website obj...
quest object of the current page. :type request: HttpRequest :rtype: Website """ self.request = request self.pk = 1 # Needed for the metadata system def metadata_strands(self): return { "text": WebsiteTextMetadata.objects, "image": WebsiteIm...
rabipanda/tensorflow
tensorflow/contrib/boosted_trees/python/ops/batch_ops_utils.py
Python
apache-2.0
5,283
0.009654
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
return self.resource_handle.device, self.op def batch_runner_fn(self): return _scheduled_stamp_resource_op_runner def _move_tensors(tensors, device): """Moves a list of tensors to a device by concatenating/splitting them.""" # Reset the device setting to avoid weird interactions with device merging # l...
sor in tensors): with ops.device(tensors[0].device): values = array_ops.stack(tensors) with ops.device(device): return array_ops.unstack(values) else: with ops.device(tensors[0].device): sizes = array_ops.stack( [array_ops.shape(tensor)[0] for tensor in tensors]...
smalley/python
exercises/grade-school/grade_school_test.py
Python
mit
2,435
0.002053
import unittest from grade_school import School # Tests adapted from `problem-specifications//canonical-data.json` @ v1.0.0 class GradeSchoolTest(unittest.TestCase): def test_adding_a_student_adds_them_to_the_sorted_roster(self): school = School() school.add_student(name="Aimee", grade=2) ...
school.add_student(name="Bradley", grade=5) school.add_student(name="Jeff", grade=1) expected = ["Bradley", "Franklin"] self.assertEqual(school.grade(5), expected) def test_grade_returns_an_empty_list_if_there_are_no_students_in_that_grade(self): school = School() ex...
in()
interactiveaudiolab/nussl
tests/core/test_mixing.py
Python
mit
1,683
0.001188
import nussl import numpy as np import pytest def test_pan_audio_signal(mix_and_sources): mix, sources = mix_and_sources sources = list(sources.values()) panned_audio = nussl.mixing.pan_audio_signal(sources[0], -45) zeros = np.zero
s_like(panned_audio.audio_data[0])
sum_ch = np.sum(panned_audio.audio_data, axis=0) assert np.allclose(panned_audio.audio_data[1], zeros) assert np.allclose(panned_audio.audio_data[0], sum_ch) panned_audio = nussl.mixing.pan_audio_signal(sources[0], 45) zeros = np.zeros_like(panned_audio.audio_data[0]) sum_ch = np.sum(panned_audio....
jslag/gml
gml.py
Python
gpl-2.0
3,630
0.02259
#!/usr/bin/env python # # Copyright (C) 2004 Mark H. Lyon <[email protected]> # # This file is the Mbox & Maildir to Gmail Loader (GML). # # Mbox & Maildir to Gmail Loader (GML) is free software; you can redistribute # it and/or modify it under the terms of the GNU General Public License # as published by th...
b won't send auth info without this second ehlo after # starttls -- thanks to # http://bytes.com/top
ic/python/answers/475531-smtplib-authentication-required-error # for the tip server.ehlo() server.login(emailname_in, password_in) server.sendmail(msg.getaddr('From')[1], emailname_in, fullmsg) server.quit() count[0] = count[0] + 1 print " %d Forwarded a message from:...
bradleyayers/xhtml2pdf
xhtml2pdf/tags.py
Python
apache-2.0
20,336
0.004081
# -*- coding: utf-8 -*- from reportlab.graphics.barcode import createBarcodeDrawing from reportlab.lib.pagesizes import A4 from reportlab.lib.units import inch, mm from reportlab.platypus.doctemplate import NextPageTemplate, FrameBreak from reportlab.platypus.flowables import Spacer, HRFlowable, PageBreak, Flowable fro...
#frag.fontName = frag.bulletFontName = c.getFontName("helvetica") #frag.fontSize = c.frag.fontSize #c.frag.fontName = c.getFontName("helvetica") frag = copy.copy(c.frag) #print "###", c.frag.fontName #frag.fontName = "au_00" # c.getFontName("helvetica") #frag.bull...
_00" # c.getFontName("helvetica") self.offset = 0 if frag.listStyleImage is not None: frag.text = u"" f = frag.listStyleImage if f and (not f.notFound()): img = PmlImage( f.getData(), width=None, ...
zencoders/pyircbot
pyircbot.py
Python
gpl-2.0
2,596
0.014638
#! /usr/bin/env python # Copyright (c) 2013 sentenza """ A simple python-twisted IRC bot with greetings and karma functionalities Usage: $ python pyircbot.py --help """ import sys import optparse from config import ConfigManager from bot_core.bot_factory import BotFactory if __name__ == '__main__': config_man...
ptions.server_address config_manager.server_port = options.port config_manager.channel = options.channel config_manager.bot_nick = options.nick config_manager.verbose = options.verbose config_manager.greeting_probability = options.greeting_probability #if not options.<something>: # parse...
lp') if config_manager.verbose: print "Information will be stored in ", config_manager.data_path factory = BotFactory() factory.connect() factory.run()
jackrzhang/zulip
zerver/migrations/0187_userprofile_is_billing_admin.py
Python
apache-2.0
498
0
# -*- coding: utf-8 -*- # Generated by Django 1.11.14 on 2018-08-22 05:45 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('zerver', '0186_userprofile_starred_message_counts'), ] operations = [
migratio
ns.AddField( model_name='userprofile', name='is_billing_admin', field=models.BooleanField(db_index=True, default=False), ), ]
anomaly/prestans
prestans/provider/throttle.py
Python
bsd-3-clause
1,895
0.001583
# -*- coding: utf-8 -*- # # prestans, A WSGI compliant REST micro-framework # http://prestans.org # # Copyright (c) 2017, Anomaly Software Pty Ltd. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are...
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL ANOMALY SOFTWARE BE LIABLE FOR ANY # 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 # ...
open-synergy/opnsynid-hr
hr_attendance_computation/models/hr_attendance.py
Python
agpl-3.0
21,338
0.000703
# -*- coding: utf-8 -*- # Copyright 2011 Domsense srl (<http://www.domsense.com>) # Copyright 2011-15 Agile Business Group sagl (<http://www.agilebg.com>) # Copyright 2017 OpenSynergy Indonesia (<https://opensynergy-indonesia.com>) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from __future__ imp...
ins can't be greater than 60 # ==================================== # if mins >= 60.0: # hours = hours + 1 # mins = 0.0 float_time = "%02d:%02d" % (hours, mins) return
float_time def float_to_datetime(self, float_val): str_float = self.float_time_convert(float_val) hours = int(str_float.split(":")[0]) minutes = int(str_float.split(":")[1]) days = 1 if hours / 24 > 0: days += hours / 24 hours = hours % 24 ret...
agermanidis/Pattern
examples/01-web/05-flickr.py
Python
bsd-3-clause
1,296
0.006944
import os, sys; sys.path.append(os.path.join("..", "..", "..")) from pattern.web import Flickr, extension from pattern.web import RELEVANCY, LATEST, INTERESTING # Image sort order. from pattern.web import SMALL, MEDIUM, LAR
GE # Image size. # This example downloads an image from Flickr (http://flickr
.com). # Acquiring the image data takes three Flickr queries: # - the first query with Flickr.search() retrieves a list of results, # - the second query is executed behind the scenes in the FlickResult.url property, # - the third query downloads the actual image data using this URL. # It is a good idea to cache result...
abrt/satyr
tests/python/satyr.py
Python
gpl-2.0
215
0.004651
import sys import os.path oldpath = sys.path newpath = os.path.join(os.path.dirname(__file__), '../../python/.libs') sys.path = [newpath] f
rom _satyr3 impor
t * sys.path = oldpath del sys, os del oldpath, newpath
leonardoarroyo/django-google-address
google_address/api.py
Python
mit
692
0.011561
from google_address import helpers import requests class GoogleAddressApi(): url = 'https://maps.googleapis.com/maps/api/geocode/json?address={address}' key = None def __init__(self): # Set key self.key = helpers.get_settings().get("API_KEY", None) # Set language self.language = helpers.get_set...
rmat(url, self.language) return url def query(self, raw): url = self._get_url().format(address=raw) r = requests.get(url) data = r.
json() return data
nsh87/regressors
tests/test_regressors.py
Python
isc
9,685
0.00031
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_regressors --------------- Tests for the `regressors` module. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np import pandas as pd import u...
stats.residuals(ols, X, y, r_type='studentized') except Exception as e: self.fail("Testing studentized residuals failed unexpectedly: " "{0}".format(e)) class TestSummaryStats(uni
ttest.TestCase): def setUp(self): pass def tearDown(self): pass def test_error_not_raised_by_sse(self): # Test that assertion is not raise for supported models for classifier in _utils.supported_linear_models: clf = classifier() clf.fit(X, y) ...
bop/foundation
lib/python2.7/site-packages/compressor/utils/decorators.py
Python
gpl-2.0
2,549
0.002746
import functools class memoize(object): def __init__ (self, func): self.func = func def __call__ (self, *args, **kwargs): if (args, str(kwargs)) in self.__dict__: value = self.__dict__[args, str(kwargs)] else: value = self.func(*args, **kwargs) self...
return self try: return obj.__dict__[self.__name__] except KeyError: value = obj.__dict__[self.__name__] = self.__get(obj) return value def __set__(self, obj, value): if obj is None: return self
if self.__set is not None: value = self.__set(obj, value) obj.__dict__[self.__name__] = value def __delete__(self, obj): if obj is None: return self try: value = obj.__dict__.pop(self.__name__) except KeyError: pass els...
ntoll/fluiddb.py
fluiddb.py
Python
mit
5,024
0.000398
# -*- coding: utf-8 -*- """ A very thin wrapper on top of the FluidDB RESTful API Copyright (c) 2009-2010 Seo Sanghyeon, Nicholas Tollervey and others See README, AUTHORS and LICENSE for more information """ import sys import httplib2 import urllib import types if sys.version_info < (2, 6): import simplejson as ...
headers.copy() if custom_headers: headers.update(custom_headers) # make sure the path is a string for the following elif check for PUT # based requests if isinstance(path, list): path = '/'+'/'.join(path) # Make sure the correct content-type header is sent if isinstance(body, dic...
.upper() == 'PUT' and ( path.startswith('/objects/') or path.startswith('/about')): # A PUT to an "/objects/" or "/about/" resource means that we're # handling tag-values. Make sure we handle primitive/opaque value types # properly. if mime: # opaque value (just set t...
MobinRanjbar/hue
apps/oozie/src/oozie/views/dashboard.py
Python
apache-2.0
44,447
0.011047
#!/usr/bin/env python # Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. licenses this file # to you under the
Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless r
equired 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 json i...
bitedgeco/survivor-pool
survivor_pool/models/__init__.py
Python
mit
2,411
0.000415
# -*- coding: utf-8 -*- from __future__ import unicode_literals from sqlalchemy import engine_from_config from sqlalchemy.orm import sessionmaker from sqlalchemy.orm import configure_mappers import zope.sqlalchemy # import or define all models here to ensure they are attached to the # Base.metadata prior to any initia...
""" Initialize the model for a Pyramid app. Activate this setup using ``config.include('survivor-pool.models')``. """ settings = config.get_se
ttings() # use pyramid_tm to hook the transaction lifecycle to the request config.include('pyramid_tm') session_factory = get_session_factory(get_engine(settings)) config.registry['dbsession_factory'] = session_factory # make request.dbsession available for use in Pyramid config.add_request_m...
meahmadi/ThreeDHighway
Content/Scripts/FilmActor.py
Python
apache-2.0
767
0.059974
import unreal_engine as ue import json class FilmActor: def begin_play(self): self.pawn = self.uobject.get_owner() def getjson(self): ue.log("@@@@video getting json:") loc = self.uobject.get_actor_location() rot = self.uobject.get_actor_forward() data = { "x":loc.x,"y":loc.y,"z":loc.z, "rx":rot.x,...
t_actor_location() loc.x = data["x"] loc.y = dat
a["y"] loc.z = data["z"] self.uobject.set_actor_location(loc) rot = self.uobject.get_actor_forward() return True def tick(self, delta_time): pass
ajinabraham/YSO-Mobile-Security-Framework
mobsf/StaticAnalyzer/views/ios/macho_analysis.py
Python
gpl-3.0
9,156
0
# !/usr/bin/python # coding=utf-8 import logging import lief logger = logging.getLogger(__name__) class Checksec: def __init__(self, macho): self.macho = lief.parse(macho.as_posix()) def checksec(self): macho_dict = {} macho_dict['name'] = self.macho.name has_nx = self.has_n...
enable the ' '‘NX bit’ because it’s always ena
bled for all ' 'third-party code.') macho_dict['nx'] = { 'has_nx': has_nx, 'severity': severity, 'description': desc, } if has_pie: severity = 'info' desc = ( 'The binary is build with -fPIC flag which ' ...
idrogeno/IdroMips
lib/python/Plugins/SystemPlugins/WirelessLan/plugin.py
Python
gpl-2.0
16,367
0.025661
from enigma import eTimer, eEnv from Screens.Screen import Screen from Components.ActionMap import ActionMap, NumberActionMap from Components.Pixmap import Pixmap,MultiPixmap from Components.Label import Label from Components.Sources.StaticText import StaticText from Components.Sources.List import List from Components....
.append("HEX") config.plugins.wlan = ConfigSubsection() config.plugins.wlan.essid = NoSave(ConfigText(default = "", fixed_size = False)) config.plugins.wlan.hiddenessid = NoSave(ConfigYesNo(default = False
)) config.plugins.wlan.encryption = NoSave(ConfigSelection(list, default = "WPA2")) config.plugins.wlan.wepkeytype = NoSave(ConfigSelection(weplist, default = "ASCII")) config.plugins.wlan.psk = NoSave(ConfigPassword(default = "", fixed_size = False)) class WlanStatus(Screen): skin = """ <screen name="WlanStatus"...
mbohlool/client-python
kubernetes/test/test_v1beta1_subject_access_review_spec.py
Python
apache-2.0
1,077
0.004643
# coding: utf-8 """ Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v1.8.2 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import os import sys im...
ubjectAccessReviewSpec unit test stubs """ def setUp(self): pass def tearDown(self): pass def testV1beta1SubjectAccessReviewSpec(self): """ Test V1beta1SubjectAccessReviewSpec """ # FIXME: construct object with mandatory attributes with example values ...
rnetes.client.models.v1beta1_subject_access_review_spec.V1beta1SubjectAccessReviewSpec() pass if __name__ == '__main__': unittest.main()
megrela/flask-cms-control-panel
application/mongo_db/__init__.py
Python
mit
98
0
from
application import app from flask.ext.pymongo import PyMongo m
ongo = PyMongo(app, "MONGO")
AlexaProjects/Alexa2
ALEXA-IDE/core/user_files/alexa_ide/addins/plugins/alexatools/windowcropregion.py
Python
gpl-3.0
8,071
0.005823
# -*- coding: UTF-8 -*- # # Copyright (C) 2013 Alan Pipitone # # This file is part of Al'EXA-IDE. # # Al'EXA-IDE 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 o...
dth(1) pen.setBrush(Qt.red) pen.setCapStyle(Qt.RoundCap) pen.setJoinStyle(Qt.RoundJoin) else: pen.setWidth(1) pen.setStyle(Qt.SolidLine) #pen.setBrush(QColor(128, 128, 128, 255)) pen.setBrush(QBrush(QColor(0, 255, 0, 255))) ...
n(pen) paint.fillRect(self.mouseOldX + 1, self.mouseOldY + 1, center.x() - self.mouseOldX - 1, center.y() - self.mouseOldY - 1, QBrush(QColor(32, 178, 170, 100))) rect = QRect(self.mouseOldX, self.mouseOldY, center.x...
pymedusa/SickRage
ext/diskcache/__init__.py
Python
gpl-3.0
835
0.001198
"DiskCache: disk and file backed cache." from .core import Cache, Disk, UnknownFileWarning, EmptyDirWarning, Timeout from .core import DEFAULT_SETTINGS, EVICTION_POLICY from .fanout import FanoutCache from .persistent import Deque, Index __all__ = [ 'Cache', 'Disk',
'UnknownFileWarning', 'EmptyDirWarning', 'Timeout', 'DEFAULT_SETTINGS', 'EVICTION_POLICY', 'FanoutCache', 'Deque', 'Index', ] try: from .djangocache import DjangoCache # pylint: disable=wrong-import-position __all__.append('DjangoCache') except Exception: # pylint: disable=broad...
= 'diskcache' __version__ = '2.9.0' __build__ = 0x020900 __author__ = 'Grant Jenks' __license__ = 'Apache 2.0' __copyright__ = 'Copyright 2016 Grant Jenks'
terracoin/terracoin
qa/rpc-tests/txindex.py
Python
mit
2,703
0.0037
#!/usr/bin/env python3 # Copyright (c) 2014-2016 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 txindex generation and fetching # import time from test_framework.test_framework import Bitcoin...
lify("C5E4FB9171C22409809A3E8047A29C83886E325D") scriptPubKey = CScript([OP_DUP, OP_HASH160, addressHash, OP_EQUALVERIFY, OP_CHECKSIG]) unspent = self.nodes[0].listunspent()
tx = CTransaction() amount = unspent[0]["amount"] * 100000000 tx.vin = [CTxIn(COutPoint(int(unspent[0]["txid"], 16), unspent[0]["vout"]))] tx.vout = [CTxOut(amount, scriptPubKey)] tx.rehash() signed_tx = self.nodes[0].signrawtransaction(binascii.hexlify(tx.serialize()).dec...
alucryd/django-pkgbuild
django_pkgbuild/__init__.py
Python
gpl-3.0
59
0
default_app_c
onfig = 'django_pkgbuild.apps.Pkgbu
ildConfig'
w495/python-video-shot-detector
shot_detector/filters/compound/__init__.py
Python
bsd-3-clause
201
0
# -*- coding: utf8 -*- """ Compound
filters """ from __future__ import absolute_import, division, print_function from .mole_filter import mo
le_filter from .mole_filter import simple_mole_filter
karllessard/tensorflow
tensorflow/lite/testing/op_tests/equal.py
Python
apache-2.0
2,749
0.001819
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
he equal op testing graph.""" input_value1 = tf.compat.v1.placeholder( dtype=parameters["input_dtype"], name="input1", shape=parameters["input_shape_pair"][0]) input_value2 = tf.compat.v1.placeholder( dtype=parame
ters["input_dtype"], name="input2", shape=parameters["input_shape_pair"][1]) out = tf.equal(input_value1, input_value2) return [input_value1, input_value2], [out] def build_inputs(parameters, sess, inputs, outputs): input_value1 = create_tensor_data(parameters["input_dtype"], ...
netjunki/trac-Pygit2
trac/web/main.py
Python
bsd-3-clause
29,627
0.001586
# -*- coding: utf-8 -*- # # Copyright (C) 2005-2009 Edgewall Software # Copyright (C) 2005-2007 Christopher Lenz <[email protected]> # Copyright (C) 2005 Matthew Good <[email protected]> # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this ...
eb.href import Href from trac.web.session import Session #: This U
RL is used for semi-automatic bug reports (see #: `send_internal_error`). Please modify it to point to your own #: Trac instance if you distribute a patched version of Trac. default_tracker = 'http://trac.edgewall.org' class FakeSession(dict): sid = None def save(self): pass class FakePerm(dict): ...
ppecio/py-html-diff
pyhtmldiff/utils.py
Python
apache-2.0
518
0
# -*- coding: utf-8 -*- ""
"Created on 23.06.17 .. moduleauthor:: Paweł Pecio """ def longzip(a, b): """Like `izip` but yields `None` for missing items.""" aiter = iter(a) biter = iter(b) try: for
item1 in aiter: yield item1, next(biter) except StopIteration: for item1 in aiter: yield item1, None else: for item2 in biter: yield None, item2 def irepeat(a, b): biter = iter(b) for item in biter: yield a, item
joaovitorsilvestre/MongographQL
graphene_mongodb/mutation/__init__.py
Python
mit
2,026
0.003949
import graphene from graphene.utils.str_converters import to_snake_case from graphene_mongodb.query import mongo_to_graphene def gen_mutation(model, graphene_schema, operators_mutation, fields_mutation, mutate_func, validator): """ We need to create a class that seems as follows (http://docs.graphene-python.org/...
raise TypeError('Failed to resolve mutation of the schema {}' ' because mutate function must return a instance of {}, and the return type was {}.' .f
ormat(graphene_schema.__name__, model.__name__, type(obj))) graphene_obj = mongo_to_graphene(obj, graphene_schema, fields_mutation) return Create(**{to_snake_case(model.__name__): graphene_obj}) def generic_mutate(root, info, **kwargs): if validator: validator(model, kwargs, {}...
ray-project/ray
python/ray/tests/test_placement_group_mini_integration.py
Python
apache-2.0
4,294
0.000466
import pytest import sys import time from random import random try: import pytest_timeout except Imp
ortError: pytest_timeout = None import ray import ray.cluster_utils from ray._private.test_utils import wait_for_condition from ray.util.placement_group import placement_group, remove_placement_group def run_mini_integration_test(cluster, pg_removal=True, num_pgs=999): # This test checks the race condition b...
s a real bug. # It also runs 3 times to make sure the test consistently passes. # When 999 resource quantity is used, it fails about every other time # when the test was written. resource_quantity = num_pgs num_nodes = 5 custom_resources = {"pg_custom": resource_quantity} # Create pg that us...
ericrrichards/rpgEngine
RpgEngine/RpgEngine/Scripts/Main.py
Python
mit
1,809
0.012175
import math print "loaded script" #LoadScript("Map.py") LoadScript("Entity.py") LoadScript("StateMachine.py") LoadScript("WaitState.py") LoadScript("Util.py") LoadScript("Actions.py") LoadScript("Trigger.py") gTiledMap = TileMap.LoadMap("small_room.json") gMap = Map(gTiledMap) gMap.GotoTile(5,5) class Chara...
lf.Entity = entity self.Controller = StateMachine({ "wait": lambda: self.WaitState, "move": lambda: self.MoveState }) self.WaitState = WaitState(self, gMap) self.MoveState = MoveState(self, gMap) self.Controller.Change("wait", None) heroDef = EntityDef...
DownDoorTeleport = Actions.Teleport(gMap, 10, 11) gDownDoorTeleport(None, gHero.Entity) gTriggerTop = Trigger(gDownDoorTeleport, None, None) gTriggerBottom = Trigger(gUpDoorTeleport, None, None) gMap.AddTrigger(10, 12, gTriggerBottom) gMap.AddTrigger(11, 2, gTriggerTop) def Update(): dt = GetDeltaTime() pla...
blablacar/exabgp
lib/exabgp/dep/objgraph.py
Python
bsd-3-clause
31,092
0.000032
""" Tools for drawing Python object reference graphs with graphviz. You can find documentation online at http://mg.pov.lt/objgraph/ Copyright (c) 2008-2015 Marius Gedminas <[email protected]> and contributors Released under the MIT licence. """ # Permission is hereby granted, free of charge, to any person obtaining a # ...
, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABI...
THORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. import codecs import gc import re import inspect import types import operator...
dongguangming/requests-oauthlib
docs/conf.py
Python
isc
8,489
0.007186
# -*- coding: utf-8 -*- # # Requests-OAuthlib documentation build configuration file, created by # sphinx-quickstart on Fri May 10 11:49:01 2013. # # 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 fil...
e, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and modul
eauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message...
modulexcite/wal-e
wal_e/tar_partition.py
Python
bsd-3-clause
19,584
0.000306
#!/usr/bin/env python """ Converting a file tree into partitioned, space-contr
olled TAR files
. This module attempts to address the following problems: * Storing individual small files can be very time consuming because of per-file overhead. * It is desirable to maintain UNIX metadata on a file, and that's not always possible without boxing the file in another format, such as TAR. * Because multiple c...
muxiaobai/CourseExercises
python/kaggle/data-visual/plot%26seaborn.py
Python
gpl-2.0
2,005
0.011837
# coding: utf-8 # In[1]: import pandas as pd import matplotlib.pyplot as plt import numpy as np from pandas import Series,DataFrame import seaborn as sns # In[2]: #https://www.kaggle.com/residentmario/bivariate-plotting-with-pandas/data reviews = pd.read_csv("winemag-data_first150k.csv", index_col=0) reviews.h...
sns.boxplot(x='variety', y='points', data=df) plt.show() # #### Red Blend 比Chardonnay variety得分更高一点 # In[20]: sns.violinplot( x='varie
ty',y='points',data=reviews[reviews.variety.isin(reviews.variety.value_counts()[:5].index)]) plt.show()
HiSPARC/station-software
user/python/Lib/test/test_dis.py
Python
gpl-3.0
4,663
0.00193
# Minimal tests for dis module from test.test_support import run_unittest import unittest import sys import dis import StringIO def _f(a): print a return 1 dis_f = """\ %3d 0 LOAD_FAST 0 (a) 3 PRINT_ITEM 4 PRINT_NEWLINE %3d 5 LOAD_CONST ...
c_code.co_firstlineno + 3) def bug1333982(x=[]): assert 0, ([s for s in x] + 1) pass dis_bug1333982 = """\ %3d 0 LOAD_CONST 1 (0) 3 POP_JUMP_IF_TRUE 41 6 LOAD_GLOBAL 0 (AssertionError) 9 BUILD_LIST ...
2 LOAD_FAST 1 (s) 25 LIST_APPEND 2 28 JUMP_ABSOLUTE 16 %3d >> 31 LOAD_CONST 2 (1) 34 BINARY_ADD 35 CALL_FUNCTION 1 38 RAISE_VARARGS 1 %3d >> 41 LOAD_CONST ...
aaronsw/watchdog
vendor/rdflib-2.4.0/rdflib/plugin.py
Python
agpl-3.0
3,689
0.00244
from rdflib.store import Store from rdflib.syntax import serializer, serializers from rdflib.syntax import parsers from rdflib import sparql from rdflib.QueryResult import QueryResult _kinds = {} _adaptors = {} def register(name, kind, module_path, class_name): _module_info = _kinds.get(kind, None) if _module...
nd try: Adaptee = get(name, _adaptors[kind]) except Exception, e: raise Exception("could not get plugin for %s, %s: %s" % (name, kind, e)) def const(*args, **keywords): return Adaptor(Adaptee(*args, **keywords)) return const def register_adaptor(adapt...
er, parsers.Parser) register('rdf', serializers.Serializer, 'rdflib.syntax.serializers.XMLSerializer', 'XMLSerializer') register('xml', serializers.Serializer, 'rdflib.syntax.serializers.XMLSerializer', 'XMLSerializer') register('rdf/xml', serializers.Serializer, 'rdflib.syntax.serializer...
doptio/you-owe-it
yoi/authentication.py
Python
mit
215
0.004651
from flask import g, session from yoi.app import app @app.before_request def get_current_user(): if session.get('user_id'): g.user =
app.db.User.get(session['user_id']) els
e: g.user = None
realgam3/phantom-requests
setup.py
Python
apache-2.0
721
0
#!/usr/bin/env python from setuptools import setup setup( name='phantom-requests', version='0.0.1', description='Use PhantomJS As You Are U
sing Requests.', author='Tomer Zait (RealGame)', author_email='[email protected]', packages=['phantom_requests'], package_data={ 'phantom_requests': [
'ghostdriver/VERSION', 'ghostdriver/*.*', 'ghostdriver/src/*.*', 'ghostdriver/src/request_handlers/*.*', 'ghostdriver/src/third_party/*.*', 'ghostdriver/src/third_party/webdriver-atoms/*.*', ] }, install_requires=[ 'selenium >= ...
keithemiller/shell-scribe
shell-scribe.py
Python
apache-2.0
12,528
0.010536
#!/usr/bin/python """ .. module:: shellscribe Shell-Scribe run.py @author: Keith E. Miller <[email protected]> Expected issues: - cd command is shell-scribe specific so commands that use cd in a non-trivial way might break the cd command """ import cmd import os import sys import argparse as ap import datetime im...
outfile = os.popen(json_dict[str(x)]["command"]) output = outfile.read() return_val = outfile.close() if return_val != None: self.send_call() print '\033[93m' + "Output: ", os.popen(json_dict[str(x)]["command"]).read() + '\033[0m' ...
.write(line + "\n") def load_config_json(self): """ Configures Shell-Scribe based on the JSON configuration file """ with open(self.config_filename, 'r') as f: json_dict = json.load(f) #print "Dict from Json:", json_dict self.TWILIO = (1 == json_dict["tw...
puavo-org/puavo-os
parts/puavomenu/user_programs.py
Python
gpl-2.0
10,226
0.002543
# Loads, updates and maintains user programs import os import logging from pathlib import Path import time import threading import socket import utils import menudata import loaders.menudata_loader as menudata_loader import loaders.dotdesktop_loader class UserProgramsManager: def __init__(self, base_dir, langua...
rograms.items(): if isinstance(program, menudata.UserProgram): current.add(pid) for name in existing_keys.in
tersection(new_keys): if self.__file_cache[name]['modified'] != new_files[name]['modified'] or \ self.__file_cache[name]['size'] != new_files[name]['size']: changed.add(name) something_changed = False # Unload removed programs first. This way, if a .desktop f...
raj4/bigbang
bigbang/archive.py
Python
gpl-2.0
6,045
0.004632
import datetime import mailman import mailbox import numpy as np from bigbang.thread import Thread from bigbang.thread import Node import pandas as pd import pytz import utils def load(path): data = pd.read_csv(path) return Archive(data) class Archive: """ A representation of a mailing list archive...
series looking for maximal overlap counts = {} last = None last_i = None current = None def clean_footer(foot): return foot.strip() for b in srb: if last is None: last = b continue elif b is None: continue else: ...
) last = b if head in counts: counts[head] = counts[head] + 1 else: counts[head] = 1 last = b # reduce candidates that are strictly longer and less frequent # than most promising footer candidates for n,foot1 in sorted([(v,k) for...
simleo/openmicroscopy
components/tools/OmeroWeb/omeroweb/webadmin/views.py
Python
gpl-2.0
43,638
0.000229
#!/usr/bin/env python # -*- coding: utf-8 -*- # # # # Copyright (c) 2008-2014 University of Dundee. # # 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...
e']['email'] = request.session \ .get('server_settings', False) \ .get('email', False) ############################################################################## # utils import omero from omero.model import PermissionsI def prepar...
= conn.getObject("Experimenter", eid) defaultGroup = experimenter.getDefaultGroup() otherGroups = list(experimenter.getOtherGroups()) hasAvatar = conn.hasExperimenterPhoto() isLdapUser = experimenter.isLdapUser() return experimenter, defaultGroup, otherGroups, isLdapUser, hasAvatar def otherGroups...
LarryHillyer/PoolHost
PoolHost/pooltype/forms.py
Python
gpl-3.0
911
0.027442
from django import forms from django.forms import ModelForm from django.db import models from app.models import PoolType class PoolTypeForm_Create(ModelForm): name = forms.CharField(max_length = 100, label = 'Pool Type',
widget = forms.TextInput({ 'class':'form-control', 'placeholder': 'Enter Pool Type'})) class Meta: model
= PoolType fields = ['name'] class PoolTypeForm_Edit(ModelForm): id = forms.IntegerField(widget = forms.HiddenInput()) name = forms.CharField(max_length = 100, label = 'Pool Type', widget = forms.TextInput({ 'class':'form-control', ...
le717/Shutdown-Timer
constants.py
Python
gpl-3.0
937
0
# -*- coding: utf-8 -*- """Shutdown Timer - Small Windows shutdown timer. Created 2013, 2015 T
riangle717 <http://Triangle717.WordPress.com> Shutdown Timer 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. Shutdown Timer is distributed ...
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 Shutdown Timer. If not, see <http://www.gnu.org/licenses/>. """ import os import sys appName = "Shutdown Timer" version = "1.5" creator = "Triangle717" exeName =...
guillempalou/scikit-cv
skcv/video/segmentation/region_tracking.py
Python
bsd-3-clause
3,595
0.003338
import networkx as nx import numpy as np def bipartite_region_tracking(partition, optical_flow, reliability, matching_th=0.1, reliability_th=0.2): """ Parameters ---------- partition: numpy array A 3D label array where each label represents a region optical_flow: numpy arra...
continue if n not in matchings: px, py = np.where(partition[frame+1, ...] == n) new_partition[frame+1, px, py] = current_label + 1 current_label += 1 return new_partition
makiftasova/hangoutsbot
hangupsbot/plugins/forecast.py
Python
agpl-3.0
9,895
0.006975
""" Use DarkSky.net to get current weather forecast for a given location. Instructions: * Get an API key from https://darksky.net/dev/ * Store API key in config.json:forecast_api_key """ import logging import plugins import requests from decimal import Decimal logger = logging.getLogger(__name__) _internal = ...
on = ''.join(args).strip() if not location: yield from bot.coro_send_message(event.conv_id, _('No location was specified, please specify a location.')) return location = _lookup_address(location) if location is None: yield from bo
t.coro_send_message(event.conv_id, _('Unable to find the specified location.')) return if not bot.memory.exists(["conv_data", event.conv.id_]): bot.memory.set_by_path(['conv_data', event.conv.id_], {}) bot.memory.set_by_path(["conv_data", event.conv.id_, "default_weather_location"], {'lat'...
fuchsia-mirror/third_party-ninja
configure.py
Python
apache-2.0
22,852
0.001532
#!/usr/bin/env python # # Copyright 2001 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 require...
ar='TYPE', choices=profilers, help='enable profiling (' + '/'.join(profilers) + ')',) parser.add_option('--with-gtest', metavar='PATH', help='ignored') parser.add_option('--with-python', metavar='EXE', help='use EXE as the Python interpreter', defa...
('--force-pselect', action='store_true', help='ppoll() is used by default where available, ' 'but some platforms may need to use pselect instead',) (options, args) = parser.parse_args() if args: print('ERROR: extra unparsed command-line arguments:', args) sys.exit(1) pl...
ellisonbg/nbgrader
nbgrader/tests/preprocessors/test_savecells.py
Python
bsd-3-clause
11,442
0.000961
import pytest from nbformat.v4 import new_notebook from ...preprocessors import SaveCells from ...api import Gradebook from ...utils import compute_checksum from .base import BaseTestPreprocessor from .. import ( create_grade_cell, create_solution_cell, create_grade_and_solution_cell, create_locked_cell) @p...
_and_solution_cell(self, preprocessor, gradebook, resources): cell = create_grade_and_solution_cell("hello", "markdown", "foo", 1) cell.metadata.nbgrader['checksum'] = compute_checksum(cell) nb = new_notebook() nb.cells.append(cell) nb, resources = preprocessor.preprocess(nb, re...
"foo", "test", "ps0") assert grade_cell.max_score == 1 assert grade_cell.cell_type == "markdown" gradebook.find_solution_cell("foo", "test", "ps0") source_cell = gradebook.find_source_cell("foo", "test", "ps0") assert source_cell.source == "hello" assert source_cell.che...
akvo/akvo-rsr
akvo/rsr/models/partnership.py
Python
agpl-3.0
11,614
0.003186
# -*- coding: utf-8 -*- # Akvo RSR is covered by the GNU Affero General Public License. # See more details in the license.txt file located at the root folder of the Akvo RSR module. # For additional details on the GNU license please see < http://www.gnu.org/licenses/agpl.html >. import logging from typing import Type ...
from django.core.exception
s import ValidationError from django.apps import apps from django.db import models from django.db.models.signals import pre_save, pre_delete from django.dispatch import receiver from django.utils.translation import ugettext_lazy as _ import akvo.cache as akvo_cache from ..fields import ValidXMLCharField logger = logg...
sauloal/cnidaria
scripts/venv/lib/python2.7/site-packages/cogent/app/cd_hit.py
Python
mit
11,924
0.007716
#!/usr/bin/env python """Application controller for CD-HIT v3.1.1""" import shutil from os import remove from cogent.app.parameters import ValuedParameter from cogent.app.util import CommandLineApplication, ResultPath,\ get_tmp_filename from cogent.core.moltype import RNA, DNA, PROTEIN from cogent.core.alignme...
# alignment coverage for the shorter sequence, default 0.0 # if set to 0.9, the alignment must covers 90% of the sequenc
e '-aS':ValuedParameter('-',Name='aS',Delimiter=' '), # alignment coverage control for the shorter sequence, default 99999999 # if set to 60, and the length of the sequence is 400, # then the alignment must be >= 340 (400-60) residues '-AS':ValuedParameter('-',Name='AS',Delimite...
rcanepa/cs-fundamentals
python/tests/strings/test_msd_string_sort.py
Python
mit
1,284
0.000779
import unittest from strings.msd_string_sort import msd_sort class MSDSort(unittest.TestCase): def setUp(self): self.licenses = [ "4PGC938", "2IYE230", "3CI0720", "1ICK750", "1OHV845", "4JZY524", "1ICK750", "3C...
s_are_sorted(self): sorted_data = msd_sort(self.licenses) manually_sorted_data = sorted(self.licenses) self.assertEqual(sorted_data, manually_sorted_data) def test_variable_length_strings_are_sorted(self): sorted_data = msd_sort(self.unsorted_strings) manually_sorted_data = ...
h2oai/h2o-3
h2o-py/h2o/estimators/glrm.py
Python
apache-2.0
45,329
0.002537
#!/usr/bin/env python # -*- encoding: utf-8 -*- # # This file is auto-generated by h2o-3/h2o-bindings/bin/gen_python.py # Copyright 2016 H2O.ai; Apache License Version 2.0 (see LICENSE for details) # from __future__ import absolute_import, division, print_function, unicode_literals from h2o.estimators.estimator_base ...
s: int :param init_step_size: Initial step size Defaults to ``1.0``. :type init_step_size: float :param min_step_size: Minimum step size Defaults to ``0.0001``. :type min_step_size: float :param seed: RNG seed for initialization Defaul...
:type init: Literal["random", "svd", "plus_plus", "user"] :param svd_method: Method for computing SVD during initialization (Caution: Randomized is currently experimental and unstable) Defaults to ``"randomized"``. :type svd_method: Literal["gram_s_v_d", "power", "r...
aliyun/oss-ftp
python27/win32/Lib/site-packages/setuptools/svn_utils.py
Python
mit
18,855
0.00175
from __future__ import absolute_import import os import re import sys from distutils import log import xml.dom.pulldom import shlex import locale import codecs import unicodedata import warnings from setuptools.compat import unicode, PY2 from setuptools.py31compat import TemporaryDirectory from xml.sax.s...
or last depending on where #the URL falls if urlparse.urlsplit(line[-1])[0]: external = line[0] else: external = line[-1] external = decode_as_string(exter
nal, encoding="utf-8") externals.append(os.path.normpath(external)) return externals def parse_prop_file(filename, key): found = False f = open(filename, 'rt') data = '' try: for line in iter(f.readline, ''): # can't use direct iter! parts = line.split()...
dls-controls/dls_ade
dls_ade/dls_checkout_module_test.py
Python
apache-2.0
2,092
0.000478
#!/bin/env dls-python import unittest from dls_ade import dls_checkout_module from mock import patch, MagicMock class MakeParserTest(unittest.TestCase): def setUp(self): self.parser = dls_checkout_module.make_parser() @patch('dls_ade.dls_changes_since_release.ArgParser.add_branch_flag') def tes...
ame__ == '__main__':
# buffer option suppresses stdout generated from tested code unittest.main(buffer=True)
jxtech/wechatpy
tests/test_events.py
Python
mit
18,940
0.000371
# -*- coding: utf-8 -*- import unittest from datetime import datetime from wechatpy import parse_message class EventsTestCase(unittest.TestCase): def test_scan_code_push_event(self): from wechatpy.events import ScanCodePushEvent xml = """<xml> <ToUserName><![CDATA[gh_e136c6e50636]]></ToU...
![CDATA[weixin_media1]]></ToUserName>
<FromUserName><![CDATA[oDF3iYyVlek46AyTBbMRVV8VZVlI]]></FromUserName> <CreateTime>1398144192</CreateTime> <MsgType><![CDATA[event]]></MsgType> <Event><![CDATA[merchant_order]]></Event> <OrderId><![CDATA[test_order_id]]></OrderId> <OrderStatus>2</OrderStatus> <ProductId...
yuyangit/tornado
tornado/test/simple_httpclient_test.py
Python
apache-2.0
22,936
0.000523
from __future__ import absolute_import, division, print_function, with_statement import collections from contextlib import closing import errno import gzip import logging import os import re import socket import sys from tornado import gen from tornado.httpclient import AsyncHTTPClient from tornado.httputil import HT...
b"hello") stream.close() class EchoPostHandler(RequestHandler): def post(self): self.write(self.request.body) @stream_request_body class RespondInPrepareHand
ler(RequestHandler): def prepare(self): self.set_status(403) self.finish("forbidden") class SimpleHTTPClientTestMixin(object): def get_app(self): # callable objects to finish pending /trigger requests self.triggers = collections.deque() return Application([ ...
openhealthcare/gloss
sites/rfh/settings.py
Python
gpl-3.0
340
0.002941
DATABASE_STRING = 'postgresql://gloss:gloss@localhost/gloss_rfh' INFORMATION_SOURCE = 'sites.rfh.information_source.InformatinSourceOnTest' UPSTREAM_DB = dict( USERNAME="username", PASSWORD="password", IP_ADDRESS="192.1.1.1", DATABASE="some_database", TABLE_NAME="some table" ) from
site
s.rfh.local_settings import *
opencog/ros-behavior-scripting
sensors/audio_power.py
Python
agpl-3.0
1,713
0.008173
# # audio_power.py - Sound energy and power. # Copyright (C) 2016 Hanson Robotics # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your optio...
t even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin ...
port rospy from atomic_msgs import AtomicMsgs from hr_msgs.msg import audiodata ''' This implements a ROS node that subscribes to the `audio_sensors` topic, and passes the audio power data to the cogserver. This is used by OpenCog to react to loud sounds, sudden changes, and general background noise l...
uhavin/pubbd
tests/api/__init__.py
Python
mit
96
0
from a
pi import Api def full_url(resource): return Api.url_base.format(resource=resource
)
stormi/tsunami
src/secondaires/familier/masques/nom_familier/__init__.py
Python
bsd-3-clause
3,922
0.000255
# -*-coding:Utf-8 -* # Copyright (c) 2014 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...
import ErreurValidation class NomFamilier(Masque): """Masque <nom_familier>. On attend un nom unique de familier. Quand le joueur change le nom de son familier, il doit veiller à ce qu'il reste unique. """ nom = "nom_familier" nom_complet = "nom d'un familier" def __init__(self)...
"""Constructeur du masque""" Masque.__init__(self) self.proprietes["nouveau"] = "False" self.proprietes["salle_identique"] = "True" def init(self): """Initialisation des attributs""" self.nom_familier = "" self.familier = None def repartir(self, personnage, masq...
mmcdermo/RedLeader
redleader/resources/lambda.py
Python
apache-2.0
1,662
0.002407
from redleader.resources import Resource import botocore class LambdaFunctionResource(Resource): """ Resource modeling a Lambda FunctionArn """ def __init__(self, context, function_name, ): super(DynamoDBTableResource, self).__init__(context, cf_params) ...
te for this resource """ return { "Type" : "AWS::Lambda::Function", "Properties" : { "TableName": self._table_name, "AttributeDefinitions": attribute_definitions, "KeySchema": key_schema, "ProvisionedThroughput": { ...
lf._write_units } } } def resource_exists(self): client = self._context.get_client("dynamodb") try: desc = client.describe_table(TableName=self._table_name) return True except botocore.exceptions.ClientError as e: if "e...
znoland3/zachdemo
venvdir/lib/python3.4/site-packages/bs4/dammit.py
Python
mit
29,774
0.010428
# -*- coding: utf-8 -*- """Beautiful Soup bonus library: Unicode, Dammit This library converts a bytestream to Unicode through any means necessary. It is heavily based on code from Mark Pilgrim's Universal Feed Parser. It works best on XML and HTML, but it does not rewrite the XML or HTML to reflect a new encoding; th...
am value: A string to be substituted. The less-than sign will become &lt;, the greater-than sign will become &gt;,
and any ampersands will become &amp;. If you want ampersands that appear to be part of an entity definition to be left alone, use substitute_xml_containing_entities() instead. :param make_quoted_attribute: If True, then the string will be quoted, as befits an attribute value. ...
roaet/wafflehaus.nova
wafflehaus/nova/nova_base.py
Python
apache-2.0
1,330
0
# Copyright 2013 Openstack Foundation # 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 requ...
e specific language governing permissions and limitations # under the License. from nova import compute from wafflehaus.base import WafflehausBase class WafflehausNova(WafflehausBase): def _get_compute(self): return compute def __init__(self, application, conf): super(WafflehausNova, se...
ute = self._get_compute() def _get_context(self, request): """Mock target for testing.""" context = request.environ.get("nova.context") return context def _get_instance(self, context, server_id): """Mock target for testing.""" compute_api = self.compute.API() in...
gaolichuang/neutron-fwaas
neutron_fwaas/services/firewall/drivers/cisco/csr_firewall_svc_helper.py
Python
apache-2.0
10,054
0.000497
# Copyright 2014 Cisco Systems, 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 requir...
_process_firewall_pending_op(self, context, firewall_list): for firewall in firewall_list:
firewall_status = firewall['status'] if firewall_status == 'PENDING_CREATE': self._invoke_firewall_driver( context, firewall, 'create_firewall') elif firewall_status == 'PENDING_UPDATE': self._invoke_firewall_driver( con...
Adward-R/InfoVis
Wang/email_relations/jsonsplit.py
Python
apache-2.0
2,100
0.024286
#!/usr/bin/python # -*- coding: utf-8 -*- import copy import simplejson as json attrs = { 'BC' : 'BirthCountry', 'G' : 'Gender', 'CC' : 'CitizenshipCountry', 'CB' : 'CitizenshipBasis', 'PC' : 'PassportCountry', 'CETP' : 'CurrentEmploymentType', 'CETT' : 'CurrentEmploymentTitle', 'MSB' : 'MilitaryServic...
et']] else: continue key = str(new_link['source']) + '_' + str(new_link['target']) if count_table.has_key(key): count_table[key] += 1 else: count_table[key] = 0 for t in count_table.keys(): new_link = {} new_link['value'] = count_table[t] t = t.split('_') new_link['source'] = int(t[0]) new
_link['target'] = int(t[1]) new_links.append(new_link) # Handle the fucking nodes for key in attrs: clustering(nodes, key) outputfile = file('content.json', 'w') outputfile.write(json.dumps(content, indent = 2, sort_keys = True)) outputfile.close()
aronsky/home-assistant
tests/components/yamaha/test_media_player.py
Python
apache-2.0
5,828
0.00103
"""The tests for the Yamaha Media player platform.""" from unittest.mock import MagicMock, PropertyMock, call, patch import pytest import homeassistant.components.media_player as mp from homeassistant.components.yamaha import media_player as yamaha from homeassistant.components.yamaha.const import DOMAIN from homeass...
setup_host(hass, device, main_zone): """Test set up integration with host.""" assert await async_setup_component(hass, mp.DOMAIN, CONFIG) await hass.async_block_till_done() state = hass.states.get("media_player.yamaha_receiver_main_zone") assert state is not None assert state.state == "off" ...
async_setup_component( hass, mp.DOMAIN, {"media_player": {"platform": "yamaha"}} ) await hass.async_block_till_done() state = hass.states.get("media_player.yamaha_receiver_main_zone") assert state is not None assert state.state == "off" async def test_setup_discovery(hass, de...
nccgroup/Scout2
tools/gen-tests.py
Python
gpl-2.0
843
0.002372
#!/usr/bin/env python import os scout2_dir = 'AWSScout2' tests_dir = 'testsbase' for root, dirnames, filenames in os.walk(scout2_dir): for filename in filenames: if filename.startswith('__') or not filename.endswith('.py'): continue filepath = os.
path.join(root, filename) tmp = filepath.split('.')[0].split('/') print(str(tmp)) test = '# Import AWS utils\nfrom %s import *\n\n#\n# Test methods for %s\n#\n\nclass Test%sClass:\n\n' % ('.'.join(tmp), filepath, ''.join(t.title() for t in tmp))
test_filename = 'test-%s.py' % '-'.join(tmp[1:]) print('%s --> %s' % (filepath, test_filename)) test_file = os.path.join(tests_dir, test_filename) if not os.path.isfile(test_file): with open(test_file, 'w+') as f: f.write(test)
YorkJong/pyResourceLink
reslnk/myutil.py
Python
lgpl-3.0
4,850
0.002268
# -*- coding: utf-8 -*- """ This module put my utility functions """ __author__ = "Jiang Yu-Kuan <[email protected]>" __date__ = "2016/02/08 (initial version) ~ 2019/04/17 (last revision)" import re import os import sys #------------------------------------------------------------------------------ ...
ename(path): r"""Return a main name of a basename of a given file path. Example ------- >>> main_basename('c:\code\langconv\MsgID.h') 'MsgID.h' """ base = os.path.basename(path) base_main, _base_e
xt = os.path.splitext(base) return base_main #------------------------------------------------------------------------------ # Math #------------------------------------------------------------------------------ def is_numeric(str): try: _offset = int(eval(str)) except: return...
flensrocker/yavdr-python-buildserver
gh2lp.py
Python
gpl-2.0
16,587
0.003376
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from email.mime.text import MIMEText from http.server import BaseHTTPRequestHandler from http.server import HTTPServer from socketserver import ThreadingMixIn import argparse import ast import configparser import hashlib import hmac import datetime import json import os i...
vdr") self.name = get_from_args(args, "name") self.git_url = get_from_args(args, "git-url") self.branch = get_from_args(args, "branch", "master") self.urgency = get_from_args(args, "urgency", "medium") return def build(self): logfile = None package_name_versi...
irectory: ", tmpdir) os.chdir(tmpdir) # log the output to files logfile = open('build.log', 'w+b') if self.owner != self.config.github_owner: raise Exception("wrong owner: {OWNER} != {GHOWNER}".format(OWNER=self.owner, GHOWNER=self.config.github_owner)) ...
Cue/greplin-tornado-sendgrid
src/greplin/tornado/sendgrid.py
Python
apache-2.0
2,166
0.01108
# Copyright 2011 The greplin-tornado-sendgrid 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 License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law...
% (self._BASE_URL, self._FORMAT) post_body = urllib.urlencode(kwargs) http = httpclient.AsyncHTTPClient() r
equest = httpclient.HTTPRequest(api_url, method='POST', body=post_body) http.fetch(request, functools.partial(self._on_sendgrid_result, callback)) def _on_sendgrid_result(self, callback, result): """Parse out a result from SendGrid""" result = escape.json_decode(result.body) if result.get("errors"):...
thehajime/ns-3-dev
src/point-to-point/bindings/modulegen__gcc_LP64.py
Python
gpl-2.0
349,061
0.015158
from pybindgen import Module, FileCodeSink, param, retval, cppclass, typehandlers import pybindgen.settings import warnings class ErrorHandler(pybindgen.settings.ErrorHandler): def handle_error(self, wrapper, exception, traceback_): warnings.warn("exception %r in wrapper %s" % (exception, wrapper)) ...
## ipv4-address.h (module 'network'): ns3::Ipv4Address [class] module.add_class('Ipv4Address', import_from_module='ns.network') ## ipv4-address.h (module 'network'): ns3::Ipv4Address [class] root_module['ns3::Ipv4Address'].implicitly_converts_to(root_module['ns3::Address']) ## ipv4-address.h (modul...
lass('Ipv4Mask', import_from_module='ns.network') ## ipv6-address.h (module 'network'): ns3::Ipv6Address [class] module.add_class('Ipv6Address', import_from_module='ns.network') ## ipv6-address.h (module 'network'): ns3::Ipv6Address [class] root_module['ns3::Ipv6Address'].implicitly_converts_to(root_mod...
inveniosoftware/invenio-records-rest
invenio_records_rest/config.py
Python
mit
13,214
0
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2016-2019 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Invenio-Records-REST configuration.""" from __future__ import absolute_import, pr...
ME`) to valid mimetypes for records search serializers: dict(alias -> mimetype). :param search_type: Name of the search type used when searching records. :param suggesters: Suggester fields configuration. Any element of the dictionary represents a suggestion field. For ea
ch suggestion field we can optionally specify the source filtering (appropriate for ES5) by using ``_source``. The key