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 |
|---|---|---|---|---|---|---|---|---|
jonathansick/androcmd | scripts/dust_grid.py | Python | mit | 2,095 | 0 | #!/usr/bin/env python
# encoding: utf-8
"""
Make a grid of synths for a set of attenuations.
2015-04-30 - Created by Jonathan Sick
"""
import argparse
import numpy as np
from starfisher.pipeline import PipelineBase
from androcmd.planes import BasicPhatPlanes
from androcmd.phatpipeline import (
SolarZIsocs, Sola... | ")
parser.add_argument('brick', type=int)
parser.add_argument('--max-av', type=float, default=1.5)
parser.add_argument('--delta-av', type=float, default=0.1)
parser.add_argument('--fit', action='store_true', default=False)
parser.add_argument('--av', default=None)
return parser.parse_args()
de... | ine = Pipeline(root_dir="b{0:d}_{1:.2f}".format(brick, av),
young_av=av, old_av=av, av_sigma_ratio=0.25,
isoc_args=dict(isoc_kind='parsec_CAF09_v1.2S',
photsys_version='yang'))
print(pipeline)
print('av {0:.1f} done'.format(a... |
jendrikseipp/rednotebook | tests/test_filesystem.py | Python | gpl-2.0 | 420 | 0 | import os
from rednotebook.util.filesystem import get_journal_title
def test_journal_title():
root = os.path.abspath(os.sep)
dirs = [
("/home/my journal", "my journal"),
("/my journal/", "my journal"),
("/home/name/Journal", "Journal"),
("/home/name/jörnal", | "jörnal"),
(root, root),
]
for path, title in dirs | :
assert get_journal_title(path) == title
|
google/tangent | tests/test_compile.py | Python | apache-2.0 | 1,290 | 0.007752 | # Copyright 2017 Google 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 wri... | "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 inspect
import gast
import pytest
from tangent import compile as compile_
from tangent import quoting
... | ompile_.compile_function(quoting.parse_function(f))
assert f(2) == 4
assert inspect.getsource(f).split('\n')[0] == 'def f(x):'
def f(x):
return y * 2
f = compile_.compile_function(quoting.parse_function(f), {'y': 3})
assert f(2) == 6
def test_function_compile():
with pytest.raises(TypeError):
co... |
KDD-OpenSource/fexum | features/apps.py | Python | mit | 145 | 0 | from django.a | pps import AppConfig
class FeaturesConfig(AppConfig):
name = 'features'
def ready(self):
| import features.signals
|
priya-pp/Tacker | tacker/db/migration/alembic_migrations/versions/5246a6bd410f_multisite_vim.py | Python | apache-2.0 | 2,711 | 0.001475 | # Copyright 2016 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 ... | lumn('placement_attr', sa.PickleType(), nullable=True),
sa.Column('shared', sa.Boolean(), ser | ver_default=sa.text(u'true'),
nullable=False),
sa.PrimaryKeyConstraint('id'),
mysql_engine='InnoDB'
)
op.create_table('vimauths',
sa.Column('id', sa.String(length=36), nullable=False),
sa.Column('vim_id', sa.String(length=255), nullable=False),
sa.Column... |
kpj/PyWave | model.py | Python | mit | 5,052 | 0.001781 | """
Implementation of model
"""
import numpy as np
import numpy.random as npr
from scipy import ndimage
from configuration import get_config
config = get_config()
class LatticeState(object):
""" Treat 1D list as 2D lattice and handle coupled system
This helps wit | h simply passing this object to scipy's odeint
"""
def __init__(self, width, height, pacemakers=[]):
""" Initialize lattice
"""
self.width = width
self.height = height
self.pacemakers = pacemakers
self.discrete_laplacian = np.ones((3, 3)) * 1/2
| self.discrete_laplacian[1, 1] = -4
self.state_matrix = np.zeros((width, height))
self.tau_matrix = np.ones((width, height)) * (-config.t_arp) # in ARP
def _update_state_matrix(self, camp, exci):
""" Compute state matrix value, with
quiescent/refractory cell -> 0
... |
mwickert/scikit-dsp-comm | sk_dsp_comm/test/test_imports.py | Python | bsd-2-clause | 1,438 | 0.000695 | from unittest import TestCase
class TestImports(TestCase):
_multiprocess_can_split_ = True
def test_coeff2header_import(self):
import sk_dsp_comm.coeff2header
def test_coeff2header_from(self):
from sk_dsp_comm import coeff2header
def test_digitalcom_import(self):
import sk_d... | ort fir_design_helper
def test_fir_design_helper_from(self):
import sk_dsp_comm.fir_design_helper
def test_iir_design_helper_from(self):
from sk_dsp | _comm import iir_design_helper
def test_iir_design_helper_import(self):
import sk_dsp_comm.iir_design_helper
def test_multirate_helper_from(self):
from sk_dsp_comm import multirate_helper
def test_multirate_helper_import(self):
import sk_dsp_comm.multirate_helper
def test_sig... |
mlml/autovot | autovot/bin/auto_vot_append_files.py | Python | lgpl-3.0 | 4,617 | 0.003682 | #! /usr/bin/env python3
#
# Copyright (c) 2014 Joseph Keshet, Morgan Sonderegger, Thea Knowles
#
# This file is part of Autovot, a package for automatic extraction of
# voice onset time (VOT) from audio files.
#
# Autovot is free software: you can redistribute it and/or modify it
# under the terms of the GNU Lesser Gen... | Y WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy o | f the GNU Lesser General Public
# License along with Autovot. If not, see
# <http://www.gnu.org/licenses/>.
#
# auto_vot_append_files.py : Append set of features and labels
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_im... |
otron/zenodo | zenodo/demosite/receivers.py | Python | gpl-3.0 | 2,660 | 0.005639 | # -*- coding: utf-8 -*-
#
## This file is part of Zenodo.
## Copyright (C) 2012, 2013, 2014 CERN.
##
## Zenodo 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 Lice | nse, or
## (at your option) any later version.
##
## Zenodo is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received... | ith Zenodo. If not, see <http://www.gnu.org/licenses/>.
##
## In applying this licence, CERN does not waive the privileges and immunities
## granted to it by virtue of its status as an Intergovernmental Organization
## or submit itself to any jurisdiction.
import os
import shutil
from flask import current_app
from inv... |
jterrace/sphinxtr | extensions/natbib/latex_codec.py | Python | bsd-2-clause | 15,250 | 0.003607 | """latex.py
Character translation utilities for LaTeX-formatted text.
Usage:
- unicode(string,'latex')
- ustring.decode('latex')
are both available just by letting "import latex" find this file.
- unicode(string,'latex+latin1')
- ustring.decode('latex+latin1')
where latin1 can be replaced by any other known encod... | _(self):
"""Turn self into an iterator. It already is one, nothing to do."""
return self
def __init__(self,tex):
"""Create a new token converter from a string."""
self.tex = tuple(_tokenize(tex)) # turn tokens into indexable list
self.pos = 0 # index of ... | ken
self.lastoutput = 'x' # lastoutput must always be nonempty string
def __getitem__(self,n):
"""Return token at offset n from current pos."""
p = self.pos + n
t = self.tex
return p < len(t) and t[p] or None
def next(self):
"""Find and return another ... |
YakindanEgitim/EN-LinuxClipper | thrift/transport/TZlibTransport.py | Python | gpl-3.0 | 8,187 | 0.006596 | #
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | or non-threaded scenarios only, since the cache only holds one object)
The purpose of this caching is to allocate only one TZlibTransport where
only one is really needed (since it must have separate read/write buffers),
and makes the statistics from getCompSavings() and getCompRatio()
easier to understand.
... | oped cache of last transport given and zlibtransport returned
_last_trans = None
_last_z = None
def getTransport(self, trans, compresslevel=9):
'''Wrap a transport , trans, with the TZlibTransport
compressed transport class, returning a new
transport to the caller.
@param compresslevel: The ... |
DrOctogon/appscake-rewrite | config/wsgi.py | Python | bsd-3-clause | 1,421 | 0.000704 | """
WSGI config for appscake project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION``... | eady in the environment. This breaks
# if running multiple sites in the same mod_wsgi process. To fix this, use
# mod_wsgi dae | mon mode with each site in its own daemon process, or use
# os.environ["DJANGO_SETTINGS_MODULE"] = "config.settings"
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings")
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the W... |
SergeyCherepanov/ansible | ansible/paramiko/_version.py | Python | mit | 80 | 0 | __v | ersion_info__ = (2, 4, 2)
__version__ = ".".join(map(str, __version | _info__))
|
Rassilion/ProjectC | web/problems/003/solver.py | Python | gpl-3.0 | 527 | 0 | for i in range(1, 101):
print i
asd = open("inp/" + str(i), "r")
s = asd.read()
s | = s[:-1]
n = int(s)
print n
if n % 100 != 0:
if n % 4 == 0:
s = "EVET" + "\n"
else:
s = "HAYIR" + "\n"
else:
if n % 400 == 0:
s = "EVET" + "\n"
print "400e bolunme!!! | "
else:
s = "HAYIR" + "\n"
print "100 e bolnmede hayir"
asd.close()
asd = open("out/" + str(i), "w")
asd.write(s)
asd.close()
|
cydenix/OpenGLCffi | OpenGLCffi/GLES3/EXT/NV/viewport_array.py | Python | mit | 1,222 | 0.011457 | from OpenGLCffi.GLES3 import params
@params(api='gles3', prms=['first', 'count', 'v'])
def glViewportArrayvNV(first, count, v):
pass
@params(api='gles3', prms=['index', 'x', 'y', 'w', 'h'])
def glViewportIndexedfNV(index, x, y, w, h):
pass
@params(api='gles3', prms=['index', 'v'])
def glViewportIndexedfvNV(index,... | (index, left, bottom, width, height):
pass
@params(api='gles3', prms=['index', 'v'])
def glScissorIndexedvNV(index, v):
pass
@params(api='gles3', prms=['first', 'count', 'v'])
def glDept | hRangeArrayfvNV(first, count, v):
pass
@params(api='gles3', prms=['index', 'n', 'f'])
def glDepthRangeIndexedfNV(index, n, f):
pass
@params(api='gles3', prms=['target', 'index', 'data'])
def glGetFloati_vNV(target, index):
pass
@params(api='gles3', prms=['target', 'index'])
def glEnableiNV(target, index):
pas... |
makennajohnstone/CSS | css/forms.py | Python | mit | 11,524 | 0.010413 | from django import forms
from django.core.mail import send_mail
from css.models import CUser, Room, Course, SectionType, Schedule, Section, Availability, FacultyCoursePreferences
from django.http import HttpResponseRedirect
from settings import DEPARTMENT_SETTINGS, HOSTNAME
import re
from django.forms import ModelChoic... | Confirm Password', widget=forms.PasswordInput)
def __init__(self, *args, **kwargs):
if kwargs.pop('request') is "GET":
self.first_name = kwargs.pop('first_name')
self.last_name = kwargs.pop('last_name')
| self.user_type = kwargs.pop('user_type')
self.email = kwargs.pop('email')
self.declared_fields['first_name'].initial = self.first_name
self.declared_fields['last_name'].initial = self.last_name
self.declared_fields['email'].initial = self.email
self.declared... |
Aravinthu/odoo | addons/l10n_ch/tests/test_l10n_ch_isr.py | Python | agpl-3.0 | 5,070 | 0.006509 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import time
from odoo.addons.account.tests.account_test_classes import AccountingTestCase
from odoo.exceptions import ValidationError
class ISRTest(AccountingTestCase):
def create_invoice(self, currency_to_use='b... | N must be valid")
self.assertEqual(account_test_iban_ok.l10n_ch_postal, '000250097798', "A valid swiss IBAN should set the postal reference")
#A non-swiss IBAN must not allow the computation of a postal reference
account_test_iban_wrong = self.create_account('GR160110 | 1250000000012300695')
self.assertEqual(account_test_iban_wrong.acc_type, 'iban', "The IBAN must be valid")
self.assertFalse(account_test_iban_wrong.l10n_ch_postal, "A valid swiss IBAN should set the postal reference")
def test_isr(self):
#Let us test the generation of an ISR for an invoice,... |
sih4sing5hong5/hue7jip8 | 匯入/management/commands/族語辭典1轉檔.py | Python | mit | 1,474 | 0 | from os import makedirs
from os.path import join
from posix import listdir
from django.conf import settings
from django.core.management.base import BaseCommand
from libavwrapper.avconv import Input, Output, AVConv
from libavwrapper.codec import AudioCodec, NO_VIDEO
from 匯入.族語辭典 import 代碼對應
class Command(BaseComma... |
type=str,
help='選擇的族語'
)
def handle(self, *args, **參數):
# 檢查avconv有裝無
代碼 = 代碼對應[參數['語言']]
語料目錄 = join(settings.BASE_DIR, '語料', '族語辭典', 代碼)
目標目錄 = join(settings.BASE_DIR, '語料', '族語辭典wav', 代碼)
makedirs(目標目錄, exist_ok=True)
for 檔名 in sor... | 檔名)
目標 = join(目標目錄, 檔名[:-4] + '.wav')
目標聲音格式 = AudioCodec('pcm_s16le')
目標聲音格式.channels(1)
目標聲音格式.frequence(16000)
原始檔案 = Input(來源)
網頁檔案 = Output(目標).overwrite()
指令 = AVConv('avconv', 原始檔案, 目標聲音格式, NO_VIDEO, ... |
batermj/algorithm-challenger | code-analysis/programming_anguage/python/source_codes/Python3.8.0/Python-3.8.0/Lib/distutils/tests/test_check.py | Python | apache-2.0 | 5,711 | 0.000525 | """Tests for distutils.command.check."""
import os
import textwrap
import unittest
from test.support import run_unittest
from distutils.command.check import check, HAS_DOCUTILS
from distutils.tests import support
from distutils.errors import DistutilsSetupError
try:
import pygments
except ImportError:
pygment... | gSilencer,
support.TempdirManager,
unittest.TestCase):
def _run(self, metadata=None, cwd=None, **options):
if metadata is None:
metadata = {}
if cwd is not None:
old_dir = os.getcwd()
os.chdir(cwd)
pkg_info, dist = ... | eck(dist)
cmd.initialize_options()
for name, value in options.items():
setattr(cmd, name, value)
cmd.ensure_finalized()
cmd.run()
if cwd is not None:
os.chdir(old_dir)
return cmd
def test_check_metadata(self):
# let's run the command w... |
utarsuno/quasar_source | deprecated/code_api/code_section.py | Python | mit | 979 | 0.022472 | # coding=utf-8
"""This module, code_section.py, is an abstraction for code sections. Needed for ordering code chunks."""
class CodeSection(object):
"""Represents a single code section of a source code file."""
def __init__(self, section_name):
self._section_name = section_name
self._code_chunks = []
def add... | ode section."""
self._code_chunks.insert(0, code_chunk)
def add_code_chunk(self, code_chunk):
"""Adds a code chunk to this code section."""
self._code_chunks.append(code_chunk)
def get_all_code_chunks(self):
"""Returns a list of all the code chunks in this code section."""
return self._code_chunks
@prop... | y
def empty(self) -> bool:
"""Returns a boolean indicating if this code section is empty or not."""
return len(self._code_chunks) == 0
@property
def name(self) -> str:
"""Returns the name of this code section."""
return self._section_name
|
pbarton666/buzz_bot | djangoproj/djangoapp/csc/corpus/migrations/0001_initial.py | Python | mit | 8,362 | 0.008012 |
from south.db import db
from django.db import models
from csc.corpus.models import *
class Migration:
def forwards(self, orm):
# Adding model 'TaggedSentence'
db.create_table('tagged_sentences', (
('text', orm['corpus.TaggedSentence:text']),
('language', orm['... | odels.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'blank': 'True'}),
'is_staff': ('django.db.model | s.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('d... |
rwatson/chromium-capsicum | o3d/tests/selenium/selenium_utilities.py | Python | bsd-3-clause | 11,831 | 0.007776 | #!/usr/bin/python2.4
# Copyright 2009, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of... | iumNeedResize") == "true")
if need_client_resize:
session.wait_for_condition(
"window.%s.width == 800 && window.%s.height == 600" % (client, client),
2000 | 0)
else:
session.run_script("window.resizeTo(%d, %d)" %
(selenium_constants.RESIZE_WIDTH,
selenium_constants.RESIZE_HEIGHT))
# Execute screenshot capture code
# Replace all backslashes with forward slashes so it is parsed correctly
# by Javascript
full_path... |
AndroidOpenDevelopment/android_external_chromium_org | tools/android/adb_profile_chrome.py | Python | bsd-3-clause | 288 | 0.003472 | #!/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.
import sys
from adb_pro | file_chrome import main
if __name__ == '__ | main__':
sys.exit(main.main())
|
kasemir/org.csstudio.display.builder | org.csstudio.display.builder.model/examples/python/jython.py | Python | epl-1.0 | 377 | 0.005305 | # Script executed by jython
# Can import any Java package
from org.csstudio.display.builder.runtime.script impor | t PVUtil
# Can also import some python code that's available under Jython
import sys, time
trigger = PVUtil.getInt(pvs | [0])
if trigger:
info = "%s,\ninvoked at %s" % (sys.version, time.strftime("%Y-%m-%d %H:%M:%S"))
widget.setPropertyValue("text", info)
|
CDSherrill/psi4 | tests/pytests/test_misc.py | Python | lgpl-3.0 | 3,413 | 0.004102 | import pytest
from .addons import using_networkx
from .utils | import *
import math
import numpy as np
import qcelemental as qcel
import psi4
from psi4. | driver import qcdb
pytestmark = pytest.mark.quick
def hide_test_xtpl_fn_fn_error():
psi4.geometry('He')
with pytest.raises(psi4.UpgradeHelper) as e:
psi4.energy('cbs', scf_basis='cc-pvdz', scf_scheme=psi4.driver_cbs.xtpl_highest_1)
assert 'Replace extrapolation function with function name' in s... |
tndatacommons/tndata_backend | tndata_backend/goals/utils.py | Python | mit | 3,686 | 0 | import csv
import re
from io import TextIOWrapper
from django.conf import settings
from django.core.cache import cache
from django.utils.termcolors import colorize
# Import clog if we're in debug otherwise make it a noop
if settings.DEBUG:
from clog.clog import clog
else:
def clog(*args, **kwargs):
pa... |
"""
file = TextIOWrapper(
uploaded_file.file,
encoding=encoding,
newline='',
errors=errors
)
for row in csv.reader(file):
if any(row):
yield row
def delete_content(prefix):
"""Delete content whose title/name starts with the given prefix."""
... | ns = Action.objects.filter(title__startswith=prefix)
print("Deleting {} Actions...".format(actions.count()))
actions.delete()
triggers = Trigger.objects.filter(name__startswith=prefix)
print("Deleting {} Triggers...".format(triggers.count()))
triggers.delete()
goals = Goal.objects.filter(title... |
derekmd/opentag-presenter | tags/zschemaname.py | Python | bsd-2-clause | 2,160 | 0.056019 | from font import font
class zschemaname( font ):
"""
Displays a header name for a Z Schema. It may contain text, images,
equations, etc... but the width of it should be kept to a minimum so
it isn't wider than the containing Z Schema | box. See
<a href="zschema.html"><zschema></a> for proper usage.
"""
def __init__( self, *args ):
"""
Initiate the container, contents, and properties.
-*args, arguments for the for constructor.
"""
apply( font.__init__, (self,) + args )
self.setColorDefined( self.hasProperty("color") )
def re... | urns x, y coordinates where the rendering left off.
"""
#
# Don't draw anything it this isn't a direct child of a
# <zschema> tag in the XML document.
#
from zschema import zschema
if not isinstance(self.getContainer(), zschema):
return x, y
if not self.colorDefined():
borderQColor = self.getCon... |
pebble/spacel-provision | src/test/provision/app/alarm/endpoint/__init__.py | Python | mit | 688 | 0 | import unittest
RESOURCE_NAME = 'Test_Resource'
class BaseEndpointTest(unittest.TestCase):
def setUp(self | ):
self.endpoint = None
self.resources = {}
self.template = {
'Resources': self.resources
}
def test_reso | urce_name(self):
if self.endpoint:
resource_name = self.endpoint.resource_name(RESOURCE_NAME)
self.assertEquals(self.topic_resource(), resource_name)
def subscriptions(self):
resource_name = self.topic_resource()
return self.resources[resource_name]['Properties']['Su... |
NaN-tic/nereid | nereid/config.py | Python | gpl-3.0 | 1,087 | 0.00184 | #This file is part of Tryton & Nereid. The COPYRIGHT file at the top level of
#this repository contains the full copyright notices and license terms.
import imp
from flask.config import ConfigAttribute, Config as ConfigBase # noqa
class Config(ConfigBase):
"Configuration without the root_path"
def __init__... | behaves as if the file was imported as module with the
:meth:`from_object` function.
:param filename: the filename of the config. This can either be an
absolute filename or a filename relative to the
root path.
"""
d = imp.new_mod... | d.__file__ = filename
try:
execfile(filename, d.__dict__)
except IOError, e:
e.strerror = 'Unable to load configuration file (%s)' % e.strerror
raise
self.from_object(d)
|
scienceopen/histutils | XMLparamPrint.py | Python | mit | 340 | 0 | #!/u | sr/bin/env python
"""
demos reading HiST camera parameters from XML file
"""
from histutils.hstxmlparse import xmlparam
from argparse import ArgumentParser
if __name__ == "__main__":
p = ArgumentParser()
p.add_argument("fn", help="xml filename to parse")
p = p.parse_args()
params = xmlparam(p.fn)
| print(params)
|
wunderlist/hamustro | utils/send_single_message.py | Python | mit | 1,002 | 0.00499 | from __future__ import print_function |
import os
import time
import json
import datetime
import argparse
import requests
from message import Message
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('-f','--format', default="protobuf", choices=["protobuf","json"], help="message format")
parser | .add_argument('CONFIG', type=argparse.FileType('r'), help="configuration file")
parser.add_argument('URL', help="tavis url")
args = parser.parse_args()
config = json.load(args.CONFIG)
shared_secret = config.get('shared_secret', 'ultrasafesecret')
msg = Message(random_payload=False)
msg.time = ... |
nkgilley/home-assistant | homeassistant/components/geofency/__init__.py | Python | apache-2.0 | 4,573 | 0.000219 | """Support for Geofency."""
import logging
from aiohttp import web
import voluptuous as vol
from homeassistant.components.device_tracker import DOMAIN as DEVICE_TRACKER
from homeassistant.const import (
ATTR_LATITUDE,
ATTR_LONGITUDE,
ATTR_NAME,
CONF_WEBHOOK_ID,
HTTP_OK,
HTTP_UNPROCESSABLE_ENTI... | ONGITUDE]
return _set_location(hass, data, location_name)
def _is_mobile_beacon(data, mobile_beacons):
"""Check if we have a mobile beacon."""
return ATTR_BEACON_ID in data and data["name"] in mobile_beacons
|
def _device_name(data):
"""Return name of device tracker."""
if ATTR_BEACON_ID in data:
return f"{BEACON_DEV_PREFIX}_{data['name']}"
return data["device"]
def _set_location(hass, data, location_name):
"""Fire HA event to set location."""
device = _device_name(data)
async_dispatcher_... |
macobo/documentation | code_snippets/results/result.api-comment-edit.py | Python | bsd-3-clause | 224 | 0.017857 | {'comment': {'handle': 'matt@example.com' | ,
'id': 2603645287324504065,
'message': 'I think differently now.',
'resource': '/api/v1/comments/2603645287324504065',
'url': '/event/jump_to?event_id=2603645287324504065 | '}}
|
adrianpaesani/odoo-argentina | l10n_ar_invoice/models/afip.py | Python | agpl-3.0 | 6,822 | 0.000293 | # -*- coding: utf-8 -*-
##############################################################################
# For copyright and license notices, see __openerp__.py file in module root
# directory
##############################################################################
from openerp import fields, models, api, _
from op... | et_journal_document_class_ids',
string='Documents Classes',
)
@api.one
@api.depends('type', | 'sufix', 'prefix', 'number')
def get_name(self):
# TODO mejorar esto y que tome el lable traducido del selection
if self.type == 'manual':
name = 'Manual'
elif self.type == 'preprinted':
name = 'Preimpresa'
elif self.type == 'online':
name = 'Onlin... |
apache/incubator-airflow | tests/providers/google/cloud/transfers/test_oracle_to_gcs.py | Python | apache-2.0 | 6,070 | 0.002471 | #
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... | e = iter(ROWS)
oracle_hook_mock.get_conn().cursor().description = CURSOR_DESCRIPTION
gcs_hook_mock = gcs_hook_mock_class.return_value
expected_upload = {
JSON_FILENAME.format(0): b''.join(NDJSON_LINES[:2]),
JSON_FILENAME.format(1): N | DJSON_LINES[2],
}
def _assert_upload(bucket, obj, tmp_filename, mime_type=None, gzip=False):
assert BUCKET == bucket
assert 'application/json' == mime_type
assert GZIP == gzip
with open(tmp_filename, 'rb') as file:
assert expected_upload[o... |
benjaoming/simple-pypi-statistics | simple_pypi_statistics/api.py | Python | gpl-2.0 | 6,238 | 0.000321 | from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
"""
Get package download statistics from PyPI
"""
# Based on https://github.com/collective/Products.PloneSoftwareCenter\
# /commit/601558870175e35cfa4d05fb309859e580271a1f
# For sorting XML-RPC result... | data")
honeypot = honeypot['releases']
# Add a field used to store diff | when choosing the best honey pot release
# for some statistic
for x in honeypot:
x['diff'] = 0
stats, __, version = get_stats(package)
if not stats:
return
# Denote release date diff and choose the honey pot release that's closest
# to the one of each release
releases = s... |
kgiusti/pyngus | examples/perf-tool.py | Python | apache-2.0 | 6,874 | 0 | #!/usr/bin/env python
#
# 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
# "... | eiver_link | , error):
"""Protocol error occurred."""
LOG.warn("receiver_failed error=%s", error)
receiver_link.close()
def message_received(self, receiver, message, handle):
now = time.time()
receiver.message_accepted(handle)
self.tx_total_latency += now - message.body['tx-times... |
openUniverse/singularity | BensPractice/Practise2.py | Python | mit | 2,825 | 0.013805 | # # 1. Define a function max() that takes two numbers as arguments and returns the largest of them.
# # Use the if-then-else construct available in Python.
# # (It is true that Python has the max() function built in, but writing it yourself is nevertheless a good exercise.)
#
# def max (a, b):
# if a>b:
# r... | mple, sum([1, 2, 3, 4]) sho | uld return 10, and multiply([1, 2, 3, 4]) should return 24.
#
# # n+=x means store n + x in n (means n = n + x)
# # n*=x means store n * x in n
# # = is not equals to it is store in
#
# NumList=[1, 2, 3, 4]
#
# def sum (list):
# n=0
# for element in list:
# n+= element
# return n
# print (sum(NumLis... |
jittat/ku-eng-direct-admission | scripts/filter_quota.py | Python | agpl-3.0 | 1,880 | 0.007447 | import codecs
input_filename = '/home/jittat/mydoc/directadm53/payment/assignment.csv'
quota_filename = '/home/jittat/mydoc/directadm53/payment/quota.txt'
output_filename = '/home/jittat/mydoc/directadm53/payment/assignment-added.csv'
def read_quota():
q_data = {
'nat_id': {},
'firstname': {},
... | uota_filename, encoding='utf-8', mode='r').readlines():
items = l.strip().split('\t')
l = l.strip()
if len(items)!=4:
continue
q_data['nat_id'][items[0]] = l
if items[2] in q_data['firstname']:
q_data['firstname'][items[2]].append(l)
else:
... |
if items[3] in q_data['lastname']:
q_data['lastname'][items[3]].append(l)
else:
q_data['lastname'][items[3]] = [l]
return q_data
def main():
q_data = read_quota()
lines = codecs.open(input_filename, encoding='utf-8', mode='r').readlines()
outfile = codecs.ope... |
yoriyuki/nksnd | nksnd/evaluate.py | Python | mit | 2,104 | 0.003802 | from __future__ import print_function
import sys
import argparse
import numpy as np
def max3(x, y, z):
return max(max(x, y), z)
def lcs(s1, s2):
m = len(s1)
n = len(s2)
t = np.zeros((n + 2, m + 2), dtype=int)
for j in range(1, n + 1):
for i in range(1, m + 1):
is_same = 0
... | inals',help='original texts')
parser.add_argument('converted_texts',help='converted texts')
parser.add_argument('--verbose', '-v', type=bool, help='verbose output')
args = parser.parse_args()
lcs_sum = 0
conv_sum = 0
orig_sum = 0
sentences = 0
correct_sentences = 0
with open(args.o... | for orig, conv in zip(origs, convs):
orig.strip(' \n')
conv.strip(' \n')
sentences += 1
if orig == conv:
correct_sentences += 1
lcs_len = lcs(orig, conv)
if args.verbose:
print(u'\"{... |
wayetender/whip | whip/src/adapter/util/serialization.py | Python | gpl-2.0 | 1,453 | 0.007571 | from thrift.protocol import TBin | aryProtocol
from thrift.transport import TTransport
import pickle
import bz2
def SerializeThriftMsg(msg, protocol_type=TBinaryProtocol.TBinaryProtocol):
"""Serialize a thrift m | essage using the given protocol.
The default protocol is binary.
Args:
msg: the Thrift object to serialize.
protocol_type: the Thrift protocol class to use.
Returns:
A string of the serialized object.
"""
msg.validate()
transportOut = TTransport.TMemoryBuff... |
quantsini/pyswf | py_swf/clients/decision.py | Python | mit | 9,074 | 0.002976 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import unicode_literals
from collections import namedtuple
from botocore.vendored.requests.exceptions import ReadTimeout
from py_swf.errors import NoTaskFound
__all__ = ['DecisionClient', 'DecisionTask']
DecisionTask = namedtuple('Dec... | .get_workflow_execution_history(
**kwargs
)
next_page_token = r | esults.get('nextPageToken', None)
events = results['events']
for event in events:
if not use_raw_event_history:
event = nametuplefy(event)
yield event
if next_page_token is None:
break
kwargs['nextPage... |
Eloff/silvershell | client/silvershell/white_on_black_prefs.py | Python | bsd-3-clause | 6,018 | 0.003157 | # You can edit these settings and save them, they
# will be applied immediately and remembered for next time.
# This will reset the interpreter.
# ******************************************************************************* #
# If changing these settings makes the interpreter unrecoverable, you #
# can... | </LinearGradientBrush>
</Border.BorderBrush>
<ListBox x:Name="MemberListBox" MaxHeight="240" />
</Border>
''')
CursorAnimation = utils.load_xaml('''
<ColorAnimationUsingKeyFrames
xmlns="%(client_ns)s"
BeginTime="0"
Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)"
>
<Di... | arent" KeyTime="0:0:0" />
<LinearColorKeyFrame Value="White" KeyTime="0:0:0.35" />
<DiscreteColorKeyFrame Value="White" KeyTime="0:0:0.6" />
</ColorAnimationUsingKeyFrames>
''')
|
vmindru/ansible | lib/ansible/plugins/callback/mail.py | Python | gpl-3.0 | 8,479 | 0.002831 | # -*- coding: utf-8 -*-
# Copyright: (c) 2012, Dag Wieers <dag@wieers.com>
# 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 = '''
callback: mail
type: notification
short_d... | _mail
key: bcc
version_added: '2.5'
note:
- "TODO: expand configuration options now that plugins can leverage Ansible's configuration"
'''
import json
import os
import re
import smtplib
from ansible.module_utils.six import string_types
from ansible.module_utils._text import to_bytes
from ansible.p... | Base
class CallbackModule(CallbackBase):
''' This Ansible callback plugin mails errors to interested parties. '''
CALLBACK_VERSION = 2.0
CALLBACK_TYPE = 'notification'
CALLBACK_NAME = 'mail'
CALLBACK_NEEDS_WHITELIST = True
def __init__(self, display=None):
super(CallbackModule, self).... |
mindriot101/k2catalogue | k2catalogue/k2logging.py | Python | mit | 350 | 0.002857 | import logging
logging.basicConfig(
level=logging.INFO, format='%(asctime)s|%(name)s|%(le | velname)s|%(message)s')
logging.getLogger('vcr.stubs').setLevel(logging.WARNING)
logging.getL | ogger('requests.packages.urllib3.connectionpool')\
.setLevel(logging.WARNING)
def get_logger(*args, **kwargs):
return logging.getLogger(*args, **kwargs)
|
tnadeau/pybvc | samples/sampleopenflow/demos/demo42.py | Python | bsd-3-clause | 8,783 | 0.00353 | #!/usr/bin/python
# Copyright (c) 2015, BROCADE COMMUNICATIONS SYSTEMS, INC
# 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 n... | following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# 3. Neither the name of the copyright hold | er nor the names of its
# contributors may be used to endorse or promote products derived from this
# software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED W... |
herow/planning_qgis | tests/src/python/test_qgscomposerlabel.py | Python | gpl-2.0 | 4,750 | 0.017053 | # -*- coding: utf-8 -*-
'''
test_qgscomposerlabel.py
--------------------------------------
Date : Oct 2012
Copyright : (C) 2012 by Dr. Hugo Mercier
email : hugo dot mercier at oslandia dot com
*****************... | mLabel = QgsComposerLabel( mComposition )
mComposition.addComposerLabel( mLabel )
self.evaluation_test( mComposition, mLabel )
self.feature_evaluation_test( mComposition, mLabel, mVectorLayer )
self.page_evaluation_test( mComposition, mLabel, mVectorLayer )
def evaluation_te... | Composition, mLabel ):
# $CURRENT_DATE evaluation
mLabel.setText( "__$CURRENT_DATE__" )
assert mLabel.displayText() == ( "__" + QDate.currentDate().toString() + "__" )
# $CURRENT_DATE() evaluation
mLabel.setText( "__$CURRENT_DATE(dd)(ok)__" )
expected = "__" + QDateTime.... |
mlskit/astromlskit | REGRESSION/lassofront.py | Python | gpl-3.0 | 3,925 | 0.000764 | # -*- coding: utf-8 -*-
# Form implem | entation generated from reading ui file 'lassoui.ui'
#
# Created: Sat Apr 11 09:14:27 2015
# by: PyQt4 UI code generato | r 4.10.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return ... |
yrunts/python-for-qa | 4-http-json-xml-html/examples/html_parse.py | Python | cc0-1.0 | 358 | 0.002793 |
from lxml import html
def main():
dom = ht | ml.parse(('http://www.amazon.com/Apple-MH0W2LL-10-Inch-Retina-'
'Display/dp/B00OTWOAAQ/ref=sr_1_1?s=pc&ie=UTF8&'
'qid=1459799371&sr=1-1&ke | ywords=ipad'))
title = dom.find('//*[@id="productTitle"]')
print(title.text)
if __name__ == '__main__':
main()
|
dmnfarrell/peat | pKaTool/titration_class.py | Python | mit | 5,464 | 0.010615 | #!/usr/bin/env python
#
# pKaTool - analysis of systems of titratable groups
# Copyright (C) 2010 Jens Erik Nielsen
#
# 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 Lice... | ka))-1-exp)
for group in self.curves.keys():
if pKas.has_key(group):
pka = pKas[group]
HH_dev | iation[group] = {}
for ph in self.curves[group].keys():
try:
HH_deviation[group][ph] = deviation(float(ph),float(pka),float(self.curves[group][ph]))
except:
pass
return HH_deviation
|
dagwieers/dstat | plugins/dstat_vmk_nic.py | Python | gpl-2.0 | 2,648 | 0.009819 | ### Author: Bert de Bruijn <bert+dstat$debruijn,be>
### VMware ESX kernel vmknic stats
### Displays VMkernel port statistics on VMware ESX servers
# NOTE TO USERS: command-line plugin configuration is not yet possible, so I've
# "borrowed" the -N argument.
# EXAMPLES:
# # dstat --vmknic -N vmk1
# You can even combine... | et2['total'] = [0, 0]
for line | in self.fd[0].readlines():
l = line.replace(' /','/').split()
if len(l) != 12: continue
if l[2][:5] == '<Link': continue
if ','.join(l) == 'Name,Mtu/TSO,Network,Address,Ipkts,Ierrs,Ibytes,Opkts,Oerrs,Obytes,Coll,Time': continue
if l[0] == 'Usage:': continue
... |
oldm/OldMan | oldman/validation/__init__.py | Python | bsd-3-clause | 21 | 0 | __author__ = | 'benji'
| |
terzeron/FeedMakerApplications | funbe/capture_item_funbe.py | Python | gpl-2.0 | 1,590 | 0.000629 | #!/usr/bin/env python
import sys
import re
import getopt
from typing import List, Tuple
from feed_maker_util import IO
def main() -> int:
link: str = ""
title: str = ""
url_prefix = ""
state = 0
num_of_recent_feeds = 1000
optlist, _ = getopt.getopt(sys.argv[1:], "f:n:")
for o, a in optl... | int(a)
line_list = IO.read_stdin_as_line_list()
result_list: List[Tuple[str, str]] = []
for line in | line_list:
if state == 0:
m = re.search(r'var\s+g5_url\s+=\s+"(?P<url_prefix>[^"]+)";', line)
if m:
url_prefix = m.group("url_prefix")
state = 1
elif state == 1:
m = re.search(r'<td[^>]*name="view_list"[^>]*data-role="(?P<link>[^"]+)">... |
shawnadelic/shuup | shuup_tests/xtheme/test_edit.py | Python | agpl-3.0 | 681 | 0 | # -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2016, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
from shuup.xtheme.editing import could_edit, is_edit_mode, set_edit_mode
fro... | request)
set_edit_mode(request, True)
assert is_edit_mode(request)
set_edit_mode(request, False)
assert not is_edit | _mode(request)
|
johnwallace123/dx-toolkit | src/python/dxpy/cli/workflow.py | Python | apache-2.0 | 11,696 | 0.00436 | # Copyright (C) 2013-2016 DNAnexus, Inc.
#
# This file is part of dx-toolkit (DNAnexus platform client libraries).
#
# 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.a... | om __future__ import print_function, unicode_literals, division, absolute_import
import dxpy
import dxpy.utils.printing as printing
from .parsers import (process_data | object_args, process_single_dataobject_output_args,
process_instance_type_arg)
from ..utils.describe import io_val_to_str
from ..utils.resolver import (resolve_existing_path, resolve_path, is_analysis_id)
from ..exceptions import (err_exit, DXCLIError, InvalidState)
from . import (try_call, try_ca... |
cavaunpeu/vanilla-neural-nets | vanilla_neural_nets/recurrent_neural_network/loss_function.py | Python | mit | 606 | 0.008251 | import itertools
import numpy as np
from vanilla | _neural_nets.base.loss_function import BaseLossFunction
class CrossEntropyLoss(BaseLossFunction):
| @classmethod
def loss(cls, y_true, y_predicted):
return cls.total_loss(y_true=y_true, y_predicted=y_predicted) / len(y_true)
@classmethod
def total_loss(cls, y_true, y_predicted):
row_indices = np.arange( len(y_true) )
column_indices = y_true
return np.sum([ -np.log(y_predi... |
domob1812/bitcoin | test/functional/mempool_packages.py | Python | mit | 16,008 | 0.003686 | #!/usr/bin/env python3
# Copyright (c) 2014-2020 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test descendant package tracking code."""
from decimal import Decimal
from test_framework.blocktools ... | sert_equal(ainfo['s | pentby'], [chain[chain.index(ancestor)+1]])
if ainfo['ancestorcount'] > 1:
assert_equal(ainfo['depends'], [chain[chain.index(ancestor)-1]])
else:
assert_equal(ainfo['depends'], [])
# Check that getmempoolancestors/getmempooldescendants co... |
amanzi/ats-dev | tools/utils/plot_wrm.py | Python | bsd-3-clause | 6,867 | 0.011213 | from matplotlib import pyplot as plt
import numpy as np
class Spline(object):
"""Forms a cublic spline on an interval given values and derivatives at the endpoints of that interval."""
def __init__(self, x1, y1, dy1, x2, y2, dy2):
self.x1 = x1
self.x2 = x2
self.y1 = y1
self.y2 ... | ert(3 <= len(s) <= 5)
alpha, n, sr = map(float, s[0:3])
if len(s) > 3:
label = s[3]
else:
label = None
if len(s) > 4:
smooth_int_sat = float(s[4])
else:
smooth_int_sat = 0.
... | print(f" alpha = {alpha}")
print(f" n = {n}")
print(f" sr = {sr}")
print(f" smoothing_interval_sat = {smooth_int_sat}")
print(f" label = {label}")
except:
raise argparse.ArgumentTypeError("WRM must be van Genucten parameters ... |
siosio/intellij-community | python/testData/intentions/PyInvertIfConditionIntentionTest/commentsPylintNoElseBoth.py | Python | apache-2.0 | 183 | 0.005464 | def fu | nc():
value = "not-none"
# pylint: disable=unused-argument1
<caret>if value is None:
print("None")
# py | lint: disable=unused-argument2
print(value)
|
takeshineshiro/nova | nova/tests/unit/objects/test_objects.py | Python | apache-2.0 | 68,588 | 0.000029 | # Copyright 2013 IBM Corp.
#
# 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... | nova import context
from nova import exception
from nova import objects
from nova.objects import base
from nova.objects import fields
from nova import test
from nova.tests import fixtures as nova_fixtures
from nova.tests.unit import fake_notifier
from nova import utils
LOG = log.getLog | ger(__name__)
class MyOwnedObject(base.NovaPersistentObject, base.NovaObject):
VERSION = '1.0'
fields = {'baz': fields.IntegerField()}
class MyObj(base.NovaPersistentObject, base.NovaObject,
base.NovaObjectDictCompat):
VERSION = '1.6'
fields = {'foo': fields.IntegerField(default=1),
... |
h-2/seqan | misc/trac_plugins/DocLinks/doc_links/macro.py | Python | bsd-3-clause | 7,207 | 0.002498 | """Seqan Doc Links for Trac.
Version 0.1.
Copyright (C) 2010 Manuel Holtgrewe
Install by copying this file into the plugins directory of your trac
work directory. In your trac.ini, you can use something like this
(the following also shows the defaults).
[seqan_doc_links]
prefix = seqan
base_url = http://www.... | t_link_resolvers(self):
"""Method from IWikiSyntaxProvider.
Returns iterable (list) of (prefix, function) pairs.
"""
return [(self.prefix, self.format_doc_link)]
def format_doc_link(self, formatter, ns, target, label):
"""Function to perfo | rm formatting for dox:XYZ links.
This roughly follows [1].
[1] http://trac.edgewall.org/wiki/TracDev/IWikiSyntaxProviderExample
"""
# Stylesheet already done for doc_links.
add_stylesheet(formatter.req, 'doc_links/css/doc_links.css')
# The following is a heuristic for "... |
cloudcopy/seahub | seahub/api2/serializers.py | Python | apache-2.0 | 4,418 | 0.003395 | import re
from rest_framework import serializers
from seahub.auth import authenticate
from seahub.api2.models import Token, TokenV2, DESKTOP_PLATFORMS
from seahub.api2.utils import get_client_ip
from seahub.utils import is_valid_username
def all_none(values):
for value in values:
if value is not None:
... | s:
if value is None:
return False
return True
_ANDROID_DEVICE_ID_PATTERN = re.compile('^[a-f0-9]{1,16}$')
class AuthTokenSerializer(serializers.Serializer):
username = serializers.CharField()
| password = serializers.CharField()
# There fields are used by TokenV2
platform = serializers.CharField(required=False)
device_id = serializers.CharField(required=False)
device_name = serializers.CharField(required=False)
# These fields may be needed in the future
client_version = serialize... |
Zlash65/erpnext | erpnext/patches/v10_0/set_b2c_limit.py | Python | gpl-3.0 | 417 | 0.014388 | # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license. | txt
from __future__ import unicode_literals
import frappe
def execute():
frappe.reload_doc("regional", "doctype", "gst_settings")
frappe.reload_doc | ("accounts", "doctype", "gst_account")
gst_settings = frappe.get_doc("GST Settings")
gst_settings.b2c_limit = 250000
gst_settings.save()
|
hombit/house | house/secrets.py | Python | mit | 130 | 0 | import os
y | andex_api_key = os.environ['YANDEX_API_KEY']
weather_underground_api_key = os.envir | on['WEATHER_UNDERGROUND_API_KEY']
|
PulseRain/Arduino_M10_IDE | M10_upload/FP51_upload.py | Python | lgpl-3.0 | 9,618 | 0.020067 | #! python3
###############################################################################
# Copyright (c) 2016, PulseRain Technology LLC
#
# This program is distributed under a dual license: an open source license,
# and a commercial license.
#
# The open source license under which this program is distributed is t... | cd.code_mem_write_byte (addr + offset, data [offset])
offset = offset + 1
def _do_load_hex_file (self):
intel_hex_file = Intel_Hex(self._args[1])
if (len (intel_hex_file.da | ta_record_list) == 0):
return
if (len(self._args) > 2):
try:
f = open(self._args[2], 'w')
except IOError:
print ("Fail to open: ", self._args[2])
return
#self._do_pause_cpu()
#print ... |
cripplet/practice | codeforces/492/attempt/b_lanterns.py | Python | mit | 897 | 0.044593 | import fileinput
def str_to_int(s):
return([ int(x) for x in s.split() ])
# args = [ 'line 1', 'line 2', ... ]
def proc_input(args):
(n, l) = str_to_int(args[0])
a = tuple(str_to_int(args[1]))
return(l, a)
def solve(args, verbose=False):
(l, a) = proc_input(args)
list_a = list(a)
list_a.sort()
max_dist = max... | ange(len(a) - 1):
max_dist = max(max_dist, list_a[x + 1] - list_a[x])
if verbose:
print max_dist / float(2)
return max_dist / float(2)
def test():
assert(str_to_int('1 2 3') == [ 1, 2 | , 3 ])
assert(proc_input([ '2 5', '2 5' ]) == (5, (2, 5)))
assert(solve([ '2 5', '2 5' ]) == 2.0)
assert(solve([ '4 5', '0 1 2 3' ]) == 2.0)
assert(solve([ '7 15', '15 5 3 7 9 14 0' ]) == 2.5)
if __name__ == '__main__':
from sys import argv
if argv.pop() == 'test':
test()
else:
solve(list(fileinput.input())... |
kevindiltinero/seass3 | tests/test_toggle.py | Python | bsd-2-clause | 137 | 0.014599 | from tests import tests
def test_toggle():
temporary = te | sts.toggled_seats
asser | t temporary == [[1, 1, 1], [1, 1, 1], [1, 1, 1]] |
mafiya69/sympy | sympy/solvers/tests/test_solveset.py | Python | bsd-3-clause | 40,909 | 0.001076 | from sympy import (
Abs, Dummy, Eq, Gt, Function,
LambertW, Piecewise, Poly, Rational, S, Symbol, Matrix,
asin, acos, acsc, asec, atan, atanh, cos, csc, erf, erfinv, erfc, erfcinv,
exp, log, pi, sin, sinh, sec, sqrt, symbols,
tan, tanh, atan2, arg,
Lambda, imageset, cot, acot, I, EmptySet, Union... | FiniteSet(log(y)))
assert invert_real(exp(3*x | ), y, x) == (x, FiniteSet(log(y) / 3))
assert invert_real(exp(x + 3), y, x) == (x, FiniteSet(log(y) - 3))
assert invert_real(exp(x) + 3, y, x) == (x, ireal(FiniteSet(log(y - 3))))
assert invert_real(exp(x)*3, y, x) == (x, FiniteSet(log(y / 3)))
assert invert_real(log(x), y, x) == (x, FiniteSet(exp(y))... |
yacoin/yacoin | test/functional/test_framework/test_node.py | Python | mit | 24,353 | 0.003203 | #!/usr/bin/env python3
# Copyright (c) 2017-2019 The Bitcoin Core developers
# | Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Class for bitcoind node under test"""
import contextlib
import decimal
import errno
from enum import Enum
import http.client
import json
import logging
import os
import re
import s... | rse
import collections
import shlex
import sys
from .authproxy import JSONRPCException
from .util import (
MAX_NODES,
append_config,
delete_cookie_file,
get_rpc_proxy,
rpc_url,
wait_until,
p2p_port,
EncodeDecimal,
)
BITCOIND_PROC_WAIT_TIMEOUT = 60
class FailedToStartError(Exception):... |
meerkat-code/meerkat_api | meerkat_api/test/test_locations.py | Python | mit | 8,430 | 0.00083 | #!/usr/bin/env python3
"""
Meerkat API Tests
Unit tests for the location resource in Meerkat API
"""
import json
import unittest
import meerkat_api
from meerkat_api.test import db_util
from meerkat_api.resources import locations
from meerkat_api.test.test_data.locations import DEVICE_IDS_CSV_LIST, DEVICEID_1, DEVICE_I... | for id in ["42", "fake_device_id", DEVICEID_1[1:]]:
rv = self.app.get('locations?deviceId={}'.format(id), headers=settings.header)
self.assertEqual(rv.status_code, 200)
actual_response_json = json.loads(rv.data.decode('utf-8'))
empty_js | on = {}
self.assertEqual(actual_response_json, empty_json)
def test_location_by_device_id(self):
for id in DEVICE_IDS_CSV_LIST.split(','):
self.validate_correct_location_returned(deviceid=id, expected_loc_id='12')
def test_location_by_device_id_imei_format(self):
for id... |
munhyunsu/UsedMarketAnalysis | joonggonara_crawl/joonggonara/spiders/lgt_spiders.py | Python | gpl-3.0 | 7,133 | 0.033962 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
##### ##### ===== 포함 파일 =====
# 개인적인 아이디, 비밀번호 파일.
from personal.jconfig import LOGIN_ID, LOGIN_PW
# scrapy item 파일.
from joonggonara.items import JoonggonaraItem
# 로그인을 위한 FormRequest.
# 로그인 이후 크롤링을 위한 Request.
from scrapy.http import FormRequest, Request
# 게시판 페이지에서 ... | SELECT COUNT(*) FROM ''' + LIST_DB
)
CRAWL_COUNT = CRAWL_COUNT + int(cur.fetchone()[0])
# 로그인 성공 후 게시판에서 각 게시글의 URL을 따옴
return Request(url=BOARD_PAGE_URL + str(1), callback=self.parse_list)
# 수집한 게시판 정보에서 공지사항을 제외한 게시글 URL을 파싱
def parse_list(self, response):
# 글로벌 변수를 불러옴
global CRAWL_TARGET
glo... | ):
# 수집 목표량을 채웠을 경우 탈출
if CRAWL_COUNT >= CRAWL_TARGET:
break
# 게시글 번호 파싱
article_num = re.split(r'[?=&]', ahref)[12]
# 이미 받은 게시글일 경우 패스
cur.execute('SELECT * FROM ' + DOWNLOADED_DB + ' WHERE article_num = ' + str(article_num)
)
if cur.fetchone() is not None:
print 'tartget skip: ' +... |
nicolasgallardo/TECHLAV_T1-6 | bebop_ws/build/laser_scan_publisher_tutorial/catkin_generated/pkg.develspace.context.pc.py | Python | gpl-2.0 | 389 | 0 | # generated from catkin/cmake/template/pkg.context.pc.in
CATKIN_PACKAGE_PREFIX = ""
| PROJECT_PKG_CONFIG_INCLUDE_DIRS = "".split(';') if "" != "" else []
PROJECT_CATKIN_DEPENDS = "".replace(';', ' ')
PKG_CONFIG_LIBRARIES_WITH_PREFIX = "".split(';') if "" != "" else | []
PROJECT_NAME = "laser_scan_publisher_tutorial"
PROJECT_SPACE_DIR = "/home/robot/bebop_ws/devel"
PROJECT_VERSION = "0.2.1"
|
rtucker-mozilla/WhistlePig | vendor-local/lib/python/tastypie/resources.py | Python | bsd-3-clause | 94,814 | 0.002067 | from __future__ import with_statement
import sys
import logging
import warnings
import django
from django.conf import settings
try:
from django.conf.urls import patterns, url
except ImportError: # Django < 1.4
from django.conf.urls.defaults import patterns, url
from django.core.exceptions import ObjectDoesNotEx... | ""
Handles the data, request dispatch and responding to requests.
Serialization/deserialization is handled "at the edges" (i.e. at the
beginning/end of the request/respons | e cycle) so that everything internally
is Python data structures.
This class tries to be non-model specific, so it can be hooked up to other
data sources, such as search results, files, other data, etc.
"""
__metaclass__ = DeclarativeMetaclass
def __init__(self, api_name=None):
self.fi... |
sysadminmatmoz/ingadhoc | account_journal_book/models/account.py | Python | agpl-3.0 | 1,050 | 0 | # -*- encoding: utf-8 -*-
##############################################################################
# For copyright and license notices, see __openerp__.py file in root directory
##############################################################################
from openerp import fields, models, api
import logging
_... | string='Number in Book',
help='This number is set when closing a period or by running a wizard'
)
| _sql_constraints = [
('number_in_book_uniq', 'unique(number_in_book, company_id)',
'Number in Book must be unique per Company!')]
@api.multi
def moves_renumber(self, sequence):
_logger.info("Renumbering %d account moves.", len(self.ids))
for move in self:
new_num... |
CPSC491FileMaker/project | helper.py | Python | gpl-2.0 | 2,133 | 0.018753 | import xml.etree.ElementTree as et
import os, time
from xml.etree.ElementTree import Element
from PyQt4 import QtCore, QtGui
class Helper():
#initiatlizes the class and prepares an XMLtree for parsing
def __init__(self):
self.tree = et.parse('./data/data.xml')
self.root = self.tree.getroot()
def wr... | ' + name.text
#print 'to xml: ' + co | lor.text
emp.append(name)
emp.append(color)
kid.append(emp)
self.write('./data/data.xml')
def addStatus(self, sName):
st = Element('Stat')
st.text = sName
kid = self.root.find('Proj_statuses')
kid.append(st)
self.write('./data/data.xml')
if __name__ == "__main__":
A = Hel... |
tryexceptpass/sofi | test/tablerow_test.py | Python | mit | 429 | 0.011655 | from sofi.ui import TableRow
def test_basic():
assert(str(TableRow()) == "<tr></tr>")
def test_text():
assert(str(TableRow("text")) == "<tr>text</tr>")
def test_custom_class_ident_style_and_att | rs():
assert(str(TableRow("text", cl='abclass', ident='123', style="font-size:0.9em;", attrs={"data-test": 'abc'}))
== "<tr id=\ | "123\" class=\"abclass\" style=\"font-size:0.9em;\" data-test=\"abc\">text</tr>")
|
mtik00/bottle-wiki | wikiapi.py | Python | mit | 1,234 | 0.007293 | """ A simple restful webservice to provide access to the wiki.db"""
import json
from bottle import Bottle, run, response, static_file, redirect
from dbfu | nctions import Wikidb
api = Bottle()
db = Wikidb()
@api.route('/static/<filepath:path>')
def static(filepath):
return static_file(filepath, root='./static')
@api.route('/api/search/<term>')
def search(term):
response.headers['Content-Type'] = 'application/json'
response.headers['Cache-Control'] = 'no-c... | eaders['Cache-Control'] = 'no-cache'
return json.dumps(db.detail(subject))
if __name__ == '__main__':
# Demonstrates the truely awesome awesomplete drawing data right from the search API above.
@api.route('/search')
def autocompletesearch():
return redirect('/static/autocomplete.html')
db.... |
code-ape/SocialJusticeDataProcessing | stats.py | Python | apache-2.0 | 3,877 | 0.003869 | import json
import correlation
import category
import tools
import settings
from matplotlib.backends.backend_pdf import PdfPages
def process_data(data_type, stats, highlights):
print("Starting student data processing.")
all_pdf_path, highlight_pdf_path = (None,None)
question_types, demographic_question... | e_demographic = category.base_demographic(data, demographic_questions)
answer_response_lists = category.generate_answer_response_lists(
data, opinion_questions)
opinion_demogra | phic_dict = category.generate_demographic_for_response_lists(
answer_response_lists, data)
opinion_demographic_diff_dict = category.calc_demographic_diff(
base_demographic, opinion_demographic_dict)
interes... |
masterqa/MasterQA | setup.py | Python | mit | 2,876 | 0 | """
The setup package to ins | tall MasterQA dependencies
"""
from setuptools import setup, find_packages # noqa
import os
import sys
this_directory = os.path.abspath(os.path.dirname(__file__))
long_description = None
total_descript | ion = None
try:
with open(os.path.join(this_directory, 'README.md'), 'rb') as f:
total_description = f.read().decode('utf-8')
description_lines = total_description.split('\n')
long_description_lines = []
for line in description_lines:
if not line.startswith("<meta ") and not line.startsw... |
akx/shoop | shoop/xtheme/plugins/_base.py | Python | agpl-3.0 | 7,820 | 0.002046 | # -*- coding: utf-8 -*-
# This file is part of Shoop.
#
# Copyright (c) 2012-2016, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
from __future__ import unicode_literals
from django.template.loader import ... | The template to render
template_name = ""
#: Variables to copy from the parent context.
inherited_variables = set()
#: Variables to copy from the plugin configuration
config_copied_variables = set()
engine = None # | template rendering engine
def get_context_data(self, context):
"""
Get a context dictionary from a Jinja2 context.
:param context: Jinja2 rendering context
:type context: jinja2.runtime.Context
:return: Dict of vars
:rtype: dict[str, object]
"""
var... |
hmcc/price-search | scraper/scraper.py | Python | mit | 3,591 | 0.003063 | """
This module contains a single class that manages the scraping of data
from one or more supermarkets on mysupermarket.co.uk
"""
from datetime import datetime
from os import remove
from os.path import isfile, getmtime
from time import time
from scrapy import signals
from scrapy.crawler import Crawler
from scrapy.uti... | rmarket -- the supermarket whose cachefile should be checked
"""
cachefile = supermarket_filename(supermarket)
if not isfile(cachefile):
return False
mtime = datetime.fromtimestamp(getmtime(cachefile))
now = datetime.fromtimestamp(time())
return mtime.day == ... | awler.
See http://doc.scrapy.org/en/latest/topics/practices.html#run-scrapy-from-a-script.
Keyword arguments:
supermarket -- the supermarket whose crawler should be set up
"""
cachefile = supermarket_filename(supermarket)
if isfile(cachefile):
... |
pacificIT/mopidy | mopidy/file/library.py | Python | apache-2.0 | 4,786 | 0 | from __future__ import unicode_literals
import logging
import operator
import os
import sys
import urllib2
from mopidy import backend, exceptions, models
from mopidy.audio import scan, utils
from mopidy.internal import path
logger = logging.getLogger(__name__)
FS_ENCODING = sys.getfilesystemencoding()
class FileL... | uld accept / in dir name
media_dir['name'] = media_dir_split[0].replace(os.sep, '+')
yield media_dir
def _get_media_dirs_refs(self):
for media_dir in self._media_dirs:
yield models.Ref.directory(
name=media_dir['name'],
uri=path.path_... | sedir(self, local_path):
return any(
path.is_path_inside_base_dir(local_path, media_dir['path'])
for media_dir in self._media_dirs)
|
faisaltheparttimecoder/EMEARoster | MyRoster/views.py | Python | mit | 1,122 | 0.000891 | from datetime import datetime
from django.contrib.auth.decorators import login_required
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
from Core.models import RosterAudit, RosterUser
@login_required
@csrf_exempt
def myroster_rows(request):
"""
Obtain all the rows for... | r
date_now = datet | ime.now().date()
# Variables
connected_username = ""
collector = []
# Get the name of the user based on email from the roster table
# we not relying on the username that can be obtained via request
# Since anyone can enter anyname and it will be become hard to
# manage.
for user in Ros... |
elkingtowa/pyrake | tests/test_djangoitem/models.py | Python | mit | 440 | 0.002273 | from django.db import models
class Person(models.Model):
name = models.CharField(max_length=255, defa | ult='Robot')
age = models.IntegerField()
class Meta:
app_label = 'test_djangoitem'
class IdentifiedPerson(models.Model):
identifier = models.PositiveIntegerField(primary_key=True)
name = models.CharField(max_length=255)
age = models.IntegerField()
class Meta:
app_label | = 'test_djangoitem'
|
ControCurator/controcurator | python_code/anchorGenerator.py | Python | mit | 1,229 | 0.026037 | # anchorGenerator
from models.anchor import *
# main function
if __name__=='__main__':
# TEMP: Wipe existing anchors
# anchors = Anchor.all(size=1000)
# Anchor.delete_all(anchors)
# THIS IS TEMPORARY:
anchors = {'Vaccination', 'Vaccinations', 'Vaccine', 'Vaccines', 'Inoculation', 'Immunization', 'Shot', 'Chicken... | anchor)
a.findInstances()
a.save()
"""
query = {
"size": 0,
"query": {
"filtered": {
"query": {
"query_string": {
"query": "*",
"analyze_wildcard": True
}
}
}
},
"aggs": { |
"2": {
"terms": {
"field": "title",
"size": 100,
"order": {
"_count": "desc"
}
}
}
}
}
response = es.search(index="crowdynews"', 'body=query)
retrieved = now()
anchors = {}
# go through each retrieved document
for hit in response['aggregations']['2... |
Open-E-WEB/django-powerpages | powerpages/tests/test_admin.py | Python | mit | 7,705 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.test import TestCase
from django.conf import settings
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from powerpages.models import Page
from powerpages.sync import PageFileDumper
from powerpages.admi... | ', title='Lorem')
page.title = 'Ipsum'
user = User.objects.create_user('admin-user')
save_page(page=page, user=user, created=False)
self.assertEqual(Page.objects.get(pk=page.pk).title, 'Ipsum')
self.assertTrue(page.is_dirty)
self.assertDictContainsSubset(
{'... | ge_edited_kwargs
)
class SwitchEditModeViewTestCase(TestCase):
maxDiff = None
def setUp(self):
self.url = reverse('switch_edit_mode')
self.staff_member = User.objects.create_user(
'staff_member', password='letmein123', is_staff=True
)
self.super_user = Use... |
danalec/dotfiles | sublime/.config/sublime-text-3/Packages/anaconda_php/anaconda_php.py | Python | mit | 673 | 0 |
# Copyright (C) 2014 - Oscar Campos <oscar.campos@member.fsf.org>
# This program is Free Software see LICENSE file for details
"""AnacondaPHP is a PHP linting plugin for Sublime Text 3
"""
from .plugin_version import anaconda_required_version
from .anaconda_lib.anaconda_plugin import anaconda_version |
if anaconda_required_version > anaconda_version:
raise RuntimeError(
'AnacondaPHP requires version {} or better of anaconda but {} '
'is installed'.format(
'.'.join([ | str(i) for i in anaconda_required_version]),
'.'.join([str(i) for i in anaconda_version])
)
)
from .commands import *
from .listeners import *
|
yarabarla/python-challenge | 3.py | Python | mit | 812 | 0.022167 | # http://www.pythonchallenge.com/pc/def/equality.html
import re
file_ob = open("3.dat", 'r')
ob_read = file_ob.read()
read_arr = list(ob_read)
word = []
def for_loop(): # Loops through array to find solution
for i in range(len(read_arr)):
if (i + 8) > len(read_arr): # To keep index in bounds
break
if not(... | (read_arr[i + 4])
print "".join(word)
def reg | _ex(): # Uses regex to find the pattern
print "".join( re.findall("[^A-Z][A-Z]{3}([a-z])[A-Z]{3}[^A-Z]", ob_read))
# for_loop()
# reg_ex()
|
zwadar/pyqode.python | pyqode/python/managers/file.py | Python | mit | 2,598 | 0 | """
Contains the python specific FileManager.
"""
import ast
import re
from pyqode.core.api import TextBlockHelper
from pyqode.core.managers import FileManager
class PyFileManager(FileManager):
"""
Extends file manager to override detect_encoding. With python, we can
detect encoding by reading the two fir... | ncoding)
try:
folding_panel = self.editor.panels.get('FoldingPanel')
except KeyError:
pass
else:
# fold imports and/or doc | strings
blocks_to_fold = []
sh = self.editor.syntax_highlighter
if self.fold_imports and sh.import_statements:
blocks_to_fold += sh.import_statements
if self.fold_docstrings and sh.docstrings:
blocks_to_fold += sh.docstrings
f... |
tryexceptpass/sofi | sofi/ui/anchor.py | Python | mit | 1,243 | 0.004023 | from .element import Element
class Anchor(Element):
"""Implements the <a> tag"""
def __init__(self, text=None, href="#", cl=None, ident=None, style=None, attrs=None):
super().__init__(cl=cl, ident=ident, style=style, attrs=attrs)
self.href = href
if text:
self._children.... | put.append(" id=\"")
output.append(self.ident)
output.append("\"")
if self.cl:
output.append(" class=\"")
output.append(self.cl)
output.append("\"")
output.append(' href="')
output.append(self.href)
output.append('"')
... | for k in self.attrs.keys():
output.append(' ' + k + '="' + self.attrs[k] + '"')
output.append(">")
for child in self._children:
output.append(str(child))
output.append("</a>")
return "".join(output)
|
adrianomargarin/py-notacarioca | notacarioca/settings.py | Python | apache-2.0 | 377 | 0.007958 | URL = {
3304 | 557: {
"production": "https://notacarioca.rio.gov.br/WSNacional/nfse.asmx?wsdl",
"sandbox": "https://homologacao.notacarioca.rio.gov.br/WSNacional/nfse.asmx?wsdl"
}
}
TEMPLATES = {
'send_rps': "GerarNfseEnvio.xml",
'status': "ConsultarNfseEnvio.xml",
'get_nfse': "Consult | arNfseEnvio.xml",
'cancel': "CancelarNfseEnvio.xml"
} |
adaptivethreat/Empire | lib/modules/powershell/situational_awareness/host/antivirusproduct.py | Python | bsd-3-clause | 4,095 | 0.012698 | from lib.common import helpers
class Module:
def __init__(self, mainMenu, params=[]):
self.info = {
'Name': 'Get-AntiVirusProduct',
'Author': ['@mh4x0f', 'Jan Egil Ring'],
'Description': ('Get antivirus product information.'),
'Background' : True,
... | /12/use-windows-powershell-to-get-antivirus-product-information/'
]
}
# any options needed by the module, settable during runtime
self.options = {
# format:
# value_name : {description, required, default_value}
'Agent' : {
'Descr... | nt to run module on.',
'Required' : True,
'Value' : ''
},
'ComputerName' : {
'Description' : 'Computername to run the module on, defaults to localhost.',
'Required' : False,
'Value' ... |
ravenscroftj/freecite | setup.py | Python | mit | 446 | 0.042601 | from setuptools import setup, find_packages
setup(
name = "FreeCite",
version = "0.1",
py_modules = ['freecite'],
#install requirements
| install_requires = [
'requests==1.1.0'
],
#author details
author = "James Ravenscroft",
author_email = "ravenscroftj@gmail.com",
| description = "A wrapper around the FreeCite REST API",
url = "http://wwww.github.com/ravenscroftj/freecite"
)
|
degibenz/vispa-chat | src/api/chat_ws.py | Python | mit | 5,947 | 0.002097 | # -*- coding: utf-8 -*-
__author__ = 'degibenz'
import logging
log = logging.getLogger(__name__)
log.setLevel(logging.DEBUG)
import json
from aiohttp import web
from core.model import ObjectId
from core.exceptions import *
from models.chat import *
from models.client import Client, Token
__all__ = [
'ChatWS'... | if self.db:
client.db = self.db
await client.get()
q = {
'chat': self.chat_pk,
'client': ObjectId(receiver)
}
if not await self.c | lient_in_chat.get(**q):
self.client_in_chat.save(**q)
async def prepare_msg(self):
async for msg in self.socket:
content = json.loads(msg.data)
receiver = content.get('receiver', None)
if receiver:
await self.check_receiver(receiver)
... |
srittau/python-htmlgen | htmlgen/image.py | Python | mit | 952 | 0 | from .attribute import html_attribute
from .element import VoidElement
class Image(VoidElement):
"""An HTML image (<img>) element.
Images must have an alternate text description that describes the
contents of the image, if the image can not be displayed. In some
cases the alternate text can be empty.... | ge just
displays a company logo next to the company's name or if the image just
adds an icon next to a textual description of an action.
Example:
>>> image = Image("whiteboard.jpg",
... "A whiteboard filled with mathematical formulas.")
>>> image.title = "Whiteboards ... | uper().__init__("img")
self.url = url
self.alternate_text = alternate_text
url = html_attribute("src")
alternate_text = html_attribute("alt")
title = html_attribute("title")
|
mumax/2 | tests/reduce.py | Python | gpl-3.0 | 704 | 0.012784 | from mumax2 import *
# Standard Problem 4
Nx = 32
Ny = 32
Nz = 1
setgridsize(Nx, Ny, Nz)
setcellsize(500e-9/Nx, 125e-9/Ny, 3e-9/Nz)
load('micromagnetism')
load('solver/rk12')
|
setv('Msat', 800e3)
setv('demag_acc', 7)
setv('Aex', 1.3e-11)
setv('alpha', 1)
setv('dt', 1e-12)
setv('m_maxerror', 1./1000)
new_maxabs("my_maxtorque", "torque")
new_maxnorm("m | axnorm", "torque")
m=[ [[[1]]], [[[1]]], [[[0]]] ]
setarray('m', m)
t1=getv("maxtorque")
t2=getv("my_maxtorque")
t3=getv("maxnorm")
echo("maxtorque:" + str(t1) + " my_maxtorque:" + str(t2) + " maxnorm:" + str(t3))
if t3 != t1:
crash
if t3 < t2:
crash
new_maxabs("maxtorquez", "torque.z")
getv("maxtorquez")
printst... |
wwj718/ANALYSE | pavelib/utils/test/suites/nose_suite.py | Python | agpl-3.0 | 5,609 | 0 | """
Classes used for defining and running nose test suites
"""
import os
from paver.easy import call_task
from pavelib.utils.test import utils as test_utils
from pavelib.utils.test.suites import TestSuite
from pavelib.utils.envs import Env
__test__ = False # do not collect
class NoseTestSuite(TestSuite):
"""
... | lf.verbosity,
test_id=self.test_id,
test_opts=self.test_options_flags,
)
)
return self._under_coverage_cmd(cmd)
@property
def _default_test_id(self):
"""
If no test id is provided, we need to limit the test runner
to the Djang... | using a default test id.
"""
# We need to use $DIR/*, rather than just $DIR so that
# django-nose will import them early in the test process,
# thereby making sure that we load any django models that are
# only defined in test files.
default_test_id = "{system}/djang... |
openshine/osweb | osweb/projects/__init__.py | Python | gpl-3.0 | 108 | 0.009259 | from | osweb.projects.ManageProject import ManageProject
from osweb.projects.projects_data import ProjectsDat | a |
alberthdev/pyradmon | pyradmon/dummymp/loghandler.py | Python | apache-2.0 | 2,314 | 0.008643 | #!/usr/bin/env python
# DummyMP - Multiprocessing Library for Dummies!
# Copyright 2014 Albert Huang.
#
# 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/LI... | se is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, e | ither express or
# implied. See the License for the specific language governing
# permissions and limitations under the License.
#
# DummyMP Library - Logging Redirect Handler
# multiprocessing library for dummies!
# (library for easily running functions in parallel)
#
import logging
import config
import os
cla... |
siosio/intellij-community | python/testData/completion/heavyStarPropagation/lib/_pkg0/_pkg0_1/_pkg0_1_1/_pkg0_1_1_0/_pkg0_1_1_0_0/_mod0_1_1_0_0_2.py | Python | apache-2.0 | 128 | 0.007813 | name0_1_1_0_0_2_0 = None
name0_1_1_0_0_2_1 = None
name0_1_1_0_0_2_2 = None
name0_1_1_0_0_2_ | 3 = None
name0_1_1_0_0_2 | _4 = None |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.