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 |
|---|---|---|---|---|---|---|---|---|
technosaurus/samba4-GPL2 | webapps/qooxdoo-0.6.5-sdk/frontend/framework/tool/icon/modules/kde-to-freedesktop.py | Python | gpl-2.0 | 3,279 | 0.017688 | #!/usr/bin/env python
################################################################################
#
# qooxdoo - the new era of web development
#
# http://qooxdoo.org
#
# Copyright:
# 2007 1&1 Internet AG, Germany, http://www.1and1.org
#
# License:
# LGPL: http://www.gnu.org/licenses/lgpl.html
# EPL: h... | ort sys
im | port shutil
import optparse
def rmgeneric(path, __func__):
try:
__func__(path)
except OSError, (errno, strerror):
print ERROR_STR % {'path' : path, 'error': strerror }
def removeall(path):
if not os.path.isdir(path):
return
files=os.listdir(path)
for x in files:
fullpath=os.path.join(path... |
zothor/software | MiniprojectProgrammerenWeek3/buttons.py | Python | gpl-2.0 | 17,539 | 0.032898 | __author__ = 'Bram + Frank + Ricardo + Kevin + Jouke-bouwe'
import csv
from tkinter import *
from MiniprojectProgrammerenWeek3 import FilmsOphalen, Aankoop
#Verwijst naar de csv bestanden die gebruikt worden. Moet worden aangepast als deze op een andere pc wordt uitgevoerd
csvKlantBestand = 'C:/Users/Rica/PycharmProje... | p.geometry("500x250+50+70")
top["bg"] = "grey"
helptekst = Canvas(top, width = 200, height = 50)
helptekst.create_rectangle(200,50,0,0, fill = "red")
helptekst.create_text(100, 25, text = "Fill in the blanks", fill = "white", font = ("broadway", 12))
helptekst.place(relx= 0.3,rely = 0.05)
bot... | mframe["bg"] = "grey"
label_1 = Label(bottomframe, text = "Email", bg = "grey", fg = "white")
label_2 = Label(bottomframe, text = "Name", bg = "grey", fg = "white")
label_3 = Label(bottomframe, text = "Surname", bg = "grey", fg = "white")
label_4 = Label(bottomframe, text = "Password", bg = "grey", fg ... |
erdc-cm/air-water-vv | 2d/waveTransformation/Dingemans_wave_shoaling/DingemansWaveShoaling.py | Python | mit | 13,687 | 0.016001 | """
Dingemans Wave Shoaling
"""
from proteus import Domain, Context
from proteus.mprans import SpatialTools as st
from proteus import WaveTools as wt
from math import *
import numpy as np
opts=Context.Options([
# predefined test cases
("water_level", 0.86, "Height of free surface above seabed"),
# tank
... | ,
("tank_sponge", (5., 5.), "Length of relaxation zones zones (left, right)"),
("free_slip", True, "Should tank walls have free slip conditions "
"(otherwise, no slip conditions will be applied)."),
# waves
("waves", True, "Generate waves (True/False)"),
("wave_period", 2.02,... | wave_height", 0.02, "Height of the waves"),
("wave_depth", 0.86, "Wave depth"),
("wave_dir", (1.,0.,0.), "Direction of the waves (from left boundary)"),
("wave_wavelength", 5.037, "Direction of the waves (from left boundary)"), #calculated by FFT
("wave_type", 'Fenton', "type of wave"),
("Bcoeff", n... |
omererdem/honeything | src/cwmp/google3.py | Python | gpl-3.0 | 964 | 0.001037 | #!/usr/bin/python
# Copyright 2011 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 required by appli... | le 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 the License.
"""Fix sys.path so it can find o... | le is named google3.py because gpylint specifically ignores it when
complaining about the order of import statements - google3 should always
come before other non-python-standard imports.
"""
__author__ = 'apenwarr@google.com (Avery Pennarun)'
import tr.google3 #pylint: disable-msg=C6204,W0611
|
nop33/indico | indico/modules/events/features/controllers.py | Python | gpl-3.0 | 4,902 | 0.003468 | # This file is part of Indico.
# Copyright (C) 2002 - 2017 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (a... | name):
if name in disallowed:
continue
field = BooleanField(feature.friendly_name, widget=SwitchWidget(on_label=_('On'), off_label=_('Off')),
description=feature.description)
set | attr(form_class, name, field)
defaults = {name: True for name in get_enabled_features(self.event)}
return form_class(csrf_enabled=False, obj=FormDefaults(defaults))
def _process(self):
form = self._make_form()
widget_attrs = {field.short_name: {'disabled': True} for field in form} i... |
trivoldus28/pulsarch-verilog | tools/local/bas-release/bas,3.9-SunOS-i386/lib/python/lib/python2.4/subprocess.py | Python | gpl-2.0 | 39,931 | 0.001928 | # subprocess - Subprocesses with accessible I/O streams
#
# For more information about this module, see PEP 324.
#
# This module should remain compatible with Python 2.2, see PEP 291.
#
# Copyright (c) 2003-2005 by Peter Astrand <astrand@lysator.liu.se>
#
# Licensed to PSF under a Contributor Agreement.
# See http://ww... | Note: The data read is buffered in memory, so do not use this
method if the data siz | e is large or unlimited.
The following attributes are also available:
stdin
If the stdin argument is PIPE, this attribute is a file object
that provides input to the child process. Otherwise, it is None.
stdout
If the stdout argument is PIPE, this attribute is a file object
that provides output from... |
bjodah/sym | sym/tests/test_Dummy.py | Python | bsd-2-clause | 339 | 0 | # -*- coding: utf-8 -*-
from __future_ | _ import (absolute_import, division, print_function)
import pytest
from .. import Backend
from . import AVAILABLE_BACKENDS
@pytest.mark.parametrize('key', AVAILABLE_BACKENDS)
def test_Dummy(key):
be = Backend(key)
d0 = be.Dummy()
d1 = be.Dummy()
a | ssert d0 == d0
assert d0 != d1
|
Anmol-Singh-Jaggi/gDrive-auto-sync | gDrive-auto-sync/api_boilerplate.py | Python | mit | 1,850 | 0 | """
This module is responsible for doing all the authentication.
Adapted from the Google API Documentation.
"""
from __future__ import print_function
import os
import httplib2
import apiclient
import oauth2client
try:
import argparse
flags = argparse.ArgumentParser(
parents=[oauth2client.tools.argpar... | gdrive-credentials.json')
store = oauth2client.file.Storage(cr | edential_path)
credentials = store.get()
if not credentials or credentials.invalid:
flow = oauth2client.client.flow_from_clientsecrets(
CLIENT_SECRET_FILE, SCOPES)
flow.user_agent = APPLICATION_NAME
if flags:
credentials = oauth2client.tools.run_flow(flow, store, ... |
Azure/azure-sdk-for-python | sdk/testbase/azure-mgmt-testbase/azure/mgmt/testbase/aio/operations/_favorite_processes_operations.py | Python | mit | 17,645 | 0.005101 | # 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 may ... | unction that will be passed the direct response
:return: FavoriteProcessResource, or the result of cls(response)
:rtype: ~test_base.models.FavoriteP | rocessResource
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.FavoriteProcessResource"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_ma... |
csparkresearch/eyes-online | app/static/scripts/Maths/numpy2.py | Python | gpl-3.0 | 203 | 0.029557 | #Example numpy2.py
from numpy import *
a = arange(1.0, 2.0, 0.1) # | start, stop & step
pr | int a
b = linspace(1,2,11)
print b
c = ones(5)
print c
d = zeros(5)
print d
e = random.rand(5)
print e
|
fuzzy/mvm | mvm/term.py | Python | bsd-2-clause | 2,114 | 0.009461 | # Author: Mike 'Fuzzy' Partin
# Copyright: (c) 2016-2018
# Email: fuzzy@fumanchu.org
# License: See LICENSE.md for details
# Stdlib imports
import math
import datetime
def red(txt):
return '\033[1;31m%s\033[0m' % txt
def green(txt):
return '\033[1;32m%s\033[0m' % txt
def yellow(txt):
return '\033[1;33m%... | t):
return '\033[1;36m%s\033[0m' % txt
def white(txt):
return '\033[1;37m%s\033 | [0m' % txt
# Console messages
# TODO: the framework for this, should take cues from the config file
# and if no console output is desired, do the right thing, as
# well as logging to file. But that will come later.
def debug(txt):
print('%s: %s' % (cyan('DEBUG'), txt))
def info(txt):
print('%s: %... |
TheAlgorithms/Python | strings/word_patterns.py | Python | mit | 1,293 | 0.000773 | def get_word_pattern(word: str) -> str:
"""
>>> get_word_pattern("pattern")
'0.1.2.2.3.4.5'
>>> get_word_pattern("word pattern")
'0.1.2.3.4.5.6.7.7.8.2.9'
>>> get_word_pattern("get word pattern")
'0.1.2.3.4.5.6.7.3.8.9.2.2.1.6.10'
"""
word = word.upper()
next_num = 0
letter_n... | letter not in letter_nums:
letter_nums[letter] = str(next_num)
next_num += 1
word_pattern.append(letter_nums[letter])
return ".".join(word_pattern)
if __name__ == "__main__":
import pprint
import time
start_time = time.time()
with open("dictionary.txt") as in_file:... | ord)
if pattern in all_patterns:
all_patterns[pattern].append(word)
else:
all_patterns[pattern] = [word]
with open("word_patterns.txt", "w") as out_file:
out_file.write(pprint.pformat(all_patterns))
totalTime = round(time.time() - start_time, 2)
print(f"Done... |
keras-team/keras | keras/distribute/dataset_creator_model_fit_test.py | Python | apache-2.0 | 10,240 | 0.004297 | # Lint as: python3
# Copyright 2021 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 requ... | in
# `model.predict` so there predictions should match.
self.assertTrue(all(predictions[0] == predictions[i] for i in [0, 3, 5 | ]))
self.assertFalse(
all(predictions[0] == predictions[i] for i in [0, 1, 2, 4]))
def testModelPredictWithStepsPerExecution(self, strategy):
_, predictions = self._model_predict(
strategy, steps_per_execution=3, steps=3)
# Check the first (0th index), fourth (3rd index) and the last pr... |
AtScaleInc/Impala | tests/shell/test_shell_interactive.py | Python | apache-2.0 | 3,707 | 0.006474 | #!/usr/bin/env python
# encoding=utf-8
# Copyright 2014 Cloudera 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 app... | eractive(command, shell_args=''):
"""Runs a command in the Impala shell interactively."""
cmd = "%s %s" % (SHELL_CMD, shell_args)
# workaround to make Popen environment 'utf-8' compati | ble
# since piping defaults to ascii
my_env = os.environ
my_env['PYTHONIOENCODING'] = 'utf-8'
p = Popen(shlex.split(cmd), shell=True, stdout=PIPE,
stdin=PIPE, stderr=PIPE, env=my_env)
p.stdin.write(command + "\n")
p.stdin.flush()
return get_shell_cmd_result(p)
|
mishka28/NYU-Python | advance_python_class_3/Homework1/temptest.py | Python | mit | 307 | 0.026059 | #!/usr/bin/env python3
# sequence = []
defence = 0.4
for x in range(1):
print(x)
for x in range(10):
if x == 0:
defence = defence
else:
defence = defence + (1 - defence) * (1 / 2)
print(defence)
# print(defence)
# print(sequence)
# print(sum(sequence))
# x = input()
# | print(x) | |
thorwhalen/ut | slurp/simple_request.py | Python | mit | 787 | 0.007624 | __author__ = 'thorwhalen'
import requests
from serialize.khan_logger import KhanLogger
import logging
class SimpleRequest(object):
def __init__(self, log_file_name=None, log_level=lo | gging.INFO):
full_log_path_and_name = KhanLogger.default_log_path_with_unique_name(log_file_name)
self.logger = KhanLogger(file_path_and_name=full_log_path_and_name, level=log_level)
def slurp(self, url):
r = requests.get(url, timeout=30.0)
if not r.ok:
self.logger.log... | rl {}".format(r.status_code, url))
else:
self.logger.log(level=logging.INFO, simple_request="Slurped url {}".format(url))
return r.text
if __name__ == '__main__':
sr = SimpleRequest() |
mlperf/training_results_v0.7 | Inspur/benchmarks/dlrm/implementations/implementation_closed/dlrm/nn/__init__.py | Python | apache-2.0 | 70 | 0 | from .modules.buckle_embedding import *
from .modules.gather impo | rt *
| |
venicegeo/eventkit-cloud | eventkit_cloud/auth/migrations/0003_auto_20210519_2024.py | Python | bsd-3-clause | 399 | 0 | # Generated by Django 3.1.2 on 2021-05-19 20:24
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('eventkit_cloud_aut | h', '0002_auto_20191127_1425'),
]
operations = [
migrations. | AlterField(
model_name='oauth',
name='user_info',
field=models.JSONField(default=dict),
),
]
|
kilon/sverchok | old_nodes/__init__.py | Python | gpl-3.0 | 4,863 | 0.008842 | # ##### BEGIN GPL LICENSE BLOCK #####
#
# 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 distrib... | mod = importlib.import_module(".{}".format(old_bl_idnames[bl_id]), __name__)
res = inspect.getmembers(mod)
for name, cls in res:
if inspect.isclass(cls):
if issubclass(cls, bpy.types.Node) and cls.bl_idname == bl_id:
if bl_id no | t in imported_mods:
try:
mod.register()
except:
traceback.print_exc()
imported_mods[bl_id] = mod
return mod
print("Cannot find {} among old nod... |
sggottlieb/cmfieldguide | cmfieldguide/cmsdetector/signatures/expressionengine.py | Python | unlicense | 1,264 | 0.011867 | """
This signature containts test to see if the site is running on ExpressionEngine.
"""
__author__ = "Seth Gottlieb"
__copyright__ = "CM Fieldguide"
__credits__ = ["Seth Gottlieb",]
__license__ = "Unlicense"
__version__ = "0.1"
__maintainer__ = "Seth Gottlieb"
__email__ = "sgottli | eb@alumni.duke.edu"
__status__ = "Experimental"
from cmfieldguide.cmsdetector.signatures import BaseSignature
class Signature(BaseSignature):
NAME = 'ExpressionEngi | ne'
WEBSITE = 'http://expressionengine.com/'
KNOWN_POSITIVE = 'http://expressionengine.com/'
TECHNOLOGY = 'PHP'
def test_has_ee_login(self, site):
"""
By default, Expression Engine ships with a login page at /admin.php
"""
if site.page_cache[site.url_stem + ... |
dtrodrigues/nifi-minifi-cpp | python/getFile.py | Python | apache-2.0 | 3,036 | 0.000988 | #!/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 re | garding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from minifi import * # noqa F403
from argparse import ArgumentParser
from ctypes import cdll # noqa F401
import ctypes # noqa F401
import sys
from _cffi_backend import callback # ... |
DonBeo/statsmodels | statsmodels/examples/ex_sandwich3.py | Python | bsd-3-clause | 1,967 | 0.008134 | # -*- coding: utf-8 -*-
"""Cluster Robust Standard Errors with Two Clusters
Created on Sat Dec 17 08:39:16 2011
Author: Josef Perktold
"""
from statsmodels.compat.python import urlretrieve
import numpy as np
from numpy.testing import assert_almost_equal
import statsmodels.api as sm
import statsmodels.stats.sandwich... | culty/petersen/htm/papers/se/test_data.txt',
'test_data.txt')
print('downloading file')
pet = np.genfromtxt("test_data.txt")
endog = pet[:,-1]
group = pet[:,0].astype(int)
time = pet[:,1].astype(int)
exog = sm.add_constant(pet[:,2])
res = | sm.OLS(endog, exog).fit()
cov01, covg, covt = sw.cov_cluster_2groups(res, group, group2=time)
#Reference number from Petersen
#http://www.kellogg.northwestern.edu/faculty/petersen/htm/papers/se/test_data.htm
bse_petw = [0.0284, 0.0284]
bse_pet0 = [0.0670, 0.0506]
bse_pet1 = [0.0234, 0.0334] #year
bse_pet01 = [0.065... |
Chaffelson/whoville | whoville/cloudbreak/models/recipe_request.py | Python | apache-2.0 | 7,284 | 0.002059 | # coding: utf-8
"""
Cloudbreak API
Cloudbreak is a powerful left surf that breaks over a coral reef, a mile off southwest the island of Tavarua, Fiji. Cloudbreak is a cloud agnostic Hadoop as a Service API. Abstracts the provisioning and ease management and monitoring of on-demand clusters. SequenceIQ's Cloud... | of the resource
:return: The description of this RecipeRequest.
:rtype: str
"""
return self._description
@description.setter
def description(self, description):
"""
Sets the description of this RecipeRequest.
description of the resource
:param d... | eError("Invalid value for `description`, length must be less than or equal to `1000`")
if description is not None and len(description) < 0:
raise ValueError("Invalid value for `description`, length must be greater than or equal to `0`")
self._description = description
@property
def... |
michielkauwatjoe/Meta | meta/objects/cubicbezier.py | Python | mit | 392 | 0.002558 | #!/usr/bin | /env python
# -*- coding: utf-8 -*-
#
# https://github.com/michielkauwatjoe/Meta
class CubicBezier:
def __init__(self, bezierId=None, points=None, parent=None, isClosed=False):
u"""
Stores points of the cubic Bézier curve.
"""
self.bezierId = bezierId
self.points = points
... | |
pixbuffer/django-cms | cms/utils/permissions.py | Python | bsd-3-clause | 11,836 | 0.00414 | # -*- coding: utf-8 -*-
from cms.exceptions import NoPermissionsException
from cms.models import Page, PagePermission, GlobalPagePermission
from cms.plugin_pool import plugin_pool
from cms.utils import get_cms_setting
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.au... | lter(**filters)
if site:
qs = q | s.filter(Q(sites__in=[site]) | Q(sites__isnull=True))
request._cms_global_perms[key] = qs.exists()
return request._cms_global_perms[key]
def get_any_page_view_permissions(request, page):
"""
Used by the admin template tag is_restricted
"""
return PagePermission.objects.for_page(page=page).... |
apark263/tensorflow | tensorflow/contrib/tensorrt/test/concatenation_test.py | Python | apache-2.0 | 3,388 | 0.010035 | # 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... | _test
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import gen_array_ops
from tensorflow.python.ops import gen_math_ops
from tensorflow.python.platform ... | est(trt_test.TfTrtIntegrationTestBase):
def GetParams(self):
"""Testing Concatenation in TF-TRT conversion."""
dtype = dtypes.float32
input_name = "input"
input_dims = [2, 3, 3, 1]
output_name = "output"
g = ops.Graph()
with g.as_default():
x = array_ops.placeholder(dtype=dtype, sha... |
jamy015/slack-latex-bot | application.py | Python | gpl-3.0 | 2,527 | 0.001979 | import os
import requests
from flask import Flask, request, abort, redirect, jsonify
from requests.exceptions import RequestException
import quicklatex
application = Flask(__name__)
slack_client_id = os.environ['SLACK_CLIENT_ID']
slack_client_secret = os.environ['SLACK_CLIENT_SECRET']
slack_verification_token = os.... | 'text': 'QuickLaTeX seems to be having some trouble (HTTP {}). Please try again later.'.format(err)
})
return jsonify({
'response_type': 'in_channel',
'attachments': [
err_attachment,
{
'fallback': 'LaTeX',
'text': 'LaTeX',
... | _name__ == "__main__":
application.run()
|
refeed/coala-bears | bears/c_languages/GNUIndentBear.py | Python | agpl-3.0 | 7,940 | 0 | import platform
import shlex
from coalib.bearlib import deprecate_settings
from coalib.bearlib.abstractions.Linter import linter
from coalib.bearlib.spacing.SpacingHelper import SpacingHelper
from dependency_management.requirements.DistributionRequirement import (
DistributionRequirement)
@linter(executable='ind... | e`` statements.
:param delete_optional_blank_lines:
Deletes blank lines that are not needed. An example of needed
| blank line, is the blank line following a declaration when
``blank_line_after_declaration=True``.
:param declaration_indent:
Forces variables names to be aligned in column ``n`` with
``n = declaration_indent`` in declaration.
Example: If ``declaration_ind... |
sarvex/tensorflow | tensorflow/lite/micro/examples/person_detection/utils/raw_to_bitmap.py | Python | apache-2.0 | 5,452 | 0.007337 | # Copyright 2019 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... | r.add_argument(
'-r',
'--resolution',
dest='resolution',
required=False,
help='Resolution',
choices=['QVGA', 'RGB', 'GRAY'],
default='QVGA',
)
parser.add_argument(
'-v',
'--version',
help='Program version',
action='version',
version='%(prog)s ... | idth, height,
channels) = _DICT_RESOLUTIONS.get(args.resolution,
('Resolution not supported', 0, 0, 0))
frame_list = parse_file(open(args.inputfile), width, height, channels)
bitmap_list = reshape_bitmaps(frame_list, width, height, channels)
show_and_save_bitmaps(args.input... |
airbnb/streamalert | streamalert/apps/config.py | Python | apache-2.0 | 18,276 | 0.002845 | """
Copyright 2017-present Airbnb, 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, sof... | 'required keys: {}'.format(self, missing_auth_keys))
@classmethod
def _get_parameters(cls, *names):
"""Simple helper function to house the boto3 ssm client ge | t_parameters operations
Args:
names (list): A list of parameter names to retrieve from the aws ssm
|
foxcarlos/decimemijobot | bot/migrations/0014_auto_20171109_1813.py | Python | gpl-3.0 | 694 | 0.001441 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-11-09 1 | 8:13
from __future__ import unicode_literals
i | mport datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('bot', '0013_auto_20171109_1759'),
]
operations = [
migrations.AlterField(
model_name='alertausuario',
name='chat_id',
field=models.Integer... |
mlperf/training_results_v0.6 | Fujitsu/benchmarks/resnet/implementations/mxnet/3rdparty/tvm/nnvm/tests/python/compiler/test_top_level3.py | Python | apache-2.0 | 1,275 | 0.012549 | import numpy a | s np
import tvm
from tvm.contrib import graph_runtime
import topi.testing
import nnvm.symbol as sym
import nnvm.comp | iler
from nnvm.testing.config import ctx_list
from nnvm.testing.check_computation import check_function
def check_map(symfunc, np_func, np_backward=None, dtype="float32", rnd_min=-1, rnd_max=1):
x = sym.Variable("x")
y = symfunc(x)
shape = {'x': (1, 3, 32, 32)}
check_function(y, lambda x: np_func(x), n... |
adityahase/frappe | frappe/website/doctype/web_page_block/web_page_block.py | Python | mit | 272 | 0.003676 | # -*- coding: utf-8 -*-
# Copyright (c) 2020, Frappe Technologies and contributors
# For license i | nformation, please see license.txt
from __future__ import unicode_literals
# import frappe
from frappe.model.document import Document
class WebPageBlock(Document): |
pass
|
pyfidelity/rest-seed | backend/backrest/tests/test_migrations.py | Python | bsd-2-clause | 3,745 | 0.001068 | from alembic.config import Config
from alembic.environment import EnvironmentContext
from alembic.migration import MigrationContext
from alembic. | script import ScriptDirectory
from difflib import unified_diff
from | pytest import fixture
from re import split
from sqlalchemy import engine_from_config
from subprocess import call, Popen, PIPE
@fixture
def settings(testing):
# we use our own db for this test, since it will be created and dropped
project_name = testing.project_name()
db_name = '%s_migration_test' % projec... |
aronsky/home-assistant | homeassistant/components/tradfri/base_class.py | Python | apache-2.0 | 4,045 | 0.000494 | """Base class for IKEA TRADFRI."""
from __future__ import annotations
from collections.abc import Callable
from functools import wraps
import logging
from typing import Any
from pytradfri.command import Command
from pytradfri.device import Device
from pytradfri.device.air_purifier import AirPurifier
from pytradfri.de... | y_id: str,
) -> None:
"""Initialize a device."""
self._api = handle_error(api)
self._device: Device = device
self._device_control: BlindControl | LightControl | SocketControl | SignalRepeaterControl | AirPurifierControl | None = (
None
)
self._device_data:... | eption | None = None) -> None:
"""Start observation of device."""
if exc:
self.async_write_ha_state()
_LOGGER.warning("Observation failed for %s", self._attr_name, exc_info=exc)
try:
cmd = self._device.observe(
callback=self._observe_update,
... |
sridevikoushik31/nova | nova/virt/xenapi/vm_utils.py | Python | apache-2.0 | 88,420 | 0.000373 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2010 Citrix Systems, Inc.
# Copyright 2011 Piston Cloud Computing, Inc.
# Copyright 2012 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may ... | default=3600,
help='Number of seconds after downloading an image via'
' BitTorrent that it should be seeded for other peers.'),
cfg.IntOpt('xenapi_torrent_max_last_accessed',
default=86400,
he | lp='Cached torrent files not accessed within this number of'
' seconds can be reaped'),
cfg.IntOpt('xenapi_torrent_listen_port_start',
default=6881,
help='Beginning of port range to listen on'),
cfg.IntOpt('xenapi_torrent_listen_port_end',
default... |
zwindler/simfrastructure | simfrastructure_core.py | Python | mit | 9,266 | 0.015649 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import random
from graphviz import Digraph
current_indent = 0
color_map = ['lightgrey', 'lightpink', 'orange', 'cyan', 'gold', 'lawngreen', 'sienna', 'yellow', 'red', 'hotpink']
verbose = 0
def print_simple_tree():
indent= "| "
last_indent= "\_"
"""prints a beautiful de... | ed', color=color_map[guest.tenant_id])
if guest_types == "containers":
graph.attr('node', shape='box3d', style="")
elif guest_types == "vms":
graph.attr('node', shape='hexagon', style="")
graph.node(guest.name)
graph.edge(self.name, guest.name)
with graph.sub... | c.attr(color='blue')
c = guest.generate_graph(c)
return graph
class sim_server(sim_host):
"""A 2U server that may run containers or virtual machines or both"""
def __init__(self, name, vcpu_max_capacity, ram_max_capacity, tenant_id=0):
self.name = name
self.server_size = 2
self.capacity... |
guorendong/iridium-browser-ubuntu | third_party/chromite/lib/git_unittest.py | Python | bsd-3-clause | 13,396 | 0.004479 | # Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Unit tests for chromite.lib.git and helpers for testing that module."""
from __future__ import print_function
import functools
import mock
import... | t(
dict(name='chromite',
path='src/platform/somethingsomething/chromite',
# Pinned to a SHA1.
revision='1deadbeeaf1deadbeeaf1deadbeeaf1deadbeeaf'))
self.fake_versioned_patchable = git.ProjectCheckout(
dict(name='chromite',
path='src/chromite',
... | eeaf',
upstream='remotes/for/master'))
self.fake_versioned_unpatchable = git.ProjectCheckout(
dict(name='chromite',
path='src/chromite',
revision='1deadbeeaf1deadbeeaf1deadbeeaf1deadbeeaf',
upstream='1deadbeeaf1deadbeeaf1deadbeeaf1deadbeeaf'))
def testI... |
mferenca/HMS-ecommerce | ecommerce/tests/factories.py | Python | agpl-3.0 | 1,062 | 0.001883 | from django.contrib.sites.models import Site
import factory
from factory.fuzzy import FuzzyText
from oscar.core.loading import get_model
from oscar.test.factories import ProductFactory, StockRecordFactory as OscarStockRecordFactory
from ecommerce.core.models import SiteConfiguration
class PartnerFactory(factory.Djan... | SelfAttribute('name')
class SiteFactory(factory.DjangoModelFactory):
class Meta(object):
model = Site
class Site | ConfigurationFactory(factory.DjangoModelFactory):
class Meta(object):
model = SiteConfiguration
lms_url_root = factory.LazyAttribute(lambda obj: "http://lms.testserver.fake")
site = factory.SubFactory(SiteFactory)
partner = factory.SubFactory(PartnerFactory)
class StockRecordFactory(OscarStoc... |
bcstack/btsdk | shell/service.py | Python | apache-2.0 | 714 | 0.004202 | from threading import Thread, Lock
import bluetooth as bt
impo | rt socket
class SerialPortService(Thread):
def __init__(self, port):
super(SerialPortService, self).__init__()
self.port = port
self.send_lock = Lock()
self.setDaemon(True)
def run(self):
self.running = True
self.port.settimeout(0.1)
while self.running:
... | pass
self.port.close()
def end(self):
self.running = False
def send(self, msg):
self.send_lock.acquire()
self.port.send(msg)
self.send_lock.release()
|
rackerlabs/marconi | tests/unit/common/test_request.py | Python | apache-2.0 | 912 | 0 | # Copyright (c) 2013 Rackspace, Inc.
# Copyright (c) 2013 Red Hat, 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 b... | ee the License for the specific language governing permissions and
# limitations under the License.
from marconi.common import request
from marconi.tests import base
class TestRequest(base.TestBase):
def test_request_deserialized(self):
data = '{"data": "tons of GBs"}'
req = request.Request(con... | eq.deserialized_content, dict)
|
luiscberrocal/rango_tutorial | versiontools/tests.py | Python | apache-2.0 | 948 | 0.009494 | from django.test import TestCase
from versiontools.models import AssemblyInfo
from django.utils.timesince import timesince
from django.utils.datetime_safe import datetime
# Create your tests here.
class AssembyInf | oTest(TestCase):
def test_create(self):
data = {'fullpath' : r'C:\Users\lberrocal\Documents\Visual Studio 2010\Projects\vessel_scheling_app\5-VesselScheduleEngine\VsApplicationData\My | Project\AssemblyInfo.vb ',
'title' : 'Vessel Schedule WorkBench',
'description' : '',
'version' : '1.2.6'}
ai = AssemblyInfo.objects.create(**data)
self.assertEqual(ai.fullpath, data['fullpath'])
self.assertEqual(ai.title, data['title... |
openaid-IATI/OIPA | OIPA/currency_convert/migrations/0002_monthlyaverage_imf_url.py | Python | agpl-3.0 | 404 | 0 | # Generated by Django 2.0.13 on 2020-10-09 14:56
from django. | db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('currency_convert', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='monthlyaverage',
name='imf_url',
field=models.URLField(max_length=2000, null=Tr... | ),
]
|
ServiceLearningB/ServiceLearningNew | submit_reports/views.py | Python | mit | 12,136 | 0.023978 | from django.shortcuts import render, RequestContext
from .forms import *
import datetime
from django.forms import modelformset_factory
from .models import SubmitReport, Student, Faculty, Staff, Course
from django.http import HttpResponse, HttpResponseRedirect, HttpResponsePermanentRedirect
from django.contrib import au... | eportFormSet = modelformset_factory(SubmitReport, form=ReportApproveForm, extra=0)
reports = SubmitReport.objects.query_pending_reports().filter(courses__in=request.user.staff.courses.all()).distinct()
reports.query = pickle.loads(request.session['search_results'])
print reports
if request.method == 'POST':
repor... | ms = ApproveReportFormSet(request.POST, queryset=reports)
if report_forms.is_valid():
report_forms.save()
reports.filter(status__exact='PENDING')
return render(request, "ta_search_results.html", {'formset': report_forms,})
else:
report_forms = ApproveReportFormSet(queryset=reports)
print report_forms
... |
cobrab11/black1-bot | extensions/servres.py | Python | apache-2.0 | 1,659 | 0.027557 | # BS mark.1-55
# /* coding: utf-8 */
# BlackSmith plugin
# servres_plugin.py
# Coded by: WitcherGeralt (WitcherGeralt@jabber.ru)
# http://witcher-team.ucoz.ru/
SERVSTAT = {}
RESSTAT = {}
def handler_servres_stat(conf, nick, afl, role, status, text):
instance = GROUPCHATS[conf][nick]
if instance.has_key('full_ji... | ERVSTAT:
SERVSTAT[server] = []
if stripped_jid not in SERVSTAT[server]:
SERVSTAT[server].append(stripped_jid)
if resourse not in RESSTAT:
RESSTAT[resourse] = []
if stripped_jid not in RESSTAT[resourse]:
RESSTAT[resourse].append(stripped_jid)
def handler_check_servsta | t(type, source, body):
stat = []
for server in SERVSTAT:
stat.append([len(SERVSTAT[server]), server])
stat.sort()
stat.reverse()
list = ''
col = 0
for item in stat:
col = col + 1
if col <= 20:
list += '\n'+str(col)+'. '+item[1]+' - '+str(item[0])
reply(type, source, u'Всего серверов '+str(col)+' :'+lis... |
elkingtowa/alphacoin | Bitcoin/ngcccbase-master/server/run.py | Python | mit | 2,469 | 0.00081 | #!/usr/bin/env python
import json
import sys
import web
from coloredcoinlib import BlockchainState, ColorDefinition
blockchainstate = BlockchainState.from_url(None, True)
urls = (
'/tx', 'Tx',
'/prefetch', 'Prefetch',
)
class ErrorThrowingRequestProcessor:
def require(self, data, key, message):
... | of the affecting
inputs first and then scan that tx.
"""
if limit and len(tx_lookup) > limit:
return
if tx_lookup.get(current_txhash):
return
current_tx = blockchainstate.get_tx(current_txhash)
if not current_tx:
... | _txhash] = blockchainstate.get_raw(current_txhash)
# note a genesis tx will simply have 0 affecting inputs
inputs = set()
inputs = inputs.union(
color_def.get_affecting_inputs(current_tx,
[current_outindex]))
... |
iitjee/steppinsPython | SystemProgramming/Parallel System/01 Forking.py | Python | gpl-3.0 | 5,146 | 0.021697 | Forked processes are a traditional way to structure parallel tasks, and they are a fun- damental part of the Unix tool set.
Forking is based on the notion of copying programs: when a program calls the fork routine, the operating system makes a new
copy of that program and its process in memory and starts running that... | s; fork doesn't currently work on Windows without Cygwin:
use os.spawnv or multiprocessing on Wi | ndows instead; spawnv is roughly like a fork+exec combination;
"""
import os, time
def counter(count):
for i in range(count):
time.sleep(1)
print('[%s] => %s' % (os.getpid(), i))
for i in range(5):
pid = os.fork()
if pid != 0:
print('Process %d spawned' % pid)
else:
counter(5)
os._exit(0)
... |
thinkAmi-sandbox/python_ms_access_sample | pyodbc_runner.py | Python | unlicense | 487 | 0.020316 | import pyodbc |
import config
def main():
# formatで`{`を使うため、`{`を重ねることでエスケープ
con_str = 'Driver={{Microsoft Access Driver (*.mdb, *.accdb)}};Dbq={0};'.format(config.PATH_ACCDB)
conn = pyodbc.connect(con_str)
cur = conn.cursor()
cur.execute("select item_name from item")
for c in cur.fetchall():
prin... | .close()
conn.close()
if __name__ == '__main__':
main() |
UCRoboticsLab/BaxterTictactoe | src/baxter_tictactoe/scripts/animator_server.py | Python | apache-2.0 | 4,046 | 0.005932 | #!/usr/bin/env python
import glob
import cv2
import cv_bridge
import rospy
from sensor_msgs.msg import Image
from std_msgs.msg import Int32, Float32
import rospkg
import sys
class Animation:
def __init__(self, directory):
self.fnames = [fname for fname in glob.glob("%s/*" % directory)]
self.fnames... | elf.current_value = 0
self.current_idx = 0
self.set_velocity(1/20.0)
self.current_target = 99
self.image_publisher = rospy.Publisher("/robot/xdisplay", Image,
queue_size=10)
self.value_subscriber = rospy.Subscriber("/confusion/valu... | et_subscriber = rospy.Subscriber("/confusion/target/command", Int32, self.set_target)
self.value_publisher = rospy.Publisher("/confusion/value/state", Int32,
queue_size=10)
self.target_publisher = rospy.Publisher("/confusion/target/state", Int32,
... |
Coder-Yu/RecQ | algorithm/ranking/DMF.py | Python | gpl-3.0 | 6,418 | 0.012932 | #coding:utf8
from baseclass.DeepRecommender import DeepRecommender
import numpy as np
from random import choice,random,randint,shuffle
from tool import config
import tensorflow as tf
#According to the paper, we only
class DMF(DeepRecommender):
def __init__(self,conf,trainingSet=None,testSet=None,fold='[1]'):
... | self.n_hidden_i=[256,512]
| self.input_u = tf.placeholder(tf.float, [None, n_input_u])
self.input_i = tf.placeholder(tf.float, [None, n_input_i])
def buildModel(self):
super(DMF, self).buildModel_tf()
initializer = tf.contrib.layers.xavier_initializer()
#user net
user_W1 = tf.Variable(initializer(... |
mypinballs/whirlwind | tilt.py | Python | gpl-3.0 | 2,464 | 0.027597 | # Top Rollover Lanes
__author__="jim"
__date__ ="$Jan 18, 2011 1:36:37 PM$"
import procgame
import locale
from procgame import *
base_path = config.value_for_key_path('base_path')
game_path = base_path+"games/whirlwind/"
speech_path = game_path +"speech/"
sound_path = game_path +"sound/"
music_path = game_path +"mu... | riority)
self.text_layer = dmd.TextLayer(128/2, 10, self.game.fonts['num_09Bx7'], "center", opaque=True)
self.game.sound.register_sound('tilt', sound_path+"tilt.ogg")
self.game.sound.register_sound('tilt_warning', sound_path+"tilt_warning.ogg")
self.reset()
de... | def status(self):
if self.status==0:
return False
elif self.status==1:
return True
def tilt(self):
#check if already in a tilt state
if self.status == 0:
#set status
self.status = 1
#upda... |
isb-cgc/ISB-CGC-Webapp | seqpeek/admin.py | Python | apache-2.0 | 666 | 0 | #
# Copyright 2015-2019, Institute for Systems Biology
#
# 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 the License.
#
from django.contrib im... |
drodri/client | command/tool_catalog.py | Python | mit | 2,824 | 0.001771 | import inspect
from biicode.client.shell.biistream import Color
class ToolCatalog(dict):
def __init__(self, main_class, tools):
dict.__init__(self)
self.main_class = main_class
# dict from tool group name to set of classes
for c in tools:
self[c.group] = c
self.... |
out.writeln(self._get_doc_short(doc))
if not argv:
out.writeln('\n--------- Tools ----------', Color.YELLOW)
out.writeln('For help about one or more tools ("all" for all):', Color.YELLOW)
out.writeln(' $ bii --help TOOL [TOOL2]\n')
for... | out.write(' %-10s ' % class_.group, Color.GREEN)
out.writeln(class_.__doc__)
else:
# Tools, as main commands
for group, class_ in self.iteritems():
if group not in argv and 'all' not in argv:
continue
out.writeln('----... |
mpvoss/RickAndMortyWeatherTweets | env/lib/python3.5/site-packages/pyowm/commons/weather_client.py | Python | mit | 4,935 | 0.001216 | """
Module containing classes for HTTP client/server interactions
"""
# Python 2.x/3.x compatibility imports
try:
from urllib.error import HTTPError, URLError
from urllib.parse import urlencode
except ImportError:
from urllib2 import HTTPError, URLError
from urllib import urlencode
import socket
from ... | lse:
data = response.read().decode('utf-8')
cache.set(API_full_url, data)
return data
def call_API(self, API_endpoint_URL, params_dict,
timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
| """
Invokes a specific OWM web API endpoint URL, returning raw JSON data.
:param API_endpoint_URL: the API endpoint to be invoked
:type API_endpoint_URL: str
:param params_dict: a dictionary containing the query parameters to be
used in the HTTP request (given as key... |
di/ppa | stats.py | Python | mit | 2,062 | 0.022793 | #!/usr/bin/python
import fetch
import sys
from pymongo import MongoClient
db = MongoClient().ppa.ticket
for loc in db.distinct('location'):
print loc
sys.exit(1)
''' Getting the count | for each date
for date in sorted(db.distinct('issueDate')):
print "%s: %s" % (date, db.find({'issueDate':date}).count())
'''
min_id = db.find().sort([('_id', 1)]).limit(1)[0]['_id'] - 1
max_id = db.find().sort([('_id', -1)]).limit(1)[0]['_id'] + 1
i = (min_id % 1000) % 200
block_start = min_id - i + 1
_total =... | rt, '$lte':block_end}}).count()
try :
start_date = db.find({'_id':{'$gte':block_start,'$lte':block_end},'issueTime':{'$exists':True}}).sort([('_id', 1)]).limit(1)[0]['issueTime']
except :
start_date = "???"
try :
end_date = db.find({'_id':{'$gte':block_start,'$lte':block_end},'issueT... |
opendoor-labs/rets | rets/http/parsers/parse_object.py | Python | mit | 4,892 | 0.001635 | import mimetypes
from typing import Optional, Sequence
import cgi
from requests import Response
from requests.structures import CaseInsensitiveDict
from requests_toolbelt.multipart.decoder import MultipartDecoder
from rets.errors import RetsApiError, RetsResponseError
from rets.http.data import Object
from rets.http.... | k line, and a body area.
HTTP/1.1 200 OK
Server: Apache/2.0.13
Date: Fri, 22 OCT 2004 12:03:38 GMT
Cache-Control: private
RETS-Version: RETS/1.7.2
MIME-Version: 1.0
Content-Type: multipart/parallel; boundary="simple boundary"
--simple boundary
Content-Type: image/jpeg
Content-I... | undary
Content-Type: text/xml
Content-ID: 123457
Object-ID: 1
<RETS ReplyCode="20403" ReplyText="There is no listing with that ListingID"/>
--simple boundary--
"""
encoding = response.encoding or DEFAULT_ENCODING
multipart = MultipartDecoder.from_response(response, encoding)
# We n... |
stacybird/CS510CouchDB | scripts/csv_to_json.py | Python | apache-2.0 | 651 | 0.029186 | #!/usr/bin/env python
import sys
import csv
import json
if len(sys.argv) != 3:
print 'Inco | rrect number of arguments.'
print 'Usage: csv_to_json.py path_to_csv path_to_json'
exit()
print 'Argument List:', str(sys.argv)
csvFileName = sys.argv[1]
jsonFileName = sys.argv[2]
csvFile = open (csvFileName, 'rU')
myReader = csv.reader(csvFile)
header = myReader.next()
print "Header fields:", header
myReade | r = csv.DictReader( csvFile, fieldnames = header)
parsedJson = json.dumps( [ row for row in myReader ] )
print "JSON parsed."
jsonFile = open( jsonFileName, 'w')
jsonFile.write(parsedJson)
print "JSON saved to: ", jsonFileName
|
JavaRabbit/CS496_capstone | codelabs/flex_and_vision/main.py | Python | apache-2.0 | 4,034 | 0 | # Copyright 2017 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 required by applicable law or a... | a new blob and upload the file's content.
blob = bucket.blob(photo.filename)
blob.upload_from_string(
photo.read(), content_type=photo.content_type)
# Make the blob publicly viewable.
blob.make_public()
# Create a Cloud Vision client.
vision_client = vision.Client()
# Use the ... | for our image.
source_uri = 'gs://{}/{}'.format(CLOUD_STORAGE_BUCKET, blob.name)
image = vision_client.image(source_uri=source_uri)
faces = image.detect_faces(limit=1)
# If a face is detected, save to Datastore the likelihood that the face
# displays 'joy,' as determined by Google's Machine Learni... |
mathblogging/mathblogging | dataexport.py | Python | agpl-3.0 | 4,361 | 0.016969 | from main import *
from django.utils import simplejson
class CsvView(CachedPage):
cacheName = "CsvView"
mimeType = "text/csv"
selfurl = "database.csv"
def generatePage(self):
output = []
output.append( """title, homepage, person, category, posts_url, comments_url, priority, fav... | t)
class OPMLView(CachedPage):
cacheName = "OPMLView"
mimeType = "application/xml"
| selfurl = "database-opml.xml"
def generatePage(self):
output = []
output.append("""<?xml version="1.0" encoding="UTF-8"?> <opml version="1.0">
<head>
<title>Mathblogging.org Database export to OPML</title>
</head>
<body><outline title="Mathblogging.org" text="Mathblogging.o... |
ColinDuquesnoy/QCrash | qcrash/_forms/dlg_github_login_ui.py | Python | mit | 3,196 | 0.003755 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file '/home/colin/dev/QCrash/forms/dlg_github_login.ui'
#
# Created by: PyQt5 UI code generator 5.5.1
#
# WARNING! All changes made in this file will be lost!
from qcrash.qt import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
def setupU... | ign in to github"))
self.lbl_html.setText(_translate("Dialog", | "<html><head/><body><p align=\"center\"><img src=\":/rc/GitHub-Mark.png\"/></p><p align=\"center\">Sign in to GitHub</p></body></html>"))
self.label_2.setText(_translate("Dialog", "Username:"))
self.label_3.setText(_translate("Dialog", "Password: "))
self.cb_remember.setText(_translate("Dialog"... |
libyal/libfsntfs | tests/pyfsntfs_test_support.py | Python | lgpl-3.0 | 1,560 | 0.005128 | #!/usr/bin/env python
#
# Python-bindings support functions test script
#
# Copyright (C) 2010-2022, Joachim Metz <joachim.metz@gmail.com>
#
# Refer to AUTHORS for acknowledgements.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as ... | 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 Lesser General Public License
# along with this program. If not, see <https://ww... | rtFunctionsTests(unittest.TestCase):
"""Tests the support functions."""
def test_get_version(self):
"""Tests the get_version function."""
version = pyfsntfs.get_version()
self.assertIsNotNone(version)
if __name__ == "__main__":
argument_parser = argparse.ArgumentParser()
argument_parser.add_argu... |
takinbo/rapidsms-borno | apps/logger/models.py | Python | lgpl-3.0 | 675 | 0.013333 | #!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
import django
from django.db import models
class MessageBase(models.Model):
text = models.CharField(max_length=140)
# TODO save connection title rather than wacky object string?
identity = models.CharField(max_length=150)
backend = models.CharField(max_... | abstract = True
class IncomingMessage(MessageBase):
| received = models.DateTimeField(auto_now_add=True)
class OutgoingMessage(MessageBase):
sent = models.DateTimeField(auto_now_add=True)
|
tbenthompson/quadracheer | interpolate_rl5.py | Python | mit | 496 | 0.002016 | # I was jus | t curious how well I could approximate the rl5 starting values
# with an interpolative scheme
from quadracheer.rl5 import *
import numpy as np
import matplotlib.pyplot as plt
fnc = lambda ay, by: mu_5_4(ay, by, k1(ay, by), k2(ay, by))
ay = np.linspace(-2, 2, 100)
by = np.linspace(-2.0, 2.0, 100)
Ay, By = np.meshgrid... | ow()
|
mazafrav/JdeRobot | src/drivers/MAVLinkServer/modules/mavproxy_smartcamera/sc_main.py | Python | gpl-3.0 | 7,941 | 0.004282 | import time
import math
import cv2
from pymavlink import mavutil
from droneapi.lib import VehicleMode, Location
import sc_config
from sc_video import sc_video
from sc_webcam import SmartCameraWebCam
from sc_SonyQX1 import SmartCamera_SonyQX
"""
sc_main.py - runs top level smart camera function
To run this module:
* R... | get_frame()
# save image for debugging later
if not self.writer is None:
self.writer.write(f)
def run(self):
while True:
# ask all cameras to take a picture
self.take_picture_all()
# store images to disk
self.save_picture_all()
... | # only process images once home has been initialised
if self.check_home():
# start video if required
self.check_video_out()
# check if we are controlling the vehicle
self.check_status()
# ask all cameras to ta... |
mikrosimage/OpenRenderManagement | src/pulitools/puliquery/settings.py | Python | bsd-3-clause | 556 | 0.001799 | #!/usr/bin/python2.6
# -*- coding: utf8 -*-
"""
settings. | py: Config des utilitaires pul_* permettant la consultation et l'edition des jobs en batch
"""
__author__ = "Jerome Samson"
__copyright__ = "Copyright 2013, Mikros Image"
class Settings(object):
# Global tools attributes
verbose = False
# Initial server/port config
hostname = "puliserver"
port = ... | cise_time_format = '%H:%M:%S'
|
chromium2014/src | tools/telemetry/telemetry/core/platform/profiler/perf_profiler.py | Python | bsd-3-clause | 8,787 | 0.008649 | # 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.
import logging
import os
import re
import signal
import subprocess
import sys
import tempfile
from telemetry.core import platform
from telemetry.core import... | .relpath(path, os.curdir)
return rel_path if len(rel_path) < len(path) else path
def _PrepareHostForPerf():
kptr_file = '/proc/sys/k | ernel/kptr_restrict'
with open(kptr_file) as f:
if f.read().strip() != '0':
logging.warning('Making kernel symbols unrestricted. You might have to '
'enter your password for "sudo".')
with tempfile.NamedTemporaryFile() as zero:
zero.write('0')
zero.flush()
subprocess.... |
hpbader42/Klampt | Python/klampt/sim/simlog.py | Python | bsd-3-clause | 14,115 | 0.011335 | from ..math import vectorops,so3,se3
class SimLogger:
"""A CSV logger for a simulation. """
def __init__(self,sim,state_fn,contact_fn=None,colliding='all',saveheader=True):
"""
Logs a simulation to a CSV file.
Arguments:
- sim: the klampt.Simulator object you wish to use
... | cvalues = [sim.getTime(),body1,body2,len(clist)]
cvalues += pavg
cvalues += navg
cvalues += f
| cvalues += m
self.f_contact.write(','.join(str(v) for v in cvalues))
self.f_contact.write('\n')
if extra:
values += extra
if not (self.f is None):
self.f.write(','.join([str(v) for v in values]))
self.f.wri... |
WildBill567/nn-toy | neat/phenome.py | Python | gpl-3.0 | 8,014 | 0.002496 | # Copyright (C) 2016 William Langhoff WildBill567@users.noreply.github.com
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your optio... | is program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARR | ANTY; 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
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Adapt... |
cboyce93/epitome-xl | src/util/treestore_functions.py | Python | gpl-3.0 | 316 | 0 | import pygtk
import gtk
import dill
pygtk.require('2.0')
class TreeStoreFunctions():
def get_children(self, root_iter):
c | hildren = []
for i in range(0, self.treestore.iter_n_children(root_iter)):
c | hildren.append(self.treestore.iter_nth_child(root_iter, i))
return children
|
drglove/SickRage | sickbeard/notifiers/libnotify.py | Python | gpl-3.0 | 5,007 | 0.003795 | # Author: Nic Wolfe <nic@wolfeden.ca>
# URL: http://code.google.com/p/sickbeard/
#
# This file is part of SickRage.
#
# SickRage is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License,... | bus = dbus.SessionBus()
except dbus.DBusException, e:
return (u"<p>Error: unable to connect to D-Bus session bus: <code>%s</code>."
| u"<p>Are you running SickRage in a desktop session?") % (cgi.escape(e),)
try:
bus.get_object('org.freedesktop.Notifications',
'/org/freedesktop/Notifications')
except dbus.DBusException, e:
return (u"<p>Error: there doesn't seem to be a notification dae... |
mcallaghan/tmv | BasicBrowser/parliament/migrations/0030_auto_20180430_1447.py | Python | gpl-3.0 | 556 | 0.001799 | # -*- | coding: utf-8 -*-
# Generated by Django 1.11.3 on 2018-04-30 14:47
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('parliament', '0029_auto_20180323_1039'),
]
operations = [
migrations.AlterField(
... | 'Objection'), (4, 'Amusement'), (5, 'Laughter'), (6, 'Outcry')]),
),
]
|
FederatedAI/FATE | python/federatedml/transfer_variable/transfer_class/oblivious_transfer_transfer_variable.py | Python | apache-2.0 | 1,391 | 0.002876 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2019 The FATE Authors. All Righ | ts 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 applicable law or agreed to in writing, software
# ... | n "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.
#
################################################################################
#
# AUTO GENERATED TRANSFER VARIABLE C... |
bgris/ODL_bgris | lib/python3.5/site-packages/spyder/widgets/projects/type/python.py | Python | gpl-3.0 | 2,795 | 0 | # -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright © Spyder Project Contributors
#
# Licensed under the terms of the MIT License
# (see spyder/__init__.py for details)
# -----------------------------------------------------------------------------
... | honpath(self):
"" | "Return a copy of pythonpath attribute"""
return self.pythonpath[:]
def set_pythonpath(self, pythonpath):
"""Set project's PYTHONPATH"""
self.pythonpath = pythonpath
self.save()
def remove_from_pythonpath(self, path):
"""Remove path from project's PYTHONPATH
... |
watsonbox/xbmc-confreaks | api/video.py | Python | gpl-3.0 | 558 | 0.010753 | class Video(object):
def __init__(self, json):
self.id = json['id']
self.slug = json['slug']
self.title = json['title']
| self.presenters = json['presenters']
self.host = json['host']
self.embed_code = json['embed_code']
| def presenter_names(self):
return ', '.join(map(lambda p: p['first_name'] + ' ' + p['last_name'], self.presenters))
def url(self):
return 'plugin://plugin.video.%s/?action=play_video&videoid=%s' % (self.host, self.embed_code)
def is_available(self):
return True if self.embed_code else False
|
Aravinthu/odoo | addons/point_of_sale/models/__init__.py | Python | agpl-3.0 | 368 | 0 | # -*- coding: utf-8 -*-
# Part of Odo | o. See LICENSE file for full copyright and licensing details.
from . import account_bank_statement
from . import account_journal
from . import barcode_rule
from . import pos_category
from . import pos_config
from . import pos_order
from . import pos_session
from . import product
from . import res_partner
from . impo | rt res_users
|
endlessm/chromium-browser | third_party/chromite/lib/build_target_lib_unittest.py | Python | bsd-3-clause | 1,720 | 0.004651 | # -*- coding: utf-8 -*-
# Copyright 2019 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""build_target_lib tests."""
from __future__ import print_function
import os
from chromite.lib.build_target_lib import BuildTa... | .assertEqual(bt1, bt2)
self.assertNotEqual(bt1, bt3)
def testInvalidName(self):
"""Test invalid name check."""
with self.assertRaises(InvalidNameError):
BuildTarget('')
def testNormalRoot(self):
"""Test normalized sysroot path."""
target = BuildTarget('board', build_root=self.sysroot)
... | path."""
target = BuildTarget('board', build_root=self.sysroot_denormalized)
self.assertEqual(self.sysroot, target.root)
def testDefaultRoot(self):
"""Test the default sysroot path."""
target = BuildTarget('board')
self.assertEqual('/build/board', target.root)
|
patta42/pySICM | pySICM.py | Python | gpl-3.0 | 1,938 | 0.006192 | #!/usr/ | bin/python
# Copyright (C) 2015 Patrick Happel <patri | ck.happel@rub.de>
#
# This file is part of pySICM.
#
# pySICM 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.
#
# pySICM is distributed... |
butchman0922/gourmet | gourmet/plugins/import_export/html_plugin/html_exporter.py | Python | gpl-2.0 | 12,913 | 0.013785 | import re, os.path, os, xml.sax.saxutils, time, shutil, urllib, textwrap
from gettext import gettext as _
from gourmet import convert,gglobals
from gourmet.exporters.exporter import ExporterMultirec, exporter_mult
HTML_HEADER_START = """<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
"... | temprop:
self.out.write('<p class="%s"><span class="label">%s:</span> <span itemprop="%s">%s</span></p>\n' % (attr, label.capitalize(), itemprop, xml.sax.saxutils.escape(text)))
else:
self.out.write("<p class='%s'><span class='label'>%s:</span> %s</p>\n"%(attr, label.capitali... | ))
def write_attr_foot (self):
self.out.write("</div>")
def write_grouphead (self, name):
self.out.write("<li class='inggroup'>%s:<ul class='ing'>"%name)
def write_groupfoot (self):
self.out.write("</ul></li>")
def write_ingref (self, a... |
MsStryker/Games | sudoku/default.py | Python | mit | 4,916 | 0 | # -*- coding: utf-8 -*-
from collections import Counter
from copy import deepcopy
from math import sqrt
from random import sample as random_sample
from string import ascii_uppercase
class SudokuBoard(object):
"""Create a Sudoku Board of variable size
The method will create the random sudoku Board
of vari... | elf.board = self.get_initial_matrix()
for i in range(0, self.base_iterations):
self.swap_columns()
self.swap_rows()
return self.board
def | swap_columns(self):
"""Swap the columns and return the board"""
board = self.board
swap_list = range(0, self.size)
for i in range(0, self.size, self.base):
l_ind = i
r_ind = i + self.base
for j in range(self.base - 1):
swap = random_sa... |
CSC301H-Fall2013/Ultra-Remote-Medicine | sample/admin.py | Python | mit | 1,569 | 0.007648 | from django.contrib import admin
from django import forms
from django.contrib.auth.models import User
from sample.models import (Doctor, Worker, Patient, SpecialtyType, TimeSlot, Case, Comment, CommentGroup,
Scan)
class searchDoctor(admin.ModelAdmin):
list_display = ['user_first_name', 'user_last_name', '... | me']
class searchWorker(admin.ModelAdmin):
list_display = ['user_first_name', 'user_last_name']
search_fields = ['user__first_name', 'user__last_name']
class searchPatient(admin.ModelAdmin):
list_display = ['first_name', 'last_name']
| search_fields = ['first_name', 'last_name']
class searchSpeciality(admin.ModelAdmin):
search_fields = ['name']
list_display = ['name']
class searchTimeslot(admin.ModelAdmin):
search_fields = ['start_time', 'end_time']
class searchCase(admin.ModelAdmin):
search_fields = ['id']
list_display = ['... |
fHachenberg/pyecstaticalib | Ecstatica/PixelEncoding.py | Python | gpl-3.0 | 6,356 | 0.013845 | # coding: utf-8
#Created on 05.06.2012
#Copyright (C) 2013 Fabian Hachenberg
#This file is part of EcstaticaLib.
#EcstaticaLib is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation, either version 3 of the License... | uct.unpack(structstr, viewfileobj.read(len_a))
decodePi | xels(packed_pixeldata_a)
structstr = "".join(itertools.repeat("B", len_b))
packed_depthdata = struct.unpack(structstr, viewfileobj.read(len_b))
decodePixelsWords(packed_depthdata)
|
markgw/pimlico | src/python/pimlico/datatypes/corpora/formatters/json.py | Python | gpl-3.0 | 313 | 0 | import json
from pimlico.datatypes.corpora.json import JsonDocumentType
from pimlico.cli.browser.tools.formatter import DocumentBrowserFormatter
class JsonFormatter(DocumentBrowserFormatter):
| DATATYPE = JsonDoc | umentType()
def format_document(self, doc):
return json.dumps(doc.data, indent=4)
|
narasimhan-v/avocado-misc-tests-1 | io/net/bridge.py | Python | gpl-2.0 | 4,362 | 0.000229 | #!/usr/bin/env python
# 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 the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
# See LICENSE for more details.
#
# Copyright: 2017 IBM
# Author: Harish Sriram <harish@linux.vnet.ibm.com>
# Bridge interface test
import os
import netifaces
fro... | ocado.utils import process
from avocado.utils.network.interfaces import NetworkInterface
from avocado.utils.network.hosts import LocalHost
class Bridging(Test):
'''
Test bridge interface
'''
def check_failure(self, cmd):
if process.system(cmd, sudo=True, shell=True, ignore_status=True):
... |
unicefuganda/edtrac | edtrac_project/rapidsms_polls/poll/app.py | Python | bsd-3-clause | 3,327 | 0.010219 | # -*- coding: utf-8 -*-
import rapidsms
import datetime
from rapidsms.apps.base import AppBase
from .models import Poll
from django.db.models import Q
from rapidsms_httprouter.models import Message,MessageBatch
class App(AppBase):
def respond_to_message(self,message,response_msg,poll):
if response_msg ==... | response_obj, response_msg = poll.process_response(message)
if poll.response_type == Poll.RESPONSE_TYPE_ONE :
if not response_obj.has_errors or old_response.has_errors:
old_response.delete()
if hasattr(mess... | age.handled_by = 'poll'
db_message.save()
if response_msg and response_msg.strip():
self.respond_to_message(message,response_msg,poll)
else:
response_obj.delete()
... |
wangjun/pythoner.net | pythoner/topic/views.py | Python | gpl-3.0 | 9,196 | 0.015263 | #encoding:utf-8
"""
pythoner.net
Copyright (C) 2013 PYTHONER.ORG
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Th... | =request.user,deleted=False)
| except (ValueError,Topic.DoesNotExist):
raise Http404()
else:
topic.deleted = True
topic.save()
set(request) # 记录用户操作次数
return HttpResponseRedirect('/topic/')
def detail(request,topic_id):
current_page = 'topic'
"""
话题详细页面
"""
next = '/topic/... |
ricardonhuang/blog | app/decorators.py | Python | gpl-3.0 | 516 | 0.001938 | #coding=utf-8
from functools import wraps
from flask import abort
from flask_login | import current_user
from app.models import Permission
def permission_required(permission):
def decorator(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if not current_user.can(permission):
abort(403)
return f(*args, **kwargs)
return decorated... | f admin_required(f):
return permission_required(Permission.ADMINISTER)(f)
|
bootcamptropa/django | races/migrations/0002_auto_20160119_1628.py | Python | mit | 870 | 0.002299 | # -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2016-01-19 15:28
from __future__ import unicode_literals
import datetime
from django.db import migrations, models
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('races', '0001_initial'),
]
opera... | tions.AddField(
model_name='race',
name='updated_at',
field=models.DateTimeField(auto_now=True, defa | ult=datetime.datetime(2016, 1, 19, 15, 28, 36, 816957, tzinfo=utc)),
preserve_default=False,
),
]
|
dbischof90/sdetools | tests/test_scheme_implementations.py | Python | mit | 6,216 | 0.005952 | import functools as ft
import math
from collections import OrderedDict
import numba
import numpy as np
from sde import SDE
# from simulation.strong.explicit.predictorcorrector import Order_10 as pc_e
from simulation.strong.explicit.rk import Order_10 as rk_e
from simulation.strong.explicit.taylor import Order_05 as E... | 103259, -0.00915205, 0.01928274, 0.09207789, -0.13199381,
0.17663064, 0.1333172, -0.01288733, -0.31281056, -0.05924482,
-0.01702982, 0.18025385, -0.17514341, 0.03477228, 0.31712905,
... | 494, -0.13901742,
-0.15492822, 0.0384501, -0.0544241, -0.15041881, -0.07649629,
0.07692755, -0.12122493, 0.18393892, 0.12113368, 0.10871338,
-0.1328373, -0.05468304... |
mationic/pyload | module/plugins/hoster/Keep2ShareCc.py | Python | gpl-3.0 | 4,411 | 0.007255 | # -*- coding: utf-8 -*-
import re
import urlparse
from module.plugins.captcha.ReCaptcha import ReCaptcha
from module.plugins.internal.SimpleHoster import SimpleHoster, create_getInfo
class Keep2ShareCc(SimpleHoster):
__name__ = "Keep2ShareCc"
__type__ = "hoster"
__version__ = "0.25"
__status__... | (errmsg)
m = re.search(self.WAIT_PATTERN, self.html)
if m:
self.log_debug("Hoster told us to wait for %s" % m.group(1))
#: String to time convert court | esy of https://stackoverflow.com/questions/10663720
ftr = [3600, 60, 1]
wait_time = sum(a * b for a, b in zip(ftr, map(int, m.group(1).split(':'))))
self.wantReconnect = True
self.retry(wait_time=wait_time, msg="Please wait to download this file")
self.info.pop(... |
fengyqf/wildmatch | wildmatch.py | Python | gpl-2.0 | 2,849 | 0.023619 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
待匹配的数据 (tofill)及匹配数据池(pool),存储于csv文件中,两个csv都要包含主键列,
及数据列。脚本将对tofill的每一条数据字段,在pool文件的数据列中做匹配,如果pool
数据列包含tofile列数据,则将各自主键列建立一条关系记录,存储在结果文件csv中
以上提到的csv文件,格式要求:
使用逗号分隔,字段可以使用双引号括起。
不支持字段内换行
必须包含主键列,主键列不得重复
主键列在数据列后
----
事实上,两表主键列可以重复,只不过对应关系也是重复的;恰好需此... | 01,AAAA,90001,AAAA/xyz
202,BBBB,20003,12BBBB
---------------------------------
"""
pool_path='pool.csv'
pool_pk_index=0
pool_data_index=1
tofill_path='tofill.csv'
tofill_pk_index=0
tofill_data_index=1
# 每处理指定次数,报告一次处理行数
tick_every_lines=100
import sys
import csv
pool=[]
tofill=[]
match=[]
reader=csv.reader(f... | _index],line[pool_data_index]])
print 'pool file loaded, %s lines'%(len(pool))
reader=csv.reader(file(tofill_path,'rb'))
for line in reader:
if len(line)>=pool_data_index:
tofill.append([line[pool_pk_index],line[pool_data_index]])
tofill_count=len(tofill)
print 'tofill file loaded, %s lines'%(tofill_co... |
qubs/climate-data-api | herbarium_data/models.py | Python | apache-2.0 | 3,109 | 0.002252 | import datetime
from django.db import models
from django.core.exceptions import ValidationError
def validate_year(year):
if year is None:
return # Years can be null
if year < 1800 or year > datetime.datetime.now().year:
raise ValidationError("Not a valid year.")
def validate_day_of_month(d... |
updated = models.DateTimeField(auto_now=True)
dataset = models.CharField(max_length=50, default="")
genus = models.CharField(max_length=50, default="", db_index=True)
species = models.CharField(max_length=50, default="", db_index=True)
common_name = models.CharField(max_length=255, default="")
... | year_collected = models.PositiveSmallIntegerField(null=True, validators=[validate_year])
month_collected = models.PositiveSmallIntegerField(null=True, choices=MONTH_CHOICES)
day_collected = models.PositiveSmallIntegerField(null=True, validators=[validate_day_of_month])
collectors = models.TextField(def... |
pdunnigan/namefileparse | namefileparse/__init__.py | Python | mit | 1,123 | 0.016919 | # Copyright | (c) 2012 Patrick Dunnigan
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in the
# Software without restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute | , sublicense, and/or sell copies of
# the Software, and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED ... |
Jgarcia-IAS/Fidelizacion_odoo | openerp/extras/jasper_server/__openerp__.py | Python | agpl-3.0 | 2,744 | 0 | # -*- coding: utf-8 -*-
##############################################################################
#
# jasper_server module for OpenERP
# Copyright (c) 2008-2009 EVERLIBRE (http://everlibre.fr) Eric VERNICHON
# Copyright (C) 2009-2011 SYLEAM ([http://www.syleam.fr]) Christophe CHAUVET
#
# This file is a... | ##########
{
'name': 'JasperReport Server Interface',
'version': '6.3',
'category': 'Reporting',
'sequence': 20,
'complexity': "expert",
'description': """This module interface JasperReport Server with OpenERP
Features:
- Document source must be in CSV, XML
- Save document as attachment on obje... | m fields function)
- Affect group on report
- Use context to display or not the print button
(eg: in stock.picking separate per type)
- Execute SQL query before and after treatement
- Launch report based on SQL View
- Add additional pages at the begining or at the end of the document
This module required library t... |
vincentdavis/corrupt_image_finder | test_images/RandomMutateImage.py | Python | bsd-3-clause | 73 | 0.013699 | im = open('006993 | _photoA. | tif', 'rb')
ord(im.read(1))
chr(ord(im.read(1))) |
polyaxon/polyaxon | core/tests/test_polypod/test_contexts.py | Python | apache-2.0 | 14,317 | 0.000279 | #!/usr/bin/python
#
# Copyright 2018-2021 Polyaxon, 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 ... | text_root),
"name": "run",
"uuid": "uu | id",
"namespace": "test",
"iteration": None,
"created_at": None,
"compiled_at": None,
"schedule_at": None,
"started_at": None,
"finished_at": None,
"duration": None,
"cloning_k... |
skraghu/softlayer-python | SoftLayer/CLI/block/replication/order.py | Python | mit | 2,315 | 0 | """Order a block storage replica volume."""
# :license: MIT, see LICENSE for more details.
import click
import SoftLayer
from SoftLayer.CLI import environment
from SoftLayer.CLI import exceptions
CONTEXT_SETTINGS = {'token_normalize_func': lambda x: x.upper()}
@click.command(context_settings=CONTEXT_SETTINGS)
@cli... | pshot_schedule,
location=location,
tier=tier,
os_type=os_type,
| )
except ValueError as ex:
raise exceptions.ArgumentError(str(ex))
if 'placedOrder' in order.keys():
click.echo("Order #{0} placed successfully!".format(
order['placedOrder']['id']))
for item in order['placedOrder']['items']:
click.echo(" > %s" % item['descript... |
ReapOmen/open-media | openmedia/player/track.py | Python | gpl-3.0 | 2,287 | 0 | import os.path
from gi.repository import Gst, GstPbutils
DEFAULT_IMAGE_PATH = './openmedia/gui/res/img/no_image.png'
class Track(object):
"""
This holds data abo | ut media files.
The inform | ation about the media file associated with this includes
the name, file path, duration and metadata.
"""
def __init__(self, file_path):
"""
Create a track using data from the specified file.
Parameters
----------
:param file_path: the path of the file out of which t... |
srio/oasys-comsyl | orangecontrib/comsyl/scripts/load_results_from_file.py | Python | mit | 2,411 | 0.014102 | import numpy
from srxraylib.plot.gol import plot_image, plot
import sys
from comsyl.scripts.CompactAFReader import CompactAFReader
def plot_stack(mystack,what="intensity",title0="X",title1="Y",title2="Z"):
from silx.gui.plot.StackView import StackViewMainWindow
from silx.gui import qt
app = qt.QAppl... | sv.setStack(numpy.angle(mystack,deg=True))
else:
raise Exception("Undefined label "+what)
sv.se | tLabels([title0,title1,title2])
sv.show()
app.exec_()
def load_stack(filename):
# filename = "/users/srio/OASYS_VE/comsyl_srio/calculations/new_u18_2m_1h_s2.5"
reader = CompactAFReader(filename)
print("File %s:" % filename)
print("contains")
print("%i modes" % reader.number_modes())
p... |
DayGitH/Python-Challenges | DailyProgrammer/DP20170414C.py | Python | mit | 1,976 | 0.005567 | """
[2017-04-14] Challenge #310 [Hard] The Guards and the Mansion
https://www.reddit.com/r/dailyprogrammer/comments/65fkwh/20170414_challenge_310_hard_the_guards_and_the/
# Description
I recently came into some money and built myself a mansion. And I'm afraid of robbers who now want to come and steal
the rest of my m... | presenting the
coordinates. For *every* row of input please tell me how many different triangles I can have - that is arrangements of
3 occupied towers. I like diversity, let's keep the | thieves guessing as to where the towers are occupied every night.
# Input Description
You'll be given an integer on the first line telling you how many lines of tower coordinate pairs to read. Example:
4
3 -1
-1 3
-1 -1
-5 -2
# Output Description
For *every row of input* tell me how many triangles ... |
google/gnxi | oc_config_validate/oc_config_validate/models/vlan.py | Python | apache-2.0 | 1,672 | 0.009569 | # -*- coding: utf-8 -*-
from operator import attrgetter
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType
from pyangbind.lib.yangtypes import RestrictedClassType
from pyangbind.lib.yangtypes import TypedListType
from pyangbind.lib.yangtypes import YANGBool
from pyangbind.lib.yangtypes import YANGListTy... | associated with interfaces
"""
_pyangbind_elements = {}
class openconfig_vlan(PybindBase):
"""
This class was auto-generated by the PythonClass plugin for PYANG
from YANG module openconfig-vlan - based on the path /openconfig- | vlan. Each member element of
the container is represented as a class variable - with a specific
YANG type.
YANG Description: This module defines configuration and state variables for VLANs,
in addition to VLAN parameters associated with interfaces
"""
_pyangbind_elements = {}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.