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 |
|---|---|---|---|---|---|---|---|---|
ddurieux/alignak | test/alignak_modules.py | Python | agpl-3.0 | 10,473 | 0.004774 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2015-2015: Alignak team, see AUTHORS.txt file for contributors
#
# This file is part of Alignak.
#
# Alignak 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 So... | shutil
import datetime # not used but "sub-"imported by livestatus test.. (to be corrected..)
import sys # not here used but "sub-"imported by livestatus test.. (to be corrected..)
#
from alignak.modulesctx import modulesctx
from alignak.objects.module import Module
from alignak.modulesmanager import ModulesManager
fr... | ak.misc.datamanager import datamgr
from alignak.log import logger
#
from alignak_test import (
modules_dir,
alignakTest,
time_hacker, # not used here but "sub"-imported by lvestatus test (to be corrected)
)
modulesctx.set_modulesdir(modules_dir)
# Special Livestatus module opening since the module renam... |
mjiang-27/django_learn | template_III/template_III/urls.py | Python | gpl-3.0 | 1,076 | 0.003717 | """template_III URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/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')
Cla... | rl(r'^admin/', admin.site.urls),
url(r'^$', app_views.home, name='home'), # new
url(r'^add/(\d+)/(\d+)/$', app_views.add, name='add'), # new
# if method is replaced with method sum below, the app can still works fine
# url(r'^sum/(\d+)/(\d+)/$', app_views. | add, name='add'), # new
]
|
kustomzone/Rusthon | regtests/go/loop_arrays.py | Python | bsd-3-clause | 677 | 0.116691 | '''
array loop
'''
def main():
a = [1,2,3]
y = 0
for x in a:
y += x
TestError( y==6 )
z = ''
arr = ['a', 'b', 'c']
for v in arr:
z += v
TestError( z == 'abc' )
b = 0 |
for i in range(10):
b += 1
TestError( b == 10 )
b2 = 0
for i in range(5, 10):
b2 += 1
TestError( b2 == 5 )
c = ''
d = 0
for i,v in enumerate(arr):
c += v
d += i
TestError( c == 'abc' )
e = 0
for i in range( len(arr) ):
e += 1
TestError( e == 3 )
| s = a[:2]
#print('len of s:')
#print(len(s))
TestError( len(s)==2 )
s2 = a[2:]
#print('len of s2:')
#print(len(s2))
#print(s2[0])
TestError( len(s2)==1 )
#e = 0
#for i in s:
# e += i
#TestError( e == 3 )
|
globocom/vault | actionlogger/actionlogger.py | Python | apache-2.0 | 1,424 | 0 | # -*- coding: utf-8 -*-
import syslog
from .models import Audit
class ActionNotFound(Exception):
pass
class ActionLogger:
""" A wrapper to log actions """
def __init__(self):
self._actions = {
"create": "Criou",
"update": "Atualizou",
"delete": "Removeu",
... | "set_private": "Setou container como privado",
"set_public": "Setou container como publico",
}
def log(self, user, action, item):
if action not in self._actions.keys():
raise ActionNotFound("Invalid action: '{}'".format(action))
audit = Audit(user=user,
... | syslog.syslog(syslog.LOG_INFO, msg)
def _make_log_message(self, user, action, item):
return 'Usuario {} {} {}'.format(user,
self._actions[action],
str(item))
|
ciudadanointeligente/check-it | promises_web/tests/tags_extra_css_tests.py | Python | gpl-3.0 | 1,786 | 0.008399 | from django.test import TestCase
from django.utils.timezone import now
from promises.models import Promise, Category
from popolo.models import Person
from taggit.models import Tag
from ..models import TagExtraCss
nownow = now()
class TagsExtraCssTestCase(TestCase):
def setUp(self):
self.person = Person.ob... | cts.create(name=u"A person")
self. | category = Category.objects.create(name="Education")
self.promise = Promise.objects.create(name="this is a promise",\
description="this is a description",\
date = nownow,\
person = self.per... |
opennewzealand/linz2osm | linz2osm/workslices/migrations/0004_auto__add_field_workslicefeature_layer_in_dataset.py | Python | gpl-3.0 | 7,883 | 0.00685 | # -*- coding: utf-8 -*-
# LINZ-2-OSM
# Copyright (C) 2010-2012 Koordinates 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 3 of the License, or
# (at your option) an... | odels.fields.CharField', [], {'unique': 'True', 'max_length': '255', 'primary_key': 'True'}),
'srid': ('django.db.models.fields.IntegerField', [], {})
},
'data_dict.layer': {
'Meta': {'object_name': 'Layer'},
'datasets': ('django.db.models.fi | elds.related.ManyToManyField', [], {'to': "orm['data_dict.Dataset']", 'through': "orm['data_dict.LayerInDataset']", 'symmetrical': 'False'}),
'entity': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '200', 'blank': 'True'}),
'name': ('django.db.models.fields.CharFie... |
udacity/nose2-gae | tests/bad_app/bad_app.py | Python | lgpl-3.0 | 460 | 0.01087 | import socket
import wsgiref.handlers
class App:
def __call__( | self, environ, start_response):
# This won't work under GAE, since this is app code
here = socket.gethostbyname('localhost')
start_response('200 OK', [('Content-type', 'text/plain')])
return ['Hello %s' % here]
|
def application():
return App()
def main():
wsgiref.handlers.CGIHandler().run(application())
if __name__ == '__main__':
main()
|
bryan-lunt/execnet | testing/test_fixes.py | Python | mit | 1,009 | 0 | from execnet import Group
from execnet.gateway_bootstrap import fix_pid_for_jython_popen
def test_jython_bootstrap_not_on_remote():
group = Group()
try:
group.makegateway('popen//id=via')
group.makegateway('popen//via=via')
finally:
group.terminate(timeout=1.0)
def test_jython_bo... | othing happens when calling it on a normal seyup
fix_pid_for_jython_popen(gw)
assert popen.pid == real_pid
# if there is no pid for a popen gw, restore
popen.pid = None
fix_pid_for_jython_popen(gw)
assert popen.pid == real_pid
# if there is no pid for other gw, ... | popen.pid = real_pid
group.terminate(timeout=1)
|
jrbourbeau/composition | save_sim/save_sim.py | Python | mit | 4,424 | 0.000678 | #!/bin/sh /cvmfs/icecube.opensciencegrid.org/py2-v1/icetray-start
#METAPROJECT /data/user/jbourbeau/metaprojects/icerec/V05-00-00/build
import numpy as np
import time
import glob
import argparse
import os
from icecube import dataio, toprec, dataclasses, icetray, phys_services
from icecube.frame_object_diff.segments i... | .__class__ == dataclasses.I3RecoPu | lseSeriesMapMask:
# VEMpulses = VEMpulses.apply(frame)
#
# for om, pulses in VEMpulses:
# n_channels += 1
# for pulse in pulses:
# q_tot += pulse.charge
#
# frame.Put('InIce_charge', dataclasses.I3Double(q_to... |
klette/comics | comics/comics/applegeekslite.py | Python | agpl-3.0 | 688 | 0.002907 | from comics.aggregator.crawler import CrawlerBase, CrawlerImage
from comics.meta.base import MetaBase
class Meta(MetaBase):
n | ame = 'AppleGeeks Lite'
language = 'en'
url = 'http://www.applegeeks.com/'
start_date = '2006-04-18'
rights = 'Mohammad Haque & Ananth Panagariya'
class Crawler(CrawlerBase):
history_capable_days = 30
schedule = | None
time_zone = -5
def crawl(self, pub_date):
feed = self.parse_feed('http://www.applegeeks.com/rss/?cat=lite')
for entry in feed.for_date(pub_date):
url = entry.summary.src('img')
title = entry.title.replace('AG Lite - ', '')
return CrawlerImage(url, title)... |
modelbrouwers/modelbouwdag.nl | src/modelbouwdag/exhibitors/migrations/0003_auto_20160409_2153.py | Python | mit | 448 | 0 | # -*- | coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('exhibitors', '0002_auto_20160409_2110'),
]
operations = [
migratio | ns.AlterField(
model_name='exhibitorlistplugin',
name='for_event',
field=models.ForeignKey(to='events.Event', verbose_name='event'),
),
]
|
gdementen/PyTables | bench/table-bench.py | Python | bsd-3-clause | 16,167 | 0.003835 | #!/usr/bin/env python
from __future__ import print_function
import numpy as NP
from tables import *
# This class is accessible only for the examples
class Small(IsDescription):
var1 = StringCol(itemsize=4, pos=2)
var2 = Int32Col(pos=1)
var3 = Float64Col(pos=0)
# Define a user record to characterize som... | signed short integer
ADCcount = Int32Col(pos=6) # signed short integer
grid_i = Int32Col(pos=7) # integer
grid_j = Int32Col(pos=8) # integer
pressure = Float32Col(pos=9) # float (single-precision)
energy = Float64Col(pos=2) # doubl... | a user record to characterize some kind of particles
class Big(IsDescription):
name = StringCol(itemsize=16) # 16-character String
float1 = Float64Col(shape=32, dflt=NP.arange(32))
float2 = Float64Col(shape=32, dflt=2.2)
TDCcount = Int8Col() # signed short integer
#AD... |
fin/froide | froide/publicbody/migrations/0024_auto_20181114_1516.py | Python | mit | 556 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.15 on 2018-11-14 14:16
from __future__ import unicode_literals
from django.db import migrations
def move_region_to_regions(apps, schema_editor):
PublicBody = apps.get_model("publicbody", "PublicBody")
for pb in PublicBody.objects.filter(region__isnull=False | ):
| pb.regions.add(pb.region)
class Migration(migrations.Migration):
dependencies = [
("publicbody", "0023_auto_20181114_1515"),
]
operations = [
migrations.RunPython(move_region_to_regions),
]
|
michaelrosejr/pyaos6 | netmiko/checkpoint/checkpoint_gaia_ssh.py | Python | mit | 774 | 0 | from __future__ import unicode_literals
from netmiko.base_connection import BaseConnection
class CheckPointGaiaSSH(BaseConnection):
"""
Implements methods for communicating with Check Point Gaia
firewalls.
"""
def session_preparation(self):
"""
Prepare the session after the connect... | ""
self._test_channel_read()
self.set_base_prompt()
self.disable_paging(command="set clienv rows 0\n")
def config_mode(self, config_command=''):
"""N | o config mode for Check Point devices."""
return ''
def exit_config_mode(self, exit_config=''):
"""No config mode for Check Point devices."""
return ''
|
belangeo/pyo | tests/test_Expr_object/expr_test_07_load.py | Python | lgpl-3.0 | 678 | 0.001475 | from pyo import *
s = Server().boot()
s.amp = 0.1 |
TEST = 2
if TEST == 0:
t = """
(load utils.expr) // scalef
(load generators.expr) // osc, pwm
(pwm 110
(scalef (osc 0.2) 0.05 0.95)
)
"""
ex = Expr(Sig | (0), t).out()
elif TEST == 1:
t = """
(load generators.expr) // square
(load filters.expr) //notch
(notch (square 86) 5000 0.75)
"""
ex = Expr(Sig(0), t).out()
elif TEST == 2:
t = """
(load utils.expr) // scalef
(load generators.expr) // noise
(load filters.expr) // peak
(peak (noise 0.5) ... |
alvico/solaris | solaris/helpers.py | Python | bsd-2-clause | 1,048 | 0 | import fileinput
import itertools
import subprocess
def insert_line_file(file, new_line, anchor):
insert = False
for line in fileinput.input(file, inplace=1):
if line.startswith(anchor):
insert = True
else:
if insert:
print new_line
insert = ... | lse
print line
def insert_line_after(content, new_line, anchor):
i = 0
new_content = []
for line in content:
i += 1
if line.startswith(anchor):
head = itertools.islice(content, i)
tail = iter(())
if len(content) > 1:
tail = iterto... | new_content
def docker_exec(cmd, container, usr="root"):
full_cmd = "docker exec --user {0} {1} {2}".format(usr, container, cmd)
# subprocess.call(full_cmd, shell=True)
p = subprocess.Popen(full_cmd, stdout=subprocess.PIPE, shell=True)
return p.communicate()
|
zimeon/iiif | tests/test_auth_basic.py | Python | gpl-3.0 | 3,828 | 0.000522 | """Test code for iiif.auth_basic.
See http://flask.pocoo.org/docs/0.10/testing/ for Flask notes.
"""
from flask import Flask, request, make_response, redirect
from werkzeug.datastructures import Headers
import base64
import json
import re
import unittest
from | iiif.auth_basic import IIIFAuthBasic
dummy_app = Flask('dummy')
class TestAll(unittest.TestCase):
"""Tests."""
def setUp(self):
"""Set up dummy app."""
self.app = dummy_app.test_client()
def tearDown(self):
"""No op."""
pass
def test0 | 1_init(self):
"""Test inialization."""
auth = IIIFAuthBasic()
self.assertTrue(re.match(r'\d+_', auth.cookie_prefix))
auth = IIIFAuthBasic(cookie_prefix='abc')
self.assertEqual(auth.cookie_prefix, 'abc')
def test02_logout_service_description(self):
"""Test logout_serv... |
Sorsly/subtle | google-cloud-sdk/lib/surface/functions/describe.py | Python | mit | 2,021 | 0.002474 | # Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | client = self.context['functions_client']
messages = self.context['functions_messages']
project = properties.VALUES.core.project.Get(required=Tru | e)
registry = self.context['registry']
function_ref = registry.Parse(
args.name, params={'projectsId': project, 'locationsId': args.region},
collection='cloudfunctions.projects.locations.functions')
# TODO(user): Use resources.py here after b/21908671 is fixed.
return client.projects_lo... |
joeatwork/python-lzw | tests/__init__.py | Python | mit | 36 | 0 | # Put your tests in this direc | tory.
| |
wegamekinglc/alpha-mind | alphamind/tests/test_suite.py | Python | mit | 4,079 | 0.001716 | # -*- coding: utf-8 -*-
"""
Created on 2017-4-25
@author: cheng.li
"""
import os
SKIP_ENGINE_TESTS = True
if not SKIP_ENGINE_TESTS:
try:
DATA_ENGINE_URI = os.environ['DB_URI']
except KeyError:
DATA_ENGINE_URI = "mysql+mysqldb://reader:Reader#2020@121.37.138.1:13317/vision?char... | d.utilities import alpha_logger
from alphamind.tests.data.test_neutralize import TestNeutralize
from alphamind.tests.data.test_standardize import TestStandardize
from alphamind.tests.data.test_winsorize import TestWinsorize
from alphamind.tests.data.test_quantile import TestQuantile
from alpham... | alphamind.tests.portfolio.test_constraints import TestConstraints
from alphamind.tests.portfolio.test_evolver import TestEvolver
from alphamind.tests.portfolio.test_longshortbuild import TestLongShortBuild
from alphamind.tests.portfolio.test_rankbuild import TestRankBuild
from alphamind.tests.portfo... |
nthitz/dreamlastnight | pgutils.py | Python | mit | 1,920 | 0.0125 | #collection of stuff to make postgres easier
import psycopg2
import os
pgConnectionString = "dbname=" + os.environ['PGNAME'] + " user=" + os.environ['PGUSER'] + " password=" + os.environ['PGPASS']
pg = psycopg2.connect(pgConnectionString)
pgCursor = pg.cursor()
def close():
pg.commit()
pgCursor.close()
pg... | on, valueKey,cached = True):
requestRelation(relation, valueKey, cached)
return savedRelations[relation]['keys']
def getRelationByValues(relation, valueKey,cached = True):
requestRelation(relation, valueKey, cached)
return savedRelations[relation]['values']
def getQueryDictionary(q,*arg):
pgCursor.... | column = description[i].name
tuple = result[i]
resultMap[column] = tuple
results.append(resultMap)
return results
def requestRelation(relation, valueKey, cached = True):
global savedRelations
# if a cached request is ok
if cached:
#and we have a cached req... |
domluna/ml_p5_capstone | filters.py | Python | mit | 1,135 | 0.003524 | """Filters"""
from skimage.color import rgb2gray
from skimage.transform import resize
import numpy as np
from | modular_rl import *
class ObFilterFF(object):
def __init__(self, new_width, new_height):
self.w = new_width
self.h = new_height
self.f = Flatten()
def __call__(self, ob):
out = resize(rgb2gray(ob), (self.h, s | elf.w))
return self.f(out)
def output_shape(self, input_shape):
return (self.h * self.w,)
class ObFilterCNN(object):
def __init__(self, new_width, new_height):
self.w = new_width
self.h = new_height
def __call__(self, ob):
out = resize(rgb2gray(ob), (self.h, self.w... |
Orav/kbengine | kbe/src/lib/python/Lib/tabnanny.py | Python | lgpl-3.0 | 11,731 | 0.001961 | #! /usr/bin/env python3
"""The Tab Nanny despises ambiguous indentation. She knows no mercy.
tabnanny -- Detection of ambiguous indentation
For the time being this module is intended to be called as a script.
However it is possible to import it into an IDE and use the function
check() described below.
Wa... | in which
# case it will return at least one witnessing tab size.
def not_equal_witness(self, other):
n = max(self.longest_run_of_spaces(),
other.longest_run_of_spaces()) + 1
| a = []
for ts in range(1, n+1):
if self.indent_level(ts) != other.indent_level(ts):
a.append( (ts,
self.indent_level(ts),
other.indent_level(ts)) )
return a
# Return True iff self.indent_level(t) < other.... |
hip-odoo/odoo | addons/website_portal/controllers/main.py | Python | agpl-3.0 | 4,979 | 0.002008 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import http
from odoo.http import request
from odoo import tools
from odoo.tools.translate import _
from odoo.fields import Date
class website_account(http.Controller):
MANDATORY_BILLING_FIELDS = ["name... | begin, date_end = dates.split('/')
| groups.append({
'date_begin': Date.to_string(Date.from_string(date_begin)),
'date_end': Date.to_string(Date.from_string(date_end)),
'name': label,
'item_count': group[groupby + '_count']
})
return groups
@http.route(['/my'... |
telminov/knowledge-base | kb/data.py | Python | mit | 1,498 | 0.004633 | __author__ = 'g10k'
"""Потом убрать в миграции"""
# ('Регистраторы','Регистраторы'),
# ('Менеджеры','Менеджеры'),
# ('Проф департамент','Проф департамент'),
# ('Аналитика','Аналитика'),
# ('Контроль качества','Контроль качества'),
import kb.models
departaments = {
'Регистра... | nfo in departaments.items():
for app in set_apps:
kb.models.App.objects.get_or_create(name=app)
apps = info.get('apps')
color = info.get('color')
departament, created = kb.models.Departament.objects.get_or_create(name=department_name)
app_objects = kb.models | .App.objects.filter(name__in=apps)
departament.apps.set(app_objects, clear=True)
departament.color = color
departament.save()
|
kennethd/moto | moto/ec2/responses/elastic_ip_addresses.py | Python | apache-2.0 | 6,068 | 0.003461 | from __future__ import unicode_literals
from moto.core.responses import BaseResponse
from moto.ec2.utils import sequence_from_querystring
class ElasticIPAddresses(BaseResponse):
def allocate_address(self):
if "Domain" in self.querystring:
domain = self.querystring.get('Domain')[0]
else... | self.ec2_backend.address_by_ip(public_ips)
elif "AllocationId.1" in self.querystring:
allocation_ids = sequence_from_querystring("AllocationId", self.querystring)
addresses = self.ec2_backend.address_by_allocation(allocation_ids)
else:
addresses = self.ec2_backend.des... | icIp" in self.querystring:
self.ec2_backend.disassociate_address(address=self.querystring['PublicIp'][0])
elif "AssociationId" in self.querystring:
self.ec2_backend.disassociate_address(association_id=self.querystring['AssociationId'][0])
else:
self.ec2_backend.raise_... |
jwadden/django-sharding | django_sharding_library/constants.py | Python | bsd-3-clause | 161 | 0 | class | Backends(object):
MYSQL = 'django.db.backends.mysql'
POSTGRES = 'django.db.backends.postgresql_psycopg2'
SQLITE = 'django.db.backends.sq | lite3'
|
yqowen/odatapy-client | codegen_template.py | Python | mit | 34,379 | 0.002443 | # OData Python Client and Server Libraries ver. 1.0.0
# Copyright (c) Microsoft Corporation
# All rights reserved.
# MIT License
# 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 re... | if complex i | s None or self._{0} is None:
return
complex_type = odata_client_python.to_complex_type(complex.get_value_type())
if complex_type is None:
return
edm_property = complex_type.find_property("{1}")
if edm_property is None:
return
property_type = ed... |
dvarrazzo/Pyrseas | tests/augment/test_audit.py | Python | bsd-3-clause | 12,757 | 0 | # -*- coding: utf-8 -*-
"""Test audit columns"""
import pytest
from pyrseas.testutils import AugmentToMapTestCase
CREATE_STMT = "CREATE TABLE t1 (c1 integer, c2 text)"
FUNC_SRC1 = """
BEGIN
NEW.modified_by_user = SESSION_USER;
NEW.modified_timestamp = CURRENT_TIMESTAMP;
RETURN NEW;
END"""
FUNC_SRC2 = """
BEGI... | 'not_null': True}},
{'modified_timestamp': {'type': 'timestamp with time zone',
'not_null': True}}]
assert expmap == dbmap['schema public']['table t1']['columns']
def test_change_existing_columns(self):
"Change already existing audit c... | TABLE t1 ADD modified_timestamp "
"timestamp with time zone NOT NULL"]
augmap = {'schema public': {'table t1': {'audit_columns': 'default'}}}
dbmap = self.to_map(stmts, augmap)
expmap = [{'c1': {'type': 'integer'}}, {'c2': {'type': 'text'}},
{'modified_by_user... |
ikanor/typeschema | tests/typeschema_test.py | Python | mit | 237 | 0 | import doctest
import unittest
import typeschema
class TestCase(unittest.TestCase):
def test_doc(self): |
fails, tested | = doctest.testmod(typeschema.typeschema)
if fails > 0:
self.fail('Doctest failed!')
|
cincinnatusc123/jbrowse | bin/list_interval_tables.py | Python | lgpl-2.1 | 1,553 | 0.025113 | #!/usr/bin/python
import cgi
import simplejson as json
import os
import os.path
import shutil
import sys
sys.path.append(".. | /lib")
import GlobalConfig
import utils
import time
from subprocess import Popen, PIPE
err_filename = "%s/list_tables_error.txt" % (GlobalConfig.DEBUG_DIR)
sys.stderr = open( err_filename,'w')
out_filename = "%s/list_tables_output.txt" % (GlobalConfig.DEBUG_DIR)
sys.stdout = open( | out_filename,'w')
fields = cgi.FieldStorage()
project_name = fields.getvalue("project_name")
print "project_name", project_name
utils.printToServer( 'Content-type: text/json\n\n' )
#path = "%s/data/tracks/%s%s/interval_tables" % \
#(GlobalConfig.ROOT_DIR, \
#GlobalConfig.PROJECT_PREFIX, \
... |
xu6148152/Binea_Python_Project | wikiSpider/wikiSpider/pipelines.py | Python | mit | 290 | 0 | # -*- coding: utf-8 -*-
# Define your item pipelines here
| #
# Don't forget to add your pipeline to the ITEM | _PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
class WikispiderPipeline(object):
def process_item(self, item, spider):
return item
|
v-iam/azure-sdk-for-python | azure-mgmt-compute/azure/mgmt/compute/compute/v2017_03_30/models/resource_sku_restrictions.py | Python | mit | 1,903 | 0.000525 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporatio | n. 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 cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------... | Variables are only populated by the server, and will be ignored when
sending a request.
:ivar type: The type of restrictions. Possible values include: 'location'
:vartype type: str or :class:`ResourceSkuRestrictionsType
<azure.mgmt.compute.compute.v2017_03_30.models.ResourceSkuRestrictionsType>`
... |
xorpaul/shinken | test/test_antivirg.py | Python | agpl-3.0 | 3,398 | 0.013537 | #!/usr/bin/env python
# -*- coding: utf-8 -*
from shinken_test import *
class TestConfig(ShinkenTest):
def setUp(self):
# load the configuration from file
self.setup_with_file('etc/nagios_antivirg.cfg')
def test_hostname_antivirg(self):
"""Check that it is allowed to have a host with... | )
# We can send a command by escaping the semicolon.
command = '[%lu] PROCESS_HOST_CHECK_RESULT;test_host_2\;with_semicolon;2;down' % (time.time())
self.sched.run_external_command(command)
# can need 2 run for get the consu | m (I don't know why)
self.scheduler_loop(1, [])
self.scheduler_loop(1, [])
if '__main__' == __name__:
unittest.main()
|
salamb/girder | girder/api/v1/file.py | Python | apache-2.0 | 17,532 | 0.000285 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# Copyright 2013 Kitware 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 cop... | ffset)
self.route('GET', (':id',), self.getFile)
self.route('GET', (':id', 'download'), self.download)
self.route('GET', (':id', 'download', ':name'), self.downloadWithName)
self.route('POST', (), self.initUpload)
self.route('POST', ('chunk',), | self.readChunk)
self.route('POST', ('completion',), self.finalizeUpload)
self.route('POST', (':id', 'copy'), self.copy)
self.route('PUT', (':id',), self.updateFile)
self.route('PUT', (':id', 'contents'), self.updateFileContents)
@access.public(scope=TokenScope.DATA_READ)
@loadm... |
wdv4758h/flake8 | flake8/_pyflakes.py | Python | mit | 4,605 | 0.000217 | # -*- coding: utf-8 -*-
try:
# The 'demandimport' breaks pyflakes and flake8._pyflakes
from mercurial import demandimport
except ImportError:
pass
else:
demandimport.disable()
import os
import pep8
import pyflakes
import pyflakes.checker
def patch_pyflakes():
"""Add error codes to Pyflakes messag... |
if options.builtins:
cls.builtIns = cls.builtIns.union(options.builtins.split(','))
cls.withDoctest = options.doctests
included_files = []
for included_file in options.include_in_doctest.split(','):
if included_file == '':
| continue
if not included_file.startswith((os.sep, './', '~/')):
included_files.append('./' + included_file)
else:
included_files.append(included_file)
cls.include_in_doctest = pep8.normalize_paths(','.join(included_files))
excluded_files = ... |
digitalmacgyver/vedit | examples.py | Python | mit | 16,762 | 0.019687 | #!/usr/bin/env python
import glob
import os
import random
import vedit
import logging
logging.basicConfig()
log = logging.getLogger()
log.setLevel( logging.DEBUG )
def example01():
'''Clip 2 seconds out of the middle of a video.'''
# Clipping 2 seconds out of source video from 1.5 seconds to 3.5 second... | audio track).
#
# Note - if the window audio track is longer than the video
# content, it fades out starting 5 seconds from the end.
window = vedit.Window( audio_file="./examples/a2.mp4", duration=10,
output_file=output_file )
window.clips = [ clip ]
window.render()
... | ion = '''This video features the song:
Chuckie Vs Hardwell Vs Sandro Silva Vs Cedric & Quintino
EPIC CLARITY JUMP- (NC MASHUP) LIVE
By: NICOLE CHEN
Available under under a Creative Commons License:
http://creativecommons.org/licenses/by/3.0/ license'''
output_file = "./example_output/example04-attributed.mp4"
... |
sde1000/quicktill | quicktill/modifiers.py | Python | gpl-3.0 | 4,594 | 0.004354 | from . import ui, td, user, linekeys, keyboard
from .models import KeyboardBinding
from decimal import Decimal
import inspect, itertools
import logging
log = logging.getLogger(__name__)
class Incompatible(Exception):
def __init__(self, msg=None):
self.msg = msg
# Dictionary of all registered modifiers, al... | super().keypress(k)
def deletebinding(se | lf):
log.debug("modifier deletebinding: cursor is %s", self.s.cursor)
if self.s.cursor is None:
return
line = self.s.dl.pop(self.s.cursor)
self.s.redraw()
td.s.add(line.userdata)
td.s.delete(line.userdata)
td.s.flush()
def defined_modifiers():
"""... |
mediachain/mediachain-client | multihash/__init__.py | Python | mit | 121 | 0 | from mult | ihash import SHA1, SHA2_256, SHA2_512, SHA3, BLAKE2B, BLAKE2S, \
decode, encode, i | s_valid_code, is_app_code
|
yajiedesign/mxnet | tests/python/unittest/test_operator.py | Python | apache-2.0 | 407,016 | 0.007034 | # 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... | #
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.... | print_function
from __future__ import division
import numpy as np
import mxnet as mx
import copy
import math
import random
import itertools
from distutils.version import LooseVersion
from numpy.testing import assert_allclose, assert_array_equal
from mxnet.test_utils import *
from mxnet.operator import *
from mxnet.bas... |
grevutiu-gabriel/sympy | sympy/assumptions/handlers/common.py | Python | bsd-3-clause | 3,168 | 0.000316 | from sympy.core.logic import _fuzzy_group
from sympy.logic.boolalg import conjuncts
from sympy.assumptions import Q, ask
class AskHandler(object):
"""Base class that all Ask Handlers must inherit"""
pass
class CommonHandler(AskHandler):
"""Defines some useful methods common to most Handlers """
@st... | ve unless otherwise stated"""
assumps = conjuncts(assumptions)
if expr.is_commutative is not None:
return expr.is_commutative and not ~Q.commutative(expr) in assumps
if Q.commutative(expr) in assumps:
return True
elif ~Q.commutative(expr) in assumps:
r... | tive(arg), assumptions):
return False
return True
Number, NaN = [staticmethod(CommonHandler.AlwaysTrue)]*2
class TautologicalHandler(AskHandler):
"""Wrapper allowing to query the truth value of a boolean expression."""
@staticmethod
def bool(expr, assumptions):
return... |
glaudsonml/kurgan-ai | tools/sqlmap/plugins/dbms/maxdb/__init__.py | Python | apache-2.0 | 1,033 | 0.001936 | #!/usr/bin/env python
"""
Copyright (c) 2006-2016 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission
"""
from lib.core.enums import DBMS
from lib.core.settings import MAXDB_SYSTEM_DBS
from lib.core.unescaper import unescaper
from plugins.dbms.maxdb.enumeration import Enumeration
... | = MAXDB_SYSTEM_DBS
Syntax.__init__(self)
Fingerprint.__init__(self)
Enumeration.__init__(self)
Filesystem.__init__(self)
Miscellaneous.__init__(self)
Takeover.__init__(self)
unescaper[DBMS.M | AXDB] = Syntax.escape
|
drzunny/hydrus | hydrus/__init__.py | Python | bsd-2-clause | 131 | 0 | # -*- coding:utf8 -*-
from . import server
__VERSION__ = server.__VERS | ION__
__author__ = 'drz' |
__email__ = 'drzunny@hotmail.com'
|
nagyistoce/devide | modules/vtk_basic/vtkImageAnisotropicDiffusion2D.py | Python | bsd-3-clause | 517 | 0.001934 | # class generated by DeVIDE::createDeVIDEModuleFromVTKObject
f | rom module_kits.vtk_kit.mixins import SimpleVTKClassModuleBase
import vtk
class vtkImageAnisotropicDiffusion2D(SimpleVTKClassModuleBase):
def __init__(self, module_manager):
SimpleVTKClassModuleBase.__init__(
self, module_manager,
vtk.vtkImageAnisotropicDiffusion2D(), 'Processing.',... | ('vtkImageData',),
replaceDoc=True,
inputFunctions=None, outputFunctions=None)
|
oemof/examples | oemof_examples/oemof.solph/v0.4.x/emission_constraint/emission_constraint.py | Python | gpl-3.0 | 2,523 | 0 | # -*- coding: utf-8 -*-
"""
General description
-------------------
Example that shows how to add an emission constraint in a model.
Installation requirements
-------------------------
This example requires the version v0.3.x of oemof. Install by:
pip install 'oemof.solph>=0.4,<0.5'
"""
__copyright__ = "oemof ... | _ = "MIT"
import pandas as pd
from oemof import solph
from oemof.solph import constraints
try:
import matplotlib.pyplot as plt
except ImportError:
plt = None
# create energy system
energysystem = solph.EnergySystem(
timeindex=pd.date_range("1/1/2012", periods=3, freq="H")
)
# create gas bus
bgas = solph... | source object representing biomass plants
energysystem.add(
solph.Source(
label="biomass",
outputs={
bel: solph.Flow(
nominal_value=100,
variable_costs=10,
emission_factor=0.01,
fix=[0.1, 0.2, 0.3],
)
},... |
maciekswat/Twedit | Plugins/CC3DMLHelper/celltypedlg.py | Python | gpl-3.0 | 4,555 | 0.023491 | import re
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import PyQt4.QtCore as QtCore
import ui_celltypedlg
import sys
import string
MAC = "qt_mac_set_native_menubar" in dir()
class CellTypeDlg(QDialog,ui_celltypedlg.Ui_CellTypeDlg):
#signals
# gotolineSignal = QtCore.pyqtSignal( ('int'... |
return cellTypeDict
def updateUi(self):
self.cellTypeTable.insertRow(0)
mediumItem=QTableWidgetItem("Medium")
self.cellTypeTable.setIte | m (0,0, mediumItem)
mediumFreezeItem=QTableWidgetItem()
mediumFreezeItem.data(Qt.CheckStateRole)
mediumFreezeItem.setCheckState(Qt.Unchecked)
self.cellTypeTable.setItem (0,1, mediumFreezeItem)
baseSize=self.cellTypeTable.baseSize()
self.cellTypeTable... |
BenSimonds/DHTSite | app/dhtapp/config.py | Python | mit | 166 | 0.006024 | #!/usr/bin/env python
import os
# | My Sonos
SONOS_IP = '192.168.0.34'
# API stuff,.
DHT_API_URL = os.environ['DHT_API_URL']
DB_BASE_TIMECODE | = '%Y-%m-%d %H:%M:%S.%f' |
JulienMcJay/eclock | windows/Python27/Lib/site-packages/pywin32-218-py2.7-win32.egg/Demos/RegRestoreKey.py | Python | gpl-2.0 | 1,832 | 0.019651 | import win32api, win32security
import win32con, ntsecuritycon, winnt
import os
temp_dir=win32api.GetTempPath()
fname=win32api.GetTempFileName(temp_dir,'rsk')[0]
print fname
## file can't exist
os.remove(fname)
## enable backup and restore privs
required_privs = ((win32security.LookupPrivilegeValue('',ntsecuritycon.SE... | on(th,ntsecuritycon.TokenUser)[0]
sa.SEC | URITY_DESCRIPTOR.SetSecurityDescriptorOwner(my_sid,0)
k, disp=win32api.RegCreateKeyEx(win32con.HKEY_CURRENT_USER, 'Python test key', SecurityAttributes=sa,
samDesired=win32con.KEY_ALL_ACCESS, Class='some class', Options=0)
win32api.RegSetValue(k, None, win32con.REG_SZ, 'Default value for python test ke... |
jastarex/DeepLearningCourseCodes | 01_TF_basics_and_linear_regression/tensorflow_basic.py | Python | apache-2.0 | 8,932 | 0.004368 |
# coding: utf-8
# # TensorFlow基础
# In this tutorial, we are going to learn some basics in TensorFlow.
# ## Session
# Session is a class for running TensorFlow operations. A Session object encapsulates the environment in which Operation objects are executed, and Tensor objects are evaluated. In this tutorial, we will... | nal name instead of printing out an error message. Note that you should be careful not to call `tf.Variable` giving same name more than once, because it will cause a fatal problem when you save and restore the variables.
# In[9]:
var2 = tf.Variable(tf.random_normal([2, 3], stddev=0.1), name='my_var')
var3 = tf.Variab... | al([2, 3], stddev=0.1), name='my_var')
print var2.name
print var3.name
# #### tf.all_variables
# Using `tf.all_variables()`, we can get the names of all existing variables as follows:
# In[10]:
for var in tf.all_variables():
print var.name
# ## Sharing variables
# TensorFlow provides several classes and opera... |
wxue/xiakelite | libs/flaskext/wtf/recaptcha/widgets.py | Python | mit | 2,664 | 0.003754 | """
Custom widgets
"""
try:
import json
except ImportError:
import simplejson as json
from flask import current_app
from werkzeug import url_encode
# use flaskext.babel for translations, if available
try:
from flaskext.babel import gettext as _
except ImportError:
_ = lambda(s) : s
RECAPTCHA_API_SER... | ="40"></textarea>
<input type="hidden" name="recaptcha_response_field" value="manual_challenge"></div>
</noscript>
'''
__all__ = ["RecaptchaWidget"]
class RecaptchaWidget(object):
def recaptcha_html(self, server, query, options):
return RECAPTCHA_HTML % dict(
script_url='%schallenge?%s' % (... | rame_url='%snoscript?%s' % (server, query),
options=json.dumps(options)
)
def __call__(self, field, error=None, **kwargs):
"""Returns the recaptcha input HTML."""
if current_app.config.get('RECAPTCHA_USE_SSL', False):
server = RECAPTCHA_SSL_API_SERV... |
ptrgags/turtle-fractals | turtlelsystem/tests/test_TurtleSVGMachine.py | Python | gpl-2.0 | 665 | 0.018045 | from turtlelsystem.TurtleSVGMachine import TurtleSVGMachine
from nose.tools import assert_almost_equal
def test_forward():
turtle = TurtleSVGMachine(width = 20, height = 20)
turtle.do_command("FORWARD 10")
assert_almost_equal(turtle.x, 20.0)
def test_backward():
turtle = TurtleSVGMachine(width = 20 | , height = 20)
turtle.do_command("BACKWARD 10")
assert_almost_equal(turtle.x, 0.0)
def test_left():
turtle = TurtleSVGMachine()
turtle.do_command("LEFT 30")
assert_almost_equal(turtle.theta, 30.0)
def test_right():
turtle = TurtleSVGMachine()
turtl | e.do_command("RIGHT 30")
assert_almost_equal(turtle.theta, 330.0)
|
houshengbo/nova_vmware_compute_driver | nova/openstack/common/lockutils.py | Python | apache-2.0 | 8,446 | 0 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack LLC.
# 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/... | ing(), it seems
# to have a laughable 10 attempts "blocking" mechanism.
self.trylock()
return self
except IOError, e:
if e.errno in (errn | o.EACCES, errno.EAGAIN):
# external locks synchronise things like iptables
# updates - give it some time to prevent busy spinning
time.sleep(0.01)
else:
raise
def __exit__(self, exc_type, exc_val, exc_tb):
try:
... |
mixman/djangodev | tests/regressiontests/model_inheritance_regress/tests.py | Python | bsd-3-clause | 15,371 | 0.001041 | """
Regression tests for Model inheritance behaviour.
"""
from __future__ import absolute_import
import datetime
from operator import attrgetter
from django.test import TestCase
from .models import (Place, Restaurant, ItalianRestaurant, ParkingLot,
ParkingLot2, ParkingLot3, Supplier, Wholesaler, Child, SelfRefP... | _issue_7105(self):
# Regression | s tests for #7105: dates() queries should be able to use
# fields from the parent model as easily as the child.
obj = Child.objects.create(
name='child',
created=datetime.datetime(2008, 6, 26, 17, 0, 0))
dates = list(Child.objects.dates('created', 'month'))
self.a... |
wdv4758h/ZipPy | lib-python/3/cgi.py | Python | bsd-3-clause | 34,511 | 0.001275 | #! /usr/local/bin/python
# NOTE: the above "/usr/local/bin/python" is NOT a mistake. It is
# intentionally NOT "/usr/bin/env python". On many systems
# (e.g. Solaris), /usr/local/bin is not in $PATH as passed to CGI
# scripts, and /usr/local/bin is the default directory where Python is
# installed, so /usr/bin/env w... | of the same parsing algorithm.
Also, FieldStorage protects itself better against certain DoS attacks
by limiting the size of the data read in one chunk. The API here
does not support that kind of protection. This also affects parse()
since it can call parse_multipart().
"""
import http.clien... | alueError('Invalid boundary in multipart form: %r'
% (boundary,))
nextpart = "--" + boundary
lastpart = "--" + boundary + "--"
partdict = {}
terminator = ""
while terminator != lastpart:
bytes = -1
data = None
if terminator:
# At star... |
DBCDK/opensearch | tools/transformDir.py | Python | gpl-3.0 | 3,672 | 0.025606 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# -*- mode: python -*-
# This file is part of opensearch.
# Copyright © 2009, Dansk Bibliotekscenter a/s,
# Tempovej 7-11, DK-2750 Ballerup, Denmark. CVR: 15149043
#
# opensearch is free software: you can redistribute it and/or modify
# it under the terms of the GNU Gene... | ow = datetime.datetime.now()
print "Starting Transformation ", now.ctime() ;
print("-"*70)
if os.path.isfile( dest ):
os.remove( dest )
if not os.path.isdir( dest ):
os.mkdir( dest )
files_transformed = 0
for root, dirs, files in os.walk(src):
for f in file... | .path.join( root, f ) )
dest_file = os.path.join( dest, f )
if os.path.exists( dest_file ) and not overwrite:
print( "cannot write file='%s' already exists"%dest_file )
# log no go
else:
print( "\n--> Starting Transformat... |
bruecksen/impacts-world | impacts_world/core/models.py | Python | mit | 3,189 | 0.002195 | from django.db import models
from modelcluster.fields import ParentalKey
from modelcluster.models import ClusterableModel
from wagtail.wagtailcore.fields import RichTextField
from wagtail.contrib.settings.models import BaseSetting
from wagtail.contrib.settings.registry import register_setting
from wagtail.wagtailsnipp... | ner_first_intro'),
FieldPanel('banner_second_intro'),
ImageChooserPanel('banner_image'),
],
heading="Banner",
),
InlinePanel('header_links', label="Link", classname="collapsed"),
MultiFieldPanel(
[
FieldPanel('sh... | ,
FieldPanel('participate_alt_name'),
PageChooserPanel('participate_target'),
],
heading="Participate",
),
]
class HeaderLink(Orderable, models.Model):
header = ParentalKey(HeaderSettings, related_name='header_links')
target = models.ForeignK... |
nugget/home-assistant | homeassistant/components/zha/switch.py | Python | apache-2.0 | 3,817 | 0 | """
Switches on Zigbee Home Automation networks.
For more details on this platform, please refer to the documentation
at https://home-assistant.io/components/switch.zha/
"""
import logging
from homeassistant.components.switch import DOMAIN, SwitchDevice
from homeassistant.const import STATE_ON
from homeassistant.core... |
self._state = True
self.asy | nc_schedule_update_ha_state()
async def async_turn_off(self, **kwargs):
"""Turn the entity off."""
success = await self._on_off_channel.off()
if not success:
return
self._state = False
self.async_schedule_update_ha_state()
def async_set_state(self, state):
... |
kivy/pyjnius | tests/test_bad_declaration.py | Python | mit | 2,212 | 0.001808 | from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
import unittest
from jnius import JavaException, JavaClass
from jnius.reflect import autoclass
class BadDeclarationTest(unittest.TestCase):
def test_class_not_found(self):
#self.assertRaises(JavaEx... | xception as je:
# print "Got JavaException: " + str(je)
# print "Got Exception Class: " + je.classname
# print "Got stacktrace: \n" + '\n'.join(je.stacktrace)
self.assertEqual("java.util.EmptyStackException", je.classname)
def test_java_exception_chaining(self):
... | fail("Expected exception to be thrown")
except JavaException as je:
# print "Got JavaException: " + str(je)
# print "Got Exception Class: " + je.classname
# print "Got Exception Message: " + je.innermessage
# print "Got stacktrace: \n" + '\n'.join(je.stacktrace)
... |
avmarchenko/exatomic | docs/source/conf.py | Python | apache-2.0 | 13,060 | 0.00513 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2015-2018, Exa Analytics Development Team
# Distributed under the terms of the Apache License 2.0
#
# exatomic documentation build configuration file, created by
# sphinx-quickstart on Tue Jun 23 21:37:50 2015.
#
# This file is execfile()d with the current d... | for generating the HTML full-text search i | ndex.
# Sphinx supports the following languages:
# "da", "de", "en", "es", "fi", "fr", "h", "it", "ja"
# "nl", "no", "pt", "ro", "r", "sv", "tr"
#html_search_language = "en"
# A dictionary with options for the search language support, empty by default.
# Now only "ja" uses this config value
#html_search_options = ... |
LLNL/spack | var/spack/repos/builtin/packages/r-affxparser/package.py | Python | lgpl-2.1 | 1,484 | 0.000674 | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-Licen | se-Identifier: (Apache-2.0 OR MIT)
from spack import *
class RAffxparser(RP | ackage):
"""Affymetrix File Parsing SDK
Package for parsing Affymetrix files (CDF, CEL, CHP, BPMAP, BAR). It
provides methods for fast and memory efficient parsing of Affymetrix
files using the Affymetrix' Fusion SDK. Both ASCII- and binary-based
files are supported. Currently, there ar... |
pelson/conda-build | tests/test-recipes/metadata/_compile-test/f2_bad.py | Python | bsd-3-clause | 49 | 0 | I am a bad | file that should not pas | s compileall.
|
SolPi/Web-Django | webLH/context_processor.py | Python | gpl-2.0 | 352 | 0.002841 | # | coding:utf8
from datetime import date
from django.conf import settings
def SiteInfo(request):
return {
'site_title': settings.SITE_TITLE,
'site_motto': settings.SITE_MOTTO,
'site_since': "Desde " + settings.SITE_SINCE,
'more_than_five': date.today().year - int(settings.IS_OLD) > i... | TE_SINCE)
}
|
USGSDenverPychron/pychron | pychron/igsn/definitions.py | Python | apache-2.0 | 3,973 | 0.000755 | # ===============================================================================
# Copyright 2016 ross
#
# 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/LICE... | "Core Section",
"Core Section Half",
"Core Sub-Piece",
"Core Whole Round",
"CTD",
"Cube",
"Culture",
"Cuttings",
"Cylinder",
"Dredge",
"Gas",
"Grab",
"Hole",
"Individual Sample",
"Liqui | d",
"Mechanical Fraction",
"Oriented Core",
"Powder",
"Rock Powder",
"Site",
"Slab",
"Smear",
"Specimen",
"Squeeze Cake",
"Terrestrial Section",
"Thin Section",
"Toothpick",
"Trawl",
"U-Channel",
"Wedge",
"Other",
)
SAMPLE_ATTRS = (
("user_code", "", ... |
15Mpedia/15Mpedia-scripts | import-flickr-photos.py | Python | gpl-3.0 | 11,518 | 0.008684 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2015 emijrp <emijrp@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 License, or
# (at your optio... | = photometadata['date-taken']
author = '{{flickr|%s}}' % (flickruser)
license = '{ | {%s}}' % (licenses[photometadata['license']])
coordinates = ''
if photometadata['coordinates']:
coordinates = '\n| coordenadas = %s' % (', '.join(photometadata['coordinates']))
tags = ''
if photometadata['tags']:
tags = '\n| palabras clave = %s' % (', '.join(photometadata['tags']))
o... |
nive-cms/nive | nive/userdb/userview/view.py | Python | gpl-3.0 | 11,106 | 0.011255 | #----------------------------------------------------------------------
# Copyright 2012, 2013 Arndt Droullier, Nive GmbH. All rights reserved.
#
# 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, ... | "login": {"fields": ["name", FieldConf(id="password", name=_("Password"), datatype="password", settings={"single": True})],
"actions": ["login"],
"defaultAction": "default"},
"mailpass":{"fields": ["email"],
"actions": ["mailpas... | "resetpass":{"fields": ["email"],
"actions": ["resetpass"],
"defaultAction": "default"},
}
self.activate = 1
self.generatePW = 0
self.notify = True
self.mail = None
self.mailpass = None
self.groups = ""
... |
yxs1112003/Django-read-python | polls/views.py | Python | bsd-2-clause | 1,707 | 0.000586 | from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.template import RequestContext, loader
from django.shortcuts import render, get_object_or_404
from django.core.urlresolvers import reverse
from .models import Question, Choice
def index(request):
latest_question_list = Questio | n.objects.order_by('-pub_date')[:5]
context = {
'latest_question_list': latest_question_list,
}
return render(reque | st, 'polls/index.html', context)
def detail(request, question_id):
question = get_object_or_404(Question, pk=question_id)
return render(request, 'polls/detail.html', {'question': question})
def results(request, question_id):
question = get_object_or_404(Question, pk=question_id)
# choice = get_objec... |
kbidarkar/robottelo | tests/foreman/api/test_host.py | Python | gpl-3.0 | 53,992 | 0 | # -*- encoding: utf-8 -*-
"""Unit tests for the ``hosts`` paths.
An API reference can be found here:
http://theforeman.org/api/apidoc/v2/hosts.html
:Requirement: Host
:CaseAutomation: Automated
:CaseLevel: Acceptance
:CaseComponent: API
:TestType: Functional
:CaseImportance: High
:Upstream: No
"""
from fauxfac... | :CaseImportance: Critical
"""
for name in valid_hosts_list():
with self.subTest(name):
host = entities.Host(name=name).create()
self.assertEqual(
host.name,
'{0}.{1}'.format(name, host.domain.read().name)
... | 3f266906-c509-42ce-9b20-def448bf8d86
:expectedresults: A host is created with expected IP address
:CaseImportance: Critical
"""
ip_addr = gen_ipaddr()
host = entities.Host(ip=ip_addr).create()
self.assertEqual(host.ip, ip_addr)
@run_only_on('sat')
@tier2
de... |
jsalcedo09/webengine | webengine/views.py | Python | gpl-2.0 | 1,293 | 0.006187 | '''
Created on 7/01/2014
@author: Jorge Salcedo
'''
import settings
from importlib import import_module
from webengine import route, WSGIWebEngine
import logging
@route('/_ah/warmup')
def warmup(handler):
for app in settings.APPS:
for name in ('views', 'models', 'apis', 'admin_views'):
try:
... |
def handle_404(request, response, exception):
logging.exception(exception)
response.write('Oops! I could swear this page was here!')
response.set_status(404)
def handle_500(request, response, exception):
logging.exception(exception)
response.write('A server error occurred!')
response.set_stat... |
WSGIWebEngine._instance.error_handlers[401] = handle_401 # @UndefinedVariable
WSGIWebEngine._instance.error_handlers[404] = handle_404 # @UndefinedVariable
WSGIWebEngine._instance.error_handlers[500] = handle_500 # @UndefinedVariable |
noba3/KoTos | addons/plugin.audio.radio7ulm/default.py | Python | gpl-2.0 | 1,255 | 0.023108 | # -*- coding: cp1254 -*-
# please visit http://www.iptvxtra.net
import xbmc,xbmcgui,xbmcplugin,sys
icondir = xbmc.translatePath("special://home/addons/plugin.audio.radio7ulm/icons/")
plugin_handle = int(sys.argv[1])
def add_video_item(url, infolabels, img=''):
listitem = xbmcgui.ListItem(infolabels['title'], icon... | dle, url, listitem, isFolder=False)
add_video_item('http://srv01.radio7.fmstreams.de/stream1/livestream.mp3',{ 'title': 'Radio 7 - Webradio'},img=icondir + 'radio-7_web.png')
add_video_item('http://srv02 | .radio7.fmstreams.de/radio7_upa',{ 'title': 'Radio 7 - 80er'},img=icondir + 'radio-7_80er.png')
add_video_item('http://srv02.radio7.fmstreams.de/radio7_downa',{ 'title': 'Radio 7 - Herz'},img=icondir + 'radio-7_herz.png')
add_video_item('http://str0.creacast.com/radio7_acta',{ 'title': 'Radio 7 - OnTour'},img=icondir +... |
tiangolo/fastapi | tests/test_tutorial/test_path_operation_configurations/test_tutorial005.py | Python | mit | 4,083 | 0.000735 | from fastapi.testclient import TestClient
from docs_src.path_operation_configuration.tutorial005 import app
client = TestClient(app)
openapi_schema = {
"openapi": "3.0.2",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/items/": {
"post": {
"responses": ... | {"title": "Price", "type": "number"},
"description": {"title": "Description", "type": "string"},
"tax": {"title": "Tax", "type": "number"},
"tags": {
"title": "Tags",
"uniqueItems": True,
... | "default": [],
},
},
},
"ValidationError": {
"title": "ValidationError",
"required": ["loc", "msg", "type"],
"type": "object",
"properties": {
"loc": {
... |
cuker/sorl-thumbnail-legacy | sorl/thumbnail/tests/__init__.py | Python | bsd-3-clause | 665 | 0 | # For these tests to run successfully, two conditions must be met:
# 1. MEDIA_URL and MEDIA_ROOT must be set in settings
# 2. The user running the tests must have read/write access to MEDIA_ROOT
# Unit tests:
from sorl.thumbnail.tests.classes import ThumbnailTest, DjangoThumbnailTest
from | sorl.thumbnail.tests.templatetags import ThumbnailTagTest
from sorl.thumbnail.tests.fields import FieldTest, \
ImageWithThumbnailsFieldTest, ThumbnailFieldTest
# Doc tests:
from sorl.t | humbnail.tests.utils import utils_tests
from sorl.thumbnail.tests.templatetags import filesize_tests
__test__ = {
'utils_tests': utils_tests,
'filesize_tests': filesize_tests,
}
|
nearlyfreeapps/python-googleadwords | tests/adspygoogle/adwords/v201206/error_handling_unittest.py | Python | apache-2.0 | 2,306 | 0.010408 | #!/usr/bin/python
#
# Copyright 2011 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... | 0, os.path.join('..', '..', '..', '..'))
import time
import unittest
from examples.adspygoogle.adwords.v201206.error_handling import handle_partial_failures
from examples.adspygoogle.adwords.v201206.error_handling import handle_two_factor_authorization_error
from tests.adspygoogle.adwords import client
from tests.adsp... | ER_V201206
from tests.adspygoogle.adwords import TEST_VERSION_V201206
from tests.adspygoogle.adwords import util
from tests.adspygoogle.adwords import VERSION_V201206
class ErrorHandling(unittest.TestCase):
"""Unittest suite for Error Handling code examples."""
SERVER = SERVER_V201206
VERSION = VERSION_V20120... |
drgarcia1986/drf-pdf | drf_pdf/exceptions.py | Python | mit | 186 | 0 | # encoding: utf-8
from rest_framework import status
from rest_framework.exceptions import APIEx | ception
class PDFFileNotFound(APIException):
status_code = status.H | TTP_404_NOT_FOUND
|
NathanW2/qquery | btree.py | Python | gpl-2.0 | 19,500 | 0.000359 | import bisect
import itertools
import operator
class _BNode(object):
__slots__ = ["tree", "contents", "children"]
def __init__(self, tree, contents=None, children=None):
self.tree = tree
self.contents = contents or []
self.children = children or []
if self.children... | arent.contents[parent_index])
parent.contents[parent_index] = self.contents.pop()
if self.children:
dest.children.insert(0, self.children.pop())
def shrink(self, ancestors):
parent = None
if ancesto | rs:
parent, parent_index = ancestors.pop()
# try to lend to the left neighboring sibling
if parent_index:
left_sib = parent.children[parent_index - 1]
if len(left_sib.contents) < self.tree.order:
self.lateral(
... |
stuliveshere/PySeis | examples/01.0_import_su.py | Python | mit | 787 | 0.030496 | imp | ort PySeis as ps
import numpy as np
import pylab
#import dataset
input = ps.io.su.SU("./d | ata/sample.su")
input.read("./data/raw.npy")
#initialise dataset
#~ data, params = toolbox.initialise("geometries.su")
#trim data
#~ params['ns'] = 1500
#~ data = toolbox.slice(data, None, **params)
#~ data.tofile("geom_short.su")
#initialise dataset
#data, params = toolbox.initialise("geom_short.su")
#agc
#~ toolb... |
exleym/IWBT | iwbt/data/readers.py | Python | apache-2.0 | 2,496 | 0.004808 | """ DataReader code lives here. All DataReader classes should extend DataReader
and implement the following methods:
- help()
- get_data()
"""
from datetime import datetime
import requests
class DataReader(object):
""" Class-level constants that can be defined in code until we get around
to putt... | _(self):
super(USGSDataReader, self).__init__()
pass
| def get_data(self, uri):
""" Hit USGS API and retrieve JSON object. Return GaugeData JSON object.
:param uri: USGS id of the gauge being queried
:returns: <GaugeData>: updated values in the form of a JSON object
"""
usgs_code = '0' * (8 - len(str(uri))) + str(uri)
pa... |
ovresko/erpnext | erpnext/config/desktop.py | Python | gpl-3.0 | 12,428 | 0.047324 | # coding=utf-8
from __future__ import unicode_literals
from frappe import _
def get_data():
return [
{
"module_name": "Item",
"_doctype": "Item",
"color": "#f39c12",
"icon": "octicon octicon-package",
"type": "link",
"link": "List/Item"
},
{
"module_name": "Customer",
"_doctype": "Custo... | r": "#2ecc71",
"icon": "fa fa-stethoscope",
"doctype": "Patient Encounter",
"type": "link",
"link": "List/Patient Encounter",
"label": _("Patient Encounter"),
"hidden": 1
},
{
"module_name": "Lab Test",
"color": "#7578f6",
"icon": "octicon octicon-beaker",
"doctype": "Lab T... | bel": _("Lab Test"),
"hidden": 1
},
{
"module_name": "Vital Signs",
"color": "#2ecc71",
"icon": "fa fa-thermometer-empty",
"doctype": "Vital Signs",
"type": "list",
"link": "List/Vital Signs",
"label": _("Vital Signs"),
"hidden": 1
},
{
"module_name": "Clini... |
Donkyhotay/MoonPy | twisted/words/im/ircsupport.py | Python | gpl-3.0 | 9,837 | 0.010674 | # Copyright (c) 2001-2004 Twisted Matrix Laboratories.
# See LICENSE for details.
"""IRC support for Instance Messenger."""
import string
from twisted.words.protocols import irc
from twisted.words.im.locals import ONLINE
from twisted.internet import defer, reactor, protocol
from twisted.internet.defer import succee... | up)
def irc_QUIT(self,prefix,params):
nickname=string.split(prefix,"!")[0]
if self._ingroups.has_key(nickname):
for group in self._ingro | ups[nickname]:
self.getGroupConversation(group).memberLeft(nickname)
self._ingroups[nickname]=[]
else:
print '*** WARNING: ingroups had no such key %s' % nickname
d |
noman798/dcny | lib/f42/setup.py | Python | mpl-2.0 | 368 | 0.029891 | #coding:utf-8
from setuptools import setup, find_packages
setup(
name='f42',
| version="0.1.3",
description="Some common use functions",
author="Lerry",
author_email="lvdachao@gmail.com",
packages = ['f42'],
zip_safe=False,
inclu | de_package_data=True,
install_requires = [
],
url = "https://bitbucket.org/vcwatch/f42",
)
|
sixty-north/bark-spider | setup.py | Python | agpl-3.0 | 1,191 | 0.00084 | import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, 'README.md')) as f:
README = f.read()
with open(os.path.join(here, 'CHANGES.txt')) as f:
CHANGES = f.read()
requires = [
# 'brooks',
'aiohttp',
'pandas',
'pytes... | Internet :: WWW/HTTP :: WSGI :: Application",
],
author='Sixty North AS',
author_email='austin@sixty-north.com',
url='http://github.com/sixty-north/bark_spider',
keywords='web pyramid pylons',
packages=fin | d_packages(),
include_package_data=True,
zip_safe=False,
install_requires=requires,
tests_require=requires,
test_suite="bark_spider",
)
|
praekelt/seed-stage-based-messaging | contentstore/apps.py | Python | bsd-3-clause | 190 | 0 | from django.apps import App | Config
class ContentStoreAppConfig(AppConfig):
name = "contentstore"
def ready(self):
import contentstore.sign | als
contentstore.signals
|
openstack/networking-bagpipe | networking_bagpipe/bagpipe_bgp/vpn/evpn/linux_vxlan.py | Python | apache-2.0 | 15,445 | 0 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# encoding: utf-8
# Copyright 2014 Orange
#
# 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... | ces[self.bridge_name].ports:
port = ndb.interfaces[port_id] # pylint: disable=no-member
if port.ifname == ifname:
return True
except KeyError:
return False
return False
def _is_vxlan_if_on_bridge(self):
ret... | ridge(self.vxlan_if_name)
def _interface_exists(self, interface):
"""Check if interface exists."""
(_, exit_code) = self._run_command("ip link show dev %s" % interface,
raise_on_error=False,
acceptable_return_code... |
lopp2005/spatial_cluster_fs | tool_densfilter.py | Python | apache-2.0 | 5,412 | 0.013673 | # -*- coding: utf-8 -*-
"""
Density Filter Tool
Created on Thu May 11 11:03:05 2017
@author: cheny
"""
from arcpy import Parameter
import arcpy
from section_cpu import dens_filter_cpu
from multiprocessing import cpu_count
class DensFilterTool(object):
def __init__(self):
"""Classify Tool"""
self... | TR_ID'
#5
paramdens = Parameter(
displayName="Density Field",
name="density_field",
datatype="Field",
parameterT | ype="Required",
direction="Input")
# Set the filter to accept only fields that are Short or Long type
paramdens.filter.list = ['Short','Long','Float','Single','Double']
paramdens.parameterDependencies = [paramclsinput.name]
paramdens.value='DENSITY'
... |
andrewbird/wader | core/oses/linux.py | Python | gpl-2.0 | 20,257 | 0.000444 | # -*- coding: utf-8 -*-
# Copyright (C) 2006-2008 Vodafone España, S.A.
# Copyright (C) 2008-2009 Warp Networks, S.L.
# Author: Pablo Martí
#
# 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; e... | any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Gen | eral Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""Linux-based OS plugin"""
import dbus
from functools import partia... |
essepuntato/opencitations | script/statistics.py | Python | isc | 3,561 | 0.001685 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) 2016, Silvio Peroni <essepuntato@gmail.com>
#
# Permission to use, copy, modify, and/or distribute this software for any purpose
# with or without fee is hereby granted, provided that the above copyright notice
# and this permission notice appear in all copies.
... | /0.1/>
SELECT (count(?auth) as ?tot) {
GRAPH <https://w3id.org/oc/corpus/ra/> {
?auth a foaf:Agent
}
}"""
]
tp = SPARQLWrapper(triplestore_url)
tp.setMethod('GET')
res = datetime.now().strftime('%Y-%m-%dT%H:%M:%S')
for | idx, query in enumerate(queries):
if idx in (0, 2, 3, 6):
res += ",-"
else:
tp.setQuery(query)
tp.setReturnFormat(JSON)
results = tp.query().convert()
for result in results["results"]["bindings"]:
res += "," + result["tot"]["value"]
with open(base_home + "st... |
Orav/kbengine | kbe/res/scripts/common/Lib/site-packages/pip/commands/search.py | Python | lgpl-3.0 | 4,868 | 0.001438 | import sys
import textwrap
import pip.download
from pip.basecommand import Command, SUCCESS
from pip.util import get_terminal_size
from pip.log import logger
from pip.backwardcompat import xmlrpclib, reduce, cmp
from pip.exceptions import CommandError
from pip.status_codes import NO_MATCHES_FOUND
from pip.... | rom pypi is really a list of versions. We want a list of
packages with the list of versions stored inline. This converts the
list from pypi into one we can use.
"""
packages = {}
for hit in hits:
name = hit['name']
summary = hit['summary']
version = hit['version']
... | summary': summary, 'versions': [version], 'score': score}
else:
packages[name]['versions'].append(version)
# if this is the highest version, replace summary and score
if version == highest_version(packages[name]['versions']):
packages[name]['summary'] =... |
praekelt/diamondash | diamondash/widgets/dynamic/__init__.py | Python | bsd-3-clause | 154 | 0 | from diamo | ndash.widgets.dynamic.dynamic import (
DynamicWidgetConfig,
DynamicWidget)
__all__ = [
'DynamicWidgetConfig',
'Dyna | micWidget']
|
benjyw/pants | src/python/pants/backend/shell/dependency_inference.py | Python | apache-2.0 | 8,271 | 0.003748 | # Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import json
import logging
import re
from collections import defaultdict
from dataclasses import dataclass
from typing import DefaultDict
from pants.ba... | p}",
level=LogLevel.DEBUG,
# We expect this to always fail, but it should still be cached because the process is
# deterministic.
cache_scope=ProcessCacheScope.ALWAYS,
),
)
try:
output = | json.loads(process_result.stdout)
except json.JSONDecodeError:
logger.error(
f"Parsing {request.fp} for dependency inference failed because Shellcheck's output "
f"could not be loaded as JSON. Please open a GitHub issue at "
f"https://github.com/pantsbuild/pants/issues/ne... |
Grokzen/repy | setup.py | Python | mit | 1,433 | 0.004187 | # -*- coding: utf-8 -*-
import repy
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
name=repy.__pkgname__,
version=repy.__version__,
description="Python Regex cli tool",
author_name=repy.__author_name__,
author_email=repy.__author_email__,
... | Status :: 2 - Pre-Alpha',
'Development Status :: 3 - Alpha',
#'Development Status :: 4 - Beta',
#'Development Status :: 5 - Production/Stable',
#'Development Status :: 6 - Mature | ',
#'Development Status :: 7 - Inactive',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.0',
'Programming Language :: Python :: 3.1',
'Programming Language :: Python :: 3.2',
'Programming Language :: P... |
rneher/FitnessInference | flu/sequence_and_annotations/get_L_L_H3N2_predictions.py | Python | mit | 1,340 | 0.015672 | #############################
#get_L_L_H3N2_predictions.tex
#
# this script identifies the strain names we obtained from Luksza and Laessig
# with sequences in our mutliple sequence alignment
#
################################
import sys
sys.path.append('../src')
import predict_flu as PF
from datetime import date
from... | iltered.fasta.gz'
with open('../data/annotations.pickle', 'r') as infile:
annotation = pickle.load(infile)
with gzip.open(aln_fname) as infile:
total_alignment = AlignIO.read(infile,'fasta')
seq_look_up = {c.name.split('|')[0].lower():c for c in total_alignment}
L_L={}
with open('../data/H3N2_L_L_predicted_v... | line.strip().split()
year=int(entries[0][:-1])
strain_name = '_'.join(entries[1].split('_')[:-3]).lower().replace('-', '_')
if strain_name in seq_look_up:
L_L[year-1] = seq_look_up[strain_name]
else:
print "strain for year", year-1, "not found"
with open('../data... |
penzance/canvas_python_sdk | canvas_sdk/methods/admins.py | Python | mit | 3,874 | 0.004904 | from canvas_sdk import client, utils
def make_account_admin(request_ctx, account_id, user_id, role=None, role_id=None, send_confirmation=None, **request_kwargs):
"""
Flag an existing user as an admin within the account.
:param request_ctx: The request context
:type request_ctx: :class:RequestC... | :type send_confirmation: boolean or None
:return: Make an account admin
:rtype: requests.Response (with Admin data)
"""
path = '/v1/accounts/{account_id}/admins'
payload = {
'user_id' : user_id,
'role' : role,
'role_id' : role_id,
'send_confirmation' : sen... | payload=payload, **request_kwargs)
return response
def remove_account_admin(request_ctx, account_id, user_id, role=None, role_id=None, **request_kwargs):
"""
Remove the rights associated with an account admin role from a user.
:param request_ctx: The request context
:type request_ctx: :c... |
nkmk/python-snippets | notebook/numpy_gcd.py | Python | mit | 807 | 0 | import numpy as np
a = np.array([0, 2, 3, 6])
b = np.array([3, 4, 5, 15])
print(np.gcd(a, b))
# [3 2 1 3]
print(type(np.gcd(a, b)))
# <class 'numpy.ndar | ray'>
l_a = [0, 2, 3, 6]
l_b = [3, 4, 5, 14]
print(np.gcd(l_a, l_b))
# [3 2 1 2]
print(type(np.gcd(l_a, l_b)))
# <class 'numpy.ndarray'>
print(np.gcd(6, 15))
# 3
print(type(np.gcd(6, 15)))
# <class 'numpy.int64'>
a_2d = np.array([[0, 2, 3, 6], [0, 2, 3, 6]])
print(a_2d)
# [[0 2 3 6]
# [0 2 3 6]]
print(b)
# [ 3 ... | 3 6 8 21]]
print(np.gcd(a_2d, b))
# [[3 2 1 3]
# [3 2 1 3]]
a_mismatch = np.array([0, 1, 2])
# print(np.gcd(a_mismatch, b))
# ValueError: operands could not be broadcast together with shapes (3,) (4,)
print(np.gcd(a, 15))
# [15 1 3 3]
print(np.gcd(15, a))
# [15 1 3 3]
|
hgqislub/hybird-orchard | code/cloudmanager/install/hws/hws_cascaded_configer.py | Python | apache-2.0 | 4,081 | 0.002695 | # -*- coding:utf-8 -*-
__author__ = 'q00222219@huawei'
import time
from heat.openstack.common import log as logging
import heat.engine.resources.cloudmanager.commonutils as commonutils
import heat.engine.resources.cloudmanager.constant as constant
import heat.engine.resources.cloudmanager.exception as exception
impor... | dFailure as e:
LOG.error("modify cascaded dns address error, cascaded: "
"%s, error: %s"
% (self.domain, e.format_message()))
time.sleep(1)
LOG.info(
"config cascaded dns address success, cascaded: %s"
... | |
zhangyage/Python-oldboy | day13/Django_study/oldboy/mymiddleware.py | Python | apache-2.0 | 731 | 0.029173 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
#自定义中间件 在Django中定义的中间件必须有下面的4个函数
#使用中间件时候需要现在setting中引用一下
from django.http.response import HttpRes | ponse
class Day13Middleware(object):
def process_request(self,request):
print '1.process_quest'
def process_view(self,request,callback,callback_args,callback_kwargs):
print '2.process_view'
def process_exception(self,request,exception):
#处理异常的,只有在出错的时候才会执行
... | rocess_response'
return response
|
bcostea/tomate2 | tomate2.py | Python | mpl-2.0 | 5,644 | 0.019135 | #!/usr/bin/env python2
from __future__ import division
import os
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import GObject as gobject
from gi.repository import Gtk
from gi.repository import Gdk
from gi.repository import Notify
from gi.repository import AppIndicator3 as appindicator
from time import t... | G:
self.start_working_time = time
delta = time - self.start_working_time
self.tooltip = "Working for " + self.format_time(delta) + "..."
self.st_menu.set_label("Working for %s... stop" % self.format_time(delta))
elif state == States.OK:
delta = time - self.start_working_time
self... | _time(delta) + "!"
elif state == States.DONE:
self.tooltip = "Worked enough, take a break!"
self.state=state
self.ind.set_icon(self.get_icon(state))
self.show_notification(self.state, self.tooltip)
def show_notification(self, state, notification):
try:
nw = Notify.Notification.new("T... |
dmdm/Pym-elFinder | pym_elfinder_tests/t002_functional/test_3080_cmd_rm.py | Python | bsd-3-clause | 1,935 | 0.006718 | import unittest
import os
from pprint import pprint
import pym_elfinder.exceptions as exc
from .. import lib
from .. import lib_localfilesystem as lfs
class TestCmdRm(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.finder = lib.create_finder()
cls.fixt = lib.CMD_FIXT['cmd_rm.txt']... | lfs.mkfile(self.file_1_1)
req = self.fixt[1]['request']
cmd, args = lib.prepare_request(req)
assert cmd == 'rm'
with self.assertRaisesRegexp(exc.FinderError, exc.ERROR_RM):
self.finder.run(cmd, args, debug=True)
r = self.finder.resp... | )
os.rmdir(self.dir_1)
|
atomgomba/txtable | txtable/__main__.py | Python | unlicense | 3,048 | 0.001312 | import csv
import json
from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser
from enum import Enum
from sys import exit, stdin
from .formatters import DefaultFormatter, HeadlessFormatter, MdFormatter, RstFormatter
from .table import TextTable
class Formatter(Enum):
default = DefaultFormatter
hea... | tParser(prog="txtable", formatter_class=ArgumentDefaultsHelpFormatter)
parser.add_argument("input", default=[], nargs="*",
help="File paths or stdin when empty")
parser.add_argument("-f", "--formatter", type=Formatter.enum, default=Formatter.default, choices=list(Formatter),
... | help="Specify input data format from stdin")
exit(main(parser.parse_args()))
|
lmazuel/azure-sdk-for-python | azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/models/storage_profile.py | Python | mit | 1,573 | 0 | # 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 ... | dant_backup: Enable Geo-redundant or not for server
backup. Possible values include: 'Enabled', 'Disabled'
:type geo_redundant_backup: str or
~azure.mgmt.rdbms.postgresql.models.GeoRedundantBackup
:param storage_mb: Max storage allowed for a server.
: | type storage_mb: int
"""
_attribute_map = {
'backup_retention_days': {'key': 'backupRetentionDays', 'type': 'int'},
'geo_redundant_backup': {'key': 'geoRedundantBackup', 'type': 'str'},
'storage_mb': {'key': 'storageMB', 'type': 'int'},
}
def __init__(self, **kwargs):
s... |
IECS/MansOS | tools/remoteaccess/tests/03-read.py | Python | mit | 439 | 0.006834 | #!/usr/bin/env python
# Get data
import os, sys, time
import urllib2
def ma | in():
host = "http://localhost:30001/read?port=/dev/ttyUSB0"
# host = "http:/ | /10.0.0.1:30001/read?port=/dev/ttyUSB0"
try:
req = urllib2.urlopen(host)
print("Reply data:")
print(req.read())
except Exception as e:
print("exception occurred:")
print(e)
return 1
if __name__ == '__main__':
main()
|
dionaea-honeypot/dionaea | modules/python/dionaea/smb/rpcservices.py | Python | gpl-2.0 | 133,752 | 0.005024 | # This file is part of the dionaea honeypot
#
# SPDX-FileCopyrightText: 2009 Paul Baecher & Markus Koetter & Mark Schloesser
# SPDX-FileCopyrightText: 2010 Markus Koetter & Tan Kean Siong
# SPDX-FileCopyrightText: 2015 Katarina Durechova
# SPDX-FileCopyrightText: 2017 Tan Kean Siong
# SPDX-FileCopyrightText: 2016-2017 ... | el (DCOM) Remote Protocol Specification
http://msdn.microsoft.com/en-us/library/cc226801%28PROT.10%29.aspx"""
uuid = UUID('99fcfec4-5260-101b-bbcb-00aa0021347a').hex
ops = {
0x5: "ServerAlive | 2"
}
class COMVERSION(object):
# typedef struct tagCOMVERSION {
# unsigned short MajorVersion;
# unsigned short MinorVersion;
# } COMVERSION;
def __init__(self, p):
self.__packer = p
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.