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 |
|---|---|---|---|---|---|---|---|---|
jiahaoliang/group-based-policy | gbpservice/neutron/tests/unit/services/grouppolicy/test_group_proxy_extension.py | Python | apache-2.0 | 8,529 | 0 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... | y' in pt)
def test_proxy_group_multiple_proxies(self):
# same PTG proxied multiple times will fail
ptg = self.create_policy_target_group | ()['policy_target_group']
self.create_policy_target_group(proxied_group_id=ptg['id'])
# Second proxy will fail
res = self.create_policy_target_group(proxied_group_id=ptg['id'],
expected_res_status=400)
self.assertEqual('InvalidProxiedGroup', ... |
Ra93POL/EsperantoLanguage | HereIsYourCode.py | Python | gpl-2.0 | 713 | 0.022876 | import LingvoObjects, Esperanto
def getAnalysis(NL):
# подгатавливаем | текст
list_sentence = LangModule.Prepearing(NL)
# возвращаем предложения в виде объекта
obj_sentence = LingvoObjects.Sentence(list_sentence)
# делаем полный морфологический и синтаксический анализы
result, GrammarNazi = LangModule | .NL2ResultA(obj_sentence)
return result.getSentence('dict')
#-----------------------------------------------------------------#
sentence = "montru dolaran kurson de gruzia banko"
#sentence = "montru dolaran kurson de gruzia banko malrapide"
#sentence = "Vi estas studento"
print getAnalysis()
|
KeepSafe/translation-real-time-validaton | notifier/executor.py | Python | apache-2.0 | 708 | 0 | import asyncio
from functools import partial
class AsyncWrapper:
def __init__(self, target_instance, executor=None):
self._target_inst | = target_instance
self._loop = asyncio.get_event_loop()
self._executor = executor
def __getattribute__(self, name):
try:
return sup | er().__getattribute__(name)
except AttributeError:
method = self._target_inst.__getattribute__(name)
return partial(self._async_wrapper, method)
async def _async_wrapper(self, method_name, *args, **kwargs):
coroutine_wrapped = partial(method_name, *args, **kwargs)
re... |
scylladb/scylla-cluster-tests | sdcm/sct_provision/aws/layout.py | Python | agpl-3.0 | 2,241 | 0.000446 | # This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be usefu... | .loader_cluster:
self.loader_cluster.provision()
if self.cs_db_cluster:
self.cs_db_cluster.provision()
@cached_property
def db_cluster(self):
return DBCluster(
params=self._params,
common_tags=self._test_config.common_tags(),
test_id=s... | r_cluster(self):
return LoaderCluster(
params=self._params,
common_tags=self._test_config.common_tags(),
test_id=self._test_config.test_id(),
)
@cached_property
def monitoring_cluster(self):
return MonitoringCluster(
params=self._params,
... |
codenote/chromium-test | tools/telemetry/telemetry/page/page_test.py | Python | bsd-3-clause | 6,182 | 0.010191 | # Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import logging
from telemetry.page.actions import all_page_actions
from telemetry.page.actions import page_action
def _GetActionFromData(action_data):
... | CanRunForPage(self, page): #pylint: disable=W0613
"""Override | to customize if the test can be ran for the given page."""
return True
def WillRunPageSet(self, tab, results):
"""Override to do operations before the page set is navigated."""
pass
def DidRunPageSet(self, tab, results):
"""Override to do operations after page set is completed, but before browser
... |
GreenLunar/Bookie | bookie/tests/test_utils/test_search.py | Python | agpl-3.0 | 1,797 | 0 | """Test if correct arguments are passed to Whoosh to search
indexed content
"""
from mock import patch
from pyramid import testing
from unittest import TestCase
class TestSearchAttr(TestCase):
attr = []
def _return_attr(self, *args, **kwargs):
"""Saves arguments passed to WhooshFulltext
sea... | ooshFulltext')
def test_search_content_ajax(self, mock_search):
"""Test if correct arguments are passed to W | hooshFulltext
with ajax request"""
mock_search().search.side_effect = self._return_attr
self.testapp.get(url='/results/ajax', xhr=True)
self.assertTrue(mock_search.called)
self.assertEqual(self.attr[0][0],
'ajax',
'search term sh... |
tylerclair/py3canvas | py3canvas/tests/progress.py | Python | mit | 858 | 0.001166 | """Progress API Tests for Version 1.0. |
This is a testing template for the generated ProgressAPI Class.
"""
import unittest
import requests
import secrets
from py3canvas.apis.progress import ProgressAPI
from py3canvas.apis.progress import Progress
class TestProgressAPI(unittest.TestCase):
"""Tests for the ProgressAPI."""
def setUp(self):
... | on test for the ProgressAPI.query_progress method."""
id = None # Change me!!
r = self.client.query_progress(id)
def test_query_progress(self):
"""Integration test for the ProgressAPI.query_progress method."""
course_id = None # Change me!!
id = None # Change me!!
... |
varunarya10/rally | rally/deploy/engines/fuel.py | Python | apache-2.0 | 6,902 | 0.000724 | # Copyright 2014: 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... | : "array",
"uniqueItems": True,
"items": FILTER_SCHEMA,
},
},
"additionalProperties": False
}
IPV4_PATTERN = "(\d+\.){3}\d+"
IPV4_ADDRESS_PATTERN = "^%s$" % IPV4_PATTERN
IPV4_CIDR_PATTERN = "^%s\/\d+$" % IPV4_PATTERN
IP_RANGE_SCHEMA = {
"type": "array",
"maxItems": 2,
... | tring",
"pattern": IPV4_ADDRESS_PATTERN,
}
}
NETWORK_SCHEMA = {
"type": "object",
"properties": {
"cidr": {"type": "string", "pattern": IPV4_CIDR_PATTERN},
"gateway": {"type": "string", "pattern": IPV4_ADDRESS_PATTERN},
"ip_ranges": {"type": "array", "items": IP_RANGE_SCHEMA... |
mrunge/openstack_horizon | openstack_horizon/dashboards/project/images/images/views.py | Python | apache-2.0 | 4,298 | 0 | # Copyright 2012 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2012 Nebula, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the... | uted 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.
"""
Views for managing images.
"""
from django.core.urlresolvers import r... | rom horizon_lib import forms
from horizon_lib import tabs
from horizon_lib.utils import memoized
from openstack_horizon import api
from openstack_horizon.dashboards.project.images.images \
import forms as project_forms
from openstack_horizon.dashboards.project.images.images \
import tables as project_tables
f... |
firasbenmakhlouf/JobLookup | metadata/models.py | Python | mit | 467 | 0 | from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class Tanit | JobsCategory(models.Model):
name = models.CharField(max_length=255, unique=True)
def __str__(self):
return "%s" % self.name
class KeeJobsCategory(models.Model):
name = models.CharField(max_length=255, unique=True)
def __str__(self):
return "%s" % self. | name
|
tboyce1/home-assistant | homeassistant/components/tasmota/fan.py | Python | apache-2.0 | 2,750 | 0.000364 | """Support for Tasmota fans."""
from hatasmota import const as tasmota_const
from homeassistant.components import fan
from homeassistant.components.fan import FanEntity
from homeassistant.core import callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from .const import DATA_REMOVE_DISCOVE... | f):
"""Flag supported features."""
return fan.SUPPORT_SET_SPEED
async def async_set_speed(self, speed):
"""Set the speed of the fan."""
if speed not in HA_TO_TASMOTA_SPEED_MAP:
raise ValueError(f"Unsupported speed {speed}")
| if speed == fan.SPEED_OFF:
await self.async_turn_off()
else:
self._tasmota_entity.set_speed(HA_TO_TASMOTA_SPEED_MAP[speed])
async def async_turn_on(self, speed=None, **kwargs):
"""Turn the fan on."""
# Tasmota does not support turning a fan on with implicit speed
... |
sgrogan/freecad-extras-eaglepcb2 | command/PCBexplode.py | Python | lgpl-2.1 | 23,993 | 0.00696 | # -*- coding: utf8 -*-
#****************************************************************************
#* *
#* Printed Circuit Board Workbench for FreeCAD PCB *
#* Flexible Printed Circuit Board Workbench for FreeCAD FP... | QWidget):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
#
self.TopStepSize = QtGui.QSpinBox()
self.TopStepSize.setRange(5, 100)
self.TopStepSize.setValue(10) |
self.TopStepSize.setSingleStep(5)
self.BottomStepSize = QtGui.QSpinBox()
self.BottomStepSize.setRange(5, 100)
self.BottomStepSize.setValue(10)
self.BottomStepSize.setSingleStep(5)
#
self.tableTop = explodeObjectTable()
self.tableBottom = explodeO... |
MalloyPower/parsing-python | front-end/testsuite-python-lib/Python-3.0/Lib/os.py | Python | mit | 21,471 | 0.00312 | r"""OS routines for Mac, NT, or Posix depending on what system we're on.
This exports:
- all functions from posix, nt, os2, or ce, e.g. unlink, stat, etc.
- os.path is either posixpath or ntpath
- os.name is either 'posix', 'nt', 'os2' or 'ce'.
- os.curdir is a string representing the current directory ('.' or... |
name = 'posix'
linesep = '\n'
from posix import *
try:
from posix import _exit
except ImportError:
pass
import posixpath as path
import posix
__all__.ext | end(_get_exports_list(posix))
del posix
elif 'nt' in _names:
name = 'nt'
linesep = '\r\n'
from nt import *
try:
from nt import _exit
except ImportError:
pass
import ntpath as path
import nt
__all__.extend(_get_exports_list(nt))
del nt
elif 'os2' in _names:
... |
speksi/python-mingus | unittest/test_track.py | Python | gpl-3.0 | 739 | 0.006766 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
sys.path += ['../']
from mingus.containers.track import Track
from mingus.containers.bar import Bar
from mingus.containers.ins | trument import Instrument, Piano, Guitar
import unittest
class test_Track(unittest.TestCase):
def setUp(self):
self.i = Track(Instrument())
self.p = Track(Piano())
self.g = Track(Guitar())
self.tr = Track()
def test_add(self):
pass
def test_transpose(self):
... | return unittest.TestLoader().loadTestsFromTestCase(test_Track)
|
madsryvang/LVsbp | python/sbp/navigation.py | Python | lgpl-3.0 | 28,612 | 0.009681 | #!/usr/bin/env python
# Copyright (C) 2015 Swift Navigation Inc.
# Contact: Fergus Noble <fergus@swiftnav.com>
#
# This source is subject to the license found in the file 'LICENSE' which must
# be be distributed together with this source. All other rights reserved.
#
# THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITH... | ation position and the rover's RTK
baseline vector. The full GPS time is given by the preceding
MSG_GPS_TIME with the matching time-of-week (tow).
Parameters
----------
sbp : SBP
SBP parent object to inherit from.
tow : int
GPS Time of Week
x : double
ECEF X coordinate
y : double
ECEF Y co... | : int
Number of satellites used in solution
flags : int
Status flags
sender : int
Optional sender ID, defaults to SENDER_ID (see sb |
webofthings/wot-a-mashup | cs/proxy/node_modules/dtrace-provider/build/c4che/Release.cache.py | Python | gpl-3.0 | 1,407 | 0 | AR = '/usr/bin/ar'
ARFLAGS = 'rcs'
CCFLAGS = ['-g']
CCFLAGS_MACBUNDLE = ['-fPIC']
CCFLAGS_NODE = ['-D_LARGEFILE_SOURCE', '-D_FILE_OFFSET_BITS=64']
CC_VERSION = ('4', '4', '3')
COMPILER_CXX = 'g++'
CPP = '/usr/bin/cpp'
CPPFLAGS_NODE = ['-D_GNU_SOURCE']
CPPPATH_NODE = '/usr/local/include/node'
CPPPATH_ST = '-I%s'
CXX = [... | ']
CXXFLAGS_NODE = ['-D_LARGEFILE_SOURCE', '-D_FILE_OFFSET_BITS=64']
CXXFLAGS_RELEASE = ['-O2']
CXXLNK_SRC_F = ''
CXXLNK_TGT_F = ['-o', '']
CXX_NAME = 'gcc'
CXX_SRC_F = ''
CXX_TGT_F = ['-c', '-o', '']
DEST_BINFMT = 'elf'
DEST_CPU = 'x86_64'
DEST_OS = 'linux'
FULLSTATIC_MARKER = '-static'
LIBDIR = '/usr/li | b/nodejs:/usr/share/javascript'
LIBPATH_NODE = '/usr/local/lib'
LIBPATH_ST = '-L%s'
LIB_ST = '-l%s'
LINKFLAGS_MACBUNDLE = ['-bundle', '-undefined', 'dynamic_lookup']
LINK_CXX = ['/usr/bin/g++']
NODE_PATH = '/usr/lib/nodejs:/usr/share/javascript'
PREFIX = '/usr/local'
PREFIX_NODE = '/usr/local'
RANLIB = '/usr/bin/ranlib... |
calico/basenji | tests/test_train.py | Python | apache-2.0 | 6,235 | 0.013953 | #!/usr/bin/env python
from optparse import OptionParser
import glob
import os
import shutil
import unittest
import numpy as np
import pandas as pd
from scipy.stats import mannwhitneyu
from scipy.stats import ttest_ind
import slurm
class TestTrain(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.par... | cpu=1,
gpu=1,
mem=23000,
| time='2-00:00:00')
jobs.append(basenji_job)
slurm.multi_run(jobs, verbose=True)
################################################################
# test check
################################################################
jobs = []
for i in range(self.iterations):
it_dir = ... |
andrewgross/pyrelic | tests/unit/test_base_client.py | Python | mit | 1,927 | 0 | import requ | ests
import httpretty
from nose.tools import nottest
from pyrelic import BaseClient
@nottest # Skip until we can properly simulate timeouts
@httpretty.activate
def test_make_request_timeout():
"""
Remote calls should time out
"""
httpretty.register_uri(httpretty.GET, "www.example.com",
... | seClient()
# Then I should raise a NewRelicApiException
c._make_request.when.called_with(requests.get,
"http://www.example.com",
timeout=0.05,
retries=1)\
.should.throw(requests.RequestException)... |
asconz/SystematicPrioritization | application/views/Delegates.py | Python | mit | 6,089 | 0.002135 | #! /usr/bin/python
######################
# views\Delegates.py #
######################
from PyQt5.QtWidgets import QStyleOptionViewItem, QDateEdit
from PyQt5.QtSql import QSqlRelationalDelegate
from PyQt5.QtCore import Qt, QDate
(TASK, WEIGHT, CATEGORY, DESCRIPTION, IMPORTANCE, URGENCY, DIFFICULTY,
DT_ADDED, DATE_DUE... | .QSize(width, height)
#
# class Window(QtGui.QWidget):
# def __init__(s | elf, rows, columns):
# super(Window, self).__init__()
# self.lay = QtGui.QVBoxLayout()
# self.setLayout(self.lay)
# self.table = QtGui.QTableWidget(rows, columns, self)
# self.table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
# self.table.setVerticalScrollB... |
matthewoliver/swift | test/functional/s3api/test_presigned.py | Python | apache-2.0 | 9,841 | 0 | # Copyright (c) 2016 SwiftStack, 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 w... | 'Got %d %s' % (resp.status_code, resp.content))
self.assertCommonResponseHeaders(resp.headers)
self.assertIsNotNone(resp.headers['content-type'])
self.assertEqual(resp.headers['content-length'],
str(len(resp.content)))
elem = fromstring(resp.cont... | em.find('Prefix').text)
self.assertIsNone(elem.find('Marker').text)
self.assertEqual(elem.find('MaxKeys').text,
str(max_bucket_listing))
self.assertEqual(elem.find('IsTruncated').text, 'false')
resp_objects = elem.findall('./Contents')
self.assertEqual(le... |
microelly2/geodata | geodat/my_xmlparser.py | Python | lgpl-3.0 | 9,730 | 0.069476 | fn='/home/thomas/Dokumente/freecad_buch/D006_landxml/Survey.xml'
fn='/home/thomas/Dokumente/freecad_buch/D006_landxml/bratton farm-2.0.xml'
# fn='/home/thomas/Dokumente/freecad_buch/D006_landxml/test.xml'
fn='/home/thomas/Dokumente/freecad_buch/D006_landxml/Portsmouth Heights.xml'
fn='/home/thomas/Dokumente/freecad_buc... | startswith(" FreeCAD Document, see http://www.freecadweb.org"):
content=content[4:]
cl=len(content)
say(cl)
i=-1
pb.setMaximum(cl)
while i<cl-1:
pb.setValue(i)
i += 1
line=content[i].strip()
j=0
while re.search(r">\s*$", line) == None and j<60:
i += 1
j += 1
line += content[i]
c2 +=[lin... | tring>" in line:
say ("break A")
continue
pb.setValue(lc)
# if lc%100 == 0:
# say(lc)
# Gui.updateGui()
# if stackpointer != -1:
# print (res.groups())
# print (stackpointer)
# print ("\n-------------NEXT:")
# print(line)
# print ("--- PARSE IT------------------------")
if re.search(r"^\s*$"... |
auntieNeo/asterisk-testsuite | tests/channels/pjsip/transfers/blind_transfer/callee_refer_only/transfer.py | Python | gpl-2.0 | 7,666 | 0.00013 | #!/usr/bin/env python
'''
Copyright (C) 2014, Digium, Inc.
John Bigelow <jbigelow@digium.com>
This program is free software, distributed under the terms of
the GNU General Public License Version 2.
'''
import logging
import pjsua as pj
from twisted.internet import reactor
LOGGER = logging.getLogger(__name__)
URI = [... | LOGGER.info("Starting second iteration.")
self.channels_hungup = 0
ITERATION += 1
lock = self.alice.pj_lib.auto_lock()
self.make_call(self.alice.account, URI[1])
del lock
elif self.channels_hungup == 3 and ITERATION == 1:
self.test_obje... | nts:
acc The pjsua to make the call from
uri The URI to dial
"""
try:
LOGGER.info("Making call to '%s'" % uri)
acc.make_call(uri, cb=AlicePhoneCallCallback())
except pj.Error, err:
LOGGER.error("Exception: %s" % str(err))
def log_call_info(ca... |
njsmith/partiwm | parti/parti_main.py | Python | gpl-2.0 | 2,693 | 0.002228 | # This file is part of Parti.
# Copyright (C) 2008, 2009 Nathaniel Smith <njs@pobox.com>
# Parti is released under the terms of the GNU GPL v2, or, at your option, any
# later version. See the file COPYING for details.
import gtk
import wimpiggy.lowlevel
from wimpiggy.wm import Wm
from wimpiggy.keys import HotkeyMan... | n_quit_really()
def _new_window_signaled(self, wm, window):
self._add_new_window(window)
def _add_new_window(self, window):
# FIXME: be less stupid
self._tr | ays.trays[0].add(window)
def _desktop_list_changed(self, *args):
self._wm.emit("desktop-list-changed", self._trays.tags())
def spawn_repl_window(self):
spawn_repl_window(self._wm,
{"parti": self,
"wm": self._wm,
"w... |
conjure-up/conjure-up | conjureup/controllers/base/addons/gui.py | Python | mit | 1,165 | 0 | from conjureup import controllers
from conjureup.app_config import app
from conjureup.download import EndpointType
from conjureup.telemetry import track_event
from conjureup.ui.views.addons import AddonsView
class AddonsController:
def render(self, going_back=False):
if not app.addons:
if goin... |
if app.endpoint_type == EndpointType.LOCAL_DIR:
prev_screen = None
self.view = AddonsView(self.finish, prev_screen)
self.view.show()
def finish(self):
app.selected_addons = self.view.selected
if app.selected_addons:
for addon in app.selected_addons:
... | # reload the bundle data w/ addons merged
controllers.setup_metadata_controller()
self.next_screen()
def next_screen(self):
controllers.use('clouds').render()
def prev_screen(self):
controllers.use('spellpicker').render()
_controller_class = AddonsController
|
lmazuel/azure-sdk-for-python | azure-mgmt-monitor/azure/mgmt/monitor/models/incident_py3.py | Python | mit | 2,119 | 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 ... | .
:vartype activated_time: date | time
:ivar resolved_time: The time at which the incident was resolved in
ISO8601 format. If null, it means the incident is still active.
:vartype resolved_time: datetime
"""
_validation = {
'name': {'readonly': True},
'rule_name': {'readonly': True},
'is_active': {'readonly... |
DanielJDufour/language-detector | language_detector/prep/parse_un.py | Python | apache-2.0 | 986 | 0.004057 | from xml.etree import ElementTree
from os.path import dirname, realpath
directory_of_sources = dirname(realpath(__file__)) + "/sources/"
d = {}
d['AR'] = "Arabic"
d['EN'] = "English"
d['ES'] = "Spanish"
d['FR'] = "French"
d['RU'] = "Russian"
d['ZH'] = "Mandarin"
filepath = '/tmp/uncorpora_plain_20090831.tmx'
count... | ww.w3.org/XML/1998/namespace}lang']
if elem.tag == "seg":
text = elem.text
print language, "text is", text
if text and len(text) > 200:
with open(directory_of_sources + d[language] + "/" + uid, "wb") as f:
f.write(text.encode("utf-8"))
... | k
|
alabeduarte/pixelated-user-agent | service/pixelated/config/services.py | Python | agpl-3.0 | 2,509 | 0.001196 | from pixelated.adapter.services.mail_service import MailService
from pixelated.adapter.model.mail import InputMail
from pixelated.adapter.services.mail_sender import MailSender
from pixelated.adapter.services.mailboxes import Mailboxes
from pixelated.adapter.soledad.soledad_querier import SoledadQuerier
from pixelated.... | f.search_engine,
pixelated_mailboxes)
self.keymanager = self.setup_keymanager(leap_session)
self.draft_service = self.setup_draft_service(pixelated_mailboxes)
self.post_setup(soledad_querier, leap_session)
def post_setup(self, soledad_querier, leap_session):
self.searc... | lback=soledad_querier.mark_all_as_not_recent)
soledad_querier.remove_duplicates()
InputMail.FROM_EMAIL_ADDRESS = leap_session.account_email()
def setup_keymanager(self, leap_session):
return leap_session.nicknym.keymanager
def setup_search_engine(self, leap_home, soledad_querier):
... |
iulian787/spack | var/spack/repos/builtin/packages/libidl/package.py | Python | lgpl-2.1 | 614 | 0.004886 | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Libidl(AutotoolsPackage):
"""libraries for Interface Defini | tion Language files"""
homepage = "https://developer.gnome.org/"
url = "https://ftp.gnome.org/pub/gnome/sources/libIDL/0.8/libIDL-0.8.14.tar.bz2"
version('0.8.14', sha256='c5d24d8c096546353fbc7cedf208392d5a02afe9d56ebcc1cccb258d7c4d2220')
dep | ends_on('pkgconfig', type='build')
depends_on('glib')
|
allthroughthenight/aces | python/functions/EQBWLE.py | Python | gpl-3.0 | 1,556 | 0.003213 | import math
# Transforms trapezoidal breakwater into a hydraulically equivalent
# rectangular breakwater
# INPUT
# rechd: head difference across equivalent rectangular breakwater
# traphd: head difference across trapezoidal breakwater
# d: water depth
# nummat: number of materials in the breakwater
# numl... | ngular breakwater
# OTHER:
# betar and beta: turbulent resistance coefficients for the equivalent
# and trapezoidal breakwater
def EQBWLE(rechd, traphd, d, nummat, numlay, diam, por, thk, hlen, pref, dref):
# find betar and beta
beta0 = 2.7
betar = beta0*((1.0 - pref)/(pref**3*dref))... | 1.0 - por[i])/(por[i]**3*diam[i])))
# find equivalent rectangular breakwater length
ind = [0.0 for i in range(nummat)]
ind2 = [0.0 for j in range(numlay)]
for j in range(numlay): #layer is columns
for k in range(nummat): # material number is rows
ind[k] = (beta[k]/betar)*hlen[k][j]
... |
ghackebeil/PyORAM | src/pyoram/tests/test_misc.py | Python | mit | 6,387 | 0.009238 | import os
import unittest
import tempfile
import pyoram.util.mis | c
class Test(unittest.TestCase):
def test_log2floor(self):
self.assertEqual(pyoram.util.misc.log2floor(1), 0)
self.assertEqual(pyoram.util.misc.log2floor(2), 1)
self.assertEqual(pyoram.util.misc.log2floor(3), 1)
self.assertEqual(pyoram.util.misc.log2floor(4), 2)
self.assert... | assertEqual(pyoram.util.misc.log2floor(8), 3)
self.assertEqual(pyoram.util.misc.log2floor(9), 3)
def test_log2ceil(self):
self.assertEqual(pyoram.util.misc.log2ceil(1), 0)
self.assertEqual(pyoram.util.misc.log2ceil(2), 1)
self.assertEqual(pyoram.util.misc.log2ceil(3), 2)
sel... |
rootulp/hackerrank | python/euler004.py | Python | mit | 570 | 0 | #!/bin/python3
import bisect
def is_palindrome(n):
return str(n) == str(n)[::-1]
def generate_palindromes():
return [i * j
for i in range(100, 1000)
for | j in range(100, 1000)
if is_palindrome(i * j)]
def find_lt(a, x):
'Find rightmost value less than x'
i = bisec | t.bisect_left(a, x)
if i:
return a[i - 1]
raise ValueError
palindromes = sorted(generate_palindromes())
test_cases = int(input().strip())
for _ in range(test_cases):
n = int(input().strip())
print(find_lt(palindromes, n))
|
moesy/AWS-Lambda-ML-Microservice-Skeleton | app/main.py | Python | mit | 69 | 0.014493 | import pandas as pd
def handler(event, context | ):
|
return ':)'
|
jakubfindura/vnos-nfc | nfc-server/RPLCD/enum.py | Python | mit | 11,214 | 0 | # Copyright (C) 2004-2013 by Barry A. Warsaw
#
# This file is part of flufl.enum
#
# flufl.enum 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, version 3 of the License.
#
# flufl.enum is distributed in... | ls._enums:
other = cls._enums[value]
# Without this, sort order is undefined and causes
| # unpredictable results for the test suite.
first = (attr if attr < other else other)
second = (other if attr < other else attr)
raise ValueError("Conflicting enum value '{}' "
"for names: '{}' and '{}'".format(
... |
yrobla/nova | nova/tests/test_vmwareapi_vm_util.py | Python | apache-2.0 | 5,302 | 0.000943 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2013 Hewlett-Packard Development Company, L.P.
# Copyright 2013 Canonical Corp.
# 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 agreed to in writing, so | ftware
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import collections
from nova import exception
from no... |
bitmovin/bitmovin-python | bitmovin/resources/enums/s3_sig_version.py | Python | unlicense | 91 | 0 | import enum
class S3SignatureVersion | (enum.Enum):
S | 3_V2 = 'S3_V2'
S3_V4 = 'S3_V4'
|
pytlakp/intranetref | src/intranet3/models/project.py | Python | mit | 10,842 | 0.002121 | from pprint import pformat
from sqlalchemy import Column, ForeignKey, orm
from sqlalchemy.types import String, Integer, Boolean, Text
from sqlalchemy.schema import UniqueConstraint
from intranet3 import memcache
from intranet3.models import Base, User
from intranet3.log import WARN_LOG, INFO_LOG, DEBUG_LOG
LOG = INF... | if self.turn_off_selectors:
return u'Turned off'
if self.ticket_id_selector:
return u'Tickets: %s' % ( | self.ticket_id_selector, )
else:
return u'%s / %s / %s' % (
self.project_selector or u'*',
self.component_selector or u'*',
self.version_selector or u'*',
)
def get_selector_tuple(self):
"""
Returns selector tuple
... |
daniLOLZ/variaRoba | Python/34.py | Python | mit | 633 | 0.023697 | import json
with open("birthdays.jso | n", "r") as damnJson:
birthDays = json.load(damnJson)
print("We know the birth days of: ")
for i in birthDays:
print(i)
print("\nWould you like to add or retrieve a birth day?")
lol = input().strip().lower()
if lol == "add":
person = input("Who's the lucky one? ")
date = input("What's his birth day? ")
birthDays... | on", "w") as damnJson:
json.dump(birthDays, damnJson)
print("\nk thx\n")
elif lol == "retrieve":
print("\nWho would you like to know the birth date of? ")
person = input()
print(birthDays[person])
else:
print("fk u m8")
|
callmetaste/PHCpack | src/Python/PHCpy3/phcpy/__init__.py | Python | gpl-3.0 | 3,727 | 0.000268 | """
PHCpy --- a package for Polynomial Homotopy Continuation
========================================================
PHCpy is a collection of Python modules to compute solutions
of polynomial systems using PHCpack.
A homotopy defines the deformation of a start system
(system with known solutions) into the target sys... | ort sets.
phcwulf
defines a simple client/server interaction to solve random trinomials.
Calling the blackbox solver
---------------------------
Polynomials and solutions | are represented as strings.
Below is an illustration of a session with the blackbox solver
on a system of two random trinomials, polynomials with three
monomials with random coefficients.
>>> from phcpy.solver import random_trinomials
>>> f = random_trinomials()
>>> print f[0]
(0.583339727743+0.8122282696... |
bhupennewalkar1337/erpnext | erpnext/buying/doctype/request_for_quotation/request_for_quotation_dashboard.py | Python | gpl-3.0 | 206 | 0.058252 | from frappe import _
def get_data():
re | turn {
'docstatus': 1,
'fieldname': 'request_for_quot | ation',
'transactions': [
{
'label': _('Related'),
'items': ['Supplier Quotation']
},
]
} |
MartinPyka/Parametric-Anatomical-Modeling | pam/pam.py | Python | gpl-2.0 | 34,811 | 0.004998 | """THis module contains the core functions needed to compute pam models"""
import logging
import random
import bpy
import mathutils
import numpy
from . import constants
from . import grid
from . import model
from . import exceptions
from . import layer
from . import connection_mapping
from .mesh import *
import mul... | mask_layer.closest_point_on_mesh(p.location)
return (p.location - l).length
# TODO(SK): missing docstring
# TODO(SK): Rephrase docstring, add parameter/return values
def co | mputeConnectivityProbability(uv1, uv2, func, args):
return func(uv1, uv2, args)
# TODO(SK): Rephrase docstring, add parameter/return values
def computeDistance_PreToSynapse(no_connection, pre_index, synapses=[]):
"""Compute distance for a pre-synaptic neuron and a certain
connection definition
synaps... |
rovere/utilities | split.py | Python | mit | 2,848 | 0.009129 | #!/usr/bin/env python
import sys
import re
def generateFilename(prefix, file_count, suffix):
return "%s_%04d.%s" % (prefix, file_count, suffix)
def split(filename, prefix, suffix, regexp, do_html, frequency=1):
file_count = 0
count = 0
f = open(filename,'r')
o = open(generateFilename(prefix, file... | count, suffix), 'w')
if g and do_html:
t | ry:
o.write('<div id=%s> <a href="%s#%s">%s</a> %s </div>\n' % (g.group(1),
generateFilename(prefix, file_count, suffix),
g.group(1).replace('"', ''),
... |
shweta97/pyta | python_ta/reporters/color_reporter.py | Python | gpl-3.0 | 1,167 | 0.003428 | import sys
from colorama import Fore, Style
from colorama import init
from .plain_reporter import PlainReporter
class ColorReporter(PlainReporter):
def __init__(self, number_of_messages):
super().__init__(number_of_messages)
# Override this method
def print_messages(self, level='all'):
... | ntly running is Windows
init(wrap=(sys.platform == 'win32'), strip=False)
| self.sort_messages()
print(Style.BRIGHT + '=== Code errors/forbidden usage (fix these right away!) ===' + Style.RESET_ALL)
for msg in self._error_messages:
code = Fore.RED + Style.BRIGHT + msg.msg_id + Style.RESET_ALL
print(code, '({}) {}\n [Line {}] {}'.format(msg.symb... |
sabiodelhielo/rancher-validation | tests/v3_api/common.py | Python | apache-2.0 | 41,077 | 0 | import inspect
import json
import os
import random
import subprocess
import time
import requests
import ast
import paramiko
import rancher
from rancher import ApiError
from lib.aws import AmazonWebServices
DEFAULT_TIMEOUT = 120
DEFAULT_MULTI_CLUSTER_APP_TIMEOUT = 300
CATTLE_TEST_URL = os.environ.get('CATTLE_TEST_URL'... | return rancher.Client(url=CATTLE_API_URL, token=token, verify=False)
def get_project_client_for_token(project, token):
p_url = project.links['self'] + '/schemas'
p_client = rancher.Client(url=p_url, token=token, verify=False)
return p_client
def get_cluster_client_for_token(cluster, token):
c_url... |
def up(cluster, token):
c_url = cluster.links['self'] + '/schemas'
c_client = rancher.Client(url=c_url, token=token, verify=False)
return c_client
def wait_state(client, obj, state, timeout=DEFAULT_TIMEOUT):
wait_for(lambda: client.reload(obj).state == state, timeout)
return client.reload(obj)
... |
SlateScience/MozillaJS | js/src/python/mozbuild/mozpack/mozjar.py | Python | mpl-2.0 | 28,516 | 0.000245 | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from io import BytesIO
import struct
import zlib
import os
from zipfile import (
ZIP_STORED,
ZIP_DEFLATED,
)
fro... | unsigned integer field, followed by a
filename_size-long string buffer 'filename'.
Fields that are used as other fields size are not stored in objects. In the
above example, an instance of such subclass would only have two attributes:
obj['version']
obj['filename']
filename_size would b... | es can be either initialized from existing data
(deserialized), or with empty fields.
'''
TYPE_MAPPING = {'uint32': ('I', 4), 'uint16': ('H', 2)}
def __init__(self, data=None):
'''
Create an instance from the given data. Data may be omitted to create
an instance with empty fiel... |
lantra/vugamedev | src/setup.py | Python | mit | 1,710 | 0.008187 | from distutils.core import setup
import py2exe
import os
import sys
sys.argv.append('py2exe')
# The filename of the script you use to start your program.
target_file = 'main.py'
# The root directory containing your assets, libraries, etc.
assets_dir = '.\\'
# Filetypes not to be included in the above.
excluded_file... | t_dir + file
if os.path.isdir(full_path):
get_data_files(base_dir, target_dir + file + '\\', list)
elif os.path.isfile(full_path):
if (len(file.split('.')) == 2 and file.split('.')[1] not in excluded_file_types):
list.append((target_dir, [full_path]))
return ... | e options we want.
opts = { 'py2exe': {
'ascii':'True',
'excludes':['_ssl','_hashlib'],
'includes' : ['anydbm', 'dbhash'],
'bundle_files':'1',
'compressed':'True'}}
# Run the setup utility.
setup(console=[target_file],... |
glerm/ScriptsMusic21 | mostrascore.py | Python | gpl-3.0 | 263 | 0.019011 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from music21 import *
import os
import sys
localcorpus=os.getcwd()+'/localcorpus/'
localXML='mikro'+str(sys.argv[1])+'.xml'
localfile=localcorpus+localXML
MIKRO=convert | er.parse(localfile)
MIKRO.show('lily.pd | f')
|
Kupoman/blendergltf | tests/unit/test_image.py | Python | apache-2.0 | 2,570 | 0.002335 | def test_image_export_reference(exporters, state, bpy_image_default, gltf_image_default):
state['settings']['images_data_storage'] = 'REFERENCE'
gltf_image_default['uri'] = '../filepath.png'
output = exporters.ImageExporter.export(state, bpy_image_default)
assert output == gltf_image_default
def test_... | porters.ImageExporter.export(state, bpy_image_default)
assert output == gltf_image_default
def test_image_export_embed_glb(exporters, state, bpy_image_default, gltf_image_default):
state['settings']['images_data_storage'] = 'EMBED'
state['settings']['gltf_export_binary'] = True
gltf_image_default['mi... | ng'
gltf_image_default['bufferView'] = 'bufferView_buffer_Image_0'
output = exporters.ImageExporter.export(state, bpy_image_default)
for ref in state['references']:
ref.source[ref.prop] = ref.blender_name
assert output == gltf_image_default
def test_image_to_data_uri(exporters, bpy_image_def... |
ministryofjustice/cla_backend | cla_backend/apps/call_centre/tests/test_forms.py | Python | mit | 24,898 | 0.003735 | import datetime
import mock
from django.test import TestCase
from django.utils import timezone
from core.tests.mommy_utils import make_recipe, make_user
from cla_eventlog.tests.test_forms import BaseCaseLogFormTestCaseMixin, EventSpecificLogFormTestCaseMixin
from cla_eventlog.models import Log
from legalaid.models imp... | cla_provider.helpers import ProviderAllocationHelper
from call_centre.forms import (
DeferAssignmentCaseForm,
ProviderAllocation | Form,
DeclineHelpCaseForm,
CallMeBackForm,
StopCallMeBackForm,
)
from cla_common.constants import CASE_SOURCE
from call_centre.tests.test_utils import CallCentreFixedOperatingHours
def _mock_datetime_now_with(date, *mocks):
dt = date.replace(tzinfo=timezone.get_current_timezone())
for _mock in moc... |
alen-alex/aqi_service | aqi_service/util/log_utils.py | Python | apache-2.0 | 2,106 | 0.001899 | # -*- coding: utf-8 -*-
import os
import logging
import datetime
def get_logger(directory, name):
"""
"""
| logger = logging.getLogger(name)
logger.setLevel(logging.INFO)
date_handler = DateFileHandler(directory, name)
fmt_str = '%(asctime)s %(process)d %(module)s.%(funcName)s.%(lineno)d %(levelname)s : %(message)s'
fmt = logging.Formatter(fmt_s | tr, datefmt='%Y-%m-%d %H:%M:%S')
date_handler.setFormatter(fmt)
logger.addHandler(date_handler)
return logger
class DateFileHandler(logging.StreamHandler):
"""
log by date file
"""
def __init__(self, directory, log_name='', mode='a'):
self.directory = directory
self.log_nam... |
jawilson/home-assistant | tests/components/vacuum/common.py | Python | apache-2.0 | 6,031 | 0.001326 | """Collection of helper methods.
All containing methods are legacy helpers that should not be used by new
components. Instead call the service directly.
"""
from homeassistant.components.vacuum import (
ATTR_FAN_SPEED,
ATTR_PARAMS,
DOMAIN,
SERVICE_CLEAN_SPOT,
SERVICE_LOCATE,
SERVICE_PAUSE,
... | ass
@bind_hass
def turn_on(hass, entity_id=ENTITY_MATCH_ALL):
"""Turn all or specified vacuum on."""
hass.add_job(async_turn_on, hass, entity_id)
async def async_turn_on(hass, entity_id=ENTITY_MATCH_ALL):
"""Turn all or specified vacuum on."""
data = {ATTR_ENTITY_ID: entity_id} if entity_id else Non... | c_call(DOMAIN, SERVICE_TURN_ON, data, blocking=True)
@bind_hass
def turn_off(hass, entity_id=ENTITY_MATCH_ALL):
"""Turn all or specified vacuum off."""
hass.add_job(async_turn_off, hass, entity_id)
async def async_turn_off(hass, entity_id=ENTITY_MATCH_ALL):
"""Turn all or specified vacuum off."""
da... |
Richard-Mathie/cassandra_benchmark | vendor/github.com/datastax/python-driver/tests/integration/cqlengine/statements/test_where_clause.py | Python | apache-2.0 | 1,642 | 0.000609 | # Copyright 2013-2016 DataStax, 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 writi... | s and
# limitations under the License.
try:
import unittest2 as unittest
except ImportError:
import unittest # noqa
import six
from cassandra.cqlengine.operators import EqualsOperator
from cassandra.cqlengine.statements import StatementException, WhereClause
class TestWhereClause(unittest.TestCase):
de... | (StatementException):
WhereClause('a', 'b', 'c')
def test_where_clause_rendering(self):
""" tests that where clauses are rendered properly """
wc = WhereClause('a', EqualsOperator(), 'c')
wc.set_context_id(5)
self.assertEqual('"a" = %(5)s', six.text_type(wc), six.text_t... |
downpoured/lnzscript | lnzscript/util/python/zipfile_wrapper.py | Python | gpl-3.0 | 3,191 | 0.024444 | '''
File.zipExtract(strZipfile, strDirectory) // returns # of extracted files or false on error
File.zipList() //returns entries
File.zipList(true) //returns only files, not folders
File.zipCreate(strDirectory)
'''
import os
import zipfile
from io import StringIO
def zipfile_list( filename, includeFolders=False):
... | ))
buflen = 2 ** 20
datum = buffer.read( buflen )
while datum:
| out.write( datum )
datum = buffer.read( buflen )
out.close()
count+=1
except:
err = True
finally:
os.chdir( pushd )
if err: return False
else: return count
def zipfile_create(strDirectory, strFilename):
try:
zf = zipfil... |
MrHalfman/gabbler | social/views.py | Python | gpl-2.0 | 7,760 | 0.001289 | from django.contrib.admin.views.decorators import staff_member_required
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect, JsonResponse
import re
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from core.models import User
fro... | pResponseRedirect("/admin/repo | rts/")
@login_required
def regab(request, gab_pk):
gab = Gab.objects.get(pk=gab_pk)
regab, created = Regab.objects.get_or_create(
gab=gab,
user=request.user
)
regabbed = created
if not created:
regab.delete()
else:
text = "%s regabbed your gab." % request.user.... |
MattBlack85/django-query-logger | query_logger/settings.py | Python | mit | 981 | 0.002039 | QUERY_LOGGING = {
'formatters': {
'wrapper_verbose': {
'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
},
'wrapper_simple': {
'format': '%(levelname)s %(message)s'
},
'wrapper_json': {
'()': 'jsonlogger.J... | nlogger.JsonFormatter',
'format': '%(levelname)s %(message)s'
},
},
'handlers': {
'console_wrapper': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': ' | wrapper_verbose',
}
},
'loggers': {
'query_logger.wrapper': {
'handlers': ['console_wrapper'],
'level': 'DEBUG',
'propagate': True
}
}
}
|
redmoo-info/proddict | ru/books.py | Python | mit | 8,821 | 0.000141 | # -*- coding: utf-8 -*-
"""'Books' part of product categories dictionary.
Must hold subcategories of 'Books'
category in the form of python dictionary data type.
"""
books = {('books', 'книги'): {
('audiobooks', 'аудиокниги'): {
('biography', 'биографии'): {},
('business, economics', 'бизнес, экон... | 'религия'): {},
('science, tech', 'наука, технология'): {},
('social sciences', 'общественные науки'): {},
('sports', 'спорт'): {},
('other', 'другое'): {},
},
('textbooks', 'учебники'): {
('accounting', 'бухгалтерия'): {},
('architecture, desig | n', 'архитектура, дизайн'): {},
('art, photography', 'искусство, фотография'): {},
('biology', 'биология'): {},
('business, economics', 'бизнес, экономика'): {},
('computers, internet', 'компьютер, интернет'): {},
('chemistry', 'химия'): {},
('engineering', 'инжиниринг, т... |
vermouthmjl/scikit-learn | sklearn/learning_curve.py | Python | bsd-3-clause | 14,601 | 0 | """Utilities to evaluate models with respect to a variable
"""
# Author: Alexander Fabisch <afabisch@informatik.uni-bremen.de>
#
# License: BSD 3 clause
import warnings
import numpy as np
from .base import is_classifier, clone
from .cross_validation import check_cv
from .externals.joblib import Parallel, delayed
fro... | rent training set sizes.
n_jobs : integer, optional
Number of jobs to run in parallel (default 1).
pre_dispatch : integer or string, optional
Number of predispatched jobs for paralle | l execution (default is
all). The option can reduce the allocated memory. The string can
be an expression like '2*n_jobs'.
verbose : integer, optional
Controls the verbosity: the higher, the more messages.
Returns
-------
train_sizes_abs : array, shape = (n_unique_ticks,), dtyp... |
markflyhigh/incubator-beam | sdks/python/apache_beam/examples/snippets/transforms/element_wise/keys_test.py | Python | apache-2.0 | 1,774 | 0.002274 | # coding=utf-8
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License");... | '🥔',
]
# [END icons]
self.icons_test = | lambda actual: assert_that(actual, equal_to(icons))
def test_keys(self):
keys(self.icons_test)
if __name__ == '__main__':
unittest.main()
|
vineodd/PIMSim | GEM5Simulation/gem5/src/learning_gem5/part2/SimpleObject.py | Python | gpl-3.0 | 1,750 | 0.000571 | # -*- coding: utf-8 -*-
# Copyright (c) 2017 Jason Lowe-Power
# 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 o... | ON) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER 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.
#
# Authors: Jason Lowe-Power
from m5.params import *
from m5.SimObject import SimObject
class SimpleObject(SimObject):
type = 'SimpleObject'
cxx_header = "learning_gem5/part2/simple_object.hh"
|
lj020326/cloudify3-plugin-test | plugin/tests/file_server.py | Python | apache-2.0 | 3,222 | 0 | #########
# Copyright (c) 2013 GigaSpaces Technologies Ltd. All rights reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless... | logger.info('Starting file server')
if self.use_subprocess:
subprocess.Popen(
[sys.executable, __file__, self.root_path],
stdin=FNULL,
stdout=FNULL,
stderr=FNULL)
else:
self.process.start()
end_time = time.... | r is up and serving from {0}'
.format(self.root_path))
return
logger.info('File server is not responding. waiting 10ms')
time.sleep(0.1)
raise exceptions.TimeoutException('Failed starting '
'file server... |
autopower/thermeq3 | support/del_dev.py | Python | gpl-3.0 | 972 | 0.001029 | import socket
import base64
def read_lines():
global client_socket
lines_buffer = ""
data = True
while data:
try:
data = client_socket.recv(4096)
lines_buffer += data
except socket.timeout:
break
return lines_buffer
print("thermeq3 delete devic... | ax_ip, 62910))
result = read_lines()
dev_id_plain = bytearray.fromhex(dev_id).decode()
message = "t:01,1," + base64.b64encode(dev_id_plain) + "\r\n"
client_socket.sendall(message)
# result must be "A:"
print("Command issued. Please read result. Result must begin with A:\n----------")
pr | int read_lines()
client_socket.close()
|
AndrewNeudegg/CIMC | run.py | Python | mit | 65 | 0.015385 | from CIMC import ap | p
if __name__ == '__main__':
| app.run() |
abelcarreras/aiida_extensions | plugins/jobs/lammps/md.py | Python | mit | 9,997 | 0.003201 | from aiida.orm.calculation.job import JobCalculation
from aiida.orm.data.parameter import ParameterData
from aiida.orm.data.structure import StructureData
from aiida.common.exceptions import InputValidationError
from aiida.common.datastructures import CalcInfo, CodeInfo
from aiida.common.utils import classproperty
fro... | ell | [1], cell[2])/(c*b))
gamma = np.arccos(np.dot(cell[1], cell[0])/(a*b))
beta = np.arccos(np.dot(cell[2], cell[0])/(a*c))
xhi = a
xy = b * np.cos(gamma)
xz = c * np.cos(beta)
yhi = np.sqrt(pow(b,2)- pow(xy,2))
yz = (b*c*np.cos(alpha)-xy * xz)/yhi
zhi = np.sqrt(pow(c,2)-pow(xz,2)-pow(yz,2)... |
fmount/tmux-layout | scripts/menu/tmuxer.py | Python | mit | 1,794 | 0.034002 | #!/usr/bin/env python
#
# v0.1 --
#
# fmount <francesco.pantano@linux.com>
#
#
from argparse import ArgumentParser as argpar | ser
import libtmux
import logging
import subprocess as sub
'''
'''
class Tmuxer(object):
def __init__(self, args):
self.logger = logging.getLogger('Tmuxer')
for attr in args.keys():
setattr(self, attr, args.get(attr, None))
self.server = libtmux.Serv | er()
self.logger.debug("Acquiring parameters: [%s] - [%s] - [%s] [%s]" \
% (self.layout, self.layout_home, self.session, self.main_pane))
def exist_session(self, curr_sess):
if curr_sess is not None:
return True
return False
def build_command(self):
cmd = "tmux source-file " + '/'.join([self.layo... |
ETShax/Coffeebot | pybot/botcommands.py | Python | gpl-3.0 | 1,196 | 0.01113 | # -*- coding: UTF-8 -*-
"""
muutama esimerkki komennoista
"""
import random, time, os
from subprocess import call
# tähän sanastoon lisätään komennot ja niitä vastaavat oliot
command_dict = {}
class Test:
def main(self, irc, line):
irc.send('PRIVMSG %s :Hell World!' % line[2])
command_dict[':!... | in irc.users:
irc.send('JOIN %s' % (line[4]))
command_dict[':!join'] = Join()
class Quit:
def main(self, irc, line):
# määritellään komento vain pääkà | ¤yttäjille
if line[0] in irc.users:
irc.send('QUIT')
irc.socket.close()
irc.done = 1
command_dict[':!quit'] = Quit()
class Kahvia:
# tarttee olla yhteys karahkaan
def main(self, irc, line):
os.system('ssh user@raspi "python ~/raspit/harkka/kahvit... |
phenoxim/nova | nova/virt/powervm/tasks/storage.py | Python | apache-2.0 | 14,010 | 0.000071 | # Copyright 2015, 2017 IBM Corp.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | per(CreateAndConnectCfgDrive, self).__init__(
name='cfg_drive', requires=['mgmt_cna'])
self.adapter = adapter
self.instance = instance
| self.injected_files = injected_files
self.network_info = network_info
self.stg_ftsk = stg_ftsk
self.ad_pass = admin_pass
self.mb = None
def execute(self, mgmt_cna):
self.mb = media.ConfigDrivePowerVM(self.adapter)
self.mb.create_cfg_drv_vopt(self.instance, self.injec... |
ralphbean/ansible | v2/ansible/plugins/connections/__init__.py | Python | gpl-3.0 | 1,862 | 0.001611 | # (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... | def __init__(self, connection_info, *args, **kwargs):
self._connection_info = connection_info
self._display = Display(verbosity=connection_info.verbosity)
def _become_method_supported(self, become_method):
''' Checks if the current class supports this | privilege escalation method '''
if become_method in self.__class__.become_methods:
return True
raise AnsibleError("Internal Error: this connection module does not support running commands via %s" % become_method)
|
Tima-Is-My-Association/TIMA | oai_pmh/models.py | Python | lgpl-3.0 | 3,783 | 0.005551 | from django.db import models
class TextFieldSingleLine(models.TextField):
pass
class MetadataFormat(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
prefix = TextFieldSingleLine(unique=True)
schema = models.URLField(max_length=20... | lt=0)
token = TextFieldSingleLine(unique=True)
from_timestamp = models.DateTimeField(blank=True, null=True)
until_timestamp = models.DateTimeField(blank=True, null=True)
metadata_prefix = models.ForeignKey(MetadataFormat, blank=True, null=Tru | e)
set_spec = models.ForeignKey(Set, blank=True, null=True)
def __str__(self):
return self.token
class Meta:
ordering = ('expiration_date',)
class DCRecord(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
he... |
lino-framework/xl | lino_xl/lib/tim2lino/utils.py | Python | bsd-2-clause | 12,793 | 0.001564 | # -*- coding: UTF-8 -*-
# Copyright 2009-2018 Luc Saffre
# License: GNU Affero General Public License v3 (see file COPYING for details)
"""
Import legacy data from TIM (basic version).
"""
import traceback
import os
from clint.textui import puts, progress
from django.conf import settings
from django.db import models
... | kw.update(trade_type=vat.TradeTypes.purchases)
vcl = finan.PaymentOrder
elif idgen.startswith('5'):
vcl = finan.BankStatement
else:
vcl = finan.JournalEntry
# if vcl is None:
# raise Exception("Journal type not reco... | ame=row.libell)
kw.update(dc=self.dc2lino(row.dc))
# kw.update(seqno=self.seq2lino(row.seq.strip()))
kw.update(seqno=int(row.seq.strip()))
# kw.update(seqno=row.recno())
kw.update(auto_check_clearings=False)
vcl, kw = self.load_jnl_alias(row, **kw)
if vcl is not N... |
mc706/prog-strat-game | core/features/environment.py | Python | mit | 1,165 | 0.003433 | """
This file is a pre-setup environments file to make splinter play nice with behave
It is setup to take screenshots whenever of the browser if your steps fail
To change which | browser you are using, change the string in Browser(). Note you may need to install Chromedriver for chrome
It is lovingly shared and free to use and modify by Ryan McDevitt (mc706.com)
"""
import datetime
import re
import os
from splinter.browser import Browser
BASE_DIR = os.path.dirname(os.path.dirname(__file__))... | er('phantomjs')
context.browser.driver.maximize_window()
def after_all(context):
context.browser.quit()
context.browser = None
def after_step(context, step):
if step.status == "failed":
day = "{0.year}_{0.month}_{0.day}".format(TODAY)
name = '[{0}]-{1}'.format(day, step.name)
... |
sjohannes/exaile | xl/metadata/mod.py | Python | gpl-2.0 | 2,441 | 0.000819 | # Copyright (C) 2008-2010 Adam Olsen
#
# 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, or (at your option)
# any later version.
#
# This program is distributed in the hope that... | code, but you are not obligated to
# do so. If y | ou do not wish to do so, delete this exception statement
# from your version.
from xl.metadata._base import BaseFormat
import os
try:
import ctypes
modplug = ctypes.cdll.LoadLibrary("libmodplug.so.0")
modplug.ModPlug_Load.restype = ctypes.c_void_p
modplug.ModPlug_Load.argtypes = (ctypes.c_void_p, c... |
Edzvu/Edzvu.github.io | M2Crypto-0.35.2/doc/conf.py | Python | mit | 9,150 | 0.007541 | # -*- coding: utf-8 -*-
#
# M2Crypto documentation build configuration file, created by
# sphinx-quickstart on Thu Apr 20 11:15:12 2017.
#
# 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.
#
# Al... | t name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'M2Crypto.tex', u'M2Crypto Documentation',
u'Matej Cepl \\textless{}mcepl@cepl.eu\\textgreater{}', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
... | ters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_... |
AMOboxTV/AMOBox.LegoBuild | plugin.video.salts/scrapers/moviexk_scraper.py | Python | gpl-2.0 | 7,244 | 0.005384 | """
SALTS XBMC Addon
Copyright (C) 2014 tknorris
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
T... | eam_url += '|User-Agent=%s' % (scraper_utils.get_ua())
source = {'multi-part': False, 'url': stream_url, 'host': host, 'class': self, 'quality': quality, 'views': None, 'ratin | g': None, 'direct': True}
sources.append(source)
return sources
def __get_best_page(self, episodes):
if 'EPTRAILER' in episodes: del episodes['EPTRAILER']
if 'EPCAM' in episodes: del episodes['EPCAM']
qualities = ['EPHD1080P', 'EPHD720P', 'EPHD', 'EPFULL']
f... |
google/differentiable-atomistic-potentials | dap/tests/test_tf_neighborlist.py | Python | apache-2.0 | 10,324 | 0.005231 | # Copyright 2018 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... | differences in computed
# positions.
Rc = 2 * a + 0.01
atoms = | bulk('Cu', structure, a=a).repeat(repeat)
nl = NeighborList(
[Rc] * len(atoms), skin=0.0, self_interaction=False, bothways=True)
nl.update(atoms)
distances = get_distances({
'cutoff_radius': 2 * Rc
}, atoms.positions, atoms.cell, np.ones((len(atoms), 1)))
... |
rohitsinha54/Learning-Python | algorithms/symbal.py | Python | mit | 889 | 0.00225 | #!/usr/bin/env python
"""symbal.py: Check for braces to be balanced"""
from stack import Stack
__author__ = 'Rohit Sinha'
def match_braces(opener, closer):
return "({[".index(opener) == ")}]".inde | x(closer)
def brace_checker(brace_string):
stack = Stack()
isbal = True
index = 0
while index < len(brace_string) and isbal:
if brace_string[index] in "({[":
stack.push(brace_string[index])
else:
if stack.isEmpty():
isbal = False
else... | return True
else:
return False
# check the above code
if __name__ == '__main__':
print(brace_checker("([({})])"))
print(brace_checker("[({)]")) |
cecep-edu/edx-platform | lms/djangoapps/badges/models.py | Python | agpl-3.0 | 12,190 | 0.003035 | """
Database models for the badges app
"""
from importlib import import_module
from django.conf import settings
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.db import models
from django.utils.translation import ugettext_lazy as _
from jsonfield import JSONF... |
Exception raised whe | n Course Badges aren't enabled, but an attempt to fetch one is made anyway.
"""
class BadgeClass(models.Model):
"""
Specifies a badge class to be registered with a backend.
"""
slug = models.SlugField(max_length=255, validators=[validate_lowercase])
issuing_component = models.SlugField(max_len... |
damorim/compilers-cin | antigo/ap3/CymbolCheckerVisitor.py | Python | mit | 1,390 | 0.039568 | from antlr4 import *
from autogen.CymbolParser import CymbolParser
from autogen.CymbolVisitor import CymbolVisitor
class Type:
VOID = "void"
INT = "int"
class CymbolCheckerVisitor(CymbolVisitor):
id_values = {}
def visitIntExpr(self, ctx:CymbolParser.IntExprContext):
print("visting "+Type.INT)
return Typ | e.INT
def visitVarDecl(self, ctx:CymbolParser.VarDeclContext):
var_name = ctx.ID().getText()
tyype = ctx.tyype(). | getText()
print("tyype = " + tyype)
if (tyype == Type.VOID):
result = Type.VOID
print("Mensagem de erro 1...")
exit(1)
else:
if ctx.expr() != None:
init = ctx.expr().accept(self)
print("init = " + init)
if init != tyype:
print("Mensagem de erro 2...")
exit(2)
result = tyyp... |
hagleitn/Openstack-Devstack2 | devstack/components/quantum.py | Python | apache-2.0 | 8,662 | 0.001039 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (C) 2012 Yahoo! 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.or... | 'bridge-id', '%OVS_EXTERNAL_ID%']
OVS_BRIDGE_CMDS = [OVS_BRIDGE_DEL, OVS_BRIDGE_ADD, OVS_BRIDGE_EXTERN_ID]
# Subdirs of the downloaded
CONFIG_DIR = 'etc'
BIN_DIR = 'bin'
# What to start (only if openvswitch enabled)
APP_Q_SERVER = 'quantum-server'
APP_Q_AGENT = 'ovs_quantum_a | gent.py'
APP_OPTIONS = {
APP_Q_SERVER: ["%QUANTUM_CONFIG_FILE%"],
APP_Q_AGENT: ["%OVS_CONFIG_FILE%", "-v"],
}
class QuantumUninstaller(comp.PkgUninstallComponent):
def __init__(self, *args, **kargs):
comp.PkgUninstallComponent.__init__(self, *args, **kargs)
class QuantumInstaller(comp.PkgInstall... |
lrq3000/pyFileFixity | pyFileFixity/lib/sortedcontainers/tests/test_stress_sortedlistwithkey.py | Python | mit | 8,149 | 0.005522 | # -*- coding: utf-8 -*-
from __future__ import print_function
from sys import hexversion
import copy
import bisect
import random
from .context import sortedcontainers
from sortedcontainers import SortedListWithKey
from nose.tools import raises
from functools import wraps
class SortedList(SortedListWithKey):
pass... | import datetime
start = datetime.now()
print('Python', sys.version_info)
try:
num = int(sys.argv[1])
print('Setting iterations to', num)
except:
print('Setting iterations to 1000 (default)')
num = 1000
try:
pea = int(sys.argv[2])
random.seed(pea)
... | finally:
print('Exiting after', (datetime.now() - start))
|
elbow-jason/flask-simple-alchemy | tests/test_relator.py | Python | mit | 3,028 | 0.003633 | from flask_simple_alchemy import Relator
from testers import db, app, FakeTable, OtherTable
this_table = Relator(db)
this_table.add('FakeTable')
this_table.add('OtherTable', foreign_key='uuid')
class ThirdTable(db.Model, this_table.HasOneToOneWith.FakeTable):
__tablename__ = 'thirdtable'
id = db.Column(db.Int... | ThirdTable.faketable_id
assert ThirdTable.faketable
with app.app_context():
fk = FakeTable()
fk.unique_name = 'gggg'
db.session.add(fk)
db.session.commit()
saved = FakeTable.query.filter_by(unique_name='gggg').first()
tt = ThirdTable()
tt.faketable_id = ... | assert saved2
def test_Realtor_relationship_again():
this_table = Relator(db)
this_table.add('FakeTable')
this_table.add('OtherTable', foreign_key='uuid', relation_name='OtherTableUUID1')
class FourthTable(db.Model, this_table.HasManyToOneWith.OtherTableUUID1):
__tablename__ = 'fourthta... |
creditbit/electrum-creditbit-server | run_electrum_creditbit_server.py | Python | agpl-3.0 | 11,252 | 0.003022 | #!/usr/bin/env python
# Copyright(C) 2012 thomasv@gitorious
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# ... | . You may experience crashes caused by mmap"
if os.getuid() == 0:
print "Do not run this program as root!"
print "Run the install script to create a non-privileged user."
sys.exit()
def attempt_read_config(config, filename):
try:
| with open(filename, 'r') as f:
config.readfp(f)
except IOError:
pass
def load_banner(config):
try:
with open(config.get('server', 'banner_file'), 'r') as f:
config.set('server', 'banner', f.read())
except IOError:
pass
def setup_network_params(config):
... |
fhirschmann/penchy | penchy/jobs/tools.py | Python | mit | 2,762 | 0.002172 | """
This module provides tools.
.. moduleauthor:: Felix Mueller
.. moduleauthor:: Pascal Wittmann
:copyright: PenchY Developers 2011-2012, see AUTHORS
:license: MIT License, see LICENSE
"""
import os.path
from penchy.jobs.elements import Tool
from penchy.jobs.hooks import Hook
from penchy.jobs.typecheck import T... | "
_POA = MavenDependency(
'de.tu_darmstadt.penchy',
'poa',
'2.0.0.0',
'http://mvn.0x0b.de',
checksum='df4418bed92205e4f27135bbf077895bd4c8c652')
DEPENDENCIES = set((_POA,))
outputs = Types(('reflection_log', list, str),
('classfolder', list, str... | :type name: str
"""
super(Tamiflex, self).__init__(name)
self.hooks.extend([
Hook(teardown=lambda: self.out['reflection_log']
.append(os.path.abspath('out/refl.log'))),
Hook(teardown=lambda: self.out['classfolder']
.... |
USGSDenverPychron/pychron | docs/user_guide/operation/scripts/examples/helix/extraction/felix_co2.py | Python | apache-2.0 | 2,035 | 0.010319 | '''
eqtime: 30
'''
def main():
info('Felix CO2 analysis')
gosub('felix:WaitForCO2Access')
gosub('felix:PrepareForCO2Analysis')
set_motor('beam',beam_diameter)
if analysis_type=='blank':
info('is blank. not heating')
'''
sleep cumulative time to account for blank
... | isable_between_positions:
end_extract()
end_extract()
disable()
info('cleaning gas {} seconds'.format(cleanup))
sleep(cleanup)
def do_extraction():
if ramp_rate>0:
'''
style 1.
'''
# begin_interval(duration)
# | info('ramping to {} at {} {}/s'.format(extract_value, ramp_rate, extract_units)
# ramp(setpoint=extract_value, rate=ramp_rate)
# complete_interval()
'''
style 2.
'''
elapsed=ramp(setpoint=extract_value, rate=ramp_rate)
pelapsed=execute_patte... |
nohona/cron-crm | usr/local/certbot/acme/acme/jose/b64.py | Python | gpl-3.0 | 1,523 | 0 | """JOSE Base64.
`JOSE Base64`_ is defined as:
- URL-safe Base64
- padding stripped
.. _`JOSE Base64`:
https://tools.ietf.org/html/draft-ietf-jose-json-web-signature-37#appendix-C
.. Do NOT try to call this module "base64", as it will "shadow" the
standard library.
"""
import base64
import six
def b6... | : if input is of incorrect type
:raises ValueError: if input is unicode with non-ASCII characters
"""
| if isinstance(data, six.string_types):
try:
data = data.encode('ascii')
except UnicodeEncodeError:
raise ValueError(
'unicode argument should contain only ASCII characters')
elif not isinstance(data, six.binary_type):
raise TypeError('argument should... |
plotly/plotly.py | packages/python/plotly/plotly/validators/parcats/_meta.py | Python | mit | 435 | 0 | import _plotly_utils. | basevalidators
|
class MetaValidator(_plotly_utils.basevalidators.AnyValidator):
def __init__(self, plotly_name="meta", parent_name="parcats", **kwargs):
super(MetaValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
array_ok=kwargs.pop("array_ok", True),
... |
derv82/wifite2 | wifite/attack/pmkid.py | Python | gpl-2.0 | 7,652 | 0.003921 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from ..model.attack import Attack
from ..config import Configuration
from ..tools.hashcat import HcxDumpTool, HcxPcapTool, Hashcat
from ..util.color import Color
from ..util.timer import Timer
from ..model.pmkid_result import CrackResultPMKID
from threading import Thread
... | r `keep_capturing == False`'''
dumptool = HcxDumpTool(self.target, self.pcapng_file)
# Let the dump tool run until we have the hash.
while self.keep_capturing and dumptool.poll() is None:
time.sleep(0.5)
dumptool.interrupt( | )
def save_pmkid(self, pmkid_hash):
'''Saves a copy of the pmkid (handshake) to hs/ directory.'''
# Create handshake dir
if not os.path.exists(Configuration.wpa_handshake_dir):
os.makedirs(Configuration.wpa_handshake_dir)
# Generate filesystem-safe filename from bssid,... |
mojodna/debian-mapnik | plugins/input/templates/helloworld/build.py | Python | lgpl-2.1 | 2,425 | 0.002474 | #!/usr/bin/env python
# Mapnik uses the build tool SCons.
# This python file is run to compile a plugin
# It must be called from the main 'SConstruct' file like:
# SConscript('path/to/this/file.py')
# see docs at: http://www.scons.org/wiki/SConscript()
import os
# Give this plugin a name
# here this happens to be... | ICU_LIB_NAME is used custom builds of icu can
# have different library names like osx which offers /usr/lib/libicucore.dylib
libraries.append(env['ICU_LIB_NAME'])
TARGET = plugin_env.SharedLibrary(
# the name of the target to build, eg 'sqlite.input'
| '../%s' % PLUGIN_NAME,
# prefix - normally none used
SHLIBPREFIX='',
# extension, mapnik expects '.input'
SHLIBSUFFIX='.input',
# list of source files to compile
source=plugin_sources,
# libraries to link to
... |
markgw/jazzparser | lib/nltk/sem/glue.py | Python | gpl-3.0 | 27,061 | 0.008647 | # Natural Language Toolkit: Glue Semantics
#
# Author: Dan Garrette <dhgarrette@gmail.com>
#
# Copyright (C) 2001-2010 NLTK Project
# URL: <http://www.nltk.org/>
# For license information, see LICENSE.TXT
import os
import nltk
from nltk.internals import Counter
from nltk.parse import *
from nltk.parse import MaltPar... | glue_term = parts[1][tuple_comma+1:i] # '(v-r)'
glue_formulas.append([meaning_term, glue_term]) # add the GlueFormula to the list
elif c == ',':
if parenCount == 1: # if it's a comma separatin... | if c == '#': # skip comments at the ends of lines
if parenCount != 0: # if the line hasn't parsed correctly so far
raise RuntimeError, 'Formula syntax is incorrect for entry ' + line
break ... |
Royal-Society-of-New-Zealand/NZ-ORCID-Hub | orcid_api_v3/models/preferences_v30_rc1.py | Python | mit | 3,447 | 0.00029 | # coding: utf-8
"""
ORCID Member
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: Latest
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import si... | cale = lo | cale
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dic... |
hmedina/KaSaAn | KaSaAn/functions/observable_coplotter.py | Python | mit | 6,362 | 0.003458 | #! /usr/bin/env python3
import ast
import glob
import warnings
import numpy as np
from typing import List, Tuple
from .observable_plotter import observable_file_reader
from .numerical_sort import numerical_sort
def _find_data_files(pattern: str) -> List[str]:
"""Find files that match the pattern."""
file_lis... | ata_y = numeric_data[:, var_index]
legend_entry = legend_data[var_index]
elif coplot_expression:
# to render an algebraic expression, we create an abstract sy | ntax tree,
# then replace the tokens that are strings found in the legend with
# the name of the data array, with proper indexing; finally
# the new tree can be executed (with fixed linenos & indents).
# TokenTransformer is declared here so it can include in its scope
... |
srange/SU2 | TestCases/parallel_regression.py | Python | lgpl-2.1 | 66,999 | 0.018254 | #!/usr/bin/env python
## \file parallel_regression.py
# \brief Python script for automated regression testing of SU2 examples
# \author A. Aranake, A. Campos, T. Economon, T. Lukaczyk, S. Padron
# \version 6.2.0 "Falcon"
#
# The current SU2 release has been coordinated by the
# SU2 International Developers Society ... | nna's group at Delft University of Technology.
# - Prof. Nicolas R. Gauger's group at Kaiserslautern University of Technology.
# - Prof. Alberto Guardone's group at Polytechnic University of Milan.
# - Prof. Rafael Palacios' group at Imperial College London.
# - Prof. Vincent Terrapon's group at the University of L... | Lab. of New Concepts in Aeronautics at Tech. Institute of Aeronautics.
#
# Copyright 2012-2019, Francisco D. Palacios, Thomas D. Economon,
# Tim Albring, and the SU2 contributors.
#
# SU2 is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
... |
our-iot-project-org/pingow-web-service | src/blog/settings.py | Python | mit | 3,829 | 0.001567 | """
Django settings for blog project.
Generated by 'django-admin startproject' using Django 1.9.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their | values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# BASE_DIR = "/Users/jmitch/desktop/blog/src/"
# Quick-start development settings - unsuitable ... | WARNING: keep the secret key used in production secret!
SECRET_KEY = 'sm@g)(fbwdh5wc*xe@j++m9rh^uza5se9a57c5ptwkg*b@ki0x'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['tienduong.pythonanywhere.com', '127.0.0.1', '10.169.3.13', '172.20.10.5', '172.20.10.10']
# Appli... |
jackliusr/scrapy-crawlers | crawlers/crawlers/spiders/jd_hardware.py | Python | apache-2.0 | 2,190 | 0.018265 | import scrapy
from scrapy.selector import Selector
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from crawlers.items import JdItem
from scrapy.http import TextResponse,FormRequest,Request
import json
class JdHardwareSpider(scrapy.Spider):
name = 'jd-hardware'
allo... | 'http://list.jd.com/737-1277-6975-0-0-0-0-0-0-0-1-1-1-1-1-72-4137-0.html',
'http://list.jd.com/737-1277-4934-0-0-0-0-0-0-0-1-1-1-1-1-72-4137-0.html',
'http://list.jd.com/737-1277-5004-0-0-0-0-0-0-0-1-1-1-1-1-72-4137-0.ht | ml'
]
def parse(self,response):
sel = Selector(response)
urls = sel.xpath("//a[contains(@href, 'item.jd.com/')]/@href").extract()
for url in urls:
itemid = url[url.rindex('/')+1:-5]
yield Request(url, callback=self.parse_item)
def parse_item(self, response... |
uclapi/uclapi | backend/uclapi/timetable/models.py | Python | mit | 65,300 | 0 | from django.db import models
models.options.DEFAULT_NAMES += ('_DATABASE',)
class Weekstructure(models.Model):
setid = models.TextField(max_length=10)
weeknumber = models.BigIntegerField(null=True, blank=True)
startdate = models.DateField(primary_key=True)
| description = models.TextField(null=True, max_length=80)
mappedto = models.BigIntegerField(null=True, blank=True)
class Meta:
managed = False
db_table = '"CMIS_OWNER"."WEEKS | TRUCTURE"'
_DATABASE = 'roombookings'
class WeekstructureA(models.Model):
id = models.AutoField(primary_key=True)
setid = models.TextField(max_length=10)
weeknumber = models.BigIntegerField(null=True, blank=True)
startdate = models.DateField()
description = models.TextField(max_length=80, ... |
docwalter/py3status | py3status/modules/whoami.py | Python | bsd-3-clause | 1,179 | 0.000848 | # -*- coding: utf-8 -*-
"""
Display logged-in username.
Configuration parameters:
format: display format for whoami (default '{username}')
Format placeholders:
{username} display current username
Inspired by i3 FAQ:
https://faq.i3wm.org/question/1618/add-user-name-to-status-bar.1.html
@author ultrabug
... | },
],
}
def whoami(self):
"""
We use the getpass module to get the current user.
"""
username = '{}'.format(getuser())
return {
'cached_until': self.py3.CACHE_FOREVER,
'full_text': self.py3.safe_format(self.for | mat, {'username': username})
}
if __name__ == "__main__":
"""
Run module in test mode.
"""
from py3status.module_test import module_test
module_test(Py3status)
|
paypal/support | examples/python_analytics/client/collect.py | Python | bsd-3-clause | 2,659 | 0.000376 | # -*- coding: utf-8 -*-
import sys
import json
import time
import uuid
import socket
import getpass
import argparse
import datetime
import platform
import socklusion
DEFAULT_HOST = '127.0.0.1'
DEFAULT_PORT = 8888
DEFAULT_PATH = '/v1/on_import'
TIMEOUT = 5.0
INSTANCE_ID = uuid.uuid4()
IS_64BIT = sys.maxsize > 2 ** 3... | build_date'] = platform.python_build()[1]
ret['version_info'] = list(sys.version_info)
ret['have_ucs4'] = HAVE_UCS4
ret['have_readline'] = HAVE_READLINE
return ret
def get_all_info():
ret = {}
ret['username'] | = getpass.getuser()
ret['uuid'] = str(INSTANCE_ID)
ret['hostname'] = socket.gethostname()
ret['hostfqdn'] = socket.getfqdn()
ret['uname'] = platform.uname()
ret['python'] = get_python_info()
ret['time'] = TIME_INFO
return ret
def build_post_message(data, host=DEFAULT_HOST, path=DEFAULT_PA... |
meisamhe/GPLshared | Research_Projects_UTD/Data_Science/some_python.py | Python | gpl-3.0 | 988 | 0.026316 | # 1. Strip non alphabetic
inputStr = "I may opt for a top yam for Amy, May, and Tommy."
import re
regex = re.compile('[^a-zA-Z ]')
output = regex.sub('',inputStr)
# 2. Convert letters to lower case
output = output.lower()
# 3. so | rt all the letters within each word
# 4. also eliminate duplicates
DicOfWords = {}
for word in output.split():
DicOfWords[''.join(sorted(word))] = 1
# 4. continue sort the list of words
outputWordList = DicOfWords.keys()
outputWordList.sort()
# 5. print the words with space
" ".join(outputWordList)
def Collatz(N):
... | rameters= [1.5,2,-1,-2.5,3]
attribute = [2,-1,2,0.5]
output = 0
for i in range(0, len(attribute)):
output = output + float(attribute[i])*float(parameters[i])
output = output + float(parameters[len(attribute)])
import math
score = 1/(1+math.exp(-output))
print('%.3f'%score)
|
DeadWisdom/inreach | app/ajax.py | Python | mit | 1,366 | 0.005124 | import json, datetime, decimal
from django.http import HttpResponse
class EnhancedJSONEncoder(json.JSONEncoder):
"""
JSONEncoder subclass that knows how to encode date/time and decimal types.
"""
def default(self, o):
if isinstance(o, datetime.datetime):
return o.ctime()
el... | t), status=stat | us, content_type=content_type)
|
grokcore/dev.lexycross | wordsmithed/menu.py | Python | mit | 7,437 | 0.045717 | '''
This will store any menus all inherited from a prototype with two functions
update and execute. Update will change display based on cursor position, while
execute will process button clicks.
'''
import pygame, ai
from pygame.locals import *
from scrabble import DISPLAYSURF, CLICK
class Menu():
def __init__(sel... | userdata.has_key("bestScore"):
text.append("Highest Score: "+str(userdata["bestScore"]))
else:
text.append("Highest Score: 0")
if userdata.has_key("numVictories"):
text.a | ppend("Victories: "+str(userdata["numVictories"]))
else:
text.append("Victories: 0")
if userdata.has_key("numGames"):
text.append("Games Played: "+str(userdata["numGames"]))
else:
text.append("Games Played: 0")
return text
#==================== GAME MENU =====================
class GameMen... |
steve9164/maze-generator | maze.py | Python | mit | 6,550 | 0.003511 |
'''
Maze Generator
By Stephen Davies
Builds a maze using tree construction
'''
# Current idea:
# - Build maze and tree at the same time
# - Start at some square - say (0, 0) for now - and randomly add unused square to leaves of the tree
import random, json
from collections import namedtuple
SquareNode = namedtuple... | (coord1, coord2))
def remove_walls(node):
'Remove walls between node and its children'
for child in node.children:
remove_ | wall(node.coord, child.coord)
remove_walls(child)
remove_walls(self.tree)
maze[2*self.start_square.y+1][2*self.start_square.x+1] = 'S'
maze[2*self.end_square.y+1][2*self.end_square.x+1] = 'E'
return '\n'.join(''.join(row) for row in maze)
def to_json(self):
... |
CCI-MOC/moc-openstack-tools | setpass.py | Python | apache-2.0 | 1,945 | 0.001542 | # Copyright 2016 Massachusetts Open Cloud
#
# 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... | userid, password, pin):
"""Add the user ID and random password to the setpass database.
Returns a token allowing the user to set their password.
"""
body = {'password': password, | 'pin': pin}
request_url = '{base}/token/{userid}'.format(base=self.url,
userid=userid)
response = self.session.put(request_url, json=body)
token = response.text
return token
def get_url(self, token):
""" Generate URL for ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.