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
xfaxca/pymlkit
pymlkit/preproc/eda.py
Python
gpl-3.0
2,894
0.003455
# explore.py """ Module containing functionality for exploratory data analysis and visualization. """ import seaborn as sns import matplotlib.pyplot as plt __all__ = [ 'class_proportions', 'see_nulls', 'distplots', 'pairplots' ] # ====== Data Statistics def class_proportions(y): """ Function...
features = [features] else: title_str = ", ".join(features) ax_label = "" for feature in features: ax_label += ('| %s |' % feature) sns.distplot(df[feature].values, label=feature, norm_hist=True) plt.xlabel(s=ax_label) plt.legend(fontsize=12) plt.title('Distrib...
) def pairplots(df, features, kind='reg', diag_kind='kde'): """ Function to make a quick pairplot of selected features :param df: DataFrame containing the feature matrix :param features: (str/list) Features selected for inclusion in pairplot. :param kind: (str) Kind of plot for the non-identity re...
timwaizenegger/osecm-sdos
mcm/__init__.py
Python
mit
1,307
0.012242
#!/usr/bin/python # coding=utf-8 """ Project MCM - Micro Content Management SDOS - Secure Delete Object Store Copyright (C) <2016> Tim Waizenegger, <University of Stuttgart> This software may be modified and distributed under the terms of the MIT license. See the LICENSE file for details. """ import logging,...
iguration log_format = '%(asctime)s %(module)s %(name)s[%(process)d][%(thread)d] %(levelname)s %(message)s' field_styles = {'module': {'color': 'magenta'}, 'hostname': {'color': 'magenta'}, 'programname': {'color': 'cyan'}, 'name': {'color': 'blue'}, 'levelname': {'color': 'black', 'bold': True}, 'asct...
t, field_styles=field_styles) #logging.getLogger("werkzeug").setLevel(level=logging.WARNING) #logging.getLogger("swiftclient").setLevel(level=logging.WARNING) """ logging.basicConfig(level=configuration.log_level, format=configuration.log_format) """ logging.error("###################################################...
mozillazg/mzgblog
model.py
Python
mit
30,298
0.018222
# -*- coding: utf-8 -*- import os,logging from google.appengine.api import users from google.appengine.ext import db from google.appengine.ext.db import Model as DBModel from google.appengine.api import memcache from google.appengine.api import mail from google.appengine.api import urlfetch from google.appengi...
.server_dir) def __getattr__(sel
f, name): if self.mapping_cache.has_key(name): return self.mapping_cache[name] else: path ="/".join((self.name,'templates', name + '.html')) logging.debug('path:%s'%path) ## if not os.path.exists(path): ## path = os.path.join(rootpat...
andrebellafronte/stoq
stoq/gui/test/test_purchase.py
Python
gpl-2.0
11,536
0.00156
# -*- coding: utf-8 -*- # vi:si:et:sw=4:sts=4:ts=4 ## ## Copyright (C) 2012 Async Open Source <http://www.async.com.br> ## All rights reserved ## ## 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 Foundati...
u'purchase') for purchase in app.results: purchase.open_date = datetime.datetime(2012, 1, 1) olist = app.results olist.select(olist[0]) with mock.patch('stoq.gui.purchase.api',
new=self.fake.api): self.fake.set_retval(purchase) self.activate(app.NewQuote) self.assertEquals(run_dialog.call_count, 1) args, kwargs = run_dialog.call_args wizard, store, edit_mode = args self.assertEquals(wizard, QuotePurchaseWizard) ...
ZanyLeonic/LeonicBinaryTool
ConUpdate.py
Python
gpl-3.0
5,039
0.009724
import argparse, requests, sys,
configparser, zipfile, os, shutil from urllib.parse import urlparse, parse_qs appname="ConverterUpdater" author="Leo Durrant (2017)" builddate="05/10/17" version="0.1a" release="alpha" filesdelete=['ConUpdate.py', 'Converter.py', 'LBT.py', 'ConverterGUI.py', 'LB
TGUI.py'] directoriesdelete=['convlib\\', 'LBTLIB\\', "data\\images\\", "data\\text\\"] def readvaluefromconfig(filename, section, valuename): try: config = configparser.ConfigParser() config.read(filename) try: val = config[section][valuename] return val exc...
hycis/Pynet
hps/models/Laura_Two_Layers.py
Python
apache-2.0
2,815
0.005329
from jobman import DD, expand, flatten import pynet.layer as layer from pynet.model import * from pynet.layer import * from pynet.datasets.mnist import Mnist, Mnist_Blocks import pynet.datasets.spec as spec import pynet.datasets.mnist as mnist import pynet.datasets.transfactor as tf import pynet.datasets.mapping as ma...
model'] = self.state.hidden1.model database['records']['h2_mo
del'] = self.state.hidden2.model log = self.build_log(database) log.info("Fine Tuning") for layer in model.layers: layer.dropout_below = None layer.noise = None train_obj = TrainObject(log = log, dataset = dataset, ...
rwl/muntjac
muntjac/demo/sampler/features/menubar/MenuBarItemStylesExample.py
Python
apache-2.0
2,645
0.000378
from muntjac.ui.vertical_layout import VerticalLayout from muntjac.ui.menu_bar import MenuBar, ICommand from muntjac.terminal.external_resource import ExternalResource class MenuBarItemStylesExample(VerticalLayout): def __init__(self): super(MenuBarItemStylesExample, self).__init__() self._menu...
and) f.addItem('Close', menuCommand) f.addItem('Close All', menuCommand).setStyleName('close-all') f.addSeparator() f.addItem('Save', menuCommand) f.addItem('Save As...', menuCommand) f.addItem('Save All', menuCommand) edit = self._menubar.addItem('Edit', None) ...
addItem('Undo', menuCommand) edit.addItem('Redo', menuCommand).setEnabled(False) edit.addSeparator() edit.addItem('Cut', menuCommand) edit.addItem('Copy', menuCommand) edit.addItem('Paste', menuCommand) edit.addSeparator() find = edit.addItem('Find/Replace', menu...
krafczyk/spack
var/spack/repos/builtin/packages/picard/package.py
Python
lgpl-2.1
4,400
0.001136
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
version('2.18.0', '20045ff141e4a67512365f0b6bbd8229', expand=False) version('2.17.0', '72cc527f1e4ca6a799ae0117af60b54e', expand=False) version('2.16.0', 'fed8928b03bb36e355656f349e579083', expand=False) version('2.15.0', '3f5751630b1a3449edda47a0712a64e4', expand=False) version('2.13.2', '3d7b33fd1f43...
6f5', expand=False) version('2.10.0', '96f3c11b1c9be9fc8088bc1b7b9f7538', expand=False) version('2.9.4', '5ce72af4d5efd02fba7084dcfbb3c7b3', expand=False) version('2.9.3', '3a33c231bcf3a61870c3d44b3b183924', expand=False) version('2.9.2', '0449279a6a89830917e8bcef3a976ef7', expand=False) version('2....
calpaterson/dircast
dircast/feed.py
Python
gpl-3.0
848
0.005896
from feedgen.feed import FeedGenerator def format_itunes_duration(td): return "{hours:02d}:{minutes:02d}:{seconds:02d}".format( hours=td.seconds//3600, minutes=(td.seconds//60)%60, seconds=int(td.seconds%60) ) def add_entry(fg, md): fe = fg.add_entry() fe.id(md.id) fe.title...
th), "audio/mpeg") if md.duration is not None: fe.podcast.itunes_duration(format_itunes_duration(md.duration)) def generate_feed(channel_dict, file_metadatas): fg = FeedGenerator() fg.load_extension("podcast") fg.link(href=channel_dict["url"], rel="self") fg.title(channe
l_dict["title"]) fg.description(channel_dict["description"]) for file_metadata in file_metadatas: add_entry(fg, file_metadata) return fg.rss_str(pretty=True)
BhallaLab/moose
moose-examples/izhikevich/Izhikevich.py
Python
gpl-3.0
23,767
0.009593
# Izhikevich.py --- # # Filename: Izhikevich.py # Description: # Author: Subhasis Ray # Maintainer: # Created: Fri May 28 14:42:33 2010 (+0530) # Version: # Last-Updated: Tue Sep 11 14:27:18 2012 (+0530) # By: subha # Update #: 1212 # URL: # Keywords: # Compatibility: # # # Commentary: # # th...
10.0, -70.0, 160.0], # Fig. 1.E "
spike_freq_adapt": ['F', 0.01 , 0.2 , -65.0, 8.0 , 30.0, -70.0, 85.0 ], # Fig. 1.F # spike frequency adaptation "Class_1": ['G', 0.02 , -0.1 , -55.0, 6.0 , 0, -60.0, 300.0], # Fig. 1.G # Spikining Frequency increases with input strength "Class_2"...
ivmech/iviny-scope
lib/xlsxwriter/test/vml/test_write_idmap.py
Python
gpl-3.0
748
0
################
############################################################### # # Tests for XlsxWriter. # # Copyright (c), 2013, John McNamara, jmcnamara@cpan.org # import unittest from ...compatibility import StringIO from ...vml import Vml class TestWriteOidmap(unittest.TestCase): """ Test the Vml _write_idmap() method....
test_write_idmap(self): """Test the _write_idmap() method""" self.vml._write_idmap(1) exp = """<o:idmap v:ext="edit" data="1"/>""" got = self.fh.getvalue() self.assertEqual(got, exp) if __name__ == '__main__': unittest.main()
DBrianKimmel/PyHouse
Project/src/Modules/House/Family/Insteon/_test/test_insteon_light.py
Python
mit
6,285
0.002546
""" @name: PyHouse/src/Modules/Families/Insteon/_test/test_Insteon_HVAC.py @author: D. Brian Kimmel @contact: D.BrianKimmel@gmail.com @copyright: (c) 2014-2020 by D. Brian Kimmel @license: MIT License @note: Created on Dec 6, 2014 @Summary: Passed all 2 tests - DBK - 2015-07-29 """ __updated__ = '20...
from Modules.House.Lighting.Controllers.controllers import Api as controllerApi from Modules.House.Lighting.Lights.lights import Api as lightingApi from Modules.Core.Utilities.debug_tools import PrettyFormatAny from Modules.House.Family.Insteon.insteon_uti
ls import Decode as utilDecode from Modules.House.Family.Insteon import insteon_decoder from Modules.House.Family.Insteon.insteon_light import DecodeResponses as Decode_Light # 16.C9.D0 = # 1B.47.81 = MSG_50_A = bytearray(b'\x02\x50\x16\x62\x2d\x1b\x47\x81\x27\x09\x00') MSG_50_B = bytearray(b'\x02\x50\x21\x34\x1F\x1b\...
bingweichen/GOKU
backend/server/utility/__init__.py
Python
apache-2.0
61
0.016393
#
from server.utility.service_utility import count_total_
page
KonichiwaKen/band-dashboard
authentication/views.py
Python
mit
4,259
0.000704
import json from django.contrib.auth import authenticate from django.contrib.auth import login from django.contrib.auth import logout from django.contrib.auth import update_session_auth_hash from rest_framework import status from rest_framework import views from rest_framework import viewsets from rest_framework.permi...
odels import Band from emails.tasks import send_unsent_emails from members.models import BandMember class AccountViewSet(viewsets.ModelViewSet): queryset = Account.objects.all() serializer_class = AccountSerializer permission_classes = ( IsAccountAdminOrAccountOwner, IsAuthenticated, )...
est.data) if serializer.is_valid(): serializer.save() return Response(serializer.validated_data, status=status.HTTP_201_CREATED) return Response({ 'status': 'Bad request', 'message': 'Account could not be created with received data.', }, status=s...
MaxTyutyunnikov/lino
lino/utils/jscompressor.py
Python
gpl-3.0
5,152
0.011258
## {{{ http://code.activestate.com/recipes/496882/ (r8) ''' http://code.activestate.com/recipes/496882/ Author: Michael Palmer 13 Jul 2006 a regex-based JavaScript code compression kludge ''' import re class JSCompressor(object): def __init__(self, compressionLevel=2, measureCompression=False): ''' ...
Subst.sub(backsub, script) if self.measureCompression: lengthAfter = float(len(script)) squeezedBy = int(100*(1-lengthAfter/lengthBefore)) script += '\n// squeezed out %s%%\n' % squeezedBy return script if __name__ == '__main__': script = ''' /* this is ...
y "quoted string", surrounded by several superfluous line breaks */ // and this is an equally important single line comment sth = "this string contains 'quotes', a /regex/ and a // comment yet it will survive compression"; function wurst(){ // this is a great function var h...
tschaume/pymatgen
pymatgen/analysis/chemenv/coordination_environments/tests/test_coordination_geometries.py
Python
mit
19,397
0.005104
#!/usr/bin/env python __author__ = 'waroquiers' import unittest import numpy as np from pymatgen.util.testing import PymatgenTest from pymatgen.analysis.chemenv.coordination_environments.coordination_geometries import ExplicitPermutationsAlgorithm from pymatgen.analysis.chemenv.coordination_environments.coordinatio...
ns, 720.0) self.assertEqual(cg_oct.ref_permutation([0, 3, 2, 4, 5, 1]), (0, 3, 1, 5, 2, 4)) sites = [FakeSite(coords=pp) for pp in cg_oct.points] faces = [[[0.0, 0.0, 1.0], [1.0, 0.0, 0.0], [0.0, -1.0, 0.0]],
[[0.0, 0.0, 1.0], [1.0, 0.0, 0.0], [0.0, 0.0, -1.0]], [[0.0, 0.0, 1.0], [0.0, 1.0, 0.0], [0.0, -1.0, 0.0]], [[0.0, 0.0, 1.0], [0.0, 1.0, 0.0], [0.0, 0.0, -1.0]], [[-1.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, -1.0, 0.0]], [[-1.0, 0.0, 0.0], ...
denim2x/Vintageous
ex/parser/nodes.py
Python
mit
6,391
0.001095
from Vintageous.ex.ex_error import ERR_NO_RANGE_ALLOWED from Vintageous.ex.ex_error import VimError from Vintageous.ex.parser.tokens import TokenDigits from Vintageous.ex.parser.tokens import TokenDollar from Vintageous.ex.parser.tokens import TokenDot from Vintageous.ex.parser.tokens import TokenMark from Vintageous.e...
if token.content == '>': sel = list(view.sel())[0] view.sel().clear() view.sel().add(sel) if sel.a < sel.b
: return row_at(view, sel.b - 1) else: return row_at(view, sel.b) raise NotImplementedError() def resolve_line_reference(self, view, line_reference, current=0): ''' Calculates the line offset determined by @line_reference. @view ...
torkelsson/meta-package-manager
meta_package_manager/base.py
Python
gpl-2.0
11,025
0
# -*- coding: utf-8 -*- # # Copyright (c) 2016-2018 Kevin Deldycke <kevin@deldycke.com> # and contributors. # All Rights Reserved. # # 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 F...
cape codes, and returns ready-to-use strings. """ assert isinstance(args, list) logger.debug("Running `{}`...".format(' '.join(args))) code = 0 output = None error = None if not dry_run: code, output, error = run(*args) else: logg...
error = error if error else None if output: output = strip_ansi(output) output = output if output else None if code and error: exception = CLIError(code, output, error) if self.raise_on_cli_error: raise exception else: ...
tseaver/google-cloud-python
logging/google/cloud/logging/_helpers.py
Python
apache-2.0
3,909
0
# Copyright 2016 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, s...
tantiate. :type resource: dict :param resource: One entry resource from API response. :type client: :class:`~google.cloud.logging.client.Client` :param client: Client that
owns the log entry. :type loggers: dict :param loggers: A mapping of logger fullnames -> loggers. If the logger that owns the entry is not in ``loggers``, the entry will have a newly-created logger. :rtype: :class:`~google.cloud.logging.entries._BaseEntry` :returns: The entry ...
mswart/openvpn2dns
tests/test_parser.py
Python
mit
1,061
0.00377
# -*- coding: UTF-8 -*- from openvpnzone import extract_zones_from_status_file from IPy import IP def test_empty_server(): assert extract_zones_from_status_file('tests/samples/empty.ovpn-status-v1') \ == {} def test_one_client_on_server(): assert extract_zones_from_status_file('tests/samples/one.ov...
== {'one.vpn.example.org': [IP('198.51.100.8')]} def test_cached_route(): assert extract_zones_from_status_file('tests/samples/cached-route.ovpn-status-v1') \ == {'one.vpn.example.org': [I
P('198.51.100.8')]}
baile/infojoiner
infojoiner/datacenter/functional_test.py
Python
mit
2,451
0.001224
import unittest from selenium import webdriver from selenium.webdriver.common.keys import Keys class NewVisitorTest(unittest.TestCase): def setUp(self): self.browser = webdriver.Firefox() def tearDown(self): self.browser.quit() def test_can_show_main_menu_and_go_to_each_section(self): ...
# Foreach menu item enter in page and check title is # "Menu Title - IJDC" """ # He is invited to enter a to-do item straight away inputbox = self.browser.find_element_by_id('id_new_item') self.assertEqual( inputbox.get_attribute('placeholder'), ...
) # He types "Buy peacock feathers" into a text box (Edith's hobby # is tying fly-fishing lures) inputbox.send_keys('Buy peacock feathers') # When He hits enter, the page updates, and now the page lists # "1: Buy peacock feathers" as an item in a to-do list table inputb...
atelier-cartographique/static-sectioner
sectioner/template.py
Python
agpl-3.0
1,286
0.002333
# Copyright (C) 2016 Pierre Marchand <pierremarc07@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. ...
er = TemplateParser() def load_template (dirpath, name, required=True): home = Path(dirpath) template_path = home.joinpath(name + '.html') try: with template_path.open() as template_file: template = template_file.read() ex
cept Exception as exc: if required: raise exc else: return '' return template def apply_template (template, data): data_local = dict(data) return parser.apply_template(template, data)
aurora-pro/apex-sigma
sigma/plugins/moderation/other/custom_command_detection.py
Python
gpl-3.0
805
0.003727
from config import Prefix from sigma.core.blacklist import check_black async def custom_command_detection(ev, message, args): if message.guild: if message.content.startswith(Prefix): cmd = message.content[len(Prefix):].lower() if cmd not in ev.bot.plugin_manager.commands: ...
if not check_black(ev.db, message): try: custom_commands = ev.db.get_settings(message.guild.id, 'CustomCommands') except:
ev.db.set_settings(message.guild.id, 'CustomCommands', {}) custom_commands = {} if cmd in custom_commands: response = custom_commands[cmd] await message.channel.send(response)
CodeReclaimers/btce-api
btceapi/public.py
Python
mit
6,783
0.001622
# Copyright (c) 2013-2017 CodeReclaimers, LLC # Public API v3 description: https://btc-e.com/api/3/documentation from collections import namedtuple from . import common, scraping PairInfoBase = namedtuple("PairInfoBase", ["decimal_places", "min_price", "max_price", "min_amount", "hidden", "fee"]) class PairIn...
plit(u"_") currencies.add(a) currencies.add(b) self.currencies = list(currencies) self.currencies.sort() self.pair_names = list(self.pairs.keys()) self.pair_names.sort() def validate_pair(self, pair): if pair not in self.pair_names: if "...
ed_pair in self.pair_names: msg = "Unrecognized pair: %r (did you mean %s?)" msg = msg % (pair, swapped_pair) raise common.InvalidTradePairException(msg) raise common.InvalidTradePairException("Unrecognized pair: %r" % pair) def get_pair_info(...
noemis-fr/old-custom
e3z_add_delivery_method/sale_order.py
Python
agpl-3.0
2,622
0.002288
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2012-2013 Elanz (<http://www.openelanz.fr>). # # This program is free software: you can redistribute it and/or modify # it under the terms of th...
received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp.osv import fields, osv from openerp.tools.translate import _ class sale_order(osv.osv): ...
len(ids) == 1 order = self.browse(cr, uid, ids[0], context=context) add_delivery_method = True only_service = True delivery_method = self.pool.get('delivery.carrier').search(cr, uid, [('default_in_sales', '=', True)]) if delivery_method: delivery_method = self.pool.g...
dgaston/ddbio-variantstore
Misc_and_Old/create_sample_coverage_reports.py
Python
mit
3,582
0.005025
#!/usr/bin/env python import argparse import getpass import sys import csv from cassandra.auth import PlainTextAuthProvider from cassandra.cqlengine import connection from ddb import configuration import utils from coveragestore import SampleCoverage from collections import defaultdict def get_target_amplicons(fi...
ore") sys.stdout.write("Processing samples\n") for sample in samples: sys.stdout.write("Processing coverage for sample {}\n".format(sample)) report_panel_path = "/mnt/shared-data/ddb-configs/disease_p
anels/{}/{}".format(samples[sample]['panel'], samples[sample]['report']) target_amplicons = get_target_amplicons(report_panel_path) reportable_amplicons = list() for amplicon in target_amplicons: c...
Alex-Ian-Hamilton/sunpy
sunpy/wcs/__init__.py
Python
bsd-2-clause
2,364
0.000423
""" The WCS package provides functions to parse World Coordinate System (WCS) coordinates for solar images as well as convert between various solar coordinate systems. The solar coordinates supported are * Helioprojective-Cartesian (HPC): The most often used solar coordinate system. Describes positions on the Sun ...
projected) physical distances instead of angles on the celestial sphere. * Heliocentric-Radial (HCR): The same as HPR but with rho expressed in true (deprojected) physical distances instead of angles on the celestial sphere. * Stonyhurst-Heliographic (HG): Expressed posi
tions on the Sun using longitude and latitude on the solar sphere but with the origin which is at the intersection of the solar equator and the central meridian as seen from Earth. This means that the coordinate system remains fixed with respect to Earth while the Sun rotates underneath it. * Carrington...
LTKills/languages
python/17.py
Python
gpl-3.0
66
0.030303
#Conver
t to lower (lol) string = input() print (string.l
ower())
lnmds/jose
ext/nsfw.py
Python
mit
7,881
0
import logging import random import urllib.parse import collections import aiohttp import discord import motor.motor_asyncio from discord.ext import commands from .common import Cog log = logging.getLogger(__name__) class BooruError(Exception): pass class BooruProvider: url = '' @classmethod def...
@commands.is_nsfw() async def gelbooru(self, ctx, *tags): """Randomly searches Gelbooru for posts.""" async with ctx.typing(): await self.booru(ctx, GelBooru, tags) @commands.command() @commands.is_nsfw() async def penis(self, ctx): """get penis from e621 bb""" ...
ype.user) async def whip(self, ctx, *, person: discord.User = None): """Whip someone. If no arguments provided, shows how many whips you received. The command has a 5/1800s cooldown per-user """ if not person: whip = await self.whip_coll.find_one({'user_...
hephaestus9/Radio
radio/logger.py
Python
mit
2,105
0.0019
# -*- coding: utf-8 -*- import logging import logging.handlers import radio import datetime import sys import os class RadioLogger(): """Radio logger""" def __init__(self, LOG_FILE, VERBOSE): """init the logger""" # set up formatting for console and the two log files confor = loggin...
logLevel == 'DEBUG': self.mylogger.debug(toLog) elif logLevel == 'INFO': self.mylogger.info(toLog) elif logLevel == 'WARNING': self.mylogger.warning(toLog) elif logLevel == 'ERROR': self.mylogger.error(toLog) ...
er.critical(toLog) time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') radio.LOG_LIST.append({'level': logLevel, 'message': toLog, 'time': time}) except ValueError: pass
93lorenzo/software-suite-movie-market-analysis
testMovies.py
Python
gpl-3.0
6,486
0.015264
from __future__ import division import numpy as np from Tkinter import * import json import io import unicodecsv as csv #import csv #file = open("moviesTest-1970.txt",'r') act = open("invertedIndexActorsWeightedAll.txt",'r') dir = open("invertedIndexDirectorsWeightedAll.txt", 'r') wri = open("invertedIndexWritersWeig...
riter") input.append([actors,directors,writers]) #imdbRating = float(gson.get(elem).get("imdbRating")) mediaAct, mediaDir, mediaWri = self.calcolaMedie(actors, directors, writers) vect = [1,mediaAct, mediaDir, mediaWri]
vector.append(vect) #labels.append(int(imdbRating)) ## CAST PER CLASSI DISCRETE ## data = np.array(vector) #labels = np.array(labels) #train_data,test_data,train_labels,test_labels = train_test_split(data,labels, train_size= 0.5) #return train_data, train_labels,test_data,...
0--key/lib
portfolio/2009_GoogleAppEngine/apps/0--key/models.py
Python
apache-2.0
651
0.004608
from google.appengine.ext import db
class Stuff (db.Model): owner = db.UserProperty(required=True, auto_current_user=True) pulp = db.BlobProperty() class Greeting(db.Model): author = db.UserProperty() content = db.StringProperty(multiline=True) avatar = db.BlobProperty() date = db.DateTimeProperty(auto_now_add=True) class Placeb...
ty() category = db.StringProperty() taxonomy = db.StringProperty() taxonomy_version = db.StringProperty() code = db.StringProperty() descriptor = db.StringProperty()
jubalh/MAT
libmat/audio.py
Python
gpl-2.0
1,375
0
""" Care about audio fileformat """ try: from mutagen.flac import FLAC from mutagen.oggvorbis import OggVorbis except ImportError: pass import parser import mutagenstripper class MpegAudioStripper(parser.GenericParser): """ Represent mpeg audio file (mp3, ...) """ def _should_remove(self, fi...
f.mfile.pictures def get_meta(self): """ Return the content of the metadata block if present """ metadata = super(FlacStripper, self).get_meta() if self.mfile.pictures: meta
data['picture:'] = 'yes' return metadata
bigdig/vnpy
vnpy/gateway/ctp/__init__.py
Python
mit
35
0.028571
from .ctp_ga
teway import CtpGatew
ay
neuropsychology/Neuropsydia.py
neuropsydia/tests/test_color.py
Python
mpl-2.0
210
0.009524
from unittest import TestCase import neuropsydia as n n.start(open_window=False)
class TestColor(
TestCase): def test_is_string(self): c = n.color("w") self.assertTrue(isinstance(c, tuple))
bowen0701/algorithms_data_structures
alg_tower_of_hanoi.py
Python
bsd-2-clause
1,320
0.001515
"""The tower of Hanoi.""" from __future__ import absolute_import from __future__ import print_function from __future__ import division def tower_of_hanoi(height, from_pole, to_pole, with_pole, counter): """Tower of Hanoi. Time complexity: T(1) = 1, T(n) = 2T(n - 1) + 1 => O(2^n). Space complexity: O(1). ...
height = 5 counter = [0] print('height: {}'.format(height)) tower_of_hanoi(height, from_pole, to_pole, with_pole, counter) print('counter: {}'.format(counter[0])) if __name__
== '__main__': main()
wli/django-allauth
allauth/socialaccount/providers/shopify/provider.py
Python
mit
1,032
0
from allauth.socialaccount import providers from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class ShopifyAccount(ProviderAccount): pass class ShopifyProvider(OAuth2Provider): id = 'shopify' name = 'Shopify' a...
scope(self): return ['read_orders', 'read_products'] def extract_uid(self, data): return str(data['shop']['id']) def extract_common_fields(self, data): # See: https://docs.shopify.com/api/shop # User is only available with Shopify Plus, email is the only # common field ...
yProvider)
ytsapras/robonet_site
scripts/tests/test_survey_data_utilities.py
Python
gpl-2.0
4,078
0.01643
# -*- coding: utf-8 -*- """ Created on Tue Apr 18 12:04:44 2017 @author: rstreet """ from os import getcwd, path, remove, environ from sys import path as systempath cwd = getcwd() systempath.append(path.join(cwd,'..')) import artemis_subscriber import log_utilities import glob from datetime import datetime import pyt...
_file': 'ogle.last.updated', } ogle_data = survey_data_utilities.read_ogle_param_files(config) last_changed = datetime(2016, 11, 2, 1, 4, 39, 360000) last_changed= last_chan
ged.replace(tzinfo=pytz.UTC) assert ogle_data.last_changed == last_changed last_updated = datetime(2017, 1, 23, 22, 30, 16) last_updated= last_updated.replace(tzinfo=pytz.UTC) assert ogle_data.last_updated == last_updated assert len(ogle_data.lenses) == 1927 lens = event_classes.Lens(...
mjames-upc/python-awips
dynamicserialize/dstypes/com/raytheon/uf/common/dataplugin/gfe/request/ExecuteIfpNetCDFGridRequest.py
Python
bsd-3-clause
6,327
0.000632
## ## # File auto-generated against equivalent DynamicSerialize Java class # and then modified post-generation to use AbstractGfeRequest and # implement str(), repr() # # SOFTWARE HISTORY # # Date Ticket# Engineer Description # ------------ ---------- ----------- -------------...
ne, compressFileFactor=0, trim=False, krunch=False, userID=None, logFileName=None, siteIdOverride=None): super(ExecuteIfpNetCDFGridRequest, self).__init__() self.outputFilename = outputFilename self.parmList = parmList
self.databaseID = databaseID self.startTime = startTime self.endTime = endTime self.mask = mask self.geoInfo = geoInfo self.compressFile = compressFile self.configFileName = configFileName self.compressFileFactor = compressFileFactor self.trim = trim ...
terhorst/psmcpp
smcpp/observe.py
Python
gpl-3.0
1,330
0
from __future__ import absolute_import from abc import ABCMeta, abstractmethod import weakref import functools # Decorator to target specific messages. def targets(target_messages, no_first=False): if isinstance(target_messages, str): target_messages = [target_messages] def wrapper(f): @funct...
ractmethod def update(self, *args, **kwargs): pass class Observab
le(object): def __init__(self): self.observers = weakref.WeakSet() def register(self, observer): self.observers.add(observer) def unregister(self, observer): self.observers.discard(observer) def unregister_all(self): self.observers.clear() def update_observers(se...
lthurlow/Network-Grapher
proj/external/numpy-1.7.0/numpy/testing/tests/test_decorators.py
Python
mit
4,070
0.001966
import numpy as np from numpy.testing import * from numpy.testing.noseclasses import KnownFailureTest import nose def test_slow(): @dec.slow def slow_func(x,y,z): pass assert_(slow_func.slow) def test_setastest(): @dec.setastest() def f_default(a): pass @dec.setastest(True) ...
kipException: pass def test_skip_generators_callable(): def skip_tester(): return skip_flag == 'skip me!' @dec.knownfailureif(skip_tester, "This test is known to fail") def g1(x): for i in xrange(x):
yield i try: skip_flag = 'skip me!' for j in g1(10): pass except KnownFailureTest: pass else: raise Exception('Failed to mark as known failure') @dec.knownfailureif(skip_tester, "This test is NOT known to fail") def g2(x): for i in xrange(x): ...
idjung96/mng_files
mng_files/wsgi.py
Python
gpl-3.0
498
0.004016
""" WSGI config for mng_files project. It exposes the WSGI callable as a module-level variable named ``application``. For more i
nformation on this file, see https://docs.djangoproject.com/en/2.0/howto/deployment/wsgi/ """ import os import sys path = os.path.abspath(__file__+'/../..') if path not in sys.path: sys.path.append(path) from django.core.wsgi import get_wsgi_appl
ication os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mng_files.settings") application = get_wsgi_application()
repotvsupertuga/tvsupertuga.repository
plugin.video.youtube/resources/lib/youtube_plugin/kodion/impl/xbmc/xbmc_progress_dialog.py
Python
gpl-2.0
911
0
__author__ = 'bromix' import xbmcgui from ..abstract_progress_dialog import AbstractProgressDialog class XbmcProgressDialog(AbstractProgressDialog): def __init__(self, heading, text): AbstractProgressDialog.__init__(self, 100) self._dialog = xbmcgui.DialogProgress() self._dialog.create(he...
g = None def update(self, steps=1, text=None): self._position += steps position = int(float(100.0 / self._total) * self._position)
if isinstance(text, basestring): self._dialog.update(position, text) else: self._dialog.update(position) def is_aborted(self): return self._dialog.iscanceled()
openlabs/payment-gateway-authorize-net
tests/test_transaction.py
Python
bsd-3-clause
23,226
0.000043
# -*- coding: utf-8 -*- """ test_transaction.py :copyright: (C) 2014-2015 by Openlabs Technologies & Consulting (P) Limited :license: BSD, see LICENSE for more details. """ import unittest import datetime import random import authorize from dateutil.relativedelta import relativedelta from trytond.tests.te...
'327deWY74422', authorize_net_transaction_key='32jF65cTxja88ZA2', test=True ) self.auth_net_gateway.save() # Create parties self.party1, = self.Party.create([{ 'name': 'Test party - 1', 'addresses': [('create', [{ 'name': '...
y': 'Test City %s' % random.randint(1, 999), }])], 'account_receivable': self._get_account_by_kind( 'receivable').id, }]) self.party2, = self.Party.create([{ 'name': 'Test party - 2', 'addresses': [('create', [{ 'name': 'Tes...
django-salesforce/django-salesforce
salesforce/backend/utils.py
Python
mit
17,530
0.003023
""" CursorWrapper (like django.db.backends.utils) """ import decimal import logging import warnings from itertools import islice from typing import Any, Callable, Iterable, Iterator, List, Tuple, TypeVar, Union, overload from django.db import models, NotSupportedError from django.db.models.sql import subqueries, Query...
uery): response = self.execute_update(self.query) elif isinstance(self.query, subqueries.DeleteQuery): response = self.
execute_delete(self.query) elif isinstance(self.query, RawQuery): self.execute_select(soql, args) elif sqltype in ('SAVEPOINT', 'ROLLBACK', 'RELEASE'): log.info("Ignored SQL command '%s'", sqltype) return elif isinstance(self.query, Query): self.ex...
jor-/scipy
scipy/fft/__init__.py
Python
bsd-3-clause
3,965
0.001261
""" ============================================== Discrete Fourier transforms (:mod:`scipy.fft`) =========================
===================== .. currentmodule:: scipy.fft Fast Fourier Transforms (FFTs) ============================== .. autosummary:: :toctree: generated/ fft - Fast (discrete) Fourier Transform (FFT) ifft - Inverse FFT fft2 - Two dimensional FFT ifft2 - Two dimensional inverse FFT fftn - n-dimensiona...
EventBuck/EventBuck
shop/handlers/event/show.py
Python
mit
2,800
0.018571
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Created on 4 juin 2013 @author: Aristote Diasonama ''' from shop.handlers.event.base import BaseHandler from shop.handlers.base_handler import asso_required from shop.models.event import Event from shop.shop_exceptions import EventNotFoundException class ShowEven...
aid_event(self): context = dict() tickets = self.event.get_all_tickets() if tickets is not None: tickets_urls = map(lambda ticket: self.uri_for('editTicket', event_id=self.event_key.id(), ticket_id=ticket.key.id()), ...
elf.event_key.id()) context['url_for_rpc_create_ticket'] = self.uri_for('rpc_createTicket', event_id=self.event_key.id()) def get_template_context_showing_all_events(self): events = self.user.get_all_events() context = dict() context['events'] = ev...
skosukhin/spack
lib/spack/spack/cmd/use.py
Python
lgpl-2.1
1,713
0
############################################################################## # Copyright (c
) 2013-2017, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Labor
atory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-647188 # # For details, see https://github.com/spack/spack # Please also see the NOTICE and LICENSE files for our notice and the LGPL. # # This program is free software; you can redistribute it and/or m...
ngageoint/geoevents
geoevents/operations/migrations/0012_auto__add_settings.py
Python
mit
17,700
0.00791
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Settings' db.create_table('operations_settings', ( ('id', self.gf('django.db.mod...
eleting model 'Settings' db.delete_table('operations_settings') models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'pri
mary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': ...
unicamp-lbic/small_world_ca
analysis.py
Python
gpl-2.0
19,617
0.005251
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys, os my_site = os.path.join(os.environ["HOME"], ".local/lib/python2.7/site-packages") sys.path.insert(0, my_site) import h5py import networkx as nx import numpy as np import pycuda.driver as cuda import scipy.stats as st import sys import aux from consts import...
(self.__majority), cuda.In(self.__executions),
cuda.InOut(sum_diffs), block=(self.__ca_size, 1, 1), grid=(1,)) cuda.Context.synchronize() except cuda.Error as e: sys.exit("CUDA: Execution failed ('%s')!" % e) # For all repetitions, calculate the ratio of total iterati...
amitjamadagni/sympy
sympy/core/expr.py
Python
bsd-3-clause
102,305
0.000655
from core import C from sympify import sympify from basic import Basic, Atom from singleton import S from evalf import EvalfMixin, pure_complex from decorators import _sympifyit, call_highest_priority from cache import cacheit from compatibility import reduce, as_int, default_sort_key from sympy.mpmath.libmp import mpf...
ol, Function and Derivative should return True to enable derivatives wrt them. The implementation in Derivative separates the Symbol and non-Symbol _diff_wrt=True variables and temporarily converts the non-Symbol vars in Symbols when performing the differentiation. Note, see the...
tive for how this should work mathematically. In particular, note that expr.subs(yourclass, Symbol) should be well-defined on a structural level, or this will lead to inconsistent results. Examples ======== >>> from sympy import Expr >>> e = Expr() >>> ...
KirillMysnik/ArcJail
srcds/addons/source-python/plugins/arcjail/modules/lrs/win_reward.py
Python
gpl-3.0
4,013
0
# This file is part of ArcJail. # # ArcJail 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. # # ArcJail is distributed in the hope that...
ld_module_config('lrs/win_reward') config_manager.controlled_cvar( float_handler, "duration", default=10, description="Duration of Win Reward" ) config_manager.controlled_cvar( float_handler, "loser_speed", default=0.5, description="Loser's speed" ) class WinReward(JailGame): capt...
t': [ "equip-damage-hooks", "set-start-status", "winreward-entry", ], 'winreward-timed-out': ["winreward-timed-out", ], } def __init__(self, players, **kwargs): super().__init__(players, **kwargs) self._counters = {} self._results = {...
Goodmind/sunflower-fm
application/widgets/emblems_renderer.py
Python
gpl-3.0
2,375
0.032842
import gtk import cairo import gobject class CellRendererEmblems(gtk.CellRenderer): """Cell renderer that accepts list of icon names.""" __gproperties__ = { 'emblems': ( gobject.TYPE_PYOBJECT, 'Emblem list', 'List of icon names to display', gobject.PARAM_READWRITE ), 'is-link': ...
size taken by emblems.""" count = 5 # optimum size, we can still render more or less emblems width = self.icon_size * count + (self.spacing * (count - 1)) height = self.icon_size result = ( 0, 0, width + 2 * self.padding, height + 2 * self.padding ) return res
ult
cathyyul/sumo-0.18
tools/build/pythonPropsMSVC.py
Python
gpl-3.0
1,517
0.005274
#!/usr/bin/env python """ @file pythonPropsMSVC.py @author Michael Behrisch @author Daniel Krajzewicz @author Jakob Erdmann @date 2011 @version $Id: pythonPropsMSVC.py 14425 2013-08-16 20:11:47Z behrisch $ This script rebuilds "../../build/msvc/python.props", the file which gives information about the python ...
ropsFile, 'w') print >> props, """<?xml version="1.0" encoding="utf-8"?> <Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup Label="UserMacros"> <PYTHON_LIB>%s\libs\python%s%s.lib</PYTHON_LIB> </PropertyGroup> <ItemDefinitionGroup> ...
PreprocessorDefinitions)</PreprocessorDefinitions> </ClCompile> </ItemDefinitionGroup> <ItemGroup> <BuildMacro Include="PYTHON_LIB"> <Value>$(PYTHON_LIB)</Value> </BuildMacro> </ItemGroup> </Project>""" % (sys.prefix, sys.version[0], sys.version[2], distutils.sysconfig.get_config_var('INCLUDE...
a25kk/stv
src/stv.sitecontent/stv/sitecontent/browser/contentpage.py
Python
mit
4,948
0
# -*- coding: utf-8 -*- """Module providing views for the folderish content page type""" from Acquisition import aq_inner from Products.Five.browser import BrowserView from zope.component import getMultiAdapter IMG = 'data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACwAAAAAAQABAAACAkQBADs=' class ContentPageView(Brows...
px' return item def contained_images(self): context = aq_inner(self.context) data = context.restrictedTraverse('@@folderListing')( portal_type='Image', sort_on='getObjPositionInParent') return data def image_tag(self, image): context = image.getO...
= {} if scale is not None: item['url'] = scale.url item['width'] = scale.width item['height'] = scale.height else: item['url'] = IMG item['width'] = '1px' item['height'] = '1px' return item def _get_scaled_img(self, si...
jeffzhengye/pylearn
speed/cython/scipy2013-cython-tutorial-master/exercises/hello-world/setup.py
Python
unlicense
299
0.020067
from distutils.core im
port setup from distutils.extension import Extension from Cython.Distutils import build_ext exts = [Extension("cython_hello_world", ["cython_hello_world.pyx"], )] setup( cmdclass = {'build_ext': build_ext}, ext_mod
ules = exts, )
reeshupatel/demo
keystone/common/serializer.py
Python
apache-2.0
13,041
0.000077
# Copyright 2012 OpenStack Foundation # # 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 # # Unle
ss required by applicable law or agreed to in writin
g, 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. """ Dict <--> XML de/serializer. The identity API prefers at...
ChristopheVuillot/qiskit-sdk-py
qiskit/qasm/_node/_customunitary.py
Python
apache-2.0
1,893
0
# -*- coding: utf-8 -*- # Copyright 2017 IBM RESEARCH. 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 # # U...
.id = id node .name = gate name string .arguments = None or exp_list node .bitlist = primary_list node """ def __init__(self, children): """Create the custom gate node.""" Node.__init__(self, 'custom_unitary', children, None) self.id = children[0] self....
None self.bitlist = children[1] def qasm(self, prec=15): """Return the corresponding OPENQASM string.""" string = self.name if self.arguments is not None: string += "(" + self.arguments.qasm(prec) + ")" string += " " + self.bitlist.qasm(prec) + ";" ...
thomasaarholt/hyperspy
hyperspy/models/eelsmodel.py
Python
gpl-3.0
38,199
0.000052
# -*- coding: utf-8 -*- # Copyright 2007-2021 The HyperSpy developers # # This file is part of HyperSpy. # # HyperSpy 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...
auto
matically setting the fine structure energy regions, # the fine structure of an EELS edge component is automatically # disable if the next ionisation edge onset distance to the # higher energy side of the fine structure region is lower that # the value of this parameter self._min...
IndigoTiger/ezzybot
ezzybot/limit.py
Python
gpl-3.0
1,649
0.004245
from .util import bucket as tokenbucket from . import wrappers class Limit(object): def __init__(self, command_limiting_initial_tokens, command_limiting_message_cost, command_limiting_restore_rate, override, permissions): """limit(20, 4, 0.13, ["admin"], {"admin": "user!*@*"}) Limits the use of c...
command_limiting_message_cost {Integer} -- Message cost for tokenbucket command_limiting_restore_rate {Integer} -- Restore rate for token bucket override {List} -- List of permissions to override the limit permissions {Dict} -- All of the bots permissions. """ self....
mand_limiting_restore_rate self.buckets = {} self.permissions = wrappers.permissions_class(permissions) self.override = override def command_limiter(self, info): #Check if admin/whatever specified if self.permissions.check(self.override, info.mask): return True ...
bgschiller/winnow
winnow/values.py
Python
mit
3,473
0.004319
'''winnow/values.py vi
vify and normalize each of the different field types: - string - collection (values a
re strings, left operand is collection) - numeric - bool - date To vivify is to turn from a string representation into a live object. So for '2014-01-21T16:34:02', we would make a datetime object. Vivify functions should also accept their return type. So vivify_absolute_date(datetime.datetime.now()) sh...
antoinecarme/pyaf
tests/artificial/transf_Quantization/trend_MovingAverage/cycle_0/ar_/test_artificial_1024_Quantization_MovingAverage_0__20.py
Python
bsd-3-clause
272
0.084559
import pyaf.Bench.TS_datasets as tsds import tests.artificial.process_artificial_data
set as art art.process_dataset(N = 1024 , FREQ = 'D', seed = 0, trendtype
= "MovingAverage", cycle_length = 0, transform = "Quantization", sigma = 0.0, exog_count = 20, ar_order = 0);
magellancloud/poncho
poncho/common/utils.py
Python
bsd-3-clause
1,121
0.00446
#!/usr/bin/env python """ poncho.common.utils : Utility Functions """ from datetime import datetime def readable_datetime(dt): """Turn a datetime into something readable, with time since or until.""" if dt is None: return "" dt = dt.replace(microsecond=0) now = datetime.now().replace(microsecon...
r', delta.days // 365), ('month', delta.days // 30), ('week', delta.days // 7), ('day', delta.days), ('hour', delta.seconds // 60 // 60 % 24), ('min'
, delta.seconds // 60 % 60), ('sec', delta.seconds % 60), ] modifier = "from now" if dt < now: modifier = "ago" two_sizes = [] for name,ammount in relative_times: if len(two_sizes) == 2: break if ammount > 0: name += "s" if ammount != 1 else ""...
trafi/djinni
test-suite/generated-src/python/map_record.py
Python
apache-2.0
1,058
0.007561
# AUTOGENERATED FILE - DO NOT MODIF
Y! # This file generated by Djinni from map.djinni from djinni.support import MultiSet # default imported in all files from djinni.exception import CPyException # default imported in all files from djinni.pycffi_marshal import CPyObject, CPyObjectProxy, CPyPrimitive, CPyRecord, CPyString from dh
__map_int32_t_int32_t import MapInt32TInt32THelper from dh__map_int32_t_int32_t import MapInt32TInt32TProxy from dh__map_string_int64_t import MapStringInt64THelper from dh__map_string_int64_t import MapStringInt64TProxy from PyCFFIlib_cffi import ffi, lib from djinni import exception # this forces run of __init__.py ...
jtopjian/st2
st2common/st2common/util/misc.py
Python
apache-2.0
1,245
0
# Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, softw...
he specific language governing permissions and # limitations under the License. import six __all__ = [ 'prefix_dict_keys' ] def prefix_dict_keys(dictionary, prefix='_'): """ Prefix dictionary keys with a provided prefix. :param dictionary: Dictionary whose keys to prefix. :type dictionary: ``di...
elatomczyk/dook
coworkok/bin/pilconvert.py
Python
gpl-3.0
2,354
0.002124
#!/home/ela/Python_Django/coworkok/coworkok/bin/python # # The Python Imaging Library. # $Id$ # # convert image files # # History: # 0.1 96-04-20 fl Created # 0.2 96-10-04 fl Use draft mode when converting images # 0.3 96-12-
30 fl Optimize output (PNG, JPEG) # 0.4 97-01-18 fl Made optimize an option (PNG, JPEG) # 0.5 98-12-30 fl Fixed -f option (from Anthony Baxter) # from __future__ import print_function import getopt, string, sys from PIL import Image def usage(): print("PIL Convert 0.5
/1998-12-30 -- convert image files") print("Usage: pilconvert [option] infile outfile") print() print("Options:") print() print(" -c <format> convert to format (default is given by extension)") print() print(" -g convert to greyscale") print(" -p convert to palett...
ychen820/microblog
y/google-cloud-sdk/platform/google_appengine/lib/grizzled/grizzled/db/base.py
Python
bsd-3-clause
32,027
0.001186
# $Id: 969e4c5fd51bb174563d06c1357489c2742813ec $ """ Base classes for enhanced DB drivers. """ from __future__ import absolute_import __docformat__ = "restructuredtext en" # --------------------------------------------------------------------------- # Imports # ------------------------------------------------------...
elf): """ Close the cursor. :raise Warning: Non-fatal warning :raise Error
: Error; unable to close """ dbi = self.__driver.get_import() try: return self.__cursor.close() except dbi.Warning, val: raise Warning(val) except dbi.Error, val: raise Error(val) def execute(self, statement, parameters=None): ""...
chippey/gaffer
python/GafferTest/UndoTest.py
Python
bsd-3-clause
5,828
0.053706
########################################################################## # # Copyright (c) 2011-2012, John Haddon. All rights reserved. # Copyright (c) 2011-2013, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted prov...
n2["sum"] ) ) with Gaffer.UndoContext( s ) : s.deleteNodes( filter = Gaffer.StandardSet( [ n2 ] ) ) self.assertEqual( n2["op1"].getInput(), None ) self.assertEqual( n2["op2"].getInput(), None ) self.assert_( n3["op1"].getInput().isSame( n1["sum"] ) ) self.assert_( n3["op2"].getInput().isSame( n1["sum"] )...
"] ) ) self.assert_( n3["op1"].getInput().isSame( n2["sum"] ) ) self.assert_( n3["op2"].getInput().isSame( n2["sum"] ) ) with Gaffer.UndoContext( s ) : s.deleteNodes( filter = Gaffer.StandardSet( [ n2 ] ), reconnect = False ) self.assertEqual( n2["op1"].getInput(), None ) self.assertEqual( n2["op2"].getI...
jmichel-otb/s2p
s2plib/sift.py
Python
agpl-3.0
5,706
0.001577
# Copyright (C) 2015, Carlo de Franchis <carlo.de-franchis@cmla.ens-cachan.fr> # Copyright (C) 2015, Gabriele Facciolo <facciolo@cmla.ens-cachan.fr> # Copyright (C) 2015, Enric Meinhardt <enric.meinhardt@cmla.ens-cachan.fr> from __future__ import print_function import os import numpy as np from s2plib import common ...
mfile)) common.run("ransac fmn 1000 .2 7 %s < %s" % (mfile, mfile)) if os.stat(mfile).st_size > 0: # return numpy array of matches return np.loadtxt(mfile) def matches_on_rpc_roi(im1, im2, rpc1, rpc2, x, y, w, h): """ Compute a list of SIFT matches between two...
functions. Args: im1, im2: paths to two large tif images rpc1, rpc2: two instances of the rpc_model.RPCModel class x, y, w, h: four integers defining the rectangular ROI in the first image. (x, y) is the top-left corner, and (w, h) are the dimensions of the rectang...
asnorkin/sentiment_analysis
site/lib/python2.7/site-packages/sklearn/neighbors/regression.py
Python
mit
11,000
0
"""Nearest Neighbor Regression""" # Authors: Jake Vanderplas <vanderplas@astro.washington.edu> # Fabian Pedregosa <fabian.pedregosa@inria.fr> # Alexandre Gramfort <alexandre.gramfort@inria.fr> # Sparseness support by Lars Buitinck # Multi-output support by Arnaud Joly <a.joly@ulg.ac...
and returns an array of the same shape containing the weights. Uniform weights are used by default. algorithm : {'auto', 'ball_tree', 'kd_tree', 'brute'}, op
tional Algorithm used to compute the nearest neighbors: - 'ball_tree' will use :class:`BallTree` - 'kd_tree' will use :class:`KDtree` - 'brute' will use a brute-force search. - 'auto' will attempt to decide the most appropriate algorithm based on the values passed to :...
vlinhart/django-smsbrana
smsbrana/views.py
Python
bsd-3-clause
1,174
0.001704
# -*- coding: utf-8 -*- from datetime import datetime from django.http import HttpResponse from smsbrana import SmsConnect from smsbrana import signals from smsbrana.const import DELIVERY_STATUS_DELIVERED, DATETIME_FORMAT from smsbrana.models import SentSms def smsconnect_notification(request): sc = SmsConnect() ...
ered['status'] != DELIVERY_STATUS_DELIVERED: continue try: sms = SentSms.objects.get(sms_id=sms_id) if sms.delivered: continue sms.delivered = True sms.delivered_date = datetime.strptime(delivered['time'
], DATETIME_FORMAT) sms.save() except SentSms.DoesNotExist: # logger.error('sms delivered which wasn\'t sent' + str(delivered)) pass # delete the inbox if there are 100+ items if len(result['delivery_report']) > 100: sc.inbox(delete=True) signals.smsconn...
nistormihai/superdesk-core
tests/io/feed_parsers/dpa_test.py
Python
agpl-3.0
2,118
0.000472
# -*- coding: utf-8; -*- # # This file is part of Superdesk. # # Copyright 2013, 2014 Sourcefabric z.u. and contributors. # # For the full copyright and license information, please see the # AUTHORS and LICENSE files distributed with this source code, or # at https://www.sourcefabric.org/superdesk/license import os ...
.open('dpa_copyright.txt') self.assertEqual('tex
t', item['type']) self.assertEqual('rs', item['anpa_category'][0]['qcode']) self.assertEqual('(Achtung)', item['headline']) self.assertEqual('Impressum', item['slugline'])
maxalbert/tohu
tohu/v6/custom_generator/utils.py
Python
mit
3,014
0.00365
import attr import pandas as pd import re from ..base impo
rt TohuBaseGenerator from ..logging import logger __all__ = ['get_tohu_
items_name', 'make_tohu_items_class'] def make_tohu_items_class(clsname, attr_names): """ Parameters ---------- clsname: string Name of the class to be created attr_names: list of strings Names of the attributes of the class to be created """ item_cls = attr.make_class(cl...
hujiajie/chromium-crosswalk
third_party/WebKit/Source/devtools/scripts/build_applications.py
Python
bsd-3-clause
1,259
0.003971
#!/usr/bin/env python # # 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. """ Invokes concatenate_application_code for applications specified on the command line. """ from os import path import concatenate_...
t simplejson as json except ImportError: import json def main(argv): try: input_path_flag_index = argv.index('--input_path') input_path = argv[input_path_flag_index + 1] output_path_flag_index = argv.index('--output_path') output_path = argv[output_path
_flag_index + 1] application_names = argv[1:input_path_flag_index] debug_flag_index = argv.index('--debug') minify = argv[debug_flag_index + 1] == '0' except: print('Usage: %s app_1 app_2 ... app_N --input_path <input_path> --output_path <output_path> --debug <0_or_1>' % argv[0]) ...
uwoseis/anemoi
anemoi/source.py
Python
mit
8,029
0.011085
from .meta import BaseModelDependent import warnings import numpy as np import scipy.sparse as sp from scipy.special import i0 as bessi0 class BaseSource(BaseModelDependent): pass class FakeSource(BaseSource): def __call__(self, loc): return loc class SimpleSource(BaseSourc...
sourceRegion = sourceRegion[index:,:] qshift = qshift[index:,:] if freeSurf[2]: sourceRegion[:index,:] -= lift if Zi > self.nz-ireg-1: index = self.nz-ireg-1 - Zi if freeSurf[0]:...
egion[index:,:]) sourceRegion = sourceRegion[:index,:] qshift = qshift[:index,:] if freeSurf[0]: sourceRegion[index:,:] -= lift if Xi < ireg: index = ireg-Xi if freeSurf[3]: ...
jhpyle/docassemble
docassemble_base/docassemble/base/core.py
Python
mit
790
0.002532
# This module imports names for backwards compatibility and to ensure # that pickled objects in existing sessions can be unpickled. __all__ = ['DAObject', 'DAList', 'DADict', 'DAOrderedDict', 'DASet', 'DAFile', 'DAFileCollection', 'DAFileList', 'DAStaticFile', 'DAEmail', 'DAEmailRecipient', 'DAEmailRecipientList', 'DA...
assemble.base.util import DAObject, DAList, DADict, DAOrderedDict,
DASet, DAFile, DAFileCollection, DAFileList, DAStaticFile, DAEmail, DAEmailRecipient, DAEmailRecipientList, DATemplate, DAEmpty, DALink, RelationshipTree, DAContext, DAObjectPlusParameters, DACatchAll, RelationshipDir, RelationshipPeer, DALazyTemplate, DALazyTableTemplate, selections, DASessionLocal, DADeviceLocal, DAU...
Catherine-Chu/DeepQA
chatbot_website/chatbot_website/settings.py
Python
apache-2.0
4,300
0.00093
""" Django settings for chatbot_website project. Generated by 'django-admin startproject' using Django 1.10. For more information on this file, see https://docs.djangoproject.com/en/1.10/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.10/ref/settings/ """ imp...
ings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'djang...
.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] CHANNEL_LAYERS = { "default": { "BACKEND": "asgi_redis.RedisChannelLayer", ...
IBM/differential-privacy-library
diffprivlib/models/__init__.py
Python
mit
1,558
0.005777
# MIT License # # Copyright (C) IBM Corporation 2019 # # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
# doc
umentation 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 conditi...
wcainboundary/boundary-api-cli
boundary/source_list.py
Python
apache-2.0
856
0
# # Copyright 2014-2015 Boundary, 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...
= "v1/account/sources/" self.method = "GET" def getDescription(self): return "Lists the sources in
a Boundary account"
mlperf/training_results_v0.7
NVIDIA/benchmarks/ssd/implementations/pytorch/test/opt_loss_test.py
Python
apache-2.0
1,453
0.003441
import torch from base_model import Loss from train import dboxes300_coco from opt_loss import OptLoss # In: # ploc : N x 8732 x 4 # plabel : N x 8732 # gloc : N x 8732 x 4 # glabel : N x 8732 data = torch.load('loss.pth') ploc = data['ploc'].cuda() plabel = data['plabel'].cuda() gloc = data['gloc'].cuda() glabe...
teration (fprop)'.format(time_per_fprop)) # fprop + bprop torch.cuda.synchronize() start = time.time() for _ in range(timing_iterations): l = loss(ploc, plabel, gloc, glabel) l.backward(dl) torch.cuda.synchronize() end = time.time() time_per_fprop_bprop = (end - start) / timing_iterations print('too
k {} seconds per iteration (fprop + bprop)'.format(time_per_fprop_bprop)) print(loss.graph_for(ploc, plabel, gloc, glabel))
hydroshare/hydroshare
hs_tracking/migrations/0001_initial.py
Python
bsd-3-clause
1,731
0.002889
# -*- coding: utf-8 -*- from django.db import migrations, models from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
] operations = [ migrations.CreateModel( name='Session', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False
, auto_created=True, primary_key=True)), ('begin', models.DateTimeField(auto_now_add=True)), ], ), migrations.CreateModel( name='Variable', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_...
dev-coop/plithos
src/plithos/simulations/random_mover.py
Python
mit
388
0
import random from ..simulator import Simulator
class RandomMover(Simulator): ACTIONS = ('up', 'down', 'left', 'right') def start(self): self.init_game() while True: self._check_pyg
ame_events() for drone in self.drones: drone.do_move(random.choice(self.ACTIONS)) self.print_map() self._draw()
animekita/selvbetjening
selvbetjening/core/mailcenter/models.py
Python
mit
6,200
0.001774
import logging import re import markdown from django.conf import settings from django.db import models from django.template import Template, Context, loader import sys from selvbetjening.core.mail import send_mail logger = logging.getLogger('selvbetjening.email') class EmailSpecification(models.Model): BODY_FO...
ce'] = context.get('invoi
ce_plain', None) return Template(body).render(context) def _get_rendered_body_html(self, context): if self.body_format == 'markdown': body = markdown.markdown(self.body) else: body = self.body context['invoice'] = context.get('invoice_html', None) ...
google/graphicsfuzz
python/src/main/python/test_scripts/inspect_compute_results_test.py
Python
apache-2.0
15,285
0.004122
#!/usr/bin/env python3 # Copyright 2019 The GraphicsFuzz Project 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless requir...
eNotFoundError: Input file "nofile.json" not found' in str(file_not_found_error) def test_exactdiff_handles_first_file_not_found(tmp_path: pathlib2.Path): onefile = tmp_path / 'something.json' onefile.touch(exist_ok=False) with pytest.raises(FileNotFoundError) as file_not_found_error: inspect_comp...
def test_exactdiff_handles_second_file_not_found(tmp_path: pathlib2.Path): onefile = tmp_path / 'something.json' onefile.touch(exist_ok=False) with pytest.raises(FileNotFoundError) as file_not_found_error: inspect_compute_results.main_helper(['exactdiff', str(onefile), 'nofile.json']) assert 'F...
DiCarloLab-Delft/PycQED_py3
pycqed/instrument_drivers/virtual_instruments/sim_control_CZ.py
Python
mit
11,275
0.001508
from qcodes.instrument.base import Instrument from qcodes.utils import validators as vals from qcodes.instrument.parameter import ManualParameter import numpy as np class SimControlCZ(Instrument): """ Noise and other parameters for cz_superoperator_simulation_new """ def __init__(self, name, **kw): ...
value=0, ) self.add_parameter( "which_gate", docstring="Direction of the CZ gate. E.g. 'NE'. Used to extract parameters from the fluxlutman ", parameter_class=ManualParameter, vals=vals.Strings(), initial_value="NE", ) self.ad...
capes can deviate significantly from experiment.", parameter_class=ManualParameter, vals=vals.Numbers(min_value=1), initial_value=4, ) self.add_parameter( "gates_num", docstring="Chain the same gate gates_num times.", parameter_cla...
okuta/chainer
chainer/functions/connection/bilinear.py
Python
mit
9,015
0
import numpy import chainer from chainer import backend from chainer import function_node from chainer.utils import type_check def _as_mat(x): if x.ndim == 2: return x return x.reshape(len(x), -1) def _ij_ik_il_to_jkl(a, b, c): ab = chainer.functions.matmul(a[:, :, None], b[:, None, :]) # ijk ...
:math:`e^2\\in \\mathbb{R}^{I\\cdot K}`, :math:`W\\in \\mathb
b{R}^{J \\cdot K \\cdot L}`, :math:`V^1\\in \\mathbb{R}^{J \\cdot L}`, :math:`V^2\\in \\mathbb{R}^{K \\cdot L}`, and :math:`b\\in \\mathbb{R}^{L}`, where :math:`I` is mini-batch size. In this document, we call :math:`V^1`, :math:`V^2`, and :math:`b` linear parameters. The output of forward ...
janeczku/calibre-web
cps/services/Metadata.py
Python
gpl-3.0
3,837
0.000784
# -*- coding: utf-8 -*- # This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web) # Copyright (C) 2021 OzzieIsaacs # # 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...
method def get_title_tokens( title: str, strip_joiners: bool = True ) -> Generator[str, None, None]: """ Taken from calibre source code It's a simplified (cut out what is unnecess
ary) version of https://github.com/kovidgoyal/calibre/blob/99d85b97918625d172227c8ffb7e0c71794966c0/ src/calibre/ebooks/metadata/sources/base.py#L363-L367 (src/calibre/ebooks/metadata/sources/base.py - lines 363-398) """ title_patterns = [ (re.compile(pat, re.IGNORECA...
jogral/tigris-python-sdk
tigrissdk/session/tigris_session.py
Python
apache-2.0
5,263
0.00019
# coding: utf-8 from __future__ import unicode_literals, absolute_import try: import requests as r except: r = None class TigrisSession(object): """ Base session layer for Tigris. """ def __init__(self, base_url, default_headers={}): """ :pa...
The name of the method :type method: `str` :param endpoint: The name of the endpoint :type endpoint: `str` :param headers: The name of the endpoint :type headers: `dict` :param post_data: PATCH/...
le` of `str`, `int`, `dict` """ url = '{0}/{1}'.format(self._base_url, endpoint) try: try: result = self._session.request(method, url, headers=headers, ...
irmen/Pyro4
examples/messagebus/subscriber_manual_consume.py
Python
mit
2,432
0.002467
""" This
is a subscriber meant for the 'weather' messages example. It uses a custom code loop to get and process messages. """ from __future__ import print_function import sys import threading import tim
e import Pyro4 from messagebus.messagebus import Subscriber from Pyro4.util import excepthook sys.excepthook = excepthook if sys.version_info < (3, 0): input = raw_input Pyro4.config.AUTOPROXY = True @Pyro4.expose class Subber(Subscriber): def consume_message(self, topic, message): # In this case, t...
Lekensteyn/buildbot
master/buildbot/steps/mtrlogobserver.py
Python
gpl-2.0
18,336
0.000545
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without eve...
self.variant = variant self.result = result self.info = info self.text = text self.callback = callback def add(self, line): self.text += line def fireCallback(self): return self.callback(self.testname, self.variant, self.result, self.info, self.text) class ...
neObserver): """ Class implementing a log observer (can be passed to BuildStep.addLogObserver(). It parses the output of mysql-test-run.pl as used in MySQL, MariaDB, Drizzle, etc. It counts number of tests run and uses it to provide more accurate completion estimates. It parses out t...
Azure/azure-sdk-for-python
sdk/resources/azure-mgmt-resource/azure/mgmt/resource/locks/models.py
Python
mit
360
0
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rig
hts reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # ----------------------------------------------------------------
---------- from .v2016_09_01.models import *
SUSE-Cloud/glance
glance/tests/integration/legacy_functional/base.py
Python
apache-2.0
7,145
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 # d...
app_factory /:
apiversions /v1: apiv1app /v2: apiv2app [app:apiversions] paste.app_factory = glance.api.versions:create_resource [app:apiv1app] paste.app_factory = glance.api.v1.router:API.factory [app:apiv2app] paste.app_factory = glance.api.v2.router:API.factory [filter:versionnegotiation] paste.filter_factory = glance.api.mid...
sdurrheimer/compose
tests/helpers.py
Python
apache-2.0
1,309
0.000764
from __future__ import absolute_import from __future__ import unicode_literals import os from compose.config.config import ConfigDetails from compose.config.config import ConfigFile from compose.config.config import load def build_config(contents, **kwargs): return load(build_config_details(contents, **kwargs))...
logs(container) raise Exception( "Container exited with code {}:\n{}".format(exitcode, output)) finally: client.remove_container(co
ntainer, force=True)
williamHuang5468/QuicklyLearnDjango
mysite/mysite/settings.py
Python
mit
2,686
0
""" Django settings for mysite project. Generated by 'django-admin startproject' using Django 1.8.3. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ # Build paths...
ngo.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Internationalization # https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.dja...
ic-files/ STATIC_URL = '/static/'
htzy/bigfour
cms/djangoapps/contentstore/management/commands/restore_asset_from_trashcan.py
Python
agpl-3.0
480
0.004167
from django.core.management.base import BaseCommand, CommandError from xmodule.contentstore.utils imp
ort restore_asset_from_trashcan class Command(BaseCommand): help = '''Restore a deleted asset from the trashcan back to it's original course''' def handle(self, *args, **options): if len(args) != 1 and len(args) != 0: raise CommandError("restore_asset_from_trashcan requires one argument: ...
sset_from_trashcan(args[0])
mvaled/sentry
tests/sentry/api/endpoints/test_project_rules.py
Python
bsd-3-clause
5,710
0.002627
from __future__ import absolute_import from django.core.urlresolvers import reverse from sentry.models import Environment, Rule from sentry.testutils import APITestCase class ProjectRuleListTest(APITestCase): def test_simple(self): self.login_as(user=self.user) team = self.create_team() ...
{ "id": "sentry.rules.conditions.first_seen_event.FirstSeenEventCondition", "key": "foo", "match": "eq", "value": "bar", } ] actions = [{"id": "sentry.rules.actions.notify_event.NotifyEventAction"}] url = reve...
-0-project-rules", kwargs={"organization_slug": project.organization.slug, "project_slug": project.slug}, ) response = self.client.post( url, data={ "name": "hello world", "actionMatch": "any", "actions": actions, ...
jasonzzz/ansible
lib/ansible/module_utils/junos.py
Python
gpl-3.0
9,209
0.000869
# # (c) 2015 Peter Sprygada, <psprygada@ansible.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 option) any late...
mport Device from jnpr.junos.utils.config import Config from jnpr.junos.version import VERSION from jnpr.junos.exception import RpcError, ConnectError, ConfigLoadError, CommitError
from jnpr.junos.exception import LockError, UnlockError if LooseVersion(VERSION) < LooseVersion('1.2.2'): HAS_PYEZ = False else: HAS_PYEZ = True except ImportError: HAS_PYEZ = False try: import jxmlease HAS_JXMLEASE = True except ImportError: HAS_JXMLEASE = False try: from ...
RocketRedNeck/PythonPlayground
pid_dot.py
Python
mit
2,665
0.01651
# -*- coding: utf-8 -*- """ pid - example of PID control of a simple process with a time constant Copyright (c) 2016 - RocketRedNeck.com RocketRedNeck.net RocketRedNeck and MIT Licenses RocketRedNeck hereby grants license for others to copy and modify this source code for whatever purpose other's deem worthy as l...
R IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import m
atplotlib.pyplot as plot import numpy as np import math tmax = 3.0 dt = 0.01 ts = np.arange(0.0, tmax, dt) pvs = np.zeros(len(ts)) sps = np.zeros(len(ts)) mvs = np.zeros(len(ts)) mps = np.zeros(len(ts)) kf = 0.0 kp = 20.0 #10.0 ki = 0.0 kd = 2.0 #1.0 dt = ts[1] - ts[0] Gp = 1.0 delay = 1 * dt tau = 1000 * dt ...
smn/garelay
manage.py
Python
bsd-2-clause
259
0
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault( "DJANGO_SETTINGS_MODULE"
, "garelay.settings") from django.core.management i
mport execute_from_command_line execute_from_command_line(sys.argv)
Akuli/porcupine
porcupine/plugins/python_tools.py
Python
mit
2,238
0.002234
""" Format the current file with black or isort. Available in Tools/Python/Black and Tools/Python/Isort. """ from __future__ import annotations import logging import subprocess import traceback from functools import partial from pathlib import Path from tkinter import messagebox from porcupine import menubar, tabs,...
exception(f"running {tool} failed") messagebox.showerror(fail_str, traceback.format_exc()) return code def format_code_in_textwid
get(tool: str, tab: tabs.FileTab) -> None: before = tab.textwidget.get("1.0", "end - 1 char") after = run_tool(tool, before, tab.path) if before != after: with textutils.change_batch(tab.textwidget): tab.textwidget.replace("1.0", "end - 1 char", after) def setup() -> None: menubar....