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 |
|---|---|---|---|---|---|---|---|---|
Aptitudetech/ERPNext | erpnext/hr/doctype/expense_claim/expense_claim.py | Python | cc0-1.0 | 8,629 | 0.027466 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.utils import get_fullname, flt, cstr
from frappe.model.document import Document
from erpnext.hr.utils imp... | _amount_reimbursed", amt)
doc.set_status()
frappe.db.set_value("Expense Claim", doc.name , "status", doc.status)
@frappe.whitelist()
def get_expense_approver(doctype, txt, searchfield, start, page_len, filters):
return frappe.db.sql("""
select u.name, concat(u.first_name, ' ', u.last_name)
from tabUser u, `tab... | over'
and u.enabled = 1 and u.name like %s
""", ("%" + txt + "%"))
@frappe.whitelist()
def make_bank_entry(docname):
from erpnext.accounts.doctype.journal_entry.journal_entry import get_default_bank_cash_account
expense_claim = frappe.get_doc("Expense Claim", docname)
default_bank_cash_account = get_default_ba... |
mark-r-g/hydrus | download_cms_data.py | Python | gpl-3.0 | 1,762 | 0.000568 | from io import BytesIO
from hashlib import sha1
from os.path import isdir, join, abspath, dirname
from zipfile import ZipFile, ZIP_DEFLATED
from urllib.request import urlopen
import hydrus.constants as c
class WrongSha1Error(Exception): pass
URL = (
# "https://www.qualitynet.org/dcs/BlobServer",
"http://ww... | with ZipFile(bio, compression=ZIP_DEFLATED) as z:
z.extractall(path=DEST)
else:
raise WrongSha1Error("Incorrect SHA1 hash.")
except Exception as e:
print('Download failed:', e)
else:
print('Download complete.', end='\n\n')
if ... | fd3e9b88427aa9932557d17cd0b4be640',
)
download_cms_data(
1228890620679,
'SAS_Data-Input_Oct2016.zip',
'62ab0e94811842f3212196e203cd95374fbb10d4',
)
|
jbornschein/mca-genmodel | pulp/em/camodels/mmca_et.py | Python | agpl-3.0 | 16,713 | 0.013881 | #
# Author: Jorg Bornschein <bornschein@fias.uni-frankfurt.de)
# Lincense: Academic Free License (AFL) v3.0
#
from __future__ import division
import numpy as np
from math import pi
from scipy.misc import comb
from mpi4py import MPI
import pulp.em as em
import pulp.utils.parallel as parallel
import pulp.utils.tra... | neal, model_params, my_suff_stat, my_data):
""" MCA M_step
my_data variables used:
my_data[ | 'y'] Datapoints
my_data['candidates'] Candidate H's according to selection func.
Annealing variables used:
anneal['T'] Temperature for det. annealing AND softmax
anneal['N_cut_factor'] 0.: no truncation; 1. trunc. according to model
"""... |
ray-project/ray | python/ray/serve/http_adapters.py | Python | apache-2.0 | 1,762 | 0.001703 | from io import BytesIO
from typing import List, Optional, Union
from fastapi import File
from p | ydantic import BaseModel, Field
import numpy | as np
from ray.serve.utils import require_packages
from ray.ml.predictor import DataBatchType
_1DArray = List[float]
_2DArray = List[List[float]]
_3DArray = List[List[List[float]]]
_4DArray = List[List[List[List[float]]]]
class NdArray(BaseModel):
"""Schema for numeric array input."""
array: Union[_1DArra... |
3D-e-Chem/snooker-alignment | scripts/entropy.py | Python | apache-2.0 | 4,710 | 0.00276 | #!/usr/bin/env python
"""
Calculate entropies of each leaf on each branch node of a tree for each column
Usage:
entropy.py -a ali.s9t100.fa -n gpcrdb_gapped_tm_numbering.csv -t ali.s9t100.ph > ali.s9t100.entropies
"""
import argparse
import collections
import logging
import math
from Bio import Phylo, AlignIO
im... | umentParser(description='Calculate entropies of each leaf on each branch node of a tree for each column')
parser.add_argument('-a', '--alignment', type=argparse.FileType('r'), required=True, help='Multiple sequence alignment (fasta format)')
parser.add_argument('-n', '--numbering', type=argparse.FileType('r'), required... | numbering scheme')
parser.add_argument('-t', '--tree', type=argparse.FileType('r'), required=True, help='Tree of multiple sequence alignment (newick format)')
parser.add_argument('--min_node_size', type=int, default=20, help='Calculate entropies for nodes with a minimum number of leafs')
parser.add_argument('--max_node... |
Niektory/fifengine | engine/python/fife/extensions/cegui/ceguibasicapplication.py | Python | lgpl-2.1 | 4,811 | 0.027229 | # -*- coding: utf-8 -*-
# ####################################################################
# Copyright (C) 2005-2013 by the FIFE team
# http://www.fifengine.net
# This file is part of FIFE.
#
# FIFE is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
#... | import fife
from fife.extensions.basicapplication import ApplicationBase
import PyCEGUI
class CEGUIEventListener(fife.IKeyLi | stener, fife.ICommandListener):
"""
Default, rudimentary event listener.
Will cause the application to quit on pressing ESC.
"""
def __init__(self, app):
self.app = app
self.engine = app.engine
eventmanager = self.engine.getEventManager()
#eventmanager.setNonConsumableKeys([fife.Key.ESCAPE])
fife.IKeyLi... |
bswartz/manila | manila/share/drivers/dell_emc/plugins/isilon/isilon.py | Python | apache-2.0 | 20,977 | 0 | # Copyright 2015 EMC Corporation
# 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... | o a container."""
return os.path.join(self._root_dir, share['name'])
def create_share(self, context, share, share_server):
"""Is called to create share."""
if share['share_proto'] == 'NFS':
location = self._create_nfs_share(share)
elif share['share_proto'] == 'CIFS':
... | location = self._create_cifs_share(share)
else:
message = (_('Unsupported share protocol: %(proto)s.') %
{'proto': share['share_proto']})
LOG.error(message)
raise exception.InvalidShare(reason=message)
# apply directory quota based on share s... |
spaceone/pyjs | pyjswidgets/pyjamas/ui/RichTextAreaConsts.py | Python | apache-2.0 | 998 | 0.001002 | """
* Copyright 2007 Google Inc.
# Copyright (C) 2009 Luke Kenneth Casson Leighton <lkcl@lkcl.net>
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may ob | tain 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 s... | defined in CSS.
"""
XX_SMALL = 1
X_SMALL = 2
SMALL = 3
MEDIUM = 4
LARGE = 5
X_LARGE = 6
XX_LARGE = 7
"""*
* Justification enumeration. The three values are <code>left</code>,
* <code>right</code>, <code>center</code>.
"""
CENTER = "Center"
LEFT = "Left"
RIGHT = "Right"
|
gabrevaya/Canto5 | doc/split_syllables.py | Python | gpl-3.0 | 984 | 0.001016 | # -*- coding: utf-8 -*-
# """
# Created on Thu Mar 9 18:12:41 2017
#
# @author: ger
# """
import numpy as np
def split_syllables(signal, boo, margin):
'''
Use a boolean mask signal to split the signal.
input: signal (numpy array), boo (boolean array), margin (int)
output: syllables(list of numpy arr... | en the boolean array changes
indices = np.nonzero(boo[1:] != boo[:-1])[0] + 1
# extend the segments of syllables with a given margin
# if the signal starts with a syllable:
if boo[0]:
indices[0::2] = indices[0::2] + margin
indices[1::2] = indices[1::2] - margin
# if the signal does... |
# keep only the syllables and not the intermediate parts
b = b[0::2] if boo[0] else b[1::2]
return b
|
jperla/webify | webify/apps/standard/__init__.py | Python | mit | 1,108 | 0.009928 | from __future__ import absolute_import
import os
import chardet
import codecs
from ...controllers import webargs
from ...http.headers import content_types
def static(file_root='static/'):
'''
static = app.subapp(path='/static')(webify.apps.standard.static(file_root='static/'))
'''
@webargs.RemainingU... | (req, p, filename):
#TODO: jperla: cache the static stuff forever
# #TODO: jperla: Note: security problem
path = os.path.join(file_root, filename)
if os.path.exists(path) and os.path.isfile(path):
#TODO: jperla: make this read in chunks
encoding = 'raw_unicode_esc... | witch on image type
p.headers = [content_types.image_png]
#p(codecs.open(path, 'rb', encoding).read())
p(open(path, 'rb').read())
else:
#TODO: jperla: webify is not defined; namespace it
p(webify.http.status.not_found())
return static
|
tensorflow/agents | tf_agents/train/utils/strategy_utils.py | Python | apache-2.0 | 2,113 | 0.004733 | # coding=utf-8
# Copyright 2020 The TF-Agents Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | ,
tf.config.list_logical_devic | es())
else:
strategy = tf.distribute.get_strategy()
return strategy
|
wd5/jangr | users/migrations/0001_initial.py | Python | bsd-3-clause | 4,060 | 0.008621 | # encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'UserProfile'
db.create_table('users_userprofile', (
('id', self.gf('django.db.... | permission': {
'Meta' | : {'ordering': "('codename',)", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentTy... |
pombredanne/product-definition-center | pdc/apps/utils/tests.py | Python | mit | 3,181 | 0.001572 | #
# Copyright (c) 2015 Red Hat
# Licensed under The MIT License (MIT)
# http://opensource.org/licenses/MIT
#
from datetime import datetime
import random
import time
from django.conf import settings
from django.core.urlresolvers import reverse
from django.test import TestCase
from rest_framework.test import APITestCase... | EWARE_SECONDS = 10
response = self.client.get(reverse('baseproduct-list'))
self.assertEqual(response.data['count'], 0)
args = {"name": "Our Awesome Product", "short": "product", "version": "1", "release_type": "ga"}
response = self.clien | t.post(reverse('baseproduct-list'), args)
self.assertEqual(status.HTTP_201_CREATED, response.status_code)
response = self.client.get(reverse('baseproduct-list'))
self.assertEqual(response.data['count'], 0)
self.assertTrue(response.has_header('Cache-Control'))
self.assertTrue(res... |
ClimateImpactLab/DataFS | datafs/__init__.py | Python | mit | 392 | 0 | # -*- coding: utf-8 -*-
'''
'''
from __future__ import absolute_import
from datafs.core.data_api import DataAPI
from datafs.config.helpers import get_api, to_con | fig_file
__author__ = """Climate Impact Lab"""
__email__ = 'jsimcock@rhg.com'
__version__ = '0.7 | .1'
_module_imports = (
DataAPI,
get_api,
to_config_file
)
__all__ = list(map(lambda x: x.__name__, _module_imports))
|
akretion/bank-statement-reconcile | __unported__/account_statement_transactionid_completion/__init__.py | Python | agpl-3.0 | 964 | 0 | # -*- coding: utf-8 -*-
##############################################################################
#
# Author: Joel Grand-Guillaume
# Copyright 2011-2012 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License a... | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##########################################... | ###############################
import statement
|
fedora-infra/fedocal | alembic/versions/4f8bd7cac829_clean_db.py | Python | gpl-3.0 | 1,420 | 0.001408 | """Clean db
Revision ID: 4f8bd7cac829
Revises: 3f249e0d2769
Create Date: 2014-01-09 14:03:13.997656
"""
# revision identifiers, used by Alembic.
revision = '4f8bd7cac829'
down_revision = '3f249e0d2769'
from alembic import op
import sqlalchemy as sa
def upgrade():
''' Drop the columns calendar_multiple_meeting... | endar_multiple_meetings')
op.drop_column('calendars', 'calendar_regional_meetings')
op.alter_co | lumn(
'meetings',
column_name='meeting_region',
name='meeting_location',
type_=sa.Text,
existing_type=sa.String(100))
def downgrade():
''' Add the columns calendar_multiple_meetings and
calendar_regional_meetings and rename meeting_location into
meeting_region.
... |
bcopy/raspbuggy | modules/pywebide/src/main/python/raspbuggy/webide/main.py | Python | gpl-2.0 | 5,823 | 0.011678 | '''
Created on Apr 19, 2015
@author: bcopy
'''
import os
import cherrypy
import sys
import subprocess
import random
import time
import threading
import Queue
import tempfile
class ScriptMonitor(object):
'''
Monitors the script execution and updates result statuses
'''
def __init__(self):
... | WEBAPP_ROOT)
},
'/blockly':
{
'tools.staticdir.on': True,
'tools.staticdir.dir': os.path.abspath(BLOCKLY_ROOT)
},
'/bootstrap':
{
'tools.staticdir.on': True,
| 'tools.staticdir.dir': os.path.abspath(BOOTSTRAP_ROOT)
},
'/jquery':
{
'tools.staticdir.on': True,
'tools.staticdir.dir': os.path.abspath(JQUERY_ROOT)
}
})
|
casutton/casutton.github.io | _scripts/after-dash.py | Python | mit | 299 | 0.013378 | import fileinput
for line in fileinput.input(inplace=True, backup='.bak'):
if fileinput.isfirstline():
do_print = False
dash_num = 0
if do_print:
| print (line, end= | '')
if line.startswith("---"):
dash_num += 1
if dash_num == 2:
do_print = True
|
moto-timo/robotframework | src/robot/utils/error.py | Python | apache-2.0 | 7,024 | 0.000427 | # Copyright 2008-2015 Nokia Solutions and Networks
#
# 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 l... | \w.+)')
_ignored_java_trace = ('org.python.', 'robot.running.', 'robot$py.',
'sun.reflect.', 'java.lang.reflect.')
def _get_message(self):
exc_name = self._ge | t_name(self._exc_type)
# OOME.getMessage and even toString seem to throw NullPointerException
if not self._is_out_of_memory_error(self._exc_type):
exc_msg = self.error.getMessage()
else:
exc_msg = str(self.error)
return self._format_message(exc_name, exc_msg)
... |
lbryio/lbry | lbry/lbry/extras/daemon/analytics.py | Python | mit | 8,491 | 0.002709 | import asyncio
import collections
import logging
import aiohttp
import typing
from lbry import utils
from lbry.conf import Config
from lbry.extras import system_info
ANALYTICS_ENDPOINT = 'https://api.segment.io/v1'
ANALYTICS_TOKEN = 'Ax5LZzR1o3q3Z3WjATASDwR5rKyHH0qOIRIbLmMXn2H='
# Things We Track
SERVER_STARTUP = 'Se... | def _make_context(platform):
# see https://segment.com/docs/spec/common/#context
# they say they'll ignore fields outside the spec, but evidently they don't
context = {
'app': {
'version': platform['lbrynet_version'],
'build': platform['build'],
},
# TODO: exp... | e linux/osx specific info
'os': {
'name': platform['os_system'],
'version': platform['os_release']
},
}
if 'desktop' in platform and 'distro' in platform:
context['os']['desktop'] = platform['desktop']
context['os']['distro'] = platform['distro']
retur... |
ncphillips/django_rpg | rpg_base/forms/location.py | Python | mit | 43 | 0 | from crispy_form | s.helper | import FormHelper
|
VA3SFA/rpi_hw_demo | led/blink.py | Python | gpl-2.0 | 312 | 0.003205 | import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setwarn | ings(False)
ledpin = 18
GPIO.setup(ledpin, GPIO.OUT)
try:
while True:
GPIO.output(ledpin, 1)
time.sleep(0.5)
GPIO.output(ledp | in, 0)
time.sleep(0.5)
except KeyboardInterrupt:
GPIO.cleanup()
|
NixaSoftware/CVis | venv/bin/tools/build/v2/test/core_dependencies.py | Python | apache-2.0 | 3,575 | 0.006154 | #!/usr/bin/python
# Copyright 2003 Vladimir Prus
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt)
# This tests correct handling of dependencies, specifically, on generated
# sources, and from generated sources.
import Bo... | main")
t.run_build_system("-d2 -f-", stdin=code)
t.fail_test(not correct_order(t.stdou | t()))
t.cleanup()
|
petrjasek/superdesk-core | superdesk/vocabularies/vocabularies.py | Python | agpl-3.0 | 18,873 | 0.002225 | # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import logg... | equir | ed": False, "nullable": True},
"schema_field": {"type": "string", "required": False, "nullable": True},
"dependent": {
"type": "boolean",
},
"service": {
"type": "dict",
"schema": {},
"allow_unknown": True,
"keysrules": {"type":... |
raghakot/keras-vis | vis/visualization/__init__.py | Python | mit | 1,680 | 0.00119 | from __future__ import absolute_import
from .activation_maximization import visualize_activation_with_losses
from .activation_maximization import visualize_activation
from .saliency import visualize_saliency_with_losses
from .saliency import visualize_saliency
from .saliency import visualize_cam_with_losses
from .sa... | ray2`. This value needs to be between [0, 1],
with 0 being `array2` only to 1 being `array1` only (Default value = 0.5) | .
Returns:
The `array1`, overlayed with `array2` using `alpha` blending.
"""
if alpha < 0. or alpha > 1.:
raise ValueError("`alpha` needs to be between [0, 1]")
if array1.shape != array2.shape:
raise ValueError('`array1` and `array2` must have the same shapes')
return (arra... |
cchristelis/feti | django_project/feti/serializers/campus_serializer.py | Python | bsd-2-clause | 862 | 0.00116 | from rest_framework import serializers
from feti.models.campus import Campus
from feti.serializers.course_serializer import CourseSerializer
__author__ = 'irwan'
class CampusSerializer(serializers.ModelSerializer):
class Meta:
model = Campus
def | to_representation(self, instance):
res = super(CampusSerializer, self).to_representation(instance)
res['long_description'] = instance.long_description
res['courses'] = CourseSerializer(instance.courses.all(), many=True).data
if instance.address:
res['address'] = instance.add... | icode__()
if instance.provider:
res['title'] = instance.provider.__unicode__()
if instance.location:
res['location'] = {
'lat': instance.location.y,
'lng': instance.location.x}
return res
|
great-expectations/great_expectations | tests/integration/docusaurus/setup/configuring_metadata_stores/how_to_configure_an_expectation_store_in_gcs.py | Python | apache-2.0 | 6,223 | 0.00225 | import os
import subprocess
from ruamel import yaml
import great_expectations as ge
context = ge.get_context()
# NOTE: The following code is only for testing and depends on an environment
# variable to set the gcp_project. You can replace the value with your own
# GCP project information
gcp_project = os.environ.ge... | xpectations_store["stores"]["expectations_GCS_store"]["store_backend"][
"bucket"
] = "test_metadata_store"
configured_expectations_store["stores"]["expectations_GCS_store"]["store_backend"][
"prefix"
] = "how_to_configure_an_expectation_store_in_gcs/expectations"
try:
# remove this bucket if there was a fa... | n_expectation_store_in_gcs/expectations".split(),
check=True,
stderr=subprocess.PIPE,
)
except Exception as e:
pass
# add and set the new expectation store
context.add_store(
store_name=configured_expectations_store["expectations_store_name"],
store_config=configured_expectations_store[... |
gokul-uf/TF-DCGAN | model.py | Python | mit | 7,113 | 0 | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import tensorflow as tf
class DCGAN(object):
"""
Tensorflow implementation of DCGAN, with four CNN layers.
We assume the input images are of size 32x32.
"""
def __init__(self):
... | s")
self.input_noise = tf.placeholder(
shape=[None, self.noise_size],
dtype=tf.float32,
name="input_noise")
def _create_generator | (self):
xav_init = tf.contrib.layers.xavier_initializer
bnorm = tf.layers.batch_normalization
with tf.variable_scope("generator"):
"""
fc_1 = tf.layers.dense(
inputs=self.input_noise, units=4 * 4 * 512, name="fc_1")
"""
fc_1 = tf.l... |
AustereCuriosity/astropy | astropy/io/ascii/basic.py | Python | bsd-3-clause | 10,920 | 0.000733 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""An extensible ASCII table reader and writer.
basic.py:
Basic table read / write functionality for simple character
delimited files with various options for column header definition.
:Copyright: Smithsonian Astrophysical Observatory (2011)
:Author:... | asic table Data Reader
Set a few defaults for common ascii table formats
(start at line 1, comments begin with ``#`` and possibly white space)
"""
start_line = 1
comment = r'\s*#'
write_comment = '# '
class Basic(core.BaseReader):
r"""
Read a character-delimited table with a single he... | er line at the top
followed by data lines to the end of the table. Lines beginning with # as
the first non-whitespace character are comments. This reader is highly
configurable.
::
rdr = ascii.get_reader(Reader=ascii.Basic)
rdr.header.splitter.delimiter = ' '
rdr.data.splitter... |
shugaoye/virt-manager | virtinst/osdict.py | Python | gpl-2.0 | 19,407 | 0.002679 | #
# List of OS Specific data
#
# Copyright 2006-2008, 2013-2014 Red Hat, Inc.
# Jeremy Katz <katzj@redhat.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 2 of the License, ... | ibosinfo as libosinfo
# This is only for back compatibility with pre-libosinfo support.
# This should never change.
_aliases = {
"altlinux" : "altlinux1.0",
"debianetch" : "debian4",
"debianlenny" : "debian5",
"debiansqueeze" : "debian6 | ",
"debianwheezy" : "debian7",
"freebsd10" : "freebsd10.0",
"freebsd6" : "freebsd6.0",
"freebsd7" : "freebsd7.0",
"freebsd8" : "freebsd8.0",
"freebsd9" : "freebsd9.0",
"mandriva2009" : "mandriva2009.0",
"mandriva2010" : "mandriva2010.0",
"mbs1" : "mbs1.0",
"msdos" : "msdos6.22",
... |
myron0330/caching-research | section_cmab/data/__init__.py | Python | mit | 208 | 0 | # -*- coding: UTF-8 -*-
# ***** | ********************************************** | *******************************#
# File:
# **********************************************************************************#
|
QingChenmsft/azure-cli | src/command_modules/azure-cli-extension/azure/cli/command_modules/extension/__init__.py | Python | mit | 698 | 0.005731 | # ----------------------------------------------------------- | ---------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# ---------------------------------------- | ----------------------------------------------------
import azure.cli.command_modules.extension._help # pylint: disable=unused-import
def load_params(_):
import azure.cli.command_modules.extension._params # pylint: disable=redefined-outer-name, unused-variable
def load_commands():
import azure.cli.comman... |
Bjornkjohnson/makeChangePython | Change.py | Python | mit | 491 | 0.016293 | import collections
class Change(object):
def __in | it__(self):
super(Change, self).__init__()
def makeChange(self, change):
coinVaulues = collections.OrderedDict()
coinVaulues['h'] = 50
coinVaulues['q'] = 25
coinVaulues['d'] = 10
coinVaulues['n'] = 5
coinVaulues['p'] = 1
coins = {}
for key in coinVaulues:
while chan... | [key]
return coins |
matthewcornell/peepweather | test/test_hour.py | Python | apache-2.0 | 8,968 | 0.002453 | import unittest
import datetime
from unittest.mock import patch
from forecast.Location import Location
from forecast.Forecast import Forecast
from forecast.Hour import Hour
from forecast.WeatherGovSource import WeatherGovSource
class ForecastTestCase(unittest.TestCase):
"""
"""
def testIsDaylight(self... | louds': [(0, Hour.P_DES_HIGH),
(32, Hour.P_DES_HIGH),
(33, Hour.P_DES_MED),
(65, Hour.P_DES_MED),
(66, Hour.P_DES_LO | W),
(100, Hour.P_DES_LOW),
],
}
location = Location('01002')
for paramName, expParamValRatings in expParamValRatings.items():
for paramval, expParamRating in expParamValRatings:
hour = Hour(None)
self.assertEqual(expP... |
jinyu121/LifeLine | ScriptSpliter.py | Python | gpl-2.0 | 817 | 0 | __author__ = 'haoyu'
from GameBlock import GameBlock
class ScriptSpliter:
def __init__(self, scriptReader):
self.reader = scriptReader
def parse(self):
blocks = {}
blockName = 'game null pointer'
blocks[blockName] = GameBlock(blockName) |
for line in self.reader:
# 空行,跳过
if 0 == len(line):
continue
# 注释行,跳过
if line.startswith('//'):
continue
# 区块开始
if line.startswith(':: '):
blockName = line[3:].strip()
if bloc... | blocks[blockName] = GameBlock(blockName)
continue
blocks[blockName].scripts.append(line)
return blocks
|
pouyana/teireader | webui/applications/grid/languages/fr.py | Python | mit | 7,935 | 0.025399 | # coding: utf8
{
'!langcode!': 'fr',
'!langname!': 'Français',
'"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" est une expression optionnelle comme "champ1=\'nouvellevaleur\'". Vous ne pouvez mettre à jour ou supprimer les résultats d\'un JOI... | 'Ne peut pas être vide',
'change password': 'changer le mot de passe',
'Check to delete': 'Cliquez pour supprimer',
'Check to delete:': 'Cliquez pour supprimer:',
'Clear CACHE?': 'Vider le CACHE?',
'Clear DISK': 'Vider le DISQUE',
'Clear RAM': 'Vider la RAM' | ,
'Client IP': 'IP client',
'Community': 'Communauté',
'Components and Plugins': 'Composants et Plugins',
'Controller': 'Contrôleur',
'Copyright': 'Copyright',
'Created By': 'Créé par',
'Created On': 'Créé le',
'Current request': 'Demande actuelle',
'Current response': 'Réponse actuelle',
'Current session': 'Session en... |
alexhayes/django-teledex | django_teledex/apps.py | Python | mit | 354 | 0 | # -*- coding: utf-8 -*-
"""
teledex.apps
~~~~~~~~~~~~
D | efines the Django application teledex.
"""
from __future__ import absolute_import, print_function, unicode_literals
from django.apps import AppConfig
class DjangoTeledexAppConfig(AppConfig):
name = 'django_teledex'
label = 'django_teledex'
verbose_name = 'Django T | eledex'
|
upconsulting/IsisCB | isiscb/isisdata/migrations/0071_asynctask_label.py | Python | mit | 450 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 20 | 17-09-24 16:45
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('isisdata', '0070_auto_20170730_1638'),
]
operations = [
migrations.AddField(
model_name='asynctask',
name='la... | field=models.TextField(default=b''),
),
]
|
artmin/weippert-addons | account_cash_discount/__openerp__.py | Python | gpl-2.0 | 1,514 | 0 | # -*- coding: utf-8 -*-
##############################################################################
#
# it.artmin
# Martin Apitz, May 2014
#
# 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 S... | enses/>.
#
##############################################################################
{
'name': 'Cash discount',
'version': '0.1',
'category': 'Account',
'description': """
Possibility to add cash discount on invoice.
""",
'author': 'it.artmin',
'website': 'http://it.artmin.de',
'summar... | s.',
'depends': [
'account',
'sale'
],
'data': [
'account_cash_discount_view.xml',
'report_invoice.xml',
],
'images': [''],
'installable': True,
'application': True,
'auto_install': False,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4... |
ezralalonde/cloaked-octo-sansa | 03/hw/06.py | Python | bsd-2-clause | 1,984 | 0.035786 | # THREE GOLD STARS
# Sudoku [http://en.wikipedia.org/wiki/Sudoku]
# is a logic puzzle where a game
# is defined by a partially filled
# 9 x 9 square of digits where each square
# contains one of the digits 1,2,3,4,5,6,7,8,9.
# For this question we will generalize
# and simplify the game.
# Define a procedure, check_s... | ly once.
# You may assume the the input is square and contains at
# least one r | ow and column.
correct = [[1,2,3],
[2,3,1],
[3,1,2]]
incorrect = [[1,2,3,4],
[2,3,1,3],
[3,1,2,3],
[4,4,4,4]]
incorrect2 = [[1,2,3,4],
[2,3,1,4],
[4,1,2,3],
[3,4,1,2]]
incorrect3 = [[1,2,3,4,5],
[2,3,1,... |
joseguerrero/sembrando | src/presentacion/librerias/configuracion.py | Python | gpl-3.0 | 4,541 | 0.005969 | #!/usr/bin/env python
class configuracion():
"""
Esta clase cumple la función de una base de datos o fichero de configuración, donde se almacenan de
manera temporal las preferencias de uso del ReDA.
"""
color = 0
"""Indica el color de la camisa del interprete, sus posibles valores son 0... | glosario."""
visit = {
"p0": False,
"p2": False
}
"""Diccionario que registra las visitas a las pantallas del recurso."""
preferencias = {
"color": 0,
"ubx": 499,
"vel_anim": 4,
"t_fuente": 18,
"velocidad": 0.5,
"audio": False,
"cache... | "disc_vis": False,
"texto_cambio": False,
"magnificador": False,
"activar_lector" : False,
"genero": "",
"synvel": "baja",
"definicion": "",
}
"""Diccionario que almacena las preferencias mientras el ReDA este cargado en memoria."""
def consultar(self):
... |
stxnext-kindergarten/presence-analyzer-kgrela | src/presence_analyzer/main.py | Python | mit | 244 | 0 | # -*- coding: utf-8 -*-
"""Flask app initialization."""
import os.path
from flask import Flask
from flask.ext.mako import MakoTemplates
app = Flask(__name__) # pylint: disable- | msg=C0103
m | ako = MakoTemplates(app) # pylint: disable-msg=C0103
|
droundy/bigbro | build/binary2header.py | Python | gpl-2.0 | 516 | 0.007752 | def convertFile(binary_filename, header_filename, variable_name):
| with open(binary_filename, 'rb') as b:
with open(header_filename, 'w') as h:
h.write('''static const unsigned char %s[] = { ''' % variable_name);
stuff = b.read()
h.write(',\n'.join('%d' % ord(stuff[i:i+1]) for i in range(len(stuff))))
h.write('\n};\n')
if __... | ], sys.argv[3])
|
gawel/irc3 | irc3/_parse_rfc.py | Python | mit | 5,523 | 0.002535 | # -*- coding: utf-8 -*-
from collections import defaultdict
import pprint
import re
_re_num = re.compile('\s(?P<num>\d+)\s+(?P<name>(RPL|ERR)_\w+)\s*(?P<_>.*)')
_re_mask = re.compile('^\s{24,25}(?P<_>("(<|:).*|\S.*"$))')
def main():
print('Parsing rfc file...')
item = None
items = []
out = open('irc... | for k in 'xyz':
if k not in params:
v = k
break
if v == 'command':
v = 'cmd'
| if v == 'real':
v = 'realname'
if v == 'name' and 'nick' not in params:
v = 'nick'
if v == 'user':
if 'nick' not in params and num not in ('352',):
v = 'nick'
else:
... |
rackerlabs/python-lunrclient | lunrclient/shared.py | Python | apache-2.0 | 1,780 | 0 | # Copyright 2011-2016 Rackspace US, 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 i... | ce.help
self.msg = msg
def __str__(self):
return self.msg
class Env(SubCommand):
"""
Display Available environment options
"""
def __init__(self):
# Give our sub command a name
self._name = 'env'
# let the base class setup methods in our class
SubC... | print("# Available environment variables")
print("export OS_TENANT_NAME='%s'" % os.environ['USER'])
print("export LUNR_ADMIN='admin'")
print("export LUNR_TENANT_ID='admin'")
print("export LUNR_STORAGE_URL='http://localhost:8081'")
print("export LUNR_API_URL='http://localho... |
TheBlueMatt/bitcoin | test/functional/feature_segwit.py | Python | mit | 41,031 | 0.007238 | #!/usr/bin/env python3
# Copyright (c) 2016-2017 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the SegWit changeover logic."""
from test_framework.address import (
key_to_p2sh_p2wpkh,
... | 00)
a | ssert(tmpl['transactions'][0]['hash'] == txid)
assert(tmpl['transactions'][0]['sigops'] == 2)
self.nodes[0].generate(1) #block 162
balance_presetup = self.nodes[0].getbalance()
self.pubkey = []
p2sh_ids = [] # p2sh_ids[NODE][VER] is an array of txids that spend to a witness vers... |
apple/swift-lldb | packages/Python/lldbsuite/test/functionalities/load_using_paths/TestLoadUsingPaths.py | Python | apache-2.0 | 5,848 | 0.004105 | """
Test that SBProcess.LoadImageUsingPaths works correctly.
"""
from __future__ import print_function
import os
import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
@skipIfWindows # The Windows platform doesn't implement DoLoadImage.
class... |
# Make sure the token works to unload it:
process.UnloadImage(token)
# Make sure this really is no long | er in the image list:
loaded_module = target.FindModule(out_spec)
self.assertFalse(loaded_module.IsValid(), "The unloaded module is no longer in the image list.")
# Make sure a relative path also works:
paths.Clear()
paths.AppendString(os.path.join(self.wd, "no_such_dir"))
... |
sethwoodworth/collect_phil_cdc | data_transport.py | Python | gpl-3.0 | 4,332 | 0.013389 | ################################################################################
################################################################################
##################### #########################
##################### Release Our Data ######################... |
Column('id', Integer, primary_key=True),
Column('status', Boolean),
mysql_charset='utf8'
)
lores_status_table = Table('lores_status', metadata,
Column('id', Integer, primary_key=True),
Column('status', Boolean),
mysql_charset='utf8'
)
thumb_status_table = Table('thumb_status', metadata,
C... | reate_all(db)
table = phil_table.insert()
def table_iterate(table_name, db2):
result = db2.execute(table_name.select())
for row in result:
table_name.insert().execute(row)
result.close()
def from_sqlite_to_mysql():
db2 = create_engine('sqlite:///full.sql')
for table in [phil_table, hires_... |
magenta/magenta | magenta/models/latent_transfer/configs/joint_exp_2mnist_parameterized.py | Python | apache-2.0 | 2,401 | 0 | # Copyright 2022 The Magenta Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | e_config_A = {
'Encoder': Encoder,
'Decoder': Decoder,
'prior_loss_beta': FLAGS.prior_loss_beta_A,
'prior_loss': 'KL',
'batch_size': batch_size,
| 'n_latent': n_latent,
'n_latent_shared': n_latent_shared,
}
vae_config_B = {
'Encoder': Encoder,
'Decoder': Decoder,
'prior_loss_beta': FLAGS.prior_loss_beta_B,
'prior_loss': 'KL',
'batch_size': batch_size,
'n_latent': n_latent,
'n_latent_shared': n_latent_shared,
}
config = {
'va... |
Feneric/doxypypy | doxypypy/test/sample_pep.py | Python | gpl-2.0 | 443 | 0 | #!/usr/bin/env python
# As close as possible to a direct copy of the sample in PEP 257 and still
# be valid code. Simple as can be.
complex_z | ero = 0j
def complex(real=0.0, imag=0.0):
"""Form a complex number.
Keyword arguments:
real -- the real part (default 0.0)
imag -- the imaginary part (default 0.0)
"""
if imag == 0.0 and real == 0.0:
return complex_zero
else:
return complex(real, i | mag)
|
guilhermemaba/django-sql-explorer | explorer/tests/test_actions.py | Python | mit | 1,728 | 0.001157 | import io
from django.test import TestCase
from explorer.actions import generate_report_action
from explorer.tests.factories import SimpleQueryFactory
from explorer.utils import csv_report
from zipfile import ZipFile
class testSqlQueryActions(TestCase):
def test_simple_query_runs(self):
expected_csv = ... | n'
r = SimpleQueryFactory()
result = csv_report(r).getvalue()
self.assertIsNotNone(result, "Query '% | s' returned None." % r.title)
self.assertEqual(result.lower(), expected_csv)
def test_single_query_is_csv_file(self):
expected_csv = b'two\r\n2\r\n'
r = SimpleQueryFactory()
fn = generate_report_action()
result = fn(None, None, [r, ])
self.assertEqual(result.content... |
williamFalcon/pytorch-lightning | legacy/simple_classif_training.py | Python | apache-2.0 | 5,832 | 0.001543 | # Copyright The PyTorch Lightning team.
#
# 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 i... | )
def val_dataloader(self):
return DataLoader(
SklearnDataset(self.x_valid, self.y_valid, self._x_type, self._y_type), batch_size=self.batch_size
)
def test_dataloader(self):
return DataLoader(
SklearnDataset(self.x_test, self.y_test, self._x_type, self._y_ty... | lf.batch_size
)
class ClassifDataModule(SklearnDataModule):
def __init__(self, num_features=24, length=6000, num_classes=3, batch_size=128):
data = make_classification(
n_samples=length,
n_features=num_features,
n_classes=num_classes,
n_clusters_per_... |
mas2tg/cs3240-f16-team07 | inbox/migrations/0005_message_blue.py | Python | mit | 430 | 0 | # -*- coding: | utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('inbox', '0004_auto_20160410_2239'),
]
operations = [
migrations.AddField(
model_name | ='message',
name='blue',
field=models.BinaryField(null=True),
preserve_default=True,
),
]
|
pbrod/numpy | numpy/linalg/lapack_lite/clapack_scrub.py | Python | bsd-3-clause | 8,661 | 0.00254 | #!/usr/bin/env python3
import os
import re
import sys
from io import StringIO
from plex import Scanner, Str, Lexicon, Opt, Bol, State, AnyChar, TEXT, IGNORE
from plex.traditional import re as Re
class MyScanner(Scanner):
def __init__(self, info, name='<default>'):
Scanner.__init__(self, self.lexicon, inf... | se:
comme | nts.flushTo(lines)
blanks.flushTo(lines)
lines.add(line)
return SourceLines
state = SourceLines
for line in StringIO(source):
state = state(line)
comments.flushTo(lines)
return lines.getValue()
def removeHeader(source):
lines = LineQueue()
def Looki... |
http2d/core | config.h.in.pre-update.py | Python | bsd-2-clause | 1,111 | 0.018002 | #!/usr/bin/env python
import os, re, sys
## assert (len(sys.argv) == 2)
PATH_SRC = sys.argv[1]
PATH_BIN = sys.argv[2]
FILENAME_CMK = os.path.join (PATH_SRC, 'CMakeLists.txt')
FILENAME_PRE = os.path.join (PATH_SRC, 'config.h.in.pre')
FILENAME_NEW = os.path.join (PATH_BIN, 'config.h.in')
# Parse CMakeLists.txt
with ... |
sizes_t += '/* %s */\n' %(h.replace('SIZEOF_','').replace('_',' '))
sizes_t += '@%s_CODE@\n' %(h)
sizes_t += '#cmakedefine HAVE_%s\n' %(h)
sizes_t += '#ifdef HAVE_%s\n' %(h)
sizes_t += '# define HAVE_%s\n' %(h.replace('SIZEOF_',''))
sizes_t += '#endif\n\n'
# Read .pre file
with open(F | ILENAME_PRE, 'r') as f:
cont = f.read()
cont = cont.replace ("${{includes}}", includes_t)
cont = cont.replace ("${{sizes}}", sizes_t)
with open(FILENAME_NEW, 'w+') as f:
f.write (cont)
|
rosarior/mayan | apps/documents/__init__.py | Python | gpl-3.0 | 8,594 | 0.007796 | from __future__ import absolute_import
import tempfile
from django.utils.translation import ugettext_lazy as _
from acls.api import class_permissions
from common.utils import validate_path, encapsulate
from dynamic_search.classes import SearchModel
from history.api import register_history_type
from history.permissio... | icates, document_update_page_count,
document_clear_transformations, document_multiple_clear_transformations,
document_print, document_history_view, document_missing_list, document_clear_image_cache,
document_page_transformation_list, document_page_transformation_create, document_page_transformation_edit,
... | ge_edit,
document_page_navigation_next, document_page_navigation_previous, document_page_navigation_first,
document_page_navigation_last, document_page_zoom_in, document_page_zoom_out,
document_page_rotate_right, document_page_rotate_left, document_page_view_reset,
document_version_list, document_versio... |
lemarcudal/sha_thedivision | test/mysite/webapp/migrations/0001_initial.py | Python | apache-2.0 | 1,780 | 0.001685 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2016-10-16 15:26
from __future__ import unicode_literals
from django.db import migrations, models
import webapp.models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
... | )),
('image', models.ImageField(blank=True, height_field='height_field', null=True, upload_to=webapp.models.upload_location, width_field='width_field')),
('height_field', models.IntegerField(default=0)),
('width_field', models.IntegerField(default=0)),
('I... | eld(choices=[('DENMARK', 'DENMARK'), ('FINLAND', 'FINLAND'), ('FRANCE', 'FRANCE'), ('GERMANY', 'GERMANY'), ('ITALY', 'ITALY'), ('NETHERLADNS', 'NETHERLANDS'), ('NORWAY', 'NORWAY'), ('RUSSIA', 'RUSSIA'), ('SPAIN', 'SPAIN'), ('SWEDEN', 'SWEDEN'), ('U.K.', 'U.K.'), ('CANADA', 'CANADA'), ('MEXICO', 'MEXICO'), ('U.S.', 'U.S... |
52ai/django-ccsds | tests/order_with_respect_to/tests.py | Python | bsd-3-clause | 4,155 | 0.000481 | from __future__ import unicode_literals
from operator import attrgetter
from django.db import models
from django.test import TestCase
from .models import Answer, Dimension, Entity, Post, Question
class OrderWithRespectToTests(TestCase):
@classmethod
def setUpTestData(cls):
cls.q1 = Question.object... | ordering can be altered
a = Answer.objects.create(text="Number five", question=self.q1)
# Swap the last two items in the order list
id_list = [o.pk for o in self.q1.answer_set.all()]
x = id_list.pop()
id_list.insert(-1, x)
# By default, the ordering is different from th... | the ordering of the queryset.
a.question.set_answer_order(id_list)
self.assertQuerysetEqual(
self.q1.answer_set.all(), [
"John", "Paul", "George", "Number five", "Ringo"
],
attrgetter("text")
)
class OrderWithRespectToTests2(TestCase):
... |
hlzz/dotfiles | graphics/VTK-7.0.0/ThirdParty/Twisted/twisted/scripts/test/test_scripts.py | Python | bsd-3-clause | 6,855 | 0.002626 | # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Tests for the command-line scripts in the top-level I{bin/} directory.
Tests for actual functionality belong elsewhere, written in a way th | at doesn't
involve launching child processes.
"""
|
from os import devnull, getcwd, chdir
from sys import executable
from subprocess import PIPE, Popen
from twisted.trial.unittest import SkipTest, TestCase
from twisted.python.modules import getModule
from twisted.python.filepath import FilePath
from twisted.python.test.test_shellcomp import ZshScriptTestMixin... |
google-research/google-research | basisnet/personalization/centralized_so_nwp/so_nwp_preprocessing.py | Python | apache-2.0 | 13,804 | 0.008476 | # coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... | hour = tf.strings.to_number(
tf.strings.substr(dates, 11, 2), out_type=tf.int64)
minute = tf.strings.to_number(
tf.strings.substr(dates, 14, 2), out_type=tf.int64)
second = tf.strings.to_number(
tf.strings.substr(dates, 17, 2), out_type=tf.int64)
timestamp = 0
timestamp = (timestamp + year)... | e) * 100
timestamp = timestamp + second
return timestamp
def _sort_examples_by_date(
examples):
"""Sorts a batch of dataset elements by increasing creation date.
Sorting is stable, so original ordering is consistently retained for ties.
Args:
examples: A batch of examples.
Returns:
Output b... |
hmpf/nav | python/nav/web/crispyforms.py | Python | gpl-3.0 | 1,764 | 0 | #
# Copyrigh | t (C) 2013 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 3 as published by
# the Free Software Foundation.
#
# This pro | gram 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 along with NAV. If n... |
levelrf/level_basestation | grextras/python/qa_msg_passing.py | Python | gpl-3.0 | 4,308 | 0.01091 | #!/usr/bin/env python
#
# Copyright 2011-2012 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio 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, or (at your opt... | c)
hb_sink.connect(hb_sink, sink)
tb.connect(hb_src, hb_sink)
#disconn | ect
hb_src.disconnect(src, hb_src)
hb_sink.disconnect(hb_sink, sink)
tb.disconnect(hb_src, hb_sink)
#reconnect
hb_src.connect(src, hb_src)
hb_sink.connect(hb_sink, sink)
tb.connect(hb_src, hb_sink)
tb.run()
self.assertItemsEqual(sink.msgs(), msgs... |
BOKteam/common | closure/google-closure-builder/builder/source.py | Python | mit | 3,415 | 0.009078 | # Copyright 2009 The Closure Library 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 a... | e for its provided and required namespaces.
Simple class to scan a JavaScript file and express its d | ependencies.
"""
__author__ = 'nnaze@google.com'
import re
_BASE_REGEX_STRING = '^\s*goog\.%s\(\s*[\'"](.+)[\'"]\s*\)'
_PROVIDE_REGEX = re.compile(_BASE_REGEX_STRING % 'provide')
_REQUIRES_REGEX = re.compile(_BASE_REGEX_STRING % 'require')
_REQUIRES_ALL_REGEX = re.compile(_BASE_REGEX_STRING % 'requireAll')
# This ... |
secdev/scapy | scapy/packet.py | Python | gpl-2.0 | 89,628 | 0.000089 | # This file is part of Scapy
# See http://www.secdev.org/projects/scapy for more information
# Copyright (C) Philippe Biondi <phil@secdev.org>
# This program is published under a GPLv2 license
"""
Packet class
Provides:
- the default Packet classes
- binding mechanisms
- fuzz() method
- exploration methods: explo... | _CanvasDumpExtended
from scapy.interfaces import _GlobInterfaceType
from scapy.volatile import RandField, VolatileValue
from scapy.utils import import_hexcap, tex_escape, colgen, issubtype, \
pretty_list, EDecimal
from scapy.error import Scapy_Exception, log_runtime, warning
from scapy.extlib import PYX
import sca... | rom scapy.compat import (
Any,
Callable,
Dict,
Iterator,
List,
NoReturn,
Optional,
Set,
Tuple,
Type,
TypeVar,
Union,
Sequence,
cast,
)
try:
import pyx
except ImportError:
pass
_T = TypeVar("_T", Dict[str, Any], Optional[Dict[str, Any]])
# six.with_meta... |
LUTAN/tensorflow | tensorflow/python/kernel_tests/sparse_tensor_dense_matmul_op_test.py | Python | apache-2.0 | 13,381 | 0.00852 | # Copyright 2015 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... | .from_value(sp_x_value),
y,
adjoint_a=adjoint_a,
adjoint_b=adjoint_b)
# Ensure that the RHS shape is known at least.
self.assertEqual(tf_value_ans.get_shape()[1], np_ans.shape[1])
self.assertEqual(tf_tensor_ans.get_shape()[1], np_ans.shape[1])
for out in (tf_value... | ype == np.float32:
self.assertAllClose(np_ans, out, rtol=1e-4, atol=1e-4)
elif x.dtype == np.float64:
self.assertAllClose(np_ans, out, rtol=1e-6, atol=1e-6)
else:
self.assertAllClose(np_ans, out, rtol=1e-4, atol=1e-4)
def _testBasic(self, value_dtype, indices_dtype=np.in... |
taigaio/taiga-back | taiga/projects/milestones/utils.py | Python | agpl-3.0 | 3,464 | 0.001732 | # -*- coding: utf-8 -*-
# Copyright (C) 2014-present Taiga Agile LLC
#
# 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... | nts_attr"):
"""Attach total of closed point values to each object of the queryset.
:param queryset: A Django milestones queryset object.
:param as_field: Attach the points as an attribute with this name.
:return: Queryset object with the additional `as_field` field.
"""
model = queryset.model
... | d = userstories_rolepoints.user_story_id
INNER JOIN projects_points ON userstories_rolepoints.points_id = projects_points.id
WHERE userstories_userstory.milestone_id = {tbl}.id AND userstories_userstory.is_closed=True"""
sql = sql.format(tbl=model._meta.db_table)
queryse... |
python-acoustics/Sea | Sea/adapter/connections/ConnectionPoint.py | Python | bsd-3-clause | 714 | 0.012605 |
import Sea
from Connection import Connection
class ConnectionPoint(Connection):
"""
Class for point connections.
"""
def __init__(self, obj, system, components):
Connection.__init__(self, obj, system, components)
|
#obj.Sort = 'Point'
def updateComponents(self, obj):
connections = Sea.actions.connection.ShapeConnection([item.Shape for item in obj.Components])
commons = connections.commons()
if any([item.Vertexes for item in commons]):
| """
There is indeed a point connection.
"""
obj.Proxy.model.components = obj.Components
obj.updateCouplings()
|
davelab6/fontqa | FontLab/Macros/System/Modules/fontQAlib.py | Python | gpl-3.0 | 27,167 | 0.015386 | #------------------------------------------------------------------------------
#
# This file is part of the fontQA framework
# Copyright (C) 2005 published by FSI Fonts und Software GmbH
# written by Andreas (Eigi) Eigendorf
#
# This programming framework is free software; you can redistribute it
# and/or modify it... | ion.
#
# This programming framework 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... | 1, USA.
#
#------------------------------------------------------------------------------
'''
This is the main module of the fontQA framework.
'''
__version__ = 'version 1.0, 2005'
__author__ = 'Andreas (Eigi) Eigendorf'
__email__ = 'mail@e-font.de'
import sys, traceback, os, shutil, webbrowser, time
from types i... |
aitjcize/creepy | examples/test_crawler.py | Python | gpl-3.0 | 418 | 0.004785 | #!/usr/bin/env python
from creepy import Crawler
from threading import Lock
class TestCrawler(Crawler):
def __init__(self):
su | per(TestCrawler, self).__init__()
self.process_lock = Lock()
def process_document(self, doc):
self.process_lo | ck.acquire()
print 'GET', doc.status, doc.url
self.process_lock.release()
c = TestCrawler()
c.crawl('http://aborigine.moc.gov.tw')
|
nyu-devops-echo/shopcarts | tests/test_vcap_services.py | Python | apache-2.0 | 1,188 | 0.004209 | import json
import os
import unittest
from unittest.mock import patch
from app.vcap_services import get_database_uri
VCAP_SERVICES = {
'cleardb': [
{
'credentials': {
'username': 'vcap_user',
'password': 'vcap_pass',
'hostname': '127.0.0.2',
... | ps(VCAP_SERVICES)})
@patch.dict(os.environ, {'DATABASE_URI': 'mysql+pymysql://vcap_user:vcap_pass@127.0.0.2:3307/vcap' })
def test_get_database_uri_vcap(self):
""" Test if it gets the vcap db uri """
db_uri = os.getenv('DATABASE_URI')
result = get_database_uri()
self.assertEqual(... | ', "mysql+pymysql://root:@localhost:3306/shopcarts")
result = get_database_uri()
self.assertEqual(result, db_uri)
if __name__ == '__main__':
unittest.main()
|
kylerbrown/openephys | setup.py | Python | mit | 1,539 | 0.0013 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
with open('README.md') as readme_file:
readme = readme_file.read()
requirements = ["h5py", "numpy", "scipy", "arf"]
test_requirements = ["pytest"]
setup(
name='openep... | ',
url='https://github.com/kylerbrown/openephys',
packages=[
'openephys',
],
package_dir={'openephys': 'openephys'},
include_package_data=True,
install_requires=requirements,
scripts=["openephys/kwik2arf.py", "openephys/kwik2dat.py",
"openephys/kwik2wav.py"],
license... | ,
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: ISC License (ISCL)',
'Natural Language :: English',
"Programming Language :: Python :: 2",
'Programming Language :: Python :: 2.6',
'Programmi... |
jmartinm/invenio-records | invenio_records/config.py | Python | gpl-2.0 | 1,717 | 0 | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2014, 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... | 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 Invenio; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
"""Records configuration."""
from __future__ import unicode_literals
from .models import RecordMetadata as RecordMetadataModel
RECORDS_BREADCRUMB_TITLE_KEY = 'title.title'
"""Key use... |
wwitzel3/awx | awx/main/tests/unit/api/test_filters.py | Python | apache-2.0 | 4,535 | 0.001766 | # -*- coding: utf-8 -*-
import pytest
from rest_framework.exceptions import PermissionDenied, ParseError
from awx.api.filters import FieldLookupBackend, OrderByBackend, get_field_from_path
from awx.main.models import (AdHocCommand, ActivityStream,
CustomInventoryScript, Credential, Job,
... | ookup = FieldLookupBackend()
# FieldDoesNotExist is caught and converted to ParseError by filter_queryset
with pytest.raises(FieldDoesNotExist) as excinfo:
field_lookup.va | lue_to_python(JobEvent, 'event_data.task_action', 'foo')
assert 'has no field named' in str(excinfo)
def test_invalid_field_hop():
with pytest.raises(ParseError) as excinfo:
get_field_from_path(Credential, 'organization__description__user')
assert 'No related model for' in str(excinfo)
def test_... |
aaronsw/watchdog | vendor/pyExcelerator-0.6.3a/examples/parse-fmla.py | Python | agpl-3.0 | 376 | 0.013298 | from pyExcelerator import ExcelFormulaParser, ExcelFormula
import sys
f = ExcelFormula.Formula(
""" -((1 | .80 + 2.898 * 1)/(1.80 + 2.898))*
AVERAGE((1.80 + 2 | .898 * 1)/(1.80 + 2.898);
(1.80 + 2.898 * 1)/(1.80 + 2.898);
(1.80 + 2.898 * 1)/(1.80 + 2.898)) +
SIN(PI()/4)""")
#for t in f.rpn():
# print "%15s %15s" % (ExcelFormulaParser.PtgNames[t[0]], t[1])
|
ultmaster/eoj3 | problem/testlib/pack.py | Python | mit | 1,142 | 0.004378 | """
This is used to pack testlib into a json
Then you can load into database by using:
manage.py loaddata <fixturename>
fixturename here is `testlib.json`
"""
import hashlib
import json
from os import path, listdir
def hash(binary):
return hashlib.sha256(binary).hexdigest()
category = ['checker', 'genera... | gram',
fields=dict(
fingerprint=hash(code_binary),
filename=fil | e,
code=code,
lang='cpp',
category=cat,
builtin=True
)))
json.dump(data, output_file)
output_file.close()
|
dstufft/warehouse | tests/unit/admin/views/test_squats.py | Python | apache-2.0 | 1,618 | 0.000618 | # 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 warehouse.admin.squats import Squat
from warehouse.admin.views import squats as views
from ....common.db.packaging import ProjectFactory
class ... |
LaurentRDC/scikit-ued | skued/tests/test_thin_films.py | Python | gpl-3.0 | 768 | 0.001302 | # -*- coding: utf-8 -*-
from random import randint, random, seed
from skued import film_optical_coefficients
seed(23)
def test_film_interaction_conservation_power():
"""Test that R + T + A = 1 always"""
wavelength = | randint(200, 1000)
thickness = randint(50, 200)
n_film = random() + 1j * random()
n_subs = random() + 1j * random()
R, T, A = film_optical_coefficients(wavelength, thickness, n_film, n_subs)
assert R + T + A == 1
def test_film_interaction_correctness():
"""Test for absorption values of VO2 ... | substrate. Values provided from Martin R. Otto"""
_, _, A = film_optical_coefficients(
800, thickness=90, n_film=2.9 + 1j * 0.43, n_substrate=1.9962
)
assert round(abs(A - 0.312495), 5) == 0
|
rahulunair/nova | nova/tests/unit/objects/test_instance_fault.py | Python | apache-2.0 | 4,346 | 0.00023 | # Copyright 2013 IBM Corp.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agree... | e-uuid': [
{'id': 1, 'instance_uuid': uuids.faults_instance, 'code': 123,
'message': 'msg1', 'details': 'details', 'host': 'host',
'deleted': False, 'created_at': None, 'updated_at': None,
'deleted_at': None},
{'id': 2, 'instance_uuid': uuids.faults_instance, 'code': 456,
... | ]
}
class _TestInstanceFault(object):
@mock.patch.object(db, 'instance_fault_get_by_instance_uuids',
return_value=fake_faults)
def test_get_latest_for_instance(self, get_mock):
fault = instance_fault.InstanceFault.get_latest_for_instance(
self.context, 'fak... |
knodir/son-emu | src/emuvim/api/openstack/openstack_dummies/neutron_dummy_api.py | Python | apache-2.0 | 38,680 | 0.00287 | from flask_restful import Resource
from flask import request, Response
from emuvim.api.openstack.openstack_dummies.base_openstack_dummy import BaseOpenstackDummy
from datetime import datetime
import logging
import json
import uuid
import copy
class NeutronDummyApi(BaseOpenstackDummy):
def __init__(self, ip, port,... | playbook)
self.app.run(self.ip, self.port, debug=True, use_reloader=False)
class Shutdown(Resource):
def get(self): |
logging.debug(("%s is beeing shut down") % (__name__))
func = request.environ.get('werkzeug.server.shutdown')
if func is None:
raise RuntimeError('Not running with the Werkzeug Server')
func()
class NeutronListAPIVersions(Resource):
def get(self):
"""
L... |
kshmirko/sageII-stat | make-stat.py | Python | gpl-2.0 | 4,462 | 0.024451 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 24 11:17:25 2014
@author: kshmirko
"""
import pandas as pds
import numpy as np
def seasons(x):
month = x.month
ret = None
if month in [12,1,2]:
ret = "Winter"
elif month in [3,4,5]:
ret = "Spring"
elif month in [... | {12}, cm^{-3}$' )
ax.set_title('Winter')
Ht0 = THseasons['Winter'][0]['mean']
Ht0e= THseasons['Winter'][0]['std']
ax.plot([Ht0,Ht0],[0,6],
'k.--',lw=2)
ax | .plot([Ht0,Ht0],[0,6],
'k.--',lw=2)
ax.annotate('$H_{tropo}=%3.1f\pm%3.1f km$'%(Ht0, Ht0e), xy=(Ht0, 4,),
xycoords='data', xytext=(30, 4.0),
arrowprops=dict(arrowstyle="->", lw=2),
size=16
)
ax.grid()
ax2 = ax.twinx()
ax2.plot(X,O3seasons_Err['Winter'],'r.--')
a... |
funkring/fdoo | addons/calendar/calendar.py | Python | agpl-3.0 | 86,995 | 0.004311 | # -*- coding: utf-8 -*-
import pytz
import re
import time
import openerp
import openerp.service.report
import uuid
import collections
import babel.dates
from werkzeug.exceptions import BadRequest
from datetime import datetime, timedelta
from dateutil import parser
from dateutil import rrule
from dateutil.relativedelta... | ry').value = event_obj.name
if event_obj.description:
event.add('description').v | alue = event_obj.description
if event_obj.location:
event.add('location').value = event_obj.location
if event_obj.rrule:
event.add('rrule').value = event_obj.rrule
if event_obj.alarm_ids:
for alarm in event_obj.alarm_ids:
valarm = event.add('v... |
bdaroz/the-blue-alliance | tests/models_tests/notifications/test_event_level.py | Python | mit | 4,813 | 0.002909 | from datetime import datetime
import unittest2
from google.appengine.ext import ndb
from google.appengine.ext import testbed
from consts.notification_type import NotificationType
from helpers.event.event_test_creator import EventTestCreator
from models.team import Team
from models.notifications.event_level import Ev... | self.assertIsNotNone(self.notification.fcm_notification)
self.asse | rtEqual(self.notification.fcm_notification.title, 'TESTPRESENT Qualification Matches Starting')
self.assertEqual(self.notification.fcm_notification.body, 'Present Test Event: Qualification Matches are starting.')
def test_fcm_notification_short_name(self):
self.notification.event.short_name = 'Ariz... |
nk113/tastypie-rpc-proxy | rpc_proxy/proxies.py | Python | bsd-3-clause | 26,445 | 0.002004 | # -*- coding: utf-8 -*-
import logging
import re
import slumber
from datetime import datetime
from dateutil import parser as dateparser
from queryset_client import client
from urllib import urlencode
from urlparse import urlparse
try:
# try to import django suite
from django.conf import settings
from dja... | ule = __import__
from rpc_proxy import exceptions
from rpc_proxy.utils import logf
PK_ID = ('pk', 'id',)
logger = logging.getLogger(__name__)
def extend(instance, new_class, attrs={}):
instance.__class__ = type(new_class.__name__,
(instance.__class__, new_class),
| attrs)
instance.__class__.__module__ = new_class.__module__
instance.__module__ = new_class.__module__
return instance
def mixin(cls, mixin):
if mixin not in cls.__bases__:
cls.__bases__ = (mixin,) + cls.__bases__
def get_setting(name, default=None):
return getattr(set... |
srajag/contrail-controller | src/config/common/vnc_cpu_info.py | Python | apache-2.0 | 7,056 | 0.000425 | #
# Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
#
"""
.. attention:: Fix the license string
"""
import os
import socket
import psutil
import gevent
from uve.cfgm_cpuinfo.ttypes import *
from uve.cfgm_cpuinfo.cpuinfo.ttypes import *
from buildinfo import build_info
from sandesh_common.vns.ttypes impo... | esh=self._sandesh)
# end | _send_cpustats
# end class CpuInfo
|
ganga-devs/ganga | ganga/GangaCore/GPIDev/Lib/Tasks/CoreTask.py | Python | gpl-3.0 | 474 | 0 | from GangaCore.GPIDev.Lib.Tasks import ITask
from GangaCore.GPIDev.Schema import Schema, Version
####### | #################################################################
class CoreTask(ITask):
"""General non-experimentally specific Task"""
_schema = Schema(Version(1, 0), dict(ITask._schema.datadict.items()))
_category = 'tasks'
_name = 'CoreTas | k'
_exportmethods = ITask._exportmethods + []
_tasktype = "ITask"
default_registry = "tasks"
|
exleym/IWBT | iwbt/blueprints/api_01/resources/rapids.py | Python | apache-2.0 | 2,036 | 0.000982 | """
API Routes for <Rapid> Resource
===================================================================
These routes serve as endpoints for performing CRUD operations on
the <Rapid> resources. Rapids are currently the smallest piece of
the systems we are modeling and are generally a single nonstop
... | abaseIntegrityError())
rapid = session.query(Rapid).filter(Rapid. | name == name) \
.filter(River.id == river_id).first()
return jsonify(rapid.shallow_json), 200 |
miing/mci_migo | identityprovider/forms.py | Python | agpl-3.0 | 21,018 | 0 | # Copyright 2010 Canonical Ltd. This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
import logging
from django import forms
from django.core.urlresolvers import reverse
from django.forms import Form, fields, widgets
from dja | ngo.utils import translation
from django.utils.translation import ugettext as _
from identityprovider.const import (
AX_DATA_FIELDS,
AX_DATA_LABELS,
)
from identityprovider.models import (
Account,
EmailAddress,
verify_token_string,
get_team_memberships_for_user,
)
from identityprovider.models.... | olicy,
)
from identityprovider.fields import OATHPasswordField
from identityprovider.widgets import (
ROAwareTextInput,
ROAwareSelect,
)
logger = logging.getLogger('sso')
TWOFACTOR_CHOICES = (
(True, _('Always require an authentication device')),
(False, _('Require only when logging in to sites that ... |
googleapis/python-dialogflow-cx | samples/generated_samples/dialogflow_v3_generated_flows_delete_flow_sync.py | Python | apache-2.0 | 1,367 | 0.000732 | # -*- coding: utf-8 -*-
# Copyright 2022 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 applic | able 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.
#
# Generated code. DO NOT EDIT!
#
# Snippet for DeleteFlow
# NOTE: This snippet has been automatically gener... |
scottwernervt/cloudstorage | src/cloudstorage/__init__.py | Python | mit | 3,311 | 0.000604 | """Cloud Storage
:copyright: (c) 2018 by Scott Werner.
:license: MIT, see LICENSE for more details.
"""
import logging
from enum import Enum, unique
from cloudstorage.base import Blob, Container, Driver
from cloudstorage.exceptions import CloudStorageError
from cloudstorage.typed import Drivers
__all__ = [
"Blob... | ge.drivers.digitalocean",
"DigitalOceanSpacesDriver",
),
}
def get_driver(driver: DriverName) -> Drivers:
"""Get driver class by DriverName enumeration member.
.. code-block:: python
>>> from cloudstorage import DriverName, get_driver
| >>> driver_cls = get_driver(DriverName.LOCAL)
<class 'cloudstorage.drivers.local.LocalDriver'>
:param driver: DriverName member.
:type driver: :class:`.DriverName`
:return: DriverName driver class.
:rtype: :class:`.AzureStorageDriver`, :class:`.CloudFilesDriver`,
:class:`.GoogleStorage... |
PlushBeaver/FanFicFare | fanficfare/adapters/adapter_literotica.py | Python | gpl-3.0 | 17,171 | 0.00594 | # -*- coding: utf-8 -*-
# Copyright 2013 Fanficdownloader team, 2015 FanFicFare team
#
# 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
#
# Un... | tor's approval" in data1:
raise exceptions.StoryDoesNotExist("This submission is awaiting moderator's approval. %s"%self.url)
# author
a = soup1.find("span", "b-story-user-y")
self.story.setMetadata('authorId', urlparse.parse_qs(a.a['href'].split('?')[1])['uid'][0])
authorur... | )
self.story.setMetadata('author', a.text)
# get the author page
try:
dataAuth = self._fetchUrl(authorurl)
soupAuth = self.make_soup(dataAuth)
#strip comments from soup
[comment.extract() for comment in soupAuth.findAll(text=lambda text:isinstance... |
tommo/gii | lib/gii/qt/controls/GraphicsView/TimelineWidget.py | Python | mit | 25,976 | 0.06941 | import sys
import math
from PyQt4 import QtGui, QtCore, uic
from PyQt4.QtCore import Qt, QObject, QEvent, pyqtSignal
from PyQt4.QtCore import QPoint, QRect, QSize
##----------------------------------------------------------------##
def _getModulePath( path ):
import os.path
return os.path.dirname( __file__ ) + '/' +... | formatter = self.formatter
width = self.width()
height = self.height()
zoom | = self.zoom
scrollPos = self.scrollPos
posStep = self.posStep
subStep = self.subStep
posFrom = int( math.floor( scrollPos/posStep ) * posStep )
posTo = int( math.ceil ( (scrollPos + width/zoom )/posStep + 1 ) * posStep )
for pos in range( posFrom, posTo, posStep ):
x = ( pos - scrollPos ) * ... |
FedoraScientific/salome-smesh | doc/salome/examples/filters_ex24.py | Python | lgpl-2.1 | 393 | 0.005089 | # Bare border volumes
# create mesh
from SMESH_mechanic import *
mesh.Tetrahedron()
mesh.Compute()
# remove some volumes to | have volumes with bare borders
mesh.RemoveElements( mesh.GetElementsByType(VOLUME)[0:5] )
# get all volumes with bare borders
filter = smesh.GetFilter(SMESH.VOLUME, SMESH.FT_BareBorderVolume)
ids = | mesh.GetIdsFromFilter(filter)
print "Volumes with bare borders:", ids
|
jaggu303619/asylum | openerp/addons/crm_claim/crm_claim.py | Python | agpl-3.0 | 11,219 | 0.005883 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-today OpenERP SA (<http://www.openerp.com>)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms o... | 'res.company', 'Company'),
'partner_id': fields.many2one('res.partner', 'Partner'),
'email_cc': fields.text('Watchers Emails', size=252, help="These email addresses will be added to the CC field of all inbound and outbound emails for this record before being sent. Separate multiple email addresses with ... | lds.char('Phone', size=32),
'stage_id': fields.many2one ('crm.claim.stage', 'Stage', track_visibility='onchange',
domain="['&',('fold', '=', False),'|', ('section_ids', '=', section_id), ('case_default', '=', True)]"),
'cause': fields.text('Root Cause'),
'state': fields.related('... |
agvergara/Python | X-Serv-15.9-Django-CMS-Templates/cms_put/views.py | Python | gpl-3.0 | 1,689 | 0.005329 | from django.shortcuts import render
from cms.models import Pages
from django.http import HttpResponse, HttpResponseNotAllowed
from django.template.loader import get_template
from django.template import Context, RequestContext
from django.core.exceptions import ObjectDoesNotExist
# Create your views here.
def getform (... |
def insertcontent(request):
if request.user.is_authenticated():
if request.method == "PUT" or request.method == "POST":
info = request.body
try:
split_list = info.spl | it('&', 2)
name = split_list[1].split('=')[1]
content = split_list[2].split('=')[1]
except IndexError:
ans = "Bad input: name=content"
return HttpResponse(ans)
page = Pages(name=name, page=content)
page.save()
... |
GeosoftInc/gxapi | spec/core/VM.py | Python | bsd-2-clause | 9,250 | 0.006919 | from .. import Availability, Class, Constant, Define, Method, Parameter, Type
gx_class = Class('VM',
doc="""
In-memory vector data methods
The :class:`VM` class will store vector (array) data in a memory buffer which
can be accessed using the :class:`... | f possible.
""",
return_type=Type.VOID,
parameters = [
| Parameter('vm', type="VM"),
Parameter('element', type=Type.INT32_T,
doc="Element to set"),
Parameter('value', type=Type.INT32_T,
doc="Value to set")
]),
Method('SetReal_VM', module='geoengine.core',... |
nvictus/23andCSB | settings/prod.py | Python | bsd-2-clause | 1,415 | 0.009894 | from .base import *
DEBUG = get_env_setting('DEBUG', False)
TEMPLATE_DEBUG = DEBUG
########## SECRET CONFIGURATION
SECRET_KEY = get_env_setting('SECRET_KEY')
########## END SECRET CONFIGURATION
########## HOST CONFIGURATION
ALLOWED_HOSTS = [get_env_setting('HOSTNAME')]
########## END HOST CONFIGURATION
# 23andMe AP... | _APPS += (
'apps.api',
'apps.csb',
)
CLIENT_ID = get_env_setting('CLIENT_ID')
CLIENT_SECRET = get_env_setting('CLIENT_SECRET')
CALLBACK_URL = | get_env_setting('CALLBACK_URL')
########## DATABASE CONFIGURATION
import os
import dj_database_url
DATABASES['default'] = dj_database_url.config()
########## END DATABASE CONFIGURATION
########## CACHE CONFIGURATION
# CACHES = {
# 'default': {
# 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',... |
zozo123/buildbot | master/buildbot/test/unit/test_www_rest.py | Python | gpl-3.0 | 26,772 | 0.001009 | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without eve... | protect the user
yield self.render_resource(self.rsrc, '/')
self.assertOk(expectHeaders=False)
@defer.inlineCallbacks
def test_cors_origin_match(self):
yield self.render_resource(self.rsrc, '/', origin='h://good')
self.assertOk()
@defer.inlineCallbacks
def test_cors_or... | self):
self.master.config.www['allowed_origins'] = ['*']
self.rsrc.reconfigResource(self.master.config)
yield self.render_resource(self.rsrc, '/', origin='h://good')
self.assertOk()
@defer.inlineCallbacks
def test_cors_origin_patterns(self):
self.master.config.www['allow... |
eReuse/DeviceHub | ereuse_devicehub/tests/test_resources/test_events/test_device_event/test_update.py | Python | agpl-3.0 | 785 | 0 | from assertpy import assert_that
from ereuse_devicehub.tests import TestStandard
class TestDeviceEventUpdate(TestStandard):
def test_creation(self):
computers_id = self.get_fixtures_computers()
update = {
'@type': 'devices:Update',
'devices': computers_id,
'mar... | 'invoiceRetailerId': 'fff',
'eTag': 'DT-494949'
}
update = self.post_201 | (self.DEVICE_EVENT_UPDATE, update)
assert_that(update).has_margin('foo')
assert_that(update).has_price('1.3')
assert_that(update).has_partners('baz')
assert_that(update).has_invoiceRetailerId('fff')
assert_that(update).has_eTag('DT-494949')
|
JorgeDeLosSantos/PiChi | core/__ws.py | Python | mit | 245 | 0.008163 | # -*- coding: utf-8 -*-
# ***********************************
# PiChi 0.0.1
# Author: Pedro Jorge De Los Santos
# | E-mail: delossantosmfq@gmail.com
# Web: labdls.blogspot.mx
# License: MIT License
# ************************* | **********
|
P1d0f/encryptGen | encryption-generator.py | Python | gpl-3.0 | 8,291 | 0.055241 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# encryption-generator.py
#
# Copyright 2016 Netuser <zorgonteam@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either v... | ] encoded at",now
print "\n[*] result :",base16
menu_item="sha224"
if menu_item == raw:
telo=raw_input('[*] text $ ')
| sha224=hashlib.sha224('%s' % (telo)).hexdigest()
for i in(5,4,3,2,1):
print "[*] encrypted at",now
print "\n[*] result :",sha224
menu_item="sha384"
if menu_item == raw:
telo=raw_input('[*] text $ ')
sha384=hashlib.sha384('%s' % (telo)).hexdigest()
for i in(5,4,3,2,1):
print "[*] encr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.