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
mrpau/kolibri
kolibri/core/tasks/queue.py
Python
mit
3,851
0.002337
from kolibri.core.tasks.job import Job from kolibri.core.tasks.job import State from kolibri.core.tasks.storage import Storage DEFAULT_QUEUE = "ICEQUBE_DEFAULT_QUEUE" class Queue(object): def __init__(self, queue=DEFAULT_QUEUE, connection=None): if connection is None: raise ValueError("Connec...
can call the update_progress functio
n to notify interested parties of the function's current progress. Another special parameter is the "cancellable" keyword parameter. When passed in and not None, a special "check_for_cancel" parameter is passed in. When called, it raises an error when the user has requested a job to be ...
PaleNeutron/EpubBuilder
my_mainwindow.py
Python
apache-2.0
3,933
0.002628
__author__ = 'PaleNeutron' import os from urllib.parse import urlparse, unquote import sys from PyQt5 import QtWidgets, QtCore, QtGui class MyMainWindow(QtWidgets.QMainWindow): file_loaded = QtCore.pyqtSignal(str) image_loaded = QtCore.pyqtSignal(QtGui.QImage) def __init__(self): su...
def image_loaded(self, file_path): # with open(file_path, "b") as f: # r = f.read() # with open("images/cover.jpg", "wb") as f: #
f.write(r) # def epub_loaded(self, file_path): # self.epub_path = file_path # self.file_loaded.emit(False, ) def uri_to_path(self, uri): if sys.platform == "win32": path = unquote(urlparse(uri).path)[1:] elif sys.platform == "linux": path = unquo...
andreaso/ansible
lib/ansible/modules/system/seboolean.py
Python
gpl-3.0
7,200
0.003194
#!/usr/bin/python # (c) 2012, Stephen Fromm <sfromm@gmail.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your optio...
tableinterface'], 'supported_by': 'core'} DOCUMENTATION = ''' --- module: seboolean short_description: Toggles SELinux booleans. description: - Toggles SELinux booleans. version_added: "0.7" options: name: description: - Name of the bool
ean to configure required: true default: null persistent: description: - Set to C(yes) if the boolean setting should survive a reboot required: false default: no choices: [ "yes", "no" ] state: description: - Desired boolean value required: true default: null choi...
hackersql/sq1map
thirdparty/bottle/bottle.py
Python
gpl-3.0
152,507
0.001489
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Bottle is a fast and simple micro-framework for small web applications. It offers request dispatching (Routes) with URL parameter support, templates, a built-in HTTP Server and adapters for many third party WSGI/HTTP-server and template engines - all in a single file an...
am.default) return (args, varargs, keywords, tuple(defaults) or None) except ImportError: from inspect import getargspec try: from simplejson import dumps as json_dumps, loads as json_lds except ImportError: # pragma: no cover try: from json impo
rt dumps as json_dumps, loads as json_lds except ImportError: try: from django.utils.simplejson import dumps as json_dumps, loads as json_lds except ImportError: def json_dumps(data): raise ImportError( "JSON support requires Python 2.6 or...
ellisdg/3DUnetCNN
unet3d/utils/normalize.py
Python
mit
7,176
0.002508
import numpy as np def zero_mean_normalize_image_data(data, axis=(0, 1, 2)): return np.divide(data - data.mean(axis=axis), data.std(axis=axis)) def foreground_zero_mean_normalize_image_data(data, channel_dim=4, background_value=0, tolerance=1e-5): data = np.copy(data) if data.ndim == channel_dim or data...
get the empirical cumulative distribution functions for the source and # template images (maps pixel value --> quantile) s_quantiles = np.cumsum(s_counts).astype(np.float64) s_quantile
s /= s_quantiles[-1] t_quantiles = np.cumsum(t_counts).astype(np.float64) t_quantiles /= t_quantiles[-1] # interpolate linearly to find the pixel values in the template image # that correspond most closely to the quantiles in the source image interp_t_values = np.interp(s_quantiles, t_quantiles, t_...
SickGear/SickGear
lib/enzyme/mpeg.py
Python
gpl-3.0
31,404
0.00035
# -*- coding: utf-8 -*- # enzyme - Video metadata parser # Copyright 2011-2012 Antoine Bertin <diaoulael@gmail.com> # Copyright 2003-2006 Thomas Schueppel <stain@acm.org> # Copyright 2003-2006 Dirk Meyer <dischi@freevo.org> # # This file is part of enzyme. # # enzyme is free software; you can redistribute it and/or mod...
0xB2: 'user_data_start_code', 0xB3: 'sequence_header_code', 0xB4: 'sequence_error_code', 0xB5: 'extension_start_code', 0xB6: 'reserved', 0xB7: 'sequence end', 0xB8: 'group of pictures', } for i in range(0x01, 0xAF): START_CODE[i] = 'slice_start_code' # #------------------------------------...
--------------------------------------- PICTURE = 0x00 USERDATA = 0xB2 SEQ_HEAD = 0xB3 SEQ_ERR = 0xB4 EXT_START = 0xB5 SEQ_END = 0xB7 GOP = 0xB8 SEQ_START_CODE = 0xB3 PACK_PKT = 0xBA SYS_PKT = 0xBB PADDING_PKT = 0xBE AUDIO_PKT = 0xC0 VIDEO_PKT = 0xE0 PRIVATE_STREAM1 = 0xBD PRIVATE_STREAM2 = 0xBf TS_PACKET_LENGTH = 18...
tartakynov/enso
enso/config.py
Python
bsd-3-clause
3,462
0.000578
# Configuration settings for Enso. Eventually this will take # localization into account too (or we can make a separate module for # such strings). # The keys to start, exit, and cancel the quasimode. # Their values are strings referring to the names of constants defined # in the os-specific input module in use. QUAS...
IMODE_END_KEY = "KEYCODE_RETURN" QUASIMODE_CANCEL_KEY1 = "KEYCODE_ESCAPE" QUASIMODE_CANCEL_KEY2 = "KEYCODE_RCONTROL" # Whether the Quasimode is actually modal ("sticky"). IS_QUASIMODE_MODAL = True # Amount of time, in seconds (float), to wait from the time # that the quasimode begins drawing to the time that the # su...
avior. QUASIMODE_SUGGESTION_DELAY = 0.2 # The maximum number of suggestions to display in the quasimode. QUASIMODE_MAX_SUGGESTIONS = 6 # The minimum number of characters the user must type before the # auto-completion mechanism engages. QUASIMODE_MIN_AUTOCOMPLETE_CHARS = 2 # The message displayed when the user types...
ricorx7/rti_python
ADCP/Predictor/Range.py
Python
bsd-3-clause
30,092
0.007344
import math import json import os import pytest import rti_python.ADCP.AdcpCommands def calculate_predicted_range(**kwargs): """ :param SystemFrequency=: System frequency for this configuration. :param CWPON=: Flag if Water Profile is turned on. :param CWPBL=: WP Blank in meters. :param CWPBS=: WP...
else: wpRange_1200000 = rScale_1200000 * (absorption_range_1200000 + config["DEFAULT"]["1200000"]["BIN"] * dB_1200000) else: wpRange_1200000 = 0.0 else: btRange_1200000 = 0.0 wpRange_1200000 = 0.0 # 600khz btRange_600000 = 0.0 wpRange_600000 = 0....
000 = math.cos(_BeamAngle_ / 180.0 * math.pi) / math.cos(config["DEFAULT"]["600000"]["BEAM_ANGLE"] / 180.0 * math.pi) dI_600000 = 20.0 * math.log10(math.pi * config["DEFAULT"]["600000"]["DIAM"] / waveLength) dB_600000 = 0.0; if config["DEFAULT"]["600000"]["BIN"] == 0 or _CyclesPe
GrognardsFromHell/TemplePlus
tpdatasrc/co8infra/scr/py00416standard_equipment_chest.py
Python
mit
4,171
0.101415
from toee import * from utilities import * from Co8 import * from py00439script_daemon import npc_set, npc_get from combat_standard_routines import * def san_dialog( attachee, triggerer ): if (npc_get(attachee, 1) == 0): triggerer.begin_dialog( attachee, 1 ) elif (npc_get(attachee, 1) == 1): triggerer.begin_dia...
create_item_in_inventory( aaa, pc ) elif pc.stat_level_get(stat_level_fighter) > 0: for aaa in [6013 ,6010 ,6011 ,6012 ,6059 ,4062 ,8014]: create_item_in_inventory( aaa, pc ) elif pc.stat_level_get(stat_level_monk) > 0: if pc.stat_level_g
et(stat_race) in [race_gnome, race_halfling]: for aaa in [6205 ,6202 ,4060 ,8014]: # dagger (4060) instead of quarterstaff create_item_in_inventory( aaa, pc ) else: for aaa in [6205 ,6202 ,4110 ,8014]: create_item_in_inventory( aaa, pc ) elif pc.stat_level_get(stat_level_paladin) > 0: ...
raphaelvalentin/Utils
optimize/optlib2.py
Python
gpl-2.0
8,671
0.011302
from functions.science import rms, mae, average, nan, inf from collections import OrderedDict from rawdata.table import table from numpy import array, log10 import cma from time import time, strftime __all__ = ['fmin', 'optimbox', 'box', 'array', 'log10', 'rms', 'mae', 'average', 'nan', 'inf'] def box(x, y, xmin=-inf...
slope = xmax-xmin intercept = xmax-slope x = slope*y + intercept X.append(x) return X def eval_error(output): if isinstance(output, dict): return optimbox(output).error() elif isinstance(outpu
t, (float, int)): return float(abs(output)) elif isinstance(output, tuple): return average([ eval_error(elt) for elt in output ]) elif hasattr(output, '__iter__'): return mae(output) else: raise Exception('output must be...
Freso/listenbrainz-server
messybrainz/db/__init__.py
Python
gpl-2.0
1,338
0.003737
from __future__ import print_function from sqlalchemy import create_engine from sqlalchemy.pool import NullPool import sqlalchemy import sys # This value must be incremented after schema changes on replicated tables! SCHEMA_VERSION = 1 engine = None def init_db_engine(connect_str): global engine engine = cre...
ine.connect() connection.connection
.set_isolation_level(0) lines = sql.read().splitlines() try: for line in lines: # TODO: Not a great way of removing comments. The alternative is to catch # the exception sqlalchemy.exc.ProgrammingError "can't execute an empty query" if line and...
joaoperfig/mikezart
source/markovzart2.py
Python
mit
8,058
0.018367
import random import musictheory import filezart import math from pydub import AudioSegment from pydub.playback import play class Part: def __init__(self, typ=None, intensity=0, size=0, gen=0, cho=0): self._type = typ #"n1", "n2", "bg", "ch", "ge" if intensity<0 or gen<0 or cho<0 or size<0 or inte...
Sequence(size) inten = intensitySequence(size) sizes = sizeSequence
(size) overl = overlaySequence(size) return joinSeqs(types, inten, sizes, overl) def joinSeqs(types, inten, sizes, overl): struct = Structure() for i in range(len(types)): if types[i]=="bg": string = "["+types[i]+"-"+str(inten[i])+"-"+str(sizes[i])+"-"+"0"+"-"+str(overl[i])+"]" # If...
gaowhen/summer
summer/db/connect.py
Python
mit
485
0
# -*-
coding: utf-8 -*- import sqlite3 from flask import g, current_app def connect_db(): db = sqlite3.connect(current_app.config['DATABASE_URI']) db.row_
factory = sqlite3.Row return db # http://flask.pocoo.org/docs/0.10/appcontext/ def get_db(): """Opens a new database connection if there is none yet for the current application context. """ db = getattr(g, '_database', None) if db is None: db = g._database = connect_db() return db
RedFoxPi/Playground
threadtest.py
Python
gpl-2.0
929
0.01507
import threading import time class Status: lock = None statusno =0 def __init__(self): self.lock = threading.Lock() def update(self, add): self.lock.acquire() self.statusno = self.statusno + add self.lock.release() def get(self): self.loc...
elease() return n def md5calc(status, args): for i in args: time.sleep (1) #print i status.update(1) def show_status(status): while threading.active_count() > 2:
time.sleep(1) print status.get() status = Status() slaves = [] for i in range(5): t = threading.Thread(target=md5calc, args=(status, [1,2,5])) t.start() slaves.append(t) m = threading.Thread(target=show_status, args=(status,)) m.start() m.join() for t in slaves: t.join()
usc-isi-i2/WEDC
spark_dependencies/python_lib/nose2/tests/functional/test_coverage.py
Python
apache-2.0
878
0.004556
import os.path import platform from nose2.compat import unittest from nose2.tests._common import FunctionalTestCase class TestCoverage(FunctionalTestCase): @unittest.skipIf( platform.python_version_tuple()[:2] == ('3', '2'), 'coverage package does not support python 3.2') def test_run(self): ...
stdout, stderr = proc.communicate() self.assertTestRunOutputMatches( proc,
stderr=expected) self.assertTestRunOutputMatches( proc, stderr='TOTAL\s+' + STATS)
t3hi3x/p-k.co
shorturls/admin.py
Python
mit
1,450
0.008276
__author__ = 'Alex Breshears' __license__ = ''' Copyright (C) 2012 Alex Breshears 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, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be in...
D TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS 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...
danalec/dotfiles
sublime/.config/sublime-text-3/Packages/anaconda_go/plugin/handlers_go/commands/package_symbols.py
Python
mit
5,136
0
# Copyright (C) 2013 - 2016 - Oscar Campos <oscar.campos@member.fsf.org> # This program is Free Software see LICENSE file for details import logging import traceback from collections import defaultdict from ..anagonda.context import guru from commands.base import Command class PackageSymbols(Command): """Run g...
os']) details['name'] = desc['desc'] details['kind'] = details['type'] aggregated_data[filename].append(details) for elem in details.get('methods', []): filename = elem['pos'].split(':')[0] elem['type'] = elem['name'] elem['...
ils['objpos'].split(':')[0] details['pos'] = details['objpos'] details['name'] = details['type'] details['kind'] = details['type'] aggregated_data[filename].append(details) for filename, elems in aggregated_data.items(): symbols += sorted(elems, key=l...
DimiterM/santander
PeriodicValidation.py
Python
mit
2,287
0.00962
import time import numpy as np import keras import tensorflow as tf import keras.backend as K from keras import optimizers from keras.models import load_model from keras.callbacks import Callback from functions import calculate_top_k_new_only """ PeriodicValidation - Keras callback - checks val_loss periodically i...
epoch_end(self, epoch, logs={}): if epoch % 5 == 4 or epoch % 5 == 2: if self.filepath: self.model.save(self.filepath+".ep_"+str(epoch)+".h5", overwrite=True) if self.val_data is None: return h = self.mode...
str(epoch) + ": ", h) y_top_k_new_only = calculate_top_k_new_only(self.model, self.val_data[0][0], self.val_data[0][1], self.val_data[1], self.batch_size, (not self.val_data[0][1].shape[2] == self.val_data[1].shape[1])) print("testing MAP@K for NEW ...
nosix/PyCraft
src/pycraft/service/whole/handler/__init__.py
Python
lgpl-3.0
171
0.005848
# -*- coding: utf8 -*- fr
om .task import TaskID from .core import Handler from .queue import EventQueue __all__ = [ 'TaskID', 'Handler', '
EventQueue', ]
samdmarshall/xcparse
xcparse/Xcode/PBX/PBX_Base.py
Python
bsd-3-clause
2,017
0.020327
from .PBXResolver import * from .PBX_Constants import * class PBX_Base(object): def __init__(self, lookup_func, dictionary, project, identifier): # default 'name' property of a PBX object is the type self.name = self.__class__.__name__; # this is the identifier for this object ...
; def fetchObjectFromProje
ct(self, lookup_func, identifier, project): find_object = project.objectForIdentifier(identifier); if find_object == None: result = lookup_func(project.contents[kPBX_objects][identifier]); if result[0] == True: find_object = result[1](lookup_func, project.contents...
chippey/gaffer
python/GafferSceneTest/PrimitiveVariablesTest.py
Python
bsd-3-clause
2,924
0.027018
########################################################################## # # Copyright (c) 2014, John Haddon. 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 so...
endorse or # promote products derived from this software without specific prior # written permission. # # THIS SOFTWARE IS PRO
VIDED 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 THE COPYRIGHT OWNER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIREC...
IBM-Security/ibmsecurity
ibmsecurity/isds/available_updates.py
Python
apache-2.0
6,037
0.002319
import logging logger = logging.getLogger(__name__) def get(isdsAppliance, check_mode=False, force=False): """ Retrieve available updates """ return isdsAppliance.invoke_get("Retrieving available updates", "/updates/available.json") def discover(isdsAppliance, ch...
obj['data']: # Split of file by '-' hyphen and '_' under score fp = re.split('-|_', firm['name']) firm_appl_version = fp[0] firm_appl_product = fp[2] firm_appl_date = fp[3
] logger.debug("Partition details ({0}): {1}: version: {2} date: {3}".format(firm['partition'], firm_appl_product, firm_appl_version, firm_appl_date)) if firm['active'] is True: from ibmsecurity.utilities import tools if tools.version_compare(firm_appl_version, fi...
NYU-Molecular-Pathology/snsxt
snsxt/sns_tasks/DemoQsubAnalysisTask.py
Python
gpl-3.0
2,720
0.015074
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys import re import task_classes from task_classes import QsubAnalysisTask class DemoQsubAnalysisTask(QsubAnalysisTask): """ Demo task that will submit a single qsub job for the analysis """ def __init__(self, analysis, taskname = 'DemoQs...
e entire analysis Put your code for performing the analysis task on the entire analysis here Parameters ---------- anal
ysis: SnsWESAnalysisOutput the `sns` pipeline output object to run the task on. If ``None`` is passed, ``self.analysis`` is retrieved instead. Returns ------- qsub.Job a single qsub job object """ self.logger.debug('Put your code for doing the analysis t...
Chavjoh/LinuxAuthenticationTester
LinuxAuthenticationTesterShadow.py
Python
apache-2.0
5,520
0.025915
๏ปฟ#!/usr/bin/python # -*- coding: utf-8 -*- #------------------------------------------------------------------------------# # Security - Linux Authentication Tester with /etc/shadow # # ============================================================================ # # Note: To be used for te...
"" # Return the shadow password database entry for the given user name shadowPw
dDb = spwd.getspnam(username)[1] # Open dictionary file with open(dictionary) as file: # Read each line : One line = One password for line in file: # Delete new line character password = line.rstrip('\n') # Check authentication if checkAuthentication(shadowPwdDb, password): return password ...
google/grr
grr/server/grr_response_server/flows/general/registry_test.py
Python
apache-2.0
12,992
0.002617
#!/usr/bin/env python # -*- encoding: utf-8 -*- """Tests for the registry flows.""" import os from absl import app from grr_response_client.client_actions import file_fingerprint from grr_response_client.client_actions import searching from grr_response_client.client_actions import standard from grr_response_core.li...
tryVFSHandler) vfs_overrider.Start() self.addCleanup(vfs_overrider.Stop) class TestFakeRegistryFinderFlow(RegistryFlowTest): """Tests for the RegistryFinder flow.""" runkey = "HKEY_USERS/S-1-5-
20/Software/Microsoft/Windows/CurrentVersion/Run/*" def RunFlow(self, client_id, keys_paths=None, conditions=None): if keys_paths is None: keys_paths = [ "HKEY_USERS/S-1-5-20/Software/Microsoft/" "Windows/CurrentVersion/Run/*" ] if conditions is None: conditions = [] ...
bitmovin/bitmovin-python
bitmovin/resources/models/encodings/sprite.py
Python
unlicense
2,500
0.002
from bitmovin.resources.models import AbstractModel from bitmovin.resources import AbstractNameDescriptionResource from bitmovin.errors import InvalidTypeError from bitmovin.utils import Serializable from .encoding_output import EncodingOutput class Sprite(AbstractNameDescriptionResource, AbstractModel, Serializable)...
t): id_ = json_object['id'] custom_data = json_object.get('customData') width = json_object.get('width') height = json_object.get('height') distance = json_object.get('distance') sprite_name = json_object.get('spriteName') vtt_name = json_object.get('vttName') ...
description = json_object.get('description') sprite = Sprite(id_=id_, custom_data=custom_data, outputs=outputs, name=name, description=description, height=height, width=width, sprite_name=sprite_name, vtt_name=vtt_name, distance=distance) return sprite @property ...
icereval/osf.io
osf_tests/test_elastic_search.py
Python
apache-2.0
47,974
0.001772
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals import time import unittest import logging import functools from nose.tools import * # flake8: noqa (PEP8 asserts) import mock from framework.auth.core import Auth from website import settings import website....
terval=0.3, retries=3): def test_wrapper(func): t_interval = interval t_retries = retries
@functools.wraps(func) def wrapped(*args, **kwargs): try: func(*args, **kwargs) except AssertionError as e: if retries: time.sleep(t_interval) retry_assertion(interval=t_interval, retries=t_retries - 1)(func)...
jeffery9/mixprint_addons
ineco_thai_account/report/jy_serv.py
Python
agpl-3.0
1,612
0.031638
#!/usr/bin/env jython import sys #sys.path.append("/usr/share/java/itextpdf-5.4.1.jar") sys.path.append("itextpdf-5.4.1.jar") #sys.path.append("/usr/share/java/itext-2.0.7.jar") #sys.path.append("/usr/share/java/xercesImpl.jar") #sys.path.append("/usr/share/java/xml-apis.jar") from java.io import FileOutputStream fro...
,e: raise Exception("Field %s: %s"%(k,str(e))) st.setFormFlattening(True) st.close() t1=time.time() #print "finished in %.2fs"%(t1-t0) return True def pdf_merge(pdf1,pdf2): #print "pdf_merge",orig_pdf,vals t0=time.time() pdf=pdf1 t1=time.time() #print "finished in %
.2fs"%(t1-t0) return pdf serv=SimpleXMLRPCServer(("localhost",9999)) serv.register_function(pdf_fill,"pdf_fill") serv.register_function(pdf_merge,"pdf_merge") print "waiting for requests..." serv.serve_forever()
trivedi/sentapy
NaiveBayes.py
Python
mit
7,810
0.009091
from __future__ import print_function import math, nltk from termcolor import colored from analyze import generate_stopwords, sanitize from vector import Vector class NaiveBayesClassifier(): def __init__(self): """ Creates: """ self.c = {"+" : Vector(), "-" : Vector()} ...
positive = sentiment["+"] # Get calculated posterior of positive sentiment negative = sentiment["-"] # Get calculated posterior fo negative sentiment #print "positive: %s negative: %s" % (positive, negative) if "not" in sanitized or "despite" in sanitized: if p...
+ positive: positive = abs(positive) if verbose: print("positive: %f negative: %f" % (positive, negative)) if positive > + math.log(1.3) + negative: if eval: return "+" else: print(colored('+', 'green')) elif negative > math.log(.9)+positive: ...
Eficent/odoo-operating-unit
account_invoice_merge_operating_unit/__init__.py
Python
agpl-3.0
202
0
# -*- coding: u
tf-8 -*- # ยฉ 2015 Eficent Business and IT Consulting Services S.L. - # Jordi Ballester Alomar # License AGPL-3.0 or later (https:/
/www.gnu.org/licenses/agpl.html). from . import models
pysam-developers/pysam
tests/compile_test.py
Python
mit
1,181
0.001693
''' compile_test.py - check pyximport functionality with pysam ========================================================== test script for checking if
compilation against pysam and tabix works. ''' # clean up previous compilation import os import unittest import pysam from TestUtils import make_data_files, BAM_DATADIR, TABIX_DATADIR def setUpModule(): make_data_files(BAM_DATADIR) make_data_files(TABIX_DATADIR) try: o
s.unlink('tests/_compile_test.c') os.unlink('tests/_compile_test.pyxbldc') except OSError: pass import pyximport pyximport.install(build_in_temp=False) import _compile_test class BAMTest(unittest.TestCase): input_filename = os.path.join(BAM_DATADIR, "ex1.bam") def testCount(self): nread = ...
ricardoalejos/RalejosMsrElcDsn
SmdAngPtnSnt/pkg/ExpFlows/Ch3LpfPlotSaEvoVsRes.py
Python
mit
5,718
0.03148
""" Title: Ch3LpfPlotResponse - Chapter 3: Plot filter response Author: Ricardo Alejos Date: 2016-09-20 Description: Plots the micro-strip filter response against the specifications Version: 1.0.0 Comments: - """ # Import Python's built-in modules import csv as _csv import logging as _...
name = "ch3_fresp_n4_xopt" ), dict( title = ("Filter response
using","\\it{n}\\rm=8 and \\bf\\it{x}\\rm=\\bf\\it{x}\\rm*"), n = 8, w1 = 1.3750, l1 = 4.9000, w2 = 3.0625, filename = "ch3_fresp_n8_xopt" ), ) def PlotResponse(w1, l1, w2, n, title, filename = None): resp = _lpf.getRawResponseData([w1, l1, w2], n) freq = resp["...
hoechenberger/psychopy
psychopy/experiment/components/joystick/mouseJoystick.py
Python
gpl-3.0
1,348
0.009644
#!/usr/bin/env python # -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2018 Jonathan Peirce # Distributed under the terms of the GNU General Public License (GPL). # Support for fake joystick/gamepad during devlopment # if no 'real' joystick/gamepad is available use keyboard emulation # 'ctrl' + ...
nt_function from psychopy import event c
lass Joystick(object): def __init__(self, device_number): self.device_number = device_number self.numberKeys = ['0','1','2','3','4','5','6','7','8','9'] self.modifierKeys = ['ctrl','alt'] self.mouse = event.Mouse() def getNumButtons(self): return(len(self.numberKeys)) ...
MAECProject/pefile-to-maec
pefile_to_maec/mappings/file_object.py
Python
bsd-3-clause
586
0.001706
# -*- coding: Latin-1 -*- # Copyright (c) 2015, The MITRE Corporation. All rights reserved. # See License.txt for complete terms. # file object ->
CybOX File Object mappings file_object_mappings = {'file_format': 'file_format', 'type': 'type', 'file_name': 'file_name', 'file_path': 'file_path', 'size': 'size_in_bytes', 'magic_number': 'magic_num...
ntropy'}
SqueezeStudioAnimation/dpAutoRigSystem
dpAutoRigSystem/Extras/sqStickyLipsSetup.py
Python
gpl-2.0
20,524
0.007698
#!/usr/bin/python # -*- coding: utf-8 -*- ################################################################### # # Company: Squeeze Studio Animation # # Author: Danilo Pinheiro # Date: 2014-02-10 # Updated: 2014-02-24 # # sqStickyLipsSetup.py # # This script will create a Sticky Lips setup. # ########...
, insertBetween=True, replaceOriginal=True) pointListA, pointListB, sideA, sideB = self.sqGetPointLists() toDeleteList = []
p = 2 for k in range((sideA+2), (sideB-1)): if p%2 == 0: toDeleteList.append(self.baseCurve+".cv["+str(k)+"]") toDeleteList.append(self.baseCurve+".cv["+str(k+len(pointListA)-1)+"]") p = p+1 q = 2 m = sideA-2...
corradio/electricitymap
parsers/NL.py
Python
gpl-3.0
9,768
0.005119
#!/usr/bin/env python3 import arrow import math from . import statnett from . import ENTSOE from . import DK import logging import pandas as pd import requests def fetch_production(zone_key='NL', session=None, target_datetime=None, logger=logging.getLogger(__name__), energieopwek_nl=True): ...
exchange_NO = [statnett.fetch_exchange(zone_key1=zone_1, zone_key2=zone_2, session=r, target_datetime=dt.datetime, logger=logger) for dt in arrow.Arrow.range( 'hour', arrow.get(min([e['datetime'] ...
for e in exchanges])).replace(minute=0))] exchanges.extend(exchange_NO) # add DK1 data (only for dates after operation) if target_datetime > arrow.get('2019-08-24', 'YYYY-MM-DD') : zone_1, zone_2 = sorted(['DK-DK1', zone_key]) df_dk = pd.DataFrame(DK.fetch_exchange(zone_key1=zone_1...
sergiooramas/tartarus
src/load.py
Python
mit
6,438
0.005747
import argparse import glob import matplotlib.pyplot as plt import numpy as np import os import pandas as pd import pickle from sklearn.preprocessing import StandardScaler, normalize import sys import common FACT = 'pmi' # nmf/pmi_wl/pmi_wp/pmi_wlp DIM = 200 DATASET = 'MSDmm' WINDOW = 1 NSAMPLES = 'all' #all MAX_N_S...
ler = StandardScaler() N = pd.np.min([len(X), max_N]) # Limit the number of patches to fit scaler.fit(X[:N]) X = scaler.transform(X) X.shape = shape return X, scaler def load_X(args): dat
a_path = '../data/patches_%s_%s/' % (DATASET, args.window) progress_update = 1 data_files = glob.glob(os.path.join(data_path, "*.npy")) #songs_in = set(open(common.DATASETS_DIR+'/trainset_%s.tsv' % # (args.dataset)).read().splitlines()) if len(data_files) == 0: raise Valu...
bikoheke/hacktoberfest
scripts/hello_world_amlaanb.py
Python
gpl-3.0
34
0.029412
import s
ys print("Hello, Wor
ld!")
jcdoll/PiezoD
python/archive/lbfgs.py
Python
gpl-3.0
752
0.009309
from cantilever_divingboard import * # We need to scale the parameters before applying the optimization algorithm # Normally there are about 20 orders of magnitude between the dimensions and # the doping concentration,
so this is a critical step # Run the script freq_min = 1e3 freq_max = 1e5 omega_min = 100e3 initial_guess = (50e-6, 1e
-6, 1e-6, 30e-6, 1e-6, 1e-6, 500e-9, 5., 1e15) constraints = ((30e-6, 100e-6), (500e-9, 20e-6), (1e-6, 10e-6), (2e-6, 100e-6), (500e-9, 5e-6), (500e-9, 20e-6), (30e-9, 10e-6), (1., 10.), (1e15, 4e19)) x = optimize_cantilever(initial_guess, constraints, freq_min, freq_max, ...
apache/incubator-airflow
airflow/example_dags/example_complex.py
Python
apache-2.0
7,913
0.004929
# # 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...
e_entry_group >> delete_entry_group delete_tag = BashOperator(task_id="delete_tag", bash_command="echo delete_tag") create_tag >> delete_tag delete_tag_template_field = BashOperator( task_id="delete_tag_template_field", bash_command="echo delete_tag_t
emplate_field" ) delete_tag_template = BashOperator(task_id="delete_tag_template", bash_command="echo delete_tag_template") # Get get_entry_group = BashOperator(task_id="get_entry_group", bash_command="echo get_entry_group") get_entry_group_result = BashOperator( task_id="get_entry_group_...
malinoff/amqproto
tests/conftest.py
Python
apache-2.0
288
0
def pytest_addoption(parser): parser.addoption( '--integra
tion', action='store_true', help='run integr
ation tests', ) def pytest_ignore_collect(path, config): if not config.getoption('integration') and 'integration' in str(path): return True
4dn-dcic/tibanna
awsf3/log.py
Python
mit
1,003
0.004985
def read_logfile_by_line(logfile): """generator function that yields the log file content line by line""" with open(logfile, 'r') as f: for line in f: yield line yield None def parse_commands(log_content): """ parse cwl commands from the line-by-line generator of log file cont...
command_list.append(
command) command = [] line = next(log_content) return(command_list)
diegodelemos/cap-reuse
step-broker/app.py
Python
gpl-3.0
3,081
0
import copy import json import logging import threading import uuid from flask import Flask, abort, jsonify, request import kubernetes app = Flask(__name__) app.secret_key = "mega secret key" JOB_DB = {} def get_config(experiment): with open('config_template.json', 'r') as config: return json.load(config...
pod_event_reade
r_thread = threading.Thread(target=kubernetes.watch_pods, args=(JOB_DB,)) pod_event_reader_thread.start() app.run(debug=True, port=5000, host='0.0.0.0')
zyga/guacamole
guacamole/ingredients/test_cmdtree.py
Python
gpl-3.0
2,078
0
# encoding: utf-8 # This file is part of Guacamole. # # Copyright 2012-2015 Canonical Ltd. # Written by: # Zygmunt Krynicki <zygmunt.krynicki@canonical.com> # # Guacamole is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License version 3, # as published by ...
2][0][1] self.assertIsInstance(cmd_obj, _cmd) self.assertIsInstance(sub_obj, _sub) self.assertEqual( self.bowl.context.cmd_tree, (None, cmd_obj, (('sub', sub_obj, ()),))) d
ef test_collect_spices(self): """check if spices are collected from top-level command only.""" self.assertTrue(self.bowl.has_spice('salt')) self.assertTrue(self.bowl.has_spice('pepper')) self.assertFalse(self.bowl.has_spice('mustard'))
belokop/indico_bare
indico/modules/attachments/controllers/compat.py
Python
gpl-3.0
3,649
0.001644
# This file is part of Indico. # Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN). # # Indico 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 (a...
ture__ import unicode_literals from flask import current_app, redirect, request from werkzeug.exceptions import NotFound from indico.modules.attachments.controllers.util import SpecificA
ttachmentMixin from indico.modules.attachments.models.legacy_mapping import LegacyAttachmentFolderMapping, LegacyAttachmentMapping from indico.modules.events import LegacyEventMapping from indico.util.string import is_legacy_id from indico.web.flask.util import url_for from MaKaC.webinterface.rh.base import RHSimple, R...
alexander-matsievsky/HackerRank
All_Domains/Python/Sets/symmetric-difference.py
Python
mit
194
0
import sys [_, ms, _, n
s] = list(sy
s.stdin) ms = set(int(m) for m in ms.split(' ')) ns = set(int(n) for n in ns.split(' ')) print(sep='\n', *sorted(ms.difference(ns).union(ns.difference(ms))))
andrzejgorski/whylog
whylog/log_reader/read_utils.py
Python
bsd-3-clause
2,366
0.000423
import os from whylog.log_reader.exceptions import EmptyFile, OffsetBiggerThanFileSize class ReadUtils(object): STANDARD_BUFFER_SIZE = 512 @classmethod def size_of_opened_file(cls, fh): prev_position = fh.tell() fh.seek(0, os.SEEK_END) size = fh.tell() fh.seek(prev_positi...
ontains the specified offset and returns also offsets of the first and the last sign of this line. if there is '
\n' on specified offset, the previous line is returned """ return cls._read_entire_line(fd, offset, buf_size)
juhi24/ilmaruuvi
ilmaruuvi/systemd_service.py
Python
mit
455
0.006593
#!python # -*- coding: utf-8 -*- from os import path import shutil def install(): fil
ename = 'ilmaruuvi.service' install_path = path.join('/etc/systemd/system', filename) here = path.abspath(path.dirname(__file__)) with open(path.join(here, filename), 'r') as f: service = f.read() service = service.format(working_dir=here, exec_start=shutil.which('ilmaruuvi')) with open(inst...
h, 'w') as f: f.write(service)
stefanseefeld/numba
numba/cuda/stubs.py
Python
bsd-2-clause
9,284
0.002801
""" This scripts specifies all PTX special objects. """ from __future__ import print_function, absolute_import, division import operator import numpy import llvmlite.llvmpy.core as lc from numba import types, ir, typing, macro from .cudadrv import nvvm class Stub(object): '''A stub object to represent special obj...
''' _description_ = '<threadIdx.{x,y,z}>' x = macro.Macro('tid.x', SREG_SIGNATURE) y = macro.Macro('tid.y', SREG_SIGNATURE) z = macro.Macro('tid.z', SREG_SIGNATURE) class blockIdx(Stub): ''' The block indices in the grid of thread blocks, accessed through the attributes ``x``, ``y``, ...
spanning the range from 0 inclusive to the corresponding value of the attribute in :attr:`numba.cuda.gridDim` exclusive. ''' _description_ = '<blockIdx.{x,y,z}>' x = macro.Macro('ctaid.x', SREG_SIGNATURE) y = macro.Macro('ctaid.y', SREG_SIGNATURE) z = macro.Macro('ctaid.z', SREG_SIGNATURE)...
mcleonard/sampyl
sampyl/samplers/NUTS.py
Python
mit
5,706
0.002103
""" sampyl.samplers.NUTS ~~~~~~~~~~~~~~~~~~~~ This module implements No-U-Turn Sampler (NUTS). :copyright: (c) 2015 by Mat Leonard. :license: MIT, see LICENSE for more details. """ from __future__ import division import collections from ..core import np from .base import Sampler from .hamiltonian import energy, ...
= k self.t0 = t0 self.Hbar = 0. self.ebar = 1. self.mu = np.log(self.step_size*10) def step(self): """ Perform one NUTS step.""" H = self.model.logp dH = self.model.grad x = self.state r0 = initial_momentum(
x, self.scale) u = np.random.uniform() e = self.step_size xn, xp, rn, rp, y = x, x, r0, r0, x j, n, s = 0, 1, 1 while s == 1: v = bern(0.5)*2 - 1 if v == -1: xn, rn, _, _, x1, n1, s1, a, na = buildtree(xn, rn, u, v, j, e, x, r0, ...
DataONEorg/d1_python
lib_common/src/d1_common/ext/mimeparser.py
Python
apache-2.0
6,325
0.003794
#!/usr/bin/env python # This work was created by participants in the DataONE project, and is # jointly copyrighted by participating institutions in DataONE. For # more information on DataONE, see our web site at http://dataone.org. # # Copyright 2009-2017 DataONE # # Licensed under the Apache License, Version 2.0 (t...
d parameter must be pre-parsed. - best_match(): Choose the mime-type with the highest quality ('q
') from a list of candidates. """ from functools import reduce __version__ = "0.1.2" __author__ = "Joe Gregorio" __email__ = "joe@bitworking.org" __credits__ = "" # TODO: Can probably delete this module. def parse_mime_type(mime_type): """Carves up a mime-type and returns a tuple of the (type, subtype, p...
SUSE/kiwi
kiwi/system/kernel.py
Python
gpl-3.0
5,997
0
# Copyright (c) 2015 SUSE Linux GmbH. All rights reserved. # # This file is part of kiwi. # # kiwi 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. # # kiwi is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ...
sol-ansano-kim/medic
plugins/Tester/faceAssigned.py
Python
mit
1,666
0.001801
import medic from maya import OpenMaya class FaceAssigned(medic.PyTester): def __init__(self): super(FaceAssigned, self).__init__() def Name(self): return "FaceAssigned" def Description(self): return "Face assigned mesh(s)" def Match(self, node):
return node.object().hasFn(OpenMaya.MFn.kMesh) or node.object().hasFn(OpenMaya.MFn.kNurbsSurfaceGeom) @staticmethod def __TestObjGrp(node, parentPlug, childPlug): dg = node.dg() if not dg.hasAttribute(parentPlug) or not dg.hasAttribute(childPlug): return False io_plug ...
lug) for i in range(io_plug.numElements()): elm = io_plug.elementByPhysicalIndex(i) og_plug = elm.child(og_obj) if not og_plug.numConnectedElements(): continue for j in range(og_plug.numElements()): gelm = og_plug.elementByPhysic...
UbiCastTeam/candies
candies2/buttons.py
Python
lgpl-3.0
9,259
0.007884
#!/usr/bin/env python # -*- coding: utf-8 -*- import gobject import clutter from text import TextContainer from roundrect import RoundRectangle, OutlinedRoundRectangle from clutter import cogl class ClassicButton(TextContainer): __gtype_name__ = 'ClassicButton' def __init__(self, label=' ', margin=0, pad...
inimal size (just suspension marks) b = ClassicButton('Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt.') b.set_size(*b.get_preferred_size()[:2]) box2.add(b) # Invisible rectangle for bottom margin r = clutter.Rectangle() r.set_size(640, 1) box...
.set_position(50, 425) stage.add(b) b = ClassicButton('C') b.set_font_color('Yellow') b.set_size(50, 50) b.set_position(125, 375) stage.add(b) b = ClassicButton('D') b.set_border_width(10) b.set_border_color('Green') b.set_size(100, 100) b.set_position(250, 325) ...
angr/cle
cle/backends/elf/relocation/pcc64.py
Python
bsd-2-clause
4,448
0.004946
import logging from . import generic from .elfreloc import ELFReloc l = logging.getLogger(name=__name__) # http://refspecs.linuxfoundation.org/ELF/ppc64/PPC-elf64abi-1.9.pdf arch = 'PPC64' class R_PPC64_JMP_SLOT(ELFReloc): def relocate(self): if self.owner.is_ppc64_abiv1: # R_PPC64_JMP_SLOT ...
elative_addr + 16, aux) else: self.owner.memory.pack_word(self.relative_addr, self.resolvedby.rebased_addr) return True class R_PPC64_RELATIVE(generic.GenericRelativeReloc): pass class R_PPC64_IRELATIVE(generic.GenericIRelativeReloc): pass class R_PPC64_ADDR64(generic.GenericAbsol...
DTPREL64(generic.GenericTLSDoffsetReloc): pass class R_PPC64_TPREL64(generic.GenericTLSOffsetReloc): pass class R_PPC64_REL24(ELFReloc): """ Relocation Type: 10 Calculation: (S + A - P) >> 2 Field: low24* """ @property def value(self): A = self.addend S = self.resol...
ai-se/Transfer-Learning
src/utils/misc_utils.py
Python
unlicense
344
0
def flatten(x): """ Takes an N times nested list of list like [[a
,b],[c, [d, e]],[f]] and
returns a single list [a,b,c,d,e,f] """ result = [] for el in x: if hasattr(el, "__iter__") and not isinstance(el, str): result.extend(flatten(el)) else: result.append(el) return result
brentp/gemini
gemini/annotation_provenance/gene_table/combined_gene_table.py
Python
mit
9,693
0.018983
""" For a detailed gene table and a summary gene table """ #!/usr/bin/env python from collections import defaultdict filename = 'detailed_gene_table_v75' detailed_out = open(filename, 'w') file = 'summary_gene_table_v75' summary_out = open(file, 'w') # write out files for detailed and summary gene table detailed_...
phen = string.split(",") phenotype = ",".join([x for x in phen if x != "None"]) if hgnc != "None": list_hgnc.append(hgnc) #we
don't want string of Nones if "None" in previous and "None" in synonyms and "None" in hgnc: string = None else: # We would like all genes names to be put together gene_string = hgnc+","+previous+","+synonyms #get rid of Nones in gene strings ...
nicolas471/Lecole
main/migrations/0015_auto_20160404_1648.py
Python
gpl-3.0
433
0.002309
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('main', '0014_generalsetting_titulo'),
] operations = [ migrations.AlterField( model_name='imagen', name='img', field=models.ImageField(upload_to=b'imgenEvento', verbose_name=b'Ruta
'), ), ]
kmahyyg/learn_py3
modules/mymodule2/__init__.py
Python
agpl-3.0
107
0.018692
#!/usr/bin
/env python3 # -*- coding : utf
-8 -*- def mymodules2(): print("test module2!") mymodules2()
wdv4758h/ZipPy
lib-python/3/idlelib/PyShell.py
Python
bsd-3-clause
52,145
0.001285
#! /usr/bin/env python3 import getopt import os import os.path import re import socket import subprocess import sys import threading import time import tokenize import traceback import types import linecache from code import InteractiveInterpreter try: from tkinter import * except ImportError: print("** IDLE...
e breaks functionality # needs to be re-verified, since the breaks at the time the # t
emp file is created may differ from the breaks at the last # permanent save of the file. Currently, a break introduced # after a save will be effective, but not persistent. # This is necessary to keep the saved breaks synched with the # saved file. # # ...
transifex/hermes
test_hermes/test_client.py
Python
bsd-3-clause
17,562
0.000228
from __future__ import absolute_import from Queue import Empty from random import randint from time import sleep import os from unittest import TestCase, skipUnless from signal import SIGINT, SIGCHLD from select import error as select_error from os import getpid from mock import MagicMock, patch, PropertyMock from psy...
self.client.directory_observer = MagicMock() def test_start_schedules_obeserver_if_watch_path(self): self.client._watch_path = randint(50, 1000) self.client._start_observer() self.client.directory_observer.schedule.assert_called_once_with( self.client, self.client._watc...
ent.directory_observer.start.assert_called_once_with() def test_start_not_schedule_observer_if_none_watch_path(self): self.client._watch_path = None self.client._start_observer() self.assertEqual(self.client.directory_observer.schedule.call_count, 0) self.assertEqual(self.client.di...
wtolson/gnsq
gnsq/backofftimer.py
Python
bsd-3-clause
899
0
# -*- coding: utf-8 -*- from __future__ import absolute_import import random class BackoffTimer(object): def __init__(self, ratio=1, max_interval=None, min_interval=None): self.c = 0 self.ratio = ratio self.max_interval = max_interval self.min_interval = min_interval def is_r...
.ratio if self.max_interval is not None: interval = min(interval, self.max_interval) if self.min_interval is not
None: interval = max(interval, self.min_interval) return interval
tesb/flask-crystal
venv/Lib/site-packages/pip/commands/wheel.py
Python
apache-2.0
7,402
0.003513
# -*- coding: utf-8 -*- from __future__ import absolute_import import os import sys from pip.basecommand import Command from pip.index import PackageFinder from pip.log import logger from pip.exceptions import CommandError, PreviousBuildDirError from pip.req import InstallRequirement, RequirementSet, parse_requirement...
finder, options.wheel_dir, build_options = options.build_options or [], global_options = options.global_options or [] ) wb.build() except PreviousBuildDirError: options.no_clean = True raise fina...
anup_files()
holloway/docvert-python3
core/pipeline_type/generatepostconversioneditorfiles.py
Python
gpl-3.0
263
0.003802
# -*- coding: utf-8 -*- import os impo
rt lxml.etree import io from . import pipeline_item import core.docvert_exception class GeneratePostConversionEditorFiles(pipeline_item.pipeline_stage): def stage(self, p
ipeline_value): return pipeline_value
k4cg/Rezeptionistin
plugins/flatter.py
Python
mit
687
0.016012
import random from plugin import Plugin class Flatter(Plugin): def help_text(self, bot): return bot.translate("flatter_help") def on_msg(self, bot, user_nick, host, channel, message): if message.lower(
).startswith(bot.translate("flatter_cmd")): if len(message.split()) >= 2: if bot.getlanguage() == "de": bot.send_message(channel, message.split()[1] + ", " + random.choice(list(open('lists/flattery.txt'))), user_nick) elif bot.getlanguage() == "en": # Source http://www.pickuplin...
bot.send_message(channel, message.split()[1] + ", " + random.choice(list(open('lists/flattery_en.txt'))), user_nick)
BorisJeremic/Real-ESSI-Examples
motion_one_component/Deconvolution_DRM_Propagation_Northridge/python_plot_parameteric_study.py
Python
cc0-1.0
5,870
0.019591
import scipy as sp import numpy as np import matplotlib.pyplot as plt import matplotlib import sys import matplotlib.lines as lines import h5py from matplotlib.font_manager import FontProperties import matplotlib.ticker as ticker from scipy.fftpack import fft axial_label_font = FontProperties() axial_label_font.se...
h[x] = max(abs(current_ac
celeration_component[0, :])); # ax.plot(Time, plot_current_acceleration[0, :], '-k', linewidth= 1); # plt.gca().set_ylim([-1,13]); # plt.gca().invert_yaxis() # # plt.gca().get_xaxis().set_ticks(np.arange(0, 60.1, 10)) # # plt.gca().get_yaxis().set_ticks(np.arange(-15, 3.1, 3)) # plt.gca().get_yaxis().set_...
jocelynmass/nrf51
toolchain/arm_cm0/arm-none-eabi/lib/thumb/v7-m/libstdc++.a-gdb.py
Python
gpl-2.0
2,482
0.006446
# -*- python -*- # Copyright (C) 2009-2017 Free Software Foundation, Inc. # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later versio...
s import gdb import os import os.path pythondir = '/Users/build/work/GCC-7-build/install-native/share/gcc-arm-none-eabi' libdir = '/Users/build/work/GCC-7-build/install-native/arm-none-eabi/lib/thumb/v7-m' # This file might be loaded when there is no current objfile. This # can happen if the user loads it manually. ...
e we don't # update sys.path; instead we just hope the user managed to do that # beforehand. if gdb.current_objfile () is not None: # Update module path. We want to find the relative path from libdir # to pythondir, and then we want to apply that relative path to the # directory holding the objfile with wh...
davidgardenier/frbpoppy
tests/monte_carlo/simulations.py
Python
mit
14,711
0
"""Run Monte Carlo simulations.""" from joblib import Parallel, delayed from frbpoppy import Survey, CosmicPopulation, SurveyPopulation, pprint from datetime import datetime from copy import deepcopy from glob import glob import frbpoppy.paths import os import numpy as np import pandas as pd from tqdm import tqdm impo...
phas)) Parallel(n_jobs=n_cpu)(delayed(iter_alpha)(i) for i in tqdm(r)) else: [iter_alpha(i) for i in tqdm(range(len(alphas)))] def gen_par_set_2(self, parallel=True, alpha=-1.5, si=0, w_mean=np.n...
td=np.nan, dm_igm_slope=np.nan, dm_host=np.nan, run=np.nan): lis = np.linspace(-1.5, 0, 11) lum_mins = 10**np.linspace(38, 46, 11) lum_maxs = 10**np.linspace(38, 46, 11) # Put all options into a dataframe self.so....
YiqunPeng/Leetcode-pyq
solutions/661ImageSmoother.py
Python
gpl-3.0
684
0.010234
class Solution(object): def imageSmoother(self, M): """ :type M: List[List[int]] :rtype: List[List[int]] """ ro
w, col = len(M), len(M[0]) ans = [[0]*col
for i in xrange(row)] for i in xrange(row): for j in xrange(col): cnt = 0 val = 0 for p in xrange(-1, 2): for q in xrange(-1, 2): if ((i+p)<0) or ((i+p)>=row) or ((j+q)<0) or ((j+q)>=col): ...
nbr23/nemubot
modules/rnd.py
Python
agpl-3.0
1,491
0.003353
"""Help to make choice""" # PYTHON STUFFS ####################################################### import random import shlex from nemubot import context from nemubot.exception import IMException from nemubot.hooks import hook from nemubot.module.more import Response # MODULE INTERFACE ############################...
################### @hook.command("choice") def cmd_choice(msg): if not len(msg.args): raise IMException("indicate some terms to pick!") return Response(random.choice(msg.args), channel=msg.channel, nick=msg.frm) @hook.command("choicecmd") def cmd_choicecmd(ms...
ex.split(random.choice(msg.args)) return [x for x in context.subtreat(context.subparse(msg, choice))] @hook.command("choiceres") def cmd_choiceres(msg): if not len(msg.args): raise IMException("indicate some command to pick a message from!") rl = [x for x in context.subtreat(context.subparse(msg...
stopstop/duvet
duvet/objects.py
Python
gpl-3.0
1,485
0.003367
from datetime import datetime import uuid class Torrent(object): def __init__(self): self.tracker = None self.url = None self.title = None self.magnet = None self.seeders = None self.leechers = None self.size = None self.date = None self.detai...
"%s Size: %s Seeders: %s Age: %s %s" % (self.title.ljust(60)[0:60], str(self.human_size).ljust(12), str(self.seeders).ljust(6), self.human_age,
self.tracker) def __str__(self): return self.__unicode__()
Kromey/piroute
iptables/utils.py
Python
mit
808
0.001238
from . import services def prep_rules(rules): prepped = [] for rule in rules: if rule['enabled']: prepped.append(prep_rule(rule)) return prepped def prep_rule(raw_rule): rule = dict(raw_rule) if rule['service'] != 'custom': proto, port = services.decode_service(rul...
if not (proto and port): raise ValueError("Unknown service: {service}".format( servi
ce=rule['service'] )) rule['proto'] = proto rule['port'] = port if not rule['comment']: rule['comment'] = "{service} service ({proto}:{port})".format( service=rule['service'], proto=proto, port=port ...
alonho/pql
pql/matching.py
Python
bsd-3-clause
14,159
0.00678
""" The parser: 1. gets and expression 2. parses it 3. handles all boolean logic 4. delegates operator and rvalue parsing to the OperatorMap SchemaFreeOperatorMap supports all mongo operators for all fields. SchemaAwareOperatorMap 1. verifies fields exist. 2. verifies operators are applied to fields of correc...
(self, *a, **k): super(SchemaAwareParser, self).__init__(SchemaAwareOperatorMap(*a, **k)) class FieldName(AstHandler): def handle_Str(self, node): return node.s def handle_Name(self, name): return name.id def
handle_Attribute(self, attr): return '{0}.{1}'.format(self.handle(attr.value), attr.attr) class OperatorMap(object): def resolve_field(self, node): return FieldName().handle(node) def handle(self, operator, left, right): field = self.resolve_field(left) return {field: self.resol...
mattdennewitz/python-acoustid-api
acoustid_api/consts.py
Python
mit
819
0
from __future__ import unicode_literals from . import exceptions DEFAULT_HOST = 'http://api.acoustid.org/' FORMATS = ('json', 'jsonp', 'xml') META = ( 'recordings', 'recordingids', 'releases', 'releaseids', 'releasegroups', 'releasegroupids', 'tracks', 'compress', 'usermeta', 'sources' ) ERRORS
= { 1: exceptions.UnknownFormat, 2: exceptions.MissingParameter, 3: e
xceptions.InvalidFingerprint, 4: exceptions.InvalidClientKey, 5: exceptions.InternalError, 6: exceptions.InvalidUserApiKey, 7: exceptions.InvalidUUID, 8: exceptions.InvalidDuration, 9: exceptions.InvalidBitrate, 10: exceptions.InvalidForeignID, 11: exceptions.InvalidMaxDurationDiff, ...
ioanaantoche/muhaha
ioana/RecordAudio.py
Python
gpl-2.0
757
0.018494
import s
ys import time from naoqi import ALProxy IP = "nao.local" PORT = 9559 if (len(sys.argv) < 2): print "Usage: 'python RecordAudio.py nume'" sys.exit(1) fileName = "/home/nao/" + sys.argv[1] + ".wav" aur = ALProxy("ALAudioRecorder", IP, PORT) channels = [0,0,1,0] aur.startMicrophonesRecording(fileName, "wav",...
udioPlayer", IP, PORT) #Launchs the playing of a file aup.playFile(fileName,0.5,-1.0) c=raw_input("gata?") #Launchs the playing of a file #aup.playFile("/usr/share/naoqi/wav/random.wav") #Launchs the playing of a file on the left speaker to a volume of 50% #aup.playFile("/usr/share/naoqi/wav/random.wav",0.5,-1.0)
nuigroup/pymt-widgets
pymt/tools/packaging/win32/build.py
Python
lgpl-3.0
6,313
0.010771
import os, sys, shutil import zipfile from zipfile import ZipFile from urllib import urlretrieve from subprocess import Popen, PIPE from distutils.cmd import Command def zip_directory(dir, zip_file): zip = ZipFile(zip_file, 'w', compression=zipfile.ZIP_DEFLATED) root_len = len(os.path.abspath(dir)) ...
ion build (either --no_cext or --no_mingw option set)" else: print "*Compiling C Extensions inplace for portable distribution" cext_cmd = [sys.executable, #path to python.exe 'setup.py', 'build_ext', #make setup.py create a src distrib...
'--inplace'] #do it inplace #this time it runs teh setup.py inside the source distribution #thats has been generated inside the build dir (to generate ext #for teh target, instead of the source were building from) Popen(cext_cmd, cwd=src_dist, stdout=...
samsu/neutron
plugins/nuage/common/exceptions.py
Python
apache-2.0
919
0
# Copyright 2014 Alcatel-Lucent USA Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable l...
d limitations # under the License. ''' Nuage specific exceptions ''' from neutron.common import exceptions as n_exc class OperationNotSupported(n_exc.InvalidConfigurationOption): message = _("Nuage Plugin does not support this operation: %(msg)s") class NuageBadRequest(n_exc.BadRequest): message = _("B...
t: %(msg)s")
christianknu/eitu
eitu/migrations/0001_initial.py
Python
mit
662
0.001511
# -*- coding: utf-8 -*- # Generated by Django 1.10 on 2016-10-26 14:20 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Occupanc...
=False, verbose_name='ID')), ('room_name', models.CharField(max_length=255)), ('occupancy', models.IntegerField()), ('timestamp', models.DateF
ield()), ], ), ]
troeger/opensubmit
web/opensubmit/templatetags/projecttags.py
Python
agpl-3.0
1,869
0.000535
from django import template from django.conf import settings from django.template.defaultfilters import stringfilter import os register = template.Library() @register.filter(name='basename') @stringfilter def basename(value): return os.path.basename(value) @register.filter(name='replace_macros') @stringfilter...
ml') def details_table(submission): return {'submission': submission} @register.inclusion_tag('inclusion_tags/deadline.html') def deadline_timeout(assignment): return {'assignment': assignment, 'show_timeout': True} @register.inclusion_tag('inclusion_tags/deadline.html') def deadline(assignment): return...
.html') def grading(submission): return {'submission': submission}
capybaralet/Blocks_quickstart
basic_blocks_script.py
Python
mit
3,082
0.00292
""" This script is a starting point for new Blocks users already familiar with Machine Learning and Theano. We demonstrate how to use blocks to train a generic set of parameters (theano shared variables) that influence some arbitrary cost function (theano symbolic variable), so you can start using blocks featu
res (e.g. monitoring, extensions, training algorithms) with your Theano code toda
y. To run an experiment, we simply construct a main_loop.MainLoop and call its run() method. It suffices to pass the MainLoop a blocks.model.Model (which needs the cost), a blocks.algorithms.TrainingAlgorithm (which needs the cost and parameters), and a fuel.streams.DataStream* As it is the script will run indefi...
TonyWu386/redshift-game
main.py
Python
gpl-2.0
49,393
0.000121
# ----------------------------------------------------------------------------- # File name: main.py # # Date created: 3/20/2014 # # Date last modified: 1/18/2015 # ...
() introsplash = pygame.image.load(isplash).convert() introsplash2 = pygame.image.load(isplash2).convert() startscreen = pygame.image.load(sscreen).convert() helpscreen = pygame.image.load(hscreen).convert() boss1white = pygame.image.load(b1w).convert_alpha() boss2white = pygame.image.load(b2w)....
onvert_alpha() laser1 = pygame.image.load(las1).convert_alpha() laserred = pygame.image.load(lasr).convert_alpha() laserredver = pygame.transform.rotate(pygame.image.load(lasr). convert_alpha(), 90) enginefire = pygame.image.load(efire).convert_alpha() engin...
jeremiedecock/snippets
python/datetime_snippets.py
Python
mit
605
0
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import datetime # Datetime ############################ dt = datetime.datetime.now() print(dt) dt = datetime.datetime(year=2018, month=8, day=30, hour=13, minute=30) print(dt) print(dt.isoformat()) # Date ################################ d = datetime.date.today() pr...
############################ t = datetime.datetime.now().time() print(t) t = datet
ime.time(hour=1, minute=30) print(t) print(t.isoformat())
azaghal/ansible
test/lib/ansible_test/_internal/cloud/aws.py
Python
gpl-3.0
3,937
0.002286
"""AWS plugin for integration tests.""" from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os from ..util import ( ApplicationError, display, ConfigParser, ) from . import ( CloudProvider, CloudEnvironment, CloudEnvironmentConfig, ) from ..core_ci ...
e: list[str] """ if os.path.isfile(self.config_static_path): return aci = self._create_ansible_core_ci() if aci.available: return super(AwsCloudProvider, self).filter(targets, exclude) def setup(self): """Setup the cloud resource before del...
if os.path.exists(aws_config_path) and not self.args.docker and not self.args.remote: raise ApplicationError('Rename "%s" or use the --docker or --remote option to isolate tests.' % aws_config_path) if not self._use_static_config(): self._setup_dynamic() def _setup_dynamic(self...
chryswoods/SireTests
unittests/SireMM/testgridff2.py
Python
gpl-2.0
3,699
0.011895
from Sire.IO import * from Sire.MM import * from Sire.System import * from Sire.Mol import * from Sire.Maths import * from Sire.FF import * from Sire.Move import * from Sire.Units import * from Sire.Vol import * from Sire.Qt import * import os coul_cutoff = 20 * angstrom lj_cutoff = 10 * angstrom amber = Amber() (...
\nEnergies") print(gridff.energies()) print(gridff2.energies()) t = QTime() t.start() nrgs = cljff.energies() ms = t.elapsed() print(cl
jff.energies()) print("Took %d ms" % ms) testff.calculateEnergy() t.start() nrgs = cljff2.energies() ms = t.elapsed() print("\nExact compare") print(cljff2.energies()) print("Took %d ms" % ms)
nikesh-mahalka/cinder
cinder/volume/drivers/dothill/dothill_client.py
Python
apache-2.0
14,785
0
# Copyright 2014 Objectif Libre # Copyright 2015 DotHill Systems # # 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 # # U...
for prop in obj.iter("PROPERTY")
if prop.get('name') in
tensorflow/probability
tensorflow_probability/python/distributions/moyal_test.py
Python
apache-2.0
10,137
0.002861
# Copyright 2020 The TensorFlow Probability 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 o...
f(x, loc=loc, scale=scale)) pdf = moyal.prob(self.
make_tensor(x)) self.assertAllClose( self.evaluate(pdf), stats.moyal.pdf(x, loc=loc, scale=scale)) def testMoyalCDF(self): batch_size = 6 loc = np.array([0.] * batch_size, dtype=self.dtype) scale = np.array([3.] * batch_size, dtype=self.dtype) x = np.array([2., 3., 4., 5., 6., 7.], dtype=...
martynbristow/gabbi-examples
test_server.py
Python
mit
367
0.016349
""" Unit
Tests for the SimpleHTTPServer """ import mock import unittest class TestHTTPServerHandler(unittest.TestCase): """ """ def setUp(self): self.handler = mock.Mock() def test_do_GET(self): pass def test_do_POST(self): pass def tearDown(self): self.handler() if __na...
n()
krishnakantkumar0/Simple-Python
13.py
Python
gpl-3.0
147
0.040816
#a=[int(x) for x in input().split()] #print (a) x=5
y=10 b=[int(y) for y in input().split()] #a=[i
nt(x) for x in input().split()] dir(_builtins_)
JaeGyu/PythonEx_1
20170106.py
Python
mit
455
0.004728
a = "python" print(a*2) try: p
rint(a[-10]) except IndexError as e: print("์ธ๋ฑ์Šค ๋ฒ”์œ„๋ฅผ ์ดˆ๊ณผ ํ–ˆ์Šต๋‹ˆ๋‹ค.") print(e) print(a[0:4]) print(a[1:-2]) # -10์€ hi๋’ค๋กœ 10์นธ print("%-10sjane." % "hi") b = "Python is best choice." print(b.find("b")) print(b.find("B")) try: print(b.index("B")) except ValueError as e: print(e) c = "hi" print(c.upper()) a =...
(a.strip())
SmartElect/SmartElect
rollgen/generate_pdf.py
Python
apache-2.0
5,841
0.003938
# 3rd party imports from reportlab.platypus import Image, Paragraph, PageBreak, Table, Spacer from reportlab.lib.units import cm from reportlab.lib.pagesizes import A4 # Django imports from django.conf import settings # Project imports from .arabic_reshaper import reshape from .pdf_canvas import NumberedCanvas, getAr...
PageBreak(), ] # Focus on one specific gender. voter_roll = [voter for voter in voter_roll if voter.gender == gender] # We wrap the page header in a table becau
se we want the header's gray background to extend # margin-to-margin and that's easy to do with a table + background color. It's probably # possible with Paragraphs alone, but I'm too lazy^w busy to figure out how. # It's necessary to wrap the table cell text in Paragraphs to ensure the base tex...
Geosyntec/python-tidegates
tidegates/__init__.py
Python
bsd-3-clause
67
0
from .analysis import * f
rom .toolbox import * from . import
utils
pantsbuild/pex
pex/vendor/_vendored/setuptools/setuptools/archive_util.py
Python
apache-2.0
6,730
0.000594
"""Utilities for extracting common archive formats""" import zipfile import tarfile import os import shutil import posixpath import contextlib from distutils.errors import DistutilsError if "__PEX_UNVENDORED__" in __import__("os").environ: from pkg_resources import ensure_directory # vendor:skip else: from pex.t...
ilename) with open(target, 'wb') as f: f.write(data) unix_attributes = info.external_attr >> 16 if unix_attributes: os.chmod(target, unix_attributes) def unpack_tarfile(filename, extract_dir, progress_filter=default_filter): """Unpack tar...
to `extract_dir` Raises ``UnrecognizedFormat`` if `filename` is not a tarfile (as determined by ``tarfile.open()``). See ``unpack_archive()`` for an explanation of the `progress_filter` argument. """ try: tarobj = tarfile.open(filename) except tarfile.TarError: raise Unrecogni...
python-astrodynamics/astrodynamics
tests/test_constants.py
Python
mit
2,079
0.000962
# coding: utf-8 # These tests are taken from astropy, as with the astrodynamics.constant.Constant # class. It retains the original license (see licenses/ASTROPY_LICENSE.txt) from __future__ import absolute_import, division, print_function import copy import astropy.units as u from astropy.units import Quantity impor...
2.value == x.value assert type(q2) is Quantity assert not hasattr(q2, 'reference') x3 = Quantity(x, subok=True) assert x3 == x assert x3.value == x.
value # make sure it has the necessary attributes and they're not blank assert x3.uncertainty assert x3.name == x.name assert x3.reference == x.reference assert x3.unit == x.unit x4 = Quantity(x, subok=True, copy=False) assert x4 is x def test_repr(): a = Constant('the name', value=1,...
rsignell-usgs/notebook
CSW/data.ioos.us-pycsw.py
Python
mit
2,570
0.01323
# coding: utf-8 # # Query `apiso:ServiceType` # In[43]: from owslib.csw import CatalogueServiceWeb from owslib import fes import numpy as np # The GetCaps request for these services looks
like this: # http://catalog.data.gov/csw-all/csw?SERVICE=CSW&VERSION=2.0.2&REQUEST=GetCapabilities # In[56]: endpoint = 'http://data.ioos.us/csw' # FAILS apiso:ServiceType #endpoint = 'http://catalog.data.gov/csw-a
ll' # FAILS apiso:ServiceType #endpoint = 'http://geoport.whoi.edu/csw' # SUCCEEDS apiso:ServiceType csw = CatalogueServiceWeb(endpoint,timeout=60) print csw.version # In[57]: csw.get_operation_by_name('GetRecords').constraints # Search first for records containing the text "COAWST" and "experimental". # In[45...
chipx86/reviewboard
reviewboard/webapi/tests/test_remote_repository.py
Python
mit
5,858
0
from __future__ import unicode_literals import json from django.utils import six from kgb import SpyAgency from reviewboard.hostingsvcs.github import GitHub from reviewboard.hostingsvcs.models import HostingServiceAccount from reviewboard.hostingsvcs.repository import RemoteRepository from reviewboard.hostingsvcs.ut...
e_name), data=json.dumps({ 'authorization': { 'token': '123', }, })) remote_repository = RemoteRepository( account.service, repository_id='123', name='repo1', owner='bob', scm...
path='ssh://example.com/repo1', mirror_path='https://example.com/repo1') self.spy_on(GitHub.get_remote_repository, owner=GitHub, call_fake=lambda *args, **kwargs: remote_repository) return (get_remote_repository_item_url(remote_repository...
betrisey/home-assistant
homeassistant/components/media_player/sonos.py
Python
mit
20,355
0
""" Support to interface with Sonos players (via SoCo). For more details about this platform, please refer to the documentation at https://home-assistant.io/components/media_player.sonos/ """ import datetime import logging from os import path import socket import urllib import voluptuous as vol from homeassistant.com...
orator, avoid calling the decorated meth
od if player is not a coordinator. If not, a grouped speaker (not in coordinator role) will throw soco.exceptions.SoCoSlaveException. Also, partially catch exceptions like: soco.exceptions.SoCoUPnPException: UPnP Error 701 received: Transition not available from <player ip address> """ def...
thumbor/thumbor
tests/handlers/test_base_handler_with_auto_webp.py
Python
mit
7,701
0.00013
#!/usr/bin/python # -*- coding: utf-8 -*- # thumbor imaging service # https://github.com/thumbor/thumbor/wiki # Licensed under the MIT license: # http://www.opensource.org/licenses/mit-license # Copyright (c) 2011 globo.com thumbor@googlegroups.com from shutil import which from unittest.mock import patch from urllib...
imated_gifs_to_webp(self): response = await self.get_as_webp("/unsafe/animated.gif") expect(response.code).to_e
qual(200) expect(response.headers).not_to_include("Vary") expect(response.body).to_be_gif() @gen_test async def test_should_convert_image_with_small_width_and_no_height(self): response = await self.get_as_webp("/unsafe/0x0:1681x596/1x/image.jpg") expect(response.code).to_equal(...
giosalv/526-aladdin
MachSuite/script/llvm_compile.py
Python
apache-2.0
3,257
0.023641
#!/usr/bin/env python import os import sys import string import random def id_generator(size=6, chars=string.ascii_uppercase + string.digits): return ''.join(random.choice(chars) for _ in range(size)) kernels = { 'aes-aes' : 'gf_alog,gf_log,gf_mulinv,rj_sbox,rj_xtime,aes_subBytes,aes_addRoundKey,aes_addRoundKey...
' -fno-slp-vectorize -fno-vectorize -fno-unroll-loops ' + \ ' -fno-inline -fno-builtin -emit-llvm -o ' + test_obj + ' ' + test print command os.system(command) command = 'opt -S -load=' + os.getenv('TRACER_HOME') + \ '/full-trace/full_trace.so -fulltrace ' + obj + ' -o ' + opt_obj ...
afaquejam/Linked-List-Problems
Others/FrontBackSplit.py
Python
mit
1,330
0.003008
import Linked_List import sys import random def split_list(lst, a, b): if lst.length % 2 == 1: first_length = (lst.length / 2) + 1 else: first_length = lst.length / 2 list_iterator = lst.head count = 0 while count < first_length: a.append(list_iterator.data) list_i...
Linked_List.LinkedList() for iterator in range(0, int(sys.argv[1])): lst.push(random.randint(1, 101)) print "\nOriginal List:" lst.print_list() a = Linked_List.LinkedList() b = Linked_List.LinkedList() split_list(lst, a
, b) print "\nSplitted List A:" a.print_list() print "\nSplitted List B:" b.print_list() # Performance # ------------ # # * Speed # The algorithm traverses the original list once and constructs # both the list. The list construction operation (append) can be implemented with # O(1) complexity. In a nutshell, the time...
MeGotsThis/BotGotsThis
lib/helper/textformat.py
Python
gpl-3.0
11,881
0
๏ปฟimport re from typing import Callable, Dict, List # noqa: F401 FormatText = Callable[[str], str] ascii: str = (''' !"#$%&'()*+,-./''' '0123456789' ':;<=>?@' 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' r'[\]^_`' 'abcdefghijklmnopqrstuvwxyz' '{|}~')...
+,-./''' '๐Ÿถ๐Ÿท๐Ÿธ๐Ÿน๐Ÿบ๐Ÿป๐Ÿผ๐Ÿฝ๐Ÿพ๐Ÿฟ' ':;<=>?@' '๐™ฐ๐™ฑ๐™ฒ๐™ณ๐™ด๐™ต๐™ถ๐™ท๐™ธ๐™น๐™บ๐™ป๐™ผ๐™ฝ๐™พ๐™ฟ๐š€๐š๐š‚๐šƒ๐š„๐š…๐š†๐š‡๐šˆ๐š‰'
r'[\]^_`' '๐šŠ๐š‹๐šŒ๐š๐šŽ๐š๐š๐š‘๐š’๐š“๐š”๐š•๐š–๐š—๐š˜๐š™๐šš๐š›๐šœ๐š๐šž๐šŸ๐š ๐šก๐šข๐šฃ' '{|}~') doubleStruck: str = (''' !"#$%&'()*+,-./''' '๐Ÿ˜๐Ÿ™๐Ÿš๐Ÿ›๐Ÿœ๐Ÿ๐Ÿž๐ŸŸ๐Ÿ ๐Ÿก' ':;<=>?@' '๐”ธ๐”นโ„‚๐”ป๐”ผ๐”ฝ๐”พโ„๐•€๐•๐•‚๐•ƒ๐•„โ„•๐•†โ„™โ„šโ„๐•Š๐•‹๐•Œ๐•๐•Ž๐•๐•โ„ค' ...