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
daniestevez/gr-satellites
python/qa_crc.py
Python
gpl-3.0
6,774
0
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright 2022 Daniel Estevez <daniel@destevez.net> # # This file is part of gr-satellites # # SPDX-License-Identifier: GPL-3.0-or-later # from gnuradio import gr, blocks, gr_unittest import numpy as np import pmt # bootstrap satellites module, even from build dir try...
_basic_block()._post(pmt.intern('in'), self.pdu) crc_append_block.to_basic_block()._post( pmt.intern('system'), pmt.cons(pmt.intern('done'), pmt.from_long(1))) self.tb.start() self.tb.wait() def test_crc_check(self): """Test a successful CRC check Ch...
al(self.dbg.num_messages(), 1) out = pmt.u8vector_elements(pmt.cdr(self.dbg.get_message(0))) self.assertEqual(out, self.data) self.assertEqual(self.dbg_fail.num_messages(), 0) def test_crc_check_header_bytes(self): """Test a successful CRC check (skipping some header bytes) ...
vmanoria/bluemix-hue-filebrowser
update-hue-ini.py
Python
gpl-2.0
1,829
0.02515
## update-hue-ini.py ## ## This script will extract the appropriate IBM Analytics for Apache Hadoop credentials from the VCAP_SERVICES ## environment variable inside a running container. It will add the username and password to the hue.ini file ## so that the hue application has access to a specific instance import s...
rt json username = None password = None webhdfsurl = None srcfile = sys.argv[1] destfile = sys.argv[2] if "VCAP_SERVICES" in os.environ: vcaps = json.loads(os.environ["VCAP_SERVICES"]) if "Analytics for
Apache Hadoop" in vcaps: username = vcaps["Analytics for Apache Hadoop"][0]["credentials"]["userid"] password = vcaps["Analytics for Apache Hadoop"][0]["credentials"]["password"] webhdfsurl = vcaps["Analytics for Apache Hadoop"][0]["credentials"]["WebhdfsUrl"] else: if "WEBHDFS_USER" in os.environ: ...
blackball/an-test6
util/usnob_get_region.py
Python
gpl-2.0
3,265
0.033691
#! /usr/bin/env python from urllib2 import urlopen from urllib import urlencode from urlparse import urlparse, urljoin import os.path from numpy import * from astrometry.util.file import * from astrometry.util.usnob_get_image import * from optparse import OptionParser if __name__ == '__main__': parser = OptionPa...
n... #dists = [distsq_between_radecs(r,d, (opt.ralo+opt.rahi)/2., (opt.declo+opt.dechi)/2.) # for (r,d) in radecs] dists = distsq_between_radecs(radecs[:,0], radecs[:,1], (opt.ralo+opt.rahi)/2., (opt.declo+opt.dechi)/2.) order = argsort(dists) for (ra,dec) in radecs[order]: (jpeg,fits) = get_usnob_i...
rue) print 'got jpeg urls:', jpeg print 'got fits urls:', fits if opt.plate is None: keepjpeg = jpeg keepfits = fits else: keepjpeg = [u for u in jpeg if opt.plate in u] keepfits = [u for u in fits if opt.plate in u] print 'keep jpeg urls:', keepjpeg print 'keep fits urls:', keepfits base = ...
endlessm/chromium-browser
tools/swarming_client/third_party/infra_libs/infra_types/__init__.py
Python
bsd-3-clause
327
0
# 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 infra_libs.infra_types.infra_types import freeze from infra_libs.infra_type
s.infra_types import thaw from infra_libs.infra_types.infra_types import FrozenDict
CianciuStyles/project-euler
011.py
Python
mit
1,763
0.028361
import time def check_vertical(matrix): max_product = 0 for row in xrange(0, len(matrix)-3): for col in xrange(0, len(matrix)): product = matrix[row][col] * matrix[row+1][col] * matrix[row+2][col] * matrix[row+3][col] max_product = max(product, max_product) return max_product def check_horizontal(matrix)...
xrange(0, len(matrix)-3): for col in xrange(0, len(matrix)-3): product = matrix[row][col] * matrix[row+1][col+1] * matrix[row+2][col+2] * matrix[row+3][col+3] max_product = max(product, max_product) return max_product def check_right_diagonal(matrix): max_product = 0 for row in xrange(0, len(matrix)-3): ...
ax(product, max_product) return max_product def main(): with open("011.txt", "r") as f: # Read the matrix from the text file, and store in an integet 2-dimensional array matrix = [] for line in f.readlines(): matrix.append([int(num) for num in line.split(" ")]) # print matrix # Check the matrix along ...
pombredanne/flagon
src/flagon/status_api/__init__.py
Python
mit
3,360
0
# The MIT License (MIT) # # Copyright (c) 2014 Steve Milner # # 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 without limitation the # rights to use, copy, modi...
knownFeatureError class FlagonStatusAPI(object): """ Simple Flag status read-only REST api. """ _url_map = Map([ Rule('/v0/<flag>', endpoint='flag_status') ]) def __init__(sel
f, backend): """ Creates the API object. Requires a pre-configured backend. """ self._backend = backend def wsgi_app(self, environ, start_response): """ The WSGI App entry point. """ request = Request(environ) response = self.dispatch_request(...
MattNolanLab/ei-attractor
grid_cell_model/simulations/common/simulation_stationary.py
Python
gpl-3.0
3,476
0.000575
'''Main simulation run: Simulation of a stationary bump.''' from __future__ import absolute_import, print_function, division from numpy.random import choice from nest.hl_api import NESTError from grid_cell_model.models.parameters import getOptParser from grid_cell_model.models.gc_net_nest import BasicGridCellNetwork ...
= DictDat
aSet(data) stats_visitor_e = SpikeStatsVisitor("spikeMon_e", forceUpdate=False) ac_visitor = AutoCorrelationVisitor(monName, stateList, forceUpdate=False) stats_visitor_e.visitDictDataSet(dummy_data_set) ac_visitor.visitDictDataSet(dummy_data_set) # Clean the state monitor data['stateMonF_e'] ...
ffunenga/virtuallinks
tests/core/test_installing.py
Python
mit
2,693
0
import pytest import os import shutil import core virtuallinks = core.import_package('virtuallinks') def setup_function(function): shutil.rmtree('temporary', ignore_errors=True) os.mkdir('temporary') os.chdir('temporary') def teardown_function(function): os.chdir('..') shutil.rmtree('temporar...
onitor('open') out, err = capsys.readouterr() assert out == '' assert err == '' virtuallinks.unmonitor('open') virtuallinks.disable_inspector() def _test_monitor_inspector_interleaved_0(capsys): virtuallinks.monitor('open') virtuallinks.enable_inspector() virtuallinks.unmonitor('open')...
ks.disable_inspector() with open('file.txt', 'w') as f: f.write('') assert os.path.exists('file.txt') assert os.path.isfile('file.txt') def test_monitor_inspector_interleaved_1(capsys): virtuallinks.monitor('open') virtuallinks.enable_inspector() virtuallinks.unmonitor('open') with...
stefanbraun-private/pyVisiToolkit
src/trend/datasource/trendfile.py
Python
gpl-3.0
49,022
0.023622
#!/usr/bin/env python # encoding: utf-8 """ trend.datasource.trendfile.py Handling and parsing of trendfiles (*.hdb) Copyright (C) 2016/2017 Stefan Braun 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 Foundat...
DBData else: # using ProMoS NT(c) version 2.x curr_DBData_class = DBData2 nof_dbdata_elems = (filesize - TRENDDATA_OFFSET) / ctypes.sizeof(curr_DBData_class) class Trendfile_structure(ctypes.LittleEndianStructure): """ Header contains DMS datapoint name, data section contains
all DBData elements, amount depends on filesize... """ # contains some hints from http://stackoverflow.com/questions/18536182/parsing-binary-data-into-ctypes-structure-object-via-readinto _fields_ = [ ("dmsDatapoint", ctypes.c_char * DMSDP_NOF_BYTES), # DMS datapoint name ("UNKNOWN...
FRidh/python-acoustics
tests/test_decibel.py
Python
bsd-3-clause
451
0.019956
fr
om acoustics.decibel i
mport * def test_dbsum(): assert(abs(dbsum([10.0, 10.0]) - 13.0103) < 1e-5) def test_dbmean(): assert(dbmean([10.0, 10.0]) == 10.0) def test_dbadd(): assert(abs(dbadd(10.0, 10.0) - 13.0103) < 1e-5) def test_dbsub(): assert(abs(dbsub(13.0103, 10.0) - 10.0) < 1e-5) def test_dbmul(): assert(ab...
yeyanchao/calibre
setup/publish.py
Python
gpl-3.0
3,819
0.008117
#!/usr/bin/env python # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai from __future__ import with_statement __license__ = 'GPL v3' __copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' import os, shutil, subprocess, glob from setup import Command, __appname__, __versio...
subprocess.check_call(['sphinx-build', '-b', 'myepub', '-d', '.build/doctrees', '.', '.build/epub'])
subprocess.check_call(['sphinx-build', '-b', 'mylatex', '-d', '.build/doctrees', '.', '.build/latex']) pwd = os.getcwdu() os.chdir('.build/latex') subprocess.check_call(['make', 'all-pdf'], stdout=open(os.devnull, 'wb')) ...
SecWiki/windows-kernel-exploits
MS11-080/CVE-2011-2005.py
Python
mit
12,217
0.014161
################################################################################ ######### MS11-080 - CVE-2011-2005 Afd.sys Privilege Escalation Exploit ######## ######### Author: ryujin@offsec.com - Matteo Memelli ######## ######### Spaghetti & Pwnsauce ##...
ate 28/11/2011" WSAGetLastError = windll.Ws2_32.WSAGetLastError
WSAGetLastError.argtypes = () WSAGetLastError.restype = c_int SOCKET = c_int WSASocket = windll.Ws2_32.WSASocketA WSASocket.argtypes = (c_int, c_int, c_int, c_void_p, c_uint, DWORD) WSASocket.restype = SOCKET closesocket = windll.Ws2_32.closesocket clos...
Faggioni/powerlab
setup.py
Python
mit
405
0.004938
from setuptools import setup setup(name='powerlab', version='0.1', description='Power System Tools', url='https://github.com/Faggioni/powerlab', author='Miguel Faggioni', auth
or_email='migu
elfaggioni@gmail.com', license='MIT', packages=['powerlab'], install_requires=[ 'numpy', ], entry_points= { }, zip_safe=False)
mjirik/dicom2fem
setup.py
Python
bsd-3-clause
3,561
0.000842
from setuptools import setup, find_packages # Always prefer setuptools over distutils from os import path here = path.abspath(path.dirname(__file__)) setup( name='dicom2fem', description='Generation of finite element meshes from DICOM images', long_desctioption="Generation of finite element meshes using c...
=[('my_data', ['data/data_file'])], # To provide executable scripts, use entry points in preference to the # "scripts" keyword. Entry points provide cross-platform support and allow # pip to create the appropriate form of executable for the target platform. # entry_points={ # 'console_scripts':...
)
DanteOnline/free-art
venv/lib/python3.4/site-packages/PIL/ImageTransform.py
Python
gpl-3.0
2,878
0
# # The Python Imaging Library. # $Id$ # # transform wrappers # # History: # 2002-04-08 fl Created # # Copyright (c) 2002 by Secret Labs AB # Copyright (c) 2002 by Fredrik Lundh # # See the README file for information on usage and redistribution. # from PIL import Image class Transform(Image.ImageTransformHandler)...
, d, e, f) which contain the first two rows from an affine transform matrix. For each pixel (x, y) in the output image, the new value is taken from a position (a x + b y + c, d x + e y + f) in the input image, rounded to nearest pixel. This function can be used to scale, translate, rotate, and shear th...
matrix A 6-tuple (a, b, c, d, e, f) containing the first two rows from an affine transform matrix. @see Image#Image.transform """ method = Image.AFFINE class ExtentTransform(Transform): """ Define a transform to extract a subregion from an image. Maps a rectangle (defined by two corn...
Chibuzor-IN/python-paystack
python_paystack/objects/plans.py
Python
mit
1,566
0.001916
''' plans.py ''' from forex_python.converter import CurrencyCodes from .base import Base class Plan(Base): ''' Plan class for making payment plans ''' interval = None name = None amount = None plan_code = None currency = None id = None send_sms = True send_invoices = True ...
) try: amount = int(amount) except ValueError: raise ValueError("Invalid amount") else: self.interval = interval.lower() self.name = name self.interval = interval self.amount = amount self.currency = currenc...
= send_sms self.send_invoices = send_invoices self.description = description def __str__(self): return "%s plan" % self.name
SerSamgy/PhotoLoader
manage.py
Python
mit
254
0
#!/usr/bin/env pyt
hon import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MOD
ULE", "PhotoLoader.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
XanderXAJ/mastercardConvert
mastercardConvert.py
Python
gpl-3.0
2,462
0.004874
#!/usr/bin/env python import argparse import logging from functools import partial from domain import date, transaction # Parse command line arguments parser = argparse.ArgumentParser(description="Convert currency using MasterCard exchange rates", epilog='If no date is specified, the...
card currency, e.g. GBP, USD, JPY') parser.add_argument('-d', '--date', help='Day the exchange was made in format YYYY-MM-DD. Only today and yesterday appear to be supported by MasterCard. Defaults to most recent day with rates.') parser.add_argument('--log_level', help='Set logging level'
, default='WARNING', type=str.upper, choices=['CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG']) parser.add_argument('-t', '--today', action='store_true', help='Use today\'s exchange rates. This may error if today\'s rates have not been uploaded') parser.add_ar...
mRokita/DPLib
dplib/parse.py
Python
agpl-3.0
3,545
0.005079
# DPLib - Asynchronous bot framework for Digital Paint: Paintball 2 servers # Copyright (C) 2017 Michał Rokita # # 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 L...
" CHAR_TAB = ['\0', '-', '-', '-', '_', '*', 't', '.', 'N', '-', '\n', '#', '.', '>', '*', '*', '[', ']', '@', '@', '@', '@', '@', '@', '<', '>', '.', '-', '*', '-', '-', '-', ' ', '!', '\"', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/', '0', '1', '2', '3', '4',...
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '[', '\\', ']', '^', '_', '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '{', '|', '}', '~', '<', '(', '=', ')', '^', ...
ztane/zsos
userland/lib/python2.5/ctypes/test/test_slicing.py
Python
gpl-3.0
3,845
0.00156
import unittest from ctypes import * import _ctypes_test class SlicesTestCase(unittest.TestCase): def test_getslice_cint(self): a = (c_int * 100)(*xrange(1100, 1200)) b = range(1100, 1200) self.failUnlessEqual(a[0:2], b[0:2]) self.failUnlessEqual(len(a), len(b)) self.failUn...
ame size self.assertRaises(ValueError, setslice, a, 0, 5, range(32)) def test_char_ptr(self): s = "abcdefghijklmnopqrstuvwxyz" dll = CDLL(_ctypes_test.__file__) dll.my_strdup.restype = POINTER(c_char) dll.my_free.restype = None res = dll.my_
strdup(s) self.failUnlessEqual(res[:len(s)], s) import operator self.assertRaises(TypeError, operator.setslice, res, 0, 5, u"abcde") dll.my_free(res) dll.my_strdup.restype = POINTER(c_byte) res = dll.my_strdup(s) self.failUnlessEqual(re...
avalentino/PyTables
tables/indexes.py
Python
bsd-3-clause
5,884
0
"""Here is defined the IndexArray class.""" from bisect import bisect_left, bisect_right from .node import NotLoggedMixin from .carray import CArray from .earray import EArray from . import indexesextension # Declarations for inheriting class CacheArray(indexesextension.CacheArray, NotLoggedMixin, EArray): ""...
hi = self.shape[1] ranges = self._v_parent.rvcache boundscache = self.boundscache # First, look at the beginning of the slice begin = ranges[nrow, 0] # Look for items at the beginning of sorted slices if item1 <= begin: result1 = 0 if item2 < beg...
0 and result2 >= 0: return (result1, result2) # Then, look for items at the end of the sorted slice end = ranges[nrow, 1] if result1 < 0: if item1 > end: result1 = hi if result2 < 0: if item2 >= end: result2 = hi ...
lmzintgraf/MultiMAuS
experiments/run_multimaus.py
Python
mit
2,970
0.001684
from authenticators.simple_authenticators import RandomAuthenticator, \ HeuristicAuthenticator, OracleAuthenticator, NeverSecondAuthenticator, \ AlwaysSecondAuthenticator from simulator import parameters from simulator.transaction_model import TransactionModel from experiments import rewards import numpy as np ...
== 'random': return RandomAuthenticator() elif auth_type == 'heuristic': return HeuristicAuthenticator(50) elif auth_type
== 'oracle': return OracleAuthenticator() elif auth_type == 'never_second': return NeverSecondAuthenticator() elif auth_type == 'always_second': return AlwaysSecondAuthenticator() if __name__ == '__main__': run_single()
devdattakulkarni/test-solum
solum/tests/api/handlers/test_workflow.py
Python
apache-2.0
4,365
0.000229
# -*- coding: utf-8 -*- # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. Yo
u may obtain # a copy of the License at # # http://www.apache.org/li
censes/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # un...
google/fedjax
fedjax/fedjax_test.py
Python
apache-2.0
1,219
0.003281
# 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 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 th...
chopmann/warehouse
warehouse/i18n/translations.py
Python
apache-2.0
2,912
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 # distributed under the Li...
tra = "" if self.plural is not None: extra = " plural={!r} n={!r}".format(self.plural, self.n) return "<TranslationString: message_id={!r}{}>".format( self.messa
ge_id, extra, ) def __mod__(self, mapping): if not isinstance(mapping, collections.abc.Mapping): raise TypeError("Only mappings are supported.") vals = self.mapping.copy() vals.update(mapping) return TranslationString( self.message_id, s...
Serchcode/cvirtual
manage.py
Python
gpl-3.0
806
0
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "cvirtual.settings") try:
from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other
# exceptions on Python 2. try: import django except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a...
Alt90/Student_progress_bar
achievement/migrations/0001_initial.py
Python
mit
819
0.003745
# -*- coding: utf-8 -*- # Generat
ed by Djan
go 1.10.6 on 2017-03-15 16:12 from __future__ import unicode_literals import django.core.validators from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Student', ...
dfleury/fairu
setup.py
Python
gpl-3.0
2,511
0.018319
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys from setuptools import setup from fairu import __version__ def packages(): packages = [] for root, dirnames, filenames in os.walk('fairu'): if '__init__.py' in filenames: packages.append(".".join(os.path.split(root)).str...
imported: setuptools " "extensions not available") else: command_hook = "distutils.commands" ENTRY_POINTS[command_hook] = [] from commands import coverage_analysis if coverage_analysis.COVERAGE_ANALYSIS_AVAILABLE: ENTRY_POINTS[command_hook].appe...
"lysis:CoverageAnalysis") return ENTRY_POINTS def get_setup_config(): from ConfigParser import ConfigParser config = ConfigParser() config.read('setup.cfg') def get_setup_config(): return config return config if __name__ == '__main__': setup...
ap--/python-seabreeze
src/seabreeze/pyseabreeze/features/databuffer.py
Python
mit
1,040
0
from seabreeze.pyseabreeze.features._base import SeaBreezeFe
ature # Definition # ========== # # TODO: This feature needs to be implemented for
pyseabreeze # class SeaBreezeDataBufferFeature(SeaBreezeFeature): identifier = "data_buffer" def clear(self) -> None: raise NotImplementedError("implement in derived class") def remove_oldest_spectra(self, number_of_spectra: int) -> None: raise NotImplementedError("implement in derived cla...
sssundar/NetworkSimulator
Code/Python/unit_test_benches.py
Python
gpl-2.0
12,927
0.044403
# Working Unit Test Benches for Network Simulator # Last Revised: 14 November 2015 by Sushant Sundaresh & Sith Domrongkitchaiporn ''' IMPORTANT: Please turn off logging (MEASUREMENT_ENABLE = False) in constants.py before running these testbenches. ''' # Unit Testing Framework import unittest # Test Modules import r...
et ID Ask flow to receive the same packet again, should get same result. ''' sim = "" # event simulator f = "" # flow, data source, static n = "" # test node def setUp (self): self.f = flow.Data_Sink("f1sink","h2","h1",\ 3*constants.DATA_PACKET_BITWIDTH, 1.0) self.n = Static_Data_Sink_Test_Node ("h...
packets = [ packet.Packet("f1source","h1","h2","",0,0), \ packet.Packet("f1source","h1","h2","",1,0)] self.n.receive(packets[0]) self.assertEqual(self.n.head_of_tx_buff(),0) self.n.receive(packets[1]) self.assertEqual(self.n.head_of_tx_buff(),1) # Two packets received, two packets acknowledged with se...
YannickDieter/testbeam_analysis
testbeam_analysis/examples/eutelescope.py
Python
mit
14,587
0.001303
''' Example script to run a full analysis on telescope data. The original data can be found in the example folder of the EUTelescope framework. Data in https://github.com/eutelescope/eutelescope/tree/v1.0-tag/jobsub/examples/datura-150mm-DAF The residuals are calculated with different cuts on prealigned a...
# Generate filenames for cluster data input_cluster_files = [os.path.splitext(data_file)[0] + '_clustered.h5' for data_file in data_files] # Correlate the row / col
umn of each DUT dut_alignment.correlate_cluster(input_cluster_files=input_cluster_files, output_correlation_file=os.path.join( output_folder, 'Correlation.h5'), n_pixels=n_pixels, ...
Micronaet/micronaet-migration
sale_exchange/__init__.py
Python
agpl-3.0
1,139
0.002634
# -*- coding: utf-8 -*- ############################################################################### # # ODOO (ex OpenERP) # Open Source Management Solution # Copyright (C) 2001-2015 Micronaet S.r.l. (<http://www.micronaet.it>) # Developer: Nicola Riolini @thebrush (<https://it.linkedin.com/in/thebrush>) # This pro...
ANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the GNU Affero General Public Lice
nse for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################### from . import exchange # vim:expandtab:smartindent:tabstop=4:soft...
aewallin/openvoronoi
python_examples/spike_1.py
Python
lgpl-2.1
4,238
0.001416
import openvoronoi as ovd import ovdvtk import time import vtk import datetime import math import random import os import sys import pickle import gzip if __name__ == "__main__": # w=2500 # h=1500 # w=1920 # h=1080 w = 1024 h = 1024 myscreen = ovdvtk.VTKScreen(width=w, height=h) ovdvt...
# print " ",2*Nmax," point-sites sites took {0:.3f}".format(times[0])," seconds, {0:.2f}".format( 1e6*float( times[0] )/(float(2*Nmax)*float(math.log10(2*Nmax))) ) ,"us/n*log(n)" print "all point sites inserted. ", vd.check() # nsegs = Nmax # nsegs = 5 #Nmax # n=1 t_before = time.time() ...
list[1], id_list[2]) # vd.check() # vd.addLineSite( id_list[2], id_list[3]) # vd.check() # vd.debug_on() # vd.addLineSite( id_list[3], id_list[4]) # vd.check() vd.debug_on() vd.addLineSite(id_list[4], id_list[1], 10) # FIXME spikes are not allowed, so this does not complete OK # ...
relic7/prodimages
python/DirWatchManager.py
Python
mit
15,047
0.009238
#!/usr/bin/env python # #To familiarize yourself with pyinotify, run a first example like this: # # # $ cd pyinotify-x-x-x && python setup.py build # # $ python src/pyinotify/pyinotify.py -v my-dir-to-watch # # # Let's start a more detailed example. Say, we want to monitor the temp directory '/tmp' and all its subdire...
s not mandatory wm.rm_watch(wdd[watchdir]) ### #### Note that its subdirectories (if any) are still being watched. If we wanted to remove '/tmp' and all the watches on its sudirectories, we could have done like that: #### wm.rm_watch(wdd[watchdir], rec=True) wm.rm_watch(wdd.values()) notifier.sto...
n, next, we can add, update or remove watches on files or directories with the same principles. ## The only remaining important task is to stop the thread when we wish stop monitoring, it will automatically destroy the inotify's instance. Call the following method: # The EventsCodes Class top # Edited Sun, 26 Nov 2...
linea-it/dri
api/userquery/email.py
Python
gpl-3.0
519
0.007707
""" send mail with html template """ import logging from django.template.loader import render
_to_string from common.notify import Notify class Email: def __init__(self): self.logger = logging.getLogger('userquery') def send(self,
data): self.logger.info("Sending mail by template %s" % data["template"]) subject = "UserQuery - %s" % data["subject"] body = render_to_string(data["template"], data) Notify().send_email(subject, body, data["email"])
obi-two/Rebelion
data/scripts/templates/object/tangible/lair/base/shared_poi_all_lair_thicket_large_evil_fire_red.py
Python
mit
468
0.047009
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE
THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = T
angible() result.template = "object/tangible/lair/base/shared_poi_all_lair_thicket_large_evil_fire_red.iff" result.attribute_template_id = -1 result.stfName("lair_n","thicket") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
supermikol/coursera
Data Structures/Week 1/check_brackets_in_code/check_brackets.py
Python
mit
1,323
0.005291
# python3 import sys class Bracket: def __init__(self, bracket_type, position): self.bracket_type = bracket_type self.position = position def Match(self, c): if self.bracket_type == '[' and c == ']': return True if self.bracket_type == '{' and c == '}':...
match = True if next == '(' or next == '[' or next == '{': # Process opening bracket, write your code here opening_brackets_stack.append(Bracket(next,i)) index.append(i+1) if next == ')' or next == ']' or next == '}':
if len(opening_brackets_stack) == 0 or opening_brackets_stack.pop().Match(next) == False: match = False index.append(i+1) break index.pop() # Process closing bracket, write your code here # Printing answer, write your code h...
graveljp/smugcli
smugcli/terminal_size.py
Python
mit
2,716
0.002577
#!/usr/bin/env python # Source: https://gist.github.com/jtriley/1108174 import os import shlex import struct import platform import subprocess def get_terminal_size(): """ getTerminalSize() - get width and height of console - works on linux,os x,windows,cygwin(windows) originally retrieved from: ...
s, rows) except: pass def _get_terminal_size_linux(): def ioctl_GWINSZ(fd): try: import fcntl import termios cr = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ, '1234')) return cr except: ...
r = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2) if not cr: try: fd = os.open(os.ctermid(), os.O_RDONLY) cr = ioctl_GWINSZ(fd) os.close(fd) except: pass if not cr: try: cr = (os.environ['LINES'], os.environ['COLUMNS']) ...
dirkjot/pingpongcam
opencv/exploration-3.py
Python
gpl-3.0
8,044
0.010816
# coding: utf-8 # Given code that can extract the contents of the inner rectangles (boxes), we can determine whether the # contents have changed. # # Here, take an image of the previous box and see whether the same contents are still there. The idea is that # a name does not only get erased, it may also be replac...
") empty = cv2.morphologyEx(empty, cv2.MORPH_OPEN, kernel) empty = cv2.cvtColor(empty, cv2.COLOR_BGR2GRAY) #empty = cv2.adaptiveThreshold(empty, 160, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 5, 2) plt.imshow(np.concatenate([writing1,writing2,empty])) #plt.imshow(writing1) #writing1.shape, writing2.shape, em
pty.shape # In[5]: writingb, contoursb = get_content1("../reference/frame274.png") writingb = cv2.morphologyEx(writingb, cv2.MORPH_OPEN, kernel) writingb = cv2.cvtColor(writingb, cv2.COLOR_BGR2GRAY) writingc, contoursc = get_content1("../reference/frame275.png") writingc = cv2.morphologyEx(writingc, cv2.MORPH_OPEN,...
BTCX/BTCX_blockchain
btcxblockchainapi/btcrpc/utils/btc_rpc_call.py
Python
mit
3,371
0.009789
from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException from btcrpc.utils.config_file_reader import ConfigFileReader import json import socket, errno from btcrpc.utils.log import * log = get_log("BTCRPCCall:") class BTCRPCCall(object): def __init__(self, wallet="receive", currency="btc"): yml_conf...
# return simplejson.dumps ({u'error' : u'txid is not valid'}) return None
def do_list_transactions(self, account, count=10, from_index=0): try: return self.access.listtransactions(account, count, from_index) except RuntimeError: print("calling failure") def do_get_transaction(self, tx_id): try: return self.access.gettransaction(tx_id) exce...
snyaggarwal/oclapi
ocl/test_helper/base.py
Python
mpl-2.0
10,616
0.004333
import random import string from collection.models import CollectionVersion, Collection from concepts.models import Concept, ConceptVersion, LocalizedText from oclapi.models import ACCESS_TYPE_EDIT, ACCESS_TYPE_VIEW from orgs.models import Organization from sources.models import Source, SourceVersion from users.model...
ction_type='Dictionary', public_access=ACCESS_TYPE_EDIT, default_locale='en', supported_locales=['en'], website='www.collection2.com',
description='This is the second test collection', custom_validation_schema=validation_schema ) kwargs = { 'parent_resource': UserProfile.objects.get(user=user) } Collection.persist_new(collection, user, **kwargs) return Collection.objects.get(id=collection.id) def creat...
jhutar/spacewalk
client/tools/rhncfg/actions/script.py
Python
gpl-2.0
9,141
0.002297
# # Copyright (c) 2008--2016 Red Hat, Inc. # # This software is licensed to you under the GNU General Public License, # version 2 (GPLv2). There is NO WARRANTY for this software, express or # implied, including the implied warranties of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. You should have received a c...
tors (including pipe since it's duped) for i in range(3, MAXFD): try: os.close(i) except: pass # all scripts initial working directory will be / # puts burden on script writer to ensure cwd is correct within the # script os...
g.gr_gid for g in grp.getgrall() if username in g.gr_mem or username in g.gr_name] os.setgroups(groups) os.setuid(uid) # give this its own process group (which happens to be equal to its # pid) os.setpgrp() # Finally, exec the script try: os.umask(in...
Dev-Cloud-Platform/Dev-Cloud
dev_cloud/cc1/src/wi/tests/cm_networks_test.py
Python
apache-2.0
4,435
0.00203
# -*- coding: utf-8 -*- # @COPYRIGHT_begin # # Copyright [2010-2014] Institute of Nuclear Physics PAN, Krakow, Poland # # 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.apac...
r = self.driver self.base_url =
self.TEST_SERVER self.login_testuser(self.TEST_admin_cm) self.login_cm_testuser() driver.get(self.base_url + "/admin_cm/pools/") self.wait_for_text("//table[@id='item-list']/tbody", ["10.10.127.0"]) self.menu_click("Address", "10.10.127.0", "Unlock") self.wait_for_t...
michaelkuty/python-app-loader
tests/testapp1/urls.py
Python
bsd-3-clause
73
0
from app_loade
r import app_loader urlpatterns = app_loader.urlpatt
erns
haystack/eyebrowse-server
common/management/commands/remove_duplicate_history.py
Python
mit
949
0
from django.core.management.base import NoArgsCommand from django.contrib.auth.models import User from api.models import EyeHistory class Command(NoArgsCommand): help = 'Detects and removes duplicated history entries' def handle(self, **options): self.stdout.write('Beginning update...\n') us...
f.stdout.write('Deletin
g: %s\n' % item) obj.delete()
ChugR/qpid-dispatch
python/qpid_dispatch_internal/router/link.py
Python
apache-2.0
3,006
0.002329
# # Licensed to the Apache Software Foundation (ASF) under one # or more contribu
tor 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...
y 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. # from .data import...
toomoresuch/pysonengine
parts/gaeunit/sample_app/model.py
Python
mit
92
0.021739
from google.app
engine.ext import db class MyEntity(db.Model): name = db.StringPropert
y()
shodoco/bcc
tests/python/test_tracepoint.py
Python
apache-2.0
2,128
0.00282
#!/usr/bin/env python # Copyright (c) Sasha Goldshtein # Licensed under the Apache License, Version 2.0 (the "License") import bcc import unittest from time import sleep import distutils.version import os import subprocess def kernel_version_ge(major, minor): # True if running kernel is >= X.Y version = distu...
n False if minor and version[1] < minor: return False return True @unittest.skipUnless(kernel_version_ge(4,7), "requires kernel >= 4.7") class TestTracepoint(unittest.TestCase): def test_tracepoint(self): text = """ BPF_HASH(switches
, u32, u64); TRACEPOINT_PROBE(sched, sched_switch) { u64 val = 0; u32 pid = args->next_pid; u64 *existing = switches.lookup_or_init(&pid, &val); (*existing)++; return 0; } """ b = bcc.BPF(text=text) sleep(1) tota...
ezigman/sftf
UserAgentBasicTestSuite/case207.py
Python
gpl-2.0
3,360
0.018155
# # Copyright (C) 2004 SIPfoundry Inc. # Licensed by SIPfoundry under the GPL license. # # Copyright (C) 2004 SIP Forum # Licensed to SIPfoundry under a Contributor Agreement. # # # This file is part of SIP Forum User Agent Basic Test Suite which # belongs to the SIP Forum Test Framework. # # SIP Forum User Agent Basic...
elf.createRequest("INVITE") cl = inv.getParsedHeaderValue("Content-Length") cl.length = 9999 inv.setHeaderValue("Content-Length", cl.create()) self.writeMessageToNetwork(self.neh, inv) self.code = 0 while (self.code <= 200): repl = self.readReplyFromNetwork(self.neh) if (repl
is not None) and (repl.code > self.code): self.code = repl.code elif repl is None: self.code = 999 if repl is None: self.addResult(TestCase.TC_FAILED, "missing reply on request") self.neh.closeSock() def onDefaultCode(self, message): if message.code > self.code: self.code = message.code i...
Leits/openprocurement.api.encryprion
openprocurement/api/encryprion/utils.py
Python
apache-2.0
1,144
0
import libnacl.secret import libnacl.utils from StringIO import
StringIO from .response import FileObjResponse from pyramid.httpexceptions import HTTPBadRequest def generate_secret_key(): return libnacl.utils.salsa_key().encode('hex') def encrypt_file(key, fileobj, nonce=None)
: if nonce is None: nonce = libnacl.utils.rand_nonce() box = libnacl.secret.SecretBox(key.decode('hex')) encrypted = box.encrypt(fileobj.read(), nonce) return StringIO(encrypted) def decrypt_file(key, fileobj): box = libnacl.secret.SecretBox(key.decode('hex')) decrypted = box.decrypt(f...
pvarenik/PyCourses
allure-python-master/tests/test_attach.py
Python
gpl-2.0
2,550
0.002402
# encoding: utf-8 ''' Tests for various attachment thingies Created on Oct 21, 2013 @author: pupssman ''' import pytest from hamcrest import has_entries, assert_that, is_, contains, has_property from allure.constants import AttachmentType from allure.utils import all_of @pytest.mark.parametrize('package', ['pytes...
decode('utf-8'), is_(u'ололо пыщьпыщь')) def test_broken_unicode(self, attach_contents): assert_that(attach_contents(u'ололо пыщьпыщь'.encode('cp1251')), is_(u'ололо пыщьпыщь'.encode('cp1251'))) def test_attach_in_fixtu
re_teardown(report_for): """ Check that calling ``pytest.allure.attach`` in fixture teardown works and attaches it there. """ report = report_for(""" import pytest @pytest.yield_fixture(scope='function') def myfix(): yield pytest.allure.attach('Foo', 'Bar') def test_x(m...
the-zebulan/CodeWars
katas/beta/how_sexy_is_your_name.py
Python
mit
566
0
SCORES = {'A': 100, 'B': 14, 'C': 9, 'D': 28, 'E': 1
45, 'F': 12, 'G': 3, 'H': 10, 'I': 200, 'J': 100, 'K': 114, 'L': 100, 'M': 25, 'N': 450, 'O': 80, 'P': 2, 'Q': 12, 'R': 400, 'S': 113, 'T': 405, 'U': 11, 'V': 10
, 'W': 10, 'X': 3, 'Y': 210, 'Z': 23} def sexy_name(name): name_score = sum(SCORES.get(a, 0) for a in name.upper()) if name_score >= 600: return 'THE ULTIMATE SEXIEST' elif name_score >= 301: return 'VERY SEXY' elif name_score >= 60: return 'PRETTY SEXY' return 'NOT TOO SEX...
aaivazis/nautilus
tests/services/test_service.py
Python
mit
2,991
0.003678
# external imports import unittest # local imports import nautilus from nautilus.api.endpoints import GraphQLRequestHandler from ..util import Mock class TestUtil(unittest.TestCase): def setUp(self): # create a service without an explict name class MyService(nautilus.Service): pass # save ...
right request handler class" ) def test_can_summarize(self): # the target summary target = { 'name': 'myService', } # summarize the service summarized = self.service().summarize() # make sure the names m
atch up assert target['name'] == summarized['name'], ( "Summarzied service did not have the right name." )
nickdrozd/ecio-lisp
fileio.py
Python
mit
581
0.003442
import json from stats import read_stats @read_stats def read_file(file_name, default='"?"'): try:
file = open(file_name, 'r') except FileNotFoundError: print('Creating file {}'.format(file_name)) file = open(file_name, 'w+') file.write(default) contents = json.loads(file.read()) file.close() return contents def write_file(file_name, data, indent=4): with open(f...
+') as file: file.write( json.dumps( data, sort_keys=True, indent=indent))
YunoHost/moulinette-yunohost
src/yunohost/tests/test_appscatalog.py
Python
agpl-3.0
9,247
0.001406
import os import pytest import requests import requests_mock import glob import shutil from moulinette import m18n from moulinette.utils.filesystem import read_json, write_to_json, write_to_yaml from yunohost.utils.error import YunohostError from yunohost.app import ( _initialize_apps_catalog_system, _read_ap...
assert "foo" in app_dict.keys() assert "bar" in app_dict.keys() def test_apps_catalog_load_with_conflicts_between_lists(mocker): # Initialize ... _initialize_apps_catalog_system() conf = [ {"id": "default", "url": APPS_CATALOG_DEFAULT_URL}, { "id": "default2", ...
write_to_yaml(APPS_CATALOG_CONF, conf) # Update with requests_mock.Mocker() as m: # Mock the server response with a dummy apps catalog # + the same apps catalog for the second list m.register_uri("GET", APPS_CATALOG_DEFAULT_URL_FULL, text=DUMMY_APP_CATALOG) m.register_uri( ...
Jacques-Florence/schedSim
src/analysis/reward.py
Python
bsd-3-clause
847
0.022432
#!/usr/bin/env python import matplotlib.pyplot as plt import sys import numpy from math import floor def movingAverage(x, N): cumsum = numpy.cumsum(numpy.insert(x, 0, 0)) return (cumsum[N:] - cumsum[:-N])/N filename = "reports/configuration.confrewardRecordReport.txt" if (len(sys.argv) > 1): filename = sys.argv[1]...
ine.split(":") time.append(float(entry[0])) temp.appen
d(float(entry[1])) windowSize = 100 avg = [0] * (windowSize - 1) avg = avg + list( movingAverage(temp, windowSize)) ratio = 0.999 avg = avg[int(floor(len(avg )*ratio)): len(avg )-1] time = time[int(floor(len(time)*ratio)): len(time)-1] temp = temp[int(floor(len(temp)*ratio)): len(temp)-1] plt.plot(time, temp, '...
akarol/cfme_tests
cfme/cloud/security_groups.py
Python
gpl-2.0
8,515
0.001292
# -*- coding: utf-8 -*- import attr from navmazing import NavigateToAttribute, NavigateToSibling from widgetastic.widget import View, Select from widgetastic_manageiq import ( Accordion, BaseEntitiesView, BootstrapSelect, BreadCrumb, ItemsToolBarViewSelector, ManageIQTree, SummaryTable, Text, TextInput) from w...
opdown, Bu
tton from cfme.base.ui import BaseLoggedInPage from cfme.exceptions import ItemNotFound, SecurityGroupsNotFound from cfme.modeling.base import BaseCollection, BaseEntity from cfme.utils.appliance.implementations.ui import navigate_to, navigator, CFMENavigateStep from cfme.utils.blockers import BZ from cfme.utils.wait ...
markm541374/gpbo
gpbo/core/config.py
Python
agpl-3.0
19,809
0.01575
import gpbo xrange=range from gpbo.core import GPdc as GPdc import scipy as sp class eimledefault(): """ fixed s, space is [-1,1]^D """ def __init__(self,f,D,n,s,path,fname): self.aqfn = gpbo.core.acquisitions.EIMAPaq self.aqpara= { 'ev': {'s': s, 'd': [sp.NaN]}, ...
'everyn':1 } self.ojfchar = {'dx': len(self.aqpara['lb']), 'dev': len(self.aqpara['ev'])} self.ojf=f self.path = path
self.fname = fname return class eihypgamma(eihypdefault): def __init__(self,*args,**kwargs): super(eihypgamma,self).__init__(*args,**kwargs) D = len(self.aqpara['lb']) self.reccpara['kindex']=self.aqpara['kindex']= GPdc.MAT52 self.reccpara['mprior']=self.aqpara['mpr...
kth-ros-pkg/hfts_grasp_planner
src/hfts_grasp_planner/rrt.py
Python
bsd-3-clause
28,198
0.003511
#!/usr/bin/env python """ This is a draft modification of the RRT algorithm for the sepcial case that sampling the goal region is computationally expensive """ import random import numpy import time import math import logging import copy from rtree import index class SampleData: def __init__(self, config, d...
r words, both the parent and all children of nodeB become children of nodeA. Labeled nodes of tree B will be added as labeled nodes of tree A. Runtime: O(size(otherTree) * num_labeled_nodes(otherTree)) @param merge_node_a The node of this tree where to attach otherTree ...
ree The other tree (is not changed) @param merge_node_b The node of tree B that is merged with mergeNodeA from this tree. @return The root of treeB as a TreeNode of treeA after the merge. """ node_stack = [(merge_node_a, merge_node_b, None)] b_root_node_in_a = None ...
swtp1v07/Savu
savu/plugins/scikitimage_filter_back_projection.py
Python
apache-2.0
3,515
0
import logging from savu.plugins.base_recon import BaseRecon from savu.data.process_data import CitationInfomration from savu.plugins.cpu_plugin import CpuPlugin import skimage.transform as transform import numpy as np from scipy import ndimage class ScikitimageFilterBackProjection(BaseRecon, CpuPlugin): """ ...
e_of_rotation_shift) def reconstruct(self, sinogram, centre_of_rotation, angles, shape, center): print sinogram.shape sinogram = np.swapaxes(sinogram, 0, 1) sinogram = self._shift(sinogram, centre_of_rotation) sino = np.nan_to_num(sinogram) theta = np.lin...
t_size=(sinogram.shape[0]), # self.parameters['output_size'], filter='ramp', # self.parameters['filter'], interpolation='linear', # self.parameters['linear'], circle=False) ...
hickey/amforth
core/devices/atmega644a/device.py
Python
gpl-2.0
7,375
0.071458
# Partname: ATmega644A # generated automatically, do not edit MCUREGS = { 'ADCSRB': '&123', 'ADCSRB_ACME': '$40', 'ACSR': '&80', 'ACSR_ACD': '$80', 'ACSR_ACBG': '$40', 'ACSR_ACO': '$20', 'ACSR_ACI': '$10', 'ACSR_ACIE': '$08', 'ACSR_ACIC': '$04', 'ACSR_ACIS': '$03', 'DIDR1': '&127', 'DIDR1...
'$20', 'PRR0_PRUSART': '$12', 'PRR0_PRTIM1': '
$08', 'PRR0_PRSPI': '$04', 'PRR0_PRADC': '$01', 'INT0Addr': '2', 'INT1Addr': '4', 'INT2Addr': '6', 'PCINT0Addr': '8', 'PCINT1Addr': '10', 'PCINT2Addr': '12', 'PCINT3Addr': '14', 'WDTAddr': '16', 'TIMER2_COMPAAddr': '18', 'TIMER2_COMPBAddr': '20', 'TIMER2_OVFAddr': '22', 'TIMER1_CAPTAddr': '24', 'TIME...
fake-name/ReadableWebProxy
WebMirror/management/rss_parser_funcs/feed_parse_extractWhatzombiesfearCom.py
Python
bsd-3-clause
551
0.034483
def extractW
hatzombiesfearCom(item): ''' Parser for 'whatzombiesfear.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', ...
return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type) return False
MicrosoftGenomics/FaST-LMM
tests/inputs/buggy/lrt_one_kernel_mixed_effect_laplace_l2_logistic_qqfit.N30.py
Python
apache-2.0
956
0.041841
distributable = FastLmmSet( phenofile = 'datasets/phenSynthFrom22.23.bin.N30.txt', alt_snpreader = 'datasets/all_chr.maf0.001.N30', altset_list = 'datasets/set_input.23_17_11.txt', covarfile = None, filenull = None, autoselect = False, mindist = 0, idist=2, nperm = ...
distribution outfile = 'tmp/lrt_one_kernel_mixed_effect_laplace_l2_logistic_qqfit.N30.txt', forcefullrank=False, qmax=0.1, #use the top 10% of null distrib test statistics to fit the null distribution write_lrtperm=True, datestamp=None, nullModel={'effect':'mixed', 'link':'logistic', ...
'approx':'laplace', 'penalty':'l2'}, altModel={'effect':'mixed', 'link':'logistic', 'approx':'laplace', 'penalty':'l2'}, log = logging.CRITICAL, detailed_table = False )
uclouvain/osis
base/forms/entity.py
Python
agpl-3.0
2,540
0.001182
############################################################################## # # OSIS stands for Open Student Information System. It's an application # designed to manage the core business of higher education institutions, # such as universities, faculties, institutes and professional schools. # The core ...
this program. If not, # see http://www.gnu.org/licenses/. # ############################################################################## import django_filters from d
jango.forms import TextInput from django.urls import reverse from django.utils.translation import gettext_lazy as _ from rest_framework import serializers from base.models.entity_version import EntityVersion class EntityVersionFilter(django_filters.FilterSet): acronym = django_filters.CharFilter( lookup_...
googleapis/python-dialogflow
samples/generated_samples/dialogflow_generated_dialogflow_v2_documents_delete_document_async.py
Python
apache-2.0
1,580
0.000633
# -*- 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...
# # Snippet for DeleteDocument # NOTE: This snippet has been automatically generated for illustrative purposes only. # It may require modifications to work in your environment. # To install the latest published package dependency, execute the following: # python3 -m pip install google-cloud-dialogflow # [START dia...
t(): # Create a client client = dialogflow_v2.DocumentsAsyncClient() # Initialize request argument(s) request = dialogflow_v2.DeleteDocumentRequest( name="name_value", ) # Make the request operation = client.delete_document(request=request) print("Waiting for operation to comp...
rahulbohra/Python-Basic
35_sum_count_avg_by_user_input.py
Python
mit
454
0.002203
count = 0 total = 0 average = 0 while True: inputNumber = raw_input('Enter a number
: ') # Edge Cases if inputNumber == 'done': break if len(inputNumber) < 1: break # Logical work try: number = float(inputNumber) except: print
'Invalid Number' continue count = count + 1 total = total + number print 'Count Total\n', count, total average = total / count print average
abramhindle/UnnaturalCodeFork
python/testdata/launchpad/buildmailman.py
Python
agpl-3.0
7,591
0
#! /usr/bin/python # # Copyright 2009, 2010 Canonical Ltd. This software is licensed under the # GNU Affero General Public License version 3 (see the file LICENSE). import errno import grp import os import pwd import socket import subprocess import sys import tempfile from lazr.config import as_username_groupname f...
), cwd=mailman_source) if retcode:
print >> sys.stderr, 'Could not make Mailman.' sys.exit(retcode) retcode = subprocess.call(('make', 'install'), cwd=mailman_source) if retcode: print >> sys.stderr, 'Could not install Mailman.' sys.exit(retcode) # Try again to import the package. try: import Mailma...
LLNL/spack
var/spack/repos/builtin/packages/r-rots/package.py
Python
lgpl-2.1
1,117
0.000895
# Copyright 2013-2021 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) from spack import * class RRots(RPackage): """Reproducibility-Optimized Test Statistic Calculates the Reprod...
9ac02f0') version('1.10.1', commit='1733d3f868cef4d81af6edfc102221d80793937b') version('1.8.0', com
mit='02e3c6455bb1afe7c4cc59ad6d4d8bae7b01428b') version('1.6.0', commit='3567ac1142ba97770b701ee8e5f9e3e6c781bd56') version('1.4.0', commit='2e656514a4bf5a837ee6e14ce9b28a61dab955e7') depends_on('r@3.3:', type=('build', 'run')) depends_on('r-rcpp', type=('build', 'run')) depends_on('r-biobase', typ...
chetan/cherokee
admin/market/ows_consts.py
Python
gpl-2.0
1,407
0.012082
# -*- coding: utf-8 -*- # # Cherokee-admin # # Authors: # Alvaro Lopez Ortega <alvaro@alobbs.com> # # Copyright (C) 2001-2010 Alvaro Lopez Ortega # # This program is free software; you can redistribute it and/or # modify it under the terms of version 2 of the GNU General Public # License as published by the Free S...
ived a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. # from consts import * from configured import * OWS_STATIC = 'http://cherokee-market.com' OWS_APPS = 'http://www....
www.octality.com/api/v%s/market/install/' %(OWS_API_VERSION) OWS_DEBUG = True URL_MAIN = '/market' URL_APP = '/market/app' URL_SEARCH = '/market/search' URL_SEARCH_APPLY = '/market/search/apply' URL_CATEGORY = '/market/category' URL_REVIEW = '/market/review'
elit3ge/SickRage
sickbeard/providers/kat.py
Python
gpl-3.0
9,861
0.003752
# coding=utf-8 # Author: Mr_Orange <mr_orange@hotmail.it> # URL: http://code.google.com/p/sickbeard/ # # This file is part of SickRage. # # SickRage 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 versi...
em in entries['rss']['channel']['item']: try: title = item['title'] # Use the torcache link kat provides, # unless it is not torcache or we are not using blackhole # because we want t...
url = item['enclosure']['@url'] if sickbeard.TORRENT_METHOD != "blackhole" or 'torcache' not in url: url = item['torrent:magnetURI'] seeders = int(item['torrent:seeds']) leechers = int(item[...
mfwarren/django-mailer-2
django_mailer/constants.py
Python
mit
475
0
PRIORITY_EMAIL_NOW = 0 PRIORITY_HIGH = 1 PRIORITY_NORMAL = 3 PRIORITY_LOW = 5 RESULT_SENT = 0 RESULT_SKIPPED = 1 RESULT_FAILED = 2 PRIORITIES = { 'now': PRIORITY_EMAIL_NOW, 'high': PRIORI
TY_HIGH, 'normal': PRIORITY_NORMAL, 'low': PRIORITY_LOW, } PRIORITY_HEADER = 'X-Mail-Queue-Priority' try: from django.core.mail import get_connection EMAIL_BACKEND_SUPPORT = True except ImportError: # Django version < 1.2 EMAIL_BACKEND_
SUPPORT = False
MjnMixael/knossos
knossos/launcher.py
Python
apache-2.0
12,595
0.003335
## Copyright 2017 Knossos authors, see NOTICE file ## ## 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...
r(sys, 'frozen') or os.path.isdir('data'): return os.path.join('data', name) else: from pkg_resources import resource_filename return resource_filename(__package__, name) def load_settings(): spath = os.path.join(center.settings_path, 'settings.json') settings = center.se
ttings if os.path.exists(spath): try: with open(spath, 'r') as stream: settings.update(json.load(stream)) except Exception: logging.exception('Failed to load settings from "%s"!', spath) # Migration if 's_version' not in settings: ...
Fatman13/gta_swarm
ctripmultiplus.py
Python
mit
1,017
0.013766
#!/usr/bin/env python # coding=utf-8 import pprint import csv
import click import requests import datetime as datetime from datetime import date from xml.etree import ElementTree as ET import os # from random import sample import random import json # import logging import subprocess import glob import time @click.command() @click.option('--days', default=10, ty...
on('--span', default=5, type=int) # @click.option('--duration', default=3, type=int) # @click.option('--days', default=1, type=int) def ctripmultiplus(days, span): start_days = days for i in range(span): subprocess.call(['python', 'ctripplus.py', '--days', str(start_days + i*10)]) for i in range(3): ...
xkmato/casepro
casepro/cases/migrations/0022_delete_mesageaction.py
Python
bsd-3-clause
697
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from djan
go.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('cases', '0021_migrate_case_contacts'), ('msgs', '0008_messageaction'), ] operations = [ migrations.RemoveField( model_name='messageaction', name='created_by', ...
), migrations.RemoveField( model_name='messageaction', name='org', ), migrations.DeleteModel( name='MessageAction', ), ]
pp-mo/iris
lib/iris/tests/unit/analysis/maths/test_divide.py
Python
lgpl-3.0
2,496
0
# Copyright Iris contributors # # This file is part of Iris and is released under the LGPL license. # See COPYING and COPYING.LESSER in the root of the repository for full # licensing details. """Unit tests for the :func:`iris.analysis.maths.divide` function.""" # Import iris.tests first so that some things can be ini...
p.ma.array([2.0, 2.0, 2.0, 2.0], mask=False) cube_a = Cube(dat_a) cube_b = Cube(dat_b) com = self.data_op(dat_b, dat_a) res = self.cube_func(cube_b, cube_a).data self.assertMaskedArrayEqual(com, res, strict=True) class TestCoordMatch(CubeArithmeticCoordsTest): def test_n...
cube1, cube2 = self.SetUpNonMatching() with self.assertRaises(ValueError): divide(cube1, cube2) def test_reversed_points(self): cube1, cube2 = self.SetUpReversed() with self.assertRaises(ValueError): divide(cube1, cube2) if __name__ == "__main__": tests....
adamwen829/instapush-py
setup.py
Python
mit
894
0.025727
#!/usr/bin/python # -*- coding: UTF-8 -*- # vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79: import os from setuptools import setup, find_packages def get_version(): basedir = os.path.dirname(__file__) with open(os.path.join(basedir, 'instapush/version.py')) as f: locals = {} exec(f.rea...
per for instap
ush', license = 'MIT License', url = 'https://github.com/adamwen829/instapush-py', author = 'Adam Wen', author_email = 'adamwen829@gmail.com', packages = find_packages(), include_package_data = True, platforms = 'any', install_requires = ['requests'] )
stellaf/sales_rental
account_invoice_start_end_dates/models/account_invoice.py
Python
gpl-3.0
3,875
0
# -*- coding: utf-8 -*- # © 2013-2016 Akretion (Alexis de Lattre <alexis.delattre@akretion.com>) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import models, fields, api, _ from odoo.exceptions import ValidationError, UserError class AccountInvoiceLine(models.Model): _inherit = 'accou...
% (invline.name)) if invline.end_date and invline.start_date and \ invline.start_date > invline.end_date: raise ValidationError( _("Start Date should be before or be the same as " "End Date for invoice line with Description
'%s'.") % (invline.name)) # Note : we can't check invline.product_id.must_have_dates # have start_date and end_date here, because it would # block automatic invoice generation/import. So we do the check # upon validation of the invoice (see below the f...
QualiSystems/shellfoundry
tests/test_utilities/config/test_config_record.py
Python
apache-2.0
5,062
0.001185
#!/usr/bin/python # -*- coding: utf-8 -*- import sys if sys.version_info >= (3, 0): from unittest.mock import patch else: from mock import patch from pyfakefs import fake_filesystem_unittest from shellfoundry.utilities.config.config_context import ConfigContext from shellfoundry.utilities.config.config_file_...
file_content, ), ) @patch("shellfoundry.utilities.config.config_file_creation.click.echo") def test_failed_to_delete_record(self, echo_mock): # Arrange self.fs.create_file( "/quali/shellfoundry/global_config.yml",
contents=""" install: host: someaddress""", ) # Act with patch("shellfoundry.utilities.config.config_context.yaml") as yaml_mock: yaml_mock.safe_load.side_effect = [Exception()] context = ConfigContext("/quali/shellfoundry/global_config.yml") record =...
njoubert/MAVProxy
MAVProxy/modules/mavproxy_misseditor/__init__.py
Python
gpl-3.0
13,978
0.00651
#!/usr/bin/env python ''' mission editor module Michael Day June 2104 ''' from MAVProxy.modules.lib import mp_module from MAVProxy.modules.lib import mp_util from MAVProxy.modules.mavproxy_misseditor import me_event MissionEditorEvent = me_event
.MissionEditorEvent from pymavlink import mavutil import multiprocessing, time import threading import Queue import traceback class MissionEditorEventThread(threading.Thread): def __init__(self, mp_misseditor, q, l): threading.Thread.__init__(self) self.mp_misseditor = mp_misseditor self....
elf.event_queue_lock = l self.time_to_quit = False def run(self): while not self.time_to_quit: queue_access_start_time = time.time() self.event_queue_lock.acquire() request_read_after_processing_queue = False while self.event_queue.qsize() > 0 and (ti...
rlindner81/pyload
module/plugins/hoster/RapiduNet.py
Python
gpl-3.0
3,047
0.001313
# -*- coding: ut
f-8 -*- import time import pycurl from module.plugins.captcha.ReCaptcha import ReCaptcha from module.plugins.internal.misc import json from module.plugins.internal.SimpleHoster import SimpleHoster class RapiduNet(SimpleHoster): __name__ = "RapiduNet"
__type__ = "hoster" __version__ = "0.14" __status__ = "testing" __pattern__ = r'https?://(?:www\.)?rapidu\.net/(?P<ID>\d{10})' __config__ = [("activated", "bool", "Activated", True), ("use_premium", "bool", "Use premium account if available", True), ("fallback", "...
mattthur/Cinnamon
files/usr/lib/cinnamon-settings/modules/cs_screensaver.py
Python
gpl-2.0
16,729
0.003288
#!/usr/bin/env python2 from SettingsWidgets import * from gi.repository import Gtk, Gdk, GLib, Pango import os, json, subprocess, re from xml.etree import ElementTree import gettext LOCK_DELAY_OPTIONS = [ (0, _("Immediately")), (15, _("After 15 seconds")), (30, _("After 30 seconds")), (60, _("After 1 ...
, size_group=size_group) settings.add_reveal_row(widget, schema
, "use-custom-format") widget = GSettingsFontButton(_("Time Font"), "org.cinnamon.desktop.screensaver", "font-time", size_group=size_group) settings.add_row(widget) widget = GSettingsFontButton(_("Date Font"), "org.cinnamon.desktop.screensaver", "font-date", size_group=size_group) sett...
jaraco/pytest
testing/test_collection.py
Python
mit
26,378
0.000986
import pytest, py from _pytest.main import Session, EXIT_NOTESTSCOLLECTED class TestCollector: def test_collect_versus_item(self): from pytest import Collector, Item assert not issubclass(Collector, Item) assert not issubclass(Item, Collector) def test_compat_attributes(self, testdir,...
pytest.Fu
nction) assert parent is fn parent = fn.getparent(pytest.Class) assert parent is cls def test_getcustomfile_roundtrip(self, testdir): hello = testdir.makefile(".xxx", hello="world") testdir.makepyfile(conftest=""" import pytest class CustomFile(pyte...
tensorflow/lingvo
lingvo/tasks/mt/model_test.py
Python
apache-2.0
35,425
0.011066
# Lint as: python3 # Copyright 2018 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 ...
src_paddings = tf.split(src_paddings, 2, 0) tgt_ids = tf.split
(tgt_ids, 2, 0) tgt_labels = tf.split(tgt_labels, 2, 0) tgt_paddings = tf.split(tgt_paddings, 2, 0) tgt_weights = tf.split(tgt_weights, 2, 0) ret.src.ids = tf.cond( tf.equal(tf.math.floormod(py_utils.GetGlobalStep(), 2), 0), lambda: src_ids[0], lambda: src_ids[1]) ret....
CallmeTorre/Idalia
ESCOM/ConsultarDocumento/views.py
Python
apache-2.0
2,955
0.012864
# -*- coding: utf-8 -*- from django.shortcuts import render, redirect from django.views.generic import View from django.http import HttpResponse from reportlab.pdfgen import canvas from reportlab.lib.pagesizes import letter from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib.units
import inch from reportlab.platypus import (Flowable, Paragraph, Simp
leDocTemplate, Spacer) from .models import TablaSolicitud from .models import Bitacora from .models import TablaAlumno # Create your views here. class ConsultarDocumento(View): template_name = "consultarDocumento.html" def get(self, request): return render( request, self.temp...
utensil-star/HandBrake
gtk/src/makedeps.py
Python
gpl-2.0
5,589
0.004831
#! /usr/bin/python import collections import sys import json DepEntry = collections.namedtuple('DepEntry', 'widget dep enable die hide') dep_map = ( DepEntry("title", "queue_add", "none", True, False), DepEntry("title", "queue_add_menu", "none", True, False), DepEntry("title", "queue_add_multiple_menu", "...
top = dict() for ii in dep_map: if ii.widget in top:
continue deps = list() for jj in dep_map: if jj.widget == ii.widget: deps.append(jj.dep) top[ii.widget] = deps json.dump(top, depsfile, indent=4) top = dict() for ii in dep_map: if ii.dep in top: continue deps = list() ...
sernst/RefinedStatistics
measurement_stats/test/test_value2D.py
Python
mit
2,275
0.002198
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import math import random import unittest from measurement_stats import angle
from measurement_stats import value from measu
rement_stats import value2D HALF_SQRT_2 = 0.5 * math.sqrt(2.0) HALF_SQRT_3 = 0.5 * math.sqrt(3.0) class TestValue2D(unittest.TestCase): def test_angleBetween(self): p1 = value2D.Point2D( value.ValueUncertainty(2.0, 0.1), value.ValueUncertainty(0.0, 0.1) ) p2 = value2D.Poi...
wakatime/wakatime
wakatime/packages/py27/pygments/lexers/capnproto.py
Python
bsd-3-clause
2,194
0
# -*- coding: utf-8 -*- """ pygments.lexers.capnproto ~~~~~~~~~~~~~~~~~~~~~~~~~ Lexers for the Cap'n Proto schema language. :copyright: Copyright 2006-2019 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ import re from pygments.lexer import RegexLexer, default from...
renexp'), default('#pop'), ], 'parenexp': [ (r'[^][;()]+', Literal), (r'[\[(]', Literal, '#push'), (r'[])
]', Literal, '#pop'), default('#pop'), ], 'annotation': [ (r'[^][;,(){}=:]+', Name.Attribute), (r'[\[(]', Name.Attribute, 'annexp'), default('#pop'), ], 'annexp': [ (r'[^][;()]+', Name.Attribute), (r'[\[(]', Name.Att...
ntt-sic/nova
nova/virt/hyperv/vhdutils.py
Python
apache-2.0
7,795
0.000257
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2013 Cloudbase Solutions Srl # 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.ap...
entService()[0] (job_path, ret_val) = image_man_svc.ExpandVirtualHardDisk( Path=vhd_path, MaxInternalSize=new_internal_max_size) self._vmutils.check_ret_val(ret
_val, job_path) def get_internal_vhd_size_by_file_size(self, vhd_path, new_vhd_file_size): """Fixed VHD size = Data Block size + 512 bytes Dynamic_VHD_size = Dynamic Disk Header + Copy of hard disk footer + Hard Disk Footer ...
jaraco/fabric
tests/test_server.py
Python
bsd-2-clause
2,975
0
""" Tests for the test server itself. Not intended to be run by the greater test suite, only by specifically targeting it on the command-line. Rationale: not really testing Fabric itself, no need to pollute Fab's own test suite. (Yes, if these tests fail, it's likely that the Fabric tests using the test server may als...
['file.txt'] ), ( "Multiple files", {'file1.txt': 'contents', 'file2.txt': 'contents2'}, '', ['file1.txt', 'file2.txt'] ), ( "Single empty folder",
{'folder': None}, '', ['folder'] ), ( "Empty subfolders", {'folder': None, 'folder/subfolder': None}, '', ['folder'] ), ( "Non-empty sub-subfolder", {'folder/subfolder/subfolder2/file.txt'...
cmjatai/cmj
cmj/sigad/models.py
Python
gpl-3.0
49,449
0.000243
from datetime import datetime import io import os import tempfile import zipfile from PIL import Image, ImageFont from PIL.Image import LANCZOS from PIL.ImageDraw import Draw from django.conf import settings from django.contrib.auth.models import Permission from django.contrib.contenttypes.fields import GenericForeign...
parents = p[0].classe.parents_and_me + p return parents def treechilds2list(self): yield self for child in self.childs.view_childs(): for item in child.treechilds2list(): yield item class CMSMixin(models.Model):
STATUS_PRIVATE = 99 STATUS_RESTRICT = 1 STATUS_PUBLIC = 0 VISIBILIDADE_STATUS = CmjChoices( (STATUS_RESTRICT, 'status_restrict', _('Restrito')), (STATUS_PUBLIC, 'status_public', _('Público')), (STATUS_PRIVATE, 'status_private', _('Privado')), ) ALINHAMENTO_LEFT = 0 ...
tsantor/banner-ad-toolkit
adkit/generate_html.py
Python
mit
5,427
0.00129
# -- coding: utf-8 -- # Copyright 2015 Tim Santor # # This file is part of proprietary software and use of this file # is strictly prohibited without written consent. # # @author Tim Santor <tsantor@xstudios.agency> """Generates HTML for HTML5 banner ads.""" # ------------------------------------------------------...
ory...') # shutil.copytree(self.get_data('js'), dest) # else: # if self.verbose: # logmsg.warning('"js" directory already exists') @staticmethod def replace_all(text, dict): """Replace all.""" for src, target in six.iteritems(dict): te...
def create_divs(self, dirpath): jpg_files = self.get_files_matching(dirpath, '*.jpg') png_files = self.get_files_matching(dirpath, '*.png') all_files = jpg_files + png_files output = '' for f in all_files: basename = os.path.basename(f) name = os.path...
Aurous/Magic-Discord-Bot
discord/__init__.py
Python
gpl-3.0
1,365
0.001465
# -*- coding: utf-8 -*- """ Discord API Wrapper ~~~~~~~~~~~~~~~~~~~ A basic wrapper for the Discord API. :copyright: (c) 2
015-2016 Rapptz :license: MIT, see LICENSE for more details. """ __title__ = 'discord' __author__ = 'Rapptz' __license__ = 'MIT' __copyright__ = 'Copyright 2015-2016 Rapptz' __version__ = '0.11.0' from .client import Client, AppInfo, ChannelPermissions from .user import User from .game import Game from .channel impo...
.permissions import Permissions, PermissionOverwrite from .role import Role from .colour import Color, Colour from .invite import Invite from .object import Object from . import utils, opus, compat from .voice_client import VoiceClient from .enums import ChannelType, ServerRegion, Status, MessageType from collections i...
Donkyhotay/MoonPy
twisted/web/test/test_distrib.py
Python
gpl-3.0
9,985
0.002203
# Copyright (c) 2008-2009 Twisted Matrix Laboratories. # See LICENSE for details. """ Tests for L{twisted.web.distrib}. """ from os.path import abspath from xml.dom.minidom import parseString try: import pwd except ImportError: pwd = None from zope.interface.verify import verifyObject from twisted.python im...
ar'}) def cbRequested(result): self.assertEquals(requestHeaders['Foo'], ['bar']) request.addCallback(cbRequested) re
turn request def test_connectionLost(self): """ If there is an error issuing the request to the remote publisher, an error response is returned. """ # Using pb.Root as a publisher will cause request calls to fail with an # error every time. Just what we want to tes...
fedora-conary/conary
conary/build/defaultrecipes.py
Python
apache-2.0
27,584
0.000435
# # Copyright (c) SAS Institute 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 w...
o all groups. If B{groupName} is not specified, or is None, then the command will apply to the current default group. PARAMETERS ========== Several parameters may be set at the time of group creation. Although these parameters are typically passed to C{r.createGroup()} for the base group,...
oup, but also the default value for all newly created groups. For example, if B{autoResolve} is set to C{True} in the base group, all other groups created will have autoResolve set to C{True} by default. B{imageGroup} is an exception to this rule; it will not propogate to sub groups. The following ...
JohnHwee/show-me-the-code
Python/0052/main.py
Python
gpl-2.0
1,327
0.024115
import random de
f markov_analysis( fname, n ): """Reads a text file and perfom Markov analysis. Return a dictionary that maps from prefixes to a collection of suffixes. fname: a text file n: n order """
d = {} prefix = tuple() fin = open( fname ) for line in fin: words = line.strip().split() for word in words: if len( prefix ) < 2: prefix += ( word, ) break # if there is no entry for this prefix, #make one d[prefix] = [word...
Lambdanaut/crits
crits/ips/migrate.py
Python
mit
869
0.003452
def migrate_ip(self): """ Migrate to the latest schema version. """ migrate_1_to_2(self) migrate_2_to_3(self) def migrate_2_to_3(self): """ Migrate from schema 2 to 3. """ if self.schema_version < 2: migrate_1_to_2(self) if self.schema_version == 2: self.schem...
ema_version = 2 self.save() self.reload() def migrate_0_to_1(self): """ Migrate from schema 0 to 1. """ if self.schema_version < 1: self.schema_
version = 1
pyta-uoft/pyta
examples/ending_locations/async_for.py
Python
gpl-3.0
169
0
async def fun(): """Note coroutine func
tion must be declared with async def.""" async for a in
b: if a > 5: break else: continue
3dfxsoftware/cbss-addons
issue_load/wizard/migrate.py
Python
gpl-2.0
6,250
0.00128
# -*- coding: utf-8 -*- """ Created on Tue Jun 12 09:56:42 2012 @author: truiz """ from sys import argv import xlrd import xmlrpclib from datetime import datetime from ustr_test import ustr def loadProjectsTasks(fileName, HOST, PORT, DB, USER, PASS): ISSUES_PAGE = 0 TASKS_PAGE = 1 WORKS_PAGE = 2 '''...
'user_id': values_issue['assigned_to'], 'planned_hours': task[2], 'remaining_hours': task[3], 'type_id': values_issue['type_id'], 'partner_id': values_issue['partner_id'], ...
), 'date_end': datetime.now().strftime("%Y/%m/%d %H:%M:%S"), 'description': values_issue['description'], } values_tasks = cleanDict(values_tasks) task_id = object_proxy.execute( ...
ImEditor/ImEditor
src/interface/headerbar.py
Python
gpl-3.0
711
0.004219
import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk, Gio UI_PATH = '/io/github/ImEditor/ui/' class ImEditorHeaderBar(): __gtype_name__ = 'ImEditorHeaderBar' def __init__(self): builder = Gtk.Builder.new_from_resource(UI_PATH + 'headerbar.ui') self.header_bar = builder.get...
self.sele
ct_button = builder.get_object('select_button') self.pencil_button = builder.get_object('pencil_button') builder.add_from_resource(UI_PATH + 'menu.ui') self.window_menu = builder.get_object('window-menu') self.menu_button.set_menu_model(self.window_menu)
percipient/threatconnect-python
examples/commit/incidents_commit.py
Python
apache-2.0
8,526
0.002698
# -*- coding: utf-8 -*- """ standard """ from random import randint import re """ custom """ from examples.working_init import * from threatconnect.Config.ResourceType import ResourceType # # CHANGE FOR YOUR TESTING ENVIRONMENT # - These incidents must be created before running this script # owner = 'Example Communi...
# # resources can be deleted with the resource add method # resource = resources.add(''.format(rn), owner) # a valid
resource name is not required # resource.set_id(dl