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 |
|---|---|---|---|---|---|---|---|---|
Phrozyn/MozDef | tests/alerts/test_bruteforce_ssh.py | Python | mpl-2.0 | 7,170 | 0.00265 | # 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/.
# Copyright (c) 2017 Mozilla Corporation
from positive_alert_test_case import PositiveAlertTestCase
from negative_alert_... | stname (10 hits)",
"tags": ['ssh'],
}
test_cases = []
test_cases.append(
PositiveAlertTestCase(
description="Po | sitive test with default event and default alert expected",
events=AlertTestSuite.create_events(default_event, 10),
expected_alert=default_alert
)
)
events = AlertTestSuite.create_events(default_event, 10)
for event in events:
event['_source']['utctimestamp'] = Alert... |
climapulse/dj-bgfiles | tests/test_http.py | Python | bsd-3-clause | 1,483 | 0.004752 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function, division, absolute_import
from bgfiles.http import create_content_disposition
from django.test import SimpleTestCase
class CreateContentDispositionTest(SimpleTestCase):
def test(self):
header = create_content_disposition('Fu... | der)
header = create_content_disposition('Fußball.pdf', attachment=False)
self.assertEqual(b'inline; filename="Fuball.pdf"; filename*=UTF-8\'\'Fu%C3%9Fball | .pdf', header)
header = create_content_disposition(b'Fussball.pdf')
self.assertEqual(b'attachment; filename="Fussball.pdf"', header)
header = create_content_disposition(b'Fussball.pdf', attachment=False)
self.assertEqual(b'inline; filename="Fussball.pdf"', header)
expected = (b'a... |
pgandev/RocketMap | pogom/webhook.py | Python | agpl-3.0 | 8,054 | 0 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import logging
import requests
from datetime import datetime
from cachetools import LFUCache
from requests_futures.sessions import FuturesSession
import threading
from .utils import get_args
from requests.packages.urllib3.util.retry import Retry
from requests.adapters import H... | return
req_timeout = args.wh_ti | meout
data = {
'type': message_type,
'message': message
}
for w in args.webhooks:
try:
session.post(w, json=data, timeout=(None, req_timeout),
background_callback=__wh_completed)
except requests.exceptions.ReadTimeout:
log.ex... |
kingvuplus/boom2 | lib/python/Components/NetworkTime.py | Python | gpl-2.0 | 1,875 | 0.005867 | # Embedded file name: /usr/lib/enigma2/python/Components/NetworkTime.py
from Components.Console import Console
from config import config
from enigma import eTimer, eDVBLocalTimeHandler, eEPGCache
from Tools.StbHardware import setRTCtime
from time import time, ctime
def AutoNTPSync(session = None, **kwargs):
... | syncpoller = NTPSyncPoller()
ntpsyncpoller.start()
class NTPSyncPoller:
def __init__(self):
self.timer = eTimer()
self.Console = Console()
def start(self):
if self.timecheck not in self.timer.callback:
self.timer.callback.append | (self.timecheck)
self.timer.startLongTimer(0)
def stop(self):
if self.timecheck in self.timer.callback:
self.timer.callback.remove(self.timecheck)
self.timer.stop()
def timecheck(self):
if config.misc.SyncTimeUsing.value == '1':
print '[NTP]: U... |
mahabuber/erpnext | erpnext/hr/report/monthly_salary_register/monthly_salary_register.py | Python | agpl-3.0 | 4,082 | 0.038707 | # 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 flt, cstr
from frappe import msgprint, _
def execute(filters=None):
if not filters: filters = {}
salary_slip... | onth") + "::80", _("Leave Without Pay") + ":Float:130",
_("Payment Days") + ":Float:120"
]
earning_types = frappe.db.sql_list("""select distinct e_type from `tabSalary Slip Earning`
where e_modified_amount != 0 and parent in (%s)""" %
(', '.join(['%s']*len(salary_slips))), tuple([d.name for d in salary_slip... | ))
ded_types = frappe.db.sql_list("""select distinct d_type from `tabSalary Slip Deduction`
where d_modified_amount != 0 and parent in (%s)""" %
(', '.join(['%s']*len(salary_slips))), tuple([d.name for d in salary_slips]))
columns = columns + [(e + ":Currency:120") for e in earning_types] + \
["Arrear Am... |
163gal/Time-Line | libs/wx/tools/Editra/src/syntax/_vbscript.py | Python | gpl-3.0 | 3,982 | 0.004269 | ###############################################################################
# Name: vbscript.py #
# Purpose: Define VBScript syntax | for highlighting and other featu | res #
# Author: Cody Precord <cprecord@editra.org> #
# Copyright: (c) 2008 Cody Precord <staff@editra.org> #
# License: wxWindows License #
##################################################################... |
TheAltcoinBoard/XAB-withoutSecp256k1 | contrib/linearize/linearize-hashes.py | Python | mit | 2,868 | 0.034519 | #!/usr/bin/python
#
# linearize-hashes.py: List blocks in a linear, no-fork version of the chain.
#
# Copyright (c) 2013 The Bitcoin developers
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
import json
import st... | ngs:
settings['min_height'] = 0
if 'max_height' not in settings:
settings['max_height'] = 319000
| if 'rpcuser' not in settings or 'rpcpassword' not in settings:
print "Missing username and/or password in cfg file"
sys.exit(1)
settings['port'] = int(settings['port'])
settings['min_height'] = int(settings['min_height'])
settings['max_height'] = int(settings['max_height'])
get_block_hashes(settings)
... |
ARCHER-CSE/parallel-io | benchmark/analysis/analyse_benchio_output.py | Python | gpl-3.0 | 4,610 | 0.014967 | #!/usr/bin/env python
#
# Analyse benchio output files
#
# System modules for grabbing data
import sys
import os.path
import re
from glob import glob
import seaborn as sns
# Modules for analysing and visualising data
import pandas as pd
import numpy as np
import matplotlib
matplotlib.use('Agg')
from matplotlib import... | s = get_filelist(resdir, "benchio_")
csvdump = open('csvdump.csv', 'w')
cs | vdump.write('"Writers","Scheme","Write Bandwidth (MiB/s)"\n')
# Loop over files getting data
resframe_proto = []
for file in files:
infile = open(file, 'r')
resdict = {}
for line in infile:
if re.search('MPI-IO', line):
break
elif re.search('Starting jo... |
admiralspark/NetSpark-Scripts | Example_Scripts/TinyDB/dbInputData.py | Python | gpl-3.0 | 2,573 | 0.002721 | '''
Usage:
dbInputData.py
dbInputData.py -h | --help
dbInputData.py [--debug] [-i INPUT] [-o FILE]
Options:
-h, --help Shows this menu.
-d, --debug Print debug information. This is the most verbose
option.
-i INPUT Input fi... | gging.debug("Iterating through csv dictionary rows...")
dbdict = {
'hostname': row[ | 'SysName'],
'device_type': row['device_type'],
'ipaddr': row['IP_Address'],
'department': row['Department']
}
logging.debug("Made the following dbdict: " + str(dbdict))
Find = Query()
logging.debug("Begin searching for IP Address using dbdict['ipaddr'... |
Clinical-Genomics/scout | tests/parse/test_parse_rank_score.py | Python | bsd-3-clause | 1,288 | 0.00854 | from scout.parse.variant.rank_score import parse_rank_score
from scout.parse.variant.variant import parse_variant
def test_parse_rank_score():
## GIVEN a rank score string on genmod format
rank_scores_info = "123:10"
variant_score = 10.0
family_id = "123"
## WHEN parsing the rank score
parsed_... |
assert variant_score == parsed_rank_score
def test_parse_rank_ | score_no_score():
## GIVEN a empty rank score string
rank_scores_info = ""
family_id = "123"
## WHEN parsing the rank score
parsed_rank_score = parse_rank_score(rank_scores_info, family_id)
## THEN assert that None is returned
assert parsed_rank_score == None
def test_parse_rank_score_vari... |
jumpstarter-io/nova | nova/tests/scheduler/test_weights.py | Python | apache-2.0 | 9,359 | 0.000427 | # Copyright 2011-2012 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless... | free_ram_mb=512
# host2: free_ram_mb=1024
# host3: free_ram_mb=3072
# host4: free_ram_mb=8192
# We do not know the host, all have same weight.
weighed_host = self._get_weighed_host(hostin | fo_list)
self.assertEqual(weighed_host.weight, 0.0)
def test_ram_filter_multiplier2(self):
self.flags(ram_weight_multiplier=2.0)
hostinfo_list = self._get_all_hosts()
# host1: free_ram_mb=512
# host2: free_ram_mb=1024
# host3: free_ram_mb=3072
# host4: free_... |
firasbenmakhlouf/JobLookup | annonce/apps.py | Python | mit | 130 | 0 | from __future__ import unicode_literals
| from django.apps import AppConfig
cl | ass AnnonceConfig(AppConfig):
name = 'annonce'
|
psi4/psi4 | psi4/driver/p4util/inpsight.py | Python | lgpl-3.0 | 23,279 | 0.016624 | #
# @BEGIN LICENSE
#
# Psi4: an open-source quantum chemistry software package
#
# Copyright (c) 2007-2022 The Psi4 Developers.
#
# The copyrights for code used from other parties are included in
# the corresponding files.
#
# This file is part of Psi4.
#
# Psi4 is free software; you can redistribute it and/or modify
#... | end([212,122,0])
colors.append([148,0,148])
colors.append([66,158,176])
colors.append([87,23,143])
colors.append([0,201,0])
colors.append([112,212,255])
colors.append([255,255,199])
colors.append([217,255,199])
colors.append([199,255,199])
colors.append([163,255,199])
colors.appe... | colors.append([0,230,117])
colors.append([0,212,82])
colors.append([0,191,56])
colors.append([0,171,36])
colors.append([77,194,255])
colors.append([77,166,255])
colors.append([33,148,214])
colors.append([38,125,171])
colors.append([38,102,150])
colors.append([23,84,135])
colors.... |
carze/cutlass | cutlass/HostVariantCall.py | Python | mit | 23,915 | 0.000794 | """
This module models the host variant call object.
"""
import json
import logging
import os
import string
from cutlass.iHMPSession import iHMPSession
from cutlass.Base import Base
from cutlass.aspera import aspera
from cutlass.Util import *
# pylint: disable=W0703, C1801
# Create a module logger named after the mo... | s = []
if not valid:
self.logger.info("Validation did not succeed for %s.", __name__)
problems.append(error_message)
if self._private_files:
self.logger.info("User specified the files are private.")
else:
self.logger.info("Data is NOT private, so... | e(self._local_file):
problems.append("Local file does not point to an actual file.")
if 'computed_from' not in self._links.keys():
problems.append("Must add a 'computed_from' link to a host_wgs_raw_seq_set.")
self.logger.debug("Number of validation problems: %s.", len(probl... |
fake-name/ReadableWebProxy | WebMirror/management/rss_parser_funcs/feed_parse_extractSpiritGodShura.py | Python | bsd-3-clause | 484 | 0.024793 | def extractSpiritGodShura(item):
"""
# Sousetsuka
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or 'preview' in item['title'].lower():
return None
if item[' | title'].startswith('Chapter') and item['tags'] == ['Chapters']:
if ':' in item['title'] and not postfix:
postfix = item['title'].split(':')[-1]
return buildReleaseMessageWithType(item | , 'Spirit God Shura', vol, chp, postfix=postfix, tl_type='oel')
return False
|
laenderoliveira/exerclivropy | cap09/exercicio-09-21.py | Python | mit | 2,962 | 0 | agenda = []
def pedenome():
return input("Nome: ").replace("#", "$")
def pedetelefone():
return input("Telefone: ").replace("#", "$")
def pedearquivo():
return input("Nome do arquivo: ")
def mostra(nome, telefone):
print(f"Nome: {nome} Telefone: {telefone}")
def pesquisa(nome):
mnome = nom... | opcao = menu()
if opcao == 0:
break
elif opcao == 1:
novo()
elif opcao == 2:
altera()
elif opcao == 3:
apaga()
elif opcao == 4:
lista()
elif opcao == 5:
grava()
elif opca | o == 6:
le()
elif opcao == 7:
ordena()
|
antoinecarme/pyaf | tests/artificial/transf_None/trend_Lag1Trend/cycle_12/ar_/test_artificial_32_None_Lag1Trend_12__20.py | Python | bsd-3-clause | 259 | 0.088803 | import pyaf.Bench.TS | _datasets as tsds
import tests.artificial.process_artificial_dataset as art
| art.process_dataset(N = 32 , FREQ = 'D', seed = 0, trendtype = "Lag1Trend", cycle_length = 12, transform = "None", sigma = 0.0, exog_count = 20, ar_order = 0); |
google/TensorNetwork | tensornetwork/backends/jax/jax_backend.py | Python | apache-2.0 | 36,454 | 0.004197 | # Copyright 2019 The TensorNetwork 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 ... | decompositions.svd(
jnp,
tensor,
pivot_axis,
max_singular_values,
max_truncation_error,
relative=relative)
def qr(
self,
tensor: Tensor, |
pivot_axis: int = -1,
non_negative_diagonal: bool = False
) -> Tuple[Tensor, Tensor]:
return decompositions.qr(jnp, tensor, pivot_axis, non_negative_diagonal)
def rq(
self,
tensor: Tensor,
pivot_axis: int = -1,
non_negative_diagonal: bool = False
) -> Tuple[Tensor, Tensor... |
egentry/stellarstructure | integrate.py | Python | mit | 6,257 | 0.042033 | import numpy as np
import scipy.integrate as integ
import matplotlib.pyplot as plt
from matplotlib import rc
rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
rc('text', usetex=True)
import derivs
import gasproperties
import opacity
import loadinitial
import modelparameters
from multiprocessing import Poo... | ((P_outward, np.flipud(P_inward)))
T_tot = np.concatenate((T_outward, np.flipud(T_inward)))
plt.figure(1)
plt.subplot(221)
plt.plot(m_tot / M_star, r_tot)
plt.xlabel( | r"$\frac{m}{M}$")
plt.ylabel(r"$r(m)$")
plt.subplot(222)
plt.semilogy(m_tot / M_star, l_tot)
plt.xlabel(r"$\frac{m}{M}$")
plt.ylabel(r"$\ell(m)$")
plt.subplot(223)
plt.semilogy(m_tot / M_star, P_tot)
plt.xlabel(r"$\frac{m}{M}$")
plt.ylabel(r"$P(m)$")
plt.subplot(224)
plt.semilogy(m_tot / M_star, T_tot)
p... |
SubhasisDutta/NoteBook | settings.py | Python | mit | 370 | 0.002703 | '''
Created on Jun 18, 2015
@author: Subhasis
'''
# Replace the following lines with client IDs obtained from the APIs
# Console or Cloud Console.
WEB_CLIENT_ID = '540614338141-drb3g1kcetlp4sbgaj7dfkj | ci6n5ove5.apps.googleusercontent.com'
ANDROID_CLIEN | T_ID = 'replace with Android client ID'
IOS_CLIENT_ID = 'replace with iOS client ID'
ANDROID_AUDIENCE = WEB_CLIENT_ID
|
sevein/archivematica | src/dashboard/src/components/helpers.py | Python | agpl-3.0 | 13,812 | 0.004634 | # This file is part of Archivematica.
#
# Copyright 2010-2013 Artefactual Systems Inc. <http://artefactual.com>
#
# Archivematica 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 ... | ta.value = value
setting_data.save()
def get_client_config_value(field):
clientConfigFilePath = '/etc/archivematica/MCPClient/clientConfig.conf'
config = ConfigParser.SafeConfi | gParser()
config.read(clientConfigFilePath)
try:
return config.get('MCPClient', field)
except:
return ''
def get_server_config_value(field):
clientConfigFilePath = '/etc/archivematica/MCPServer/serverConfig.conf'
config = ConfigParser.SafeConfigParser()
config.read(clientConfig... |
luci/luci-py | appengine/components/components/config/run_coverage.py | Python | apache-2.0 | 491 | 0.004073 | #!/usr/bin/env python
# Copyright 2015 The LUCI | Authors. All rights re | served.
# Use of this source code is governed under the Apache License, Version 2.0
# that can be found in the LICENSE file.
import os
import sys
THIS_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(THIS_DIR, '..', '..'))
from tools import run_coverage
if __name__ == '__main__':
... |
primepix/django-sentry | example_project/urls.py | Python | bsd-3-clause | 148 | 0.006757 | from django.conf.urls import * |
urlpatterns = patterns('',
url(r'^debug/', include('tests.urls')),
url(r'^', include('sentry.web.urls')) | ,
)
|
facebook/buck | test/com/facebook/buck/android/testdata/android_project/native/proguard_gen/generator.py | Python | apache-2.0 | 151 | 0.006623 | #!/usr/bin/python
import sys
assert len(sys.argv) > 2
with open | (sys.argv[1], "w") as out:
for l in | sys.argv[2:]:
out.write("# %s\n" % l)
|
marchchad/GatorApp | gator_dev/urls.py | Python | gpl-2.0 | 146 | 0.006849 | from django.conf.urls import | patterns, include, url
handler404 = 'jobs.views.FileNotFound'
urlpatterns = [
| url(r'^', include('jobs.urls'))
] |
alesdotio/Spirit | spirit/user/forms.py | Python | mit | 4,294 | 0.002329 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django import forms
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth import get_user_model
from django.utils import timezone
from django.template import defaultfilters
from django.conf import settings
from ..core.uti... | f clean_email(self):
email = self.cleaned_data["email"]
if settings.ST_CASE_INSENSITIVE_EMAILS:
email = email.lower()
| if not settings.ST_UNIQUE_EMAILS:
return email
is_taken = User.objects\
.filter(email=email)\
.exists()
if is_taken:
raise forms.ValidationError(_("The email is taken."))
return email
def get_email(self):
return self.cleaned_data["e... |
nickhand/nbodykit | nbodykit/source/catalog/tests/test_file.py | Python | gpl-3.0 | 4,337 | 0.007378 | from runtests.mpi import MPITest
from nbodykit.lab import *
from nbodykit import setup_logging
from numpy.testing import assert_allclose
import tempfile
import os
@MPITest([1])
def test_hdf(comm):
import h5py
# fake structured array
dset = numpy.empty(1024, dtype=[('Position', ('f8', 3)), ('Mass', 'f8')]... | taset='X', attrs={"Nmesh":32}, comm=comm)
correct_region = source.gslice(32, 64)
region = source.query_range(32, 64)
assert_allclose(
numpy.concatenate(comm. | allgather(region['Index'].compute())),
numpy.arange(32, 64)
)
if comm.rank == 0:
os.unlink(tmpfile)
@MPITest([1])
def test_csv(comm):
with tempfile.NamedTemporaryFile() as ff:
# generate data
data = numpy.random.random(size=(100,5))
numpy.savetxt(ff, data, fmt='%... |
pombredanne/HyperDex | bindings/__init__.py | Python | bsd-3-clause | 22,251 | 0.008314 | # Copyright (c) 2013-2014, Cornell University
# 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 ... | tatus,)),
Method('group_atomic_mul', AsyncCall, (SpaceName, Predicates, Attributes), (Status, Count)),
Method('atomic_div', AsyncCall, (SpaceName, Key, Attributes), (Status,)),
Method('uxact_atomic_div', MicrotransactionCall, (Microtransaction, Attributes), ()),
Method('cond_atomic_div', AsyncCall, (Spa... | ates, Attributes), (Status, Count)),
Method('atomic_mod', AsyncCall, (SpaceName, Key, Attributes), (Status,)),
Method('cond_atomic_mod', AsyncCall, (SpaceName, Key, Predicates, Attributes), (Status,)),
Method('group_atomic_mod', AsyncCall, (SpaceName, Predicates, Attributes), (Status, Count)),
Method('a... |
supernathan23/dn_availability | dn_availability/cli.py | Python | mit | 13,300 | 0.008722 | """ Code used for running the package directly from the Command Line """
import os.path
import logging
import argparse
import sys
from .db import AvailabilityDB
from .core import AvailabilityInfo
from .reports import ALL_REPORTS
from .settings import get_settings
def run():
# ----------------------... | ', '.join(ALL_REPORTS.keys()))
)
parser_gen_report.add_argument('-s', '--system_id', action='append',
help='System ID (use the list -t PhoneSystem" subcommand for a list of'
' syste | ms)')
parser_gen_report.add_argument('-g', '--number_group', action='append',
help='Number Group ID (use the "list -t NumberGroup" subcommand for a '
'list of number groups')
parser_gen_report.add_argument('-o', '--output_filename',
help='Destination filename (will be overwritten if... |
tboyce021/home-assistant | homeassistant/components/zha/core/channels/base.py | Python | apache-2.0 | 12,609 | 0.001269 | """Base classes for channels."""
import asyncio
from enum import Enum
from functools import wraps
import logging
from typing import Any, Union
import zigpy.exceptions
from homeassistant.core import callback
from .. import typing as zha_typing
from ..const import (
ATTR_ARGS,
ATTR_ATTRIBUTE_ID,
ATTR_ATTR... | nd_signal(
f"{self.unique_id}_{SI | GNAL_ATTR_UPDATED}",
attrid,
self.cluster.attributes.get(attrid, [attrid])[0],
value,
)
@callback
def zdo_command(self, *args, **kwargs):
"""Handle ZDO commands on this cluster."""
@callback
def zha_send_event(self, command: str, args: Union[int, dic... |
rx2130/Leetcode | python/274 H-Index.py | Python | apache-2.0 | 993 | 0.001007 | class Solution(object):
# Op1: time O(n*log(n)) space O(1)
def hIndex(self, citations):
"""
:type citations: List[int]
:rtype: int
"""
citations.sort(reverse=True)
for i, x in enumerate(citations):
# print(i, x)
if i >= x:
r... | citeCount[n] += 1
else:
citeCount[c] += 1
count = 0
f | or i in reversed(range(n + 1)):
count += citeCount[i]
if count >= i:
return i
return 0
citations = [3, 0, 6, 1, 5]
test = Solution()
print(test.hIndex(citations))
print(test.hIndex2(citations))
|
ferris-wufei/toolbox | dw/api_ga/api_ga.py | Python | gpl-2.0 | 5,603 | 0.003926 | # -*- coding: utf-8 -*-
"""
author: ferris
update: 2015-12-08
function: query from Google Analytics API, using loop to overcome quota of 10,000 records per query.
"""
import argparse
from googleapiclient.discovery import build
from oauth2client.client import SignedJwtAssertionCredentials
import httplib2
from oauth2cli... | start_index=start_index,
max_results=max_results,
| samplingLevel='HIGHER_PRECISION'
).execute()
try:
temp_data = api_query.execute()
except TypeError:
print('There was an error in constructing your q... |
apache/dispatch | tests/system_tests_tcp_adaptor.py | Python | apache-2.0 | 50,963 | 0.002178 | #
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... | esult
class TcpAdaptor(TestCase):
"""
6 edge routers connected via 3 interior routers.
9 echo servers are connected via tcpConnector, one to each router.
Each router has 10 listeners, one for each server and
another for which there is no server.
"""
# +-------+ +---------+ +--------... | | | | | | +-------+
# +-------+ | | | | | | |
livio/DocDown-Python | docdown/template_adapters/string_format.py | Python | bsd-3-clause | 1,530 | 0.001961 | # -*- coding: utf-8 -*-
"""
Adapter to use Python str.format() to render a template
"""
from __future__ import absolute_import, unicode_literals, print_function
from string import Formatter
# handle py2 and py3 strings without relying on six lib since we don't use it for anything else.
try:
basestring
except Na... | ender(self, template='', context=None, *args, **kwargs):
if context is None:
| context = {}
formatter = DefaultValueFormatter()
return formatter.format(template, **context)
|
whosonfirst/py-mapzen-whosonfirst-pip-utils | setup.py | Python | bsd-3-clause | 1,676 | 0.004773 | #!/usr/bin/env python
# Remove .egg-info directory if it exists, to avoid dependency problems with
# partially-installed packages (20160119/dphiffer) ... | pzen/py-mapzen-whosonfirst-pip-utils',
install_requires=[
'mapzen.whosonfirst.pip>=0.04',
'mapzen.whosonfirst.placetypes>=0.11',
'shapely',
],
dependency_links=[
'https://github.com/whosonfirst/py-mapzen-whosonfirst-pip/tarball/master#egg=mapzen.whosonfirst.pip-0.04',
... | hosonfirst-placetypes/tarball/master#egg=mapzen.whosonfirst.placetypes-0.11',
],
packages=packages,
scripts=[
],
download_url='https://github.com/mapzen/py-mapzen-whosonfirst-pip-utils/releases/tag/' + version,
license='BSD')
|
light-swarm/lightswarm_render | scripts/display.py | Python | mit | 385 | 0.012987 | #!/usr/bin/env python
import cv2
import cv2.cv as cv
class Di | splay:
def setup(self, fullscreen):
cv2.namedWindow('proj_0', cv2.WINDOW_OPENGL)
if fullscreen:
cv2.setWindowProperty('proj_0', cv2.WND_PROP_FULLSCREEN, cv.CV_WINDOW_FULLSCREEN)
def draw(self, image):
cv2.imshow('proj_0', image)
cv2.waitKey(1)
| |
hugoxia/Python | FluentPython/chapter_2/sequence.py | Python | mit | 919 | 0 | from collections import namedtuple
def game():
# 元组拆包
a, b, *rest = range(5)
print(a, b, rest)
a, b, *rest = range(2)
print(a, b, rest)
a, *body, c, d = range(5)
print(a, body, c, d)
*head, b, c, d = range(5)
print(head, b, c, d)
# 具名元组 page_26
City = namedtuple('City',... | ong = namedtuple('LatLong', 'lat long')
delhi_data = ('Delhi NCR', 'IN', 21.935, LatLong(28.613889, 77.208889))
delhi = City._make(delhi_data)
print(delhi._asdict()) # collections.OrderedDict
if __n | ame__ == "__main__":
game()
|
joshbedo/phpsh | src/dbgp-phpsh.py | Python | bsd-3-clause | 34,783 | 0.004226 | #!/usr/bin/env python
from select import poll, POLLIN, POLLHUP
from subprocess import Popen, PIPE
from phpsh import PhpshConfig
import xml.dom.minidom
import signal
import socket
import shlex
import time
import sys
import re
import os
"""This is a DBGp xdebug protocol proxy started by phpsh. It accepts a
connection f... | and DISPLAY is not set"
cmd = config.get_option("Debugging", "DebugClient")
if cmd.startswith("emacs"):
emacs_version = get_emacs_version()
if emacs_version < [22, 1]:
raise Exception, "emacs version " + str(emacs_version) +\
" is... | ntPath")
debugclient_version = get_debugclient_version(debugclient_path)
if debugclient_version < [0, 10, 0]:
raise Exception, "debugclient (xdebug client) version " +\
str(debugclient_version) + " is too low. 0.10.0 or "\
"above requir... |
jstasiak/python-zeroconf | examples/self_test.py | Python | lgpl-2.1 | 1,785 | 0.00112 | #!/usr/bin/env python3
import logging
import socket
import sys
from zeroconf import ServiceInfo, Zeroconf, __version__
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
if | len(sys.argv) > 1:
assert sys.ar | gv[1:] == ['--debug']
logging.getLogger('zeroconf').setLevel(logging.DEBUG)
# Test a few module features, including service registration, service
# query (for Zoe), and service unregistration.
print(f"Multicast DNS Service Discovery for Python, version {__version__}")
r = Zeroconf()
print("... |
bbsan2k/nzbToMedia | libs/beetsplug/lastgenre/__init__.py | Python | gpl-3.0 | 14,453 | 0 | # -*- coding: utf-8 -*-
# This file is part of beets.
# Copyright 2016, Adrian Sampson.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation t... | ndicates the default whitelist.
wl_filename = WHITELIST
if wl_filename:
wl_filename = normpath(wl_filename)
with open(wl_filename, 'r') as f:
for line in f:
line = line.decode('utf8').strip().lower()
if line and not line... | #'):
self.whitelist.add(line)
# Read the genres tree for canonicalization if enabled.
self.c14n_branches = []
c14n_filename = self.config['canonical'].get()
if c14n_filename in (True, ''): # Default tree.
c14n_filename = C14N_TREE
if c14n_fil... |
ipriver/0x71aBot-Web-Interface | webinter/urls.py | Python | mit | 262 | 0 | from django.conf.urls import url
from . import views
f | rom django.views.decorators.cache import cache_page
app_name = 'webinter'
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name=' | index'),
url(r'^logout/$', views.logout_view, name='logout'),
]
|
pombredanne/pants | contrib/scrooge/tests/python/pants_test/contrib/scrooge/tasks/test_scrooge_gen_integration.py | Python | apache-2.0 | 2,191 | 0.007303 | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
from pants_test.pant... | _pants(cmd)
self.assert_success(pants_run)
def test_default_java_namespace(self):
# scrooge_gen should pass with default_java_namespace specified
cmd = ['gen', self.thrift_test_target('default-java-namespace-thrift')]
pants_run = self.run_pants(cmd)
self.assert_success(pants_run)
def test_incl... | n = self.run_pants(cmd)
self.assert_success(pants_run)
|
fizz-ml/policybandit | trainer.py | Python | mit | 3,859 | 0.011143 | import torch as t
from torch.autograd import Variable as V
from torch import FloatTensor as FT
import numpy as np
from bayestorch.hmc import HMCSampler
class SimpleTrainer:
def __init__(self, env,critic,hallucinator,policy_buffer,policy_c, noise_dim):
self.env = env
self.hallucinator = hallucinator... | policy.load_state_dict(state_dict)
def closure():
noise=V(FT(np.random.randn(self.noise_dim)))
states = self.hallucinator.forward(noise.unsqueeze(0))
# Concatenating dimensions of bath(which is currently 1) and di | mensions of
states = states.view(states.size(0)*self.hallucinator.n, -1)
actions = policy.forward(states)
actions = actions.view(1,-1)
states = states.view(1,-1)
mean = self.critic(states,actions)[0]
... |
thomasleveil/pydig | pydiglib/dnsparam.py | Python | gpl-2.0 | 3,623 | 0.008556 | import hashlib
import struct
class DNSparam:
"""Class to encapsulate some DNS parameter types (type, class etc)"""
def __init__(self, prefix, name2val):
self.name2val = name2val
self.val2name = dict([(y,x) for (x,y) in name2val.items()])
self.prefix = prefix
self.prefix_offset... | else:
return self.val2name[val]
def get_val(self, name):
"""given text name, return code (value) of a dns parameter"""
if self.prefix and name.startswith(self.prefix):
return int(name[self.prefix_offset:])
else:
return self.name2val[name]
# DNS Reso... | "MG": 8,
"MR": 9,
"NULL": 10,
"WKS": 11,
"PTR": 12,
"HINFO": 13,
"MINFO": 14,
"MX": 15,
"TXT": 16,
"RP": 17,
"AFSDB": 18,
"X25": 19,
"ISDN": 20,
"RT": 21,
"NSAP": 22,
"NSAP-PTR": 23,
"SIG": 24,
"KEY": 25,
"PX": 26,
"GPOS": 27,
"AAAA": 2... |
AndreLamurias/IBEnt | src/classification/rext/ddi_kernels.py | Python | mit | 23,772 | 0.008287 | #!/usr/bin/env python
#shallow linguistic kernel
import sys, os
import os.path
import xml.etree.ElementTree as ET
import logging
from optparse import OptionParser
import pickle
import operator
from subprocess import Popen, PIPE
from time import time
#from pandas import DataFrame
import numpy as np
from scipy.stats impo... | rtext[it].lstrip()
lemma = lemmas[it]
| if tokentext == '-RRB-':
tokentext = ')'
lemma = ')'
elif tokentext == '-LRB-':
tokentext = '('
lemma = '('
#if ' ' in pairtext[it][0].lstrip() or '\n' in pairtext[it][0].lstrip():
# print "token with spaces!"
... |
saurabh-hirani/icinga2_api | icinga2_api/cmdline.py | Python | isc | 3,123 | 0.012168 | #!/usr/bin/env python
import click
import json
import re
from icinga2_api.api import Api
from icinga2_api import defaults
VALID_ACTIONS = ['create', 'read', 'update', 'delete']
def validate_uri(ctx, param, value):
if not value.startswith('/'):
raise click.BadParameter('should begin with single /')
return va... | ify certificate path - not required if profile specified',
default=None)
@click.option('-v', '--verbose/--no-verbose', help='verbose. Default: false',
default=False)
@click.option('-d', '--data', help='json data to pass',
callback=validate_data,
default=None)
@cl... | gs
obj = Api(**kwargs)
kwargs['uri'] = re.sub("/{2,}", "/", kwargs['uri'])
method_ref = getattr(obj, kwargs['action'])
output_ds = method_ref(kwargs['uri'], kwargs['data'])
exit_code = 0
if output_ds['status'] != 'success':
click.echo(click.style('CRITICAL: %s action failed' % kwargs['action'], fg='red... |
gina-alaska/emodis_ndvi_python-docker | emodis_ndvi_python/pycodes/oneyear_data_layer_subset_good.py | Python | mit | 5,054 | 0.033241 | #This python script is modified from oneyear_data_layer_subset_good.pro
#This routine open one year files defined in file lists, stack these file, subset, and fill bad data with -2000
#input arguments are flist_ndvi, flist_bq, ul_lon,ul_lat,lr_lon,lr_lat
#;inputs: yyyy_flist_ndvi----file list for one year *ndvi.tif,... | (sys.argv), 'arguments.'
print 'Argument List:', str(sys.argv)
if len(sys.argv) != 7:
print "input arguments are: flist_ndvi, flist_bq, ulx,uly,lrx,lry"
sys.exit(1)
flist_ndvi=sys.argv[1]
flist_bq=sys.argv[2]
ulx=float(sys.argv[3])
uly=float(sys.argv[4])
lrx=float(sys.argv[5])
lry=float(s... | 9'56.82"W, 54d 0' 0.07"N
#;if do not want subsize the data, just input 0,0,0,0 for ul_lon,ul_lat,lr_lon,lr_lat, respectively.
#;wrkdir='/home/jiang/nps/cesu/modis_ndvi_250m/wrkdir/'
#;flist_ndvi='/mnt/jzhu_scratch/EMODIS-NDVI-DATA/wrk/ver_new_201107/2008/flist_ndvi'
#;flist_bq = '/mnt/jzhu_scratch/EMODIS-NDVI-DAT... |
koendeschacht/python-logstash-async | logstash_async/utils.py | Python | mit | 2,122 | 0.000943 | # -*- coding: utf-8 -*-
#
# This software may be modified and distributed under the terms
# of the MIT license. See the LICENSE file for details.
from __future__ import print_function
from datetime import datetime
from importlib import import_module
from itertools import chain, islice
import sys
import traceback
im... | ds items from an iterator in iterable chunks.
http://stackoverflow.com/a/1335572
"""
itera | ble = iter(seq)
while True:
yield list(chain([next(iterable)], islice(iterable, chunksize - 1)))
# ----------------------------------------------------------------------
def safe_log_via_print(log_level, message, *args, **kwargs):
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
log_messag... |
google-research/football | gfootball/scenarios/tests/keeper_test.py | Python | apache-2.0 | 1,184 | 0.010135 | # coding=utf-8
# Copyright 2019 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 agreed to ... | d 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.
from . import *
def build_scenario(builder):
builder.config().game_duration = 30
builder.config().determini... | 1.00, 0.00, e_PlayerRole_GK, True)
builder.AddPlayer(0.85, 0.30, e_PlayerRole_RM, True)
builder.AddPlayer(0.00, 0.00, e_PlayerRole_RM, True)
builder.SetTeam(Team.e_Right)
builder.AddPlayer(-1.00, 0.00, e_PlayerRole_GK, True)
builder.AddPlayer(0.85, 0.30, e_PlayerRole_RM, True)
|
jmgilman/neolib2 | neolib/plots/altador/steps/HealPetPet.py | Python | gpl-2.0 | 2,736 | 0.001827 | from neolib.plots.Step import Step
from neolib.NST import NST
import time
class HealPetPet(Step):
_paths = {
'links': '//*[@id="content"]/table/tr/td[2]//a/@href',
'img': '//*[@id="content"]/table/tr/td[2]/div/img/@src',
'cert': '//area/@href',
}
_HEALS = {
'http://images... | f = open('test.html', 'w', encoding='utf-8')
f.write(pg.content)
f.close()
if len(self._xpath('cert', pg)) > 0:
print('Found certificate!')
url = self._base_url + self._xpath('cert', pg)[0]
pg = self._usr.get_page(url)
... | ge')
exit()
# Wait till the next minute to check on the petpet
wait = (60 - NST.sec) + 1
print('Waiting ' + str(wait) + ' seconds')
time.sleep(wait)
|
aniruddha-adhikary/bookit | bookit/providers/models/phone_number.py | Python | mit | 235 | 0 | from django.db import models
from phonenumber_field.modelfields import PhoneNumberField
class PhoneNumber(models. | Model):
provider = models.F | oreignKey(
to='providers.Provider'
)
phone_number = PhoneNumberField()
|
meisterluk/taptaptap | tests/proc_005.py | Python | bsd-3-clause | 472 | 0.019068 | #!/usr/bin/env python2
from taptaptap.proc import plan, ok, not_ok, out
plan(first=1, last=13)
ok('Starting the program')
ok('Starting the engine')
ok('Find the object')
ok('Grab it', todo=True)
ok('Use it', todo=True)
2 * 2 == 4 and ok('2 * 2 == 4') or | not_ok('2 * 2 != 4') |
out()
## validity: -1
## ok testcases: 6 / 13
## bailout: no
## stderr: 2 * 2 == 4
## stderr: TODO
## stderr: ~TRUE
## stderr: ~True
## stderr: ~true
|
boundarydevices/android_external_chromium_org | tools/json_schema_compiler/cpp_bundle_generator.py | Python | bsd-3-clause | 11,513 | 0.006428 | # 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 code
import cpp_util
from model import Platforms
from schema_util import CapitalizeFirstLetter
from schema_util import JsFunctionNameToClassName
... | % namespace_ifdefs, indent_level=0)
c.Eblock("}")
return c
class _APIHGenerator(object):
"""Generates the header for API registration / declaration"""
def __init__(self, cpp_bundle):
self._bundle = cpp_bundle
def Generate(self, namespace):
c = code.Code()
c.Append('#include <string>')
... | c.Append('#include "base/basictypes.h"')
c.Append()
c.Append("class ExtensionFunctionRegistry;")
c.Append()
c.Concat(cpp_util.OpenNamespace(self._bundle._cpp_namespace))
c.Append()
c.Append('class GeneratedFunctionRegistry {')
c.Sblock(' public:')
c.Append('static void RegisterAll('
... |
openfisca/LawToCode | lawtocode/scripts/harvest_ipp_prelevements_sociaux.py | Python | agpl-3.0 | 11,104 | 0.010558 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# Law-to-Code -- Extract formulas & parameters from laws
# By: Emmanuel Raviart <emmanuel@raviart.com>
#
# Copyright (C) 2013 OpenFisca Team
# https://github.com/openfisca/LawToCode
#
# This file is part of Law-to-Code.
#
# Law-to-Code is free software; you can redistrib... | y_name(u'PSS')
sheet_data = [
[
transform_xls_cell_to_json(book, cell_type, cell_value, she | et.cell_xf_index(row_index, column_index))
for column_index, (cell_type, cell_value) in enumerate(itertools.izip(sheet.row_types(row_index),
sheet.row_values(row_index)))
]
for row_index in range(sheet.nrows)
]
taxipp_names = sheet_data[0]
labels = sheet_d... |
e-gob/plataforma-kioscos-autoatencion | scripts/ansible-play/.venv/lib/python2.7/site-packages/ansible/modules/network/layer3/net_l3_interface.py | Python | bsd-3-clause | 2,074 | 0.000964 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2017, Ansible by Red Hat, inc
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
... | 68.3.10/24, ipv6: "fd5d:12c9:2201:1::1/64" }
- name: Remove IP addresses on aggregate
net_l3_interface:
aggregate:
- { name: eth1, ipv4: 192.168.2.10/24 }
- { name: eth2, ipv4: 192.168.3.10/24, ipv6: "fd5d:12c9:2201:1::1/64" }
state: absent
"""
RETURN = """
commands:
description: The list of c... | mands to send to the device
returned: always, except for the platforms that use Netconf transport to manage the device.
type: list
sample:
- set interfaces ethernet eth0 address '192.168.0.1/24'
"""
|
tomchor/pymicra | pymicra/algs/units.py | Python | gpl-3.0 | 7,214 | 0.016912 | from __future__ import absolute_import, print_function, division
from .. import decorators
def multiply(elems, units, inplace_units=False, unitdict=None, key=None):
"""
Multiply elements considering their units
"""
return operate(elems, units, inplace_units=inplace_units, unitdict=unitdict, key=key, op... | ns=[ data.name ])
cols = data.columns
#---------
#---------
# If the name is None or it's not in the list of units, then it's different variables
else:
| cols = data.index
#---------
#-------------
unts = [ '<{}>'.format(units[c]) if c in units.keys() else '<?>' for c in cols ]
columns = pd.MultiIndex.from_tuples(tuple(zip(cols, unts)))
if isinstance(data, pd.DataFrame):
data.columns = columns
elif isinstance(data, pd.Series):
... |
urbansearchTUD/UrbanSearch | urbansearch/server/relations.py | Python | gpl-3.0 | 807 | 0.001239 | from flask import Blueprint, jsonify, request
from urbansearch.utils import db_utils
relations_api = Blueprint('relations_api', __name__)
@relations_api.route('/document_info' | , methods=['GET'])
def document_info():
if 'city_a' not in request.args or 'city_b' not in request.args:
return jsonify(status=400, error='No city pair given')
city_a = request.args.get('city_a')
city_b = request.args.get('city_b')
documents = db_utils.get_related_documents(city_a, city_b, int(... | st.args.get('threshold', 125))
relations = db_utils.get_ic_rels(None, threshold)
return jsonify(status=200, relations=relations)
|
yangjincai/Xq2EFT | testAndOutputGrids.py | Python | apache-2.0 | 6,139 | 0.012543 | #!/usr/bin/env python2
import numpy as np
import pdb
from random import sample
from time import time
import heapq
import matplotlib
matplotlib.use('Agg')
from matplotlib import pyplot as plt
import sys, os
from eft_calculator import EFT_calculator, Water
import tools
def load_coordinates(name):
lines = open('test... | [i], charge[i], coor1[j], eps[j], sigma[j], charge[j])
e += ener
f += force
t += np.cross(coor1[j]-com1, force)
#if e>100.0:
# e = 100.0
# f = f/np.linalg.norm(f) * 100.0
# t = t/np.linalg.norm(t) * 100.0
return np.array([e, f[... | rt(e0 * e1)
s = s0 + s1
r = np.linalg.norm(x0 - x1)
if r <0.1 : return 100.0, np.array([100., 100.,100.,])
sor6 = (s/r) ** 6
evdw = e * (sor6**2 - 2 * sor6)
fvdw = e / r**2 * sor6 * (sor6 - 1) * (x1 - x0)
eelec = k * q0 * q1 / r
felec = k * q0 * q1 / r**3 ... |
i02sopop/Kirinki | kirinki/mainviewer.py | Python | agpl-3.0 | 2,339 | 0.013254 | # -*- coding: utf-8 -*-
__license__ = "GNU Affero General Public License, Ver.3"
__author__ = "Pablo Alvarez de Sotomayor Posadillo"
# This file is part of Kirinki.
#
# Kirinki 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 ... | ong with kirinki. If not, see <http://www.gnu.org/licenses/>.
from django.core.cache import cache
from django.contrib.sessions.models impo | rt Session
from django.template import RequestContext
from django.shortcuts import render_to_response
from django.template.loader import render_to_string
from recaptcha.client import captcha
from datetime import datetime, timedelta
import logging
class MainViewer:
def __init__(self, req):
logging.basicConf... |
mahim97/zulip | zerver/webhooks/homeassistant/tests.py | Python | apache-2.0 | 1,083 | 0.00554 | from typing import Text
from zerver.lib.test_classes import WebhookTestCase
class HomeAssistantHookTests(WebhookTestCase):
STREAM_NAME = 'homeassistant'
URL_TEMPLATE = "/api/v1/external/homeassistant?&api_key={api_key}"
FIXTURE_DIR_NAME = 'homeassistant'
def test_simplereq(self) -> None:
expe... | sistan | t"
expected_message = "The sun will be shining today!"
self.send_and_test_stream_message('simplereq', expected_subject, expected_message,
content_type="application/x-www-form-urlencoded")
def test_req_with_title(self) -> None:
expected_subject = "W... |
meejah/AutobahnPython | autobahn/util.py | Python | mit | 24,461 | 0.001431 | ###############################################################################
#
# The MIT License (MIT)
#
# Copyright (c) Tavendo GmbH
#
# Permission | is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the So... | ded in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLD... |
mfwarren/FreeCoding | 2015/04/fc_2015_04_09.py | Python | mit | 378 | 0.002646 | #!/usr/bin/env python3
# imports go here
import threadin | g
#
# Free Coding session for 2015-04-09
# Written by Matt Warren
#
data = threading.local()
def message():
print(data.name)
class Foo(threading.Thread):
def run(self):
data.name = self.getName()
message()
if __name__ == '__main__':
f = Foo()
f2 = Foo()
f.start()
f2.s | tart()
|
sdague/home-assistant | tests/mock/zwave.py | Python | apache-2.0 | 6,380 | 0.00047 | """Mock helpers for Z-Wave component."""
from pydispatch import dispatcher
from tests.async_mock import MagicMock
def value_changed(value):
"""Fire a value changed."""
dispatcher.send(
MockNetwork.SIGNAL_VALUE_CHANGED,
value=value,
node=value.node,
network=value.node._network,... | _POLLING_ENABLED = "mock_PollingEnabled"
SIGNAL_POLLING_DISABLED = "mock_PollingDisabled"
SIGNAL_CREATE_BUTTON = "mock_CreateButton"
SIGNAL_DELETE_BUTTON = "mock_DeleteButton"
SIGNAL_BUTTON_ON = "mock_ButtonOn"
SIGNAL_BUTTON_OFF = "moc | k_ButtonOff"
SIGNAL_ESSENTIAL_NODE_QUERIES_COMPLETE = "mock_EssentialNodeQueriesComplete"
SIGNAL_NODE_QUERIES_COMPLETE = "mock_NodeQueriesComplete"
SIGNAL_AWAKE_NODES_QUERIED = "mock_AwakeNodesQueried"
SIGNAL_ALL_NODES_QUERIED = "mock_AllNodesQueried"
SIGNAL_ALL_NODES_QUERIED_SOME_DEAD = "mock_AllNo... |
curaloucura/Enso-Ubuntu | ensocommands/random.py | Python | bsd-3-clause | 2,893 | 0.023159 | import re, os
def cmd_install(ensoapi):
seldict = ensoapi.get_selection()
text = seldict.get("text", "").strip()
lines = text.split("\n")
ensoapi.display_message(lines)
return
if len(lines) < 3:
msg = "There was no command to install!"
ensoapi.display_message(msg)
ensoapi.set_selection({
... | ensoapi.display_message(msg)
ensoapi.set_selection({
"text":"Enso: %s" % msg
})
return
cmd_folde | r = ensoapi.get_enso_commands_folder()
command_file_path = os.path.join(cmd_folder, command_file_name)
shortname = os.path.splitext(command_file_name)[0]
if os.path.exists(command_file_path):
msg = "You already have a command named %s" % shortname
ensoapi.display_message(msg)
ensoapi.set_selection({
... |
yuzie007/ph_plotter | ph_plotter/total_dos_plotter.py | Python | mit | 1,815 | 0.002204 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from .dos_plotter import DOSPlotter
__author__ = "Yuji Ikeda"
class TotalDOSPlotter(DOSPlotter):
def load_data(self, data_file='total_dos.dat'):
supe... | es["f_min"] *= scale
variables["f_max"] *= scale
variables["d_freq"] *= scale
variables["dos_min"] /= scale
variables["dos_max"] /= scale
variables["dos_ticks"] /= scale
self.up | date_variables(variables)
# self.set_is_horizontal(True)
# self.plot_dos()
self.set_is_horizontal(False)
self.create_figure()
|
fred3m/astro-toyz | astrotoyz/__init__.py | Python | bsd-3-clause | 727 | 0.001376 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This is an Astropy affiliated package.
"""
# Affiliated packages may add whatever they like to this file, but
# should keep this content at the top.
# ----------------------------------------------------------------------------
from ._astropy_init im... | m astrotoyz import data_typ | es
from astrotoyz import config |
Mlieou/leetcode_python | leetcode/python/ex_376.py | Python | mit | 570 | 0.007018 | class Solution(object):
def wiggleMaxLength(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) < 2: return len(nums)
prev_diff = nums[1] - nums[0]
if prev_diff != 0:
longest = 2
else:
lo | ngest = 1
for i in range(2, len(nums)):
curr_diff = (nums[i] - nums[i-1])
if (curr_diff > 0 and prev_diff <= 0) or (curr_diff < 0 and prev_diff >= 0):
longest += 1
| prev_diff = curr_diff
return longest |
djangophx/beer-tracker | tracker/migrations/0001_initial.py | Python | mit | 2,278 | 0.003512 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2017-09-19 16:34
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.Crea... | to_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=255)),
('description', models.TextField()),
('venue_type', models.CharField(choices=[('bar', 'Bar'), ('brew', 'Brewery'), | ('truck', 'Food Truck')], max_length=5)),
('beers', models.ManyToManyField(related_name='venues', to='tracker.Beer')),
],
),
migrations.AddField(
model_name='beer',
name='brewery',
field=models.ForeignKey(on_delete=django.db.models.deletio... |
tensorflow/tensorboard | tensorboard/compat/tensorflow_stub/tensor_shape.py | Python | apache-2.0 | 34,472 | 0.000754 | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | nsion(m) + tf.Dimension(n) == tf.Dimension(m + n)
tf.Dimension(m) + tf.Dimension(None) == tf.Dimension(None)
tf.Dimension(None) + tf.Dimension(n) == tf.Dimension(None)
tf.Dimension(None) + tf.Dimension(None) == tf.Dimension(None)
```
Args:
other: Another Di... | A Dimension whose value is the sum of `self` and `other`.
"""
other = as_dimension(other)
if self._value is None or other.value is None:
return Dimension(None)
else:
return Dimension(self._value + other.value)
def __radd__(self, other):
"""Return... |
mfalesni/cfme_tests | cfme/tests/services/test_catalog_item.py | Python | gpl-2.0 | 5,757 | 0.001563 | # -*- coding: utf-8 -*-
import fauxfactory
import pytest
from selenium.common.exceptions import NoSuchElementException
import cfme.tests.configure.test_access_control as tac
from cfme.base.login import BaseLoggedInPage
from cfme import test_requirements
from cfme.utils import error
from cfme.utils.blockers import BZ
... | g, dialog=dialog
)
yield cat_item
# fixture cleanup
try:
cat_item.delete()
except NoSuchElementException:
logger.warning( | 'test_catalog_item: catalog_item yield fixture cleanup, catalog item "{}" '
'not found'.format(cat_item.name))
@pytest.yield_fixture(scope="function")
def catalog_bundle(appliance, catalog_item):
""" Create catalog bundle
Args:
catalog_item: as resource for bundle creati... |
csilzen/whatdoyousee | python/label/label.py | Python | apache-2.0 | 2,624 | 0.001143 | #!/usr/bin/env python
# Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required... | 'content': image_content.decode('UTF-8')
},
'features': [{
'type': 'LABEL_DETECTION',
'maxResults': 1
}]
}]
})
# [END construct_request]
# [START parse_response]
response = service_req... | ound label: %s for %s' % (label, photo_file))
return 0
# [END parse_response]
# [START run_application]
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('image_file', help='The image you\'d like to label.')
args = parser.parse_args()
main(args.image_file... |
cygnushan/measurement | ST_spectrum/Ui_ST_2400.py | Python | mit | 22,827 | 0.002075 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'G:\WorkDir\gas-sensing_resistors\ST_spectrum\ST_2400.ui'
#
# Created: Tue Apr 12 22:50:19 2016
# by: PyQt4 UI code generator 4.11.3
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fro... | re.QSize(60, 22))
self.detR.setMaximumSize(QtCore.QSize(65535, 22))
self.detR.setObjectName(_fromUtf8("detR"))
self.horizontalLayout_11.addWi | dget(self.detR)
self.label_12 = QtGui.QLabel(UI_sens2400)
self.label_12.setMaximumSize(QtCore.QSize(16777215, 22))
self.label_12.setObjectName(_fromUtf8("label_12"))
self.horizontalLayout_11.addWidget(self.label_12)
self.horizontalLayout_13.addLayout(self.horizontalLayout_11)
... |
AyoubZahid/odoo | openerp/tools/translate.py | Python | gpl-3.0 | 48,927 | 0.003352 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import codecs
import csv
import fnmatch
import inspect
import locale
import os
import openerp.sql_db as sql_db
import re
import logging
import tarfile
import tempfile
import threading
from babel.messages import extract
f... | : 'Czech_Czech Republic',
'da_DK': 'Danish_Denmark',
'nl_NL': 'Dutch_Netherlands' | ,
'et_EE': 'Estonian_Estonia',
'fa_IR': 'Farsi_Iran',
'ph_PH': 'Filipino_Philippines',
'fi_FI': 'Finnish_Finland',
'fr_FR': 'French_France',
'fr_BE': 'French_France',
'fr_CH': 'French_France',
'fr_CA': 'French_France',
'ga': 'Scottish Gaelic',
'gl_ES': 'Galician_Spain',
'ka_G... |
sredmond/acmpy | tests/datastructures/test_basicgraph.py | Python | mit | 67 | 0 | """Tests for the : | mod:`campy.datastructures.basicgraph` module."""
| |
Murillo/Hackerrank-Algorithms | Algorithms/Implementation/extra-long-factorials.py | Python | mit | 437 | 0.006865 | # Extra Long Factorials
# Developer: Murillo Grubler
# https://www.hackerrank.com/challenges/extra-long-factorials/problem
# Time Comple | xity = O(n)
def factorial(n):
if n == 1:
return 1
total = n
while (n > 0):
if n == total:
total = total * (n - 1)
n -= 2
else: |
total = total * n
n -= 1
return total
n = int(input().strip())
print (factorial(n)) |
GaretJax/i18n-utils | i18n_utils/utils.py | Python | mit | 291 | 0 | import functools
def memoize(obj):
ca | che = obj.c | ache = {}
@functools.wraps(obj)
def memoizer(*args, **kwargs):
key = (args, tuple(kwargs.items()))
if key not in cache:
cache[key] = obj(*args, **kwargs)
return cache[key]
return memoizer
|
theikkila/lopputili | app/models/setting.py | Python | mit | 685 | 0.020438 | from orm import model
from .user import User
from orm import fields
class Setting(model.Model):
owner = fields.ForeignKeyField(User)
company_name = fields.CharField(max_length=140, blank=True)
address = fields.CharField(max_length=240, blank=True)
zip_code = fields.CharField(max_length=140, blank=True)
city = fie... | d(max_length=140, blank=True)
vat_code = fields.CharField(max_length=140, blank=True)
iban = fie | lds.CharField(max_length=140, blank=True)
bic = fields.CharField(max_length=140, blank=True)
def __repr__(self):
return str(self.company_name) |
mcldev/geonode | geonode/security/views.py | Python | gpl-3.0 | 9,784 | 0.001124 | # -*- coding: utf-8 -*-
#########################################################################
#
# Copyright (C) 2016 OSGeo
#
# 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 ... | 'cannot access the resource. ' \
'Please update permissions consistently!'
return HttpResponse(
json.dumps({'success': success, 'message': message}),
| status=200,
content_type='text/plain'
)
except BaseException:
success = False
message = "Error updating permissions :("
return HttpResponse(
json.dumps({'success': success, 'message': message}),
status=500,
... |
robertjacobs/zuros | zuros_deliberator/zuros_command_to_robot_sender/src/zuros_command_to_robot_sender.py | Python | mit | 6,086 | 0.006408 | #!/usr/bin/env python
# Copyright (c) 2013-2014 ZUYD Research
# 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 li... | = self.sort_dict(navigation_positions_params)
nav_pos = None
# Check if this position is known
for nav in nav_param:
if(nav[0] == position):
nav_pos = nav[1]
# Position is known
if(nav_pos != None):
rospy.loginfo("Move <<%s>> to ... | else:
ROS_ERROR("No valid position found, cancelling move command. Are you sure your position is added to the parameter server?")
return
# Convert to pose message
pose = PoseStamped()
pose.header.stamp = rospy.Time.now()
pose.header.frame_id = "/map"
... |
ployground/ploy_openvz | setup.py | Python | bsd-3-clause | 1,066 | 0 | from setuptools impo | rt setup
import os
here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README.rst')).read()
version = "1.0b3"
setup(
version=version,
description="A plugin for ploy providing support for OpenVZ containers." | ,
long_description=README + "\n\n",
name="ploy_openvz",
author='Florian Schulze',
author_email='florian.schulze@gmx.net',
license="BSD 3-Clause License",
url='http://github.com/ployground/ploy_openvz',
classifiers=[
'Environment :: Console',
'Intended Audience :: System Admin... |
iBluemind/armatis | armatis/models.py | Python | bsd-2-clause | 2,596 | 0 | # -*- coding: utf-8 -*-
class Company(object):
def __init__(self, name=None, code=None, phone=None, digit=None):
# Company's name
self.name = name
# Codename
self.code = code
# The digit of the invoice number
if digit is None:
digit = []
self.dig... | one2=None):
# Time
s | elf.time = time
# Location
self.location = location
# Status
self.status = status
# Phone number 1
self.phone1 = phone1
# Phone number 2
self.phone2 = phone2
def __repr__(self):
return '[%s] %s - %s / %s / %s' % (
self.time,
... |
chrislit/abydos | abydos/distance/_ssk.py | Python | gpl-3.0 | 4,880 | 0 | # Copyright 2019-2020 by Christopher C. Little.
# This file is part of Abydos.
#
# Abydos 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 versio... | e QGramskipgrams
tokenizer with this q value.
.. versionadded:: 0.4.1
"""
supe | r(SSK, self).__init__(
tokenizer=tokenizer, ssk_lambda=ssk_lambda, **kwargs
)
qval = 2 if 'qval' not in self.params else self.params['qval']
self.params['tokenizer'] = (
tokenizer
if tokenizer is not None
else QSkipgrams(
qval=qval... |
getsentry/zeus | zeus/api/resources/revision_tests.py | Python | apache-2.0 | 1,984 | 0.002016 | from flask import request
from sqlalchemy.dialects.postgresql import array_agg
from zeus.config import db
from zeus.constants import Result
from zeus.db.func import array_agg_row
from zeus.models import Job, TestCase, Revision
from zeus.utils.builds import fetch_build_for_revision
from .base_revision import BaseRevis... | except AttributeError:
raise NotImplementedError
query = query.order_by(
(
| array_agg(TestCase.result).label("results").contains([Result.failed])
).desc(),
TestCase.name.asc(),
)
schema = AggregateTestCaseSummarySchema(many=True, exclude=("build",))
return self.paginate_with_schema(schema, query)
|
endlessm/chromium-browser | third_party/llvm/debuginfo-tests/dexter/dex/dextIR/ProgramState.py | Python | bsd-3-clause | 3,820 | 0.000785 | # DExTer : Debugging Experience Tester
# ~~~~~~ ~ ~~ ~ ~~
#
# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
# See https://llvm.org/LICENSE.txt for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
"""Set of data classes for representing th... | e,
watches: OrderedDict = None):
if watches is None:
watches = {}
self.function = function
self.is_inlined = is_inlined
self.location = location
self. | watches = watches
def __str__(self):
return '{}{}: {} | {}'.format(
self.function,
' (inlined)' if self.is_inlined else '',
self.location,
{k: str(self.watches[k]) for k in self.watches})
def match(self, other) -> bool:
"""Returns true iff all th... |
harshkothari410/ocportal | ojp/migrations/0005_auto_20161117_0303.py | Python | mit | 493 | 0 | # -*- coding: utf-8 -*-
# Gene | rated by Django 1.10.2 on 2016-11-17 03:03
from __future__ import unicode_literals
from django.db import migrations
import tinymce.models
class Migration(migrations.Migration):
dependencies = [
('ojp', '0004_problem_num_of_correct_tries'),
]
operations = [
migrations.AlterField(
... | ption',
field=tinymce.models.HTMLField(blank=True, null=True),
),
]
|
pantheon-systems/kombu | kombu/tests/test_virtual_exchange.py | Python | bsd-3-clause | 3,747 | 0.000801 | from kombu.tests.utils import unittest
from kombu.transport.virtual import exchange
from kombu.tests.mocks import Channel
class ExchangeCase(unittest.TestCase):
type = None
def setUp(self):
if self.type:
self.e = self.type(Channel())
class test_Direct(ExchangeCase):
type = exchang... | ne, None, "qFoo"),
(None, None, "qFox"),
(None, None, "qBar")]
def test_lookup(self):
self.assertListEqual(self.e.lookup(
self.table, "eFoo", "rFoo", None),
["qFoo", "qFox", "qBar"])
class test_Topic(ExchangeCase):
type = exchange.TopicExchang... | p(self):
super(test_Topic, self).setUp()
self.table = [(rkey, self.e.key_to_pattern(rkey), queue)
for rkey, _, queue in self.table]
def test_prepare_bind(self):
x = self.e.prepare_bind("qFoo", "eFoo", "stock.#", {})
self.assertTupleEqual(x, ("stock.#", r'^sto... |
jmcnamara/XlsxWriter | xlsxwriter/test/comparison/test_textbox15.py | Python | bsd-2-clause | 900 | 0 | ###############################################################################
#
# Tests for XlsxWriter.
#
# SPDX-License-Identifier: BSD-2-Clause
# Copyright (c), 2013-2022, John McNamara, jmcnamara@cpan.org
#
from ..excel_comparison_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompar... | heet.insert_textbox('E9', 'This is some text',
| {'align': {'horizontal': 'center'}})
workbook.close()
self.assertExcelEqual()
|
chrmoritz/zoxel | src/plugins/__init__.py | Python | gpl-3.0 | 547 | 0.003656 | from os.path import dirname
from os import listdir
path = dirname(__file__)
| i = path.find(".zip")
if i == -1: # OS X app or unpacked python files
__all__ = [p[:-3] for p in listdir(path) if p.endswith(".py") and p != "__init__.py"]
del p
else: # Windows binary ziped .pyc | files
import zipfile
__all__ = [f[8:-4] for f in zipfile.ZipFile(path[:i+4]).namelist() if f.find('plugins/') == 0 and
f.endswith(".pyc") and not f.endswith("__init__.pyc")]
del f
del zipfile
del i
del path
del dirname
del listdir
|
wrouesnel/ansible | lib/ansible/modules/network/aci/aci_epg_monitoring_policy.py | Python | gpl-3.0 | 6,703 | 0.00179 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
... | tenant=dict(type='str', required=False, aliases=['tenant_name']), # Not required for querying all objects
description=dict(type='str', aliases=['descr']),
state=dict(type='str', default='present', choices=['absent', 'present', 'query']),
method=dict(type='str', choices=['delete', 'get', 'post'... | dule = AnsibleModule(
argument_spec=argument_spec,
supports_check_mode=True,
required_if=[
['state', 'absent', ['monitoring_policy', 'tenant']],
['state', 'present', ['monitoring_policy', 'tenant']],
],
)
monitoring_policy = module.params['monitoring_poli... |
tqchen/tvm | python/tvm/relay/frontend/tflite.py | Python | apache-2.0 | 137,911 | 0.001581 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | alysis
from .. import expr as _expr
from .. import function as _function
from .. import op as _op
from .. import qnn as _qnn
from ... import nd as _nd
from .common import ExprTable
from .common import infer_shape as _infer_shape
from | .tflite_flexbuffer import FlexBufferDecoder
__all__ = ["from_tflite"]
class TensorWrapper(object):
"""Tensor wrapper for TFLite Tensor"""
def __init__(self, tensor_idx, tensor, buffer, qnn_params=None):
self.tensor_idx = tensor_idx
self.tensor = tensor
self.buffer = buffer
s... |
SUSE/azure-sdk-for-python | azure-mgmt-network/azure/mgmt/network/v2017_03_01/operations/virtual_network_gateways_operations.py | Python | mit | 36,131 | 0.002353 | # 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 ... | ustom_headers=None, raw=False, **operation_config):
"""Creates or updates a virtual network gateway in the specified resource
group.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param virtual_network_gateway_name: The name of the vi... | te or update virtual
network gateway operation.
:type parameters: :class:`VirtualNetworkGateway
<azure.mgmt.network.v2017_03_01.models.VirtualNetworkGateway>`
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alon... |
AleksNeStu/ggrc-core | src/ggrc/models/mixins/__init__.py | Python | apache-2.0 | 26,526 | 0.010631 | # Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""Mixins to add common attributes and relationships. Note, all model classes
must also inherit from ``db.Model``. For example:
color
color
..
class Market(BusinessObject, db.Model):
__tablena... | rimaryjoin='{0}.modified_by_id == Person.id'.format(cls.__name__),
foreign_keys='{0}.modified_by_id'.format(cls.__name__),
uselist=False,
)
@staticmethod
def _extra_table_args(model):
"""Apply extra table args (like indexes) to model definition."""
return (
db.Inde | x('ix_{}_updated_at'.format(model.__tablename__), 'updated_at'),
)
# TODO Add a transaction id, this will be handy for generating etags
# and for tracking the changes made to several resources together.
# transaction_id = db.Column(db.Integer)
# REST properties
_publish_attrs = [
'modified_by',
... |
biothings/biothings_explorer | biothings_explorer/_deprecated_schema_parser.py | Python | apache-2.0 | 1,071 | 0.003735 | """Parse the biothings schema"""
from .config import BIOTHINGS_SCHEMA_URL, PREFIX_TO_REMOVE
from .utils.dataload import load_json_or_yaml
from .utils.common import remove_prefix
class SchemaParser():
def __init__(self):
self.schema_json = remove_prefix(load_json_or_yaml(BIOTHINGS_SCHEMA_URL),
... | son['@graph']:
if "rdfs:subPropertyOf" in rec and | rec["rdfs:subPropertyOf"]["@id"] == "http://schema.org/identifier":
self.ids.append(rec["@id"])
elif rec["@type"] == "rdf:Property":
self.properties[rec["@id"]] = {"inverse_property": None}
if "schema:inverseOf" in rec:
self.properties[rec[... |
ta2xeo/python3-kii | tests/test_data/application/test_application_scope_data.py | Python | mit | 13,511 | 0.00037 | '''
Precondition
successfully pass a users test.
'''
from datetime import datetime, timedelta
import time
import pytest
import requests
from kii import AccountType, exceptions as exc, results as rs
from kii.data import BucketType, clauses as cl
from tests.conf import (
get_env,
get_api_with_test_user,
... | }
}
assert | created2['list key'] == [4, 5, 6]
assert created._created != created2._created
assert created._modified != created2._modified
assert created._version == 1
assert created2._version == 1
def test_partially_update_an_object(self):
bucket = self.scope(BUCKET_ID)
obj = ... |
eggplantbren/DNest4 | code/Examples/RJObject_1DMixture/display.py | Python | mit | 1,414 | 0.004243 | import dnest4.classic as dn4
from pylab import *
plt.rcParams["font.family"] = "serif"
plt.rcParams["font.size"] = 16
plt.rc("text", usetex=True)
data = loadtxt('galaxies.txt')
posterior_sample = atleast_2d(dn4.my_loadtxt('posterior_sample.txt'))
x = linspace(0., 50.0, 10001)
def mixture(x, params):
N = int(para... | , bins, width=width, density=True, color="k", alpha=0.2)
xlim([0, 100.5])
ylim([0, 0.05])
xlabel("Number of gaussians, $N$")
ylabel("Posterior Probability")
savefig("galaxies_N.pdf", bbox_inches="tight | ")
show()
|
juantascon/flickr_mass_upload | flickr_mass_upload.py | Python | gpl-3.0 | 1,220 | 0.009836 | #! /u | sr/bin/env python2
import sys, os
import flickrapi
import xml.etree.ElementTree
if len(sys.argv) < 2:
sys.stderr.write("usage: %s <filename> ..." % sys.argv[0])
sys.exit(1)
def auth( | ):
api_key = "87af34fe62dafd3c5d6d4959ca92c193"
api_secret = "18ecfc909af569af"
flickr = flickrapi.FlickrAPI(api_key, api_secret)
(token, frob) = flickr.get_token_part_one(perms='write')
if not token: raw_input("Press ENTER after you authorized this program")
flickr.get_token_part_two((toke... |
jgmanzanas/CMNT_004_15 | project-addons/scheduled_shipment/__openerp__.py | Python | agpl-3.0 | 566 | 0 | # -*- coding: utf-8 -*-
# © 2016 Comunitea
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Order scheduled shipment",
"summary": "Sale order with sc | heduled shipment",
"version": "8.0.1.0.0",
"category": "Connector",
"author": "Nadia Ferreyra",
"license": "AGPL-3",
"installable": True,
"depends": [
"base",
| "sale",
"connector",
"sale_stock",
"picking_invoice_pending"
],
"data": [
'data/job_channel_data.xml',
'views/sale_view.xml',
],
}
|
team-vigir/flexbe_behavior_engine | flexbe_onboard/test/test_onboard.py | Python | bsd-3-clause | 4,765 | 0.001259 | #!/usr/bin/env python
import sys
import os
import unittest
import zlib
import rospy
from flexbe_onboard.flexbe_onboard import FlexbeOnboard
from flexbe_core.proxy import ProxySubscriberCached
from flexbe_msgs.msg import BehaviorSelection, BEStatus, BehaviorLog, BehaviorModification
class TestOnboard(unittest.TestCa... | ISHED, 3)
behavior_logs = []
while self.sub.has_buffered('flexbe/log'):
behavior_logs.append(self.sub.get_from_buffer('flexbe/log').text)
self.assertIn('Test data', behavior_logs)
# send valid complex behavior request
| be_id, _ = self.lib.find_behavior("Test Behavior Complex")
request = BehaviorSelection()
request.behavior_id = be_id
request.autonomy_level = 255
request.arg_keys = ['param']
request.arg_values = ['value_2']
request.input_keys = ['data']
request.input_values ... |
hds-lab/dsechatweb | dsechat/apps/accounts/forms.py | Python | mit | 4,148 | 0.002652 | from django import forms
from django.utils.translation import ugettext_lazy as _
from registration.models import UserModel
from models import User as AccountsUser
class UserRegistrationForm(forms.Form):
"""
Form for registering a new user account.
Validates that the requested username is not already in u... | Name"))
last_name = forms.CharField(label=_("Last Name"))
password1 = forms.CharField(widget=forms.PasswordInput,
label=_("Create a password"))
password2 = forms.CharField(widget=forms.PasswordInput,
label=_("Your password again"))
def cl... | s not already
in use.
"""
existing = UserModel().objects.filter(username__iexact=self.cleaned_data['username'])
if existing.exists():
raise forms.ValidationError(_("A user with that username already exists."))
else:
return self.cleaned_data['username']
... |
anthonyfok/frescobaldi | frescobaldi_app/fileinfo.py | Python | gpl-2.0 | 6,388 | 0.004383 | # This file is part of the Frescobaldi project, http://www.frescobaldi.org/
#
# Copyright (c) 2008 - 2014 by Wilbert Berendsen
#
# 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
... | omputes and caches various information about files.
"""
import itertools
import re
import os
import atexit
import ly.document
import lydocinfo
import ly.lex
import filecache
import util
import variables
_document_cache = filecache.FileCache()
_suffix_chars_re = re.compile(r'[^-\w]', re.UNICODE)
### XXX otherwise... | de (and every node references the document).
### (The segfault is preceded by a "corrupted double-linked list" message.)
atexit.register(_document_cache.clear)
class _CachedDocument(object):
"""Contains a document and related items."""
filename = None
document = None
variables = None
docinfo = Non... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.