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 |
|---|---|---|---|---|---|---|---|---|
SKIRT/PTS | core/config/plot_simulation_seds.py | Python | agpl-3.0 | 1,942 | 0.004637 | #!/usr/bin/env python
# -*- coding: utf8 -*-
# *****************************************************************
# ** PTS -- Python Toolkit for working with SKIRT **
# ** © Astronomical Observatory, Ghent University **
# *****************************************************************
# ... | ference SEDs")
# Ignore the | se filters
definition.add_optional("ignore_filters", "filter_list", "ignore these filters from the observed SEDs")
# -----------------------------------------------------------------
|
fupenglin/PyDHT | dht_bencode.py | Python | gpl-2.0 | 2,915 | 0 | # -*- coding:utf-8 -*-
def decode(data):
try:
value, idx = __decode(data, 0)
retval = (True, value)
except Exception as e:
retval = (False, e.message)
finally:
return retval
def encode(data):
try:
value = __encode(data)
retval = (True, value)
excep... | lse:
raise ValueError('__decode: not in i, l, d')
return value, start_idx
# 解析整数
def __decode_int(data, start_idx):
end_idx = data.inde | x('e', start_idx)
try:
value = int(data[start_idx: end_idx])
except Exception:
raise Exception('__decode_int: error')
return value, end_idx + 1
# 解析字符串
def __decode_str(data, start_idx):
try:
end_idx = data.index(':', start_idx)
str_len = int(data[start_idx: end_idx])
... |
dx9/python-agent | cattle/plugins/host_info/os_c.py | Python | apache-2.0 | 1,411 | 0 | import platform
class OSCollector(object):
def __init__(self, docker_client=None):
self.docker_client = docker_client
def key_name(self):
return "osInfo"
def _zip_fields_values(self, keys, values):
data = {}
for key, value in zip(keys, values):
if len(value) >... | 'dockerVersion'] = version
return data
def _get_os(self):
data = {}
if platform.system() == 'Linux':
info = platform.linux_distribution()
keys = ["distribution", "version", "versionDescription"]
data = self._zip_fields_values(keys, | info)
data['kernelVersion'] = \
platform.release() if len(platform.release()) > 0 else None
return data
def get_data(self):
data = self._get_os()
data.update(self._get_docker_version())
return data
|
libreosteo/Libreosteo | Libreosteo/settings/base.py | Python | gpl-3.0 | 9,670 | 0.000827 | # This file is part of LibreOsteo.
#
# LibreOsteo 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.
#
# LibreOsteo is distributed ... | LDER = SITE_ROOT
if (getattr(sys, 'frozen', False) == 'macosx_app'):
DATA_FOLDER = os.path.join(
os.path.join(os.path.join(os.environ['HOME'], 'Library'),
'Application Support'), 'Libreosteo')
SITE_ROOT = os.path.join(os.path.split(SITE_ROOT)[0], 'Resources'... | os.makedirs(DATA_FOLDER)
else:
SITE_ROOT = BASE_DIR
DATA_FOLDER = os.path.join(SITE_ROOT, "data")
if not os.path.exists(DATA_FOLDER):
os.makedirs(DATA_FOLDER)
from django.utils.translation import ugettext_lazy as _
# Quick-start development settings - unsuitable for production
# See ... |
LeoYReyes/GoogleSearchAutomator | Crawler.py | Python | bsd-3-clause | 789 | 0.011407 | import google
im | port re
from bs4 import BeautifulSoup
def findContactPage(url):
html = google.get_page(url)
soup = BeautifulSoup(html)
contactStr = soup.find_all('a', href=re.compile(".*?contact", re.IGNORECASE))
return contactStr
if __name__ == "__main__":
url = "http://www.wrangler.com/"
contactStr = find... | ("href"))
print contactStr[0].get("href")#.find_parents("a")
soup = BeautifulSoup(contactPage)
emailStr = soup.find_all(text=re.compile("[\w\.-]+@[\w\.-]+"))
if(len(emailStr) > 0) :
print addressStr
else:
print "could not find email"
else:
prin... |
Ashaba/jash | projectash/urls.py | Python | bsd-2-clause | 1,803 | 0.000555 | """projectash URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: | url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns | : url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url, include
from django.contrib import admin
from ash import view... |
Azure/azure-sdk-for-python | sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/aio/_operations/_operations.py | Python | mit | 10,950 | 0.004384 | # 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 ... | mation.
:paramtype answer_context: ~azure.ai.language.questionanswering.models.KnowledgeBaseAnswerContext
:keyword ranker_kind: Type of ranker to be used. Possible
values include: "Default", "QuestionOnly".
:paramtype ranker_kind: str
:keyword filters: Filter QnAs based on given... | :paramtype filters: ~azure.ai.language.questionanswering.models.QueryFilters
:keyword short_answer_options: To configure Answer span prediction feature.
:paramtype short_answer_options: ~azure.ai.language.questionanswering.models.ShortAnswerOptions
:keyword include_unstructured_sources: ... |
ReproducibleBuilds/diffoscope | diffoscope/comparators/utils/container.py | Python | gpl-3.0 | 7,045 | 0.001136 | # -*- coding: utf-8 -*-
#
# diffoscope: in-depth comparison of files, archives, and directories
#
# Copyright © 2016 Chris Lamb <lamby@debian.org>
#
# diffoscope 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,... | n new
return super(Container, cls).__new__(cls)
def __init__(self, source):
self._source = source
# Keep a count of how "nested" we are
self.depth = 0
if hasattr(source, 'container') and source.container is not None:
self.depth = source.container.depth + | 1
@property
def source(self):
return self._source
@abc.abstractmethod
def get_member_names(self):
raise NotImplementedError()
@abc.abstractmethod
def get_member(self, member_name):
raise NotImplementedError()
def get_path_name(self, dest_dir):
return os.pa... |
beeva-albertorincon/beeva-poc-google-ocr-faces | code/demo.py | Python | apache-2.0 | 2,248 | 0.018238 | # encoding:utf8
import numpy as np
import cv2
import base64
import beesion
import time
import logging
logging.basicConfig(format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s',
datefmt='%H:%M:%S',
level=logging.DEBUG)
frame_processing_ratio = 4
fram... | ONT_HERSH | EY_SIMPLEX, 2, (255,0,0), 2)
cv2.imshow('frame',frame)
# cv2.imshow('frame2',frame2)
if cv2.waitKey(1) & 0xFF == ord('q'):
cap.release()
cv2.destroyAllWindows()
break
frame_count+=1
if frame_count>4:
frame_count = 0 # avoid inifinite number
|
manishbisht/Competitive-Programming | Hackerrank/Practice/Python/1.introduction/05.Loops.py | Python | mit | 107 | 0.009346 | if __name__ == '__main__':
n = int(input())
for i in range(n):
| print(i**2)
| |
roscoeZA/GeoGigSync | geo_repo.py | Python | cc0-1.0 | 4,025 | 0.003727 | __author__ = 'roscoe'
import os
from datetime import datetime
import qgis.utils
import qgis.utils
from src.geogigpy import Repository
from src.geogigpy import geogig
from src.geogigpy.geogigexception import GeoGigException
from qgis.core import QgsVectorLayer, QgsMapLayerRegistry
class GeoRepo(object):
def __in... | self.local_repo.pull("origin")
except GeoGigException, e:
print e
# Notes:
# ------------------------------------------------------------------------
# changed self.connector.importpg to self.connector.importsl in repo.py
# changed commands.extend(["--ta... | ctor.importsl(database, table, add, dest)
# GeoGig can only import spatialite tables that have been created by
# export db from Geogig. |
googleapis/python-aiplatform | tests/unit/gapic/aiplatform_v1/test_tensorboard_service.py | Python | apache-2.0 | 360,461 | 0.000977 | # -*- 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 applicable law or... | Client.get_transport_class("grpc")
assert transport == transports.TensorboardServiceGrpcTransport
@pytest.mark.parametrize(
"client_class,transport_class,transport_name",
[
(TensorboardServiceClient, transports.TensorboardServiceGrpcTransport, "grpc"),
(
TensorboardServiceAsync... | boardServiceClient,
"DEFAULT_ENDPOINT",
modify_default_endpoint(TensorboardServiceClient),
)
@mock.patch.object(
TensorboardServiceAsyncClient,
"DEFAULT_ENDPOINT",
modify_default_endpoint(TensorboardServiceAsyncClient),
)
def test_tensorboard_service_client_client_options(
client_class, transpor... |
cliffclive/neuromancy | neuromancy/theano_tutorials/tutorial_mlp.py | Python | mit | 13,906 | 0.001582 | # http://deeplearning.net/tutorial/code/mlp.py
"""
This tutorial introduces the multilayer | perceptron using Theano.
A multilayer perceptron is a logistic regressor where
instead of feeding | the input to the logistic regression you insert a
intermediate layer, called the hidden layer, that has a nonlinear
activation function (usually tanh or sigmoid) . One can use many such
hidden layers making the architecture deep. The tutorial will also tackle
the problem of MNIST digit classification.
.. math::
f... |
BrandonTang/binary-transparency | transparencyscript/script.py | Python | mpl-2.0 | 3,070 | 0.002606 | import os
import sys
import logging
import base64
from subprocess import check_call
from transparencyscript.constants import TRANSPARENCY_SUFFIX
from transparencyscript.utils import make_transparency_name, get_config_vars, get_password_vars, get_task_vars, \
get_transparency_vars, get_tree_head, get_lego_env, get_... | = make_transparency_name(tree_head, config_vars["payload"]["version"],
config_vars["payload"]["stage-product"])
# Issue and save the certificate, then delete the extra files lego created
lego_env = get_lego_env(password_vars)
lego_command = get_lego_command | (config_vars, base_name, trans_name)
save_command = get_save_command(config_vars, base_name)
cleanup_command = "rm -rf {}/lego".format(config_vars["work_dir"])
check_call(lego_command, env=lego_env, shell=True)
check_call(save_command, shell=True)
check_call(cleanup_command, shell=True)
# Subm... |
OpServ-Monitoring/opserv-backend | app/server/restful_api/data/v1/endpoints/partitions_partition.py | Python | gpl-3.0 | 1,794 | 0.001115 | from misc.standalone_helper import decode_string, double_decode_string
from .__general_data_v1 import GeneralEndpointDataV1
class PartitionsPartitionEndpoint(GeneralEndpointDataV1):
def _get(self) -> bool:
partition_id = self._request_holder.get_params()["partition"]
partition_id = decode_string(p... | arent(cls):
from .partitions import PartitionsEndpoint
return PartitionsEndpoint
@classmethod
def _get_children(cls):
from .partitions_partition_free import PartitionsPartitionFreeEndpoint
from .partitions_partition_total import Partition | sPartitionTotalEndpoint
from .partitions_partition_used import PartitionsPartitionUsedEndpoint
return [
("/free", PartitionsPartitionFreeEndpoint),
("/total", PartitionsPartitionTotalEndpoint),
("/used", PartitionsPartitionUsedEndpoint)
]
@classmethod
... |
evgenybf/pyXLWriter | examples/hyperlink2.py | Python | lgpl-2.1 | 4,310 | 0.001624 | #!/usr/bin/env python
# This example script was ported from Perl Spreadsheet::WriteExcel module.
# The author of the Spreadsheet::WriteExcel module is John McNamara
# <jmcnamara@cpan.org>
__revision__ = """$Id: hyperlink2.py,v 1.3 2004/01/31 18:56:07 fufff Exp $"""
####################################################... | te('B7', 'external:../Asia/China.xls')
# External link to a remote file with worksheet
ire_links.write('B8', 'external:c:/Temp/Asia/China.xls#Sales!B8')
# External link to a remote file with worksheet (with spaces in the name)
ire_links.write('B9', "external:c:/Temp/Asia/China.xls#'Product Data'!B9")
###############... | #####################################
#
# Some utility links to return to the main sheet
#
ire_sales.write_url('A2', 'internal:Links!A2', 'Back')
ire_sales.write_url('A3', 'internal:Links!A3', 'Back')
ire_sales.write_url('A4', 'internal:Links!A4', 'Back')
ire_sales.write_url('A5', 'internal:Links!A5', 'Back')
ire_sales... |
drax68/graphite-web | webapp/graphite/events/views.py | Python | apache-2.0 | 5,333 | 0.002813 | import datetime
import six
try:
from django.contrib.sites.requests import RequestSite
except ImportError: # Django < 1.9
from django.contrib.sites.models import RequestSite
from django.core.exceptions import ObjectDoesNotExist
from django.core.serializers.json import DjangoJSONEncoder
from django.forms.model... | page range
"""
page_range = []
if 4>page:
if len(paginator.page_range)>_PAGE_LINKS:
page_range = [p for p in range(1, _PAGE_LINKS+1)]
else:
page_range=paginator.page_range
else:
for p in paginator.page_range:
if p<page:
if page... | _range.append(p)
if len(page_range)>_PAGE_LINKS and page>5:
page_range = page_range[:-1]
return page_range
@cache_page(60 * 15)
def view_events(request, page_id=1):
if request.method == "GET":
try:
page_id = int(page_id)
except ValueError:
page_id ... |
napalm-automation/napalm-yang | napalm_yang/models/openconfig/interfaces/interface/routed_vlan/ipv6/addresses/address/vrrp/vrrp_group/interface_tracking/state/__init__.py | Python | apache-2.0 | 11,529 | 0.001475 | # -*- coding: utf-8 -*-
from operator import attrgetter
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType
from pyangbind.lib.yangtypes import RestrictedClassType
from pyangbind.lib.yangtypes import TypedListType
from pyangbind.lib.yangtypes import YANGBool
from pyangbind.lib.yangtypes import YANGListTy... | ndB | ase
from collections import OrderedDict
from decimal import Decimal
from bitarray import bitarray
import six
# PY3 support of some PY2 keywords (needs improved)
if six.PY3:
import builtins as __builtin__
long = int
elif six.PY2:
import __builtin__
class state(PybindBase):
"""
This class was auto-g... |
tbereau/espresso | testsuite/python/magnetostaticInteractions.py | Python | gpl-3.0 | 2,692 | 0.007058 | #
# Copyright (C) 2013,2014,2015,2016 The ESPResSo project
#
# This file is part of ESPResSo.
#
# ESPResSo 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)... | etostatics import *
from tests_common import *
class MagnetostaticsInteractionsTests(ut.TestCase):
# Handle to espresso system
system = espressomd.System()
def setUp(self):
self.system.box_l = 10, 10, 10
if not self.system.part.exists(0):
self.system.part.add(id=0, pos=(0.1, 0... | P3M" in espressomd.features():
test_DP3M = generate_test_for_class(DipolarP3M, dict(prefactor=1.0,
epsilon=0.0,
inter=1000,
... |
madjam/mxnet | python/mxnet/_ctypes/ndarray.py | Python | apache-2.0 | 5,374 | 0.000744 | # 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 yo | u 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/li | censes/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
#... |
SohoTechLabs/django-ajax-changelist | ajax_changelist/admin.py | Python | mit | 4,495 | 0.001557 | from django import http
from django.conf.urls import patterns
from django.contrib import admin
from django.db import models
from django.forms.models import modelform_factory
from django.shortcuts import get_object_or_404
from django.template import loader, Context
from django.views.generic import View
def get_printab... | rn http.HttpResponseBadRequest()
form.save()
new_value = get_printable_field_value(instance, fieldname)
return http.HttpResponse(new | _value)
class AjaxModelAdmin(admin.ModelAdmin):
""" Admin class providing support for inline forms in
listview that are submitted through AJAX.
"""
def __init__(self, *args, **kwargs):
HANDLER_NAME_TPL = "_%s_ajax_handler"
if not hasattr(self, 'ajax_list_display'):
s... |
ptoman/icgauge | icgauge/experiment_frameworks.py | Python | mit | 11,989 | 0.009425 | # -*- coding: utf-8 -*-
#!/usr/bin/python
import numpy as np
import scipy
from sklearn import preprocessing
from sklearn.feature_extraction import DictVectorizer
from sklearn.cross_validation import train_test_split
from sklearn.metrics import classification_report, confusion_matrix
from collections import Counter
fro... | n, indices_assess, y_train, y_assess = train_test_split(
indices, y_train, train_size=train_size, stratify=y_train)
X_assess = X_train[indices_assess]
asse | ss_examples = train_examples[indices_assess]
X_train = X_train[indices_train]
train_examples = train_examples[indices_train]
print " Train y distribution:"
print " ", np.bincount(y_train)[1:]
print " Test y distribution:"
print " ", np.bincount(y_assess)[1:]... |
airanmehr/bio | Scripts/Miscellaneous/Tutorials/demography.py | Python | mit | 2,014 | 0.021351 | '''
Copyleft Mar 10, 2017 Arya Iranmehr, PhD Student, Bafna Lab, UC San Diego, Email: airanmehr@gmail.com
'''
import numpy as np;
np.set_printoptions(linewidth=200, precision=5, suppress=True)
import pandas as pd;
pd.options.display.max_rows = 20;
pd.options.display.expand_frame_repr = False
# import seaborn as sns
... | oci=1,
infoFields=model.info_fiel | ds)
pop.evolve(
initOps=[
sim.InitSex(),
sim.InitGenotype(freq=[0.5, 0.5])
],
matingScheme=sim.RandomMating(subPopSize=model),
finalOps=
sim.Stat(alleleFreq=0, vars=['alleleFreq_sp']),
gen=model.num_gens
)
model
# print out population size and frequency
#for idx, name in enum... |
nadeemsyed/swift | test/unit/common/test_splice.py | Python | apache-2.0 | 10,235 | 0 | # Copyright (c) 2014 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to ... | {}))
def test_errno(self):
'''Test handling of failures'''
# Invoke EBADF by using a read-only FD as fd_out
with open('/dev/null', 'r') as fd:
err = errno.EBADF
msg = r'\[Errno %d\] splice: %s' % (err, os.strerror(err))
try:
splice(fd, No... | except IOError as e:
self.assertTrue(re.match(msg, str(e)))
else:
self.fail('Expected IOError was not raised')
self.assertEqual(ctypes.get_errno(), 0)
@mock.patch('swift.common.splice.splice._c_splice', None)
def test_unavailable(self):
'''Test ... |
rnyberg/pyfibot | pyfibot/modules/module_geokick.py | Python | bsd-3-clause | 5,174 | 0.015471 | # -*- coding: utf-8 -*-
import sys
import pygeoip
import os.path
import socket
import sqlite3
import time
import re
DATAFILE = os.path.join(sys.path[0], "GeoIP.dat")
# STANDARD = reload from disk
# MEMORY_CACH | E = load to memory
# MMAP_CACHE = memory using mmap
gi4 = pygeoip.GeoIP(DATAFILE, pygeoip.MEMORY_CACHE)
def init(botconfig):
open_DB(True)
def open_DB(createTable=False, db="module_geokick.db"):
conn = sqlite3.connect(db)
c = conn.cursor()
if createTable:
c.execute('CREATE TABLE IF NOT EXISTS exceptions... | !ident@hostname | Supports wildcards, for example *!*@*site.com (! and @ are required)"""
if get_op_status(user):
if not get_exempt_status(args):
if len(args) < 4:
conn, c = open_DB()
insert = "INSERT INTO exceptions VALUES ('" + args + "');"
c.execute(insert)
conn.commit()
... |
jordanemedlock/psychtruths | temboo/core/Library/Bitly/LinkMetrics/GetClicksForLink.py | Python | apache-2.0 | 5,517 | 0.005256 | # -*- coding: utf-8 -*-
###############################################################################
#
# GetClicksForLink
# Returns the number of clicks on a single Bitly link.
#
# Python versions 2.6, 2.7, 3.x
#
# Copyright 2014, Temboo Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you... | (optional, date) An epoch timestamp, indicating the most recent time for which to pull metrics.)
"""
super(GetClicksForLinkInputS | et, self)._set_input('Timestamp', value)
def set_Timezone(self, value):
"""
Set the value of the Timezone input for this Choreo. ((optional, string) An integer hour offset from UTC (-12..12), or a timezone string. Defaults to "America/New_York".)
"""
super(GetClicksForLinkInputSet, s... |
zeratul2099/crypt_app | crypto/models.py | Python | gpl-3.0 | 4,784 | 0.005029 | # encoding: utf-8
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is d... | quired=True)
block_values = ((1, 'ECB'), (2, 'CBC'), (3, 'CFB'))
block_mode = forms.ChoiceField(choices=block_values, label='Blockmodus')
class AESDecryptForm(forms.Form):
cypher_text = forms.IntegerField(label='Geheimtext', required | =True)
key = forms.CharField(label='Schlüssel', required=True)
block_values = ((1, 'ECB'), (2, 'CBC'), (3, 'CFB'))
block_mode = forms.ChoiceField(choices=block_values, label='Blockmodus')
class SimpleEncryptForm(forms.Form):
message = forms.CharField(label='Klartext', required=True)
key = forms.Ch... |
bcoding/docker-host-scripts | py/generate_etc_hosts.py | Python | unlicense | 301 | 0.006645 | #!/us | r/bin/env python
import common
import sys
for name,ip,port in common.get_vm_config():
format_args = {'public_port': port,
'name': name,
'local_address': ip
}
print "%(local_address)s\t%(name)s %(name)s | .acme.intern" % format_args
|
28harishkumar/Social-website-django | user/migrations/0003_auto_20150703_0843.py | Python | mit | 485 | 0.002062 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('user', '00 | 02_auto_2015 | 0703_0836'),
]
operations = [
migrations.AlterField(
model_name='user',
name='followers',
field=models.ManyToManyField(to=settings.AUTH_USER_MODEL, related_name='followers_rel_+'),
),
]
|
sparkslabs/kamaelia_ | Sketches/RJL/SMTP/MailShared.py | Python | apache-2.0 | 2,422 | 0.004129 | # -*- coding: utf-8 -*-
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# Licensed under the Apache License, Version 2.0 (the "Lic... | else:
return False
def isPlain(text):
plaindict = {'-': True, '.': True, '1': True, '0': True, '3': True, '2': True, '5': True, '4': True, '7': True, '6': True, '9': True, '8': True, 'A': True, 'C': True, 'B': True, 'E': True, 'D': True, 'G': True, 'F': True, 'I': True, 'H': True, 'K': True, 'J': True, ... | 'V': True, 'Y': True, 'X': True, 'Z': True, '_': True, 'a': True, 'c': True, 'b': True, 'e': True, 'd': True, 'g': True, 'f': True, 'i': True, 'h': True, 'k': True, 'j': True, 'm': True, 'l': True, 'o': True, 'n': True, 'q': True, 'p': True, 's': True, 'r': True, 'u': True, 't': True, 'w': True, 'v': True, 'y': True, '... |
avcopan/meinsum | test/test_antisym.py | Python | gpl-3.0 | 5,061 | 0 | import numpy as np
import os
from tensorutils.antisym import get_antisymmetrizer_product as asym
test_dir_path = os.path.dirname(os.path.realpath(__file__))
array_path_template = os.path.join(test_dir_path, "random_arrays", "{:s}.npy")
def test__composition_1():
array1 = np.load(array_path_template.format("15x1... | - array1.transpose((0, 2, 1))
- array1.transpose((1, 0, 2))
+ array1.transpose((1, 2, 0))
+ array1.transpose((2, 0, 1))
- array1.transpose((2, 1, 0)))
assert (np.allclose(array2, array3))
def test__composition_1_3():
array1 = np.load(array_path... | - array2.transpose((2, 1, 0, 3))
- array2.transpose((3, 1, 2, 0)))
assert (np.allclose(array3, array4))
def test__composition_2_2():
array1 = np.load(array_path_template.format("15x15x15x15"))
array2 = asym("0/1|2/3") * array1
array3 = asym("0,1/2,3") * array2
array4 = (array... |
danielvdao/facebookMacBot | venv/lib/python2.7/site-packages/sleekxmpp/util/__init__.py | Python | mit | 1,067 | 0.002812 | # -*- coding: utf-8 -*-
"""
sleekxmpp.util
~~~~~~~~~~~~~~
Part of SleekXMPP: The Sleek XMPP Library
:copyright: (c) 2012 Nathanael C. Fritz, Lance J.T. Stout
:license: MIT | , see LICENSE for more details
"""
from sleekxmpp.util.misc_ops import bytes, unicode, hashes, hash, \
num_to_bytes, bytes_to_num, quote, \
XOR, safedict
# =====================================================================
# Standardize impo... | _threads_enabled():
if not 'gevent' in sys.modules:
return False
try:
from gevent import thread as green_thread
thread = __import__('thread')
return thread.LockType is green_thread.LockType
except ImportError:
return False
if _gevent_threads_enabled():
import gev... |
koduj-z-klasa/python101 | docs/webflask/quiz/quiz2.py | Python | mit | 204 | 0 | # -*- coding: utf-8 -*-
# quiz/quiz.py
from flask im | port Flask
app = Flask(__name__)
@app.route('/')
def index():
return 'Cześć, tu Python!'
if _ | _name__ == '__main__':
app.run(debug=True)
|
MooMan272/selenium_the_internet | verify/dropdown.py | Python | mit | 710 | 0.002817 | import logging
import page_objects
def option_should_be_selected(text):
'''
Verifies specified dropdown option is selected.
Parameters
----------
text : str
Returns
-------
None
Raises
------
AssertionError
| If the specified option is not selected.
'''
page = page_objects.dropdown.DropdownPage()
selected_option = page.selected_option()
if selected_option != text:
log_str = 'FAIL:\n Actual option selected: {}\n Expected option selected: {}'.format(selected_option, text)
logging.err... | ('PASS: Option "{}" selected.'.format(selected_option))
return
|
kevlened/pytanium | pytanium/webdriver.py | Python | lgpl-3.0 | 39,315 | 0.019407 | import httplib, time, inspect
import selenium.webdriver.remote.webdriver
from pytanium_element import PytaniumElement
OldRemoteWebDriver = selenium.webdriver.remote.webdriver.WebDriver
# Redefine the RemoteWebDriver
class RemoteWebDriver(OldRemoteWebDriver):
# NOTE: Both desired_capabilities and capabilities... | mages = pytanium_capabilities['waitForImages']
self.enable_recorder = pytanium_capabilities['enableRecorder']
self.recorder_host = pytanium_capabilities['recorderHost']
self.recorder_port = pytanium_capabilities['recorderPort']
# If we're | using the recorder, check the proxy
if self.enable_recorder:
self.check_recorder_proxy()
extra_ie_capabilities = {"proxy": {
"httpProxy":"{0}:{1}".format(self.recorder_host, str(self.recorder_port)),
... |
ericbuckley/django-project-template | project_name/libs/common/models.py | Python | bsd-3-clause | 2,547 | 0.002356 | # -*- coding: utf-8 -*-
"""
{{ project_name }}.libs.common.models
~~~~~~~~~~~~~~~~~~~~~~~~~
This module contains all models that can be used across apps
:copyright: (c) 2015
"""
from django.db import models
from django.utils.translation import ugettext_lazy as _
from .utils.text import slugify
clas... | me }}.libs.common.models.SlugModel` for the given
slug. If the slug dosen't exist, return None.
:param slug: the slug value to search for
"""
try:
return cls.objects.get(slug=slug)
except cls.DoesNotExist:
return None
def base_slug_v | alue(self):
"""
As a subclass of :class:`{{ project_name }}.libs.common.models.SlugModel` one must
implement the :method:`{{ project_name }}.libs.common.models.SlugModel.base_slug_value`
which returns a unicode value that is used as the basis of the slug value.
"""
raise ... |
spaetz/offlineimap | offlineimap/folder/IMAP.py | Python | gpl-2.0 | 33,949 | 0.004242 | # IMAP folder support
# Copyright (C) 2002-201 | 2 John Goerzen & contributors
#
# 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 distr... | of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA... |
eestay/edx-platform | common/test/acceptance/tests/video/test_studio_video_editor.py | Python | agpl-3.0 | 22,804 | 0.001114 | # -*- coding: utf-8 -*-
"""
Acceptance tests for CMS Video Editor.
"""
from nose.plugins.attrib import attr
from .test_studio_video_module import CMSVideoBaseTest
@attr('shard_2')
class VideoEditorTest(CMSVideoBaseTest):
"""
CMS Video Editor Test Class
"""
def setUp(self):
super(VideoEditorT... | oes not show the captions
"""
self._create_video_component(subtitles=True)
# Prevent | cookies from overriding course settings
self.browser.delete_cookie('hide_captions')
self.edit_component()
self.open_advanced_tab()
self.video.set_field_value('Show Transcript', 'False', 'select')
self.save_unit_settings()
self.assertFalse(self.video.is_captions_visible()... |
Thingee/cinder | cinder/tests/api/v2/test_snapshot_metadata.py | Python | apache-2.0 | 21,148 | 0.000142 | # 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... | lue2'}}
self.assertEqual(expected, res_dict)
def test_show_nonexistent_snapshot(self):
self.stubs.Set(cinder.db, 'snapshot_metadata_get',
return_snapshot_nonexistent)
req = fakes.HTTPRequest.blank(self.url + '/key2')
self.assertRaises(webob.exc.HTTPNotFound,
... | elf.stubs.Set(cinder.db, 'snapshot_metadata_get',
return_empty_snapshot_metadata)
req = fakes.HTTPRequest.blank(self.url + '/key6')
self.assertRaises(webob.exc.HTTPNotFound,
self.controller.show, req, self.req_id, 'key6')
def test_delete(self):
... |
mattduan/proof | util/memory.py | Python | bsd-3-clause | 982 | 0.003055 | #! /usr/bin/env python
import os
_proc_status = '/proc/%d/status' % os.getpid()
_scale = {'kB': 1024.0, 'mB': 1024.0*1024.0,
'KB': 1024.0, 'MB': 1024.0*1024.0}
def _VmB(VmKey):
'''Private.
'''
global _proc_status, _scale
# get pseudo file /proc/<pid>/status
try:
t = open(_proc_... | * _scale[v[2]]
def memory(since=0.0):
'''Return memory usage in bytes.
'''
return _VmB('VmSize:') - since
def resident(since=0.0):
'''Return resident memory usage in bytes.
'''
return _VmB('VmRSS:') - since
def stacksize(since=0.0):
'''Return stack size in bytes.
'''
return _Vm... | VmStk:') - since
|
worldbank/cv4ag | modules/get_satellite.py | Python | mit | 4,605 | 0.044517 | #!usr/bin/python
'''
Get satellite data according to input file.
'''
from random import shuffle,random
import os,json
from utils.mapbox_static import MapboxStatic
from utils.coordinate_converter import CoordConvert
from modules.getFeatures import latLon,getBBox
from libs.foldernames import satDataFolder,testDataFolder
... | +os.path.split(inputFile)[-1][:-5]
if not os.path.isdir(subpath):
os.mkdir(subpath)
print 'Directory',subpath,'created'
if not os.path.isdir(subpath+satDataFolder):
os.mkdir(subpath+satDataFolder)
print 'Directory',subpath+satDataFolder,'created'
if not os.path.isdir(subpath+testDataFolder):
os.mkdir(subpa... | estDataFolder,'created'
#Write metadata
with open(subpath+satDataFolder+"meta.csv","a+") as f:
f.write("ZoomLevel,,"+str(zoomLevel)+"\n")
#get bbox if set to random
if randomImages:
xlist=[]
ylist=[]
for element in elements['features']:
minxe,maxxe,minye,maxye=getBBox(element)
xlist.append(minxe)
... |
shootsoft/practice | lintcode/NineChapters/04/longest-increasing-subsequence.py | Python | apache-2.0 | 646 | 0.006192 | __author__ = 'yinjun'
class Solution:
"""
@param nums: The integer array
@return: The length of LIS | (longest increasing subsequence)
"""
def longestIncreasingSubsequence(self, nums):
# write your code here
if nums == None or nums == []:
return 0
l = len(nums)
length = [0 for | i in range()]
maxLength = 0
for i in range(l):
length[i] = 1
for j in range(0, i):
if nums[j] <= nums[i]:
length[i] = max(length[i], length[j] + 1)
maxLength = max(maxLength, length[i])
return maxLength |
dingmingliu/quanttrade | quanttrade/core/strategy.py | Python | apache-2.0 | 1,007 | 0.017875 | import pandas as pd
import numpy as np
import cython as cy
#coding=UTF8
class Strategy(object):
_capital = cy.declare(cy.double)
_net_flows = cy.declare(cy.double)
_last_value = cy.declare(cy.double)
_last_price = cy.declare(cy.double)
_last_fee = cy.declare(cy.double)
def run(self):... | ,long):
self.short=short
self.long=long
def run(self):
short_avg=pd.rolling_mean(self.data,self.short)
long_avg=pd.rolling_meam(self.data,self.long)
print(short_avg)
for day in self.data.index:
pass
print(self.data[day])
'''if(sel... | ort_avg[]>self.long_avg):
pass
else:
pass''' |
alexforencich/verilog-ethernet | tb/eth_mac_10g/test_eth_mac_10g.py | Python | mit | 9,014 | 0.000998 | #!/usr/bin/env python
"""
Copyright (c) 2020 Alex Forencich
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merg... | _lengths=None, payload_data=None, ifg=12):
tb = TB(dut)
tb.xgmii_source.ifg = ifg
tb.dut.ifg_delay <= ifg
await tb.reset()
test_frames = [payload_data(x) for x in payload_lengths()]
for test_data in test_frames:
test_frame = XgmiiFrame.from_payload(test_data)
await tb.xgmii_... | for test_data in test_frames:
rx_frame = await tb.axis_sink.recv()
assert rx_frame.tdata == test_data
assert rx_frame.tuser == 0
assert tb.axis_sink.empty()
await RisingEdge(dut.rx_clk)
await RisingEdge(dut.rx_clk)
async def run_test_tx(dut, payload_lengths=None, payload_data... |
dvl/imagefy-web | imagefy/wishes/migrations/0002_auto_20160522_1447.py | Python | mit | 506 | 0.001976 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-05-22 17:47
from __future__ import unicode_l | iterals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('wishes', '0001_squashed_0002_auto_20160522_1408'),
]
operations = [
migrations.AlterField(
model_name='wish',
name='brief',
field=models.CharFie... | th=140, null=True, verbose_name='Brief'),
),
]
|
LuisAlejandro/condiment | condiment/common/setup/report.py | Python | gpl-3.0 | 2,481 | 0.003226 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2014 Luis Alejandro Martínez Faneyth
#
# This file is part of Condiment.
#
# Condiment 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 ver... | data = get_package_data(path=BASEDIR, packages=packages,
data_files=data_files,
exclude_files=exclude_sources + \
exclude_patterns,
exclude_packag... | ckage_data'] = package_data
pprint(setup_data)
|
eduNEXT/edunext-platform | openedx/core/djangoapps/embargo/forms.py | Python | agpl-3.0 | 3,045 | 0.000657 | """
Defines forms for providing validation of embargo admin details.
"""
import ipaddress
from django import forms
from django.utils.translation import ugettext as _
from opaque_keys import InvalidKeyError
from opaque_keys.edx.keys import CourseKey
from xmodule.modulestore.django import modulestore
from .models imp... | valid ipv4 address or ipv6 address"""
try:
# Is this an valid ip address?
ipaddress.ip_network(address)
except ValueError:
return False
return True
def _valid_ip_addresses(self, addresses):
"""
Checks if a csv string of IP addresses contai... | sses.split(','):
address = addr.strip()
if not self._is_valid_ip(address):
error_addresses.append(address)
if error_addresses:
msg = f'Invalid IP Address(es): {error_addresses}'
msg += ' Please fix the error(s) and try again.'
raise for... |
legendlee1314/ooni | mesos.py | Python | mit | 1,625 | 0.008 | # Author: legend
# Mail: kygx.legend@gmail.com
# File: mesos.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
import argparse
import os
import re
MASTER_IP = '172.16.104.62'
MESOS_PATH = '/data/opt/mesos-1.4.0/build'
WORK_DIR = '/tmp/mesos/work_dir'
MASTER_SH = 'bin/mesos-master.sh'
WORKER_SH = 'bin/mesos-agent.sh'
d... | ArgumentP | arser(description='Mesos Cluster Tools')
parser.add_argument('-rm', '--runmaster', help='Run master', action='store_true')
parser.add_argument('-ra', '--runagent', help='Run agent', action='store_true')
parser.add_argument('-km', '--killmaster', help='Kill master', action='store_true')
parser.add_argume... |
foone/7gen | bin/obj2vxpGUI.py | Python | gpl-2.0 | 6,717 | 0.056573 | #OBJ2VXP: Converts simple OBJ files to VXP expansions
#Copyright (C) 2004-2015 Foone Turing
#
#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 ... | Author name:'))
ui.add(sockgui.Label(ui,[20,ys+42],'Orig. Author name:'))
ui.add(sockgui.Label(ui,[20,ys+58],'Shortname:'))
ui.add(sockgui.Label(ui,[20,ys+74],'Filename:'))
self.filenamelabel=sockgui.Label(ui,[120,ys+74],'')
ui.add(self.filenamelabel)
self.namebox= sockgui.TextBox(ui,[120,ys+... | TextBox(ui,[120,ys+42-3],40)
self.shortnamebox= sockgui.TextBox(ui,[120,ys+58-3],40,callback=self.onShortNameChanged)
self.shortnamebox.setAllowedKeys(sockgui.UPPERCASE+sockgui.LOWERCASE+sockgui.DIGITS+'._-')
self.authorbox.setText(self.getAuthor())
ui.add(self.namebox)
ui.add(self.authorbox)
ui.add(se... |
ghachey/flask-easywebdav | setup.py | Python | mit | 1,092 | 0 | """
Flask-EasyWebDAV
-------------
This is the description for that library
"""
from setuptools import setup
setup(
name='Flask-EasyWebDAV',
version='0.1',
url='http://github.com/ghachey/flask-easywebdav',
license='MIT',
author='Ghislain Hachey',
author_email='ghachey@outlook.com',
descrip... | f you would be using a package instead use packages instead
# of py_modules:
# packages=['flask_easywebdav'],
zip_safe=False,
include_package_data=True,
platforms='any',
install_requires=[
'Flask',
'easywebdav'
],
classifiers=[
'Environment :: Web Environment',
... | : Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules'
]
)
|
rombie/contrail-controller | src/container/mesos-manager/mesos_manager/vnc/config_db.py | Python | apache-2.0 | 32,110 | 0.000685 | #
# Copyright (c) 2016 Juniper Networks, Inc. All rights reserved.
#
"""
This file contains implementation of data model for mesos manager
"""
import json
from cfgm_common.vnc_db import DBBase
from bitstring import BitArray
from vnc_api.vnc_api import (KeyValuePair)
from mesos_manager.vnc.vnc_mesos_config import VncM... | name_to_uuid.get(
tuple(cls._get_ann_fq_name_from_params(**annotations)))
@classmethod
def _update_ann_fq_name_to_uuid(cls, uuid, ann_fq_name):
cls._ann_fq_name_to_uuid[tuple(ann_fq_name)] = uuid
def build_fq_name_to_uuid(self, uuid, ob | j_dict):
"""Populate uuid in all tables tracking uuid."""
if not obj_dict:
return
# Update annotated-fq-name to uuid table.
self.ann_fq_name = self._get_ann_fq_name_from_obj(obj_dict)
if self.ann_fq_name:
self._update_ann_fq_name_to_uuid(uuid, self.ann_fq... |
AutorestCI/azure-sdk-for-python | azure-servicefabric/azure/servicefabric/models/update_cluster_upgrade_description.py | Python | mit | 2,832 | 0.002119 | # 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 ... | ---------------------------------------------------------------------
from msrest.serialization import Model
class UpdateClusterUpgradeDescription(Model):
"""Parameters for updating a cluster upgrade.
:param upgrade_kind: Possible values include: 'Invalid', 'Roll | ing',
'Rolling_ForceRestart'. Default value: "Rolling" .
:type upgrade_kind: str or :class:`enum <azure.servicefabric.models.enum>`
:param update_description:
:type update_description: :class:`RollingUpgradeUpdateDescription
<azure.servicefabric.models.RollingUpgradeUpdateDescription>`
:param ... |
YongMan/Xen-4.3.1 | tools/python/xen/xend/tests/test_sxp.py | Python | gpl-2.0 | 1,015 | 0.003941 | import unittest
import xen.xend.sxp
class test_sxp(unittest.TestCase):
def testAllFromString(self):
def t(inp, expected):
self.assertEqual(xen.xend.sxp.all_from_string(inp), expected)
t('String', ['String' | ])
t('(String Thing)', [['String', 'Thing']])
t('(String) (Thing)', [['String'], ['Thing']])
def testParseFixed(self):
fin = file('../xen/xend/tests/xend-config.sxp', 'rb')
try:
config = xen.xend.sxp.parse(fin)
self.assertEqual(
| xen.xend.sxp.child_value(
config,
'xend-relocation-hosts-allow'),
'^localhost$ ^localhost\\.localdomain$')
finally:
fin.close()
def testParseConfigExample(self):
fin = file('../../examples/xend-config.sxp', 'rb')
try:
... |
op3/hdtv | hdtv/peakmodels/__init__.py | Python | gpl-2.0 | 217 | 0 | from .theuerkaufP | eak import PeakModelTheuerkauf
from .eePeak import PeakModelEE
# dictionary of available peak models
PeakModels = dict()
PeakModels[ | "theuerkauf"] = PeakModelTheuerkauf
PeakModels["ee"] = PeakModelEE
|
AriMeidan/Fantasy-Knesset | votes/migrations/0001_initial.py | Python | gpl-3.0 | 10,925 | 0.008055 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
depends_on = (
("django_facebook", "0001_initial"),
)
def forwards(self, orm):
# Adding ... | ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'date_of_birth': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'facebook_id... | .models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'facebook_open_graph': ('django.db.models.fields.NullBooleanField', [], {'null': 'True', 'blank': 'True'}),
'facebook_profile_url': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'})... |
ict-felix/stack | vt_manager_kvm/src/python/vt_manager_kvm/communication/sfa/methods/Start.py | Python | apache-2.0 | 471 | 0.008493 | from vt_manager_kvm.communi | cation.sfa.util.xrn import urn_to_hrn
from vt_manager_kvm.communication.sfa.trust.credential import Credential
from vt_manager_kvm.communication.sfa.trust.auth import Auth
class Start:
def __init__(self, xrn, creds, **kwargs):
hrn, type = urn_to_hrn(xrn)
valid_creds = Auth().checkCredentials(c... | 0]).get_gid_caller().get_hrn()
return
|
assamite/itm_project | docs/source/conf.py | Python | gpl-2.0 | 8,919 | 0.006282 | # -*- coding: utf-8 -*-
#
# Project of Information-Theoretic Modeling documentation build configuration file, created by
# sphinx-quickstart on Fri Dec 12 14:45:52 2014.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present i... | output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'projectofinformation-theoreticmodeli | ng', u'Project of Information-Theoretic Modeling Documentation',
[u'Simo Linkola, Teemu Pitkänen and Kalle Timperi'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Tex... |
jyotsna1820/django | django/middleware/csrf.py | Python | bsd-3-clause | 12,394 | 0.001291 | """
Cross Site Request Forgery Middleware.
This module provides a middleware that implements protection
against request forgeries from other sites.
"""
from __future__ import unicode_literals
import logging
import re
import string
from django.conf import settings
from django.core.urlresolvers import get_callable
from... | HTTPS,
| # Barth et al. found that the Referer header is missing for
# same-domain requests in only about 0.2% of cases or less, so
# we can use strict Referer checking.
ref |
ncleaton/njcant | njcant/hr_analysis.py | Python | mit | 4,240 | 0.027123 | import math
from log_parser import parse_loglines
from event_timer import add_realtimes_to_datapoint_list
class HeartBeatTimings(object):
def __init__(self, hrm_datapoint_iter):
self.samples = list(_generate_beat_samples(hrm_datapoint_iter))
def first_beat_time(self):
return self.samples[0][0]
def last_beat_... | m_time=None, to_time=None):
"Return a subset of t | he data by time interval"
return HeartBeatTimingsTimeslice(self, from_time, to_time)
def realtimes_of_beats(self):
""" Generate the real clock time of each heart beat
Yield the time of each heartbeat the occured within the data set.
Where there is incomplete data, use None as a placeholder for the
bea... |
guijomatos/SickRage | sickbeard/clients/qbittorrent_client.py | Python | gpl-3.0 | 2,391 | 0.002509 | # Author: Mr_Orange <mr_orange@hotmail.it>
# URL: http://code.google.com/p/sickbeard/
#
# This file is part of SickRage.
#
# SickRage is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the Lic... | ity(self, result):
self.url = self | .host+'command/decreasePrio '
if result.priority == 1:
self.url = self.host+'command/increasePrio'
data = {'hashes': result.hash}
return self._request(method='post', data=data)
def _set_torrent_pause(self, result):
self.url = self.host+'command/resume'
... |
anthonyndunguwanja/Anthony-Ndungu-bootcamp-17 | Day 3/http_client.py | Python | mit | 439 | 0.013667 | import json
import urllib2
# open the url and the screen name
# (The screen name is the screen name of the user for whom to return results for)
def get_data():
url = "http://api.twitter.com/1/statuses/user_timeline.json?screen_name=python"
# this takes a python object and dumps it | to a string which is a JSON
# representation of that object
data = json.load(urllib2.urlopen | (url))
# print the result
print data
get_data()
|
jleclanche/pywow | wdbc/structures/__init__.py | Python | cc0-1.0 | 1,799 | 0.033352 | """
Base logic for pywow structures
"""
from structures import Structure, Skeleton
from .fields import *
from .main import *
from .generated import GeneratedStructure
class StructureNotFound(Exception):
pass
class StructureLoader():
wowfiles = None
@classmethod
def setup(cls):
if cls.wowfiles is None:
cls... | n globals():
try:
if not issubclass(globals()[name], Structure):
continue
except TypeError:
continue
cls.wowfiles[na | me.lower()] = globals()[name]
@classmethod
def getstructure(cls, name, build=0, parent=None):
name = name.replace("-", "_")
if name in cls.wowfiles:
return cls.wowfiles[name](build, parent)
raise StructureNotFound("Structure not found for file %r" % (name))
StructureLoader.setup()
getstructure = StructureL... |
IITBinterns13/edx-platform-dev | common/lib/xmodule/xmodule/conditional_module.py | Python | agpl-3.0 | 9,200 | 0.001413 | """Conditional module is the xmodule, which you can use for disabling
some xmodules by conditions.
"""
import json
import logging
from lxml import etree
from pkg_resources import resource_string
from xmodule.x_module import XModule
from xmodule.modulestore import Location
from xmodule.seq_module import SequenceDescri... | .
"""
if not self.is_condition_satisfied():
defmsg = "{link} must be attempted before this will become visible."
message = self.descriptor.xml_attributes.get('message', defmsg) |
context = {'module': self,
'message': message}
html = self.system.render_template('conditional_module.html',
context)
return json.dumps({'html': [html], 'message': bool(message)})
html = [child.get_html()... |
csriharsha/fosswebsite | timeline/admin.py | Python | mit | 200 | 0 | # -*- coding: utf-8 -*-
from __future__ import u | nicode_literals
from django.contrib import admin
# Register your models here.
fro | m timeline.models import AlumniInfo
admin.site.register(AlumniInfo)
|
googleapis/python-securitycenter | samples/generated_samples/securitycenter_v1_generated_security_center_update_mute_config_async.py | Python | apache-2.0 | 1,620 | 0.000617 | # -*- 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 applicable law or... | software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CON | DITIONS 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 UpdateMuteConfig
# NOTE: This snippet has been automatically generated for illustrative purposes only.
# It may require ... |
taykey/nose-logpertest | tests/tests_logpertest.py | Python | apache-2.0 | 1,068 | 0.000936 | __author__ = 'roy'
import logging
logger = logging.getLogger()
class TestA():
_multiprocess_can_split_ = True
def setup(self):
logger.info("I'm in setup")
def teardown(self):
logger.info("I'm in teardown")
def test1(self):
logger.info("I'm in | test 1")
assert 1 == 1
def test2(self):
logger.info("I'm in test 2")
assert 2 == 2
def test3(self):
logger.info("I'm in test 3")
| assert 3 == 3
def test4(self):
logger.info("I'm in test 4")
assert 4 == 4
class TestB():
_multiprocess_can_split_ = True
def setup(self):
logger.info("I'm in setup")
def teardown(self):
logger.info("I'm in teardown")
def test1(self):
logger.info("I'm ... |
GrandComicsDatabase/django-templatesadmin | templatesadmin/urls.py | Python | bsd-3-clause | 328 | 0 | from django.conf.urls import url
from django.contrib.admin.sites import AdminSite
from functools import updat | e_wrapper
from templatesadmin import views as ta_views
urlpatterns = [
url(r'^$', ta_views.listing, name='templatesadmin-overview'),
url(r'^edit/(?P<path>.*)/$', ta_views.modify, | name='templatesadmin-edit'),
]
|
jorsea/odoomrp-wip | mrp_operations_extension/models/mrp_bom.py | Python | agpl-3.0 | 4,254 | 0 | # -*- encoding: utf-8 -*-
##############################################################################
#
# 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... | n
retur | n result2
@api.multi
@api.onchange('routing_id')
def onchange_routing_id(self):
for line in self.bom_line_ids:
line.operation = (self.routing_id.workcenter_lines and
self.routing_id.workcenter_lines[0])
if self.routing_id:
return {'warni... |
mxOBS/deb-pkg_trusty_chromium-browser | third_party/WebKit/Source/bindings/scripts/idl_definitions.py | Python | bsd-3-clause | 38,904 | 0.001954 | # Copyright (C) 2013 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the ... |
The type can be an actual type, or can be a typedef, which must be resolved
before passing data to the code generator.
"""
__metaclass__ = abc.ABCMeta
idl_type = None
def resolve_typedefs(self, typedefs):
"""Resolve typedefs to actual types in the object."""
# Constructors don... | erface itself.
if not self.idl_type:
return
# Need to re-assign self.idl_type, not just mutate idl_type,
# since type(idl_type) may change.
self.idl_type = self.idl_type.resolve_typedefs(typedefs)
#############################################################################... |
ClickSecurity/data_hacking | data_hacking/min_hash/__init__.py | Python | mit | 87 | 0 | '''Package for Banded Min Hash ba | sed Simila | rity Calculations'''
from min_hash import *
|
gmflanagan/waterboy | waterboy/utils.py | Python | bsd-3-clause | 941 | 0.005313 | import os
import sys
try:
import cPickle as _pickle
except ImportError:
import pickle as _pickle
if sys.version_info[0] == 2:
bytes = str
pathjoin = os.path.join
pathexists = os.path.exists
expanduser = os.path.expanduser
abspath = os.path.abspath
dirname = os.path.dirname
def pickle(value):
return ... | ):
"""Imports an object by name | .
import_object('x.y.z') is equivalent to 'from x.y import z'.
"""
parts = name.split('.')
m = '.'.join(parts[:-1])
attr = parts[-1]
obj = __import__(m, None, None, [attr], 0)
try:
return getattr(obj, attr)
except AttributeError as e:
raise ImportError("'%s' does not ex... |
petrjasek/superdesk-core | superdesk/metadata/item.py | Python | agpl-3.0 | 24,541 | 0.001589 | # -*- 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
from typing ... |
"type": "string",
"fielddata": True,
"fields": {
"phrase": {
"type": "string",
| "analyzer": "phrase_prefix_analyzer",
"search_analyzer": "phrase_prefix_analyzer",
"fielddata": True,
},
"keyword": {
"type": "keyword",
},
},
},
},
"anpa_take_key": {
"t... |
renzon/blob_app | test/testloader.py | Python | mit | 630 | 0.001587 | #!/usr/bin/env python
# coding: utf-8
import unittest
import sys
import os
PROJECT_PATH = os.path.sep.join(os.path.abspath(__file__).split(os.path.sep)[:-2])
ROOT_PATH = os.path.dirname(__file__)
if | __name__ == '__main__':
if 'GAE_SDK' in os.environ:
SDK_PATH = os.environ['GAE_SDK']
sys.path.insert(0, SDK_PATH)
import dev_appserver
dev_appserver.fix_sys_path()
sys.path.append(os.path.joi | n(PROJECT_PATH, 'src'))
tests = unittest.TestLoader().discover(ROOT_PATH, "*.py")
result = unittest.TextTestRunner().run(tests)
if not result.wasSuccessful():
sys.exit(1)
|
brain-research/mirage-rl-qprop | rllab/plotter/__init__.py | Python | mit | 23 | 0 | fr | om | .plotter import *
|
ityaptin/ceilometer | ceilometer/tests/unit/api/test_hooks.py | Python | apache-2.0 | 1,354 | 0 | # Copyright 2015 Huawei Technologies Co., Ltd.
# 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
#
# Un... |
def test_init_notifier_with_drivers(self):
self.CONF.set_override('telemetry_driver', 'messagingv2',
group='publisher_notifier')
hook = hooks.NotifierHook(self.CONF)
notifier = hook.notifier
self.assertIsInstance( | notifier, oslo_messaging.Notifier)
self.assertEqual(['messagingv2'], notifier._driver_names)
|
miptliot/edx-platform | lms/djangoapps/student_profile/views.py | Python | agpl-3.0 | 4,548 | 0.003518 | """ Views for a student's profile information. """
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.contrib.staticfiles.storage import staticfiles_storage
from django.core.exceptions import ObjectDoesNotExist
from django.core.urlresolvers import reverse
from django... | profile_username}),
'preferences_dat | a': preferences_data,
'account_settings_data': account_settings_data,
'profile_image_upload_url': reverse('profile_image_upload', kwargs={'username': profile_username}),
'profile_image_remove_url': reverse('profile_image_remove', kwargs={'username': profile_username}),
'p... |
saurabh6790/med_app_rels | controllers/status_updater.py | Python | agpl-3.0 | 8,752 | 0.035078 | # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import webnotes
from webnotes.utils import flt, cstr
from webnotes import msgprint
from webnotes.model.controller import DocListController
status_m... | conn.set_value(self.doc.doctype, self.doc.name, "status", self.doc.status)
def on_communication(self):
self.communication_set = True
self.set_status(update=True)
del self.communication_set
def communication_received(self):
if getattr(self, "communication_set", False):
last_comm = self.doclist.get({"doc... | n_sent(self):
if getattr(self, "communication_set", False):
last_comm = self.doclist.get({"doctype":"Communication"})
if last_comm:
return last_comm[-1].sent_or_received == "Sent"
def validate_qty(self):
"""
Validates qty at row level
"""
self.tolerance = {}
self.global_tolerance = None
... |
all-of-us/raw-data-repository | rdr_service/alembic/versions/942d61446bfa_renaming_jan_cope_to_feb.py | Python | bsd-3-clause | 3,082 | 0.004867 | """renaming Jan COPE to Feb
Revision ID: 942d61446bfa
Revises: 99fb6b79b5f7
Create Date: 2021-01-18 13:37:50.121134
"""
from alembic import op
import sqlalchemy as sa
import rdr_service.model.utils
from sqlalchemy.dialects import mysql
from rdr_service.participant_enums import PhysicalMeasurementsStatus, Questionnai... | eTime(), nullable=True))
op.add_column('participant_summary', sa.Column('questionnaire_on_cope_feb_time', rdr_service.model.utils.UTCDateTime(), nullable=True))
op.drop_column('participant_summary', 'questionnaire_on_cope_jan_time')
op.drop_column('participant_summary', 'questionnaire_on_cope_jan')
op.d... | authored')
# ### end Alembic commands ###
def downgrade_rdr():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('participant_summary', sa.Column('questionnaire_on_cope_jan_authored', mysql.DATETIME(), nullable=True))
op.add_column('participant_summary', sa.Column('questionna... |
titansgroup/python-phonenumbers | python/phonenumbers/data/region_FO.py | Python | apache-2.0 | 1,769 | 0.008479 | """Auto-generated file, do not edit by hand. FO metadata"""
from ..phonemetadata | import NumberFormat, PhoneNumberDesc, PhoneMetadata
PHONE_METADATA_FO = PhoneMetadata(id='FO', country_code=298, international_prefix='00',
general_de | sc=PhoneNumberDesc(national_number_pattern='[2-9]\\d{5}', possible_number_pattern='\\d{6}'),
fixed_line=PhoneNumberDesc(national_number_pattern='(?:20|[3-4]\\d|8[19])\\d{4}', possible_number_pattern='\\d{6}', example_number='201234'),
mobile=PhoneNumberDesc(national_number_pattern='(?:[27][1-9]|5\\d)\\d{4}', po... |
musically-ut/seqfile | setup.py | Python | mit | 1,646 | 0.031592 | import os
import sys
from setuptools import setup
# Utility function to read the README file.
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
# The argparse module was introduced in python 2.7 or python 3.2
REQUIRES = ["argpar | se"] if sys.version[:3] in ('2.6', '3.0', '3.1') else []
setup(
version='0.2.1.dev0',
zip_safe | = True,
name = "seqfile",
author = "Utkarsh Upadhyay",
author_email = "musically.ut@gmail.com",
description = ("Find the next file in a sequence of files in a thread-safe way."),
license = "MIT",
keywords = "file threadsafe sequence",
ins... |
rodynnz/python-tfstate | unit_tests/test_tfstate/__init__.py | Python | lgpl-3.0 | 359 | 0.002786 | # -*- coding: utf-8 -*-
# Python stdlib
import unittest
# Unit tests
from unit_tests.test_tfstate import test_base, test_p | rovider
def suite():
suite = unittest.TestSuite()
suite.addTests(test_base.suite())
suite.addTests(test_provider.suite())
return suite
if __name__ == '__main__':
uni | ttest.TextTestRunner(verbosity=2).run(suite())
|
arthurdejong/python-stdnum | stdnum/rs/pib.py | Python | lgpl-2.1 | 1,963 | 0 | # pib.py - functions for handling Serbian VAT numbers
# coding: utf-8
#
# Copyright (C) 2017 Arthur de Jong
#
# This library 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 2.1 of the L... | eful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, wri | te to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
"""PIB (Poreski Identifikacioni Broj, Serbian tax identification number).
The Serbian tax identification number consists of 9 digits where the last
digit is a check digit.
>>> validate('101134702')
'101134702'
>>... |
philanthropy-u/edx-platform | openedx/features/idea/urls.py | Python | agpl-3.0 | 799 | 0.001252 | """
Urls for idea app
"""
from django.conf.urls import url
from openedx.features.idea.api_views import FavoriteAPIView
from openedx.features.idea.views import ChallengeLandingView, IdeaCreateView, IdeaDetailView, IdeaListingView
urlpatterns = [
url(
r'^overview/$',
ChallengeLandingView.as_view(),
... | ),
url(
r'^api/favorit | e/(?P<idea_id>[0-9]+)/$',
FavoriteAPIView.as_view(),
name='mark-favorite-api-view'
)
]
|
gamunax/pyhtongamunax | backend/apps/course_app/commands.py | Python | mit | 1,665 | 0.007207 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from gaebusiness.gaeutil import SaveCommand, ModelSearchCommand
from gaeforms.ndb.form import ModelForm
from gaegraph.business_base import UpdateNode
from course_app.model import Course
class CourseForm(ModelForm):
"""
Form used ... | "
_model_class = | Course
_include = [Course.price,
Course.creation,
Course.start_date,
Course.name]
class SaveCourseCommand(SaveCommand):
_model_form_class = CourseForm
class UpdateCourseCommand(UpdateNode):
_model_form_class = CourseForm
class ListCourseCommand(Model... |
ArneBab/pypyjs | website/demo/home/rfk/repos/pypy/lib-python/2.7/json/tests/test_dump.py | Python | mit | 738 | 0.004065 | from cStringIO import StringIO
from json.tests import PyTest, CTest
class TestDump(object):
def test_dump(self):
sio = StringIO()
self.json.dump({}, sio)
self.assertEqual(sio.getvalue(), '{}')
def test_dumps(self):
self.assertEqual(self.dumps({}), '{}')
def test_encode_tr... | {2: 3.0, 4.0: 5L, False: 1, 6L: True}, sort_keys=True),
'{"false": 1, "2": 3.0, "4.0": 5, "6": true}')
class TestPyDump(TestDump, PyTest): pass
class | TestCDump(TestDump, CTest): pass
|
danielmellado/tempest | tempest/api/compute/floating_ips/test_list_floating_ips_negative.py | Python | apache-2.0 | 1,698 | 0 | # Copyright 2012 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... | or the specific language governing permissions and limitations
# under the License.
import uuid
from tempest_lib.common.utils import data_utils
from tempest_lib import exceptions as lib_exc
from tempest.api.compute import base
from tempest import config
from tempest import test
CONF = config.CONF
class Floatin... | seV2ComputeTest):
@classmethod
def setup_clients(cls):
super(FloatingIPDetailsNegativeTestJSON, cls).setup_clients()
cls.client = cls.floating_ips_client
@test.attr(type=['negative'])
@test.idempotent_id('7ab18834-4a4b-4f28-a2c5-440579866695')
@test.services('network')
def test... |
LoneKirov/PyTrace | pytrace/__init__.py | Python | bsd-3-clause | 78 | 0.025641 | __all__ | = [ "command_statistics", "json_reader", "m | ongo", "sata", "xgig" ]
|
BackupGGCode/pkgcreator | pkgcreator/PkgCreator/console.py | Python | gpl-3.0 | 2,947 | 0.003054 | #@TODO: Support for html parsing!!
import sys
try:
from colorama import init, Fore, Back, Style
colorama = True
except ImportError:
colorama = False
__all__ = ["console"]
class Console:
def __init__(self):
self.reset()
self.color = False
def set_color(self, color):
self.... | elif self.center_width:
if center_ | char:
msg = msg.center(self.center_width, center_char)
else:
msg = msg.center(self.center_width, self.center_char)
if fill_up:
title = (fill_up * size) + "\n"
msg = title + msg
elif self.fill_up:
title = (self.fill_up * size... |
zqfan/leetcode | algorithms/563. Binary Tree Tilt/solution.py | Python | gpl-3.0 | 585 | 0 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.ri | ght = None
class Solution(object):
def findTilt(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def dfs(root):
if not root:
return 0
left = dfs(root.left)
right = dfs(root.right)
diff[0] += abs(left - righ... | turn diff[0]
|
Southpaw-TACTIC/Team | src/python/Lib/site-packages/psyco/kdictproxy.py | Python | epl-1.0 | 4,502 | 0.00422 | ###########################################################################
#
# Support code for the 'psyco.compact' type.
from __future__ import generators
try:
from UserDict import DictMixin
except ImportError:
# backported from Python 2.3 to Python 2.2
class DictMixin:
# Mixin def... | ef __contains__(self, key):
return self.has_key(key)
# third level takes advantage of s | econd level definitions
def iteritems(self):
for k in self:
yield (k, self[k])
def iterkeys(self):
return self.__iter__()
# fourth level uses definitions from lower levels
def itervalues(self):
for _, v in self.iteritems():
... |
yk5/incubator-airflow | airflow/api/common/experimental/mark_tasks.py | Python | apache-2.0 | 8,610 | 0.000697 | # -*- coding: utf-8 -*-
#
# 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
#... | stream:
relatives = task.get_flat_relatives(upstream=True)
task_ids += [t.task_id for t in relatives]
# verify the integrity of the dag runs in case a task was added or r | emoved
# set the confirmed execution dates as they might be different
# from what was provided
confirmed_dates = []
drs = DagRun.find(dag_id=dag.dag_id, execution_date=dates)
for dr in drs:
dr.dag = dag
dr.verify_integrity()
confirmed_dates.append(dr.execution_date)
# go... |
dogancankilment/UnixTools | utils/biology/storage_in_bacterias.py | Python | gpl-2.0 | 2,800 | 0.000357 | def save_bacteria_dna():
"""
0 = A,
1 = T,
2 = C,
3 = G
footnote:
>>>ord('c')
99
>>>chr(97)
'c'
same unichr() command
"""
char_list = []
binary_list = []
request_word = raw_input("Please enter the word,"
... | 4):
if tmp_str[j] == '0':
result_str += 'A'
if tmp_str[j] == '1':
result_str += 'T'
if tmp_str[j] == '2':
result_str += 'C'
if tmp_str[j] == '3':
result_str += 'G'
result_str += chr(10)
c... | in__':
save_bacteria_dna() |
MetaMemoryT/aiozmq | tests/rpc_pipeline_test.py | Python | bsd-2-clause | 8,374 | 0.000239 | import unittest
import asyncio
import aiozmq
import aiozmq.rpc
import logging
from unittest import mock
from asyncio.test_utils import run_briefly
from aiozmq._test_util import log_hook, RpcMixin
class MyHandler(aiozmq.rpc.AttrHandler):
def __init__(self, queue, loop):
self.queue = queue
self.lo... | aiozmq.rpc', self.err_queue):
yield from client.notify.func_error()
ret = yield from self.err_queue.get()
self.assertEqual(logging.ERROR, ret.levelno)
self.assertEqual("An exception %r from method %r "
"call occurred.\n"
... | t.args)
self.assertIsNotNone(ret.exc_info)
self.loop.run_until_complete(communicate())
def test_default_event_loop(self):
asyncio.set_event_loop_policy(aiozmq.ZmqEventLoopPolicy())
self.addCleanup(asyncio.set_event_loop_policy, None)
self.addCleanup(self.loop.close... |
akx/coffin | coffin/management/commands/makemessages.py | Python | bsd-3-clause | 2,126 | 0.000941 | """Jinja2's i18n functionality is not exactly the same as Django's.
In particular | , the tags names and their syntax are different:
1. The Django ``trans`` tag is replaced by a _() global.
2. The Django ``blocktrans`` tag is called ``trans``.
(1) isn't an issue, since the whole ``makemessages`` process is based | on
converting the template tags to ``_()`` calls. However, (2) means that
those Jinja2 ``trans`` tags will not be picked up my Django's
``makemessage`` command.
There aren't any nice solutions here. While Jinja2's i18n extension does
come with extraction capabilities built in, the code behind ``makemessages``
unfortu... |
abrenaut/mrot | mrot/imdb.py | Python | mit | 6,223 | 0.002732 | # -*- coding: utf-8 -*-
import logging
import re
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from PIL import Image
from urllib.request import urlopen
from urllib.parse import urlencode
import json
from bs4 import BeautifulSoup, element
from datetime import datetime, timedelta
from waybackscraper.... | ttp://www.omdbapi.com/?{query}'
IMDB_MOVIE_TEMPLATE = "http://www.imdb.com/ti | tle/{movie_id}/"
IMDB_NO_POSTER = 'http://www.imdb.com/images/nopicture/medium/video.png'
class IMDbMovie(object):
def __init__(self, title, year, imdb_id, poster):
self.title = title
self.year = year
self.imdb_id = imdb_id
self.poster = poster
def download_ratings(self, concu... |
mwiencek/picard | picard/ui/options/fingerprinting.py | Python | gpl-2.0 | 3,809 | 0.001576 | # -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
# Copyright (C) 2011 Lukáš Lalinský
#
# 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... | .clicked.connect(self.acoustid_fpcalc_browse)
self.ui.acoustid_fpcalc_download.clicked.connect(self.acoustid_fpcalc_download)
self.ui.acoustid_apikey_get.clicked.connect(self.acoustid_apikey_get)
def load(self):
if self.config.setting["fingerprinting_system"] == "acoustid":
self... | erprinting.setChecked(True)
self.ui.acoustid_fpcalc.setText(self.config.setting["acoustid_fpcalc"])
self.ui.acoustid_apikey.setText(self.config.setting["acoustid_apikey"])
self.update_groupboxes()
def save(self):
if self.ui.use_acoustid.isChecked():
self.config.setting["... |
kearnsw/Twitt.IR | src/VaderSentiment.py | Python | gpl-3.0 | 1,714 | 0.001167 | from pymongo import MongoClient
from vaderSentiment.vaderSentiment import sentiment as vs
import os
# File for writing sentiment for storage and analysis
__location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
outputFile = "sentiment.json"
f = open(os.path.join(__location__, outputFile), ... | Feb": 2, "Mar": 3, "Apr": 4, "May": 5,
"Jun": 6, "Jul": 7, "Aug": 8, "Sep": 9, "Oct": 10,
"Nov": 11, "Dec": 12}
docs = []
for document in cursor:
# Convert time from Tue Mar 29 04:04:22 +0000 2016 to 2016-3-29
time = document["created_at"].split()
month = months[time[1]]
day = time[... | date = str(year) + "-" + str(month) + "-" + str(day)
docs.append({"text": document["text"],
"date": '"' + date + '"'})
aggregate = {}
count = {}
for doc in docs:
text = doc["text"].encode('utf-8')
sentiment = vs(text)
value = (sentiment['neg'] * -1) + (sentiment['pos'])
if doc["d... |
TheWaWaR/scrapy-snippets | projects/unity3d/unity3d/pipelines.py | Python | mit | 261 | 0 | # Define your item pipelines here
#
# Don | 't f | orget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
class Unity3DPipeline(object):
def process_item(self, item, spider):
return item
|
sanchopanca/rcblog | run.py | Python | mit | 60 | 0 | import | rcblog
if __name__ == '__main__': |
rcblog.main()
|
NESCent/feedingdb | debug-inspector-panel/runtests.py | Python | gpl-3.0 | 808 | 0.001238 | import os
import sys
from django.conf import settings
if not settings.configured:
settings_dict = dict(
INSTALLED_APPS=(
#'django.contrib.contenttypes',
'inspector_panel',
'inspector_panel.tests',
),
DATABASES={
| "default": {
"ENGINE": "django.db.backends.sqlite3"
}
},
)
settings.configure(**settings_dict)
def runtests(*test_args):
if not test_args:
test_args = ['tests']
parent = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, par | ent)
from django.test.simple import DjangoTestSuiteRunner
failures = DjangoTestSuiteRunner(
verbosity=1, interactive=True, failfast=False).run_tests(test_args)
sys.exit(failures)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.