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 |
|---|---|---|---|---|---|---|---|---|
goofwear/raspberry_pwn | src/pentest/sqlmap/plugins/dbms/oracle/filesystem.py | Python | gpl-3.0 | 792 | 0.001263 | #!/usr/bin/env python
"""
Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission
"""
from lib.core.exception import SqlmapUnsupportedFeatureException
from plugins.generic.filesystem import Filesystem as GenericFilesystem
class Filesystem(GenericFilesystem):
... | for "
errMsg += "Oracle"
raise SqlmapUnsupportedFeatureException(errMsg)
def writeFile(self, wFile, dFile, fileType=None, forceCheck=False):
errMsg = "File system write access not yet implemented for "
errMsg += "Oracle"
raise SqlmapUnsupportedFea | tureException(errMsg)
|
narcolepticsnowman/GarageWarden | GarageWarden/notify.py | Python | mit | 3,025 | 0.002314 | import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from datetime import datetime
from django.http import HttpResponse
from GarageWarden import status, settingHelper, settingView, config, settings as gw_settings
import RPi.GPIO as GPIO
settings = None
settings_loaded = Fa... | global settings, settings_loaded
settings_loaded = True
settings = settingHelper.values_for_prefix("email")
settingView.reload_methods['notify'] = reload_config
def send_mail(subject, text, html=None):
if not get_setting('enabled'):
print('email not enabled')
return
encryptio... | tting('host')
port = int(get_setting('port'))
if encryption == 'ssl':
smtp = smtplib.SMTP_SSL(host=host, port=port)
else:
smtp = smtplib.SMTP(host=host, port=port)
if encryption == 'tls':
smtp.starttls()
if get_setting('username') and get_setting('password'):
smtp.l... |
JaneliaSciComp/osgpyplusplus | examples/rough_translated1/osglight.py | Python | bsd-3-clause | 10,059 | 0.015409 | #!/bin/env python
# Automatically translated python version of
# OpenSceneGraph example program "osglight"
# !!! This program will need manual tuning before it will work. !!!
import sys
from osgpypp import osg
from osgpypp import osgDB
from osgpypp import osgUtil
from osgpypp import osgViewer
# Translated from fi... | ,1.0))
myLight1.setDiffuse(osg.Vec4(1.0,0.0,0.0,1.0))
myLight1.setSpotCutoff(20.0)
myLight1.setSpotExponent(50.0)
myLight1.setDirection(osg.Vec3(1.0,1.0,-1.0))
lightS1 = osg.LightSource()
lightS1.setLight(myLight1)
lightS1.s | etLocalStateSetModes(osg.StateAttribute.ON)
lightS1.setStateSetModes(*rootStateSet,osg.StateAttribute.ON)
lightGroup.addChild(lightS1)
# create a local light.
myLight2 = osg.Light()
myLight2.setLightNum(1)
myLight2.setPosition(osg.Vec4(0.0,0.0,0.0,1.0))
myLight2.setAmbient(osg.Vec4(0.0,1.... |
MichaelMauderer/GeneaCrystal | geneacrystal/nodes.py | Python | gpl-3.0 | 10,098 | 0.008418 | # GeneaCrystal Copyright (C) 2012-2013
# Christian Jaeckel, <christian.doe@gmail.com>
# Frederic Kerber, <fkerber@gmail.com>
# Pascal Lessel, <maverickthe6@gmail.com>
# Michael Mauderer, <mail@michaelmauderer.de>
#
# GeneaCrystal is free software: you can redistribute it and/or modify
# it under the ... | e=True
self._topImage = self._layer[-1]
def removeLayer(self, index):
node = self._layer[index]
node.unlink(True)
self._layer.remove(node)
if node == self._topImage:
self._topImage = self._layer[-1]
|
@property
def size(self):
return self._layer[0].size
def setEventHandler(self, *args, **kwargs):
return self._topImage.setEventHandler(*args, **kwargs)
def setEffect(self, *args, **kwargs):
for node in self._layer:
node.setEffect(*args, **kwargs... |
noironetworks/networking-cisco | networking_cisco/db/migration/alembic_migrations/versions/mitaka/expand/73c84db9f299_update_ha_group_primary_key.py | Python | apache-2.0 | 2,956 | 0 | # Copyright 2017 Cisco Systems, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | ove_foreign_keys('cisco_router_ha_groups', foreign_keys)
primary_key = inspector.get_pk_constraint('cisco_router_ha_groups')
op.drop_constraint(constraint_name=primary_key['name'],
table_name='cisco_router_ha_groups',
| type_='primary')
op.create_primary_key(
constraint_name='pk_cisco_router_ha_groups',
table_name='cisco_router_ha_groups',
columns=['ha_port_id', 'subnet_id'])
op.create_foreign_key('cisco_router_ha_groups_ibfk_1',
source_table='cisco_... |
tangentlabs/django-oscar-fancypages | oscar_fancypages/fancypages/templatetags/fp_container_tags.py | Python | bsd-3-clause | 56 | 0 | from | fancypages.templatetags.fp_container_tags import | *
|
fsinf/certificate-authority | ca/django_ca/migrations/0002_auto_20151223_1508.py | Python | gpl-3.0 | 1,224 | 0.001634 | # -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2015-12-23 15:08
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('django_ca', '0001_initial'),
]
operations = [
migrations.AlterField(
... | field=models.CharField(max_length | =64, verbose_name='CommonName'),
),
migrations.AlterField(
model_name='certificate',
name='csr',
field=models.TextField(verbose_name='CSR'),
),
migrations.AlterField(
model_name='certificate',
name='pub',
field=model... |
CivicKnowledge/rowgenerators | rowgenerators/appurl/archive/zip.py | Python | mit | 6,923 | 0.004911 | # Copyright (c) 2017 Civic Knowledge. This file is licensed under the terms of the
# MIT, included in this distribution as LICENSE
""" """
from rowgenerators.appurl.file.file import FileUrl
from rowgenerators.exceptions import AppUrlError
class ZipUrlError(AppUrlError):
pass
class ZipUrl(FileUrl):
"""Zip ... | # e.external_attr==32 is true for some single-file archives.
if bool(e.external_attr >> 31 & 1 or e.external_attr == 0 or e.external_attr == 32):
yield e.filename
@classmethod
def _match(cls, url, **kw | args):
return url.resource_format == 'zip' or kwargs.get('force_archive')
|
zhitiancheng/cliff | cliff/selection.py | Python | gpl-2.0 | 593 | 0 | """
This module is used to select features or proposals
"""
def select_preceding(features, k):
""" select preceding k features or proposals for each image
:param k: preceding k features or proposals for each image are selected
:type k: integer
:return: selected features or proposals
: | rtype: list. Each element is a k'-by-m ndarray, where m is feature
dimension or 4 for proposals. If there are enough features or proposals
for selection, then k' = k, else all features or proposals are
selected.
"""
return [i[: | k] for i in features]
|
YannThorimbert/ThorPy-1.4.3 | thorpy/__init__.py | Python | mit | 3,614 | 0.017432 | __version__ = "1.4.3"
import sys
import os
# verify that pygame is on the machine
try:
import pygame
except Exception:
print("Pygame doesn't seem to be installed on this machine.")
# add thorpy folder to Windows and Python search paths
THORPY_PATH = os.path.abspath(os.path.dirname(__file__))
try:
os.env... | .miscgui import style
from thorpy.miscgui import painterstyle
from thorpy.miscgui import parameters
from thorpy.miscgui.initializer import Initializer
fro | m thorpy.miscgui.state import State
from thorpy.miscgui.storage import Storer, store
from thorpy.miscgui.title import Title
from thorpy.miscgui.varset import VarSet
from thorpy.miscgui import theme
from thorpy.miscgui.theme import set_theme as set_theme
from thorpy.painting.writer import Writer
from thorpy.painting im... |
ajaygarg84/sugar | src/jarabe/journal/palettes.py | Python | gpl-2.0 | 15,839 | 0.000126 | # Copyright (C) 2008 One Laptop Per Child
#
# 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 distribu... | alert.connect('response', self.__erase_alert_response_cb)
journalwindow.get_journal_window().add_alert(alert)
alert.show()
def __erase_alert_response_cb(self, alert, response_id):
journalwindow.get_journal_window().remove_alert(alert)
if response_id is Gtk.ResponseType | .OK:
model.delete(self._metadata['uid'])
def __detail_activate_cb(self, menu_item):
self.emit('detail-clicked', self._metadata['uid'])
def __volume_error_cb(self, menu_item, message, severity):
self.emit('volume-error', message, severity)
def __friend_selected_cb(self, menu_it... |
zhongjingjogy/SmartQQBot | smartqq/main.py | Python | gpl-2.0 | 2,757 | 0.002176 | #coding=utf-8
import argparse
import json
import os
from smartqq import start_qq, list_messages, create_db
def load_pluginconfig(configjson):
config = None
if configjson is not None:
if os.path.isfile(configjson):
with open(configjson, "r") as f:
config = json.load(f)
... | h tk and PIL."
)
parser.add_argument(
"--new-use | r",
action="store_true",
default=False,
help="Logout old user first(by clean the cookie file.)"
)
parser.add_argument(
"--debug",
action="store_true",
default=False,
help="Switch to DEBUG mode for better view of requests and responses."
)
parser.ad... |
thomasyu888/synapsePythonClient | tests/integration/synapseutils/test_synapseutils_sync.py | Python | apache-2.0 | 11,189 | 0.003582 | import uuid
import os
import time
import tempfile
import pandas as pd
import pytest
from synapseclient.core.exceptions import SynapseHTTPError
from synapseclient import Entity, File, Folder, Link, Project, Schema
import synapseclient.core.utils as utils
import synapseutils
from tests.integration import QUERY_TIMEOUT... | are already tested in the
tests/integration/test_command_line_client::test_command_get_recursive_and_query
| which means that the only test if for path=None
"""
# Create a Project
project_entity = test_state.syn.store(Project(name=str(uuid.uuid4())))
test_state.schedule_for_cleanup(project_entity.id)
# Create a Folder in Project
folder_entity = test_state.syn.store(Folder(name=str(uuid.uuid4()), p... |
aswolf/xmeos | xmeos/models/gamma.py | Python | mit | 11,700 | 0.005215 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, division
from future.utils import with_metaclass
import numpy as np
import scipy as sp
from abc import ABCMeta, abstractmethod
from scipy import integrate
import scipy.interpolate as interpolate
from . import core
from . import refstate
_... | rameter.
Parameters
----------
Thermodyn properties depend only on volume
"""
_kind_opts = ['GammaPowLaw','GammaShiftPowLaw','GammaFiniteStrain']
def __init__(self, kind='GammaPowLaw', natom=1, model_state={}):
self._pre_init(natom=natom)
set_calculator(self, kind, self._kin... | ='T0'
ref_energy_type = 'E0'
refstate.set_calculator(self, ref_compress_state=ref_compress_state,
ref_thermal_state=ref_thermal_state,
ref_energy_type=ref_energy_type)
# self._set_ref_state()
self._post_init(model_state=mode... |
MMaus/mutils | cmodels/__init__.py | Python | gpl-2.0 | 106 | 0 | # -*- coding: utf-8 -*-
"""
Crea | ted on Fri Dec 2 | 3 15:22:48 2011
@author: moritz
"""
__all__ = ["bslip"]
|
alfkjartan/nvgimu | nvg/testing/trajectories.py | Python | gpl-3.0 | 2,671 | 0.002995 | """
Utilities for testing trajectories.
"""
# Copyright (C) 2009-2011 University of Edinburgh
#
# This file is part of IMUSim.
#
# IMUSim 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.
#
# IMUSim is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public L... | have received a copy of the GNU General Public License
# along with IMUSim. If not, see <http://www.gnu.org/licenses/>.
from __future__ import division
from imusim.testing.quaternions import assertQuaternionAlmostEqual
from imusim.maths.quaternions import QuaternionArray
from imusim.testing.vectors import assert_vec... |
cgwire/zou | tests/shots/test_breakdown.py | Python | agpl-3.0 | 4,949 | 0 | from tests.base import ApiDBTestCase
from zou.app.models.entity import Entity
class BreakdownTestCase(ApiDBTestCase):
def setUp(self):
super(BreakdownTestCase, self).setUp()
self.generate_fixture_project_status()
self.generate_fixture_project()
self.generate_fixture_asset_type()
... | ies/%s/casting"
% (self.project_id, self.shot_id)
)
casting = sorted(casting, key=lambda x: x["nb_occurences"])
self.assertEqual(casting[0]["asset_id"], newCasting[0]["asset_id"])
self.assertEqual(
casting[0]["nb_occurences"], newCasting[0]["nb_occurences"]
... | (
casting[1]["nb_occurences"], newCasting[1]["nb_occurences"]
)
self.assertEqual(casting[1]["asset_name"], self.asset_character.name)
self.assertEqual(
casting[1]["asset_type_name"], self.asset_type_character.name
)
cast_in = self.get("/data/assets/%s/cas... |
dims/cinder | cinder/volume/drivers/netapp/dataontap/client/client_base.py | Python | apache-2.0 | 15,903 | 0 | # Copyright (c) 2014 Alex Meade. All rights reserved.
# Copyright (c) 2014 Clinton Knight. All rights reserved.
# Copyright (c) 2015 Tom Barron. 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 ob... | NTAP features."""
self.features = na_utils.Features()
def get_ontapi_version(self | , cached=True):
"""Gets the supported ontapi version."""
if cached:
return self.connection.get_api_version()
ontapi_version = netapp_api.NaElement('system-get-ontapi-version')
res = self.connection.invoke_successfully(ontapi_version, False)
major = res.get_child_con... |
rlindner81/pyload | module/plugins/crypter/NosvideoCom.py | Python | gpl-3.0 | 917 | 0.002181 | # -*- coding: utf-8 -*-
from module.plugins.internal.SimpleCrypter import SimpleCrypter
class NosvideoCom(SimpleCrypter):
__name__ = "NosvideoCom"
__type__ = "crypter"
__version__ = "0.07"
__status__ = "testing"
__pattern__ = r'http://(?:www\.)?nosvideo\.com/\?v=\w+'
__config__ = [("activate... | "Create folder for each package", "Default"),
("max_wait", "int", "Reconnect if waiting time is gre | ater than minutes", 10)]
__description__ = """Nosvideo.com decrypter plugin"""
__license__ = "GPLv3"
__authors__ = [("igel", "igelkun@myopera.com")]
LINK_PATTERN = r'href="(http://(?:w{3}\.)?nosupload\.com/\?d=\w+)"'
NAME_PATTERN = r'<[tT]itle>Watch (?P<N>.+?)<'
|
TheTimmy/spack | var/spack/repos/builtin/packages/r-modelmetrics/package.py | Python | lgpl-2.1 | 1,657 | 0.001207 | ##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | e Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
from spack import *
class RModelmetrics(RPackage):
"""Collect | ion of metrics for evaluating models written in C++ using
'Rcpp'."""
homepage = "https://cran.r-project.org/package=ModelMetrics"
url = "https://cran.r-project.org/src/contrib/ModelMetrics_1.1.0.tar.gz"
version('1.1.0', 'd43175001f0531b8810d2802d76b7b44')
depends_on('r@3.2.2:')
depends_... |
stack-of-tasks/sot-stabilizer | python/scripts/robotViewerLauncher.py | Python | lgpl-3.0 | 1,912 | 0.028766 | import sys
# --- ROBOT DYNAMIC SIMULATION -------------------------------------------------
from dynamic_graph.sot.hrp2_14.robot import | Robot
robot = Robot( 'robot' )
# --- LINK ROBOT VIEWER -------------------------------------------------------
from dynamic_graph.sot.core.utils.viewer_helper import addRobotViewer
addRobotViewer(robot.device,small=True,verbose=False)
robot.timeStep=5e-3
usingRobotViewer = True
from dynamic_graph.sot.cor | e import Stack_of_vector
acc = Stack_of_vector('acc')
gyr = Stack_of_vector('gyr')
acc.selec1(0,2)
acc.selec2(0,1)
gyr.selec1(0,2)
gyr.selec2(0,1)
acc.sin1.value=(0.0,0.0)
acc.sin2.value=(9.8,)
gyr.sin1.value=(0.0,0.0)
gyr.sin2.value=(0.0,)
robot.device.accelerometer = acc.sout
robot.device.gyrometer = gyr.sout
rob... |
zstackio/zstack-woodpecker | zstackwoodpecker/zstackwoodpecker/zstack_test/vid_checker/zstack_vid_checker.py | Python | apache-2.0 | 135,498 | 0.006295 | '''
IAM2 Vid Attribute Checker.
'''
import zstackwoodpecker.test_util as test_util
import zstackwoodpecker.header.checker as checker_header
import zstackwoodpecker.operations.iam2_operations as iam2_ops
import zstackwoodpecker.operations.resource_operations as res_ops
import zstackwoodpecker.operations.vm_operations a... | itions('system', '=', 'false')
conditions = res_ops.gen_query_conditions('category', '=', 'Private', conditions)
l3_net_uuid = res_ops.query_resource(res_ops.L3_NETWORK, conditions, session_uuid=session_uuid)[0].uuid
vm_creation_option.set_l3_uuids([l3_net_uuid])
conditions = res_ops.gen... | image_uuid = res_ops.query_resource(res_ops.IMAGE, conditions, session_uuid=session_uuid)[0].uuid
vm_creation_option.set_image_uuid(image_uuid)
conditions = res_ops.gen_query_conditions('type', '=', 'UserVm')
instance_offering_uuid = res_ops.query_resource(res_ops.INSTANCE_OFFERING, conditions,... |
tryolabs/luminoth | luminoth/tools/dataset/readers/__init__.py | Python | bsd-3-clause | 670 | 0 | from .base_reader import BaseReader, InvalidDataDirectory # noqa
from .object_detection import ObjectDetectionReader # noqa
from .object_detection import (
COCOReader, CSVReader, FlatReader, Ima | geNetReader, OpenImagesReader,
PascalVOCReader, TaggerineReader
)
READERS = {
'coco': COCOReader,
'csv': CSVReader,
'flat': FlatReader,
'imagenet': ImageNetReader,
'openimages': OpenImagesReader,
'pascal': PascalVOCReader,
| 'taggerine': TaggerineReader,
}
def get_reader(reader):
reader = reader.lower()
if reader not in READERS:
raise ValueError('"{}" is not a valid reader'.format(reader))
return READERS[reader]
|
strobo-inc/pc-nrfutil | nordicsemi/utility/__init__.py | Python | bsd-3-clause | 1,580 | 0.000633 | # Copyright (c) 2015, Nordic Semiconductor
# All rights reserved.
#
# Redistr | ibution 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 following disclaimer.
#
# * Redistributions in binary form must repro... | ing disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * Neither the name of Nordic Semiconductor ASA nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE I... |
endlessm/chromium-browser | third_party/grpc/src/src/python/grpcio_tests/tests/protoc_plugin/beta_python_plugin_test.py | Python | bsd-3-clause | 26,919 | 0.000186 | # Copyright 2015 gRPC authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... | ontext):
return servicer_methods.Unary | Call(request, context)
def StreamingOutputCall(self, request, context):
return servicer_methods.StreamingOutputCall(request, context)
def StreamingInputCall(self, request_iter, context):
return servicer_methods.StreamingInputCall(request_iter, context)
def FullDuplexCa... |
slaymaker1907/hearthbreaker | tests/card_tests/id_mapping.py | Python | mit | 23,324 | 0 | id_mappings = {
"EX1_097": "Abomination",
"CS2_188": "Abusive Sergeant",
"EX1_007": "Acolyte of Pain",
"NEW1_010": "Al'Akir the Windlord",
"EX1_006": "Alarm-o-Bot",
"EX1_382": "Aldor Peacekeeper",
"EX1_561": "Alexstrasza",
"EX1_393": "Amani Berserker",
"CS2_038": "Ancestral Spirit",
... | ",
"EX1_507": "Murloc Warleader",
"EX1_557": "Nat Pagle",
"EX1_161" | : "Naturalize",
"DREAM_05": "Nightmare",
"EX1_130": "Noble Sacrifice",
"EX1_164b": "Nourish",
"EX1_164a": "Nourish",
"EX1_164": "Nourish",
"EX1_560": "Nozdormu",
"EX1_562": "Onyxia",
"EX1_160t": "Panther",
"EX1_522": "Patient Assassin",
"EX1_133": "Perdition's Blade",
"EX1_07... |
normpad/iotatipbot | test/bot_api.py | Python | gpl-3.0 | 13,535 | 0.012412 | import re
from iota import *
import praw
import sqlite3
import random
import string
from iota.adapter.wrappers import RoutingWrapper
import config
import urllib.request
from urllib.error import HTTPError
import json
import math
node_address = config.node_address
class api:
def __init__(self,seed,prod=True):
... | price = data['price_usd']
value = (amount/1000000)*float(price)
return value
except:
return am | ount/1000000
#---------IOTA API FUNCTIONS--------------#
def send_transfer(self,addr,amount):
ret = self.iota_api.send_transfer(
depth = 3,
transfers = [
ProposedTransaction(
address = Address(
addr
... |
TheTimmy/spack | var/spack/repos/builtin/packages/llvm-lld/package.py | Python | lgpl-2.1 | 1,980 | 0.000505 | ##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | 78e')
depends_on('llvm')
depends_on('cmake@2.8:', type='build')
def cmake_args(self):
if 'CXXFLAGS' in env and env['CXXFLAGS']:
env['CXXFLAGS'] += ' ' + self.compiler.cxx11_flag
else:
env['CXXFLAGS'] = self.compiler.cxx11_flag
return [
'-DLLD_PA... | ]
|
pheanex/ansible | lib/ansible/playbook/base.py | Python | gpl-3.0 | 18,228 | 0.002524 | # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) an... | _loader = None
self._variable_manager | = None
# every object gets a random uuid:
self._uuid = uuid.uuid4()
# and initialize the base attributes
self._initialize_base_attributes()
try:
from __main__ import display
self._display = display
except ImportError:
from ansible.u... |
brain-tec/partner-contact | partner_phone_search/__manifest__.py | Python | agpl-3.0 | 616 | 0 | # Copyright 2018 - TODAY Serpent Consulting | Services Pvt. Ltd.
# (<http://www.serpentcs.com>)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
{
'name': 'Search Partner Phone/Mobile/Email',
'version': '11.0.1.0.1',
'category': 'Extra Tools',
'summary': 'Partner Search by Phone/Mobile/Email',
'author': "Serpent Consulti... | munity Association (OCA)",
'website': 'https://github.com/OCA/partner-contact',
'license': 'AGPL-3',
'depends': [
'base',
],
'installable': True,
'auto_install': False,
}
|
everfor/Neural_Artistic_Style | vgg.py | Python | mit | 2,235 | 0.008501 | import tensorflow as tf
import numpy as np
import scipy.io
vgg_layers = [
'conv1_1', 'relu1_1', 'conv1_2', 'relu1_2', 'pool1',
'conv2_1', 'relu2_1', 'conv2_2', 'relu2_2', 'pool2',
'conv3_1', 'relu3_1', 'conv3_2', 'relu3_2', 'conv3_3', 'relu3_3', 'conv3_4', 'relu3_4', 'pool3',
'conv4_1', 'relu4_1', 'con... | pretrained_net = scipy.io.loadmat(path_network)
# Mean of input pixels - used to normalize input images
mean = np.mean(pretrained_net['normalization'][0][0][0], axis = (0, 1))
layers = pretrained_net['layers'][0]
convnet = {}
| current = input_image
for i, name in enumerate(vgg_layers):
if vgg_layer_types[i] == 'conv':
# Convolution layer
kernel, bias = layers[i][0][0][0][0]
# (width, height, in_channels, out_channels) -> (height, width, in_channels, out_channels)
kernels = np.tr... |
shubhamVerma/code-eval | Category - Easy/primePalindromeCodeEval.py | Python | gpl-3.0 | 1,290 | 0.020155 | '''
primepalCodeEval.py - Solution to Problem Prime Palindrome (Category - Easy)
Copyright (C) 2013, Shubham Verma
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as pub | lished by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURP | OSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
'''
'''
Description:
Write a program to determine the biggest prime palindrome under 1000.
Input sample:
... |
MaxIV-KitsControls/netspot | netspot/lib/spotmax/helpers.py | Python | mit | 1,004 | 0.025896 | #!/usr/bin/python -tt
"""Helper functions."""
from dns import resolver
# Exceptions
class CouldNotResolv(Exception):
"""Exception for unresolvable hostname."""
pass
def resolv(hostname):
"""Select and query DNS servers.
Args:
hostname: string, hostname
Returns:
ips: list, list of IPs
"""
ip... | s.na | meservers = ['172.16.2.10', '172.16.2.11']
# Green DNS servers
elif hostname.startswith('g-'):
res.nameservers = ['10.0.2.10', '10.0.2.11']
# Default to white DNS servers
else:
res.nameservers = ['194.47.252.134', '194.47.252.135']
# Query
try:
query = res.query(hostname)
for answer in quer... |
ponty/pyscreenshot | pyscreenshot/check/speedtest.py | Python | bsd-2-clause | 3,228 | 0.002169 | import sys
import time
from entrypoint2 import entrypoint
import pyscreenshot
from pyscreenshot.plugins.gnome_dbus import GnomeDBusWrapper
from pyscreenshot.plugins.gnome_screenshot import GnomeScreenshotWrapper
from pyscreenshot.plugins.kwin_dbus import KwinDBusWrapper
from pyscreenshot.util import run_mod_as_subpro... | back-end can be forced if set (example:default, scrot, wx,..),
otherwise all back-ends are tested
:param childprocess: pyscreenshot parameter childprocess (0/1)
:param number: number of screenshots for each backend (default:10)
"""
childprocess_param = childprocess
if childproces... | rue # default
elif childprocess == "0":
childprocess = False
elif childprocess == "1":
childprocess = True
else:
raise ValueError("invalid childprocess value")
if bbox:
x1, y1, x2, y2 = map(int, bbox.split(":"))
bbox = x1, y1, x2, y2
else:
bbox = Non... |
sassoo/goldman | goldman/models/__init__.py | Python | mit | 353 | 0 | """
models
~~~~~~
Module containing all | of our models that are typically
accessed in a CRUD like manner.
"""
from ..models.base import Model as BaseModel
from ..models.default_schema import Model as Defau | ltSchemaModel
from ..models.login import Model as LoginModel
MODELS = [
BaseModel,
DefaultSchemaModel,
LoginModel,
]
|
missionpinball/mpf | mpf/tests/test_PlayerVars.py | Python | mit | 2,380 | 0.006303 | from mpf.tests.MpfGameTestCase import MpfGameTestCase
class TestPlayerVars(MpfGameTestCase):
def get_config_file(self):
return 'player_vars.yaml'
def get_machine_path(self):
return 'tests/machine_files/player_vars/'
def test_initial_values(self):
self.fill_troughs()
self... | foo='bar')
self.machine.game.player.set_with_kwargs('some_var', 1, bar='foo')
self.advance_time_and_run()
self.assertEventCalledWith('player_some_var',
| value=1,
prev_value=10,
change=-9,
player_num=1,
bar='foo')
|
duducosmos/pgs4a | python-install/bin/smtpd.py | Python | lgpl-2.1 | 18,597 | 0.00043 | #!/home/tom/ab/android/python-for-android/build/python-install/bin/python2.7
"""An RFC 2821 smtp proxy.
Usage: %(program)s [options] [localhost:localport [remotehost:remoteport]]
Options:
--nosetuid
-n
This program generally tries to setuid `nobody', unless this flag is
set. The setuid call ... | r of classes are provided:
#
# SMTPServer - the base clas | s for the backend. Raises NotImplementedError
# if you try to use it.
#
# DebuggingServer - simply prints each message it receives on stdout.
#
# PureProxy - Proxies all messages to a real smtpd which does final
# delivery. One known problem with this class is that it doesn't handle
# SMTP errors from the b... |
fooelisa/netmiko | netmiko/_textfsm/_clitable.py | Python | mit | 12,990 | 0.007467 | """
Google's clitable.py is inherently integrated to Linux:
This is a workaround for that (basically include modified clitable code without anything
that is Linux-specific).
_clitable.py is identical to Google's as of 2017-12-17
_texttable.py is identical to Google's as of 2017-12-17
_terminal.py is a highly stripped... | /www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied. See the Li | cense for the specific language governing
# permissions and limitations under the License.
import copy
import os
import re
import threading
import copyable_regex_object
import textfsm
from netmiko._textfsm import _texttable as texttable
class Error(Exception):
"""Base class for errors."""
class IndexTableError(E... |
arthurio/coc_war_planner | coc_war_planner/api/views.py | Python | mit | 3,228 | 0.002478 | from coc_war_planner.api.permissions import CreateNotAllowed
from coc_war_planner.api.permissions import IsChiefOrReadOnly
from coc_war_planner.api.permissions import IsUserOrReadOnly
from coc_war_planner.api.permissions import IsOwnerOrReadOnly
from coc_war_planner.api.permissions import IsNotPartOfClanOrCreateNotAllo... | er
class TroopsViewSet(viewsets.ModelViewSet):
permission_classes = (permissions.IsAuthenticatedOrReadOnly,
IsOwnerOrReadOnly,)
def get_serializer_class(self):
if self.request.method == 'POST':
return TroopsPostSerializer
elif self.request.method == 'PUT':
... | self):
member_id = self.request.GET.get('member_id', self.request.user.member.id)
if member_id is None:
raise serializers.ValidationError({
'member_id': 'Parameter is missing.'
})
troops = Troops.objects.filter(member_id=member_id)
troops_id = se... |
andrius-preimantas/purchase-workflow | purchase_order_force_number/__openerp__.py | Python | agpl-3.0 | 1,589 | 0 | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2013 Agile Business Group sagl
# (<http://www.agilebg.com>)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public ... | ',
"depends": ['purchase'],
"data": [
| 'purchase_view.xml',
],
"demo": [],
"active": False,
"installable": False
}
|
Aramist/Self-Driving-Car | ros/install/_setup_util.py | Python | mit | 12,461 | 0.002568 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Software License Agreement (BSD License)
#
# Copyright (c) 2012, Willow Garage, 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:
#
# * Redistrib... | path in value.split(os.pathsep) if path]
value_modified = False
for subfolder in subfolders:
if subfolder:
if subfolder.startswith(os.path.sep) or (os.path.altsep and subfolder.startswith(os.path.altsep)):
subfolder = subfolder[1:]
if subfolder.endswith(os.path.se... | ath.altsep)):
subfolder = subfolder[:-1]
for ws_path in _get_workspaces(environ, include_fuerte=True, include_non_existing=True):
path_to_find = os.path.join(ws_path, subfolder) if subfolder else ws_path
path_to_remove = None
for env_path in env_paths:
... |
PBR/path2gene | path2gene.py | Python | bsd-3-clause | 8,068 | 0.005949 | #!/usr/bin/python
"""
Small web application to retrieve genes from the tomato genome
annotation involved to a specified pathways.
"""
import flask
from flaskext.wtf import Form, TextField
import ConfigParser
import datetime
import json
import os
import rdflib
import urllib
CONFIG = ConfigParser.ConfigParser()
CON... | , a string, name of the pathway for which to retrieve the
genes in the tomato genome annotation.
@return, a hash of th | e genes name and description found to be
associated with the specified pathway.
"""
query = '''
PREFIX gene:<http://pbr.wur.nl/GENE#>
PREFIX rdfs:<http://www.w3.org/2000/01/rdf-schema#>
PREFIX uniprot:<http://purl.uniprot.org/core/>
SELECT DISTINCT ?gene ?desc
FROM <%(itag)s>
... |
scheib/chromium | third_party/blink/tools/blinkpy/tool/mock_tool.py | Python | bsd-3-clause | 1,739 | 0 | # Copyright (C) 2011 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 f... | ETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from blinkpy.common.host_mock import MockHost
class MockBlinkTool(MockHost):
def __i | nit__(self, *args, **kwargs):
MockHost.__init__(self, *args, **kwargs)
def path(self):
return 'echo'
|
stvstnfrd/edx-platform | openedx/core/djangoapps/enrollments/urls.py | Python | agpl-3.0 | 1,148 | 0.002613 | """
URLs for the Enrollment API
"""
from django.conf import settings
from django.conf.urls import url
from .views import (
CourseEnrollmentsApiListView,
EnrollmentCourseDetailView,
EnrollmentListView,
EnrollmentUserRolesView,
EnrollmentView,
UnenrollmentView
)
urlpatterns = [
url(r'^enr... | enrollment'),
url(r'^enrollment/{course_key}$'.format(course_key=settings.COURSE_ID_PATTERN),
EnrollmentView.as_view(), name='courseenrollment'),
url(r'^enrollment$', EnrollmentListView.as_view(), name='courseenrollments'),
url(r'^enrollments/?$', CourseEnrollmentsApiListView.as_view(), name='course... | =settings.COURSE_ID_PATTERN),
EnrollmentCourseDetailView.as_view(), name='courseenrollmentdetails'),
url(r'^unenroll/$', UnenrollmentView.as_view(), name='unenrollment'),
url(r'^roles/$', EnrollmentUserRolesView.as_view(), name='roles'),
]
|
tri2sing/LinearAlgebraPython | vec.py | Python | apache-2.0 | 3,573 | 0.012315 | def getitem(v,d):
"Returns the value of entry d in v"
assert d in v.D
return v.f[d] if d in v.f else 0
def setitem(v,d,val):
"Set the element of v with label d to be val"
assert d in v.D
v.f[d] = val
def equal(u,v):
"Returns true iff u is equal to v"
assert u.D == v.D
union = set(u... | set(u.f)
vkeys = set (v.f)
both = ukeys & vkeys
uonly = ukeys - both
vonly = vkeys - both
f = {}
for k in both:
f[k] = u.f[k] + v.f[k]
for | k in uonly:
f[k] = u.f[k]
for k in vonly:
f[k] = v.f[k]
return Vec (u.D | v.D, f)
def dot(u,v):
"Returns the dot product of the two vectors"
assert u.D == v.D
ukeys = set(u.f)
vkeys = set (v.f)
both = ukeys & vkeys
return sum([u.f[k] * v.f[k] for k in both])
def sc... |
enigmampc/catalyst | tests/utils/test_argcheck.py | Python | apache-2.0 | 7,116 | 0 | #
# Copyright 2014 Quantopian, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... | llable_argspec(not_callable)
def test_no_starargs(self):
"""
Tests when a function does not have *args and it was expected.
"""
def f(a):
pass
with self.assertRaises(NoStarargs):
verify_callable_argspec(f, expect_starargs=True)
def test_starargs... | expect_starargs=True)
def test_unexcpected_starargs(self):
"""
Tests a function that unexpectedly accepts *args.
"""
def f(*args):
pass
with self.assertRaises(UnexpectedStarargs):
verify_callable_argspec(f, expect_starargs=False)
def test_ignor... |
rgayon/plaso | tests/analysis/mediator.py | Python | apache-2.0 | 1,743 | 0.004016 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Tests for the analysis mediator."""
from __future__ import unicode_literals
import unittest
from dfvfs.lib import definitions as dfvfs_definitions
from | dfvfs.path import factory as path_spec_factory
from plaso.analysis import mediator
from plaso.containers import sessions
from plaso.storage.fake import writer as fake_writer
from tests.analysis import test_lib
class AnalysisMediatorTest(test_lib.AnalysisPluginTestCase):
"""Tests for the analysis mediator."""
... | ."""
session = sessions.Session()
storage_writer = fake_writer.FakeStorageWriter(session)
knowledge_base = self._SetUpKnowledgeBase()
analysis_mediator = mediator.AnalysisMediator(
storage_writer, knowledge_base)
test_path = self._GetTestFilePath(['syslog.gz'])
os_path_spec = path_spec... |
MarsZone/DreamLand | evennia/evennia/commands/default/cmdset_unloggedin.py | Python | bsd-3-clause | 821 | 0 | """
This module describes the unlogged state of the default game.
The setting STATE_UNLOGGED should be set to the python path
of the state instance in this module.
"""
from evennia.commands.cmdset import CmdSet
from evennia.commands.default import unloggedin
class UnloggedinCmdSet(CmdSet):
"""
Sets up the unl... | oggedin"
priority = 0
def at_cmdset_creation(self):
"Populate the cmdset"
self.add(unloggedin.CmdUnconnectedConnect())
self.add(unloggedin.CmdUnconnectedCreate())
self.add(unloggedin.CmdUnconnectedQuit())
self.add(unloggedin.CmdUnconnectedLook())
self.add(unlogge... | nconnectedHelp())
self.add(unloggedin.CmdUnconnectedEncoding())
self.add(unloggedin.CmdUnconnectedScreenreader())
|
mantarayforensics/mantaray | Tools/Python/get_system_version.py | Python | gpl-3.0 | 3,323 | 0.020163 | #!/usr/bin/env python3
#This extracts data from xml plists
#
#########################COPYRIGHT INFORMATION############################
#Copyright (C) 2013 dougkoster@hotmail.com #
#This program is free software: you can redistribute it and/or modify #
#it under the terms of the GNU General Public License as... | xport_file.write('File Path: ' + "\t" + abs_file_path + "\n")
export_file.write('MD5: ' + "\t\t" + str(md5) + "\n\n")
print(abs_file_path + " has a plist attribute that is a dict")
process_dict(plist_info, outfile, export_file, key_name)
elif(str(type(plist_info)) == "<class 'plistlib._InternalDict'>"):
expo... | file.write('File Path: ' + "\t" + abs_file_path + "\n")
export_file.write('MD5: ' + "\t\t" + str(md5) + "\n")
print(abs_file_path + " has a plist attribute that is an internal dict")
process_dict(plist_info, outfile, export_file, key_name)
def process_dict(dictionary_plist, outfile, export_file, key_name):
#lo... |
sonali0901/zulip | zerver/webhooks/hellosign/tests.py | Python | apache-2.0 | 884 | 0.005656 | # -*- coding: utf-8 -*-
from typing import Text
from zerver.lib.test_classes import WebhookTestCase
class HelloSignHookTests(WebhookTestCase):
STREAM_NAME = 'hellosign'
URL_TEMPLATE = "/api/v1/external/hellosign?stream={stream}&api_key | ={api_key}"
FIXTURE_DIR_NAME = 'hellosign'
def test_signatures_message(self):
# type: () -> None
expected_subject = "NDA with Acme Co."
expected_message = ("The NDA with Acme Co. is awaiting the signature of "
"Jack and was just signed by Jill.")
self... | content_type="application/x-www-form-urlencoded")
def get_body(self, fixture_name):
# type: (Text) -> Text
return self.fixture_data("hellosign", fixture_name, file_type="json")
|
to266/hyperspy | hyperspy/external/tifffile.py | Python | gpl-3.0 | 172,696 | 0.000029 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# tifffile.py
# Copyright (c) 2008-2014, Christoph Gohlke
# Copyright (c) 2008-2014, The Regents of the University of California
# Produced a | t the Laboratory for Fluorescenc | e Dynamics
# 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 following disclaimer.
# ... |
svost/bitcoin | qa/rpc-tests/bumpfee.py | Python | mit | 14,241 | 0.002036 | #!/usr/bin/env python3
# Copyright (c) 2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
from segwit import send_to_witness
from test_framework.test_framework import BitcoinTestFramework
from test_fr... | ess(rbf_node): | Decimal("0.00010000")})
assert_raises_message(JSONRPCException, "Change output is too small", rbf_node.bumpfee, rbfid, {"totalFee": 20001})
def test_dust_to_fee(rbf_node, dest_address):
# check that if output is reduced to dust, it will be converted to fee
# the bumped tx sets fee=9900, but it converts to... |
Superchicken1/DirtyDrive | DirtyDrive/apps.py | Python | apache-2.0 | 136 | 0 | from __future__ import unicode_literals
f | rom django.apps import AppConfig
class DirtyDriveConfig(AppC | onfig):
name = 'DirtyDrive'
|
dabodev/dabodoc | api/epydoc/man.py | Python | mit | 8,842 | 0.005881 | # epydoc.py: manpage-style text output
# Edward Loper
#
# Created [01/30/01 05:18 PM]
# $Id: man.py,v 1.6 2003/07/18 15:46:19 edloper Exp $
#
"""
Documentation formatter that produces man-style documentation.
@note: This module is under development. It generates incomplete
documentation pages, and is not yet incorpe... | # Helpers
#////////////////////////////////////////////////////////////
def _bold(self, text):
""" | Format a string in bold by overstriking."""
return ''.join([ch+'\b'+ch for ch in text])
def _title(self, text):
return '%s\n' % self._bold(text)
def _kind(self, uid):
if uid.is_package(): return 'package'
elif uid.is_module(): return 'module'
elif uid.is_class(): return... |
googleapis/python-aiplatform | google/cloud/aiplatform_v1/services/index_endpoint_service/transports/grpc_asyncio.py | Python | apache-2.0 | 21,535 | 0.002136 | # -*- 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... | authorization credentials to attach to requests. These
credentials identify the application to the service; if none
are specified, the client will attempt to ascertain the
credentials from the environment.
This argument is ignored if ``chan... | be loaded with :func:`google.auth.load_credentials_from_file`.
This argument is ignored if ``channel`` is provided.
scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
service. These are only used when credentials are not specified and
... |
yorzh86/Step1 | scripts/post.py | Python | gpl-2.0 | 1,575 | 0.040635 | #!/usr/bin/env python
from pylab import *
t,x,y,u,v,ax,ay = loadtxt('trajectory.dat',unpack=True)
r = sqrt(x**2+y**2)
k = u**2+v**2
s = '.' if t.size < 100 else ''
figure('Trajectory',figsize=(5,4))
subplot(111,aspect=1)
plot(x,y,'b%s-'%s,lw=1)
xl,xh = (x.min(),x.max())
xb = 0.1*(xh-xl)
xlim(xl-xb,xh+xb) |
yl,yh = (y.min(),y.max())
yb = 0.1*(yh-yl)
ylim(yl-yb,yh+yb)
xlabel(r'$x$-coordinate [m]')
ylabel(r'$y$-coordinate [m]')
tight_layout()
figure('',figsize=(8,8))
subplot(221)
#~ figure('Decay',figsize=(5,4))
plot(t,r,'r%s-'%s)
yl,yh = ylim()
yb = 0.1*(yh-0)
ylim(0-yb,yh+5*yb)
xlabel(r'Time $t$ [s]')
ylabel(r'Radius $... | )
yl,yh = ylim()
yb = 0.1*(yh-0)
ylim(0-yb,yh+5*yb)
xlabel(r'Time $t$ [s]')
ylabel(r'Kinetic Energy $KE$ [J]')
#~ tight_layout()
subplot(223)
#~ figure('Velocities',figsize=(5,4))
plot(t,u,'r%s-'%s,label=r'$\vec{v}\cdot\hat{e}_x$')
plot(t,v,'b%s-'%s,label=r'$\vec{v}\cdot\hat{e}_y$')
yl,yh = ylim()
yb = 0.1*(yh-yl)
yli... |
ryansb/workstation | roles/unbound/files/ddns.py | Python | mit | 1,890 | 0.005291 | #!/usr/bin/env python3
import os
import sys
import json
import boto3
import platform
import traceback
import subprocess
from datetime import datetime
config = {}
with open(os.path.expanduser('~/.ddns.conf')) as conf:
config.update(json.load(conf))
ZONE_ID = config['zone_id']
ROOT = config['root']
HOST = config.ge... | '.split(' ')
try | :
return subprocess.check_output(cmd).decode('utf-8').strip()
except Exception as exc:
print(f'{datetime.utcnow().isoformat()}+UTC Failed to read DNS name - bailing out')
traceback.print_exc()
sys.exit(1)
def my_ip():
return dig_ip('myip.opendns.com')
def change_recordset(curre... |
darkshark007/PoGoCollection | Data/moves.py | Python | gpl-3.0 | 11,221 | 0.111755 | class BASIC_MOVE:
ID = 0
Name = 1
Type = 2
PW = 3
Duration = 4
NRG = 5
NRGPS = 6
DPS = 7
# Adapted from the GAME_MASTER_FILE Json Output at:
# https://github.com/pokemongo-dev-contrib/pokemongo-game-master/
# https://raw.githubusercontent.com/pokemongo-dev-contrib/pokemongo-game-master/... | 88888888888889,11.11111111111111],
[219,"Quick Attack","Normal",8,800,10,12.5,10],
[220,"Scratch","Normal",6,500,4,8,12],
[221,"Tackle","Normal",5,500,5,10,10],
[222,"Pound","Normal",7,600,6,10,11.666666666666668],
[223,"Cut","Normal",5,500,5,10,10],
[224,"Poison Jab","Poison",10,800,7,8.75,12.5... | oison",9,800,8,10,11.25],
[226,"Psycho Cut","Psychic",5,600,8,13.333333333333334,8.333333333333334],
[227,"Rock Throw","Rock",12,900,7,7.777777777777779,13.333333333333334],
[228,"Metal Claw","Steel",8,700,7,10,11.428571428571429],
[229,"Bullet Punch","Steel",9,900,10,11.11111111111111,10],
[230,"Wa... |
ua-snap/downscale | snap_scripts/epscor_sc/move_raw_cmip5_tas_pr.py | Python | mit | 1,039 | 0.052936 | # # # # #
# MOVE THE NEWLY DOWNLOADED TAS / PR CMIP5 data from work desktop to /Shared
# # # # #
def move_new_dir( fn, output_dir ):
dirname, basename = os.path.split( fn )
elems = basename.split('.')[0].split( '_' )
variable, cmor_table, model, | scenario, experiment, years = elems
new_dir = os.path.join( output_dir, model, scenario, variable )
try:
if not os.path.exists( new_dir ):
os.makedirs( new_dir )
except:
pass
return shutil.copy( fn, new_dir )
if __name__ == '__main__':
import os, glob, shutil
path = '/srv/synda/sdt/data'
output_dir = '/w... | ist = []
for root, subs, files in os.walk( path ):
if len( files ) > 0:
filelist = filelist + [ os.path.join( root, i ) for i in files if i.endswith( '.nc' ) ]
out = [ move_new_dir( fn, output_dir ) for fn in filelist ]
# # # # # # # #
# # CHECK FOR DUPLICATES and remove by hand. this is tedious.
# GFDL - OK... |
GuessWhoSamFoo/pandas | pandas/tests/indexes/timedeltas/test_astype.py | Python | bsd-3-clause | 4,066 | 0 | from datetime import timedelta
import numpy as np
import pytest
import pandas as pd
from pandas import (
Float64Index, Index, Int64Index, NaT, Timedelta, TimedeltaIndex,
timedelta_range)
import pandas.util.testing as tm
class TestTimedeltaIndex(object):
def test_astype_object(self):
idx = timede... | lta('4 days')]
result = idx.astype(object)
expected = Index(expected_list, dtype=object, name='idx')
tm.assert_index_equal(result, expected)
assert idx.tolist() == expected_list
def test_astype(self):
# GH 13149, GH 13209
idx = TimedeltaIndex([1e14, 'NaT', NaT, np.Na... | tm.assert_index_equal(result, expected)
result = idx.astype(int)
expected = Int64Index([100000000000000] + [-9223372036854775808] * 3,
dtype=np.int64)
tm.assert_index_equal(result, expected)
result = idx.astype(str)
expected = Index(str(x) for ... |
meisterkleister/erpnext | erpnext/hr/doctype/salary_slip/salary_slip.py | Python | agpl-3.0 | 7,265 | 0.025327 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
from frappe.utils import add_days, cint, cstr, flt, getdate, nowdate, rounded
from frappe.model.naming import make_autoname
from frappe ... | holidays_in_total_working_days")):
m["month_days"] -= len(holidays)
if m["month_days"] < 0:
frappe.throw(_("There are more holidays than working days this month."))
if not lwp:
lwp = self.calculate_lwp(holidays, m)
self.total_days_in_month = m['month_days']
self.leave_without_pay = lwp
payment_... | ment_days = payment_days > 0 and payment_days or 0
def get_payment_days(self, m):
payment_days = m['month_days']
emp = frappe.db.sql("select date_of_joining, relieving_date from `tabEmployee` \
where name = %s", self.employee, as_dict=1)[0]
if emp['relieving_date']:
if getdate(emp['relieving_date']) > m... |
Fl0r14n/django_googleapi | gdrive/urls.py | Python | mit | 560 | 0 | from django.conf import settings
from django.conf.urls import patterns, url
from django.contrib.auth.views import login, logout
import views
urlpatterns = patterns(
'gauth',
url(r'^login/$', login, {'template_name': 'login.html'}, name='login'),
url(r'^login/$', logout, {'template_name': 'logout.html'}, ... | ', views.oauth2_complete, name='oauth2_complete'), |
)
|
openstack/heat | heat/common/policy.py | Python | apache-2.0 | 7,615 | 0 | #
# Copyright (c) 2011 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not us | e this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distribu | ted 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.
# Based on glance/api/policy.py
"""Policy Engine For Heat."""
from oslo_c... |
sdgdsffdsfff/pymesos | pymesos/scheduler.py | Python | bsd-3-clause | 8,630 | 0.003708 | import time
import logging
import struct
import socket
from mesos.interface.mesos_pb2 import TASK_LOST, MasterInfo
from .messages_pb2 import (
RegisterFrameworkMessage, ReregisterFrameworkMessage,
DeactivateFrameworkMessage, UnregisterFrameworkMessage,
ResourceRequestMessage, ReviveOffersMessage, LaunchTa... | f.framework_id)
self.send(sel | f.master, msg)
@async
def reconcileTasks(self, statuses=None):
if not self.connected:
return
msg = ReconcileTasksMessage()
msg.framework_id.MergeFrom(self.framework_id)
if statuses is not None:
msg.statuses = statuses
self.send(self.master, msg)
... |
xapple/pyrotrfid | doc/conf.py | Python | gpl-3.0 | 7,241 | 0.005662 | # -*- coding: utf-8 -*-
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys, os... | '11pt' or '12pt').
#latex_font_size = '10pt'
# Grouping the document tree into LaTeX files. | List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [('index', 'pyrotrfid.tex', u'pyrotrfid Documentation', u'', 'manual')]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" ... |
seecloud/ceagle | ceagle/api/v1/regions.py | Python | apache-2.0 | 1,652 | 0 | # Copyright 2016: Mirantis 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... | IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import flask
from oss_lib im | port config
from ceagle.api import client
from ceagle.api_fake_data import fake_regions
CONF = config.CONF
bp = flask.Blueprint("regions", __name__)
@bp.route("", defaults={"detailed": False})
@bp.route("/detailed", defaults={"detailed": True})
@fake_regions.get_regions
def get_regions(detailed):
regions = {}
... |
nugget/home-assistant | homeassistant/components/bmw_connected_drive/lock.py | Python | apache-2.0 | 3,775 | 0 | """Support for BMW car locks with BMW ConnectedDrive."""
import logging
from homeassistant.components.bmw_connected_drive import DOMAIN as BMW_DOMAIN
from homeassistant.components.lock import LockDevice
from homeassistant.const import STATE_LOCKED, STATE_UNLOCKED
DEPENDENCIES = ['bmw_connected_drive']
_LOGGER = logg... | state set here because it takes some time before the
# update callback response
self._state = STATE_LOCKED
self.schedule_update_ha_state()
self._vehicle.remote_services.trigger_remote_door_lock()
def u | nlock(self, **kwargs):
"""Unlock the car."""
_LOGGER.debug("%s: unlocking doors", self._vehicle.name)
# Optimistic state set here because it takes some time before the
# update callback response
self._state = STATE_UNLOCKED
self.schedule_update_ha_state()
self._ve... |
MSusik/invenio | invenio/legacy/websearch_external_collections/__init__.py | Python | gpl-2.0 | 21,464 | 0.00601 | # -*- coding: utf-8 -*-
## This file is part of Invenio.
## Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012 CERN.
##
## Invenio is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
## published by the Free Software Foundation; either version 2 of the... | seealso_engines = copy(dico_collection_seealso[collection_id])
if collection_id in dico_collection_external_searches:
seealso_engines = seealso_engines.union(dico_collection_external_searches[collection_id])
for ext_search_name in selected_external_searches:
if ext_search_name in external_ | collections_dictionary:
engine = external_collections_dictionary[ext_search_name]
if engine.parser:
search_engines.add(engine)
else:
warning('select_external_engines: %(ext_search_name)s unknown.' % locals())
seealso_engines = seealso_engines.difference(s... |
manishpatell/erpcustomizationssaiimpex123qwe | addons/product_stone_search_ept/py/product/product_category.py | Python | agpl-3.0 | 912 | 0.024123 | from openerp import tools
from openerp.osv import osv, fields
from openerp.tools.translate import _
import openerp.addons.decimal_precision as dp
class product_category(osv.osv):
_inherit='product.category'
_columns = {
'sale_price' : fields.float('Sale Price',digits_compute=dp.get_precision('... | From',digits_compute=dp.get_precision('Stock Weight')),
'weight_to':fields.float('Weight To',digits_compute=dp.get_precision('Stock Weight')),
'color_id':fields.many2one('product.color',string='Color'),
| 'clarity_id':fields.many2one('product.clarity',string='Clarity', ondelete='restrict'),
'shape_line':fields.one2many('shape.line','categ_id','Shape Lines'),
}
|
VictorThompson/ActivityTracker | py/geepeeex.py | Python | gpl-3.0 | 5,539 | 0.017873 | #!/usr/bin/python3
import gpxpy
import datetime
import time
import os
import gpxpy.gpx
import sqlite3
import pl
import re
DATE_FORMAT = '%Y-%m-%dT%H:%M:%SZ'
filebase = os.environ["XDG_DATA_HOME"]+"/"+os.environ["APP_ID"].split('_')[0]
def create_gpx():
# Creating a new file:
# --------------------
gpx = g... | _date text, distance text,
speed text, act_type text,filename text,polyline text)""")
ret_data=[]
sql = "SELECT * FROM activities LIMIT 30"
for i in cursor.execute(sql):
ret_data.append(dict(i))
conn.close()
| return ret_data
def get_units():
os.makedirs(filebase, exist_ok=True)
conn = sqlite3.connect('%s/activities.db' % filebase)
cursor = conn.cursor()
cursor.execute("""CREATE TABLE if not exists settings
(units text)""")
ret_data=[]
sql = "SELECT units FROM settings"
curso... |
mozaik-association/mozaik | mozaik_website_event_track/__manifest__.py | Python | agpl-3.0 | 525 | 0 | # Copyright 202 | 1 ACSONE SA/NV
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Mozaik Website Event Track",
"summary": """
This module allows to see the event menu configuration
even without activated debug mode""",
"version": "14.0.1.0.0",
"license": "AGPL-3",
"author": ... | ata": [
"views/event_event.xml",
],
}
|
ebattenberg/crbm-drum-patterns | crbm.py | Python | gpl-3.0 | 63,541 | 0.013047 | import cPickle as pkl
import pdb
import datetime
import time
import numpy as np
import pylab as pl
import scipy.stats
import scipy.special
from scipy.special import gamma
from scipy.misc import factorial
import gnumpy as gp
import data_helper
class RBM(object):
'''
Restricted Boltzmann Machine (RBM) using... | CD updates.
input:
-----------------
Nv: number of visible units
Nh: number of hidden units
| vis_unit: type of visible unit {'binary','linear'}
('linear' = rectified linear unit)
vis_scale: maximum output value for linear visible units
(average std_dev is ~= 1 at this scale,
so pre-scale training data with this in mind)
bv: visible bias
... |
dhrone/pydKeg | displays/lcd_curses.py | Python | mit | 1,770 | 0.039542 | #!/usr/bin/python
# coding: UTF-8
# Driver for testing pydPiper display
# Uses the curses system to emulate a display
# Written by: Ron Ritchey
import time, curses
import lcd_display_driver
class lcd_curses(lcd_display_driver.lcd_display_driver):
def __init__(self, rows=2, cols=16 ):
self.FONTS_SUPPORTED = Fa... | curx, text.encode('utf-8'))
self.stdscr.refresh()
def msgtest(self, text, wait=1.5):
self.clear()
lcd.message(text)
time.sleep(wait)
if __name__ == '__main__':
try:
print "Curses Display Test"
lcd = lcd_curses(2,16)
lcd.msgtest("Curses\nPi Powered",2)
lcd.msgte | st("This is a driver\nused for testing",2)
accent_min = u"àáâãäçèéëêìíî \nïòóôöøùúûüþÿ"
#for char in accent_min: print char, ord(char)
lcd.msgtest(accent_min,2)
lcd.clear()
except KeyboardInterrupt:
pass
finally:
lcd.clear()
lcd.message("Goodbye!")
time.sleep(2)
lcd.clear()
curses.endwin()
print "Cur... |
espressif/esp-idf | docs/zh_CN/conf.py | Python | apache-2.0 | 789 | 0 | # -*- coding: utf-8 -*-
#
# English Language RTD & Sphinx config file
#
# Uses ../conf_common.py for most non-language-specific settings.
# Importing conf_common adds all the non-language-specific
# parts to this conf module
try:
from conf_common import * # noqa: F403,F401
except ImportError:
import os
im... | .abspath('..'))
from conf_common import * # noqa: F403,F401
import datetime
current_year = datetime.datetime.now().year
# General information about the project.
project = u'ESP-IDF 编程指南'
copyright = u'2016 - {} 乐鑫信息科技(上海)股份有限公司'.format(current_year)
# The language for content autogene | rated by Sphinx. Refer to documentation
# for a list of supported languages.
language = 'zh_CN'
|
nick-huang-cc/GraffitiSpaceTT | UnderstandStudyPython/IO_coroutine_stu1.py | Python | agpl-3.0 | 1,188 | 0.011752 | #!/usr/bin/env python3
# -*- coding:UTF-8 -*-
#Copyright (c) 1986 Nick Wong.
#Copyright (c) 2016-2026 TP-NEW Corp.
# License: TP-NEW (www.tp-new.com)
__author__ = "Nick Wong"
"""
用asyncio提供的@asyncio.coroutine可以把一个generator标记为coroutine类型,然后在coroutine内部用yield from调用另一个coroutine实现异步操作
从Python 3.5开始引入了新的语法async和await,可以... | await。
"""
import asyncio
#########旧代码#########
@asyncio.coroutine
def hello():
print('Hello World!')
r = yield from asyncio.sleep(2)
print('Hello again!')
#########新代码#########
async def hello1(): #注:async后跟的函数不能换行,否则语法错误
print('Hello World! 1')
r = await asyncio.sleep(2)
print('Hello aga... | op = asyncio.get_event_loop()
#执行coroutine
loop.run_until_complete(hello())
loop.run_until_complete(hello1())
loop.close()
|
quijot/agrimpy-package | agrimpy/test.py | Python | mit | 1,621 | 0.001858 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Pasos para transformar proy a geod/proy/GK y exportar a DXF
from geod_proy import *
from toDXF import *
#
# 1) Configurar Proyecciones usadas
#
# 1.1) Proyección Mercator Transversal cualquiera.
lat_orig = gms2gyf(-33,52)
merid_c = gms2gyf(-61,14)
pserapio = config_p... | -> gk5. Si se comparan los archivos de
# salida, deberían ser iguales entre ambas "gk5" y ambas "geod".
# proy.geod -> proy.geod.gk5
geod2proy('coord/proy.geod', gk_faja5, 'gk5')
# proy.geod.gk5 -> proy.geod.gk5.geod
proy2geod('coord/pr | oy.geod.gk5', gk_faja5)
# proy.geod.gk5.geod -> proy.geod.gk5.geod.gk5
geod2proy('coord/proy.geod.gk5.geod', gk_faja5, 'gk5')
# proy.geod.gk5.geod.gk5 -> proy.geod.gk5.geod.gk5.geod
proy2geod('coord/proy.geod.gk5.geod.gk5', gk_faja5)
#
# 4) Exportar a DXF
#
# Sólo tiene sentido mandar a DXF las coordenadas proyectad... |
johncosta/django-like-button | setup.py | Python | bsd-3-clause | 4,721 | 0.003601 | import os
import sys
import codecs
from fnmatch import fnmatchcase
from distutils.util import convert_path
from setuptools import setup, find_packages
def read(fname):
return codecs.open(os.path.join(os.path.dirname(__file__), fname)).read()
# Provided as an attribute, so you can append to these instead
# of repl... | ries = ('.*', 'CVS', '_darcs', './build',
'./dist', 'EGG-INFO', '*.egg-info')
# (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org)
# Licensed under the M | IT license: http://www.opensource.org/licenses/mit-license.php
# Note: you may want to copy this into your setup.py file verbatim, as
# you can't import this from another package, when you don't know if
# that package is installed yet.
def find_package_data(
where='.', package='',
exclude=standard_exclude,
... |
MD-Studio/MDStudio | mdstudio/mdstudio/logging/impl/printing_observer.py | Python | apache-2.0 | 805 | 0.003727 | from datetime import datetime
import os
import pytz
class PrintingLogObserver(object):
def __init__(self, fp):
self.fp = fp
def __call__(self, event):
if event.get('log_format', None):
message = event['log_format'].format(**event)
else:
message = even | t.get('message', '')
pid = str(event.get('pid', os.getpid()))
log_struct = {
'time': datetime.fromtimestamp(event['log_time'], pytz.utc).time().replace(microsecond=0).isoformat(),
'pid': pid,
'source': event.get('cb_namespace', event['log_ | namespace']).split('.')[-1],
'message': message,
'ws': max(0, 35 - len(pid))
}
self.fp.write('{time} [{source:<{ws}} {pid}] {message}\n'.format(**log_struct))
|
amohanta/thug | src/Logging/modules/HPFeeds.py | Python | gpl-2.0 | 6,225 | 0.008193 | #!/usr/bin/env python
#
# HPFeeds.py
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; w... | self.opts['ident'] +
hash)
def msg_send(self, msg):
self.sockfd.send(msg)
def get_data(self, host, port):
| self.sockfd.settimeout(3)
try:
self.sockfd.connect((host, port))
except:
log.warning('[HPFeeds] Unable to connect to broker')
return None
try:
d = self.sockfd.recv(1024)
except socket.timeout:
log.warning('[HPFeeds] Timeo... |
dhazel/buck | bucking/logvolume_2.py | Python | gpl-2.0 | 2,031 | 0.031019 | #This is a function containing an algorithmic model of the Scribner log rule,
# board-foot log volume tables. It outputs the Scribner log volume for an
# input log length and top diameter.
#
# Annotation: [v]=logvolume(L,TD)
# v = Scribner log volume
# L = log length
# ... | L < 31:
v = 10 * round((L * volume_table_2[TD + 6]) / 10.0)
elif L < 41:
v = 10 * round((L * volume_table_2[TD + 12]) / 10.0)
else:
v = 0
else:
if TD == 5: |
v = 10 * round((L * volume_table_1[0]) / 10.0)
else:
v = 10 * round((L * volume_table_1[TD - 11]) / 10.0)
return v
def debug_logvolume():
print
v = logvolume_2(input("length: "),input("topdia: "))
print "volume is:", v
|
Cjsheaf/Variation-Discovery-Pipeline | Pipeline_Core/Results_Writer.py | Python | gpl-2.0 | 3,199 | 0.003439 | __author__ = 'Cjsheaf'
import csv
from threading import Lock
class ResultsWriter:
""" This class is designed to take out-of-order result data from multiple threads and write
them to an organized csv-format file.
All data is written to disk at the very end via the "write_results" method, since th... | ries:
writer.writerow(e.name, e.rmsd)
for c in e.compounds:
writer.writerow('', '', c.name, c.rseq, c.mseq, c.rmsd_refine, c.e_conf, c.e_place,
c.e_score1, c.e_score2, c.e_refine)
class Entry:
def __init__(self, name):
self.name = nam... | , compound_name, compound):
self.compounds[compound_name] = compound
class Compound:
def __init__(self, name, rseq, mseq, rmsd_refine, e_conf, e_place, e_score1, e_score2, e_refine):
self.name = name
self.rseq = rseq
self.mseq = mseq
self.rmsd_refine = rmsd_refine
s... |
MrColwell/PythonProfessionalLearning | PythonForTeachers/studentExercises/8_2_average.py | Python | mit | 339 | 0.0059 | total = 0
n = 0
stop = 0
nextMark = input('Type in a mark: ')
while stop == 0:
nextMark = eval(nextMark)
total = total+nextMark
n = n + 1
nextMark = input('Hit enter to stop, or type in a mark: ')
if nextMark == "":
stop = 1
print("You entered", n, 'marks | . The average is:',total/n)
| |
namhyung/uftrace | tests/t159_report_diff_policy2.py | Python | gpl-2.0 | 2,877 | 0.004866 | #!/usr/bin/env python
import subprocess as sp
from runtest import TestBase
XDIR='xxx'
YDIR='yyy'
class TestCase(TestBase):
def __init__(self):
TestBase.__init__(self, 'diff', """
#
# uftrace diff
# [0] base: xxx (from uftrace record -d yyy -F main tests/t-diff 1 )
# [1] diff: yyy (from uftrace rec... | =============================== =================================== ================================ ================================================
1.075 us 1.048 us | -0.027 us 1.075 us 1.048 us -0.027 us 1 1 +0 atoi
158.971 us 0.118 us -158.853 us 1.437 us 0.118 us -1.319 us 1 1 +0 bar
1.235 ms 0.645 us -1.235 ms 3.276 us 0.527 us -2.749 us 1 1 +0 ... |
fontman/fontman-server | utility/Initializer.py | Python | gpl-3.0 | 428 | 0 | """ Initializer
Initialize application data.
Created by Lahiru Pathirage @ Mooniak<lpsandaruwan@gmail.com> on 19/12/2016
"""
from session import Base
from session import mysql_con_string
from sqlalchemy import create_engine
from utility import DBManager
def initialize():
engine = create_engine(
mysql... | con_string
)
Base.metadata.create_all(engine, checkfirst=True)
DBManager().update | _font_cache()
|
zhaochl/python-utils | es/elasticsearch_util.py | Python | apache-2.0 | 4,771 | 0.032907 | #!/usr/bin/env python
# coding=utf-8
import commands
import sys
from docopt import docopt
#from handler import LogFileClient
from sdutil.log_util import getLogger
from sdutil.date_util import *
reload(sys)
sys.setdefaultencoding('utf-8')
from elasticsearch import Elasticsearch
from pdb import *
import requests
import ... | tamp
if time_step>0:
_s1=startTimeStamp |
_s2=startTimeStamp+time_step
run_time =0
all_response = {}
time_count = {}
while(_s2<=endTimeStamp):
response_tmp = do_search(host,index,query_str,_s1,_s2,scroll,_source,time_step)
#response_tmp = do_search(_s1,_s2)
if all_response.has_key('hi... |
oregoncountryfair/ocfnet | ocfnet/migrations/env.py | Python | mit | 2,236 | 0.001342 | from __future__ import with_statement
from alembic import context
from sqlalchemy import engine_from_config, pool
from logging.config import fileConfig
from ocfnet.database import Model
from ocfnet.media.models import *
from ocfnet.user.models import *
try:
from config import DATABASE_URL
except:
from configd... | g = config.get_section(config.config_ini_section)
alembic_config['sqlalchemy.url'] = DATABASE_URL
engine = engine_from_config(alembic_config, poolclass=pool.NullPool)
connection = engine.connect()
context.configure(connection=connection,
target_metadata=target_metadata)
try:
with c... | ext.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
|
FireFry/online-judge-solutions | acm.timus.ru/1385.py | Python | gpl-2.0 | 166 | 0.024096 | from sys import stdin, stdout
n = int(stdin.read())
if n == 1:
res = "14"
elif n == 2:
res = "155"
else:
| res = "1575" + ("0" * (n - 3))
stdout.write(re | s + "\n") |
andsens/ansible-modules-extras | messaging/rabbitmq_user.py | Python | gpl-3.0 | 7,797 | 0.001411 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2013, Chatham Financial <oss@chathamfinancial.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3... | nt, absent]
'''
EXAMPLES = '' | '
# Add user to server and assign full access control
- rabbitmq_user: user=joe
password=changeme
vhost=/
configure_priv=.*
read_priv=.*
write_priv=.*
state=present
'''
class RabbitMqUser(object):
def __init__(sel... |
anurag03/integration_tests | artifactor/plugins/test.py | Python | gpl-2.0 | 705 | 0 | """ Test plugin for Artifactor """
import time
from artifactor import ArtifactorBasePlugin
class Test(ArtifactorBasePlugin):
def plugin_initialize(self):
self.register_plugin_hook("start_test", self.start_test)
self.register_plugi | n_hook("finish_test", self.finish_test)
def start_test(self, test_name, test_location, artifact_path):
filename = artifact_path + "-" + self.ident + ".log"
with open(filename, "a+") as f:
f.write(test_name + "\n")
f.write(str(time.time()) + "\n")
for i in range(2):
... | print("houh")
def finish_test(self, test_name, artifact_path):
print("finished")
|
moepman/acertmgr | acertmgr/tools.py | Python | isc | 18,467 | 0.003466 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# acertmgr - various support functions
# Copyright (c) Markus Hauschild & David Klaftenegger, 2016.
# Copyright (c) Rudolf Mayerhofer, 2019.
# available under the ISC license, see LICENSE
import base64
import datetime
import io
import os
import re
import stat
import sys
i... |
public_exponent=65537,
key_size=key_size,
| backend=default_backend()
)
elif key_algo.lower() == 'ec':
if not key_size or key_size == 256:
key_curve = ec.SECP256R1
elif key_size == 384:
key_curve = ec.SECP384R1
elif key_size == 521:
key_curve = ec.SECP521R1
else:
... |
wikimedia/integration-zuul | tests/test_daemon.py | Python | apache-2.0 | 2,085 | 0 | #!/usr/bin/env python
# Copyright 2014 Hewlett-Packard Development Company, L.P.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance | with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distr | ibuted under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import daemon
import logging
import os
import sys
import extras
import fixtures... |
trustedanalytics/spark-tk | python/sparktk/frame/pyframe.py | Python | apache-2.0 | 926 | 0.001179 | # vim: set encoding=utf-8
# Copyright (c) 2016 Intel Corporation
#
# 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 require... | License.
#
class PythonFrame(object):
"""frame backend using a Python objects: pyspark.rdd.RDD, [(str, dtype), (str, dtype), ...]"""
def __init__(self, rdd, sch | ema=None):
self.rdd = rdd
self.schema = schema
|
quiqueporta/django-admin-dialog | django_admin_dialog/__init__.py | Python | gpl-2.0 | 502 | 0 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literal | s, print_function
VERSION = (1, 0, 8, 'final')
__version__ = VERSION
def get_versio | n():
version = '{}.{}'.format(VERSION[0], VERSION[1])
if VERSION[2]:
version = '{}.{}'.format(version, VERSION[2])
if VERSION[3:] == ('alpha', 0):
version = '{} pre-alpha'.format(version)
else:
if VERSION[3] != 'final':
version = '{} {}'.format(version, VERSION[3])
... |
miqueiaspenha/gerenciadordeprovas | quiz/__init__.py | Python | gpl-2.0 | 60 | 0.05 | from | flask import Flask
app = Flask(__name_ | _)
import views |
sergiopasra/django-megaraetc | etc/models.py | Python | gpl-3.0 | 1,005 | 0.002985 | from django.db import models
class SpectralTemplate(models.Model):
name = models.CharField(max_length=10)
path = models.CharField(max_length=100)
def __str__(self):
return self.name
class PhotometricFilter(models.Model):
name = models.CharField(max_length=10)
path = models.CharField(max... | Field()
mvega = models.FloatField()
fvega = models.FloatField()
def __str__(self):
return self.name
class VPHSetup(models.Model):
name = models.CharField(max_length=10)
fwhm = models.Floa | tField()
dispersion = models.FloatField()
deltab = models.FloatField()
lambdac = models.FloatField()
relatedband = models.CharField(max_length=10)
lambda_b = models.FloatField()
lambda_e = models.FloatField()
specconf = models.CharField(max_length=10)
def __str__(self):
return ... |
stryder199/RyarkAssignments | Assignment2/ttt/archive/_old/KnR/KnR_1-10.py | Python | mit | 1,389 | 0.009359 | game_type = 'input_output'
parameter_list = [['$x1','string'], ['$y0','string']]
tuple_list = [
['KnR_1-10_',[None,None]]
]
global_code_template = '''\
d #include <stdio.h>
x #include <stdio.h>
dx #define MAXLINE 1000 /* maximum input line length */
dx
dx int max; /* maximum length seen so far ... | x line[i] = '\\0';
dx return i;
dx }
dx
dx /* copy: specialized version */
dx void copy(void)
dx {
dx int i;
dx extern char line[], longest[];
dx
dx i = 0;
dx while ((longest[i] = line[i]) != '\\0')
dx ++i;
dx }
dx
dx /* print longest input line; specialized version */
'''
main_code_template = '''\
dx int l... | max = len;
dx copy();
dx }
dx if (max > 0) /* there was a line */
dx printf("%s", longest);
'''
argv_template = ''
stdin_template = '''
a
$x1
abc
'''
stdout_template = '''\
$y0
'''
|
Yelp/beans | api/tests/logic/secret_test.py | Python | mit | 573 | 0 | import json
import pytest
fr | om ye | lp_beans.logic.secret import get_secret
def test_get_secret_file(tmpdir, database):
with tmpdir.as_cwd():
expected = 'password'
with open(tmpdir.join('client_secrets.json').strpath, 'w') as secrets:
secret = {'secret': expected}
secrets.write(json.dumps(secret))
act... |
ikekonglp/TweeboParser | scripts/AugumentBrownClusteringFeature46.py | Python | gpl-3.0 | 2,802 | 0.003212 | # Copyright (c) 2013-2014 Lingpeng Kong
# All Rights Reserved.
#
# This file is part of TweeboParser 1.0.
#
# TweeboParser 1.0 is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the Lic... | You should have received a copy of the GNU Lesser General Public License
# | along with TweeboParser 1.0. If not, see <http://www.gnu.org/licenses/>.
# Lingpeng Kong, lingpenk@cs.cmu.edu
# Oct 12, 2013
# The Brown Clustering usage for Dependency Parsing can be read from Koo et al (ACL 08)
# http://people.csail.mit.edu/maestro/papers/koo08acl.pdf
# Oct 27, 2013
# Add case-sensitive choice
# Ja... |
ministryofjustice/postcodeinfo | postcodeinfo/apps/postcode_api/migrations/0011_auto_20150702_1812.py | Python | mit | 394 | 0 | # -*- coding: utf-8 -*-
from __ | future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('postcode_api', '0010_auto_20150601_1513'),
]
operations = [
migrations.AlterIndexTogether(
name='address',
index_together=set([('po... | |
kennknowles/python-rightarrow | rightarrow/parser.py | Python | apache-2.0 | 6,194 | 0.008072 | import sys
import os.path
import logging
import ply.yacc
from rightarrow.annotations import *
from rightarrow.lexer import Lexer
logger = logging.getLogger(__name__)
class Parser(object):
tokens = Lexer.tokens
def __init__(self, debug=False, lexer_class=None):
self.debug = debug
self.lexer_... | raise Exception('Parse error at %s:%s near token %s (%s)' % (t.lineno, t.col, t.value, t.type))
def p_empty(self, p):
'empty :'
pass
def p_ty_parens(self, p):
"ty : '(' ty ')'"
p[0] = p[2]
def p_ty_var(self, p):
"ty : TYVAR"
p[0] = Variable(p[1])
... | [0] = Union([p[1], p[3]])
def p_ty_bare(self, p):
"ty : bare_arg_ty"
p[0] = p[1]
def p_ty_funty_bare(self, p):
"ty : ty ARROW ty"
p[0] = Function(arg_types=[p[1]], return_type=p[3])
def p_ty_funty_complex(self, p):
"ty : '(' maybe_arg_types ')' ARROW ty"
ar... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.