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
petervdb/eLearning
mongodb/dev_course/analyse_grades.py
Python
apache-2.0
1,351
0.014804
import pymongo con = pymongo.Connection() db = con.students grades = db.grades amount = grades.count() print "Amount of elements in grades: %s " % amount exam_el = grades.find({ "type" : "exam" }).count() print "Amount of exam types in grades: %s " % exam_el quiz_el = grades.find({ "type" : "quiz" }).coun...
cur_student = homework['student_id'] cur_score = homework['score'] # print "Student: %s Score: %s" % (cur_student, cur_score) if old_st
udent != cur_student: student_obj_id = homework['_id'] print "Students %s Homework with grade %s needs to be removed ( %s )" % (cur_student, cur_score, student_obj_id) grades.remove({"_id": student_obj_id}) else: print "Students %s best score is %s...
hbkfabio/horario
asignacion_horario/wsgi.py
Python
gpl-3.0
403
0
""" WSGI config for h
orario project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJ
ANGO_SETTINGS_MODULE", "asignacion_horario.settings") application = get_wsgi_application()
foxsi/foxsi-smex
pyfoxsi/src/pyfoxsi/__init__.py
Python
mit
674
0
from __future__ im
port absolute_import import astropy.units as u from datetime import datetime mission_title = 'FOXSI-SMEX' launch_date = datetime(2022, 7, 1) # DSI Parameters number_of_dsi_telescopes = 2 shutter_material = 'Al' shutter_thickness = [0, 0.02, 0.08, 0.3, 1.3, 6] * u.mm detector_material = 'cdte' detector_thickness = 1....
nket_thickness = 0.5 * u.mm dsi_focal_length = 14 * u.m # STC Parameters stc_aperture_area = {'Q': 1.0 * u.mm ** 2, 'F': 0.02 * u.mm ** 2} stc_detector_material = 'Si' stc_detector_thickness = 0.5 * u.mm stc_filter_material = 'Be' stc_filter_thickness = {'Q': 15 * u.micron, 'F': 50 * u.micron}
openUniverse/singularity
BensPractice/Practise.py
Python
mit
2,283
0.008322
# def p(a, b): # if b is 0: # return a # else: # return a * p(a, b -1) # # w = 5 # print(p(w, 8)) # # 5*(2 - 1) # # def universe(input, apples, bread): # if input == "hello": #
print("hi") # else: #
print("f u") # if apples == "red": # print("yum") # else: # print("boo") # if bread == "old": # print("throw it away") # # # # # universe("hello", "bread", "old") # # synonymsForHello = ['hey', 'hi'] # sforgood = ['great', 'good'] # anylist = [synonymsForHello, sforgood] # #...
hebronlin/churchlife
authentication/urls.py
Python
gpl-3.0
993
0.006042
from django.conf.urls import patterns, url from . import views urlpatterns = patterns('', # The password reset form view: url(r'^password_reset/$', views.PasswordResetView.as_view(), name='password_reset' ), # The password reset confirmation view: url(r'^reset/(?P<uidb64>[0-9A-
Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', 'django.contrib.auth.views.password_reset_confirm', name='password_reset_confirm' ), url(r'^login/$', 'django.contrib.auth.views.login', kwargs={'template_name': 'authentication/login.html'}, name='login' ...
set/done/$', 'django.contrib.auth.views.password_reset_done', kwargs={'template_name': 'authentication/password_reset_done.html'}, name='password_reset_done' ), )
josedolz/SemiDenseNet
src/LiviaNet/generateNetwork.py
Python
mit
8,290
0.01351
""" Copyright (c) 2016, Jose Dolz .All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the f...
ReLU} printActivationFunction[myParserConfigIni.activationType]() def Random(layerType): print " --- Weights initialization (" +layerType+ " Layers): Random" def Delving(layerType): print " --- Weights initialization (" +layerType+ " Layers): Delving" def PreTrained(layerTy...
alization_CNN = {0 : Random, 1 : Delving, 2 : PreTrained} printweight_Initialization_CNN[myParserConfigIni.weight_Initialization_CNN]('CNN') printweight_Initialization_CNN[myParserConfigIni.weight_Initial...
kastnerkyle/pylearn2
pylearn2/utils/exc.py
Python
bsd-3-clause
2,941
0.00034
"""Exceptions used by basic support utilities.""" __author__ = "Ian Goodfellow" import inspect import sys import textwrap from pylearn2.utils.common_strings import environment_variable_essay class EnvironmentVariableError(Exception): """ An exception raised when a required environment variable is not defined...
arg in new_exc.args) else: new_message = "" new_message
+= '\n\nOriginal exception:\n\t' + orig_exc_type.__name__ if hasattr(orig_exc_value, 'args') and len(orig_exc_value.args) > 0: if getattr(orig_exc_value, 'reraised', False): new_message += ': ' + str(orig_exc_value.args[0]) else: new_message += ': ' + ', ...
daterrell2/pint_journal_project
pint_journal_project/urls.py
Python
mit
863
0
"""pint_journal_project URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a
URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Add an import: from blog import urls as blog_ur
ls 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls)) """ from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^user/', include('pints_user.urls')), url(r'^/?', include('pints_main.urls')), ]
satra/NiPypeold
nipype/externals/pynifti/loadsave.py
Python
bsd-3-clause
1,766
0
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: # module imports from nipype.externals.pynifti import volumeutils as vu from nipype.externals.pynifti import spm2analyze as spm2 from nipype.externals.pynifti import nifti1 from nipype.externals.pynifti imp...
file to load *args **kwargs arguments to pass to image load function Returns ------- img : ``SpatialImage`` Image of guessed type ''' # Try and guess file type from filename if isinstance(filespec, basestring): fname = filespec for ending in ('.gz', '.bz2...
break if fname.endswith('.nii'): return nifti1.load(filespec, *args, **kwargs) if fname.endswith('.mnc'): return minc.load(filespec, *args, **kwargs) # Not a string, or not recognized as nii or mnc try: files = nifti1.Nifti1Image.filespec_to_files(filespec) ...
wolfsonliu/crispr
pycas/design/offtarget.py
Python
gpl-3.0
20,315
0.000443
# -*-coding:utf-8-*- # !!!!!!!!!!!!!!!!!! # need /tmp dir access # !!!!!!!!!!!!!!!!!! # ------------------ # Librarys # ------------------ import io import os import re import subprocess as sp import pandas as pd import numpy as np from Bio.Seq import reverse_complement # ------------------ from pycas.utils.decorator...
'"chr", name of reference sequence where alignment occurs;', '"site", 1-based offset into the forward reference strand', ' where leftmost character of the alignment occurs;', '"sequence", mapped sequence;', '"quality", mapping q
uality;', '"cigar", CIGAR string representation of alignment;', '"mismatch", mismatch site.' ] ), indents=1 ), examplecodelists=[ 'bowtie_offinder(', '... bowtie_path,', '... indexprefix,', '... sequence=[', '......
TimothyHelton/k2datascience
k2datascience/plotting.py
Python
bsd-3-clause
9,485
0.000633
#! /usr/bin/env python # -*- coding: utf-8 -*- """ Plotting Module .. moduleauthor:: Timothy Helton <timothy.j.helton@gmail.com> """ import matplotlib.pyplot as plt import numpy as np import pandas as pd import scipy.cluster.hierarchy as spch import seaborn as sns from k2datascience.utils import ax_formatter, size,...
t_title(title, fontsize=size['title']) ax0.set_xticklabels(ax0.xaxis.get_majorticklabels(), fontsize=size['label
']) save_fig(title, save) def distribution_plot(data, title, x_label, n_bins=50, title_size=24, label_size=14, save=False): """Create subplot of data with histogram and kernel density plot. :param data: data to be plotted :type: pd.DataFrame, pd.Series :param str title:...
cleberjsantos/ngxtop
ngxtop/ngxtop.py
Python
mit
13,509
0.001925
"""ngxtop - ad-hoc query for nginx access log. Usage: ngxtop [options] ngxtop [options] (print|top|avg|sum) <var> ... ngxtop info ngxtop [options] query <query> ... Options: -l <file>, --access-log <file> access log file to parse. -f <format>, --log-format <format> log format as specify in l...
h("foo")' Analyze apache access log from remote machine using 'common' log format $ ssh remote tail -f /var/log/apache2/access.log | ngxtop -f common """ from __future__ import print_function import atexit from contextlib import closing import curses import logging import os import sqlite3 import time import s...
rt urlparse except ImportError: import urllib.parse as urlparse from docopt import docopt import tabulate from .config_parser import detect_log_config, detect_config_path, extract_variables, build_pattern from .utils import error_exit DEFAULT_QUERIES = [ ('Summary:', '''SELECT count(1) ...
johnbywater/eventsourcing
eventsourcing/domain.py
Python
bsd-3-clause
37,825
0.000872
import inspect import os from abc import ABC, ABCMeta from dataclasses import dataclass from datetime import datetime, tzinfo from types import FunctionType, WrapperDescriptorType from typing import ( Any, Callable, Dict, Generic, Iterable, List, Optional, Type, TypeVar, Union, ...
. Const
ructor arguments: :param UUID originator_id: ID of originating aggregate. :param int originator_version: version of originating aggregate. :param datetime timestamp: date-time of the event :param str originator_topic: topic for the aggregate class """ originator_topic: str def mutate(self...
deeso/python_scrirpts
ida/ida_pro_print_xref_to_addresses_to_vtrace_bp.py
Python
apache-2.0
2,219
0.024786
# (c) 2010 Adam Pridgen # ida_pro_make_data_ref_name_cmd.py: # # GPLv3 License # 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 # any later version....
file = open(outfilename, 'a') bp_addr = idaapi.get_first_cref_to(addr) bp_lines = [] while (bp_addr != idc.BADADDR): bp_cmt = bp_str_cmt_fmt%(name, GetFuncOffset(bp_addr), bp_addr, GetDiasm(bp_addr)) bp_str = bp_str_fmt%(bp_addr, bp_cmt) bp_lines.append(bp_str+"\n") outfile.write(bp_str+"\n") bp_ad...
fmt%(name, GetFuncOffset(bp_addr), bp_addr) bp_str = bp_str_fmt%(bp_addr, bp_cmt) bp_lines.append(bp_str+"\n") outfile.write(bp_str+"\n") bp_addr = idaapi.get_next_cref_to(addr, bp_addr) return bp_lines if __name__ == "__main__": addr,comment,command,outfilename = get_info() get_write_bps_to_file...
jvrsantacruz/XlsxWriter
xlsxwriter/test/styles/test_write_xf.py
Python
bsd-2-clause
16,206
0.002592
############################################################################### # # Tests for XlsxWriter. # # Copyright (c), 2013-2015, John McNamara, jmcnamara@cpan.org # import unittest from ...compatibility import StringIO from ...styles import Styles from ...format import Format class TestWriteXf(unittest.TestCa...
xf_format = Format(properties) self.styles._write_xf(xf_format) exp = """<xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/>"""
got = self.fh.getvalue() self.assertEqual(got, exp) def test_write_xf_2(self): """Test the _write_xf() method. Has font but is first XF.""" properties = {'has_font': 1} xf_format = Format(properties) self.styles._write_xf(xf_format) exp = """<xf numFmtId="0"...
psachin/swift
swift/common/ring/builder.py
Python
apache-2.0
79,375
0
# Copyright (c) 2010-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 # # Unless required by applicable law or agree...
ger.addHandler(NullHandler()) @property def id(self): if self._id is None: # We don't automatically assign an id here because we want a caller # to explicitly know when a builder needs an id to be assigned. In # that case the caller must save the builder in order tha...
ave()') return self._id @property def part_shift(self): return 32 - self.part_power @property def ever_rebalanced(self): return self._last_part_moves is not None def _set_part_moved(self, part): self._last_part_moves[part] = 0 byte, bit = divmod(part, 8) ...
johnzimm/puppetboard
test/test_utils.py
Python
apache-2.0
5,776
0
import json import logging from types import GeneratorType import pytest from bs4 import BeautifulSoup from pypuppetdb.errors import EmptyResponseError from requests import Response from requests.exceptions import ConnectionError, HTTPError from werkzeug.exceptions import InternalServerError, NotFound from puppetboar...
assert i == val i = i + 1 def test_stop_empty(): def my_generator(): yield 1 raise EmptyResponseError yield 2 gen = utils.yield_or_stop(my_generator()) for val in gen: assert 1 == val def test_stop_conn_error(): def my_generator(): yield 1 ...
ectionError yield 2 gen = utils.yield_or_stop(my_generator()) for val in gen: assert 1 == val def test_stop_http_error(): def my_generator(): yield 1 raise HTTPError yield 2 gen = utils.yield_or_stop(my_generator()) for val in gen: assert 1 == val ...
111pontes/ydk-py
ietf/ydk/models/ietf/ietf_ipv6_unicast_routing.py
Python
apache-2.0
1,614
0.005576
""" ietf_ipv6_unicast_routing This YANG module augments the 'ietf\-routing' module with basic configuration and state data for IPv6 unicast routing. Copyright (c) 2014 IETF Trust and the persons identified as authors of the code. All rights reserved. Redistribution and use in source and binary forms, with or withou...
rt of RFC XXXX (http\://tools.ietf.org/html/rfcXXXX); see the RFC itself for full legal notices. """ import re import collections from enum import Enum from ydk.types import Empty, YList, YLeafList, DELETE, Decimal64, FixedBits
Dict from ydk.errors import YPYError, YPYModelError from ydk.models.ietf.ietf_routing import Ipv6Identity class Ipv6UnicastIdentity(Ipv6Identity): """ This identity represents the IPv6 unicast address family. """ _prefix = 'v6ur' _revision = '2015-05-25' def __init__(self): ...
gdkar/pyglet
tests/image/DEPTH_SAVE.py
Python
bsd-3-clause
1,686
0.001779
#!/usr/bin/env python '''Test depth buffer save. A scene consisting of a single coloured triangle will be rendered. The depth buffer will then be saved to a stream and loaded as a texture. You will see the original scene first for up to several seconds before the depth buffer image appears (because retrie...
redtext' __version__ = '$Id: $' import unittest import base_save from pyglet.gl import * from pyglet import image from pyglet.compat
import BytesIO class TEST_DEPTH_SAVE(base_save.TestSave): alpha = False def draw_original(self): glClear(GL_DEPTH_BUFFER_BIT) glEnable(GL_DEPTH_TEST) glBegin(GL_TRIANGLES) glColor4f(1, 0, 0, 1) glVertex3f(0, 0, -1) glColor4f(0, 1, 0, 1) glV...
hurlebouc/GDuplicity
Duplicity/duplicity-0.6.22/duplicity/backends/_ssh_pexpect.py
Python
gpl-3.0
14,459
0.003666
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*- # # Copyright 2002 Ben Escoto <ben@emerose.org> # Copyright 2007 Kenneth Loafman <kenneth@loafman.com> # # This file is part of duplicity. # # Duplicity is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License...
elif state == "copying": match = child.expect([pexpect.EOF, "(?i)timeout, server not responding", "stalled", "authenticity", ...
elif match == 1: log.Warn("Timeout waiting for response") break elif match == 2: state = "stalled" elif match == 3: log.Warn("Remote host authentication failed (missing know...
williamyangcn/iBlah_py
ui/ui_profile_dialog.py
Python
bsd-3-clause
4,945
0.003254
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file '/Users/lee/backups/code/iblah_py/ui/ui_profile_dialog.ui' # # Created: Fri May 6 21:47:58 2011 # by: PyQt4 UI code generator 4.8.3 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fro...
self.label_6 = QtGui.QLabel(ProfileDialog) self.label
_6.setGeometry(QtCore.QRect(21, 170, 52, 16)) self.label_6.setObjectName(_fromUtf8("label_6")) self.retranslateUi(ProfileDialog) QtCore.QObject.connect(self.save_btn, QtCore.SIGNAL(_fromUtf8("clicked()")), ProfileDialog.accept) QtCore.QMetaObject.connectSlotsByName(ProfileDialog) d...
gotropo/gotropo
create/prerun.py
Python
gpl-3.0
1,047
0.017192
from troposphere import Export import importlib supported_keys = dict( var_export = "Name of exported value that will hold return string from given function", function = "Function to call, expects string return value", function_args = "Arguments as key=valu
e pairs for function call" ) def call(template, prerun_items, dry_run): prerun_values = dict() for k,v in prerun_items.items(): item_value = run_item(v, dry_run) prerun_values[k.replace("_","-")] = dict(ReturnString = item
_value) template.add_mapping("PrerunValues", prerun_values) def check_keys(item_setup): for k in item_setup.keys(): if not supported_keys.get(k): raise(ValueError("Config key '{}' not supported for prerun setup".format(k))) def run_item(item_setup, dry_run): check_keys(item_setup) ...
asterix135/infonex_crm
registration/migrations/0018_invoice_revised_flag.py
Python
mit
464
0
# -*- coding
: utf-8 -*- # Generated by Django 1.10.5 on 2017-02-15 15:27 from __future__ import unicode_literals
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('registration', '0017_auto_20170214_1532'), ] operations = [ migrations.AddField( model_name='invoice', name='revised_flag', field=models.BooleanField(def...
Polytechnique-org/xorgauth
xorgauth/accounts/migrations/0013_make_UnboundedCharField_non_unique.py
Python
agpl-3.0
1,107
0.003613
# -
*- coding: utf-8 -*- # Generated by Django 1.11.9 on 2018-01-04 14:32 from __future__ import unicode_literals from django.db import migrations, models import xorgauth.utils.fields class Migration(migrations.Migration): dependencies = [ ('accounts', '0012_make_user_names_blank'), ] operations = ...
boundedCharField(verbose_name='display name'), ), migrations.AlterField( model_name='user', name='axid', field=models.CharField(blank=True, help_text='Identification in AX directory', max_length=20, null=True, unique=True, verbose_na...
aliasav/Bugman
bugman/manage.py
Python
gpl-2.0
249
0
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_
SETTINGS_MODULE", "bugman.settings") from django.core.management import execute_from_command_line exe
cute_from_command_line(sys.argv)
mfherbst/spack
var/spack/repos/builtin/packages/fluxbox/package.py
Python
lgpl-2.1
1,879
0.001597
############################################################################## # 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...
x(AutotoolsPackage): """Fluxbox is a windo
wmanager for X that was based on the Blackbox 0.61.1 code. It is very light on resources and easy to handle but yet full of features to make an easy, and extremely fast, desktop experience. """ homepage = "http://fluxbox.org/" url = "http://sourceforge.net/projects/fluxbox/files/fluxbox/1.3.7...
linwoodc3/gdeltPyR
tests/test_basevalues.py
Python
gpl-3.0
1,748
0.001144
#!/usr/bin/python # -*- coding: utf-8 -*- # Author: # Linwood Creekmore # Email: valinvescap@gmail.com ############################## # Standard Library Import ############################## import os from unittest import TestCase import numpy as np import pandas as pd ############################## # Custom Libra...
, drop=False, inplace=True) pri
nt("This is {}".format(gdelt.__file__)) return (self.assertTrue(resp.equals(codes))) def test_proxy_dict(self): "Test if proxy is dictionary" proxies = {"http": None, "https": None} gd = gdelt.gdelt(proxies=proxies) self.assertTrue(isinstance(gd.proxies, dict), "Test for di...
tiagocardosos/stoq
stoqlib/gui/search/stationsearch.py
Python
gpl-2.0
2,121
0.006601
# -*- coding: utf-8 -*- # vi:si:et:sw=4:sts=4:ts=4 ## ## Copyright (C) 2006-2007 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 Lesser General Public License as published by ## the Free Softw...
tion editor_class = StationEditor size = (-1, 450) advanced_search = False text_field_columns = [BranchStation.name] branch_filter_column = BranchStation.
branch_id # # SearchDialog Hooks # def get_columns(self): return [Column('name', _('Name'), data_type=str, sorted=True, width=190, searchable=True), AccessorColumn("branch", BranchStation.get_branch_name, ...
sayak1711/coding_solutions
coding-practice/Stack/prefix_to_infix.py
Python
mit
549
0.003643
operators = {'+', '-', '*', '/', '^'} def pre_to_in(expression): ''' scan right to left if
its a number push to stack if its a operator pop 2 numbers top is op1, next is op2 push back op1 operator op2 ''' stack = [] for token in expression.split()[::-1]: if token in operators: op1 = stack.pop() op2 = stack.pop() stack.append(f'({op1} {token...
= pre_to_in("* + a b / e f") print(ans)
boldmanQ/blogsys
blogsys/testcase/views.py
Python
mit
199
0.005025
# -*- coding: utf-8
-*- from __future__ import unicode_literals from django.shortcuts import render from django.http import HttpResponse def index(request
): return HttpResponse('hello, workd')
brianbruggeman/lose-7drl
lose/utils/ui/panels.py
Python
apache-2.0
1,076
0.000929
# -*- coding: utf-8 -*- import tcod from ..logger import get_logger logger = get_logger(__name__) __all__ = ['Panel'] class Panel(object): """Creates a panel on the screen. Args: width(int): Width of panel [default: 80] height(int): height of panel [default: 50] name(str): Title ...
parent=None): self.width = width or 80 self.height = height or 50 self.name = name or 'Untitled' self.position = position or (0, 0) self.parent = parent self.panel = tcod.console_new(self.width, self.height) def __repr__(self): cname = self.__class__.__name_...
me} {name} [{position} -> ({size})]>' return string
F5Networks/f5-ansible
ansible_collections/f5networks/f5_modules/plugins/lookup/license_hopper.py
Python
gpl-3.0
2,536
0.004338
# (c) 2013, Michael DeHaan <michael.dehaan@gmail.com> # (c) 2017 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type DOCUMENTATION = """ lookup: Select a random license k...
', False) if self.filename is None: raise AnsibleError("No 'filename' was specified") lookupfile = self.find_file_in_search_path(variables, 'files', self.filename) if lookupfile is None: raise AnsibleError("Could not find the specified 'filename'") fh = open(looku...
lines)] except Exception as e: raise AnsibleError("Unable to choose random license: %s" % to_native(e)) if self.remove: to_write = [x + "\n" for x in lines if x != ret[0]] fh = open(lookupfile, 'w') fh.writelines(to_write) return ret
fake-name/ReadableWebProxy
WebMirror/management/rss_parser_funcs/feed_parse_extractWwwNovicetranslationsCom.py
Python
bsd-3-clause
564
0.033688
def extractWwwNovicetranslationsCom(item): ''' Parser for 'www.novicetranslations.com' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfi
x(item['title']) if not (chp or vol) or "prev
iew" in item['title'].lower(): return None tagmap = [ ('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel'), ] for tagname, name, tl_type in tagmap: if tagname in item['tags']: return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix...
stxnext-kindergarten/presence-analizer-rkierzkowski
setup.py
Python
mit
909
0.0033
from setuptools import setup, find_packages import os name = "presence_analyzer" version = "0.2.0" def read(*rnames): return open(os.path.join(os.path.dirname(__file__), *rnames)).read() setup( name=name, version=version, des
cription="Presence analyzer", long_description=read('README.md'), classifiers=[], keywords="", author="", author_email='', url='', license='MIT', package_dir={'': 'src'}, packages=find_packages('src'), include_package_data=True, zip_safe=False, install_requires
=[ 'setuptools', 'Flask', 'lxml', 'requests', ], entry_points=""" [console_scripts] flask-ctl = presence_analyzer.script:run refresh-users = presence_analyzer.script:refresh_users [paste.app_factory] main = presence_analyzer.script:make_app debug = presence_anal...
spectrumtouch/lang_dynmcs
travis_pypi_setup.py
Python
mit
3,763
0.000266
#!/usr/bin/env python # -*- coding: utf-8 -*- """Update encrypted deploy password in Travis config file """ from __future__ import print_function import base64 import json import os from getpass import getpass import yaml from cryptography.hazmat.primitives.serialization import load_pem_public_key from cryptography.h...
umtouch/lang_dynmcs' TRAVIS_CONFIG_FILE = os.path.join( os.path.dirname(os.path.abspath(__file__)), '.travis.yml') def load_key(pubkey): """Load public RSA key, with work-around for keys using incorrect header/footer format. Read more about RSA encryption with cryptography: https://cryptography.i...
ey.encode(), default_backend()) except ValueError: # workaround for https://github.com/travis-ci/travis-api/issues/196 pubkey = pubkey.replace('BEGIN RSA', 'BEGIN').replace('END RSA', 'END') return load_pem_public_key(pubkey.encode(), default_backend()) def encrypt(pubkey, password): "...
jamesturk/oyster
oyster/tests/test_storage.py
Python
bsd-3-clause
1,021
0.000979
from nose.plugins.skip import SkipTest from oyster.conf import settings from oyster.core import Kernel from oyster.storage.gridfs import GridFSStorage from oyster.storage.dummy import DummyStorage def _simple_storage_test(StorageCls): kernel = Kernel(mongo_db='oyster_test') kernel.doc_classes['default'] = {}...
nsure the class has a storage_type attribute assert hasattr(storage, 'storag
e_type') doc = {'_id': 'aabbccddeeff', 'url': 'http://localhost:8000/#test', 'doc_class': 'default', 'metadata': {} } storage_id = storage.put(doc, 'hello oyster', 'text/plain') assert storage_id assert storage.get(storage_id) == 'hello oyster' def test_s3(): if not hasattr(settings, ...
monzum/tuf-legacy
src/TUF/src/tuf/tests/unittest_toolbox.py
Python
mit
16,778
0.009954
""" <Program> unittest_toolbox.py <Author> Konstantin Andrianov <Started> March 26, 2012 <Copyright> See LICENSE for licensing information. <Purpose> Provides an array of various methods for unit testing. Use it instead of actual unittest module. This module builds on unittest module. Specifically, ...
olute path of an empty temp file. make_temp_data_file(self, suffix='', directory=None, data = junk_data): Returns an absol
ute path of a temp file containing some data. make_temp_config_file(self, suffix='', directory=None, config_dict={}, expiration=None): Creates a temporary file and puts a config dictionary in it using ConfigParser. It then returns a (config_file_path, config_dictionary) tuple. make_temp_dir...
drnextgis/QGIS
python/plugins/processing/algs/gdal/rgb2pct.py
Python
gpl-2.0
2,969
0.000674
# -*- coding: utf-8 -*- """ *************************************************************************** rgb2pct.py --------------------- Date : August 2012 Copyright : (C) 2012 by Victor Olaya Email : volayaf at gmail dot com ******************************...
def getConsoleCommands(self): arguments = [] arguments.append('-n') arguments.append(str(self.getParameterValue(rgb2pct.NCOLORS))) arguments.append('-of') out = self.getOutputValue(rgb2pct.OUTPUT) arguments.ap
pend(GdalUtils.getFormatShortNameFromFilename(out)) arguments.append(self.getParameterValue(rgb2pct.INPUT)) arguments.append(out) if isWindows(): commands = ['cmd.exe', '/C ', 'rgb2pct.bat', GdalUtils.escapeAndJoin(arguments)] else: comman...
indevgr/django
tests/staticfiles_tests/test_management.py
Python
bsd-3-clause
14,449
0.002284
from __future__ import unicode_literals import codecs import os import shutil import tempfile import unittest from admin_scripts.tests import AdminScriptTestCase from django.conf import settings from django.contrib.staticfiles import storage from django.contrib.staticfiles.management.commands import collectstatic fr...
.strip() for l in result.split('\n')] self.assertEqual(len(lines), 3) # three because there is also the "Found <file> here" line self.assertIn('project', force_text(lines[1])) self.assertIn('apps', force_text(lines[2])) def test_all_files_less_verbose(self): """
Test that findstatic returns all candidate files if run without --first and -v0. """ result = call_command('findstatic', 'test/file.txt', verbosity=0, stdout=six.StringIO()) lines = [l.strip() for l in result.split('\n')] self.assertEqual(len(lines), 2) self.assertIn('project'...
dwhickox/NCHS-Programming-1-Python-Programs
Chap 3/Squares.py
Python
mit
778
0.025707
#David Hickox #Feb 15 17 #Squares (counter update) #descriptions, description, much descripticve #variables # limit, where it stops # num, sentry variable #creates array if needbe #array = [[0 for x in range(h)] for y in range(w)] #imports date time and curency handeling because i hat
e string formating (this takes the place of #$%.2f"%) import locale locale.setlocale( locale.LC_ALL, '' ) #use locale.currency() for currency formating print("Welcome to the (insert name here bumbblefack) Program\n") limit = float(input("How many squares do you want? ")) num = 1 print("number\tnumber^2") while num <=...
um,num**2,sep='\t') #increments num += 1 input("\nPress Enter to Exit")
dopplershift/MetPy
src/metpy/io/_nexrad_msgs/__init__.py
Python
bsd-3-clause
203
0
# Copyright (c) 2016
MetPy Developers. # Distributed under the terms of the BSD 3-Clause License. # SPDX-License-Identifier: BSD-3-Clause """Contains parsed specs for various NEXRAD messages fo
rmats."""
camilortte/RecomendadorUD
apps/establishment_system/migrations/0001_initial.py
Python
mit
5,616
0.006944
# -*- coding: utf-8 -*- from south.utils import datetime_utils as 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 'Categoria' db.create_table(u'establishment_system_categor...
'establishment_system', ['SubCategoria']) # Addi
ng model 'Establecimiento' db.create_table(u'establishment_system_establecimiento', ( (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('nombre', self.gf('django.db.models.fields.CharField')(unique=True, max_length=100)), ('email', self.gf('django.db.m...
ahamilton/vigil
eris/__main__.py
Python
artistic-2.0
48,571
0.000103
#!/usr/bin/env python3.9 # -*- coding: utf-8 -*- """Eris Codebase Monitor Eris maintains an up-to-date set of reports for every file in a codebase. A status indicator summarises the state of each report, and a report is viewed by selecting this status indicator with the cursor. The reports are cached in the codeba...
os.path.basename(path)) def type_sort(entry): path = entry.path return (tools.splitext(path)[1], os.path.dirname(path), os.path.basename(path)) class Summary: def __init__(self, root_path, jobs_added_event): self._root_path = root_path self._jobs_added_event = jobs_...
d_entries = [] self.__cursor_position = (0, 0) self.reset() def reset(self): Entry.MAX_WIDTH = 0 self._max_path_length = 0 self.result_total = 0 self.completed_total = 0 self.is_loaded = False self.closest_placeholder_generator = None sort_fun...
bert/geda-gaf
xorn/src/python/base64.py
Python
gpl-2.0
7,731
0.030526
# xorn.geda - Python library for manipulating gEDA files #********************************************************************** # _ _ __ _ _ # __ _ _ __ ___| |_ | |__ __ _ ___ ___ / /_ | or | # / _` | '_ \ / _ \ __| | '_ \ / _` / __|/ _ \ '_ \| or |_ # | (_| | | | ...
elif state == 1: # Invalid = in second position raise DecodingError elif state == 2: # Valid, means one byte of info # Make sure there is another trailing = sign. if pad != 2: raise DecodingError elif state == 3: ...
ise DecodingError if state == 2 or state == 3: # Now make sure for cases 2 and 3 that the "extra" # bits that slopped past the last full byte were # zeros. If we don't check them, they become a # subliminal channel. if res != 0: raise ...
aroig/async
async/config.py
Python
gpl-3.0
12,584
0.011444
#!/usr/bin/env python # -*- coding: utf-8 -*- # # async - A tool to manage and sync different machines # Copyright 2012,2013 Abdó Roig-Maranges <abdo.roig@gmail.com> # # 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 # th...
val, dic): return parse_dict(key, val, dic, parse_path) def parse_list_path(key, val, dic): return parse_list(key, val, dic, parse_path) def parse_keyval_path(key, val, dic): return parse_keyval(key, val, dic, parse_path) class AsyncConfig(ConfigParser): # default values and parsing functions
FIELDS={ 'host': { 'dirs' : ([], parse_list), 'ignore' : ([], parse_list_path), 'symlinks' : ({}, parse_dict_path), # key:val. 'key' is dirname, 'val' target path. 'hostname' : (None, parse_string), 'user' :...
xrotwang/segments
setup.py
Python
apache-2.0
1,483
0
# -*- coding: utf-8 -*- from setuptools import setup, find_packages requires = [ 'regex', 'six', 'clldutils>=1.7.3', ] tests_require = [ 'mock', ] testing_extras
= tests_require + [ 'nose', 'coverage', ] def read(fname): with open(fname) as fp: content = fp.read() return content setup( name='segments', version="1.1.0", description='', long_description=read("README.rst"), author='Steven Moran', author_email='steven.moran@uzh.ch...
mbooforest/segments', install_requires=requires, license=read("LICENSE"), zip_safe=False, keywords='tokenizer', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: Engli...
kunxi/docxgen
tests/test_docx.py
Python
mit
2,167
0.005999
from datetime import datetime from zipfile import ZipFile from io import BytesIO from lxml import etree from docxgen import * from docxgen import nsmap from . import check_tag def test_init(): doc = Document() check_tag(doc.doc, ['document', 'body']) check_tag(doc.body, ['body']) def test_save(): doc ...
('word/document.xml') root = etree.parse(zxf) check_tag(root, 'document body'.split()) def test_load(): # assume save works d = Document() tmp = BytesIO() d.save(tmp) doc = Document.load(tmp) check_tag(doc.doc, 'document body'.split()) chec
k_tag(doc.body, 'body'.split()) def test_dumps(): doc = Document() assert doc.dumps() def test_core_props(): doc = Document() attrs = dict(lastModifiedBy='Joe Smith', keywords=['egg', 'spam'], title='Testing Doc', subject='A boilerplate document', creator='Jill Smith', ...
ukurumba/epidemic_network_modelling
setup.py
Python
mit
2,161
0.004627
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup from distutils.core import setup from Cython.Build import cythonize from distutils.extension import Extension from Cython.Distutils import build_ext with open('README.rst') as readme_file: readme = readme_file.read() with open('HISTORY.r...
e_dir={'epidemic_network_modelling': 'epidemic_network_modelling'}, include_package_data=True, install_requires=requirements, license="MIT license", zip_safe=False, keywords='epidemic_network_modelling', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Inten...
sh', "Programming Language :: Python :: 2", 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Lang...
anoushkaalavilli/String-Jumble
stringjumble.py
Python
mit
1,639
0.010982
""" stringjumble.py Author: Eric Credit: Me! Assignment: The purpose of this challenge is to gain proficiency with manipulating lists. Write and submit a Python program that accep
ts a string from the user and prints it back in three different ways: * With all letters in reverse. * With words in reverse order, but letters within each w
ord in the correct order. * With all words in correct order, but letters reversed within the words. Output of your program should look like this: Please enter a string of text (the bigger the better): There are a few techniques or tricks that you may find handy You entered "There are a few techniques or tricks ...
matrumz/RPi_Custom_Files
Printing/hplip-3.15.2/installer/dcheck.py
Python
gpl-2.0
10,306
0.006889
#!/usr/bin/env python # -*- coding: utf-8 -*- # # (c) Copyright 2003-2007 Hewlett-Packard Development Company, L.P. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the Lice...
.join(utils.which('ldconfig'), 'ldconfig'), log_output=False)
if status != 0: log.debug("ldconfig failed.") def check_tool(cmd, min_ver=0.0): log.debug("Checking: %s (min ver=%f)" % (cmd, min_ver)) status, output = utils.run(cmd) if status != 0: log.debug("Not found!") return False else: if min_ver: try: ...
amchagas/python-neo
neo/core/event.py
Python
bsd-3-clause
1,955
0.000512
# -*- coding: utf-8 -*- ''' This module defines :class:`Event`, an event occuring at a particular point in time. :class:`Event` derives from :class:`BaseNeo`, from :module:`neo.core.baseneo`. ''' # needed for python 3 compatibility from __future__ import absolute_import, division, print_function import quantities as...
Initialize a new :class:`Event` instance. ''' BaseNeo.__init__(self, name=name, file_origin=file_origin, description=description, **annotations) self.time = time self.label = label self.segment = None def merge(self, other): ''' ...
rging is not supported in :class:`Epoch`. ''' raise NotImplementedError('Cannot merge Epoch objects')
beaker-project/beaker
Server/bkr/server/tag.py
Python
gpl-2.0
1,468
0.012943
# This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. from bkr.server.database import session from turbogears import expose,...
s_grid = widgets.PaginateDataGrid(fields=[ widgets.PaginateDataGrid.Column(name='tag', getter=lambda x: make_link(url = '../distros/tagsearch/?tag=%s' % x.tag, text = x.tag), title='Tag', options=dict(sortable=True)),
]) return dict(title="Tags", grid = tags_grid, search_bar = None, list = tags) default = index
plotly/python-api
packages/python/plotly/plotly/validators/violin/_hovertext.py
Python
mit
498
0.002008
import _plotly_utils.basevalidators class HovertextValidator(_plotly_utils.basevalidators.StringValidator): de
f __init__(self, plotly_name="hovertext", parent_name="violin", **kwargs): super(HovertextValidator, self).__init__( plotly_name=plotly_name, parent_name=p
arent_name, array_ok=kwargs.pop("array_ok", True), edit_type=kwargs.pop("edit_type", "style"), role=kwargs.pop("role", "info"), **kwargs )
peragro/peragro-at
src/damn_at/analyzers/audio/metadata.py
Python
bsd-3-clause
2,736
0.004386
from damn_at.metadata import MetaDataExtractor from damn_at import MetaDataType class MetaDataSox(MetaDataExtractor): duration = MetaDataType.STRING, lambda context: context['duration'] precision = MetaDataType.STRING, lambda context: context['precision'] bit_rate = MetaDataType.STRING, lambda context: c...
.INT, lambda context: int(context['sample_rate']) class MetaDataAcoustID(MetaDataExtractor): duration = MetaDataType.STRING, lambda context: context['duration'] fingerprint = MetaDataType.STRING, lambda context: context['fingerprint'] fingerprint_uuid = MetaDataType.STRING, lambda context: context['finge...
_uuid'] class MetaDataFeatureExtraction(MetaDataExtractor): bpm = MetaDataType.INT, lambda context: int(context['bpm']) beats_count = MetaDataType.DOUBLE, lambda context: float(context['beats_count']) chord = MetaDataType.STRING, lambda context: context['chord'] key = MetaDataType.STRING, lambda cont...
eggsandbeer/scheduler
db/dao/site_dao.py
Python
bsd-3-clause
1,526
0.000655
__author__ = 'Bohdan Mushkevych' from bson import ObjectId from threading import RLock from db.model.raw_data import * from db.model.site_statistics import SiteStatistics from synergy.db.manager import ds_manager from synergy.system.decorator import thread_safe class SiteDao(object): """ Thread-safe Data Access...
f.logger = logger self.lock = RLock() self.ds = ds_manager.ds_factory(logger) @thread_safe def get_one(self,
collection_name, domain_name, timeperiod): collection = self.ds.connection(collection_name) query = {DOMAIN_NAME: domain_name, TIMEPERIOD: timeperiod} document = collection.find_one(query) if document is None: raise LookupError('MongoDB has no site record in...
JohnTroony/nikola
nikola/plugins/compile/html.py
Python
mit
2,509
0
# -*- coding: utf-8 -*- # Copyright © 2012-2015 Roberto Alsina and others. # 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 t...
FTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """Implementation of compile_html for HTML source files.""" from __future__ import unicode_literals import os im
port io from nikola.plugin_categories import PageCompiler from nikola.utils import makedirs, write_metadata class CompileHtml(PageCompiler): """Compile HTML into HTML.""" name = "html" def compile_html(self, source, dest, is_two_file=True): makedirs(os.path.dirname(dest)) with io.open(de...
arhote/exchange
exchange/tests/test_get_version.py
Python
gpl-3.0
298
0
from exchange i
mport __version__ as the_version, get_version from . import ExchangeTest class TestGetVersion(ExchangeTest): def test_get_version(self): self.assertTrue( the_version in get_version(), '%s != %s! Bad version!' % (the_version, get
_version()))
DIRACGrid/DIRAC
src/DIRAC/DataManagementSystem/DB/FileCatalogComponents/DirectoryMetadata/DirectoryMetadata.py
Python
gpl-3.0
37,350
0.001847
""" DIRAC FileCatalog mix-in class to manage directory metadata """ # pylint: disable=protected-access import six import os from DIRAC import S_OK, S_ERROR from DIRAC.Core.Utilities.Time import queryTime class DirectoryMetadata(object): def __init__(self, database=None): self.db = database def setDa...
_MetaFields" result = self.db._query(req) if not result["OK"]: return result metaDict = {} for row
in result["Value"]: metaDict[row[0]] = row[1] return S_OK(metaDict) def addMetadataSet(self, metaSetName, metaSetDict, credDict): """Add a new metadata set with the contents from metaSetDict :param str metaSetName: metaSet name :param dict metaSetDict: contents of the ...
eentzel/myeventbot
outgoing_mail.py
Python
mit
1,865
0.003753
#!/usr/bin/env python # # Copyright 2010 Eric Entzel <eric@ubermac.net> # from google.appengine.api import mail from google.appengine.ext.webapp import template from google.appengine.api imp
ort memcache from datetime import datetime import os from_address = '"EventBot" <admin@myeven
tbot.com>' email_interval = 10 # TODO: the memcache rate-limiting part of this might make a nice decorator # TODO: swallow over quota exception so tasks don't back up def send(to, template_name, values, extra_headers=None): """Send an email to the specified address using a template. No more than one email ...
MaximeGLegault/StrategyIA
RULEngine/Util/image_transformer/kalman_image_transformer.py
Python
mit
2,570
0.002335
import time from copy import deepcopy from RULEngine.Util.Pose import Pose from RULEngine.Util.Position import Position from RULEngine.Util.image_transformer.image_transformer import ImageTransformer from config.config_service import ConfigService class KalmanImageTransformer(ImageTransformer): def __init__(self...
amera["ball"] = Position(ball.x, ball.y) for blue in packet.detection.robots_blue: new_camera["blues"][blue.robot_id] = Pose(Position(blue
.x, blue.y), blue.orientation) for yellow in packet.detection.robots_yellow: new_camera["yellows"][yellow.robot_id] = Pose(Position(yellow.x, yellow.y), ...
Comunitea/CMNT_004_15
project-addons/product_battery/models/product.py
Python
agpl-3.0
175
0
from odoo import fields, m
odels class ProductTemplate(models.Model): _inherit = 'product.template' battery_id = fields.Many2one('product.battery', 'Ba
ttery Type')
holdenk/spark
python/pyspark/rdd.py
Python
apache-2.0
109,178
0.001878
# # Licensed to the Apache Soft
ware Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in complianc...
to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import copy import sys import os import operato...
choldgraf/ecogtools
ecogtools/utils.py
Python
bsd-2-clause
5,920
0
"""Quick utility functions.""" from IPython import embed import numpy as np import pandas as pd import mne import sys from os import path, sep, remove from glob import glob from datetime import datetime def vembed(): import matplotlib.pyplot as plt embed() def ipy_post_mortem(): """Causes ipython/idb t...
day = datetime.today() time_stamp = '_'.join([str(i) for i in [today.date(), 'h{}'.format(today.hour), 'm{}'.format(today.minute)]]) if append is not None: if overwrite is True: to_remove = glob(dir_name ...
t(over_file)) remove(over_file) time_stamp = time_stamp + '__' + append + '.stamp' file_stamp = path.dirname(save_path) + '/{0}'.format(time_stamp) open(file_stamp, 'a').close() def decimate_by_binning(data, data_names, n_decim): """Decimates along the first axis.""" data_names...
beeverycreative/BEEweb
src/octoprint/util/bvc_gcoder.py
Python
agpl-3.0
22,091
0.004029
#!/usr/bin/env python # This file is copied from GCoder. # # GCoder 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. # # GCoder is distr...
rrent coordinate system: current_x - offset_x filament_length = None duration = None xmin = None xmax = None ymin = None ymax = None zmin = None zmax = None width = None depth = None height = None est_layer_height = None # abs_x is the c
urrent absolute X in machine current coordinate system # (after the various G92 transformations) and can be used to store the # absolute position of the head at a given time def _get_abs_x(self): return self.current_x - self.offset_x abs_x = property(_get_abs_x) def _get_abs_y(self): ...
cvsuser-chromium/chromium
mojo/public/bindings/generators/mojom.py
Python
bsd-3-clause
3,043
0.023661
# Copyright (c) 2013 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. # mojom's classes provide an interface to mojo modules. Modules are collections # of interfaces and structs to be used by mojo ipc clients and servers. #...
d('u16') UINT32 = Kind('u32') UINT64 = Kind('u64') FLOAT = Kind('f') DOUBLE = Kind('d') STRING = Kind('s') HANDLE = Kind('h') # Collection of all Primitive types PRIMITIVES = ( BOOL, INT8, INT16, INT32, INT64, UINT8, UINT16, UINT32, UINT64, FLOAT, DOUBLE, STRING, HANDLE ) class Field(obje...
.default = default class Struct(Kind): def __init__(self, name = None): self.name = name if name != None: spec = 'x:' + name else: spec = None Kind.__init__(self, spec) self.fields = [] def AddField(self, name, kind, ordinal = None, default = None): field = Field(name, kind, o...
CSC-IT-Center-for-Science/pouta-blueprints
pebbles/views/blueprint_templates.py
Python
mit
7,676
0.002475
from flask_restful import marshal_with, reqparse from flask import abort, g from flask import Blueprint as FlaskBlueprint from flask_restful import fields from sqlalchemy.orm.session import make_transient import logging import uuid from pebbles.models import db, BlueprintTemplate, Plugin from pebbles.forms import Blu...
s.String(attribute='id'), 'name': fields.String, 'is_enabled': fields.Boolean, 'plugin': fields.String, 'config': fields.Raw, 'schema': fields.Raw, 'form': fields.Raw, 'allowed_attrs': fields.Raw, 'blueprint_schema': fields.Raw, 'blueprint_form': fields.Raw, 'blueprint_model': fi...
mplateList(restful.Resource): @auth.login_required @requires_group_manager_or_admin @marshal_with(blueprint_template_fields) def get(self): user = g.user query = apply_rules_blueprint_templates(user) query = query.order_by(BlueprintTemplate.name) results = [] for ...
chuckharmston/ghosttown
setup.py
Python
mpl-2.0
788
0
import os from setuptools impor
t setup, find_packages __dirname = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(__dirname, 'README.md')) as readme: README = readme.read() with open(os.path.join(__dirname, 'app', 'requirements.txt')) as reqs: REQUIREMENTS = reqs.read() setup(name='ghosttown', version='0.0.1', ...
long_description=README, classifiers=[ "Programming Language :: Python", "Framework :: Flask", "Topic :: Internet :: WWW/HTTP", ], author='Chuck Harmston', author_email='chuck@mozilla.com', packages=find_packages(), include_package_data=True, zip_saf...
team-vigir/flexbe_behavior_engine
flexbe_states/src/flexbe_states/input_state.py
Python
bsd-3-clause
2,805
0.003565
#!/usr/bin/env python import pickle from flexbe_core import EventState, Logger from flexbe_msgs.msg import BehaviorInputAction, BehaviorInputGoal, BehaviorInputResult from flexbe_core.proxy import ProxyActionClient class InputState(EventState): ''' Implements a state where the state machine needs an input fr...
waypoint, a template, or a pose, can be specified. -- request uint8 One of the custom-defined values to specify the type of request. -- message strin
g Message displayed to the operator to let him know what to do. #> data object The data provided by the operator. The exact type depends on the request. <= received Returned as soon as valid data is available. <= aborted The operator declined to provide the requested data. <= no_connection...
lockout87/Projects
Python/bodyguards.py
Python
mit
510
0.037255
import urllib.r
equest, urllib def get_challenge(s): return urllib.request.urlopen('http://www.pythonchallenge.com/pc/' + s).read() src = get_challenge('def/equali
ty.html') count = 0 lcount = 0 ucount = 0 print (src) for i in src: if i == i.uppercase(): count += 1 if count == 3 and i == i.lowercase() and ucount == 0: lcount += 1 jew = i if count == 3 and i == i.uppercase() and lcount == 1: ucount += 1 if count > 3 or lcount > 1 or ucount > 3: count = 0 lcount = ...
jaconsta/soat_cnpx
api/citizens/models.py
Python
mit
672
0
from django.db import models class Citizen(models.Model): """ The insurance users. """ name = models.CharField(max_length=50) last_nam
e = models.CharField(max_length=50) # Contact information email = models.EmailField() phone = models.CharField(max_length=50) # Citizen documents CC = 'CC' PASSPORT = 'PP' document_choices = ( (CC, 'cc'), (PASSPORT, 'Passport') ) document_type = models.CharField(max...
models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True)
zhreshold/mxnet
example/extensions/lib_custom_op/test_relu.py
Python
apache-2.0
2,798
0.006076
#!/usr/bin/env python3 # 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 # "...
------ndarray compute---------") print(mx.nd.my_relu(a)) print(mx.nd.my_relu(b)) print(mx.nd.my_state_relu(a)) print(mx.nd.my_state_relu(b)) print("--------symbolic compute--------") c = mx.sym.Variable('c') d = mx.sym.Variable('d') e = mx.sym.my_relu(c) base = mx.sym.relu(d) in_grad = [mx.nd.empty((2,2), ctx=mx.gpu()...
rad_base = [mx.nd.empty((2,2), ctx=mx.gpu())] exe = e.bind(ctx=mx.gpu(), args={'c':b}, args_grad=in_grad) exe_base = base.bind(ctx=mx.gpu(), args={'d':b}, args_grad=in_grad_base) out = exe.forward() out_base = exe_base.forward() print(out) print(out_base) print("--------backward compute--------") out_grad = mx.nd.ones...
0359xiaodong/viewfinder
backend/www/test/xsrf_test.py
Python
apache-2.0
5,189
0.008094
#!/usr/bin/env python # # Copyright 2012 Viewfinder Inc. All Rights Reserved. """Test xsrf protection. """ __author__ = 'mike@emailscrubbed.com (Mike Purtell)' import json import re from viewfinder.backend.base import message from viewfinder.backend.www.test import service_base_test class XsrfTestCase(service_base...
.ics', 'year': 2012}]}),
headers={'Content-Type': 'application/json', 'Cookie': 'user=%s' % self._cookie}) response = self.wait() self.assertEqual(response.code, 200) set_cookie = response.headers.get('Set-Cookie', '') match = re.compile('_xsrf=(.*);').match(set_coo...
mice-software/maus
src/input/InputCppRootData/test_input_cpp_root_data.py
Python
gpl-3.0
9,584
0.010017
# This file is part of MAUS: http://micewww.pp.rl.ac.uk:8080/projects/maus # # MAUS 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...
maus_cpp.converter.del_data_repr(event) for key, value in checks.iteritems(): self.assertEqual(json_event[key], value, msg=str(key)+":"+str(value)+"\n"+json.dumps(json_event, indent=2)) def test_read_events(self): """ Try reading a realistic data structure ...
s":[]})) # should ignore headers and go straight for spills... self.__test_event(inputter, {"maus_event_type":"Spill", "run_number":10, "spill_number":1}) self.__test_event(inputter, {"maus_event_type":"Spill", ...
fracpete/python-weka-wrapper-examples
src/wekaexamples/flow/list_file.py
Python
gpl-3.0
1,948
0.00154
# This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # b...
files.config["dir"] = str(tempfile.gettempdir()) listfiles.config["list_files"] = True listfiles.config["list_dirs"] = False listfiles.config["recursive"] = False listfiles.config["regexp"] = ".*r.*" # listfiles.print_
help() flow.actors.append(listfiles) console = Console() console.config["prefix"] = "Match: " # console.print_help() flow.actors.append(console) # run the flow msg = flow.setup() if msg is None: print("\n" + flow.tree + "\n") msg = flow.execute() if msg is not N...
Chiefwaffles/-tg-station
bot/NanoTrasenBot.py
Python
gpl-3.0
71,195
0.027054
# -*- coding: utf-8 -*- # This script is shared under the # Creative Commons Attribution-ShareAlike 3.0 license (CC BY-SA 3.0) # Added clause to Attribution: # - You may not remove or hide the '<Bot_name> who created you?' functionality # and you may not modify the name given in the response. #CREDITS # Auth...
essage_limit = 5 # per u
ser optimize_fml = True # -CPU usage +Memory usage when enabled. optimize_greeting = True # +Startup time +Memory usage -CPU usage when enabled heavy_psyco = True # +Memory +Startup time -CPU usage -CPU time cache_youtube_links = True personality_greeter = True respond_of_course = True #Responds with "Of course!"...
tpltnt/ircensus
ircensus_channel_bot.py
Python
agpl-3.0
2,132
0.002345
#!/usr/bin/env python3 """ A simple bot to gather some census data in IRC channels. It is intended to sit in a channel and collect the data for statistics. :author: tpltnt :license: AGPLv3 """ import irc.bot import irc.strings from irc.client import ip_numstr_to_quad, ip_quad_to_numstr
class CensusBot(irc.bot.
SingleServerIRCBot): """ The class implementing the census bot. """ def __init__(self, channel, nickname, server, port=6667): """ The constructor for the CensusBot class. :param channel: name of the channel to join :type channel: str :param nickname: nick of the...
flennerhag/mlens
benchmarks/scale_cpu.py
Python
mit
5,516
0.000181
"""ML-ENSEMBLE Comparison of multiprocessing performance as data scales. Example Output -------------- ML-ENSEMBLE Threading performance test for data set dimensioned up to (10000, 50) Available CPUs: 4 Ensemble architecture Num layers: 2 Fit per b
ase layer estimator: 2 + 1 layer-1 | Estimators: ['svr-1', 'svr-2', 'svr-3', 'svr-4']. layer-2 | Meta Estimator: svr FIT TIMES samples 1000 SuperLearner (1) : 0.88s | BlendEnsemble (1) : 0.35s | 1000 SuperLearner (4) : 0.71s | BlendEnsemble (4) : 0.41s | 2000 SuperLearner (1) : 2.82s | BlendEnsembl...
emble (4) : 0.59s | 3000 SuperLearner (1) : 6.04s | BlendEnsemble (1) : 1.56s | 3000 SuperLearner (4) : 2.96s | BlendEnsemble (4) : 0.90s | 4000 SuperLearner (1) : 10.94s | BlendEnsemble (1) : 2.79s | 4000 SuperLearner (4) : 7.92s | BlendEnsemble (4) : 1.53s | 5000 SuperLearner (1) : ...
szaghi/MaTiSSe
release/MaTiSSe-0.3.3/matisse/matisse.py
Python
gpl-3.0
6,252
0.008157
#!/usr/bin/env python """ MaTiSSe.py, Markdown To Impressive Scientific Slides """ __appname__ = "MaTiSSe.py" __description__ = "MaTiSSe.py, Markdown To Impressive Scientific Slides" __long_description__ = "MaTiSSe.py, Markdown To Impressive Scientific Slides. It is a very simple and stupid-to-use (KISS) presentation m...
tput_tree(output=output) if __config__.verbose: print('Parsing source ' + cliargs.input) presentation = Presentation(source=source) presentation.save(output=output) pprint(presentation=presentation, cliargs=cliargs) if cliargs.sample: source = __config__.put_theme(source=__sample__...
h open(cliargs.sample, 'w') as sample: sample.write(source) source = seditor.includes(source=source) presentation = Presentation(source=source) output = os.path.splitext(os.path.basename(cliargs.sample))[0] + os.sep make_output_tree(output=output) presentation.save(output=output) pprint(pr...
ovnicraft/openerp-restaurant
poi_pos_table_designer/controllers/__init__.py
Python
agpl-3.0
1,093
0.00183
# -*- coding: utf-8 -*
- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # Copyright (C) 2011-2013 Serpent Consulting Services Pvt. Ltd. (<http://serpentcs.com>). # # This program is free software: y...
General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNE...
ddboline/sync_app
sync_app/file_info_local.py
Python
mit
2,404
0.000832
#!/usr/bin/python # -*- coding: utf-8 -*- """ extract FileInfo object for local files """ from __future__ import (absolute_import, division, print_function, unicode_literals) import multiprocessing as mp from concurrent.futures import ProcessPoolExecutor import os from sync_app.util import get_md5, get_sha1 fro...
t os.path.isfile(absfn): print('ERROR') raise TypeError _url = 'file://%s' % absfn FileInfo.__init__(self, fn=absfn, url=_url, md5=md5, sha1=sha
1, fs=fs, in_tuple=in_tuple) def get_md5(self): """ Wrapper around sync_utils.get_md5 """ if os.path.exists(self.filename): return _pool.submit(get_md5, self.filename) else: return self.md5sum def get_sha1(self): """ Wrapper around sync_utils.get_sha1 ""...
glemaitre/protoclass
protoclass/extraction/brix_quantification_extraction.py
Python
gpl-2.0
11,975
0
"""Brix quantification extraction from temporal modality.""" from __future__ import division import numpy as np from joblib import Parallel, delayed from scipy.optimize import curve_fit from .temporal_extraction import TemporalExtraction from .tofts_quantification_extraction import ToftsQuantificationExtraction fr...
) - 1) * np.exp(-kel * t) - b * (np.exp(k21 * t_prime) - 1) * np.exp(-k21 * t))) return s_t def _fit_hoffmann_model(t_mod, s_t, S0, start_enh, init_params): """Private f
unction to fit concentration to extended Hoffmann model. Parameters ---------- t_mod : ndarray, shape (n_serie, ) The time associated to the concentration kinetic. s_t : ndarray, shape (n_serie, ) Signal of the pixel to be fitted. S0 : float, The value of the baseline to n...
korniichuk/rk
rk/ssh/__init__.py
Python
unlicense
28
0
from rk.ssh.tunnel imp
ort
*
crashtack/code-katas
src/stack.py
Python
mit
511
0
# -*- coding utf-
8 -*- from linked_list import LinkedList class Stack(object): def __init__
(self, input=None): self._linked_list = LinkedList(input) def pop(self): """pops the vlaue of the top of the stack""" return self._linked_list.pop() def push(self, val): """pushes a value onto the top of the stack""" return self._linked_list.push(val) def size(self...
GrognardsFromHell/TemplePlus
tpdatasrc/tpgamefiles/scr/tpModifiers/abjurant_champion.py
Python
mit
13,175
0.030133
from templeplus.pymod import PythonModifier from toee import * import tpdp import char_class_utils import tpactions ################################################### def GetConditionName(): return "Abjurant Champion" def GetSpellCasterConditionName(): return "Abjurant Champion Spellcasting" print "Registering ...
137) # untyped, description: "Class" return 0 def OnGetSaveThrowFort(attachee, args, evt_obj): value = char_class_utils.SavingThrowLevel(classEnum, attachee, D20_Save_Fortitude) evt_obj.bonus_list.add(value, 0, 137)
return 0 def OnGetSaveThrowReflex(attachee, args, evt_obj): value = char_class_utils.SavingThrowLevel(classEnum, attachee, D20_Save_Reflex) evt_obj.bonus_list.add(value, 0, 137) return 0 def OnGetSaveThrowWill(attachee, args, evt_obj): value = char_class_utils.SavingThrowLevel(classEnum, attachee, D20_Save_Will) ...
ryszard/django-fts
fts/words/porter.py
Python
bsd-3-clause
12,764
0.005798
"""Porter Stemming Algorithm This is the Porter stemming algorithm, ported to Python from the version coded up in ANSI C by the author. It may be be regarded as canonical, in that it follows the algorithm presented in Porter, 1980, An algorithm for suffix stripping, Program, Vol. 14, no. 3, pp 130-137, only differin...
s(1)) if i == 0 or not self.cons(i) or self.cons(i-1) or not self.cons(i-2): return 0 ch = self.b[i] if ch == 'w' or ch == 'x' or ch == 'y': return 0 return 1 def ends(self, s): """ends(s) is TRUE <=> k0,...k ends with the string s.""" length ...
iny speed-up return 0 if length > (self.k - self.k0 + 1): return 0 if self.b[self.k-length+1:self.k+1] != s: return 0 self.j = self.k - length return 1 def setto(self, s): """setto(s) sets (j+1),...k to the characters in the string s, read...
Aloomaio/googleads-python-lib
examples/ad_manager/v201811/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py
Python
apache-2.0
2,126
0.006585
#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requir...
h suggested ad unit. print( 'Suggested ad unit with ID "%s" and num requests "%d" was found.\n' % (suggested_ad_unit['id'], suggested_ad_unit['numRequests'])) statement.offset += statement.limit else:
break print '\nNumber of results found: %s' % response['totalResultSetSize'] if __name__ == '__main__': # Initialize client object. ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() main(ad_manager_client, NUM_REQUESTS)
RodericDay/CIF-characterize
characterize.py
Python
mit
2,124
0.004708
import re import numpy as np from scipy import ndimage, spatial import bresenham import mpl_tools import vtk_tools def load_pdb(name): with open(name+'.pdb') as fp: points = [] conns = [] for line in fp: if line.startswith('HET'): pattern = r'(-?\d+.\d\d\d)'...
ll needs a lot of improvement ''' im = np.atleast_3d(im) data = ndimage.morphology.distance_transform_edt(im) max_data = ndimage.filters.maximum_filter(data, 10) maxima = data==max_data # but this includes some globally low voids min_data = ndimage.filters.minimum_filter(data, 10) diff = (ma...
dimage.center_of_mass(labels==i) for i in range(1, num_maxima+1)] radii = [data[center] for center in centers] return np.array(centers), np.array(radii) def rasterize(): pass solid_nodes, solid_edges = map(np.array, load_pdb('CHA')) solid_nodes -= solid_nodes.min(axis=0) solid_nodes *= 4 coord_pair = sol...
jordibc/destaca_palabras
test_iwords.py
Python
gpl-3.0
823
0.001218
""" Test functions in iwords.py. To run with pytest. """ import os from tempfile import NamedTemporaryFile import iwords def test_get_freqs():
with NamedTemporaryFile() as fp: fp.write(b'Hello world!') fp.flush() assert iwords.get_freqs([fp.name]) == {'hello': 0.5, 'world': 0.5} def test_clean(): assert iwords.clean('Cómo estás') == 'como estas' def test_run(): assert os.system('./iwords.py --help') == 0 with NamedTem...
f'./iwords.py {fp.name} --show-score') == 0 assert os.system(f'./iwords.py {fp.name} --limit 1') == 0 assert os.system(f'./iwords.py {fp.name} --learn /usr/share/dict/words') == 0
Silvian/Blog
blog/migrations/0005_auto_20160404_2211.py
Python
gpl-3.0
599
0.001669
# -*- coding: utf-8 -*- # Generat
ed by Django 1.9.1 on 2016-04-04 22:11 from __future__ import unicode_literals import
datetime from django.db import migrations, models from django.utils.timezone import utc class Migration(migrations.Migration): dependencies = [ ('blog', '0004_auto_20160404_2211'), ] operations = [ migrations.AlterField( model_name='blog', name='published_date', ...
Karel-van-de-Plassche/bokeh
bokeh/models/markers.py
Python
bsd-3-clause
5,924
0.002532
''' Display a variety of simple scatter marker shapes whose attributes can be associated with data columns from ``ColumnDataSources``. The full list of markers built into Bokeh is given below: * :class:`~bokeh.models.markers.Asterisk` * :class:`~bokeh.models.markers.Circle` * :class:`~bokeh.models.markers.CircleCross...
markers.InvertedTriangle` * :class:`~bokeh.models.markers.Square` * :class:`~bokeh.models.markers.SquareCross` * :class:`~bokeh.models.markers.SquareX` * :class:`~bokeh.models.markers.Triangle` * :class:`~bokeh.models.markers.X` Markers are all su
bclasses of ``Glyph``. Additionally, they all share the same common interface providing fill and line properties provided by their base class ``Marker``. Note that a few glyphs, ``Cross`` and ``X``, only draw lines. For these the fill property values are ignored. Also note that the ``Circle`` glyph has some additional ...
richardcornish/django-itunespodcast
podcast/migrations/0020_auto_20171026_2121.py
Python
bsd-3-clause
1,412
0.002833
# -*- coding: utf-8 -*- # Generated by Django 1.11.5 on 2017-10-26 21:21 from __future__ import unicode_literals from django.db import migrations, models def get_status(apps, schema_editor): Episode = apps.get_model('podcast', 'Episode') for episode in Episode.objects.all(): episode.status = 'public'...
migrations.AlterField( model_name='episode', name='pub_date', field=models.DateTimeField(help_text='If in future
, episode hidden until date arrives (unless status is secret)', verbose_name='pub date'), ), migrations.RunPython(get_status, reverse_code=migrations.RunPython.noop), ]
kirichoi/tellurium
examples/tellurium-files/parameterscan/parameter_scan.py
Python
apache-2.0
1,273
0.015711
""" Parameter scan """ from __future__ import print_function, division import tellurium as te # -------------------------------------------------- # Parameter Scan 1 # -------------------------------------------------- cell = ''' J1: $Xo -> x; 0.1 + k1*x^4/(k2+x^4); x -> $w; k3*x; k1 = 0.9; k2 = 0.3; ...
rray() # -------------------------------------------------- # Parameter Scan 2 # -------------------------------------------------- cell = ''' $Xo -> S1; vo
; S1 -> S2; k1*S1 - k2*S2; S2 -> $X1; k3*S2; vo = 1 k1 = 2; k2 = 0; k3 = 3; ''' rr = te.loada(cell) p = te.ParameterScan(rr, startTime=0, endTime=6, numberOfPoints=50, startValue=1, endValue=5, colormap="cool", independent=["Time", "k1"], dependent="S1", xlabel=...
areitz/pants
src/python/pants/base/worker_pool.py
Python
apache-2.0
8,234
0.012023
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import multiprocessi...
nksize=1).get(timeout=1000000000) def _do_work(self, func, args_tuple, workunit_name, workunit_parent, on_failure=None): try: if workunit_name: with self._run_tracker.new_workunit_under_parent(name=workunit_name, parent=workunit_parent): return func(*args_tuple) else: return...
agate it to the main # thread. thread.interrupt_main() raise except Exception as e: if on_failure: # Note that here the work's workunit is closed. So, e.g., it's OK to use on_failure() # to close an ancestor workunit. on_failure(e) raise def shutdown(self): ...
bdelliott/pyfb
pyfb_django/session.py
Python
mit
1,100
0.010909
''' Wrapper around session access. Keep track of session madness as the app grows. ''' import logging logger = logging.getLogger("pyfb") FB_ACCESS_TOKEN = "fb_access_token" FB_EXPIRES = "fb_expires" FB_USER_ID = "fb_user_id" def get_fb_access_token(request, warn=True): token = request.session.get(FB_ACCESS_TOKE...
urn expires def get_fb_user_id(request, warn=True): user_id = request.session.get(FB_USER_ID) if not user_id and warn: logger.warn("pyfb: No user_id found in session") return user_id def set_fb_access_token(request, access_token): request.session[FB_ACCESS_TOKEN] = access_token def se...
ER_ID] = user_id
luotao1/Paddle
python/paddle/fluid/tests/unittests/test_fmax_op.py
Python
apache-2.0
7,540
0
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
self.input_a = np.array([0, np.nan, np.nan]).astype('int64') self.input_b = np.array([2, np.inf,
-np.inf]).astype('int64') self.input_c = np.array([4, 1, 3]).astype('int64') self.np_expected1 = np.fmax(self.input_x, self.input_y) self.np_expected2 = np.fmax(self.input_x, self.input_z) self.np_expected3 = np.fmax(self.input_a, self.input_c) self.np_expected4 = np.fmax(self....
gobuild/gobuild3
web/routers/doc.py
Python
mit
228
0.004386
from flask imp
ort Blueprint from flask import request, flash, redirect, url_for, render_template bp = Blueprint('doc', __name__) @bp.route('/') def doc(): flash('not finished yet') return render_template('index.htm
l')
abingham/kfg
setup.py
Python
mit
1,967
0
import io import os from setuptools import setup, find_packages def local_file(*name): return os.path.join( os.path.dirname(__file__), *name) def read(*names, **kwargs): with io.open( os.path.join(os.path.dirname(__file__), *names), encoding=kwargs.get("encoding", "utf8") ...
fest', 'wheel'], # 'doc': ['sphinx', 'cartouche'], 'test': ['hypothesis', 'pytest', 'tox'], }, entry_points={ # 'console_scripts': [ # 'k
fg = kfg.cli:main', # ], }, long_description=long_description, )
MonsterKiller/django-material
tests/examples/accounting/modules.py
Python
bsd-3-clause
97
0
from material.fron
tend import Module class Accounting(Modu
le): icon = "mdi-action-payment"
DreamSourceLab/DSView
libsigrokdecode4DSL/decoders/sda2506/pd.py
Python
gpl-3.0
5,750
0.003652
## ## This file is part of the libsigrokdecode project. ## ## Copyright (C) 2018 Max Weller ## Copyright (C) 2019 DreamSourceLab <support@dreamsourcelab.com> ## ## 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 Sof...
'] channels = ( {'id': 'clk', 'name': 'CLK', 'desc': 'Clock'}, {
'id': 'd', 'name': 'DATA', 'desc': 'Data'}, {'id': 'ce', 'name': 'CE#', 'desc': 'Chip-enable'}, ) annotations = ( ('cmdbit', 'Command bit'), ('databit', 'Data bit'), ('cmd', 'Command'), ('data', 'Data byte'), ('warnings', 'Human-readable warnings'), ) anno...
domibarton/CodeEval
number_of_ones.py
Python
gpl-3.0
1,060
0.000944
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright © 2016 Dominique Barton # # This file is part of Dominique Barton's CodeEval solutions. # # Dominique Barton's CodeEval solutions are 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 any later version. #
# Dominique Barton's CodeEval solutions are 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 GNU General # Public License for more details. # # You should have received a copy of the GNU Gener...