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 |
|---|---|---|---|---|---|---|---|---|
Diyago/Machine-Learning-scripts | DEEP LEARNING/Kaggle Avito Demand Prediction Challenge/stem to SVD.py | Python | apache-2.0 | 8,068 | 0.028398 | #Thanks for the approach https://github.com/ML-Person/My-solution-to-Avito-Challenge-2018 (@nikita)
import pandas as pd
import numpy as np
import gc
import os
import re
import pickle
import string
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
from sklearn.preproces... | t_tfidf]))
test_tfidf = csr_matrix(hstack([test_title_tfidf, test_desc_tfidf, test_text_tfidf]))
del train_title_tfidf, train_desc_tfidf, train_text_tfidf
del test_title_tfidf, test_desc_tfidf, tes | t_text_tfidf
gc.collect()
vocab = np.hstack([
title_tfidf.get_feature_names(),
desc_tfidf.get_feature_names(),
text_tfidf.get_feature_names()
])
[DUMP] TF-IDF pickle files + vocabulary
with open(os.path.join(PATH_TO_DATA, 'train_tfidf.pkl'), 'wb') as train_tfidf_pkl:
pickle.dump(train_tfidf, train_tf... |
xialeiliu/RankIQA | src/data_layer/rank_layer_live.py | Python | mit | 4,545 | 0.010341 | import cv2
import caffe
import numpy as np
import multiprocessing as mtp
import pdb
import os.path as osp
class DataLayer(caffe.Layer):
def setup(self, bottom, top):
self._name_to_top_map = {}
self._name_to_top_map['data'] = 0
self._name_to_top_map['label'] = 1
# === Read input p... | db = []
for i in range(len(db_inds)):
minibatch_db.append(self._roidb[int(db_inds[i])])
#minibatc | h_db = [self._roidb[i] for i in db_inds]
#print minibatch_db
scores = []
for i in range(len(db_inds)):
scores.append(self.scores[int(db_inds[i])])
blobs = self.get_minibatch(minibatch_db)
blobs ['label'] =np.asarray(scores)
for blob_name, blob in blobs.iterite... |
dr-glenn/PiClock | Clock/q1.py | Python | mit | 3,326 | 0.001203 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'q1.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
... | self.menuMain_Window = QtGui.QMenu(self.menubar)
self.menuMain_Window.setObjectName(_fromUtf8("menuMain_Window"))
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtGui.QStatusBar(MainWindow)
self.statusbar.setObjectName(_fromUtf8("statusbar"))
MainWindow.setStatusBar(se... | self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
__sortingEnabled = self.listWidget.isSortingEnabled()
self.listWidget.setSortingEnabled(F... |
oomlout/oomlout-OOMP | old/OOMPpart_RESE_0805_X_O202_01.py | Python | cc0-1.0 | 243 | 0 | import OOMP
newPart = OOMP.oompItem(9439)
newPart.addTag("oompType" | , "RESE")
newPa | rt.addTag("oompSize", "0805")
newPart.addTag("oompColor", "X")
newPart.addTag("oompDesc", "O202")
newPart.addTag("oompIndex", "01")
OOMP.parts.append(newPart)
|
crobertsbmw/RobertsAB | admin.py | Python | mit | 283 | 0.010601 | from RobertsAB.models impor | t Test, Experiment
from django.contrib import admin
class TestInline(admin.StackedInline):
model = Test
class ExperimentAdmin(admin.ModelAdmin):
inli | nes = [TestInline]
admin.site.register(Test)
admin.site.register(Experiment, ExperimentAdmin)
|
hrayr-artunyan/shuup | shuup_tests/utils/test_numbers.py | Python | agpl-3.0 | 745 | 0.001342 | # This file is part of Shuup.
#
# Copyright (c) 2012-2016, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file | in the root directory of this source tree.
from decimal import Decimal
import pytest
from shuup.utils.numbers import parse_decimal_string
@pytest.mark.parametrize("input_val, expected_val", [
(0.0, Decimal('0.0')),
(1.1, Decimal('1.1')),
(-1.1, Decimal('-1.1')),
(1e10, Decimal('10000000000')),
(... | parse_decimal_string(input_val)
assert result == expected_val
|
Hoikas/korman | korman/exporter/convert.py | Python | gpl-3.0 | 21,736 | 0.002484 | # This file is part of Korman.
#
# Korman 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.
#
# Korman is distributed i... | a CoordinateInterface
self._harvest_actors()
# S | tep 2.9: It is assumed that static lighting is available for the mesh exporter.
# Indeed, in PyPRP it was a manual step. So... BAKE NAO!
self._bake_static_lighting()
# Step 3: Export all the things!
self._export_scene_objects()
... |
PaloAltoNetworks-BD/SplunkforPaloAltoNetworks | Splunk_TA_paloalto/bin/splunk_ta_paloalto/aob_py3/splunk_aoblib/setup_util.py | Python | isc | 13,234 | 0.001662 | from builtins import str
from builtins import range
from builtins import object
import json
import os
import solnlib.utils as utils
from splunktaucclib.global_config import GlobalConfig, GlobalConfigSchema
'''
Usage Examples:
setup_util = Setup_Util(uri, session_key)
setup_util.get_log_level()
setup_util.get_proxy_... | ulti_dropdownlist', 'radiogroup']
def get_schema_path():
dirname = os.path.dirname
basedir = dirname(dirname(dirname(dirname((dirname(__file__))))))
return os.path.join(basedir, 'appserver', 'static', 'js', 'build', 'globalConfig.json')
class Setup_Util(object):
def __init__(self, uri, session_key, ... | self.__uri = uri
self.__session_key = session_key
self.__logger = logger
self.scheme, self.host, self.port = utils.extract_http_scheme_host_port(
self.__uri)
self.__cached_global_settings = {}
self.__global_config = None
def init_global_config(self):
... |
brandond/ansible | lib/ansible/modules/storage/hpe3par/ss_3par_cpg.py | Python | gpl-3.0 | 9,304 | 0.000967 | #!/usr/bin/python
# Copyright: (c) 2018, Hewlett Packard Enterprise Development LP
# GNU General Public License v3.0+
# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
... | growthIncrementMiB': growth_increment,
'growthLimitMiB': growth_limit,
'usedLDWarningA | lertMiB': growth_warning,
'LDLayout': ld_layout}
client_obj.createCPG(cpg_name, optional)
else:
return (True, False, "CPG already present")
except exceptions.ClientException as e:
return (False, False, "CPG creation failed | %s" % (e))
return (True, True, ... |
christianbrodbeck/nipype | nipype/pipeline/plugins/dagman.py | Python | bsd-3-clause | 4,865 | 0.001028 | """Parallel workflow execution via Condor DAGMan
"""
import os
import sys
from .base import (GraphPluginBase, logger)
from ...interfaces.base import CommandLine
class CondorDAGManPlugin(GraphPluginBase):
"""Execute using Condor DAGMan
The plugin_args input to run can be used to control the DAGMan executio... | - infer CPU requirements from jobs
# - | infer memory requirements from jobs
# - looks like right now all jobs come in here, regardless of whether they
# actually have to run. would be good to be able to decide whether they
# actually have to be scheduled (i.e. output already exist).
def __init__(self, **kwargs):
self._template = "... |
CraigglesO/Ciphers | vigenere_plaintext_encrypt.py | Python | apache-2.0 | 3,166 | 0.026532 | #########################################################################################
#################### HOW TO USE ##########################
#########################################################################################
# This takes input from the terminal so run (in th... |
# #
# so obviously the first variable is the plaintext with no spaces allowed #
# and the key is an arbitrary length you use to encode the words #
| # #
# #
# #
# For decrypting your code check the brother script 'vigenere_plaintext_decrypt.py' #
#########################################################################################
########################################... |
OKThess/website | main/migrations/0044_okthessmeetup.py | Python | mit | 775 | 0.002581 | # -*- c | oding: utf-8 -*-
# Generated by Django 1.11.5 on 2017-10-16 16:08
from __future__ import unicode_literals
import ckeditor.fields
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main', '0043_about'),
]
operations = [
migrations.CreateMod... | se, verbose_name='ID')),
('date', models.DateField()),
('time', models.TimeField()),
('title', models.TextField(blank=True, null=True)),
('agenda', ckeditor.fields.RichTextField(blank=True, null=True)),
],
),
]
|
jcugat/django-custom-user | src/custom_user/tests.py | Python | bsd-3-clause | 22,621 | 0.001371 | """EmailUser tests."""
import os
import re
from io import StringIO
from unittest import mock
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.middleware import AuthenticationMiddleware
from django.core import mail, management
from django.forms.fields import Field... | /"
user = get_user_model().objects.create_superuser(email_lowercase, password)
self.assertEqual(user.email, email_lowercase)
self.assertTrue(user.check_password, password)
self.assertTrue(user.is_active)
self.assertTrue(user.is_staff)
self.assertTrue(user.is_superuser)
... | must have is_superuser=True."
):
get_user_model().objects.create_superuser(
email="test@test.com",
is_superuser=False,
)
def test_create_superuser_raises_error_on_false_is_staff(self):
with self.assertRaisesMessage(ValueError, "Superuser must... |
fbradyirl/home-assistant | homeassistant/components/lovelace/__init__.py | Python | apache-2.0 | 6,719 | 0.000298 | """Support for the Lovelace UI."""
from functools import wraps
import logging
import os
import time
import voluptuous as vol
from homeassistant.components import websocket_api
from homeassistant.exceptions import HomeAssistantError
from homeassistant.util.yaml import load_yaml
_LOGGER = logging.getLogger(__name__)
... | pdated"
LOVELACE_CONFIG_FILE = "ui-lovelace.yaml"
WS_TYPE_GET_LOVELACE_UI = "lovelace/config"
WS_TYPE_SAVE_CONFIG = "lovelace/config/save"
SCHEMA_GET_LOVELACE_UI = websocket_api.BASE_COMMAND_MESSAGE_SCHEMA.extend(
{
| vol.Required("type"): WS_TYPE_GET_LOVELACE_UI,
vol.Optional("force", default=False): bool,
}
)
SCHEMA_SAVE_CONFIG = websocket_api.BASE_COMMAND_MESSAGE_SCHEMA.extend(
{
vol.Required("type"): WS_TYPE_SAVE_CONFIG,
vol.Required("config"): vol.Any(str, dict),
}
)
class ConfigNotFound(... |
hicham-a/luna | test/test06.py | Python | gpl-3.0 | 308 | 0.016234 | from Luna import Luna
from bson import ObjectId
luna = Luna('luna',['cluster','nodes'])
print 1
print luna.find_obj('nodes', 'node005')
print 2
print luna.add_array_elem('nodes', ['node005', 'node006'], 'nodes1', ['a1', | 'a2', 'a3'] )
print 3
print luna.change_obj('nodes',['node001', 'node003'], {'zzz': 6})
| |
putcn/Paddle | python/paddle/fluid/layers/metric.py | Python | apache-2.0 | 2,939 | 0.000681 | # Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... | lper.append_op(
type="accuracy",
in | puts={
"Out": [topk_out],
"Indices": [topk_indices],
"Label": [label]
},
outputs={
"Accuracy": [acc_out],
"Correct": [correct],
"Total": [total],
})
return acc_out
def auc(input, label, curve='ROC', num_thresholds=200)... |
bergonzzi/eracareers | era_scraper/eracareers/middlewares/elasticsearch_new.py | Python | apache-2.0 | 2,816 | 0.002486 | # -*- coding: utf-8 -*-
# Copyright 2014 Michael Malocha <michael@knockrentals.com>
#
# Expanded from the work by Julien Duponchelle <julien@duponchelle.info>.
#
# 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 ... | each in item:
self.process_item(each, spider)
else:
self.index_item(item, spider)
spider.logger.info("Item sent | to Elastic Search %s" % (self.settings.get('ELASTICSEARCH_INDEX')))
return item |
robhudson/warehouse | tests/test_serving.py | Python | apache-2.0 | 1,290 | 0 | # Copyright 2013 Donald Stufft
#
# 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, so... | d
# limitations under the Licens | e.
from __future__ import absolute_import, division, print_function
from __future__ import unicode_literals
import pretend
from warehouse import serving
from warehouse.serving import WSGIRequestHandler
def test_request_handler_log(monkeypatch):
_log = pretend.call_recorder(lambda *a, **kw: None)
monkeypatc... |
intel-analytics/BigDL | python/ppml/test/bigdl/ppml/algorithms/test_hfl_logistic_regression.py | Python | apache-2.0 | 1,167 | 0 | #
# Copyright 2016 The BigDL Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in complia | nce 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 ag | reed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import unittest
import numpy as np
from b... |
mikerjacobi/goji-skeleton | go.py | Python | apache-2.0 | 547 | 0.012797 | #!/usr/bin/python
| import os
container_name = "goji"
host_port = "8003"
cmd = "docker ps -a | grep %s"%container_name
container_exists = len(os.popen(cmd).read().split('\n')) > 1
print cmd
print "exists:", container_exists
if container_exists:
cmd = "go build && docker restart %s"%container_name
print cmd
os.system(cmd)
els... | "name":container_name
})
print cmd
os.system(cmd)
|
irares/WirelessHart-Gateway | NetworkManager/scripts/Python/ReviewOperations.py | Python | gpl-3.0 | 9,145 | 0.044505 | #!/usr/bin/python
#
# python module for detecting unconfirmed operations from
# nmOperations.log, packets and events in nm.log file
# complaints: radu marginean
#
import re
import os
_operations = {}
_packets = {}
_events = {}
def _PrintUnconfirmedOperations(nodeNickname_):
global _operations
tmpDict = {}
fo... | ndx])
#confirmed
if state == 'C':
if (id, own) in _operations.keys(): |
del _operations[(id, own)]
else:
if verbose_:
print "Operation confirmed without being listed as generated:"
print reason, lineString
elif state == 'G':
_operations[(id, own)] = (reason, lineString)
log.close()
def _CheckPackets(logFile_, verbose_):
global _packets
log = open(logFi... |
nkiraly/ansible-sshjail | sshjail.py | Python | mit | 4,773 | 0.005447 | import distutils.spawn
import traceback
import os
import shutil
import subprocess
import re
import sys
from ansible import errors
from ansible.callbacks import vvv
import ansible.constants as C
from ansible.runner.connection_plugins.ssh import Connection as SSHConn
class Connection(object):
''' jail-over-ssh based... | exec %s %s' % (
self.get_jail_id(), cmd,
self.get_jail_id(), c | md
)
vvv("JAIL (%s) %s" % (become_user, local_cmd), host=self.host)
return self._exec_command(local_cmd, tmp_path, become_user, True, executable, in_data)
def _normalize_path(self, path, prefix):
if not path.startswith(os.path.sep):
path = os.path.join(os.path.sep, path... |
realmarcin/data_api | data_loading/genome_loading/upload_assemblies.py | Python | mit | 17,445 | 0.012554 | #!/usr/bin/env python
# standard library imports
import os
import sys
import logging
import re
import hashlib
import time
import traceback
import os.path
# 3rd party imports
import simplejson
# KBase imports
import doekbase.Transform.script_utils as script_utils
import TextFileDecoder
import doekbase.workspace.c... | sequence
if (not sequence_exists) and first_header_found:
logger.error("There is no sequence related to FASTA record : {0}".format(fasta_header))
raise Exception("There is no sequence related to FASTA record : {0}" | .format(fasta_header))
if not first_header_found:
first_header_found = True
# sequence_start = input_file_handle.tell()
sequence_start = 0
else:
sequence_stop = input_file_handle.tell() - len(curre... |
zhendilin/django-block-ip | block_ip/models.py | Python | bsd-3-clause | 866 | 0.001155 | import ipcalc
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.core.cache import cache
from django.db.models.signals import post_save, post_delete
class BlockIP(models.Model):
network = models.CharField(_ | ('IP address or mask'), max_length=18)
reason_for_block = models.TextField(blank=True, null=True, help_text=_("Optional reason for block"))
def __unicode__(self):
return 'BlockIP: %s' % self.network
def get_network(self):
return ipcalc.Network(self.network)
class Meta:
verbose... | IPs & masks to ban')
def _clear_cache(sender, instance, **kwargs):
cache.set('blockip:list', BlockIP.objects.all())
post_save.connect(_clear_cache, sender=BlockIP)
post_delete.connect(_clear_cache, sender=BlockIP)
|
Dai-trying/daixmms2client | connector.py | Python | gpl-3.0 | 1,747 | 0 |
# Copyright 2016 by Dai Trying
#
# This file is part of daixmms2client.
#
# daixmms2client 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 opti... | 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 daixmms2client. If not, see <http://www.gnu.org/licenses/>.
from PyQt5.QtCore import QObject, QSocketNotifier
class XMMSConnector(QObject):
def __init__(self, x... |
uclouvain/OSIS-Louvain | learning_unit/api/serializers/learning_unit.py | Python | agpl-3.0 | 6,633 | 0.002413 | ##############################################################################
#
# OSIS stands for Open Student Information System. It's an application
# designed to manage the core business of higher education institutions,
# such as universities, faculties, institutes and professional schools.
# The core ... | iendly',
'components',
'parent',
'partims',
'proposal',
'summary_status',
'professional_integration',
'remark',
'remark_en' | ,
)
@staticmethod
def get_proposal(learning_unit_year):
if not hasattr(learning_unit_year, "proposallearningunit"):
return {}
return {
"folder": learning_unit_year.proposallearningunit.folder,
"type": learning_unit_year.proposallearningunit.get_type_... |
GoogleCloudPlatform/sap-deployment-automation | third_party/github.com/ansible/awx/awxkit/awxkit/api/pages/settings.py | Python | apache-2.0 | 1,336 | 0 | from awxkit.api.resources import resources
from . import base
from . impor | t page
class Setting(base.Bas | e):
pass
page.register_page([resources.setting,
resources.settings_all,
resources.settings_authentication,
resources.settings_changed,
resources.settings_github,
resources.settings_github_org,
... |
ayepezv/GAD_ERP | addons/hr_holidays/tests/test_holidays_flow.py | Python | gpl-3.0 | 11,913 | 0.002434 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from datetime import datetime
from dateutil.relativedelta import relativedelta
from odoo.exceptions import AccessError, ValidationError
from odoo.tools import mute_logger, test_reports
from odoo.addons.hr_holidays.tests... | NotLimitedMeetingType'}).id
})
self.holidays_status_1 = HolidayStatusManagerGroup.create({
'name': 'NotLimited',
'limit': True,
})
self.holidays_status_2 = HolidayStatusManagerGroup.create({
'name': 'Limited',
'limit': False,
'd... | uest
# --------------------------------------------------
# Employee creates a leave request for another employee -> should crash
HolidaysEmployeeGroup = Holidays.sudo(self.user_employee_id)
with self.assertRaises(ValidationError):
HolidaysEmployeeGroup.create({
... |
andreivasiliu2211/upm | examples/python/bmp280.py | Python | mit | 2,069 | 0.0058 | #!/usr/bin/python
# Author: Jon Trulson <jtrulson@ics.com>
# Copyright (c) 2016 Intel Corporation.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Soft | ware"), 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 So | ftware 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 "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO... |
niliafsari/KSP-SN | Lbolcorr.py | Python | bsd-3-clause | 11,518 | 0.023615 | from astropy.io import fits
from astropy.wcs import WCS
import numpy as np
import matplotlib
import os
import glob
from findSN import *
from matplotlib.ticker import AutoMinorLocator
import sys
sys.path.insert(0, '/home/afsari/')
from SNAP2.Analysis import *
current_path=os.path.dirname(os.path.abspath(__file__))
matp... |
beta=l2+(-alpha*t2)
zz[1]=beta
zz[0]=alpha
fit_2 = np.poly1d(zz)
# Mv=v
# vi_t=v_t
# vi_t_late=vi_t[vi_t>=474]
# Mv_late=Mv[vi_t>=474]
# z = np.polyfit(vi_t_late, Mv_late, 1)
# fit = np.poly1d(z)
# Mv_new=fit(vi_t_late)
# Mv[vi_t>=474]=Mv_new
print np.shape(Mv)
for k, M_mag in enumerate(Mv):
if (1):
#Lyman... | k]>0.4):
Mbol[k] = M_mag + 0.057 + 0.708 * (vi[k]) - 0.912 * (np.square(vi[k]))
else:
Mbol[k] = M_mag-0.61 + 2.244 * (vi[k]) - 2.107 * (np.square(vi[k]))
#V-R
# Mbol[k] = M_mag + 0.073 + 0.902 * (vi[k]) - 1.796 * (np.square(vi[k]))
# Mbol[k] = M_mag + 0.059 + 0.744 * (v... |
yugangw-msft/azure-cli | src/azure-cli/azure/cli/command_modules/synapse/manual/operations/accesscontrol.py | Python | mit | 11,030 | 0.004624 | # --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
if assignment_id and not is_guid(assig | nment_id):
raise InvalidArgumentValueError('usage error: --id GUID')
if bool(assignee) == bool(assignee_object_id):
raise ArgumentUsageError('usage error: --assignee STRING | --assignee-object-id GUID')
if assignee_principal_type and not assignee_object_id:
raise ArgumentUsageError('us... |
hhj0325/pystock | com/hhj/baihuabigdata/demo8.py | Python | apache-2.0 | 1,943 | 0.003603 | """
page
222
225
226
227
"""
from sklearn.datasets import fetch_20newsgroups
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.neighbors.nearest_centroid import NearestCentroid
from sklearn.naive_bayes import Multinomia... | twenty_train.data)
tfidf_transformer = TfidfTransformer()
X_train_tfidf = tfidf_transformer.fit_transform(X_train_counts)
docs_new = ['God is love', 'OpenGl on the GPU is fast']
X_new_counts = count_vect.transform(docs_new)
X_new_tfidf = tfidf_transformer.transform(X_new_counts)
print(datetime.datetime.now())
predic... | ('NearestCentroid', docs_new, predicted1, twenty_train)
print(datetime.datetime.now())
predicted2 = MultinomialNB().fit(X_train_tfidf, twenty_train.target).predict(X_new_tfidf)
print_result('MultinomialNB', docs_new, predicted2, twenty_train)
print(datetime.datetime.now())
predicted3 = KNeighborsClassifier(15).fit(X_... |
flaviovdf/vodlibs | vod/test/test_entropy.py | Python | mit | 3,236 | 0.005253 | # -*- coding: utf8
from __future__ import print_function, division
from vod import entropy
import numpy as np
import math
import unittest
#Calculates the entropy iteratively.
def it_entropy(probs):
ent = 0.0
for prob in probs:
if prob == 0:
continue
ent -= prob * math.log(prob, 2)... | l(entropy.kullback_leiber_divergence(x_probs,
xy_probs),
dkl)
def test_kl2(self):
x_probs = np.array([0.04, 0.16] * 5 + [0])
xy_probs = np.array([0.02, 0.18] * 5 + [0])
dkl = 0
... | v = x_probs[i] / xy_probs[i]
dkl += x_probs[i] * math.log(div, 2)
self.assertAlmostEqual(entropy.kullback_leiber_divergence(x_probs,
xy_probs),
dkl)
def test_kl3(self):
x_prob... |
haard/quarterapp | quarterapp/app.py | Python | mit | 3,685 | 0.012754 | #
# Copyright (c) 2013 Markus Eliasson, http://www.quarterapp.com/
#
# 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... | color = activity_dict[int(i)]["color"]
border_color = "#ccc" # darken color
quarters.append({ "id" : i, "color" : color, "border | -color" : border_color})
else:
quarters.append({ "id" : i, "color" : "#fff", "border-color" : "#ccc"})
else:
quarters = self.default_sheet()
self.render(u"app/sheet.html", date = date_obj, weekday = weekday,
today = today, yesterday = yesterda... |
tyb0807/angr | angr/engines/vex/irop.py | Python | bsd-2-clause | 36,944 | 0.003681 | """
This module contains symbolic implementations of VEX operations.
"""
import re
import sys
import collections
import itertools
import operator
import logging
l = logging.getLogger("angr.engines.vex.irop")
import pyvex
import claripy
#
# The more sane approach
#
def op_attrs(p):
m = re.match(r'^Iop_'
... | self._from_side = None
self._from_type = None
self._from_signed = None
self._to_size = None
self._to_type = None
self._to_signed = None
self._conversion = None
self._vector_size = None
self._vector_signed | = None
self._vector_type = None
self._vector_zero = None
self._vector_count = None
self._rounding_mode = None
for k,v in self.op_attrs.items():
if v is not None and ('size' in k or 'count' in k):
v = int(v)
setattr(self, '_%s'%k, v)
... |
alexandrebatista84/fundamentos-programacao | Aula Prática 2/Exercicio20.py | Python | mit | 84 | 0.107143 |
n=1
i=1
while i<10:
|
print(n,"X 8 +",i," | =",n*8+i)
i=i+1
n=n*10+i
|
esteinig/dartQC | dartqc/DartModules.py | Python | gpl-3.0 | 36,121 | 0.003211 | import csv
import operator
import os
import shutil
from subprocess import call
import pandas
import numpy
from Bio import SeqIO
from Bio.Alphabet import IUPAC
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from scipy import stats
from dartqc.DartUtils import stamp
from dartqc.DartMessages ... | urn params, removed
def _get_sample_results(self):
try:
removed = {"mind": self.attributes["individual"]["results"]["mind"]["removed_samples"],
"samples": self.attributes["individual"]["results"]["mind"]["removed_samples"]}
params = {"mind": self.att... | nd"]["value"],
"samples": len(self.attributes["individual"]["states"]["mind"]["sample_names_original"])}
except KeyError:
stamp("Could not detect results for Sample Module, skipping...")
params = {"mind": None, "samples": None}
removed = {"mind"... |
sarrionandia/taber | results/controllers/PointsController.py | Python | gpl-2.0 | 1,456 | 0 | from results.controllers.ResultsController import ResultsController
class PointsController():
results_controller = None
def __init__(self):
self.results_controller = ResultsController()
def team_points_for_team(self, team, round):
result = self.results_controller.result_for_team(team, r... | , round):
result = self.results_controller.result_for_team(team, round)
debate = result.debate
if debate.OG == team:
return [result.ogsp1, result.ogsp2]
if debate.OO == team:
return [result.oosp1, result.oosp2]
if debate.CG == team:
return [re... | return [result.cosp1, result.cosp2]
def team_points_map_for_round(self, round, teams):
points = {}
for team in teams:
points.update({team: self.team_points_for_team(team, round)})
return points
|
nathanielvarona/airflow | airflow/providers/tableau/operators/tableau_refresh_workbook.py | Python | apache-2.0 | 3,881 | 0.001804 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | Executes the Tableau Extract Refresh and pushes the job id to xcom.
:param context: The task context during execution.
:type context: dict
:return: the id of the job that executes the extract refresh
:rtype: str |
"""
with TableauHook(self.site_id, self.tableau_conn_id) as tableau_hook:
workbook = self._get_workbook_by_name(tableau_hook)
job_id = self._refresh_workbook(tableau_hook, workbook.id)
if self.blocking:
from airflow.providers.tableau.sensors.tableau_... |
soundgnome/django-rom | rom/invoices/calculator.py | Python | mit | 3,170 | 0.003155 | from datetime import date, timedelta
from decimal import Decimal
from django.db.models import Q, Sum
from .models import Expense, Invoice
def get_monthly_totals(year, month):
totals = {}
start = date(year, month, 1)
if month == 12:
end = date(year+1, 1, 1)
else:
end = date(year, month... | rt = date(start.year-1, start.month+10, 1)
aggregate = expenses.filter(date__gte=quarterly_start).filter(date__lt=end). \
filter(month_span=3).aggregate(Sum('amount'))
if aggregate['amount__sum']:
total += aggregate['amount__sum']/3
annual_start = date(end.year-1, end.month, 1)
... | filter(month_span=12).aggregate(Sum('amount'))
if aggregate['amount__sum']:
total += aggregate['amount__sum']/12
return total.quantize(Decimal('.01'))
def _get_filtered_expenses(tax=False):
if tax:
expenses = Expense.objects.filter(Q(type=Expense.Type.TAX_QUARTERLY) | Q(ty... |
vadosl/photorganizer | photorganizer/photo/views__.py | Python | mit | 8,479 | 0.006318 | # coding: utf-8
from django.http import HttpResponseRedirect, HttpResponse
from django.template import RequestContext
from django.shortcuts import get_object_or_404, render_to_response
from collections import defaultdict
from django.contrib.auth.decorators import login_required
from django.core.context_processors impo... | if not album.public and not request.user.is_authenticated():
return HttpResponse("Error: you need to be logged in to view this album.")
images = album.image_set.all()
paginator = Paginator(images, 30)
try: page = int(request.GET.get("page", '1'))
except ValueError: page = 1
try:
... | ator.page(paginator.num_pages)"""
#Write another code for Slideshow realization
num_images = 30
if view == "full": num_images = 10
album = Album.objects.get(pk=pk)
images = album.image_set.all()
paginator = Paginator(images, num_images)
try: page = int(request.GET.get("page", '1'))
ex... |
jimporter/bfg9000 | test/unit/tools/test_ld.py | Python | bsd-3-clause | 2,557 | 0 | from unittest import mock
from .. import *
from bfg9000.tools.ld import LdLinker
from bfg9000.path import abspath
from bfg9000.versioning import Version
def mock_execute(args, **kwargs):
return 'SEARCH_DIR("/dir1")\nSEARCH_DIR("=/dir2")\n'
class TestLdLinker(CrossPlatformTestCase):
def __init__(self, *arg... | arch_dirs_fail(self):
def mock_bad_execute(*args, **kwargs):
raise OSError()
with mock.patch('bfg9000.shell.execute', mock_bad_execute):
ld = LdLinker(None, self.env, ['ld'], 'version')
| self.assertEqual(ld.search_dirs(), [])
self.assertRaises(OSError, lambda: ld.search_dirs(strict=True))
|
hofschroeer/shinysdr | shinysdr/blocks.py | Python | gpl-3.0 | 15,994 | 0.005252 | # Copyright 2013, 2014 Kevin Reid <kpreid@switchb.org>
#
# This file is part of ShinySDR.
#
# ShinySDR 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) an... | int(factor)
# assert size % factor == 0
offset = size // factor
gr.hier_block2.__init__(
self, self.__class__.__name__,
gr.io_signature(1, 1, itemsize),
gr.io_signature(1, 1, itemsize),
)
if factor == 1:
# No duplication ... | self.connect(self, blocks.copy(itemsize), self)
else:
interleave = blocks.interleave(itemsize * size)
self.connect(
interleave,
blocks.vector_to_stream(itemsize, size),
self)
for i in xrange(0, factor):
... |
dbcls/dbcls-galaxy | scripts/scramble/scripts/psycopg2.py | Python | mit | 4,933 | 0.028583 | import os, sys, subprocess, tarfile, shutil
def unpack_prebuilt_postgres():
if not os.access( POSTGRES_BINARY_ARCHIVE, os.F_OK ):
print "unpack_prebuilt_postgres(): No binary archive of Postgres available for this platform - will build it now"
build_postgres()
else:
print "unpack_prebui... | ARCHIVE
t = tarfile.open( POSTGRES_ARC | HIVE, "r" )
for fn in t.getnames():
t.extract( fn )
t.close()
# configure
print "build_postgres(): Running postgres configure script"
p = subprocess.Popen( args = CONFIGURE, shell = True, cwd = os.path.join( os.getcwd(), "postgresql-%s" %POSTGRES_VERSION) )
r = p.wait()
if r != 0:
... |
iledarn/odoo-saas-tools | saas_portal_demo/controllers/main.py | Python | lgpl-3.0 | 1,196 | 0.002508 | # -*- coding: utf-8 -*-
import werkzeug
from openerp.addons.web import http
from openerp.addons.web.http import request
from openerp.addons.saas_portal.controllers.main import SaasPortal
def signup_redirect():
url = '/web/signup?'
redirect_url = '%s?%s' % (request.httprequest.base_url, werkzeug.urls.url_encod... | ion, plan_url, **post):
domain = [('odoo_version', '=', version), ('page_url', '=', plan_url),
('state', '=', 'confirmed')]
plan = request.env['saas_portal.plan'].sudo().search(domain)
if not plan:
# TODO: maybe in this case we can redirect to saas_portal_templates.... | return request.website.render("saas_portal_demo.unavailable_plan")
values = {'plan': plan[0]}
return request.website.render("saas_portal_demo.show_plan", values)
|
ict-felix/stack | vt_manager_kvm/src/python/scripts/setup_ch.py | Python | apache-2.0 | 3,204 | 0.003121 | '''
Created on Jul 19, 2010
@author: jnaous
'''
from django.core.urlresolvers import reverse
from django.test import Client
from common.tests.client import test_get_and_post_form
from django.contrib.auth.models import User
from pyquery import PyQuery as pq
from openflow.plugin.models import OpenFlowInterface, NonOpenF... | agg %s" % pl_agg["url"]
response = test_get_and_post_form(
client,
reverse("planetlab_aggregate_create"),
pl_agg,
)
print "got response %s" % response
assert response.status_code == 302
for of_agg in OF_AGGREGATE_INFO:
print "addin... | erse("openflow_aggregate_create"),
of_agg,
del_params=["verify_certs"],
)
assert response.status_code == 302
for cnxn_tuple in OF_PL_CONNECTIONS:
print "adding cnxn %s" % (cnxn_tuple,)
NonOpenFlowConnection.objects.get_or_create(
of_iface=... |
neilswainston/development-py | synbiochemdev/datascience/ch6.py | Python | mit | 1,896 | 0 | '''
synbiochem (c) University of Manchester 2016
synbiochem is licensed under the MIT License.
To view a copy of this license, visit <http://opensource.org/licenses/MIT/>.
@author: neilswainston
'''
# pylint: disable=invalid-name
import math
import random
import sys
import numpy
def cent_limit_theorem(tests, lng... | []
for _ in range(tests):
rand_dist = get_rand_dist(lngth, min_val, max_val)
mean_val = numpy.mean(rand_dist)
print str(mean_val) + '\t' + str(numpy.std(rand_dist))
means.append(mean_val)
print '\t'.join([str(numpy.mean(means)),
str(numpy.std(means)),
... | def get_rand_dist(lngth, min_val, max_val):
'''Returns random distribution.'''
return [random.randrange(min_val, max_val) for _ in range(lngth)]
def normal_cdf(x, mu=0, sigma=1):
'''Returns normal cumulative distribution function.'''
return (1 + math.erf((x - mu) / math.sqrt(2) / sigma)) / 2
def inv... |
basu96/crux-judge | src/server/contest/migrations/0003_profile.py | Python | mit | 849 | 0.002356 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-12-25 23:46
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_depende... | odes'),
]
operations = [
migrations.CreateModel(
name='Profile',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('logged_in', models.BooleanField(default=False)),
('user'... | ttings.AUTH_USER_MODEL)),
],
),
]
|
t3dev/odoo | addons/hr_expense_check/__manifest__.py | Python | gpl-3.0 | 421 | 0 | # -*- coding: utf-8 -*-
{
'name': "Check Printing in Expenses",
'summary': """Print amount in words | on checks issued for expenses""",
'category': 'Accounting',
'description': """
Print amount in words on checks issued for expenses
""",
'version': '1.0',
'depends': ['account_check_printing', 'hr_expense'],
'auto_install': True,
'dat | a': [
'views/payment.xml',
],
}
|
BiznetGIO/horizon | openstack_dashboard/utils/settings.py | Python | apache-2.0 | 14,525 | 0 | # 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
# d... | e configurations were imported.
For example, given this setup:
| foo/__init__.py
| foo/_10_baz.py
| foo/_20_qux.py
| bar/__init__.py
| bar/_30_baz_.py
and being called with ``modules=[foo, bar]``, we will first have the
configu | ration from ``_10_baz`` and ``_30_baz`` merged, then the
configurations will be applied in order ``qux``, ``baz`` (``baz`` is
second, because the most recent file which contributed to it, ``_30_baz``,
comes after ``_20_qux``).
Panel specific configurations are stored in horizon_config. Dashboards
f... |
Spoken-tutorial/spoken-website | events/migrations/0038_auto_20190531_0738.py | Python | gpl-3.0 | 98,329 | 0.003112 | # -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2019-05-31 07:38
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('events', '0037_auto_20190306... | migrations.AlterField(
| model_name='academiccenter',
name='district',
field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='events.District'),
),
migrations.AlterField(
model_name='academiccenter',
name='institute_category',
field=models.Foreign... |
chickonice/AutonomousFlight | simulation/simulation_ws/build/rotors_simulator/rotors_control/catkin_generated/pkg.installspace.context.pc.py | Python | gpl-3.0 | 777 | 0.005148 | # generated from catkin/cmake/template/pkg.context.pc.in
CATKIN_PACKAGE_PREFIX = ""
PROJECT_PKG_CONFIG_INCLUDE_DIRS = "/home/spacecat/AutonomousFlight/simulation/simulation_ws/install/include;/usr/include/eigen3".split(';') if "/home/spacecat/AutonomousFlight/simulation/simulation_ws/install/include;/usr/incl | ude/eigen3" != "" else []
PROJECT_CATKIN_DEPENDS = "geometry_msgs;mav_msgs;roscpp;sensor_msgs;glog_catkin".replac | e(';', ' ')
PKG_CONFIG_LIBRARIES_WITH_PREFIX = "-llee_position_controller;-lroll_pitch_yawrate_thrust_controller".split(';') if "-llee_position_controller;-lroll_pitch_yawrate_thrust_controller" != "" else []
PROJECT_NAME = "rotors_control"
PROJECT_SPACE_DIR = "/home/spacecat/AutonomousFlight/simulation/simulation_ws/i... |
ursky/metaWRAP | bin/metawrap-scripts/plot_binning_results.py | Python | mit | 7,420 | 0.019946 | #!/usr/bin/env python2.7
# USAGE:
# ./script file1.stats file2.stats file3.stats
import sys
import matplotlib.pyplot as plt
plt.switch_backend('agg')
max_contamination=int(sys.argv[2])
min_completion=int(sys.argv[1])
####################################################################################################... | a sets
for bin_set in data:
data[bin_set].sort(reverse=True)
print "Plotting completion data..."
# MAKING THE PLOT PRETTY!!!!
# set some color schemes
tableau20 = [(21 | 4, 39, 40), (31, 119, 180), (255, 127, 14),
(44, 160, 44), (255, 152, 150),
(148, 103, 189), (197, 176, 213), (140, 86, 75), (196, 156, 148),
(227, 119, 194), (247, 182, 210), (127, 127, 127), (199, 199, 199),
(188, 189, 34), (219, 219, 141), (23, 190,... |
burzillibus/RobHome | venv/lib/python2.7/site-packages/bs4/dammit.py | Python | mit | 29,930 | 0.01034 | # -*- coding: utf-8 -*-
"""Beautiful Soup bonus library: Unicode, Dammit
This library converts a bytestream to Unicode through any means
necessary. It is heavily based on code from Mark Pilgrim's Universal
Feed Parser. It works best on XML and HTML, but it does not rewrite the
XML or HTML to reflect a new encoding; th... | if make_quoted_attribute:
value = cls.quoted_attribute_value(value)
return value
@classmethod
def substitute_xml_containing_entities(
cls, value, make_quoted_attribute=False):
""" | Substitute XML entities for special XML characters.
:param value: A string to be substituted. The less-than sign will
become <, the greater-than sign will become >, and any
ampersands that are not part of an entity defition will
become &.
:param make_quoted_attr... |
taimur97/Feeder | server/appengine/endpoints/api_backend_service.py | Python | gpl-2.0 | 5,564 | 0.005931 | #!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | ter_spi(self, config_contents):
"""Register a single SPI and its config contents.
Args:
config_contents: String containing API configuration.
"""
if config_contents is None:
return
parsed_config = json.loads(config_contents)
self.__register_class(parsed_con | fig)
self.__api_configs.add(config_contents)
self.__register_methods(parsed_config)
def __register_class(self, parsed_config):
"""Register the class implementing this config, so we only add it once.
Args:
parsed_config: The JSON object with the API configuration being added.
Raises:
... |
sonaht/ansible | lib/ansible/modules/utilities/logic/set_fact.py | Python | gpl-3.0 | 2,883 | 0.002775 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright 2013 Dag Wieers <dag@wieers.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the Lice... | ing the key=value syntax, however it is still
# recommended that booleans be set | using the complex argument style:
- set_fact:
one_fact: true
other_fact: false
'''
|
boto/s3transfer | s3transfer/constants.py | Python | apache-2.0 | 910 | 0 | # Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the A | pache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying | this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
import s3transfer
KB = 1024
MB = KB * KB
GB = MB * KB
ALLOWED_DOWNLOAD_ARGS = [
... |
luiscberrocal/homeworkpal | homeworkpal_project/maximo/migrations/0007_auto_20151117_1038.py | Python | mit | 506 | 0.001976 | # -*- coding | : utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import django.core.validators
class Migration(migrations.Migration):
dependencies = [
('maximo', '0006_auto_20151111_2021'),
]
operations = [
migrations.AlterField(
model_name='maxim... | x_length=7),
),
]
|
janeen666/mi-instrument | mi/instrument/wetlabs/fluorometer/flord_d/test/__init__.py | Python | bsd-2-clause | 22 | 0 | __auth | or__ = 'tgu | pta'
|
JenSte/libsigrokdecode | decoders/jtag_stm32/__init__.py | Python | gpl-3.0 | 1,163 | 0.012898 | ##
## This file is part of the libsigrokdecode project.
##
## Copyright (C) 2012 Uwe Hermann <uwe@hermann-uwe.de>
##
## 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 Li... | GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program; if not, write to th | e Free Software
## Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
##
'''
This decoder stacks on top of the 'jtag' PD and decodes JTAG data specific to
the STM32 microcontroller series.
Details:
https://en.wikipedia.org/wiki/STM32
http://www.st.com/internet/com/TECHNICAL_RESOURCES/TECHNICAL_... |
selurvedu/openprocurement.api | src/openprocurement/api/views/award_complaint.py | Python | apache-2.0 | 6,347 | 0.002521 | # -*- coding: utf-8 -*-
from logging import getLogger
from cornice.resource import resource, view
from openprocurement.api.models import Complaint, STAND_STILL_TIME, get_now
from openprocurement.api.utils import (
apply_patch,
save_tender,
add_next_award,
error_handler,
update_journal_handler_params... | us = 403
return
apply_patch(self.request, save=False, src=complaint.serialize())
if complaint.status == 'cancelled':
self.request.errors.add('body', 'data', 'Can\'t cancel complaint')
self.request.errors.status = 403
return
if complaint.status == '... | if tender.status == 'active.awarded':
tender.status = 'active.qualification'
tender.awardPeriod.endDate = None
if award.status == 'unsuccessful':
for i in tender.awards[tender.awards.index(award):]:
i.complaintPeriod.endDate = get_now... |
total-impact/impactstory-analytics | impactstoryanalytics/widgets/hourly_new_users.py | Python | mit | 903 | 0.003322 | from collections import defaultdict
import iso8601
import arrow
| import logging
from impactstoryanalytics.widgets.widget import Widget, get_raw_dataclip_data
logger = logging.getLogger("impactstoryanalytics.widgets.hourly_new_users")
class Hourly_new_users(Widget):
new_accounts_query_url = "https://dataclips.heroku.com/hefcjkzcteluxosfhdvsofefjrjr.json"
def get_data(sel... | of_datapoints]
pans = Widget.get_time_pan_list(number_of_datapoints, interval="hour")
for datapoint in datapoints:
(iso_time, new_accounts, total_accounts) = datapoint
time = arrow.get(str(iso_time), 'YYYY-MM-DDTHH:mm:ss')
pans.add_to_pan(time, "new_accounts", int(ne... |
MathYourLife/TSatPy-thesis | sandbox/dns_string_io.py | Python | mit | 10,430 | 0.005561 |
import struct
OK, EFORMAT, ESERVER, ENAME, ENOTIMP, EREFUSED = range(6)
IXFR, AXFR, MAILB, MAILA, ALL_RECORDS = range(251, 256)
IN, CS, CH, HS = range(1, 5)
from io import BytesIO
class Message:
"""
L{Message} contains all the information represented by a single
DNS request or response.
@ivar id: Se... | self.maxSize = 0
header = readPrecisely(strio, self.headerSize)
r = struct.unpack(self.headerFmt, header)
self.id, byte3, byte4, nqueries, nans, nns, nadd = r
self.answer = ( byte3 >> 7 ) & 1
self.opCode = ( byte3 >> 3 ) & 0xf
self.auth = ( byte3 >> 2 ) & 1
self.t... | & 1
self.recDes = byte3 & 1
self.recAv = ( byte4 >> 7 ) & 1
self.authenticData = ( byte4 >> 5 ) & 1
self.checkingDisabled = ( byte4 >> 4 ) & 1
self.rCode = byte4 & 0xf
self.queries = []
for i in range(nqueries):
self.name.decode(strio)
b... |
thozza/energy-track | energytrack/gui/gui_helper.py | Python | gpl-3.0 | 6,070 | 0.002142 | #!/usr/bin/env python
#
# -*- coding: utf-8 -*-
#
# gui_helper.py -
# Copyright 2013 Tomas Hozza <thozza@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 version 3 of the Lic... | Gtk.DialogFlags.DESTROY_WITH_PARENT,
| Gtk.MessageType.ERROR,
buttons,
message)
if sec_message is not None:
dlg.format_secondary_text(sec_message)
return dlg
@staticmethod
def show_msg_dialog(type=DIALOG_TYPE_INFO,
... |
gcsadovy/generalPY | manageParcels.py | Python | gpl-3.0 | 217 | 0.009217 | # manageParcels.py
import parcelClass
myParcel = parcelClass.parce | l(145000, "residential")
print "Value:", myParcel.value
print "Zoning:", myParcel.zoning
mytax = myParcel | .calculateTax()
print "Tax:", mytax |
llimllib/champsleagueviz | europa/stats.py | Python | mit | 1,359 | 0.002943 | import glob, csv, re, shutil, mustache, time
import numpy as np
oddsfile = list(sorted(glob.glob('raw/odds*.csv')))[-1]
timestamp = re.search('s(.*?)\.', oddsfile).group(1)
with open(oddsfile) as infile:
reader = csv.reader(infile)
header = reader.next()
teams = [row for row in reader]
fixed = []
for team... |
odds = team[2:]
try:
max_ = max(odds)
except ValueError:
#nobody is offering odds on this team, they're elimin | ated, skip them
continue
min_ = min(odds)
mean = np.mean(odds)
median = np.median(odds)
summary.append(team[:2] + [max_, min_, mean, median])
summaryfile = "raw/summary%s.csv" % timestamp
with file(summaryfile, 'w') as outfile:
w = csv.writer(outfile)
w.writerow(['name', 'group', 'max',... |
lmcro/webserver | admin/CTK/CTK/Plugin.py | Python | gpl-2.0 | 7,366 | 0.008824 | # CTK: Cherokee Toolkit
#
# Authors:
# Alvaro Lopez Ortega <alvaro@alobbs.com>
#
# Copyright (C) 2010-2014 Alvaro Lopez Ortega
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of version 2 of the GNU General Public
# License as published by the Free Software Foundation.... | help_grp = HelpGroup (name)
for entry in module.HELPS:
help_grp += HelpEntry (entry[1], entry[0])
global_help += help_grp
return [global_help]
def Render (self):
# Load the plugin
render = self.plugin.Render()
... | Javascript
render.js += SELECTOR_CHANGED_JS %({
'id': self.selector_widget.id,
'url': self._url,
'plugin_id': self.plugin.id,
'key': self._key})
# Helps
render.helps = self._get_helps()
return render
# ... |
ksrajkumar/openerp-6.1 | win32/setup.py | Python | agpl-3.0 | 1,676 | 0.008353 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the... | "_imagingtk","PIL._imagingtk",
"ImageTk", "PIL.ImageTk",
"FixTk"],
"skip_archive": 1,
| "optimize": 2,}},
data_files=datas(),
)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
drpngx/tensorflow | tensorflow/contrib/mixed_precision/python/loss_scale_manager_test.py | Python | apache-2.0 | 6,362 | 0.005816 | # 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... | an_or_inf=2):
ratio = 2
lsm = lsm_lib.ExponentialUpdateLossScaleManager(
init_loss_scale=init_loss_scale,
incr_every_n_steps=incr_every_n_step,
decr_every_n_nan_or_inf=decr_every_n_nan_or_inf,
incr_ratio=ratio,
decr_ratio=1. / ratio)
itr = _GetExampleIter(inputs)
... | lsm.update_loss_scale(itr.get_next())
self.evaluate(variables.global_variables_initializer())
actual_outputs = []
if not context.executing_eagerly():
update_op = update_fn()
for _ in range(len(inputs)):
if context.executing_eagerly():
update_fn()
else:
self.evaluate(... |
GNOME/gnome-code-assistance | backends/json/mkdeps.py | Python | lgpl-3.0 | 859 | 0.003492 | #!/usr/bin/env python
import subprocess, os, re
perdir = {}
ret = subprocess.check_output(['git', 'ls-files', '--', 'deps']).decode('utf-8').splitlines()
seen = {}
for r in ret:
if r in seen:
continue
seen[r] = True
dname = os.path.dirname(r)
if dname in perdir:
perdir[dname].appe... | n/".join(perdir[dname])))
print('')
datas.append('$({0}_D | ATA)'.format(vname))
print('endif\n')
print('EXTRA_DIST += \\\n\t{0}'.format(' \\\n\t'.join(datas)))
# vi:ts=4:et
|
biocore/qiita | qiita_pet/handlers/study_handlers/sample_template.py | Python | bsd-3-clause | 19,340 | 0 | # -----------------------------------------------------------------------------
# Copyright (c) 2014--, The Qiita Development Team.
#
# Distributed under the terms of the BSD 3-clause License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... | )
return {'job': job.id}
elif req_op == 'replace':
# WARNING: Although the patch operation is a replace, is not a full
# true replace. A replace is in theory equivalent to a remove + add.
# In this case, the repl | ace operation doesn't necessarily removes
# anything (e.g. when only new columns/samples are being added to the)
# sample information.
# Path format: study_id/data
# Forcing to specify data for extensibility. In the future we may want
# to use this function to replace other eleme... |
Distrotech/bzr | bzrlib/send.py | Python | gpl-2.0 | 8,490 | 0.001296 | # Copyright (C) 2009, 2010 Canonical Ltd
#
# 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 distribut... | ranch known or'
' specified'))
if remembered_target_branch is not None:
trace.note(gettext('Using saved {0} location "{1}" to determine '
'what changes to submit.').format(
remembered_target_branch,
... | ranch,
possible_transports=possible_transports)
possible_transports.append(submit_branch.bzrdir.root_transport)
if mail_to is None or format is None:
if mail_to is None:
mail_to = submit_branch.get_config_stack().get(
'child_submit_to')
... |
ZachOhara/Project-Euler | python/p061_p070/problem062.py | Python | gpl-3.0 | 688 | 0.050872 | import itertools
def main():
#print(permutations(41063625))
| #print([isCube(i) for i in [41063625, 56623104, 66430125]])
#print(hasCubicPermutations(41063625, 3))
i = 1
while not hasCubicPermutations(i ** 3, 5):
i += 1
print(i)
print(i, i ** 3)
def hasCubicPermutations(n, p):
cubesCount = 0
for i in set(permutations(n)):
if isCube(i):
cubesCount += 1
#print(i... | isCube(n):
root = int(round(n ** (1 / 3)))
return root ** 3 == n
def permutations(n):
return [int("".join(i)) for i in itertools.permutations(str(n))]
if __name__ == "__main__":
main()
|
GraphProcessor/CommunityDetectionCodes | Prensentation/metrics/util.py | Python | gpl-2.0 | 504 | 0.003968 | import networkx as nx
import re
def get_grap | h_info(file_path):
def extract_first_two(collection):
return [int(collection[0]), int(collection[1])]
with open(file_path) as ifs:
lines = map(lambda ele: ele.strip(), ifs.readlines())
lines = filter(lambda ele: not ele.startswith('#') and re.match('.*[0-9]+.*[0-9]+', ele), lines)
... | return nx.Graph(pair_list)
|
jnerin/ansible | lib/ansible/inventory/manager.py | Python | gpl-3.0 | 23,570 | 0.001782 | # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible 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) an... | tory.hosts
def get_vars(self, *args, **kwargs):
return self._inventory.get_vars(args, kwargs)
def add_host(self, host, group=None, port=None):
return self._inventory.add_host(host, group, port)
def add_group(self, group):
return self._inventory.add_group(group)
def get_groups... | _inventory.get_groups_dict()
def reconcile_inventory(self):
self.clear_caches()
return self._inventory.reconcile_inventory()
def get_host(self, hostname):
return self._inventory.get_host(hostname)
def _setup_inventory_plugins(self):
''' sets up loaded inventory plugins for... |
Azure/azure-sdk-for-python | sdk/commerce/azure-mgmt-commerce/azure/mgmt/commerce/aio/_usage_management_client.py | Python | mit | 2,922 | 0.002396 | # 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 ... | # pylint: disable=unused-import,ungrouped-imports
from azure.core.credentials_async import AsyncTokenCredential
from ._configuration import UsageManagementClientConfiguration
from .operations import UsageAggregatesOperations
from .operations import RateCardOper | ations
from .. import models
class UsageManagementClient(object):
"""UsageManagementClient.
:ivar usage_aggregates: UsageAggregatesOperations operations
:vartype usage_aggregates: azure.mgmt.commerce.aio.operations.UsageAggregatesOperations
:ivar rate_card: RateCardOperations operations
:vartype ... |
pkyad/libreERP-old | Employee/models.py | Python | gpl-2.0 | 8,557 | 0.052121 | from django.db import models
from django import forms
from django.contrib.auth.models import User
from time import time
# Create your models here.
def getSignaturesPath(instance , filename):
return 'images/Sign/%s_%s_%s' % (str(time()).replace('.', '_'), instance.user.username, filename)
def getDisplayPicturePath(... | IDPhoto = models.ImageField(upload_to = getDisplayPicturePath , null = True)
TNCandBond = models.FileField(upload_to = getTNCandBondPath , null = True)
resume = models.FileField(upload_to = getResumePath , null = True)
certificates = models.FileField(upload_to = getCertificatesPath , | null = True)
transcripts = models.FileField(upload_to = getTranscriptsPath , null = True)
otherDocs = models.FileField(upload_to = getOtherDocsPath , null = True , blank = True)
almaMater = models.CharField(max_length = 100 , null = True)
pgUniversity = models.CharField(max_length = 100 , null = True... |
rakeshmi/cinder | cinder/tests/unit/api/v2/test_types.py | Python | apache-2.0 | 8,430 | 0 | # Copyright 2011 OpenStack Foundation
# aLL Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requ... | ault_not_found(self):
self.stubs.Set(volume_types, 'get_default_volume_type',
return_volume_types_get_default_not_found)
req = fakes.HTTPRequest.blank('/v2/fake/types/default')
req.method = 'GET'
self.assertRaises(webob.exc.HTTPNotFound,
... | views_types.ViewBuilder()
now = timeutils.isotime()
raw_volume_type = dict(
name='new_type',
description='new_type_desc',
deleted=False,
created_at=now,
updated_at=now,
extra_specs={},
deleted_at=None,
id=42... |
N402/NoahsArk | ark/goal/models.py | Python | mit | 6,393 | 0.003285 | from datetime import datetime
from flask.ext.babel import lazy_gettext as _
from sqlalchemy import func, select
from sqlalchemy.ext.hybrid import hybrid_property
from ark import settings
from ark.exts import db, cache
from ark.ranking.models import GoalRankingBan
class Goal(db.Model):
__tablename__ = 'goal'
... | terval.expression
def last_activity_interval(cls):
return (select([func.datediff(func | .now(), GoalActivity.created)])
.where(GoalActivity.goal_id==cls.id)
.order_by(GoalActivity.created.desc())
.limit(1).label('last_activity_interval'))
@hybrid_property
def like_count(self):
return self.likes.filter(GoalLikeLog.is_deleted==False).count()
... |
clarson469/reinforcementLearning | solutions/solution_util.py | Python | mit | 819 | 0.006105 | import numpy as np
def e_greedy(estimates, epsilon):
numBandits, numArms = estimates.shape
explore = np.zeros(numBandits)
explore[np.random.rand | om(numBandits) <= epsilon] = 1
arm = np.argmax(estimates, axis=1)
arm[explore == 1] = np.random.randint(0, numArms, np.count_nonzero(explore))
return arm
def softmax(estimates, temperature):
temp_est = estimates.T / temperature
exponents = np.exp(temp_est - np.max(temp_est))
dist = exponents /... | (np.random.random(temp_est.shape) < dist.cumsum(axis=0)).argmax(axis=0)
def pref_softmax(preferences):
pref = preferences.T
exponents = np.exp(pref - np.max(pref))
dist = exponents / np.sum(exponents, axis=0)
return (np.random.random(pref.shape) < dist.cumsum(axis=0)).argmax(axis=0)
|
vicnet/weboob | weboob/applications/qbooblyrics/main_window.py | Python | lgpl-3.0 | 11,785 | 0.002376 | # -*- coding: utf-8 -*-
# Copyright(C) 2016 Julien Veyssier
#
# This file is part of weboob.
#
# weboob is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your op... | returnPressed.connect(self.searchId)
| count = self.config.get('settings', 'maxresultsnumber')
self.ui.countSpin.setValue(int(count))
showT = self.config.get('settings', 'showthumbnails')
self.ui.showTCheck.setChecked(showT == '1')
self.ui.stopButton.hide()
self.ui.actionBackends.triggered.co |
barbour-em/osf.io | website/profile/views.py | Python | apache-2.0 | 22,557 | 0.001286 | # -*- coding: utf-8 -*-
import logging
import operator
import httplib
import httplib as http
import os
from dateutil.parser import parse as parse_date
from flask import request
from modularodm.exceptions import ValidationError, NoResultsFound
from modularodm import Q
from framework import sentry
from framework.auth... | ser.timezone = data['timezone']
user.save()
return _profile_view(user)
def _profile_view(profile, is_profile=False):
# TODO: Fix circular import
from website.addons.badges.util import get_sorted_user_badges
if profile and profile.is_disabled:
raise HTTPError(http.GONE)
if 'badges' ... | d, 'assertions' and 'badges' can be
# empty lists.
badge_assertions = []
badges = []
if profile:
profile_user_data = profile_utils.serialize_user(profile, full=True)
return {
'profile': profile_user_data,
'assertions': badge_assertions,
'b... |
LAL/SLAM | src/slam/interface.py | Python | apache-2.0 | 32,758 | 0.004152 | """Helper to execute actions on the database independantly from the interface
and output format."""
import logging, datetime, sys, re
from slam import generator, models
from slam.log import DbLogHandler
# set-up logging to the database
LOGGER = logging.getLogger(__name__)
LOGGER.setLevel(logging.INFO)
DBLOGHANDLER =... | t_pool(pool)
pool.generator.add(genobj)
genobj.save()
return genobj
def get_generator(name):
"""Get the correct configuration generator object."""
genobj = None
if name:
if not models.Config.objects.filter(name=name):
raise InexistantObjectError("Could not find ge... | get(name=name)
if confobj.conftype == "bind":
genobj = generator.BindConfig.objects.get(name=name)
elif confobj.conftype == "rbind":
genobj = generator.RevBindConfig.objects.get(name=name)
elif confobj.conftype == "dhcp":
genobj = generator.DhcpdConfig.objects... |
OhmNomNom/Michelangelo | TempLogger/prog.py | Python | gpl-3.0 | 534 | 0.013109 | import serial,time
ser = serial.Serial( | 2, baudrate=9600)
print(ser.name)
file = open("Output.txt","w")
ser.write(b"M04\n")
ser.flush() |
ser.readline().decode();
t = time.clock()
while t <= 180:
ser.write(b"M105\n")
ser.flush()
resp = ser.readline().decode();
t = time.clock()
resp = resp[resp.find('T')+1:].split()[0]
print(str(t) + " " + resp)
file.write(str(t) + " " + resp + "\n")
file.flush()
time.sle... |
edespino/gpdb | src/test/tinc/tincrepo/mpp/gpdb/tests/storage/walrepl/oom/__init__.py | Python | apache-2.0 | 4,065 | 0.003936 | """
Copyright (c) 2004-Present Pivotal Software, Inc.
This program and the accompanying materials are made available under
the terms of the 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.... | he License.
"""
import os
import subprocess
import socket
from time import sleep
import tinctest
from tinctest.lib import local_path
from gppylib.commands.base import Command
from mpp.lib.config import GPDBConfig
from mpp.lib.PSQL import PSQL
from mpp.gpdb.tests.storage.walrepl.lib.pg_util import GpUtility
from mpp.gp... | mpp.gpdb.tests.storage.walrepl.lib.verify import StandbyVerify
from mpp.gpdb.tests.storage.walrepl.lib.standby import Standby
config = GPDBConfig()
class OOMClass(object):
'''Class for methods required for OOM testcase'''
standby_port = '5433'
standby_dirname = 'newstandby'
def __init__(self):
... |
lyubomir1993/AlohaServer | api/migrations/0002_auto_20170328_1936.py | Python | apache-2.0 | 448 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.12 on 2017-03-28 19:36
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('api', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_n... | el(
name | ='Profile',
),
]
|
fnl/libfnl | src/fnl/text/test/test_extract.py | Python | agpl-3.0 | 7,798 | 0.000513 | from html.parser import HTMLParseError
from unittest import main, TestCase
from fnl.text.extract import HtmlExtractor, GREEK_LOWER, GREEK_UPPER
class ExtractHtmlTests(TestCase):
def setUp(self):
self.ex = HtmlExtractor()
def testBasicExtraction(self):
self.ex.namespace = 'test'
self.e... | elf.ex.feed("&#x{:x};".format(ord("a")))
self.ex.close()
self.assertEqual('a', self.ex.string)
self.ex.reset()
self.ex.feed("&#x{:x};".format(ord("Z")).upper())
self.ex.close()
self.assertEqual('Z', self.ex.string)
| self.ex.reset()
self.ex.feed("�")
self.ex.close()
self.assertEqual(HtmlExtractor.REPLACEMENT, self.ex.string)
def testIgnoredTags(self):
self.ex.feed("<script key=value />")
self.ex.close()
self.assertEqual('', self.ex.string)
self.assertEqual({}, se... |
coolralf/KaggleTraining | HELP.py | Python | mit | 18 | 0.055556 | print("hello!!!!" | ) | |
mayukh18/BlindChat | modules/gifs.py | Python | mit | 646 | 0.012384 | _male_start_hi = ['https://media.giphy.co | m/media/dzaUX7CAG0Ihi/giphy-downsized.gif',
'https://media.giphy.com/media/oJiCqvIqPZE3u/giphy.gif']
_female_start_hi = ['https://media.giphy.com/media/a1QLZUUtCcgyA/giphy-downsized.gif',
'https://media.giphy.com/media/EPJZhOrStSpz2/giphy-downsized.gif']
import random
def get_sta... | elif gender == "female":
#return random.choice(_female_start_hi)
return _female_start_hi[1]
else:
return random.choice(_male_start_hi) |
davande/hackernews-top | graphing.py | Python | apache-2.0 | 2,759 | 0.001812 | '''
Graphing
Author: Rylan Santinon
'''
import pygal
from csv_io import CsvIo
from urlparse import urlparse
import os
class Graphing(object):
'''Graphs and diagrams based on retrieved data'''
def __init__(self, directory):
self.directory = directory
self.csvio = CsvIo()
self.make_direc... | createds = []
c = 0
| for u in user_list:
c = c + 1
if int(u[1]) > 250 and int(u[1]) < 110000:
if c % 15 != 0:
continue
karmas.append(int(u[1]))
createds.append(int(u[2])/FACTOR)
xychart = pygal.XY(stroke=False, x_title='Created time ... |
labordoc/labordoc-next | modules/bibformat/lib/bibformat_utils_unit_tests.py | Python | gpl-2.0 | 6,733 | 0.008911 | # -*- coding: utf-8 -*-
##
## This file is part of Invenio.
## Copyright (C) 2010, 2011, 2013 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 yo... | term snippet cut out core creation"""
self.assertEqual(('This', 0, 0), cut_out_snippet_core_crea | tion(['This', 'is', 'a', 'test'], ['This'], 50))
self.assertEqual(('This is a test', 0, 3), cut_out_snippet_core_creation(['This', 'is', 'a', 'test'], ['This' ,'test'], 50))
self.assertEqual(('is', 1, 1), cut_out_snippet_core_creation(['This', 'is', 'a', 'test'], ['is'], 50))
self.assertEqual(('... |
zl352773277/django-sae | django_sae/contrib/tasks/tests/views.py | Python | apache-2.0 | 276 | 0.003623 | # coding=ut | f-8
from django_sae.contrib.tasks.cron import OperationView
from django_sae.contrib.tasks.operations import TaskOperationMixin
class OperationViewMock(OperationView):
| def get_operation(self, request):
return [TaskOperationMixin() for _ in range(0, 3)] |
odoousers2014/odoo-addons-supplier_price | stock_scrap_resupply/stock_scrap_resupply.py | Python | agpl-3.0 | 1,818 | 0.003302 | # -*- coding: utf8 -*-
#
# Copyright (C) 2015 NDP Systèmes (<http://www.ndp-sy | stemes.fr>).
#
# 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 version.
#
# This program is distributed in ... | 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/>.
#
from openerp import fields, models, api
class StockMove(models.Model):
_inherit = 'stock.mo... |
supermurat/hamsi-manager | SpecialTools/__init__.py | Python | gpl-3.0 | 16,028 | 0.002808 | # This file is part of HamsiManager.
#
# Copyright (c) 2010 - 2015 Murat Demir <mopened@gmail.com>
#
# Hamsi Manager 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 yo... | mationSection.currentIndex() == 0:
self.cbInformationSectionX.setEnabled(False)
else:
self.cbInformationSectionX.setEnabled(True)
if self.cbInformationSection.currentIndex() > 4:
self.cbInformationSectionY.setEnabled(True)
else:
self.cbInformationS... | ndReplace.columns.clear()
self.fill.columns.clear()
self.clear.columns.clear()
self.characterState.columns.clear()
self.characterEncoding.columns.clear()
try:
for btn in self.specialActions.pbtnAddObjects:
btn.setVisible(False)
btn.dele... |
tectronics/chimerascan | chimerascan/deprecated/nominate_spanning_reads_v04.py | Python | gpl-3.0 | 12,171 | 0.004519 | '''
Created on Jan 30, 2011
@author: mkiyer
chimerascan: chimeric transcript discovery using RNA-seq
Copyright (C) 2011 Matthew Iyer
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 ... | )
for c in Chimera.parse(open(chimera_file)):
# find breakpoint coords of chimera
end5p = c.tx_end_5p
start3p = c.tx_start_3p
for r5p,r3p in c.encomp_frags:
# if 5' read overlaps breakpoint then it should be remapped
if r5p.clipstart < end5p < r5p.... | key5p not in remap_qnames:
remap_qnames.add((r5p.qname, r5p.readnum))
print >>fqfh, to_fastq(r5p.qname, r5p.readnum,
r5p.seq, "I" * len(r5p.seq),
is_reverse=r5p.is_reverse)
# if 3' ... |
titusjan/argos | argos/qt/treeitems.py | Python | gpl-3.0 | 11,395 | 0.004563 | import logging
from argos.external import six
from argos.utils.cls import check_class, check_is_a_string
logger = logging.getLogger(__name__)
class BaseTreeItem(object):
""" Base class for storing item data in a tree form. Each tree item represents a row
in the BaseTreeModel (QAbstractItemModel).
... | _init__(self, nodeName):
""" Constructor
:param nodeName: short name describing this node. Is used to construct the nodePath.
Currently we don't check for | uniqueness in the children but this may change.
The nodeName may not contain slashes (/).
"""
check_class(nodeName, six.string_types, allow_none=False)
assert nodeName, "nodeName may not be empty"
assert '/' not in nodeName, "nodeName may not contain slashes"
sel... |
OpenNetworkingFoundation/ONFOpenTransport | RI/flask_server/tapi_server/models/tapi_photonic_media_application_identifier.py | Python | apache-2.0 | 3,599 | 0.001945 | # coding: utf-8
from __future__ import absolute_import
from datetime import date, datetime # noqa: F401
from typing import List, Dict # noqa: F401
from tapi_server.models.base_model_ import Model
from tapi_server.models.tapi_photonic_media_application_identifier_type import TapiPhotonicMediaApplicationIdentifierTy... | application_code of this Ta | piPhotonicMediaApplicationIdentifier.
none # noqa: E501
:param application_code: The application_code of this TapiPhotonicMediaApplicationIdentifier.
:type application_code: str
"""
self._application_code = application_code
|
wkschwartz/django | tests/i18n/contenttypes/tests.py | Python | bsd-3-clause | 752 | 0.001333 | import os
from django.contrib.contenttypes.models import ContentType
from django.test import TestCase, override_settings
from django.utils import translation
@override_settings(
USE_I18N=True,
LOCALE_PATHS=[
os.path.join(os.path.dirname(__file__), 'locale'),
],
LANGUAGE_CODE='en',
LANGUAG... | h translation.override('fr'):
| self.assertEqual(str(company_type), 'i18n | Société')
|
dkoudlo/py-manage-server | modules/file/replace.py | Python | apache-2.0 | 1,593 | 0.00565 | import modules.options_helper as opt_helper
from modules.file.file_helper import File
import sys
def main(options):
# available config keys
options_registry = ["path","find","replace_with"]
# verify config option provided match registry
opt_helper.check_opt | ions(options, options_ | registry)
path = options.get("path", False)
find = options.get("find", False)
replace_with = options.get("replace_with", False)
# see if all required fields are present
if path and find and replace_with:
f = File(path)
is_find_in_file = f.is_in_file(find)
filetype... |
coblo/isccbench | iscc_bench/readers/harvard.py | Python | bsd-2-clause | 2,886 | 0.001386 | # -*- coding: utf-8 -*-
"""Read data from 'Harvard Library Open Metadata'.
Records: ~12 Million
Size: 12.8 GigaByte (Unpacked)
Info: http://library.harvard.edu/open-metadata
Data: https://s3.amazonaws.com/hlom/harvard.tar.gz
Instructions:
Download datafile and run `tar xvf harvard.tar.gz` to extract marc21 files.... | ile_reader(marc21_file_path):
yield meta_record
def marc21_file_reader(file_path):
"""Return a generator that yields parsed MetaData records from a harvard marc21 file.
:param str file_path: path to harvard marc21 file
:return: Generator[:class:`MetaData`]
"""
with open(file_path, "r... | (mf, utf8_handling="ignore")
while True:
try:
record = next(reader)
yield MetaData(record.isbn(), record.title(), record.author())
except UnicodeDecodeError as e:
log.error(e)
continue
except StopIteration:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.