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 |
|---|---|---|---|---|---|---|---|---|
LukeC92/iris | lib/iris/tests/test_cube_to_pp.py | Python | lgpl-3.0 | 14,217 | 0.005135 | # (C) British Crown Copyright 2010 - 2017, Met Office
#
# This file is part of Iris.
#
# Iris 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 Software Foundation, either version 3 of the License, or
# (at your option) any l... |
reference_txt_path = tests.get_result_path(('cube_to_pp', 'replace_multi.txt'))
with self.cube_save_test(reference_txt_path, reference_cubes=cubes[2:]) as temp_pp_path:
iris.save(cubes[:2], temp_pp_path)
iris.save(cubes[2:], temp_pp_path)
def add_coords_to_cube_and_test(se... | ).reshape(4, 4)
cm = iris.cube.Cube(data=dataarray)
cm.add_dim_coord(coord1, 0)
cm.add_dim_coord(coord2, 1)
# TODO: This is the desired line of code...
# reference_txt_path = tests.get_result_path(('cube_to_pp', '%s.%s.pp.txt' % (coord1.name(), coord2.name())))
... |
jkonecny12/anaconda | pyanaconda/modules/storage/partitioning/interactive/interactive_interface.py | Python | gpl-2.0 | 1,424 | 0.001404 | #
# DBus interface for the interactive partitioning module
#
# Copyright (C) 2019 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it su | bject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including t | he implied warranties 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 General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Bo... |
skyfielders/python-skyfield | skyfield/framelib.py | Python | mit | 5,257 | 0.004967 | # -*- coding: utf-8 -*-
"""Raw transforms between coordinate frames, as NumPy matrices."""
from numpy import array
from .constants import ANGVEL, ASEC2RAD, DAY_S, tau
from .data.spice import inertial_frames as _inertial_frames
from .functions import mxm, rot_x, rot_z
def build_matrix():
# 'xi0', 'eta0', and 'da0'... | s rotation with
respect | to the stars, and (if your ``Timescale`` has polar offsets
loaded) the polar wobble of the crust with respect to the Earth’s
pole of rotation.
.. versionadded:: 1.34
"""
@staticmethod
def rotation_at(t):
R = mxm(rot_z(-t.gast * tau / 24.0), t.M)
if t.ts.polar_motion_table is no... |
hongta/practice-python | sorting/bucket_sort.py | Python | mit | 416 | 0.012019 | #!/usr/bin/ | env python
# -*- coding: utf-8 -*-
from insertion_sort import insertion_sort
def bucket_sort(a):
"""
0.0 <= a[i] <= 1
"""
b = [[] for _ in a]
n = len(a)
for v in a:
b[int(n*v)].append(v)
a = []
for i in range(len(b)):
a.extend(insertion_sort(b[i]))
retur... | rt(d)
|
enthought/etsproxy | enthought/envisage/ui/single_project/action/configure_action.py | Python | bsd-3-clause | 119 | 0 | # proxy module
from __future__ import absolute_import
from envisage.ui.single_project.a | ction.config | ure_action import *
|
reviewboard/reviewboard | reviewboard/diffviewer/evolutions/add_diff_hash.py | Python | mit | 542 | 0 | from django_evolution.mutations import AddField, RenameField
from django.db import models
MUTATIONS = [
RenameField('FileDiff', 'diff', 'diff64', db_column='diff_base64'),
RenameField('FileDiff', 'parent_diff', 'parent_diff64',
db_column='parent_diff_base64'),
AddField('FileDiff', 'diff | _hash', models.ForeignKey, null=True,
related_model='diffviewer.FileDiffData'),
AddField('FileDiff', 'parent_diff_hash', models.ForeignKey, null=True,
| related_model='diffviewer.FileDiffData'),
]
|
sigmunau/nav | python/nav/web/navlets/error.py | Python | gpl-2.0 | 900 | 0 | #
# Copyright (C) 2014 UNINETT AS
#
# This file is part of Network Administration Visualized (NAV).
#
# NAV is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License version 2 as published by
# the Free Software Foundation.
#
# This program is distributed in the hope... | 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 t | he GNU General Public
# License along with NAV. If not, see <http://www.gnu.org/licenses/>.
#
"""Replacement widget for when we can not find the widget class"""
from . import Navlet
class ErrorWidget(Navlet):
title = "Error"
description = "Jau"
can_be_added = False
def get_template_basename(self):
... |
tartopum/MPF | setup.py | Python | mit | 1,662 | 0.007822 | import os
import sys
from setuptools import setup
from setuptools.command.test import test as TestCommand
import mpf
# Test
class PyTest(TestCommand):
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = []
self.test_suite = True
def run_tests(se... | _data=True,
i | nstall_requires=requirements,
license="MIT",
zip_safe=False,
keywords="mpf",
classifiers=[
"Development Status :: 2 - Pre-Alpha",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Natural Language :: English",
"Programming Language :: P... |
supriyantomaftuh/python-publisher | pubsubhubbub_publish_test.py | Python | apache-2.0 | 4,205 | 0.005945 | #!/usr/bin/env python
#
# Copyright 2009 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 o... | h.PublishError,
pubsubhubbub_publish.publish,
'http://asdf.does.not.resolve', self.feed)
def testBadArgument(self):
self.assertRaises(
pubsubhubbub_publish.PublishError,
pubsubhubbub_publish.publish,
self.hub + '/fail', self.feed)
def testBadHubUrl(self):
self.asser... | .feed)
def testNotFound(self):
self.assertRaises(
pubsubhubbub_publish.PublishError,
pubsubhubbub_publish.publish,
self.hub + '/unknown', self.feed)
if __name__ == '__main__':
unittest.main()
|
Cataloniacoin/CataloniacoinS | contrib/wallettools/walletunlock.py | Python | mit | 158 | 0 | from | jsonrpc import ServiceProxy
access = ServiceProxy("http://127.0.0.1:9678")
pwd = raw_input("Enter wallet passphrase: ")
access.walletpassphrase(pwd, 60 | )
|
lopiola/integracja_wypadki | scripts/gb_accident_parser.py | Python | mit | 7,122 | 0.001545 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Parsing accident CSV files for Great Britain data and putting them into DB
"""
import csv
import sys
import db_api.accident
from parsing.common import get_timestamp, translate_field, to_float, to_int, map_from_dictionary, mph_to_kmph
from parsing.gb_common import get_acc_... | tion_Control':
return {'junction_control': accident_data[field], 'special_conditions': accident_data['Special_Conditions_at_Site']}
return {'value': accident_data[field]}
def update_ids(accidents):
new_ids = {}
for accident in accident | s:
new_ids[accident['id']] = True
ids = get_gb_ids()
ids.update(new_ids)
with open(GB_IDS_FILE, "w+") as pickle_file:
pickle.dump(ids, pickle_file)
if __name__ == '__main__':
if len(sys.argv) != 2:
print('Usage: {0} <csv_file>'.format(sys.argv[0]))
exit(1)
with o... |
miracle2k/pysieved | plugins/accept.py | Python | gpl-2.0 | 2,161 | 0.007867 | #! /usr/bin/py | thon
## pysieved - Python managesieve server
## Copyright (C) 2007 Neale Pickett
## 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.
## This program is distributed in the hope that it will be useful, but
## WITHOUT ANY WARRANTY; without even... |
camptocamp/ngo-addons-backport | addons/account/account.py | Python | agpl-3.0 | 191,194 | 0.007307 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... | =context)
except ValueError:
pass
return financial_report_ref
d | ef _get_current_report_type(self, cr, uid, ids, name, arg, context=None):
res = {}
financial_report_ref = self._get_financial_report_ref(cr, uid, context=context)
for record in self.browse(cr, uid, ids, context=context):
res[record.id] = 'none'
for key, financial_report i... |
JevinJ/Bittrex-Notify | src/GUIfasttick.py | Python | mit | 3,213 | 0.002179 | import tkinter as tk
from time import sleep
from playsound import playsound
import config
import fasttick
from helpmessage import fasttick_help_message
import misc
from tickerwindow import TickerWindow
class GUIfasttick(TickerWindow):
def __init__(self, app):
super().__init__(app)
misc.delete_anci... |
def timer_update(self):
if self.timerValue == 3:
self.async = self.pool.apply_async(fasttick.heartbeat)
if self.timerValue == 0:
while True:
if self.async.ready():
break
for i in range(1, 4):
if self.asy... | .ready():
break
self.timerDisp.config(text=f'{"." * i}', font=('', 20))
self.app.update()
sleep(1)
self.ticker_data = self.async.get()
self.sort_ticker()
if self.notifyIsActive and self.ticker_data:
... |
kevin-coder/tensorflow-fork | tensorflow/python/tpu/tensor_tracer.py | Python | apache-2.0 | 67,356 | 0.007824 | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | amework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import graph_io
from tensorflow.python.framework import ops
from tensorflow.python.framework import tensor_util
from tensorflow.python.ops import | array_ops
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import control_flow_util
from tensorflow.python.ops import gen_math_ops
from tensorflow.python.ops import init_ops
from tensorflow.python.ops import linalg_ops
from tensorflow.python.ops import logging_ops
from tensorflow.python.ops... |
ColumbiaCMB/kid_readout | apps/data_taking_scripts/cooldown/2017-11-23_starcryo/r2h14_test.py | Python | bsd-2-clause | 3,665 | 0.003274 | """
Measure resonators, one at a time, with the readout tone centered in the filterbank bin.
"""
from __future__ import division
import time
import numpy as np
from kid_readout.roach import analog, calculate, hardware_tools, tools
from kid_readout.measurement import acquire, basic
from kid_readout.equipment import h... | = 0
conditioner = analog.HeterodyneMarkII()
hw = hardware.Hardware(temperature, lock, mmw, conditioner)
ri = hardware_tools.r2h14_with_mk2(initialize=True, use_config=False)
ri.set_modulation_output('high')
ri.iq_delay = -1
ri.adc_valon.set_ref_select(0) # internal
assert np.all(ri.adc_valon.get_phase_locks())
# Cal... | and baseband sweep frequencies
ri_state = ri.state
tone_sample_exponent = int(np.round(np.log2(ri_state.adc_sample_rate / df_baseband_target)))
df_baseband = ri_state.adc_sample_rate / 2 ** tone_sample_exponent
num_sweep_tones = int(f_sweep_span / df_baseband)
f_baseband = f_baseband_minimum + ri.state.adc_sample_rate... |
KarchinLab/2020plus | src/savedb/python/gene_features.py | Python | apache-2.0 | 4,824 | 0.001244 | """The gene_features module generates a DB table for features
like gene length and misc. features from the MutSigCV paper (fig s5).
The MutSigCV paper can be found here:
http://www.nature.com/nature/journal/v499/n7457/full/nature12213.html
The MutSigCV paper suggested that the background mutation rate for genes i... | length.')
return gene_length_dict
def save_db(df, genedb_path):
"""Saves the data into the gene_features table.
If the table already exists, the table is droped and then
re-inserted.
**Parameters**
df : pd.DataFrame
data to insert into DB table
genedb_path : str
path to ... | th=genedb_path, kind='sqlite') # drop table if exists
logger.debug('After dropping gene_features table IF EXISTS.')
logger.info('Saving gene_features table ...')
conn = sqlite3.connect(genedb_path) # open connection
# save to sqlite3 database
psql.write_frame(df, # pandas dataframe
... |
kumar303/olympia | src/olympia/discovery/serializers.py | Python | bsd-3-clause | 2,792 | 0 | from rest_framework import serializers
from olympia.addons.models import Addon
from olympia.addons.serializers import AddonSerializer, VersionSerializer
from olympia.discovery.models import DiscoveryItem
from olympia.versions.models import Version
class DiscoveryEditorialContentSerializer(serializers.ModelSerializer... | # and custom_description, plus a guid to identify the add-on.
fields = ('addon', 'custom_heading', 'custom_description')
def get_addon(self, obj):
return {
# Note: we select_related() the addon, so we don't have extra
# queries. But that also means the Addon transformers do... | scoveryVersionSerializer(VersionSerializer):
class Meta:
fields = ('id', 'compatibility', 'is_strict_compatibility_enabled',
'files',)
model = Version
class DiscoveryAddonSerializer(AddonSerializer):
current_version = DiscoveryVersionSerializer()
class Meta:
fiel... |
tfeldmann/organize | manage.py | Python | mit | 5,445 | 0.001286 | import argparse
import getpass
import os
import re
import subprocess
from datetime import datetime
from pathlib import Path
import requests
SRC_FOLDER = "organize"
CURRENT_FOLDER = Path(__file__).resolve().parent
GITHUB_API_ENDPOINT = "https://api.github.com/repos/tfeldmann/organize"
def ask_confirm(text):
whil... | sk_confirm(f"Creating version v{version}. Continue?"):
return
# update library version
versionfile = CURRENT_FOLDER / SRC_FOLDER / "__version__.py"
with open(versionfile, "w") as f:
print(f"Updating {versionfile}")
f.write(f'__version__ = "{version}"\n')
# update poetry version... | print("Updating pyproject.toml")
subprocess.run(["poetry", "version", version], check=True)
# read changelog
print("Updating CHANGELOG.md")
with open(CURRENT_FOLDER / "CHANGELOG.md", "r") as f:
changelog = f.read()
# check if WIP section is in changelog
wip_regex = re.compile(r"## WIP... |
Crowdcomputer/CC | general/urls.py | Python | apache-2.0 | 853 | 0.007034 | from django.conf.urls import patterns, url
from django.views.generic.base import TemplateView
from general import views
urlpatterns = patterns('',
url(r'^geoloc/updateloc/$', views.UpdateLoc, name='updateloc'),
url(r'^geoloc/$', views.GeoLoc | , name='geoloc'),
url(r'^geoloc/more$', views.AddGeoLoc, | name='addgeoloc'),
url(r'^create/$', views.CreateUser, name='register'),
url(r'^profile/$', views.ProfileView, name='profile'),
url(r'^login/$', views.Login, name='login'),
url(r'^apilogin/$', views.ApiLogin, name='apilogin'),
url(r'^logout/$', views.Logout, name='logout'),
url(r'^thanks/$', Tem... |
mate-desktop/pluma | plugins/externaltools/tools/functions.py | Python | gpl-2.0 | 10,724 | 0.004476 | # -*- coding: utf-8 -*-
# Pluma External Tools plugin
# Copyright (C) 2005-2006 Steve Frécinaux <steve@istique.net>
# Copyright (C) 2012-2021 MATE Developers
#
# 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
# ... | s_uri),
PLUMA_DOCUMENTS_PATH = ' '.join(documents_path))
flags = capture.CAPTURE_BOTH
if not node.has_hash_bang():
flags |= capture.CAPTURE_NEEDS_SHELL
capture.set_flags(flags)
# Get input text
input_type = node.input
output_type = node.output
# Clear the... | the output panel
panel.set_process(capture)
if input_type != 'nothing' and view is not None:
if input_type == 'document':
start, end = document.get_bounds()
elif input_type == 'selection' or input_type == 'selection-document':
try:
start, end = document.... |
drmateo/ecto | test/compile/check_new_bsd_license.py | Python | bsd-3-clause | 2,820 | 0.003546 | #!/usr/bin/env python
import sys
bsd = '''
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 conditions and the following disclai... | ult += "ok"
if thiserror and autofix:
newf = open(filename, "w")
for k, v in commentchars.iteritems():
if filename.endswith(k):
cmt = v
if txt.startswith('#!'):
hashbang, rest = txt.split('\n', 1)
print >>newf, hashbang
else:
| rest = txt
print >>newf, cmt, bsd.replace('\n', '\n' + cmt + ' ')
print >>newf, rest
newf.close()
result += filename + "AUTOFIXED"
print result
sys.exit(nerrors)
|
rajalokan/glance | glance/tests/unit/common/scripts/test_scripts_utils.py | Python | apache-2.0 | 5,341 | 0 | # Copyright 2014 OpenStack Foundation
# 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 requ... | script_utils.validate_location_uri(locati | on))
def test_validate_location_none_error(self):
self.assertRaises(exception.BadStoreUri,
script_utils.validate_location_uri, '')
def test_validate_location_file_location_error(self):
self.assertRaises(exception.BadStoreUri,
script_utils.val... |
AbdealiJK/file-metadata | file_metadata/video/ogv_file.py | Python | mit | 683 | 0 | # -*- coding: utf-8 -*-
from __future__ import (division, absolute_import, unicode_literals,
print_function)
from file_metadata.video.video_file import VideoFile
class OGVFile(VideoFile):
@classmethod
def create(cls, *args, **kwargs):
return cls(*args, **k | wargs)
def analyze_file_format(self):
"""
Simply add a metadata mentioning this is a valid OGV file. This is
useful because OGV cannot be simply detected by MimeType as it shares
the same mime with OGG.
:return: dict with the keys:
| - Composite:FileFormat - 'ogv'
"""
return {'Composite:FileFormat': 'ogv'}
|
ZeitOnline/zeit.newsletter | src/zeit/newsletter/browser/edit.py | Python | bsd-3-clause | 2,579 | 0 | from zeit.cms.i18n import MessageFactory as _
from zope.cachedescriptors.property import Lazy as cachedproperty
import os.path
import zeit.cms.browser.view
import zeit.cms.content.interfaces
import zeit.cms.interfaces
import zeit.content.image.interfaces
import zeit.content.video.interfaces
import zeit.edit.browser.for... | content.thumbnail
images = zeit.content.image.interfaces.IImages(content, None)
if images is None:
preview = zope.component.queryMultiAdapter(
(content, self.request), name='preview')
if preview:
| return self.url(preview)
return
if not images.image:
return
group = images.image
for name in group:
basename, ext = os.path.splitext(name)
if basename.endswith('148x84'):
image = group[name]
return self.url(ima... |
bw4sz/DeepMeerkat | training/Detection/object_detection/trainer_test.py | Python | gpl-3.0 | 6,550 | 0.00229 | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | puts. Returns an image with one box."""
image = tf.random_uniform([32, 32, 3], dtype=tf.float32)
class_label = tf.random_uniform(
[1], minval=0, maxval=NUMBER_OF_CLASSES, dtype=tf | .int32)
box_label = tf.random_uniform(
[1, 4], minval=0.4, maxval=0.6, dtype=tf.float32)
return {
fields.InputDataFields.image: image,
fields.InputDataFields.groundtruth_classes: class_label,
fields.InputDataFields.groundtruth_boxes: box_label
}
class FakeDetectionModel(model.DetectionM... |
paulmartel/voltdb | lib/python/vdm/tests/server/deployment_user_test.py | Python | agpl-3.0 | 12,365 | 0.003316 | # This file is part of VoltDB.
# Copyright (C) 2008-2016 VoltDB Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later ver... | nistrator", "databaseid": 1}
response = requests.post(user_url, json=db_data, headers=headers)
value = response.json()
self.assertEqual(value['statusString'], u'user name already exists')
self.assertE | qual(response.status_code, 404)
else:
print "The database list is empty"
def test_validate_username_empty(self):
"""ensure username value is not empty"""
db_data = {"password": "voltdb", "plaintext": True, "roles": "Administrator", "databaseid": 1}
headers = {'Content-T... |
homeworkprod/byceps | tests/integration/blueprints/admin/orga_team/test_team_views.py | Python | bsd-3-clause | 4,119 | 0.000243 | """
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
from byceps.services.orga_team import service as orga_team_service
from byceps.services.party import service as party_service
from tests.helpers import create_party
def test_tea | ms_for_party(orga_team_admin_client, party):
url = f'/admin/orga_teams/teams/{party.id}'
response = orga_team_admin_client.get(url)
assert response.status_code == 200
def test_team_create_form(orga_team_admin_client, party):
url = f'/admin/orga_teams/teams/{party.i | d}/create'
response = orga_team_admin_client.get(url)
assert response.status_code == 200
def test_team_create_and_delete(orga_team_admin_client, party):
assert orga_team_service.count_teams_for_party(party.id) == 0
url = f'/admin/orga_teams/teams/{party.id}'
form_data = {'title': 'Support'}
r... |
smcmahon/beatbox | setup.py | Python | gpl-2.0 | 672 | 0.046131 |
from setuptools import set | up
setup(name='beatbox',
version='20.1', # be sure to update the version in _beatbox.py too
package_dir={'': 'src'},
packages=['beatbox'],
author = "Simon Fell et al",
author_email = 'plonesf@googlegroups.com',
description = "A Python library for querying/updating Saleforce.com data via SOAP AP... | ad() + "\n" + open('CHANGES.txt').read(),
license = "GNU GENERAL PUBLIC LICENSE Version 2",
keywords = "python salesforce salesforce.com",
url = "http://code.google.com/p/salesforce-beatbox/",
classifiers = ["Development Status :: 5 - Production/Stable"]
)
|
apple/swift | utils/build_swift/tests/build_swift/test_defaults.py | Python | apache-2.0 | 4,351 | 0 | # This source file is part of the Swift.org open source project
#
# Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See https://swift.org/LICENSE.txt for license information
# See https://swift.org/CONTRIBUTORS.txt for the list o... | ------------------------------
# _default_swift_lto_link_jobs
@utils.requires_module('unittest.mock')
def test_default_swift_lto_link_jobs(self):
with mock.patch.object(defaults, '_system_memory') as mock_memory:
mock_memory.return_value = _SYSCTL_HW_MEMSIZE
lto_link_jobs =... | @utils.requires_module('unittest.mock')
def test_default_swift_lto_link_jobs_with_unknown_system_memory(self):
with mock.patch.object(defaults, '_system_memory') as mock_memory:
mock_memory.return_value = None
self.assertIsNone(defaults._default_llvm_lto_link_jobs())
|
AlexeyKruglov/Skeinforge-fabmetheus | skeinforge_application/skeinforge_plugins/craft_plugins/preface.py | Python | agpl-3.0 | 10,703 | 0.019434 | #! /usr/bin/env python
"""
This page is in the table of contents.
Preface converts the svg slices into gcode extrusion layers, optionally with home, positioning, turn off, and unit commands.
The preface manual page is at:
http://fabmetheus.crsndoo.com/wiki/index.php/Skeinforge_Preface
==Settings==
===Meta===
Default ... | a = settings.StringSetting().getFromValue('Meta:', self, '')
self.setPositioningToAbsolute = settings.BooleanSetting().getFromValue('Set Positioning to Absolute', self, True )
self.setUnitsToMillimeters = settings.BooleanSetting().getFromValue('Set Units to Millimeters', self, True )
self.startAtHome = settings.B... | parator().getFromRepository(self)
settings.LabelDisplay().getFromName('- Turn Extruder Off -', self )
self.turnExtruderOffAtShutDown = settings.BooleanSetting().getFromValue('Turn Extruder Off at Shut Down', self, True )
self.turnExtruderOffAtStartUp = settings.BooleanSetting().getFromValue('Turn Extruder Off at ... |
dcodix/mv-elsewhere | mv-elsewhere.py | Python | gpl-2.0 | 5,068 | 0.00513 | #! /usr/bin/env python
# Copyright (C) 2012 dcodix
# This file may be distributed and/or modified under the terms of
# the GNU General Public License version 2 as published by
# the Free Software Foundation.
# This file is distributed without any warranty; without even the implied
# warranty of merchantability or fi... | y to read files directly from a file instead of stdin.
file1 = sys.stdin.readline()
if not file1:
break
file1 = file1.rstrip()
debugmessage('file '+file1)
fpath = os.path.dirname(file1)
if len(fpath) == 0:
fpath = file1
if debuging:
... | ude in file1:
excludefile = True
debugmessage('file '+file1+' will be excluded')
dfile = dst + '/' + file1
dpath = dst + '/' + fpath
if not os.path.isdir(dpath):
verbosemessage('COPYNG TREE: from '+fpath+' to '+dpath)
copydirtree(fp... |
sxjscience/tvm | python/tvm/contrib/xcode.py | Python | apache-2.0 | 7,815 | 0.000896 | # 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... | o 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 gov | erning permissions and limitations
# under the License.
# pylint: disable=invalid-name
"""Utility to invoke Xcode compiler toolchain"""
from __future__ import absolute_import as _abs
import os
import sys
import subprocess
import json
from .._ffi.base import py_str
from . import util
def xcrun(cmd):
"""Run xcrun ... |
mkeilman/sirepo | tests/auth/guest1_test.py | Python | apache-2.0 | 1,794 | 0.000557 | # -*- coding: utf-8 -*-
u"""Test auth.guest
:copyright: Copyright (c) 2019 RadiaSoft LLC. All Rights Reserved.
:license: http://www.apache.org/licenses/LICENSE-2.0.html
"""
from __future__ import absolute_import, division, print_function
import pytest
def test_happy_path(auth_fc):
fc = auth_fc
from pykern... | c.sr_get('authGuestLogin', {'simulation_type': fc.sr_sim_type}, redirect=False)
pkeq(200, r.status_code)
d = pkjson.load_any(r.data)
pkeq(True, d.authState.isLogge | dIn)
fc.sr_post('listSimulations', {'simulationType': fc.sr_sim_type})
fc.sr_auth_state(
isGuestUser=True,
isLoggedIn=True,
isLoginExpired=False,
)
fc.sr_get_json('adjustTime', params={'days': '2'})
fc.sr_auth_state(
isGuestUser=True,
isLoggedIn=True,
... |
tdickers/mitmproxy | netlib/tutils.py | Python | mit | 3,536 | 0.000848 | from io import BytesIO
import tempfile
import os
import time
import shutil
from contextlib import contextmanager
import six
import sys
from netlib import utils, tcp, http
def treader(bytes):
"""
Construct a tcp.Read object from bytes.
"""
fp = BytesIO(bytes)
return tcp.Reader(fp)
@contextma... | six.reraise(AssertionError, AssertionError(
"Expected %s, but caught %s %s" % (
| expected.__name__, actual.__class__.__name__, repr(actual)
)
), exc_tb)
def raises(expected_exception, obj=None, *args, **kwargs):
"""
Assert that a callable raises a specified exception.
:exc An exception class or a string. If a class, assert that an
excepti... |
ChromiumWebApps/chromium | build/android/pylib/base/test_dispatcher_unittest.py | Python | bsd-3-clause | 7,737 | 0.007496 | # Copyright 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.
"""Unittests for test_dispatcher.py."""
# pylint: disable=R0201
# pylint: disable=W0212
import os
import sys
import unittest
sys.path.append(os.path.join(o... |
self.assertEqual(runner.teardowns, 1)
| def testRetry(self):
runners = test_dispatcher._CreateRunners(MockRunnerFail, ['0', '1'])
results, exit_code = test_dispatcher._RunAllTests(
runners, self.test_collection_factory, 0)
self.assertEqual(len(results.GetFail()), len(self.tests))
self.assertEqual(exit_code, constants.ERROR_EXIT_CODE... |
google-research/long-range-arena | lra_benchmarks/models/longformer/longformer.py | Python | apache-2.0 | 13,102 | 0.001679 | # Copyright 2021 Google LLC
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# https://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, sof... | sal attention masking.
inputs_positions: input subsequence positions for packed examples.
inputs_segmentation: input segmentation info for packed examples.
shared_embedding: a shared em | bedding layer to use.
use_bfloat16: bool: whether use bfloat16.
emb_dim: dimension of embedding
num_heads: number of heads
dtype: the dtype of the computation (default: float32)
num_layers: number of layers
qkv_dim: dimension of the query/key/value
mlp_dim: dimension of the mlp... |
ravenac95/testkit | tests/test_context.py | Python | mit | 2,056 | 0.002432 | from testkit.context import *
def test_context_user():
from contextlib import contextmanager
test_dict = dict(value='before')
@contextmanager
def test_context(test_dict):
test_dict['value'] = 'during'
yield 'test'
test_dict['value'] = 'after'
ctx = ContextUser(test_context... | def after(self):
self.done = True
def test_context_decorator_as_decorator():
as_decorator = my_context()
@as_decorator
def hello(context):
assert context.hello == 'hello'
hello()
assert as_decorator.done == True
def test_context_decorator_as_decorator_exception():
as_dec... | def hello(context):
raise Exception(fake_message)
try:
hello()
except Exception, e:
assert e.message == fake_message
assert as_decorator.done == True
def test_context_decorator_as_context():
as_context = my_context()
with as_context as context:
assert context.he... |
gvalkov/git-link | tests/test_gitweb.py | Python | bsd-3-clause | 2,301 | 0.00565 | #!/usr/bin/env python
# encoding: utf-8
from util import *
res = [
# commit
('90f02cb510335a5bfdb57f0c78915d5ac236013c',
'http://git.naquadah.org/?p=oocairo.git;a=commitdiff;h=90f02cb510335a5bfdb57f0c78915d5ac236013c'),
# tree
('90f02cb510335a5bfdb57f0c78915d5ac236013c^{tree}',
'http://git.... | d2ab'
@p | ytest.fixture
def gitlink(request):
return mk_gitlink(url, 'gitweb', 'gitweb', linkurl, headrev)
@mark.parametrize(('cmdargs', 'expect'), res)
def test_gitweb_auto_lib(gitlink, cmdargs, expect):
assert gitlink[0](cmdargs) == expect
assert validate_url_404(expect)
@skipif_no_gitlink
@mark.parametrize(('cm... |
saurabh6790/frappe | frappe/core/doctype/role/role.py | Python | mit | 2,874 | 0.02366 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document impo | rt Document
desk_properties = ("search_bar", "notifications", "chat", "list_sidebar",
"bulk_actions", "view_switcher", "form_sidebar", "timeline", "dashboard")
class Role(Document):
def before_rename(self, old, new, merge=False):
if old in ("Guest", "Administrator", "System Manager", "All"):
frappe.throw(frapp... | disabled:
self.disable_role()
else:
self.set_desk_properties()
def disable_role(self):
if self.name in ("Guest", "Administrator", "System Manager", "All"):
frappe.throw(frappe._("Standard roles cannot be disabled"))
else:
self.remove_roles()
def set_desk_properties(self):
# set if desk_access is... |
ciappi/Yaranullin | yaranullin/config.py | Python | isc | 2,801 | 0.000357 | # yaranullin/config.py
#
# Copyright (c) 2012 Marco Scopesi <marco.scopesi@gmail.com>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS... | F CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
"""Global configuration."""
import os
import sys
import ConfigParser
import platf | orm
# Global information
__version__ = '0.5.0'
__platform__ = platform.system()
# Check home folder
if 'HOME' not in os.environ:
if __platform__ == 'Windows':
HOME_DIR = os.path.join(os.environ['HOMEDRIVE'],
os.environ['HOMEPATH'])
else:
sys.exit('Cannot find home folder')
else:
... |
g0tmi1k/veil-Evasion | modules/payloads/python/shellcode_inject/base64_substitution.py | Python | gpl-3.0 | 16,041 | 0.00374 | """
This payload receives the msfvenom shellcode, base64 encodes it, and stores it within the payload.
At runtime, the executable decodes the shellcode and executes it in memory.
module by @christruncer
"""
import base64
from datetime import date
from datetime import timedelta
from modules.common import shellcod... | ate Random Variable Names
ShellcodeVariableName = helpers.randomString()
RandPtr = helpers.randomString()
| RandBuf = helpers.randomString()
RandHt = helpers.randomString()
RandT = helpers.randomString()
randctypes = helpers.randomString()
PayloadCode = 'import ctypes as ' + randctypes + '\n'
PayloadCode += 'import base64\n'
... |
fabianvaccaro/pygums | pythonLibs/mahotas-1.1.0/mahotas/internal.py | Python | gpl-2.0 | 5,299 | 0.003963 | # Copyright (C) 2011-2012, Luis Pedro Coelho <luis@luispedro.org>
# vim: set ts=4 sts=4 sw=4 expandtab smartindent:
#
# License: MIT (see COPYING file)
import numpy as np
def _get_output(array, out, fname, dtype=None, output=None):
'''
output = _get_output(array, out, fname, dtype=None, output=None)
Imple... | ]
if A.dtype not in int_typ | es:
raise TypeError('mahotas.%s: This function only accepts integer types (passed array of type %s)' % (function_name, A.dtype))
def _make_binary(array):
'''
bin = _make_binary(array)
Returns (possibly a copy) of array as a boolean array
'''
array = np.asanyarray(array)
if array.dtype ... |
abhi-bit/memcache-queue | benchmark.py | Python | mit | 1,075 | 0.008372 | from memqueue import MemQueue
import sys, time
import memcache
from optparse import OptionParser
client = ['127.0.0.1:11211']
queue = M | emQueue('benchmark', memcache.Client(client))
start = time.time()
if __name__ == '__main__':
parser = OptionParser(usage="usage: %prog [options] filename",
version="%prog 0.1")
parser.add_option("-a", "--add", dest="add", | default='notAdd', help="add keys to queue")
parser.add_option("-r", "--read", dest="read", default='notRead', help="read from queue")
parser.add_option("-c", "--count", dest="count", default='1000', type='int', help="no. of keys to read/add")
(options, args) = parser.parse_args()
add = options.add
... |
socialdevices/manager | profiler/management/commands/plotprofilingstats.py | Python | bsd-3-clause | 1,441 | 0.004858 | from django.core.management.base import NoArgsCommand, CommandError
from profiler.db import ProfilerDatabase
from profiler.plotter import StatsPlotter
import time
class Command(NoArgsCommand):
help = 'Creates graphs based on profiling statistics.'
can_import_settings = True
def handle_noargs(self, **o... | ler_group_run = profiler_group_runs[profiler_group_run_index]
try:
| start_time = time.time()
dir_name = '%s_%s' % (profiler_group_run['name'], profiler_group_run['started'])
plotter = StatsPlotter()
plotter.plot(profiler_group_run['id'], dir_name)
except KeyboardInterrupt:
plotter.stop()
self.stdout.write('\nPlot... |
egabancho/invenio-communities | docs/conf.py | Python | gpl-2.0 | 10,685 | 0.005335 | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2015 CERN.
#
# Invenio 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... | ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = Fals... | ------------------
on_rtd = os.environ.get('READTHEDOCS', None) == 'True'
# only set the theme when we are not on RTD
if not on_rtd:
try:
import sphinx_rtd_theme
html_theme = "sphinx_rtd_theme"
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
except ImportError:
print(... |
ProgDan/maratona | Maratona_Python/OBI2013/tomadas.py | Python | gpl-3.0 | 140 | 0.014286 | #!/ | usr/bin/python
#coding: utf-8
T1, T2, T3, T4 = map(int,input().split())
s = int(T1) + int(T2) + int(T3) + int(T4) - 3
print(s)
exit(0 | )
|
open-ods/open-ods | openods/request_utils.py | Python | gpl-3.0 | 1,400 | 0.004286 | import uuid
from flask import g
# Utility method to get source_ip from a request - first checks headers for forwarded IP, then uses remote_addr if not
def get_source_ip(my_request):
try:
# First check for an X-Forwarded-For header provided by a proxy / router e.g. on Heroku
source_ip = my_request.... | orwarded-For']
except KeyError:
try:
# First check for an X-Forwarded-For header provided by a proxy / router e.g. on Heroku
source_ip = my_request.head | ers['X-Client-IP']
except KeyError:
# If that header is not present, attempt to get the Source IP address from the request itself
source_ip = my_request.remote_addr
g.source_ip = source_ip
return source_ip
# Utility method to get the request_id from the X-Request-Id header, a... |
m-garanin/conference | urls.py | Python | bsd-3-clause | 526 | 0.007605 | from django.conf.urls.defaults import patterns, include, url
from django.conf import settings
from django.contrib import admin
admin.autodiscover()
urlpatterns = patte | rns('',
url(r'^admin/', include(admin.site.urls)),
(r'^site_media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}),
(r'^storage/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings. | MEDIA_ROOT}),
url(r'', include('mbco.conference.app.urls')),
url(r'^', include('cms.urls')),
)
|
acourt/doortracker | doorreport/doorlogger/models.py | Python | gpl-3.0 | 531 | 0.035782 | from django.db import models
from datetime import datetime
class Door(models.Model):
door_name = models.CharField(max_length=144)
door_type = models.CharField(max_length=35)
def __str__(self):
return self.door_name
class Event(models.Model | ):
door = models.ForeignKey(Door, on_delete=models.CASCADE)
event_type = models.CharField(max_length=20)
open_level = models.IntegerField(default=0)
ti | me_stamp = models.DateTimeField('time stamp')
def __str__(self):
return ("%s: %d" % (self.event_type, self.open_level)) |
KrzysiekJ/django-getpaid | getpaid/utils.py | Python | mit | 1,875 | 0.002133 | from django.conf import settings
import sys
def import_name(name):
components = name.split('.')
if len(components) == 1:
# direct module, import the module directly
mod = __import__(name, globals(), locals(), [name])
else:
# the module is within another, so we
# need to im... | '%s.%s' % (fqmn, submodule)
__import__(fqmn)
module = sys.modules[fqmn]
modules[backend_name] = module
return modules
def get_backend_choices(currency=None):
"""
Get active backends modules. Backend list can be filtered by supporting given currency.
"""
choices = []
bac... | getattr(settings, 'GETPAID_BACKENDS', [])
for backend_name in backends_names:
backend = import_name(backend_name)
if currency:
if currency in backend.PaymentProcessor.BACKEND_ACCEPTED_CURRENCY:
choices.append((backend_name, backend.PaymentProcessor.BACKEND_NAME, ))
... |
pravinas/et-maslab-2016 | sandbox/test_hugs.py | Python | mit | 2,236 | 0.00805 | from tamproxy import SyncedSketch, Timer
from tamproxy.devices import Motor, Encoder
# Cycles a motor back and forth between -255 and 255 PWM every ~5 seconds
HUGS_MOTOR_CONTROLLER_DIRECTION = 8
HUGS_MOTOR_CONTROLLER_PWM = 9
HUGS_MOTOR_ENCODER_YELLOW = 31
HUGS_MOT | OR_ENCODER_WHITE = 32
# The limit point at which the motor is considered stalled.
INTAKE_ENCODER_LIMIT = 150
# The speed of the intake motors.
INTAKE_POWER = 120
class HugTest(SyncedSketch):
def setup(self):
# Motor object representing the intake mechanism motors.
self.in... | GS_MOTOR_CONTROLLER_DIRECTION, HUGS_MOTOR_CONTROLLER_PWM)
# Encoder object for the intake motor.
self.intakeEncoder = Encoder(self.tamp, HUGS_MOTOR_ENCODER_YELLOW, HUGS_MOTOR_ENCODER_WHITE)
# Timer object to moderate checking for intake errors.
self.intakeTimer = Timer()
# Are th... |
georgeyk/quickstartup | quickstartup/website/urls.py | Python | mit | 158 | 0.006329 | # coding: utf-8
from django.conf.urls import p | atterns, url
urlpatterns = patterns('',
| url(r"^$", "quickstartup.website.views.index", name="index"),
)
|
skagedal/fido | experiments/test.py | Python | gpl-2.0 | 3,542 | 0.008752 | from __future__ import print_function
import sqlite3
import time
from datetime import datetime
def adapt_datetime(ts):
return int(time.mktime(ts.timetuple()))
sqlite3.register_adapter(datetime, adapt_datetime)
def pp(cursor, data=None, rowlens=0):
d = | cursor.description
if not d:
return "#### NO RESULTS ###"
names = []
lengths = []
rules = []
if not data:
data = cursor.fetchall()
for dd in d: # iterate over description
l = dd[1]
if not l:
l = 12 # or default arg ...
l = max(l, | len(dd[0])) # handle long names
names.append(dd[0])
lengths.append(l)
for col in range(len(lengths)):
if rowlens:
rls = [len(str(row[col])) for row in data if row[col]]
lengths[col] = max([lengths[col]]+rls)
rules.append("-"*lengths[col])
format = " ".joi... |
kscharding/integral-solutions-smxq | codereview/models.py | Python | apache-2.0 | 28,836 | 0.01082 | # Copyright 2008 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 writing, ... | .ListProperty(db.Email)
cc = db.ListProperty(db.Email)
closed = db.BooleanProperty(default=False)
private = db.BooleanProperty(default=False)
n_comme | nts = db.IntegerProperty()
_is_starred = None
@property
def is_starred(self):
"""Whether the current user has this issue starred."""
if self._is_starred is not None:
return self._is_starred
account = Account.current_user_account
self._is_starred = account is not None and self.key().id() in... |
corumcorp/redsentir | redsentir/lineatiempo/views.py | Python | gpl-3.0 | 2,842 | 0.017241 | # -*- coding: utf-8 -*-
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from .models import *
@login_required
def inicio(request):
if not request.user.perfil.es_joven and not request.user.is_superuser:
return redirect('mesa:inicio')
if request.POS... | comentario.imagen = request.FILES['imagen_c' | ]
if 'contenido' in request.POST :
comentario.contenido = request.POST['contenido']
comentario.save()
Publicacion.objects.filter(pk=comentario.publicacion_id).update(comentarios=(comentario.publicacion.comentarios+1))
elif 'accion' ... |
andersonjonathan/Navitas | navitas/contact/models.py | Python | mit | 391 | 0 | f | rom django.db import models
from django.utils.translation import ugettext_lazy as _
class Contact(models.Model):
name = models.CharField(max_length=255, verbose_name=_("namn"))
email = models.EmailField(verbose_name=_("e-post"))
def __s | tr__(self):
return self.name
class Meta:
verbose_name = _("Kontaktval")
verbose_name_plural = _("Kontaktval")
|
samatdav/zulip | bots/zephyr_mirror_backend.py | Python | apache-2.0 | 48,314 | 0.002235 | #!/usr/bin/env python
# Copyright (C) 2012 Zulip, Inc.
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, m... | 5 seconds), but
# it's worth doing 1 retry immediately to avoid
# missing 15 seconds of messages on the affected
# classes
zephyr._z.sub(cls, instance, recipient)
except IOError:
pass
else:
| current_zephyr_subs.add(cls)
def update_subscriptions():
# type: () -> None
try:
f = open(options.stream_file_path, "r")
public_streams = simplejson.loads(f.read())
f.clos |
varunarya10/tempest | tempest/scenario/test_shelve_instance.py | Python | apache-2.0 | 4,194 | 0 | # Copyright 2014 Scality
# 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... | 64e700-0af0-4a4c-8792-35909a88743c')
@testtools.skipUnless(CONF.compute_feature_enabled.shelve,
'Shelve is not available.')
@test.services('compute', 'network', 'image')
def test_shelve_instance(self):
self.keypair = self.create_keypair()
self.security_group = self... | te_kwargs = {
'key_name': self.keypair['name'],
'security_groups': security_groups
}
server = self.create_server(image=CONF.compute.image_ref,
create_kwargs=create_kwargs)
if CONF.compute.use_floatingip_for_ssh:
floating_ip... |
tfroehlich82/EventGhost | plugins/EventGhost/ShowOSD.py | Python | gpl-2.0 | 17,182 | 0 | # -*- coding: utf-8 -*-
#
# This file is part of EventGhost.
# Copyright © 2005-2020 EventGhost Project <http://www.eventghost.net/>
#
# EventGhost 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 versio... | #
# You should have received a copy of the GNU General Public License along
# with EventGhost. If not, | see <http://www.gnu.org/licenses/>.
import threading
from os import listdir
from os.path import abspath, dirname, join
import wx
import eg
from eg.WinApi.Dynamic import (
CreateEvent,
SetEvent,
SetWindowPos,
SWP_FRAMECHANGED,
SWP_HIDEWINDOW,
SWP_NOACTIVATE,
SWP_NOOWNERZORDER,
SWP_SHO... |
oleg-shilo/sublime-codemap | custom_mappers/ts.py | Python | mit | 5,302 | 0.004715 | # Custom mapper sample for CodeMap plugin
# This script defines a mandatory `def generate(file)` and module attribute map_syntax:
# - `def generate(file)`
# The routine analyses the file content and produces the 'code map' representing the content structure.
# In this case it builds the list of sections (lines th... | if content_type != last_type:
extra_line = '\n'
elif content_type == 'class' or content_type == 'interface':
extra_line = '\n'
preffix = str_of(indent, ' ')
lean_content = content[in | dent:]
suffix = str_of(item_max_length-len(content), ' ')
map = map + extra_line + preffix + lean_content + suffix +' :'+str(line) +'\n'
last_indent = indent
last_type = content_type
# print(map)
return map |
arielalmendral/ert | python/tests/core/util/test_hash.py | Python | gpl-3.0 | 1,507 | 0 | from ctypes import c_void_p
from ert.test import ExtendedTestCase
from ert.util import Hash, StringHash, DoubleHash, IntegerHash
class HashTest(ExtendedTestCase):
def test_string_hash(self):
hash = StringHash()
self.assertEqual(len(hash), 0)
hash["hipp"] = ""
self.assertEqual(l... | with self.assertRaises(KeyError):
hopp = hash["hopp"]
self.assertTrue("hipp" in hash)
self.assertEqual(list(hash.keys()), ["hipp"])
def test_int_hash(self):
hash = IntegerHash()
with self.assertRaises(ValueError):
hash["one"] = "ein"
with ... | ["two"] = 2
self.assertEqual(hash["two"], 2)
def test_double_hash(self):
hash = DoubleHash()
with self.assertRaises(ValueError):
hash["one"] = "ein"
hash["two"] = 2
hash["three"] = 3.0
self.assertEqual(hash["two"], 2)
self.assertEqual(hash["th... |
linkleonard/lib-python | outbound/__init__.py | Python | mit | 12,217 | 0.003765 | import sys
import json
from numbers import Number
import time
import requests
import version
__BASE_URL = "https://api.outbound.io/v2"
this = sys.modules[__name__]
ERROR_INIT = 1
ERROR_USER_ID = 2
ERROR_EVENT_NAME = 3
ERROR_CONNECTION = 4
ERROR_UNKNOWN = 5
ERROR_TOKEN = 6
APNS = "apns"
GCM = "gcm"
def init(key):... | ge.
:param func on_success: An optional function to call if/when the API call succeeds.
on_success callback takes no parameters.
"""
on_error = on_error or __on_error
on_success = on_success or __on_success
if not hasattr(this, '__HEADERS'):
on_error(ERROR_INIT, __error_mess | age(ERROR_INIT))
return
if not isinstance(user_id, (basestring, Number)):
on_error(ERROR_USER_ID, __error_message(ERROR_USER_ID))
return
if not isinstance(event, basestring):
on_error(ERROR_EVENT_NAME, __error_message(ERROR_EVENT_NAME))
return
data = dict(user_id=us... |
RPGOne/Skynet | pytorch-master/torch/nn/modules/batchnorm.py | Python | bsd-3-clause | 6,848 | 0.00219 | import torch
from .module import Module
from torch.nn.parameter import Parameter
from .. import functional as F
# TODO: check contiguous in THNN
# TODO: use separate backend functions?
class _BatchNorm(Module):
def __init__(self, num_features, eps=1e-5, momentum=0.1, affine=True):
super(_BatchNorm, self)... | m1d(100, affine=False)
>>> | input = autograd.Variable(torch.randn(20, 100))
>>> output = m(input)
"""
def _check_input_dim(self, input):
if input.dim() != 2 and input.dim() != 3:
raise ValueError('expected 2D or 3D input (got {}D input)'
.format(input.dim()))
super(BatchNor... |
emgirardin/compassion-modules | message_center_compassion/mappings/__init__.py | Python | agpl-3.0 | 467 | 0 | # -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2015 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emanuel Cino <ecino@compassion.ch>
#
# The licence is i | n the file __openerp__.py
#
############################################################## | ################
from . import base_mapping
from . import advanced_query_mapping
|
ewanbarr/UtmostFanbeamMapper | map_maker.py | Python | apache-2.0 | 4,128 | 0.018411 | from astropy.io import fits
from astropy.wcs import WCS
import numpy as np
class RADecMap(object):
def __init__(self,extent,nra,ndec):
"""
Container for equatorial maps.
extent: extent of map [ra0,ra1,dec0,dec1]
nra: sampling in ra
ndec: sampling in dec
"""
... | ent | re in NS axis.
ns_offsets: scalar or array of offsets
"""
fwhm = np.radians(2.0)
sigma = fwhm/2.355
return 1/gaussian(ns_offsets,0.0,sigma)
def fanbeam_model(ns_offsets,ew_offsets):
ns_fwhm = np.radians(2.0)
ns_sigma = ns_fwhm/2.355
ew_fwhm = np.radians(41/3600.0)
ew_sigma = ew_fwhm... |
dragoon/kilogram | kilogram/dataset/edit_histories/wikipedia/__init__.py | Python | apache-2.0 | 427 | 0 | import re
END_SENTENCE | _RE = re.compile(r'\s[.?!]\s(?=[^a-z])')
def line_filter(line):
sentences = END_SENTENCE_RE.split(line)
last = len(sentences) - 1
for i, sentence in enumerate(sentences):
if not sentence.strip():
continue
if i == last and not sentence.endswith('.'):
continue
... | sentence += ' .'
yield sentence
|
GoogleCloudPlatform/cloud-opensource-python | compatibility_server/loadtest/locustfile.py | Python | apache-2.0 | 2,473 | 0 | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | query = urllib.parse.urlencode(
{'python-version': '2',
'package': random.choice(PYTHON2_PACKAGES)})
self.client.get('/?%s' % query)
@locust.task
def single_python3(self):
query = urllib.parse.urlencode(
{'python-version': '3',
'package': rand... | ouble_python2(self):
package1 = random.choice(PYTHON2_PACKAGES)
package2 = random.choice(list(set(PYTHON2_PACKAGES) - {package1}))
query = urllib.parse.urlencode([('python-version', '2'),
('package', package1),
('pa... |
d1m0/browser_bench | build_worksheet.py | Python | mit | 4,846 | 0.026826 | #! /usr/bin/env python
import gspread
import argparse
from format import *
import sys
from stats import getMean
import pdb
import json
from oauth2client.client import SignedJwtAssertionCredentials
from gsheets import openSS, Table, putRawTable
p = argparse.ArgumentParser(description=\
"Given a set of runs for severa... | n(colNames))]
if (baseline):
meanOverPerRow = [('=({0}-{1})*100.0/{1}' if col_benchmark(c) != 'octane' else '=({1}-{0})*100.0/{1}').format(\
resTbl.cellLbl('Mean', cname(c)), \
resTbl.cellLbl('Mean', col_ben | chmark(c) + ',' + baseline)) \
for c in resCols]
stdevOverPerRow = ['=sqrt({0}*{0}+{1}*{1})*100.0/{2}'.format(\
resTbl.cellLbl('Std. Dev.', cname(c)),
resTbl.cellLbl('Std. Dev.', col_benchmark(c) + ',' + baseline),
resTbl.cellLbl('Mean', col_benchmark(c) + ',' + baseline))
for c in... |
cbertinato/pandas | pandas/tests/io/excel/test_writers.py | Python | bsd-3-clause | 47,648 | 0.000021 | from datetime import date, datetime, timedelta
from functools import partial
from io import BytesIO
import os
import numpy as np
from numpy import nan
import pytest
from pandas.compat import PY36
import pandas.util._test_decorators as td
import pandas as pd
from pandas import DataFrame, Index, MultiIndex, get_option... | "ext", ['.xls', '.xlsx', '.xlsm'])
class TestRoundTrip:
@td.skip_if_no("xlwt")
@td.skip_if_no("openpyxl")
@pytest.mark.parametrize("header,expected", [
(None, DataFrame([np.nan] | * 4)),
(0, DataFrame({"Unnamed: 0": [np.nan] * 3}))
])
def test_read_one_empty_col_no_header(self, ext, header, expected):
# xref gh-12292
filename = "no_header"
df = pd.DataFrame(
[["", 1, 100],
["", 2, 200],
["", 3, 300],
["",... |
nmercier/linux-cross-gcc | win32/bin/Lib/sysconfig.py | Python | bsd-3-clause | 23,180 | 0.001726 | """Provide access to Python's configuration information.
"""
import sys
import os
from os.path import pardir, realpath
_INSTALL_SCHEMES = {
'posix_prefix': {
'stdlib': '{base}/lib/python{py_version_short}',
'platstdlib': '{platbase}/lib/python{py_version_short}',
'purelib': '{ba... | 'include': '{base}/include/python',
'platinclude': '{base}/include/python',
'scripts': '{base}/bin',
'data' : '{base}',
},
'nt': {
'stdlib': '{base}/Lib',
'platstdlib': '{base}/Lib',
'purelib': '{base}/Lib/site-packages',
'platlib': '{ba... | 'data' : '{base}',
},
'os2': {
'stdlib': '{base}/Lib',
'platstdlib': '{base}/Lib',
'purelib': '{base}/Lib/site-packages',
'platlib': '{base}/Lib/site-packages',
'include': '{base}/Include',
'platinclude': '{base}/Include',
'scripts': '{base}... |
catapult-project/catapult | third_party/gsutil/gslib/commands/hmac.py | Python | bsd-3-clause | 13,530 | 0.003991 | # -*- coding: utf-8 -*-
# Copyright 2019 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 require... | te GOOG56JBMFZX6PMPTQ62VD2
Note that keys must be updated to be in the ``INACTIVE`` state before they can be
deleted.
<B>DELETE OPTIONS< | /B>
The "delete" sub-command has the following option
-p <project_id> Specify a project from which to delete a key.
"""
_GET_DESCRIPTION = """
<B>GET</B>
The ``hmac get`` command retrieves the specified HMAC key's metadata:
gsutil hmac get GOOG56JBMFZX6PMPTQ62VD2
Note that there is no option... |
octaflop/django_music | apps/web_app/forms.py | Python | mit | 240 | 0 | from django import forms
class SongForm(forms.Form):
| track = | forms.IntegerField(label='Track', required=False)
title = forms.CharField(label='Title')
duration = forms.CharField(label='Duration', max_length=15, required=False)
|
mangaki/mangaki | mangaki/mangaki/migrations/0081_merge_20170720_1125.py | Python | agpl-3.0 | 350 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-07-20 11:25
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('mangaki', '0080_ | auto_20170719_0511'),
('mangaki', '0080_save_studi | o_and_editor_on_work'),
]
operations = [
]
|
platformio/platformio | tests/test_misc.py | Python | apache-2.0 | 1,489 | 0 | # Copyright (c) 2014-present PlatformIO <contact@platformio.org>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
# |
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under t | he License.
import pytest
import requests
from platformio import exception, util
def test_platformio_cli():
result = util.exec_command(["pio", "--help"])
assert result["returncode"] == 0
assert "Usage: pio [OPTIONS] COMMAND [ARGS]..." in result["out"]
def test_ping_internet_ips():
for host in util... |
tztztztztz/SYMLeaveRequestServer | service/appsetting.py | Python | mit | 528 | 0.001894 | from config import config
class AppSetting(object):
def __init__(self):
self.config = config.config
def get_password(self):
return self.config['app']['auth_password']
def change_password(self, oldpassword, newpassword):
if oldpassword != self.get_password():
| return None, 'password is not correct'
self.set_password(newpassword)
return [], None
def set_password(self, password):
self.config['app']['auth_pa | ssword'] = password
config.save()
|
harinisuresh/yelp-district-clustering | Map.py | Python | mit | 7,068 | 0.009479 | """Module for Map Class"""
from MapUtil | s import Position, Coordinate
from PIL import Image
from PIL import ImageFont, ImageDraw, ImageOps
class Map:
"""Map class for hanlding coordinate conversion and adding labels to map image."""
def __init__(self, top_left_coord, top_right_coord, bottom_left_coord, bottom_right_coord, image_path):
"""
... | coord - Coordinate Object representing the top right corner
bottom_left_coord - Coordinate Object representing the bottom left corner
bottom_right_coord - Coordinate Object representing the bottom right corner
image_path - path of the image of the map
Returns:
A Map object.
... |
eeue56/PyGeo2 | pygeo/examples/real/beziercurves.py | Python | gpl-2.0 | 2,623 | 0.032406 | from pygeo import *
explanation ="""Bezier curves are an interesting way to
visually explore issues related to permutations,
since unique curves are created by the same
control points provided in varying sequence to
the curve creation code"""
v=display(title="Bezier Permutations",scale=40,width=600,
axis=Fa... | e actual points are in | L, P is a list of sublists of
# permutated integers. P elements serve as
# indexes which select from the points contained in L.
for i in range(len(P)):
#create a list of points selected acccording to the indexes
#retrieved from the permsets function call
cp=[L[j] for j in P[i]]
# dr... |
DozyDolphin/Worksets | setup.py | Python | gpl-3.0 | 1,774 | 0.000564 | '''
Copyright 2017 Anders Lykke Gade
This file is part of Worksets.
Worksets 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 Foundatio | n, either version 3 of the License, or
(at your option) any later version.
Worksets 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 ha... | s import setup
from setuptools import find_packages
package_dir = path.abspath(path.dirname(__file__))
with open(path.join(package_dir, 'README.rst'), encoding='utf-8') as file:
long_description = file.read()
setup(
name='worksets',
version='0.1.1',
description='Worksets helps you to quickly launch... |
openturns/otsvm | python/test/t_NormalRBF_std.py | Python | lgpl-3.0 | 701 | 0 | #! /usr/bin/env python
from __future__ import print_function, division
from openturns import *
from otsvm import *
# instantiate a kernel=Gaussian with sigma = 2
kernel = NormalRBF(2)
x = Point(2, 2.0)
y = Point(2, 1.0)
print(" kernel ([2 2],[1 1]) = %.12g" % kernel(x, y))
print(" dkernel/dx_i([2 2],[1 1]) = ", repr... | ernel.partialGradient(x, y)))
print(" d2kernel/(dx_i*dx_j)([0 5],[0 3]) = ", repr(
kernel.partialHessian(x, y))) | |
juslop/angular-chat | django_chat/chat/models.py | Python | mit | 2,659 | 0.007522 | from django.db import models
from django.contrib.auth.models import User
from django.contrib import admin
import os
from PIL import Image
#http://javiergodinez.blogspot.fi/2008/03/square-thumbnail-with-python-image.html
def _thumbnail(img, size):
width, height = img.size
if width > height:
delta =... | n img
class Room(models.Model):
name = models.CharField(max_length=32)
createdBy = models.ForeignKey(User)
created = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return self.name
class Message(models.Model):
content = models.TextField(max_len | gth=1000)
responseTo = models.ForeignKey('Message', blank=True, null=True, related_name='responses')
room = models.ForeignKey(Room)
writer = models.ForeignKey(User)
created = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return self.content[:30]
class UserExtra(models.... |
moustakas/impy | projects/desi-archetypes/elg-archetypes.py | Python | gpl-2.0 | 1,011 | 0.004946 | """
Generate archetypes from the DESI ELG basis spectra.
"""
from __future__ import division, print_function
import os
import sys
import numpy as np
import argparse
import pdb
from astropy.io import fits
from astropy.table import Table
from SetCoverPy.mathutils import quick_amplitude
from desispec.log import get... | e = args.objtype.upper()
log.debug('Using OBJTYPE {}'.format(objtype))
baseflux, ba | sewave, basemeta = read_basis_templates(objtype=objtype)
pdb.set_trace()
|
siosio/intellij-community | python/testData/completion/fStringLikeCompletionNotAvailableInUnicodeLiterals.py | Python | apache-2.0 | 35 | 0.028571 | my_e | xpr = 42
s = u'foo{my_e<care | t>' |
davidsoncolin/IMS | IO/Command.py | Python | mit | 328 | 0.030488 | #!/usr/bin/env python
import ViconConnect
import IO
import zmq
import time
import sys
if __name__ == | '__main__' :
print sys.argv[1]
client = zmq.Context().socket(zmq.REQ)
client.connect('tcp://localhost:18666')
client.send(sys.argv[1])
print IO.unwrap(client.recv())
#for example:
#python Command.py current_frame | =-1
|
magic2du/dlnn | cmds2/run_CNN_SAT.py | Python | apache-2.0 | 5,839 | 0.010447 | # Copyright 2015 Tianchuan Du University of Delaware
# 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
#
# THIS CODE IS PROVIDED *AS IS* BAS... | train | _data_spec = arguments['train_data']; valid_data_spec = arguments['valid_data']
si_nnet_spec = arguments['si_nnet_spec']
si_conv_nnet_spec = arguments['si_conv_nnet_spec']
adapt_nnet_spec = arguments['adapt_nnet_spec'];
wdir = arguments['wdir']
init_model_file = arguments['init_model']
# parse ... |
rizar/attention-lvcsr | libs/blocks/tests/extensions/test_progressbar.py | Python | mit | 1,721 | 0 | import numpy
import theano
from fuel.datasets import IterableDataset
from theano import tensor
from blocks.algorithms import GradientDescent, Scale
from blocks.extensions import FinishAfter, ProgressBar, Printing
from blocks.main_loop import MainLoop
from blocks.utils import shared_floatx
def setup_mainloop(extensio... | return main_loop
def test_progressb | ar():
main_loop = setup_mainloop(ProgressBar())
# We are happy if it does not crash or raise any exceptions
main_loop.run()
def test_printing():
main_loop = setup_mainloop(Printing())
# We are happy if it does not crash or raise any exceptions
main_loop.run()
|
secisland/HostMonitor | system.py | Python | gpl-2.0 | 4,072 | 0.041307 | #!/usr/bin/env python
#coding:utf-8
import commands
import os
import base
class SystemStat(object):
'系统基本性能数据收集'
def __init__(self,interval = 30 , cpu_core = True ):
self.interval = interval
self.cpu_core = cpu_core
def _read_cpu_usage(self):
'''
从/proc/stat 读取CPU状态
返回值为列表: [ ['cpu', 'total_value','use_... | lf._read_net_rate()
for i in netinfo.keys():
total2[i] = long(netinfo[i][0]) + long(netinfo[i][1])
for i in total2.keys():
ret[i] = ((total2[i] -total1[i])/1024.0/interval)*8
return ret
def get_load(self):
''' 获取系统5分钟内的平均负载 '''
return os.getloadavg()[0]
def ge | t_disk_usage(self):
'''获取磁盘使用率,返回字典{挂载点:百分数}'''
ret = {}
mountinfo = open('/proc/mounts').readlines()
for i in mountinfo:
mountpoint = i.split()[1].strip()
if i.split()[2].strip().startswith('ext'):
mp_info = os.statvfs(mountpoint)
mp_usage = 100*((mp_info.f_blocks - mp_info.f_bavail)/float(mp_inf... |
vsquare95/JiyuuBot | modules/pull.py | Python | gpl-3.0 | 353 | 0.005666 | def pull(self, command):
import subprocess
output = subprocess.Po | pen(["git", "pull"], | stdout=subprocess.PIPE, stderr=subprocess.PIPE)
for line in output.stdout:
self.conman.gen_send("***Git output: %s" % line)
for line in output.stderr:
self.conman.gen_send("***Git error: %s" % line)
self._map("command", "pull", pull)
|
gilt/incubator-airflow | airflow/operators/check_operator.py | Python | apache-2.0 | 9,424 | 0.000318 | # -*- coding: utf-8 -*-
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
... | ("SELECT {sqlexp} FROM {table}"
" WHERE {date_filter_column}=").format(**locals())
self.sql1 = sqlt + "'{{ ds }}'"
self.sql2 = sqlt + "'{{ macros.ds_add(ds, "+str(se | lf.days_back)+") }}'"
def execute(self, context=None):
hook = self.get_db_hook()
self.log.info('Executing SQL check: %s', self.sql2)
row2 = hook.get_first(self.sql2)
self.log.info('Executing SQL check: %s', self.sql1)
row1 = hook.get_first(self.sql1)
if not row2:
... |
jralls/gramps | gramps/plugins/lib/libcairodoc.py | Python | gpl-2.0 | 62,883 | 0.003403 | #
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2000-2007 Donald N. Allingham
# Copyright (C) 2007 Zsolt Foldvari
# Copyright (C) 2009 Benny Malengier
# Copyright (C) 2009 Brian Matherly
# Copyright (C) 2010 Peter Landgren
# Copyright (C) 2010 Jakim Friant
# Copyright ... | the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
"""Report output generator based on Cairo.
"""
#------------------------------------------------------------------------
#
# Python modules
#
... | _LOCALE as glocale
_ = glocale.translation.gettext
from math import radians
import re
#------------------------------------------------------------------------
#
# Gramps modules
#
#------------------------------------------------------------------------
from gramps.gen.plug.docgen import (BaseDoc, TextDoc, DrawDoc, P... |
bluedynamics/vdexcsv | src/vdexcsv/tests.py | Python | bsd-3-clause | 886 | 0.003386 | import unittest
import doctest
from pprint import pprint
from interlude import interact
import lxml.etree as etree
optionflags = doctest.NORMALIZE_WH | ITESPACE | \
doctest.ELLIPSIS | \
doctest.REPORT_ONLY_FIRST_FAILURE #| \
# doctest.REPORT_NDIFF
TESTFILES = [
'api.rst',
'script.rst',
]
def fxml(xml):
et = etree.fromstring(xml)
return etree.tostring(et, pretty_print=True)
def pxml(xml):
print fxml(xml)... | filename,
optionflags=optionflags,
globs={'interact': interact,
'pprint': pprint,
'pxml': pxml},
) for filename in TESTFILES
])
if __name__ == '__main__': # pragma NO COVERAGE
unittest.main(defaultTest='test_suite') # pragma NO ... |
kuc2477/django-record | django_record/tests/test_mixins.py | Python | gpl-2.0 | 2,680 | 0 | from django.test import TestCase
from random import randint, uniform
from faker import Faker
from .models import TITLE_MAX_LENGTH, POINT_MAX_LENGTH, TEXT_MAX_LENGTH
from .models import Article, Comment, Vote
f = Faker()
class MixinTest(TestCase):
def setUp(self):
article = Article.objects.create(
... | )
Vote.objects.create(
comment=comment,
score=randint(0, 10)
)
def tearDown(self):
Article.objects.all().delete()
def test_record_on_creation(self):
vote = Vote.objects.first()
self.assertTrue(vote.records.exists())
def test_changed_... | Vote.objects.first()
number_of_records_before_save = vote.records.count()
vote.score = 999
vote.save()
r = vote.records.latest()
self.assertEqual(
number_of_records_before_save + 1,
vote.records.count()
)
self.assertEqual(vote.score, r.... |
lmazuel/azure-sdk-for-python | azure-servicefabric/azure/servicefabric/models/service_placement_policy_description.py | Python | mit | 1,801 | 0.00111 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | """Describes the policy to be used for placement of a Service Fabr | ic service.
You probably want to use the sub-classes and not this class directly. Known
sub-classes are: ServicePlacementInvalidDomainPolicyDescription,
ServicePlacementNonPartiallyPlaceServicePolicyDescription,
ServicePlacementPreferPrimaryDomainPolicyDescription,
ServicePlacementRequiredDomainPol... |
mitchmyburgh/compilers_assignment | part2/ir_ula.py | Python | gpl-2.0 | 4,411 | 0.005894 | #----------------------------------------------
# ir_ula.py
#
# Intermediate representation for the ula (unconventional language)
# By Mitch Myburgh (MYBMIT001)
# 24 09 2015
#----------------------------------------------
from llvmlite import ir
from ctypes import CFUNCTYPE, c_float
import llvmlite.binding a... | "$":
return(builder.fsub(code_gen(tree[1]),code_gen(tree[2])))
elif tree[0] == "#":
r | eturn(builder.fmul(code_gen(tree[1]),code_gen(tree[2])))
elif tree[0] == "&":
return(builder.fdiv(code_gen(tree[1]),code_gen(tree[2])))
elif tree[0] in var_dict.keys():
return builder.load(var_dict[tree[0]])
elif isinstance(float(tree[0]), float):
return(ir.Constant(ir.FloatTyp... |
h4ck3rm1k3/OpenWrt-Firefly-SDK | staging_dir/host/lib/scons-2.3.1/SCons/Tool/msgfmt.py | Python | gpl-2.0 | 4,460 | 0.015919 | """ msgfmt tool """
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014 The SCons Foundation
#
# 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... |
linguas = _r | ead_linguas_from_files(env, linguas_files)
if SCons.Util.is_List(source):
source.extend(linguas)
elif source is not None:
source = [source] + linguas
else:
source = linguas
result = BuilderBase._execute(self,env,target,source,*args, **kw)
if linguas_files is not None:
... |
kareemallen/beets | test/test_vfs.py | Python | mit | 1,780 | 0.000562 | # -*- coding: utf-8 -*-
# This file is part of beets.
# Copyright 2015, Adrian Sampson.
#
# 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 t... | whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
"""Tests for the virtual filesystem builder.."""
from __future__ import (division, absolute_import, print_... | ss VFSTest(_common.TestCase):
def setUp(self):
super(VFSTest, self).setUp()
self.lib = library.Library(':memory:', path_formats=[
('default', 'albums/$album/$title'),
('singleton:true', 'tracks/$artist/$title'),
])
self.lib.add(_common.item())
self.lib... |
npinto/Oger | Oger/gradient/models.py | Python | gpl-3.0 | 2,883 | 0.005897 | """
Several pre-defined models that use the gradient nodes.
"""
import mdp
import Oger
import trainers
# TODO: The Autoencoder has not been tested yet.
class MLPNode(mdp.Node):
"""Defines a multilayer pe | rceptron with | a hidden layer of tanh units.r
"""
def __init__(self, input_dim, output_dim, hidden_dim=100,
trainer=trainers.GradientDescentTrainer(), loss='mse', dtype='float64'):
"""Initializes and constructs a multilayer perceptron.
Arguments:
- input_dim: input dimen... |
sniemi/SamPy | herschel/plotmergers3.py | Python | bsd-2-clause | 24,711 | 0.00518 | """
Generates some prediction plots for the Herschel I paper.
:author: Sami-Matias Niemi
:contact: sammy@sammyniemi.com
:version: 0.5
"""
import matplotlib
matplotlib.use('PS')
#matplotlib.use('Agg')
matplotlib.rc('text', usetex=True)
matplotlib.rcParams['font.size'] = 17
matplotlib.rc('xtick', labelsize=14)
matplotl... | + b + c + d + e
#make the figure
# fig = P.figure()
fig = P.figure(figsize=(10, 10))
fig.subplots_adjust(left=0.08, bottom=0.1,
right=0.97, top=0.93)
ax1 | = fig.add_subplot(111)
#calculate widths
wd = (mids[1] - mids[0]) * 1.0
#draw bars
ax1.bar(mids, noMergerFraction,
label='Never Merged', align='center',
color='grey', width=wd, hatch='.')
ax1.bar(mids, mergerFraction,
bottom=noMergerFraction, align='center',
... |
ItsLastDay/academic_university_2016-2018 | subjects/BigData/hw01/fourth_group/gen.py | Python | gpl-3.0 | 409 | 0.007335 | from datetime import timedelta, date
def daterange(start_date, end_date):
for | n in range(int ((end_date - start_date).days)):
yield start_date + timedelta(n)
start_date = date(2017, 9, 30)
end_date = date(2017, 1 | 0, 23)
for single_date in daterange(start_date, end_date):
print './neg_runner.sh', single_date.strftime("%Y-%m-%d")
print './pos_runner.sh', single_date.strftime("%Y-%m-%d")
|
gromacs/copernicus | cpc/server/state/asset.py | Python | gpl-2.0 | 958 | 0.003132 | # This file is part of Copernicus
# http://www.copernicus-computing.org/
#
# Copyright (C) 2011, Sander Pronk, Iman Pouya, Erik Lindahl, and others.
#
# This program is free software; yo | u can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as published
# by the Free Software Foundati | on
#
# This program 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 a copy of the GNU General Public License alo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.